@bastani/atomic 0.9.10 → 0.9.11-alpha.1

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.
Files changed (94) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/builtin/cursor/CHANGELOG.md +6 -0
  3. package/dist/builtin/cursor/package.json +2 -2
  4. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  5. package/dist/builtin/intercom/package.json +2 -2
  6. package/dist/builtin/mcp/CHANGELOG.md +6 -0
  7. package/dist/builtin/mcp/package.json +1 -1
  8. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  9. package/dist/builtin/subagents/package.json +1 -1
  10. package/dist/builtin/web-access/CHANGELOG.md +6 -0
  11. package/dist/builtin/web-access/package.json +1 -1
  12. package/dist/builtin/workflows/CHANGELOG.md +17 -0
  13. package/dist/builtin/workflows/README.md +8 -3
  14. package/dist/builtin/workflows/builtin/deep-research-codebase.ts +1 -1
  15. package/dist/builtin/workflows/package.json +1 -1
  16. package/dist/builtin/workflows/src/durable/backend.ts +2 -2
  17. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres-root.ts +173 -0
  18. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres.ts +36 -12
  19. package/dist/builtin/workflows/src/durable/dbos-lifecycle.ts +9 -3
  20. package/dist/builtin/workflows/src/durable/factory.ts +35 -6
  21. package/dist/builtin/workflows/src/durable/local-command.ts +11 -2
  22. package/dist/builtin/workflows/src/extension/extension-lifecycle.ts +14 -2
  23. package/dist/builtin/workflows/src/extension/public-types.ts +3 -4
  24. package/dist/builtin/workflows/src/extension/render-call.ts +4 -0
  25. package/dist/builtin/workflows/src/extension/render-result.ts +31 -1
  26. package/dist/builtin/workflows/src/extension/workflow-prompts.ts +5 -2
  27. package/dist/builtin/workflows/src/extension/workflow-schema.ts +3 -2
  28. package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +1 -0
  29. package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +88 -2
  30. package/dist/builtin/workflows/src/extension/workflow-tool.ts +13 -0
  31. package/dist/core/agent-session-events.d.ts.map +1 -1
  32. package/dist/core/agent-session-events.js +2 -1
  33. package/dist/core/agent-session-events.js.map +1 -1
  34. package/dist/core/agent-session-retry.d.ts.map +1 -1
  35. package/dist/core/agent-session-retry.js +7 -0
  36. package/dist/core/agent-session-retry.js.map +1 -1
  37. package/dist/core/agent-session-runtime.d.ts +13 -0
  38. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  39. package/dist/core/agent-session-runtime.js +12 -0
  40. package/dist/core/agent-session-runtime.js.map +1 -1
  41. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  42. package/dist/core/atomic-guide-command.js +2 -0
  43. package/dist/core/atomic-guide-command.js.map +1 -1
  44. package/dist/core/auth-storage-backends.d.ts +4 -0
  45. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  46. package/dist/core/auth-storage-backends.js +48 -3
  47. package/dist/core/auth-storage-backends.js.map +1 -1
  48. package/dist/core/auth-storage.d.ts.map +1 -1
  49. package/dist/core/auth-storage.js +27 -11
  50. package/dist/core/auth-storage.js.map +1 -1
  51. package/dist/core/codex-errors.d.ts +3 -0
  52. package/dist/core/codex-errors.d.ts.map +1 -0
  53. package/dist/core/codex-errors.js +12 -0
  54. package/dist/core/codex-errors.js.map +1 -0
  55. package/dist/core/slash-commands.js +1 -1
  56. package/dist/core/slash-commands.js.map +1 -1
  57. package/dist/modes/interactive/interactive-auth-routing.d.ts +2 -1
  58. package/dist/modes/interactive/interactive-auth-routing.d.ts.map +1 -1
  59. package/dist/modes/interactive/interactive-auth-routing.js +10 -5
  60. package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
  61. package/dist/modes/interactive/interactive-autocomplete.js +12 -2
  62. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  63. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +3 -1
  64. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
  65. package/dist/modes/interactive-engine/extension-ui-bridge.js +6 -0
  66. package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
  67. package/dist/modes/interactive-engine/isolated-runtime.d.ts +4 -5
  68. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  69. package/dist/modes/interactive-engine/isolated-runtime.js +14 -24
  70. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  71. package/dist/modes/interactive-engine/remote-model-catalog.d.ts +15 -0
  72. package/dist/modes/interactive-engine/remote-model-catalog.d.ts.map +1 -0
  73. package/dist/modes/interactive-engine/remote-model-catalog.js +67 -0
  74. package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -0
  75. package/dist/modes/rpc/rpc-client-api.d.ts +8 -1
  76. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  77. package/dist/modes/rpc/rpc-client-api.js +9 -0
  78. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  79. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  80. package/dist/modes/rpc/rpc-command-handler.js +30 -0
  81. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  82. package/dist/modes/rpc/rpc-types.d.ts +67 -7
  83. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  84. package/dist/modes/rpc/rpc-types.js.map +1 -1
  85. package/docs/docs.json +9 -1
  86. package/docs/models/artificial-analysis-index.md +82 -0
  87. package/docs/models/model-selection.md +63 -0
  88. package/docs/models/pareto-efficiency.md +64 -0
  89. package/docs/providers.md +5 -1
  90. package/docs/quickstart.md +1 -1
  91. package/docs/rpc.md +27 -0
  92. package/docs/workflows.md +20 -7
  93. package/npm-shrinkwrap.json +24 -24
  94. package/package.json +4 -4
@@ -65,13 +65,13 @@ export class FileAuthStorageBackend {
65
65
  * never observe a half-written file. The temp file is best-effort cleaned up
66
66
  * if the rename fails.
67
67
  */
68
- writeAtomic(content) {
69
- const dir = dirname(this.authPath);
68
+ writeAtomic(content, path = this.authPath) {
69
+ const dir = dirname(path);
70
70
  const tempPath = join(dir, `.${`auth.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`}.tmp`);
71
71
  try {
72
72
  writeFileSync(tempPath, content, AUTH_FILE_WRITE_OPTIONS);
73
73
  chmodSync(tempPath, 0o600);
74
- renameSync(tempPath, this.authPath);
74
+ renameSync(tempPath, path);
75
75
  }
76
76
  catch (error) {
77
77
  try {
@@ -87,6 +87,51 @@ export class FileAuthStorageBackend {
87
87
  read() {
88
88
  return this.readMergedAuth();
89
89
  }
90
+ deleteProvider(provider) {
91
+ const paths = [...new Set(this.readPaths.filter((path) => existsSync(path)))].sort();
92
+ const releases = [];
93
+ try {
94
+ for (const path of paths)
95
+ releases.push(this.acquireLockSyncWithRetry(path));
96
+ for (const path of paths) {
97
+ const data = JSON.parse(readFileSync(path, "utf-8"));
98
+ if (!(provider in data))
99
+ continue;
100
+ delete data[provider];
101
+ this.writeAtomic(JSON.stringify(data, null, 2), path);
102
+ }
103
+ return this.readMergedAuth();
104
+ }
105
+ finally {
106
+ for (const release of releases.reverse())
107
+ release();
108
+ }
109
+ }
110
+ async deleteProviderAsync(provider) {
111
+ const paths = [...new Set(this.readPaths.filter((path) => existsSync(path)))].sort();
112
+ const releases = [];
113
+ try {
114
+ for (const path of paths) {
115
+ releases.push(await lockfile.lock(path, {
116
+ realpath: false,
117
+ retries: { retries: 10, factor: 2, minTimeout: 100, maxTimeout: 10000, randomize: true },
118
+ stale: 30000,
119
+ }));
120
+ }
121
+ for (const path of paths) {
122
+ const data = JSON.parse(readFileSync(path, "utf-8"));
123
+ if (!(provider in data))
124
+ continue;
125
+ delete data[provider];
126
+ this.writeAtomic(JSON.stringify(data, null, 2), path);
127
+ }
128
+ return this.readMergedAuth();
129
+ }
130
+ finally {
131
+ for (const release of releases.reverse())
132
+ await release();
133
+ }
134
+ }
90
135
  withLock(fn) {
91
136
  this.ensureParentDir();
92
137
  let release;
@@ -1 +1 @@
1
- {"version":3,"file":"au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Q,CAAI,EAAkD;QAC7D,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACnB,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;IAED,KAAK,CAAC,aAAa,CAAI,EAA2D;QACjF,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC9C,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACnB,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;CACD","sourcesContent":["import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport type { AuthStorageData } from \"./auth-storage.ts\";\n\nexport type LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\nexport interface AuthStorageBackend {\n\t/**\n\t * Read the current credential snapshot WITHOUT acquiring the exclusive write\n\t * lock. Pure reads do not need cross-process write-exclusion: writers replace\n\t * the file atomically (temp file + rename), so a lock-free reader always\n\t * observes a complete previous-or-next snapshot, never a torn one. Keeping\n\t * reads lock-free is what prevents many concurrent sessions from starving each\n\t * other on `auth.json` and misreporting configured providers as unreadable\n\t * under contention (issue #1431).\n\t *\n\t * Optional for backward compatibility with custom backends that predate this\n\t * method (the released `AuthStorageBackend` interface): when absent,\n\t * `AuthStorage.reload()` falls back to a `withLock`-based read.\n\t */\n\tread?(): string | undefined;\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tdeclare private authPath: string;\n\tdeclare private readPaths: string[];\n\n\tconstructor(\n\t\tauthPath: string = join(getAgentDir(), \"auth.json\"),\n\t\treadPaths: string[] = [authPath],\n\t) {\n\t\tthis.authPath = normalizePath(authPath);\n\t\tthis.readPaths = readPaths.map((readPath) => normalizePath(readPath));\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\tprivate readMergedAuth(): string | undefined {\n\t\tlet merged: AuthStorageData = {};\n\t\tlet found = false;\n\t\tfor (let i = this.readPaths.length - 1; i >= 0; i--) {\n\t\t\tconst readPath = this.readPaths[i]!;\n\t\t\tif (!existsSync(readPath)) continue;\n\t\t\tconst parsed = JSON.parse(readFileSync(readPath, \"utf-8\")) as AuthStorageData;\n\t\t\tmerged = { ...merged, ...parsed };\n\t\t\tfound = true;\n\t\t}\n\t\treturn found ? JSON.stringify(merged, null, 2) : undefined;\n\t}\n\n\t/**\n\t * Atomically replace `auth.json` with `content`: write a sibling temp file\n\t * (same directory, so `rename` is a same-filesystem atomic swap), fix its\n\t * permissions, then `rename` it over the target. Lock-free readers therefore\n\t * never observe a half-written file. The temp file is best-effort cleaned up\n\t * if the rename fails.\n\t */\n\tprivate writeAtomic(content: string): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tconst tempPath = join(\n\t\t\tdir,\n\t\t\t`.${`auth.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`}.tmp`,\n\t\t);\n\t\ttry {\n\t\t\twriteFileSync(tempPath, content, AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(tempPath, 0o600);\n\t\t\trenameSync(tempPath, this.authPath);\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tif (existsSync(tempPath)) rmSync(tempPath, { force: true });\n\t\t\t} catch {\n\t\t\t\t// Best-effort cleanup; ignore.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tread(): string | undefined {\n\t\treturn this.readMergedAuth();\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\tif (existsSync(this.authPath)) {\n\t\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\t}\n\t\t\tconst current = this.readMergedAuth();\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\tif (!existsSync(this.authPath)) {\n\t\t\t\t\tthis.ensureFileExists();\n\t\t\t\t}\n\t\t\t\tif (!release) {\n\t\t\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\t\t}\n\t\t\t\tthis.writeAtomic(next);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tif (!existsSync(this.authPath)) {\n\t\t\t\tthis.ensureFileExists();\n\t\t\t}\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: 30000,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = this.readMergedAuth();\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\tthis.writeAtomic(next);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\tread(): string | undefined {\n\t\treturn this.value;\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n"]}
1
+ {"version":3,"file":"auth-storage-backends.js","sourceRoot":"","sources":["../../src/core/auth-storage-backends.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACvG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAQlD,MAAM,uBAAuB,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAW,CAAC;AAuB5E,MAAM,OAAO,sBAAsB;IAIlC,YACC,QAAQ,GAAW,IAAI,CAAC,WAAW,EAAE,EAAE,WAAW,CAAC,EACnD,SAAS,GAAa,CAAC,QAAQ,CAAC;QAEhC,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC;IACv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AAC;QACF,CAAC;IACF,CAAC;CACD;AAED,MAAM,OAAO,0BAA0B;IAGtC,IAAI;QACH,OAAO,IAAI,CAAC,KAAK,CAAC;IACnB,CAAC;IAED,QAAQ,CAAI,EAAkD;QAC7D,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACnB,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;IAED,KAAK,CAAC,aAAa,CAAI,EAA2D;QACjF,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC9C,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACnB,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;CACD","sourcesContent":["import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport type { AuthStorageData } from \"./auth-storage.ts\";\n\nexport type LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\nexport interface AuthStorageBackend {\n\t/**\n\t * Read the current credential snapshot WITHOUT acquiring the exclusive write\n\t * lock. Pure reads do not need cross-process write-exclusion: writers replace\n\t * the file atomically (temp file + rename), so a lock-free reader always\n\t * observes a complete previous-or-next snapshot, never a torn one. Keeping\n\t * reads lock-free is what prevents many concurrent sessions from starving each\n\t * other on `auth.json` and misreporting configured providers as unreadable\n\t * under contention (issue #1431).\n\t *\n\t * Optional for backward compatibility with custom backends that predate this\n\t * method (the released `AuthStorageBackend` interface): when absent,\n\t * `AuthStorage.reload()` falls back to a `withLock`-based read.\n\t */\n\tread?(): string | undefined;\n\tdeleteProvider?(provider: string): string | undefined;\n\tdeleteProviderAsync?(provider: string): Promise<string | undefined>;\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tdeclare private authPath: string;\n\tdeclare private readPaths: string[];\n\n\tconstructor(\n\t\tauthPath: string = join(getAgentDir(), \"auth.json\"),\n\t\treadPaths: string[] = [authPath],\n\t) {\n\t\tthis.authPath = normalizePath(authPath);\n\t\tthis.readPaths = readPaths.map((readPath) => normalizePath(readPath));\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\tprivate readMergedAuth(): string | undefined {\n\t\tlet merged: AuthStorageData = {};\n\t\tlet found = false;\n\t\tfor (let i = this.readPaths.length - 1; i >= 0; i--) {\n\t\t\tconst readPath = this.readPaths[i]!;\n\t\t\tif (!existsSync(readPath)) continue;\n\t\t\tconst parsed = JSON.parse(readFileSync(readPath, \"utf-8\")) as AuthStorageData;\n\t\t\tmerged = { ...merged, ...parsed };\n\t\t\tfound = true;\n\t\t}\n\t\treturn found ? JSON.stringify(merged, null, 2) : undefined;\n\t}\n\n\t/**\n\t * Atomically replace `auth.json` with `content`: write a sibling temp file\n\t * (same directory, so `rename` is a same-filesystem atomic swap), fix its\n\t * permissions, then `rename` it over the target. Lock-free readers therefore\n\t * never observe a half-written file. The temp file is best-effort cleaned up\n\t * if the rename fails.\n\t */\n\tprivate writeAtomic(content: string, path = this.authPath): void {\n\t\tconst dir = dirname(path);\n\t\tconst tempPath = join(\n\t\t\tdir,\n\t\t\t`.${`auth.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`}.tmp`,\n\t\t);\n\t\ttry {\n\t\t\twriteFileSync(tempPath, content, AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(tempPath, 0o600);\n\t\t\trenameSync(tempPath, path);\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tif (existsSync(tempPath)) rmSync(tempPath, { force: true });\n\t\t\t} catch {\n\t\t\t\t// Best-effort cleanup; ignore.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tread(): string | undefined {\n\t\treturn this.readMergedAuth();\n\t}\n\n\tdeleteProvider(provider: string): string | undefined {\n\t\tconst paths = [...new Set(this.readPaths.filter((path) => existsSync(path)))].sort();\n\t\tconst releases: Array<() => void> = [];\n\t\ttry {\n\t\t\tfor (const path of paths) releases.push(this.acquireLockSyncWithRetry(path));\n\t\t\tfor (const path of paths) {\n\t\t\t\tconst data = JSON.parse(readFileSync(path, \"utf-8\")) as AuthStorageData;\n\t\t\t\tif (!(provider in data)) continue;\n\t\t\t\tdelete data[provider];\n\t\t\t\tthis.writeAtomic(JSON.stringify(data, null, 2), path);\n\t\t\t}\n\t\t\treturn this.readMergedAuth();\n\t\t} finally {\n\t\t\tfor (const release of releases.reverse()) release();\n\t\t}\n\t}\n\n\tasync deleteProviderAsync(provider: string): Promise<string | undefined> {\n\t\tconst paths = [...new Set(this.readPaths.filter((path) => existsSync(path)))].sort();\n\t\tconst releases: Array<() => Promise<void>> = [];\n\t\ttry {\n\t\t\tfor (const path of paths) {\n\t\t\t\treleases.push(await lockfile.lock(path, {\n\t\t\t\t\trealpath: false,\n\t\t\t\t\tretries: { retries: 10, factor: 2, minTimeout: 100, maxTimeout: 10000, randomize: true },\n\t\t\t\t\tstale: 30000,\n\t\t\t\t}));\n\t\t\t}\n\t\t\tfor (const path of paths) {\n\t\t\t\tconst data = JSON.parse(readFileSync(path, \"utf-8\")) as AuthStorageData;\n\t\t\t\tif (!(provider in data)) continue;\n\t\t\t\tdelete data[provider];\n\t\t\t\tthis.writeAtomic(JSON.stringify(data, null, 2), path);\n\t\t\t}\n\t\t\treturn this.readMergedAuth();\n\t\t} finally {\n\t\t\tfor (const release of releases.reverse()) await release();\n\t\t}\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\tif (existsSync(this.authPath)) {\n\t\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\t}\n\t\t\tconst current = this.readMergedAuth();\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\tif (!existsSync(this.authPath)) {\n\t\t\t\t\tthis.ensureFileExists();\n\t\t\t\t}\n\t\t\t\tif (!release) {\n\t\t\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\t\t}\n\t\t\t\tthis.writeAtomic(next);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tif (!existsSync(this.authPath)) {\n\t\t\t\tthis.ensureFileExists();\n\t\t\t}\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: 30000,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = this.readMergedAuth();\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\tthis.writeAtomic(next);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\tread(): string | undefined {\n\t\treturn this.value;\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"auth-storage.d.ts","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAGN,KAAK,eAAe,EACpB,KAAK,SAAS,EAEd,KAAK,gBAAgB,EACrB,MAAM,uBAAuB,CAAC;AAI/B,OAAO,EAAsD,KAAK,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACzH,OAAO,EACN,KAAK,yBAAyB,EAK9B,MAAM,4BAA4B,CAAC;AAGpC,MAAM,MAAM,gBAAgB,GAAG;IAC9B,IAAI,EAAE,SAAS,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACZ,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,OAAO,CAAC;CACd,GAAG,gBAAgB,CAAC;AAErB,MAAM,MAAM,cAAc,GAAG,gBAAgB,GAAG,eAAe,CAAC;AAEhE,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;AAE7D,MAAM,MAAM,UAAU,GAAG;IACxB,UAAU,EAAE,OAAO,CAAC;IACpB,MAAM,CAAC,EAAE,QAAQ,GAAG,SAAS,GAAG,aAAa,GAAG,UAAU,GAAG,iBAAiB,GAAG,qBAAqB,CAAC;IACvG,KAAK,CAAC,EAAE,MAAM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E,MAAM,GAAG,OAAO,CAE7B;IAED;;;OAGG;IACH,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAMjC;IAED;;OAEG;IACH,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,CAmB1C;IAED,kDAAkD;IAClD,MAAM,IAAI,eAAe,CAExB;IAED,WAAW,IAAI,KAAK,EAAE,CAIrB;IAED;;;;;;;;;;OAUG;IACH,YAAY,IAAI,KAAK,GAAG,IAAI,CAE3B;IAED;;OAEG;IACG,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC,CAGnF;IAED,iEAAiE;IACjE,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAE7B;IAED,sEAAsE;IAChE,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEjD;IAED;;;OAGG;YACW,yBAAyB;IAyCvC;;;;;;;;OAQG;IACG,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CA+B9G;IAEK,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAExG;IAED;;OAEG;IACH,iBAAiB,mEAEhB;IAED,OAAO,CAAC,qBAAqB;IAS7B,uEAAuE;IACvE,iBAAiB,IAAI,eAAe,CA+DnC;CACD"}
@@ -155,7 +155,19 @@ export class AuthStorage {
155
155
  * Remove credential for a provider.
156
156
  */
157
157
  remove(provider) {
158
- this.persistProviderChange(provider, undefined);
158
+ if (!this.storage.deleteProvider) {
159
+ this.persistProviderChange(provider, undefined);
160
+ return;
161
+ }
162
+ try {
163
+ this.data = this.parseStorageData(this.storage.deleteProvider(provider));
164
+ this.bumpCredentialVersion(provider);
165
+ this.loadError = null;
166
+ }
167
+ catch (error) {
168
+ this.recordError(error);
169
+ throw error instanceof Error ? error : new Error(String(error));
170
+ }
159
171
  }
160
172
  /**
161
173
  * List all providers with credentials.
@@ -382,18 +394,22 @@ export class AuthStorage {
382
394
  }
383
395
  }),
384
396
  delete: (providerId) => this.runCredentialMutation(async () => {
385
- let synchronizedData;
386
397
  try {
387
- await this.storage.withLockAsync(async (current) => {
388
- const data = this.parseStorageData(current);
389
- delete data[providerId];
390
- synchronizedData = data;
391
- return { result: undefined, next: JSON.stringify(data, null, 2) };
392
- });
393
- if (synchronizedData) {
394
- this.data = synchronizedData;
395
- this.bumpCredentialVersion(providerId);
398
+ if (this.storage.deleteProviderAsync) {
399
+ this.data = this.parseStorageData(await this.storage.deleteProviderAsync(providerId));
400
+ }
401
+ else {
402
+ let synchronizedData;
403
+ await this.storage.withLockAsync(async (current) => {
404
+ const data = this.parseStorageData(current);
405
+ delete data[providerId];
406
+ synchronizedData = data;
407
+ return { result: undefined, next: JSON.stringify(data, null, 2) };
408
+ });
409
+ if (synchronizedData)
410
+ this.data = synchronizedData;
396
411
  }
412
+ this.bumpCredentialVersion(providerId);
397
413
  this.loadError = null;
398
414
  }
399
415
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"auth-storage.js","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAUH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,sBAAsB,EAAE,0BAA0B,EAA2B,MAAM,4BAA4B,CAAC;AACzH,OAAO,EAEN,2BAA2B,EAC3B,kBAAkB,EAClB,qBAAqB,EACrB,oBA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;oBACH,IAAI,gBAAgB,EAAE,CAAC;wBACtB,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;wBAC7B,IAAI,CAAC,qBAAqB,CAAC,UAAU,CAAC,CAAC;oBACxC,CAAC;oBACD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;gBACvB,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBAChB,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;oBACxB,MAAM,KAAK,CAAC;gBACb,CAAC;YACF,CAAC,CAAC;SACH,CAAC;IACH,CAAC;CACD","sourcesContent":["/**\n * Credential storage for API keys and OAuth tokens.\n * Handles loading, saving, and refreshing credentials from auth.json.\n *\n * Uses file locking to prevent race conditions when multiple pi instances\n * try to refresh tokens simultaneously.\n */\n\nimport {\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\ttype ModelAuth,\n\ttype OAuthCredential as PiOAuthCredential,\n\ttype OAuthCredentials,\n} from \"@earendil-works/pi-ai\";\nimport { findEnvKeys, getEnvApiKey } from \"@earendil-works/pi-ai/compat\";\nimport { join } from \"path\";\nimport { getAgentConfigPaths, getAgentDir } from \"../config.ts\";\nimport { FileAuthStorageBackend, InMemoryAuthStorageBackend, type AuthStorageBackend } from \"./auth-storage-backends.ts\";\nimport {\n\ttype AtomicOAuthLoginCallbacks,\n\tgetOAuthProviderDescriptors,\n\tloginOAuthProvider,\n\toauthCredentialToAuth,\n\trefreshOAuthProvider,\n} from \"./oauth-provider-bridge.ts\";\nimport { resolveConfigValue } from \"./resolve-config-value.ts\";\n\nexport type ApiKeyCredential = {\n\ttype: \"api_key\";\n\tkey: string;\n};\n\nexport type OAuthCredential = {\n\ttype: \"oauth\";\n} & OAuthCredentials;\n\nexport type AuthCredential = ApiKeyCredential | OAuthCredential;\n\nexport type AuthStorageData = Record<string, AuthCredential>;\n\nexport type AuthStatus = {\n\tconfigured: boolean;\n\tsource?: \"stored\" | \"runtime\" | \"environment\" | \"fallback\" | \"models_json_key\" | \"models_json_command\";\n\tlabel?: string;\n};\n\nexport { FileAuthStorageBackend, InMemoryAuthStorageBackend, type AuthStorageBackend } from \"./auth-storage-backends.ts\";\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage {\n\tprivate data: AuthStorageData = {};\n\tprivate runtimeOverrides: Map<string, string> = new Map();\n\tprivate fallbackResolver?: (provider: string) => string | undefined;\n\tprivate loadError: Error | null = null;\n\tprivate errors: Error[] = [];\n\tprivate credentialMutationTail: Promise<void> = Promise.resolve();\n\tprivate credentialVersions = new Map<string, number>();\n\n\tdeclare private storage: AuthStorageBackend;\n\n\tprivate constructor(storage: AuthStorageBackend) {\n\t\tthis.storage = storage;\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath?: string | string[]): AuthStorage {\n\t\tconst paths = authPath === undefined\n\t\t\t? getAgentConfigPaths(\"auth.json\")\n\t\t\t: Array.isArray(authPath) ? authPath : [authPath];\n\t\treturn new AuthStorage(new FileAuthStorageBackend(paths[0] ?? join(getAgentDir(), \"auth.json\"), paths));\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\t/**\n\t * Set a runtime API key override (not persisted to disk).\n\t * Used for CLI --api-key flag.\n\t */\n\tsetRuntimeApiKey(provider: string, apiKey: string): void {\n\t\tthis.runtimeOverrides.set(provider, apiKey);\n\t}\n\t/** Read a non-persisted request override without resolving stored credentials. */\n\tgetRuntimeApiKey(provider: string): string | undefined {\n\t\treturn this.runtimeOverrides.get(provider);\n\t}\n\n\n\t/**\n\t * Remove a runtime API key override.\n\t */\n\tremoveRuntimeApiKey(provider: string): void {\n\t\tthis.runtimeOverrides.delete(provider);\n\t}\n\n\t/**\n\t * Set a fallback resolver for API keys not found in auth.json or env vars.\n\t * Used for custom provider keys from models.json.\n\t */\n\tsetFallbackResolver(resolver: (provider: string) => string | undefined): void {\n\t\tthis.fallbackResolver = resolver;\n\t}\n\n\tprivate recordError(error: unknown): void {\n\t\tconst normalizedError = error instanceof Error ? error : new Error(String(error));\n\t\tthis.errors.push(normalizedError);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\ttry {\n\t\t\t// Pure read: never take the exclusive write lock. Writers replace\n\t\t\t// auth.json atomically, so a lock-free read always sees a complete\n\t\t\t// snapshot. This keeps many concurrent sessions from starving each other\n\t\t\t// on the lock and misreporting configured providers as unreadable under\n\t\t\t// contention (issue #1431).\n\t\t\tconst content = this.readSnapshot();\n\t\t\tthis.data = this.parseStorageData(content);\n\t\t\tthis.loadError = null;\n\t\t} catch (error) {\n\t\t\tthis.loadError = error as Error;\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\t/**\n\t * Read the credential snapshot, preferring the backend's lock-free `read()`.\n\t * Falls back to a `withLock`-based read for custom backends that predate\n\t * `read()` so the released `AuthStorageBackend` interface stays compatible.\n\t */\n\tprivate readSnapshot(): string | undefined {\n\t\tif (this.storage.read) {\n\t\t\treturn this.storage.read();\n\t\t}\n\t\tlet content: string | undefined;\n\t\tthis.storage.withLock((current) => {\n\t\t\tcontent = current;\n\t\t\treturn { result: undefined };\n\t\t});\n\t\treturn content;\n\t}\n\n\tprivate bumpCredentialVersion(provider: string): void {\n\t\tthis.credentialVersions.set(provider, (this.credentialVersions.get(provider) ?? 0) + 1);\n\t}\n\n\tprivate persistProviderChange(provider: string, credential: AuthCredential | undefined): void {\n\t\tif (this.loadError) {\n\t\t\tthis.reload();\n\t\t\tif (this.loadError) throw this.loadError;\n\t\t}\n\n\t\ttry {\n\t\t\tconst persistedData = this.storage.withLock((current) => {\n\t\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\t\tconst merged: AuthStorageData = { ...currentData };\n\t\t\t\tif (credential) {\n\t\t\t\t\tmerged[provider] = credential;\n\t\t\t\t} else {\n\t\t\t\t\tdelete merged[provider];\n\t\t\t\t}\n\t\t\t\treturn { result: merged, next: JSON.stringify(merged, null, 2) };\n\t\t\t});\n\t\t\tthis.data = persistedData;\n\t\t\tthis.bumpCredentialVersion(provider);\n\t\t\tthis.loadError = null;\n\t\t} catch (error) {\n\t\t\tthis.recordError(error);\n\t\t\tthrow error instanceof Error ? error : new Error(String(error));\n\t\t}\n\t}\n\n\t/**\n\t * Get credential for a provider.\n\t */\n\tget(provider: string): AuthCredential | undefined {\n\t\treturn this.data[provider] ?? undefined;\n\t}\n\n\t/**\n\t * Set credential for a provider.\n\t */\n\tset(provider: string, credential: AuthCredential): void {\n\t\tthis.persistProviderChange(provider, credential);\n\t}\n\n\t/**\n\t * Remove credential for a provider.\n\t */\n\tremove(provider: string): void {\n\t\tthis.persistProviderChange(provider, undefined);\n\t}\n\n\t/**\n\t * List all providers with credentials.\n\t */\n\tlist(): string[] {\n\t\treturn Object.keys(this.data);\n\t}\n\n\t/**\n\t * Check if credentials exist for a provider in auth.json.\n\t */\n\thas(provider: string): boolean {\n\t\treturn provider in this.data;\n\t}\n\n\t/**\n\t * Check if any form of auth is configured for a provider.\n\t * Unlike getApiKey(), this doesn't refresh OAuth tokens.\n\t */\n\thasAuth(provider: string): boolean {\n\t\tif (this.runtimeOverrides.has(provider)) return true;\n\t\tif (this.data[provider]) return true;\n\t\tif (getEnvApiKey(provider)) return true;\n\t\tif (this.fallbackResolver?.(provider)) return true;\n\t\treturn false;\n\t}\n\n\t/**\n\t * Return auth status without exposing credential values or refreshing tokens.\n\t */\n\tgetAuthStatus(provider: string): AuthStatus {\n\t\tif (this.data[provider]) {\n\t\t\treturn { configured: true, source: \"stored\" };\n\t\t}\n\n\t\tif (this.runtimeOverrides.has(provider)) {\n\t\t\treturn { configured: false, source: \"runtime\", label: \"--api-key\" };\n\t\t}\n\n\t\tconst envKeys = findEnvKeys(provider);\n\t\tif (envKeys?.[0]) {\n\t\t\treturn { configured: false, source: \"environment\", label: envKeys[0] };\n\t\t}\n\n\t\tif (this.fallbackResolver?.(provider)) {\n\t\t\treturn { configured: false, source: \"fallback\", label: \"custom provider config\" };\n\t\t}\n\n\t\treturn { configured: false };\n\t}\n\n\t/** Return a copy of all persisted credentials. */\n\tgetAll(): AuthStorageData {\n\t\treturn { ...this.data };\n\t}\n\n\tdrainErrors(): Error[] {\n\t\tconst drained = [...this.errors];\n\t\tthis.errors = [];\n\t\treturn drained;\n\t}\n\n\t/**\n\t * Returns the error from the most recent failed credential load, or null when\n\t * the last reload succeeded.\n\t *\n\t * A non-null value means stored credentials could NOT be read — e.g. the auth\n\t * file was temporarily locked by another process (ELOCKED) or contained\n\t * invalid JSON — so an empty/absent credential set is NOT authoritative.\n\t * Callers that would otherwise report \"No API key found\" should surface this\n\t * load failure instead of treating the provider as unauthenticated\n\t * (issue #1431).\n\t */\n\tgetLoadError(): Error | null {\n\t\treturn this.loadError;\n\t}\n\n\t/**\n\t * Login to an OAuth provider.\n\t */\n\tasync login(providerId: string, callbacks: AtomicOAuthLoginCallbacks): Promise<void> {\n\t\tconst credential = await loginOAuthProvider(providerId, callbacks);\n\t\tawait this.asCredentialStore().modify(providerId, async () => credential);\n\t}\n\n\t/** Logout through the preserved synchronous persistence path. */\n\tlogout(provider: string): void {\n\t\tthis.remove(provider);\n\t}\n\n\t/** Serialized logout for callers that need persistence completion. */\n\tasync logoutAsync(provider: string): Promise<void> {\n\t\tawait this.asCredentialStore().delete(provider);\n\t}\n\n\t/**\n\t * Refresh OAuth token with backend locking to prevent race conditions.\n\t * Multiple pi instances may try to refresh simultaneously when tokens expire.\n\t */\n\tprivate async refreshOAuthTokenWithLock(\n\t\tproviderId: string,\n\t): Promise<{ auth: ModelAuth; newCredentials: OAuthCredentials } | null> {\n\t\treturn this.runCredentialMutation(async () => {\n\t\t\tlet synchronizedData: AuthStorageData | undefined;\n\t\t\tconst credentialVersion = this.credentialVersions.get(providerId) ?? 0;\n\t\t\tconst result = await this.storage.withLockAsync(async (current) => {\n\t\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\t\tsynchronizedData = currentData;\n\t\t\t\tconst cred = currentData[providerId];\n\t\t\t\tif (cred?.type !== \"oauth\") return { result: null };\n\n\t\t\t\tconst oauthCredential: PiOAuthCredential = { ...cred, type: \"oauth\" };\n\t\t\t\tif (Date.now() < cred.expires) {\n\t\t\t\t\tconst auth = await oauthCredentialToAuth(providerId, oauthCredential);\n\t\t\t\t\treturn { result: auth ? { auth, newCredentials: cred } : null };\n\t\t\t\t}\n\n\t\t\t\tconst refreshed = await refreshOAuthProvider(providerId, oauthCredential);\n\t\t\t\tif (!refreshed) return { result: null };\n\t\t\t\tif ((this.credentialVersions.get(providerId) ?? 0) !== credentialVersion) {\n\t\t\t\t\tsynchronizedData = undefined;\n\t\t\t\t\treturn { result: null };\n\t\t\t\t}\n\t\t\t\tconst merged: AuthStorageData = {\n\t\t\t\t\t...currentData,\n\t\t\t\t\t[providerId]: refreshed.credential,\n\t\t\t\t};\n\t\t\t\tsynchronizedData = merged;\n\t\t\t\treturn {\n\t\t\t\t\tresult: { auth: refreshed.auth, newCredentials: refreshed.credential },\n\t\t\t\t\tnext: JSON.stringify(merged, null, 2),\n\t\t\t\t};\n\t\t\t});\n\n\t\t\tif (synchronizedData) this.data = synchronizedData;\n\t\t\tthis.loadError = null;\n\t\t\treturn result;\n\t\t});\n\t}\n\n\t/**\n\t * Get API key for a provider.\n\t * Priority:\n\t * 1. Runtime override (CLI --api-key)\n\t * 2. API key from auth.json\n\t * 3. OAuth token from auth.json (auto-refreshed with locking)\n\t * 4. Environment variable\n\t * 5. Fallback resolver (models.json custom providers)\n\t */\n\tasync getModelAuth(providerId: string, options?: { includeFallback?: boolean }): Promise<ModelAuth | undefined> {\n\t\tconst runtimeKey = this.runtimeOverrides.get(providerId);\n\t\tif (runtimeKey) return { apiKey: runtimeKey };\n\n\t\tconst cred = this.data[providerId];\n\t\tif (cred?.type === \"api_key\") return { apiKey: resolveConfigValue(cred.key) };\n\n\t\tif (cred?.type === \"oauth\") {\n\t\t\ttry {\n\t\t\t\tif (Date.now() >= cred.expires) {\n\t\t\t\t\treturn (await this.refreshOAuthTokenWithLock(providerId))?.auth;\n\t\t\t\t}\n\t\t\t\treturn await oauthCredentialToAuth(providerId, { ...cred, type: \"oauth\" });\n\t\t\t} catch (error) {\n\t\t\t\tthis.recordError(error);\n\t\t\t\tthis.reload();\n\t\t\t\tconst updated = this.data[providerId];\n\t\t\t\tif (updated?.type === \"oauth\" && Date.now() < updated.expires) {\n\t\t\t\t\treturn oauthCredentialToAuth(providerId, { ...updated, type: \"oauth\" });\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tconst envKey = getEnvApiKey(providerId);\n\t\tif (envKey) return { apiKey: envKey };\n\t\tif (options?.includeFallback !== false) {\n\t\t\tconst fallback = this.fallbackResolver?.(providerId);\n\t\t\tif (fallback) return { apiKey: fallback };\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tasync getApiKey(providerId: string, options?: { includeFallback?: boolean }): Promise<string | undefined> {\n\t\treturn (await this.getModelAuth(providerId, options))?.apiKey;\n\t}\n\n\t/**\n\t * Get all registered OAuth providers\n\t */\n\tgetOAuthProviders() {\n\t\treturn getOAuthProviderDescriptors();\n\t}\n\n\tprivate runCredentialMutation<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = this.credentialMutationTail.then(operation, operation);\n\t\tthis.credentialMutationTail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n\n\t/** Private async adapter for pi-ai's provider-owned Models runtime. */\n\tasCredentialStore(): CredentialStore {\n\t\tconst runtimeCredential = (providerId: string): Credential | undefined => {\n\t\t\tconst key = this.runtimeOverrides.get(providerId);\n\t\t\treturn key === undefined ? undefined : { type: \"api_key\", key };\n\t\t};\n\t\treturn {\n\t\t\tread: async (providerId) => runtimeCredential(providerId) ?? (this.get(providerId) as Credential | undefined),\n\t\t\tlist: async (): Promise<readonly CredentialInfo[]> => {\n\t\t\t\tconst providers = new Set([...this.list(), ...this.runtimeOverrides.keys()]);\n\t\t\t\treturn [...providers].map((providerId) => ({\n\t\t\t\t\tproviderId,\n\t\t\t\t\ttype: runtimeCredential(providerId)?.type ?? this.data[providerId].type,\n\t\t\t\t}));\n\t\t\t},\n\t\t\tmodify: (providerId, fn) =>\n\t\t\t\tthis.runCredentialMutation(async () => {\n\t\t\t\t\tlet synchronizedData: AuthStorageData | undefined;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.storage.withLockAsync(async (current) => {\n\t\t\t\t\t\t\tconst data = this.parseStorageData(current);\n\t\t\t\t\t\t\tconst next = await fn(data[providerId] as Credential | undefined);\n\t\t\t\t\t\t\tif (next === undefined) {\n\t\t\t\t\t\t\t\tsynchronizedData = data;\n\t\t\t\t\t\t\t\treturn { result: data[providerId] as Credential | undefined };\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst merged = { ...data, [providerId]: next as AuthCredential };\n\t\t\t\t\t\t\tsynchronizedData = merged;\n\t\t\t\t\t\t\treturn { result: next, next: JSON.stringify(merged, null, 2) };\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (synchronizedData) {\n\t\t\t\t\t\t\tthis.data = synchronizedData;\n\t\t\t\t\t\t\tthis.bumpCredentialVersion(providerId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.loadError = null;\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.recordError(error);\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\tdelete: (providerId) =>\n\t\t\t\tthis.runCredentialMutation(async () => {\n\t\t\t\t\tlet synchronizedData: AuthStorageData | undefined;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.storage.withLockAsync(async (current) => {\n\t\t\t\t\t\t\tconst data = this.parseStorageData(current);\n\t\t\t\t\t\t\tdelete data[providerId];\n\t\t\t\t\t\t\tsynchronizedData = data;\n\t\t\t\t\t\t\treturn { result: undefined, next: JSON.stringify(data, null, 2) };\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (synchronizedData) {\n\t\t\t\t\t\t\tthis.data = synchronizedData;\n\t\t\t\t\t\t\tthis.bumpCredentialVersion(providerId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.loadError = null;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.recordError(error);\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t};\n\t}\n}\n"]}
1
+ {"version":3,"file":"auth-storage.js","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAUH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,sBAAsB,EAAE,0BAA0B,EAA2B,MAAM,4BAA4B,CAAC;AACzH,OAAO,EAEN,2BAA2B,EAC3B,kBAAkB,EAClB,qBAAqB,EACrB,oBAAoB,GACpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAqB/D,OAAO,EAAE,sBAAsB,EAAE,0BAA0B,EAA2B,MAAM,4BAA4B,CAAC;AAEzH;;GAEG;AACH,MAAM,OAAO,WAAW;IAWvB,YAAoB,OAA2B;QAVvC,SAAI,GAAoB,EAAE,CAAC;QAC3B,qBAAgB,GAA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OAAO,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,CAAC;oBACvF,CAAC;yBAAM,CAAC;wBACP,IAAI,gBAA6C,CAAC;wBAClD,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;4BAClD,MAAM,IAAI,GAAG,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;4BAC5C,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC;4BACxB,gBAAgB,GAAG,IAAI,CAAC;4BACxB,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;wBACnE,CAAC,CAAC,CAAC;wBACH,IAAI,gBAAgB;4BAAE,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;oBACpD,CAAC;oBACD,IAAI,CAAC,qBAAqB,CAAC,UAAU,CAAC,CAAC;oBACvC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;gBACvB,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBAChB,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;oBACxB,MAAM,KAAK,CAAC;gBACb,CAAC;YACF,CAAC,CAAC;SACH,CAAC;IACH,CAAC;CACD","sourcesContent":["/**\n * Credential storage for API keys and OAuth tokens.\n * Handles loading, saving, and refreshing credentials from auth.json.\n *\n * Uses file locking to prevent race conditions when multiple pi instances\n * try to refresh tokens simultaneously.\n */\n\nimport {\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\ttype ModelAuth,\n\ttype OAuthCredential as PiOAuthCredential,\n\ttype OAuthCredentials,\n} from \"@earendil-works/pi-ai\";\nimport { findEnvKeys, getEnvApiKey } from \"@earendil-works/pi-ai/compat\";\nimport { join } from \"path\";\nimport { getAgentConfigPaths, getAgentDir } from \"../config.ts\";\nimport { FileAuthStorageBackend, InMemoryAuthStorageBackend, type AuthStorageBackend } from \"./auth-storage-backends.ts\";\nimport {\n\ttype AtomicOAuthLoginCallbacks,\n\tgetOAuthProviderDescriptors,\n\tloginOAuthProvider,\n\toauthCredentialToAuth,\n\trefreshOAuthProvider,\n} from \"./oauth-provider-bridge.ts\";\nimport { resolveConfigValue } from \"./resolve-config-value.ts\";\n\nexport type ApiKeyCredential = {\n\ttype: \"api_key\";\n\tkey: string;\n};\n\nexport type OAuthCredential = {\n\ttype: \"oauth\";\n} & OAuthCredentials;\n\nexport type AuthCredential = ApiKeyCredential | OAuthCredential;\n\nexport type AuthStorageData = Record<string, AuthCredential>;\n\nexport type AuthStatus = {\n\tconfigured: boolean;\n\tsource?: \"stored\" | \"runtime\" | \"environment\" | \"fallback\" | \"models_json_key\" | \"models_json_command\";\n\tlabel?: string;\n};\n\nexport { FileAuthStorageBackend, InMemoryAuthStorageBackend, type AuthStorageBackend } from \"./auth-storage-backends.ts\";\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage {\n\tprivate data: AuthStorageData = {};\n\tprivate runtimeOverrides: Map<string, string> = new Map();\n\tprivate fallbackResolver?: (provider: string) => string | undefined;\n\tprivate loadError: Error | null = null;\n\tprivate errors: Error[] = [];\n\tprivate credentialMutationTail: Promise<void> = Promise.resolve();\n\tprivate credentialVersions = new Map<string, number>();\n\n\tdeclare private storage: AuthStorageBackend;\n\n\tprivate constructor(storage: AuthStorageBackend) {\n\t\tthis.storage = storage;\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath?: string | string[]): AuthStorage {\n\t\tconst paths = authPath === undefined\n\t\t\t? getAgentConfigPaths(\"auth.json\")\n\t\t\t: Array.isArray(authPath) ? authPath : [authPath];\n\t\treturn new AuthStorage(new FileAuthStorageBackend(paths[0] ?? join(getAgentDir(), \"auth.json\"), paths));\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\t/**\n\t * Set a runtime API key override (not persisted to disk).\n\t * Used for CLI --api-key flag.\n\t */\n\tsetRuntimeApiKey(provider: string, apiKey: string): void {\n\t\tthis.runtimeOverrides.set(provider, apiKey);\n\t}\n\t/** Read a non-persisted request override without resolving stored credentials. */\n\tgetRuntimeApiKey(provider: string): string | undefined {\n\t\treturn this.runtimeOverrides.get(provider);\n\t}\n\n\n\t/**\n\t * Remove a runtime API key override.\n\t */\n\tremoveRuntimeApiKey(provider: string): void {\n\t\tthis.runtimeOverrides.delete(provider);\n\t}\n\n\t/**\n\t * Set a fallback resolver for API keys not found in auth.json or env vars.\n\t * Used for custom provider keys from models.json.\n\t */\n\tsetFallbackResolver(resolver: (provider: string) => string | undefined): void {\n\t\tthis.fallbackResolver = resolver;\n\t}\n\n\tprivate recordError(error: unknown): void {\n\t\tconst normalizedError = error instanceof Error ? error : new Error(String(error));\n\t\tthis.errors.push(normalizedError);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\ttry {\n\t\t\t// Pure read: never take the exclusive write lock. Writers replace\n\t\t\t// auth.json atomically, so a lock-free read always sees a complete\n\t\t\t// snapshot. This keeps many concurrent sessions from starving each other\n\t\t\t// on the lock and misreporting configured providers as unreadable under\n\t\t\t// contention (issue #1431).\n\t\t\tconst content = this.readSnapshot();\n\t\t\tthis.data = this.parseStorageData(content);\n\t\t\tthis.loadError = null;\n\t\t} catch (error) {\n\t\t\tthis.loadError = error as Error;\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\t/**\n\t * Read the credential snapshot, preferring the backend's lock-free `read()`.\n\t * Falls back to a `withLock`-based read for custom backends that predate\n\t * `read()` so the released `AuthStorageBackend` interface stays compatible.\n\t */\n\tprivate readSnapshot(): string | undefined {\n\t\tif (this.storage.read) {\n\t\t\treturn this.storage.read();\n\t\t}\n\t\tlet content: string | undefined;\n\t\tthis.storage.withLock((current) => {\n\t\t\tcontent = current;\n\t\t\treturn { result: undefined };\n\t\t});\n\t\treturn content;\n\t}\n\n\tprivate bumpCredentialVersion(provider: string): void {\n\t\tthis.credentialVersions.set(provider, (this.credentialVersions.get(provider) ?? 0) + 1);\n\t}\n\n\tprivate persistProviderChange(provider: string, credential: AuthCredential | undefined): void {\n\t\tif (this.loadError) {\n\t\t\tthis.reload();\n\t\t\tif (this.loadError) throw this.loadError;\n\t\t}\n\n\t\ttry {\n\t\t\tconst persistedData = this.storage.withLock((current) => {\n\t\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\t\tconst merged: AuthStorageData = { ...currentData };\n\t\t\t\tif (credential) {\n\t\t\t\t\tmerged[provider] = credential;\n\t\t\t\t} else {\n\t\t\t\t\tdelete merged[provider];\n\t\t\t\t}\n\t\t\t\treturn { result: merged, next: JSON.stringify(merged, null, 2) };\n\t\t\t});\n\t\t\tthis.data = persistedData;\n\t\t\tthis.bumpCredentialVersion(provider);\n\t\t\tthis.loadError = null;\n\t\t} catch (error) {\n\t\t\tthis.recordError(error);\n\t\t\tthrow error instanceof Error ? error : new Error(String(error));\n\t\t}\n\t}\n\n\t/**\n\t * Get credential for a provider.\n\t */\n\tget(provider: string): AuthCredential | undefined {\n\t\treturn this.data[provider] ?? undefined;\n\t}\n\n\t/**\n\t * Set credential for a provider.\n\t */\n\tset(provider: string, credential: AuthCredential): void {\n\t\tthis.persistProviderChange(provider, credential);\n\t}\n\n\t/**\n\t * Remove credential for a provider.\n\t */\n\tremove(provider: string): void {\n\t\tif (!this.storage.deleteProvider) {\n\t\t\tthis.persistProviderChange(provider, undefined);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.data = this.parseStorageData(this.storage.deleteProvider(provider));\n\t\t\tthis.bumpCredentialVersion(provider);\n\t\t\tthis.loadError = null;\n\t\t} catch (error) {\n\t\t\tthis.recordError(error);\n\t\t\tthrow error instanceof Error ? error : new Error(String(error));\n\t\t}\n\t}\n\n\t/**\n\t * List all providers with credentials.\n\t */\n\tlist(): string[] {\n\t\treturn Object.keys(this.data);\n\t}\n\n\t/**\n\t * Check if credentials exist for a provider in auth.json.\n\t */\n\thas(provider: string): boolean {\n\t\treturn provider in this.data;\n\t}\n\n\t/**\n\t * Check if any form of auth is configured for a provider.\n\t * Unlike getApiKey(), this doesn't refresh OAuth tokens.\n\t */\n\thasAuth(provider: string): boolean {\n\t\tif (this.runtimeOverrides.has(provider)) return true;\n\t\tif (this.data[provider]) return true;\n\t\tif (getEnvApiKey(provider)) return true;\n\t\tif (this.fallbackResolver?.(provider)) return true;\n\t\treturn false;\n\t}\n\n\t/**\n\t * Return auth status without exposing credential values or refreshing tokens.\n\t */\n\tgetAuthStatus(provider: string): AuthStatus {\n\t\tif (this.data[provider]) {\n\t\t\treturn { configured: true, source: \"stored\" };\n\t\t}\n\n\t\tif (this.runtimeOverrides.has(provider)) {\n\t\t\treturn { configured: false, source: \"runtime\", label: \"--api-key\" };\n\t\t}\n\n\t\tconst envKeys = findEnvKeys(provider);\n\t\tif (envKeys?.[0]) {\n\t\t\treturn { configured: false, source: \"environment\", label: envKeys[0] };\n\t\t}\n\n\t\tif (this.fallbackResolver?.(provider)) {\n\t\t\treturn { configured: false, source: \"fallback\", label: \"custom provider config\" };\n\t\t}\n\n\t\treturn { configured: false };\n\t}\n\n\t/** Return a copy of all persisted credentials. */\n\tgetAll(): AuthStorageData {\n\t\treturn { ...this.data };\n\t}\n\n\tdrainErrors(): Error[] {\n\t\tconst drained = [...this.errors];\n\t\tthis.errors = [];\n\t\treturn drained;\n\t}\n\n\t/**\n\t * Returns the error from the most recent failed credential load, or null when\n\t * the last reload succeeded.\n\t *\n\t * A non-null value means stored credentials could NOT be read — e.g. the auth\n\t * file was temporarily locked by another process (ELOCKED) or contained\n\t * invalid JSON — so an empty/absent credential set is NOT authoritative.\n\t * Callers that would otherwise report \"No API key found\" should surface this\n\t * load failure instead of treating the provider as unauthenticated\n\t * (issue #1431).\n\t */\n\tgetLoadError(): Error | null {\n\t\treturn this.loadError;\n\t}\n\n\t/**\n\t * Login to an OAuth provider.\n\t */\n\tasync login(providerId: string, callbacks: AtomicOAuthLoginCallbacks): Promise<void> {\n\t\tconst credential = await loginOAuthProvider(providerId, callbacks);\n\t\tawait this.asCredentialStore().modify(providerId, async () => credential);\n\t}\n\n\t/** Logout through the preserved synchronous persistence path. */\n\tlogout(provider: string): void {\n\t\tthis.remove(provider);\n\t}\n\n\t/** Serialized logout for callers that need persistence completion. */\n\tasync logoutAsync(provider: string): Promise<void> {\n\t\tawait this.asCredentialStore().delete(provider);\n\t}\n\n\t/**\n\t * Refresh OAuth token with backend locking to prevent race conditions.\n\t * Multiple pi instances may try to refresh simultaneously when tokens expire.\n\t */\n\tprivate async refreshOAuthTokenWithLock(\n\t\tproviderId: string,\n\t): Promise<{ auth: ModelAuth; newCredentials: OAuthCredentials } | null> {\n\t\treturn this.runCredentialMutation(async () => {\n\t\t\tlet synchronizedData: AuthStorageData | undefined;\n\t\t\tconst credentialVersion = this.credentialVersions.get(providerId) ?? 0;\n\t\t\tconst result = await this.storage.withLockAsync(async (current) => {\n\t\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\t\tsynchronizedData = currentData;\n\t\t\t\tconst cred = currentData[providerId];\n\t\t\t\tif (cred?.type !== \"oauth\") return { result: null };\n\n\t\t\t\tconst oauthCredential: PiOAuthCredential = { ...cred, type: \"oauth\" };\n\t\t\t\tif (Date.now() < cred.expires) {\n\t\t\t\t\tconst auth = await oauthCredentialToAuth(providerId, oauthCredential);\n\t\t\t\t\treturn { result: auth ? { auth, newCredentials: cred } : null };\n\t\t\t\t}\n\n\t\t\t\tconst refreshed = await refreshOAuthProvider(providerId, oauthCredential);\n\t\t\t\tif (!refreshed) return { result: null };\n\t\t\t\tif ((this.credentialVersions.get(providerId) ?? 0) !== credentialVersion) {\n\t\t\t\t\tsynchronizedData = undefined;\n\t\t\t\t\treturn { result: null };\n\t\t\t\t}\n\t\t\t\tconst merged: AuthStorageData = {\n\t\t\t\t\t...currentData,\n\t\t\t\t\t[providerId]: refreshed.credential,\n\t\t\t\t};\n\t\t\t\tsynchronizedData = merged;\n\t\t\t\treturn {\n\t\t\t\t\tresult: { auth: refreshed.auth, newCredentials: refreshed.credential },\n\t\t\t\t\tnext: JSON.stringify(merged, null, 2),\n\t\t\t\t};\n\t\t\t});\n\n\t\t\tif (synchronizedData) this.data = synchronizedData;\n\t\t\tthis.loadError = null;\n\t\t\treturn result;\n\t\t});\n\t}\n\n\t/**\n\t * Get API key for a provider.\n\t * Priority:\n\t * 1. Runtime override (CLI --api-key)\n\t * 2. API key from auth.json\n\t * 3. OAuth token from auth.json (auto-refreshed with locking)\n\t * 4. Environment variable\n\t * 5. Fallback resolver (models.json custom providers)\n\t */\n\tasync getModelAuth(providerId: string, options?: { includeFallback?: boolean }): Promise<ModelAuth | undefined> {\n\t\tconst runtimeKey = this.runtimeOverrides.get(providerId);\n\t\tif (runtimeKey) return { apiKey: runtimeKey };\n\n\t\tconst cred = this.data[providerId];\n\t\tif (cred?.type === \"api_key\") return { apiKey: resolveConfigValue(cred.key) };\n\n\t\tif (cred?.type === \"oauth\") {\n\t\t\ttry {\n\t\t\t\tif (Date.now() >= cred.expires) {\n\t\t\t\t\treturn (await this.refreshOAuthTokenWithLock(providerId))?.auth;\n\t\t\t\t}\n\t\t\t\treturn await oauthCredentialToAuth(providerId, { ...cred, type: \"oauth\" });\n\t\t\t} catch (error) {\n\t\t\t\tthis.recordError(error);\n\t\t\t\tthis.reload();\n\t\t\t\tconst updated = this.data[providerId];\n\t\t\t\tif (updated?.type === \"oauth\" && Date.now() < updated.expires) {\n\t\t\t\t\treturn oauthCredentialToAuth(providerId, { ...updated, type: \"oauth\" });\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tconst envKey = getEnvApiKey(providerId);\n\t\tif (envKey) return { apiKey: envKey };\n\t\tif (options?.includeFallback !== false) {\n\t\t\tconst fallback = this.fallbackResolver?.(providerId);\n\t\t\tif (fallback) return { apiKey: fallback };\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tasync getApiKey(providerId: string, options?: { includeFallback?: boolean }): Promise<string | undefined> {\n\t\treturn (await this.getModelAuth(providerId, options))?.apiKey;\n\t}\n\n\t/**\n\t * Get all registered OAuth providers\n\t */\n\tgetOAuthProviders() {\n\t\treturn getOAuthProviderDescriptors();\n\t}\n\n\tprivate runCredentialMutation<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = this.credentialMutationTail.then(operation, operation);\n\t\tthis.credentialMutationTail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n\n\t/** Private async adapter for pi-ai's provider-owned Models runtime. */\n\tasCredentialStore(): CredentialStore {\n\t\tconst runtimeCredential = (providerId: string): Credential | undefined => {\n\t\t\tconst key = this.runtimeOverrides.get(providerId);\n\t\t\treturn key === undefined ? undefined : { type: \"api_key\", key };\n\t\t};\n\t\treturn {\n\t\t\tread: async (providerId) => runtimeCredential(providerId) ?? (this.get(providerId) as Credential | undefined),\n\t\t\tlist: async (): Promise<readonly CredentialInfo[]> => {\n\t\t\t\tconst providers = new Set([...this.list(), ...this.runtimeOverrides.keys()]);\n\t\t\t\treturn [...providers].map((providerId) => ({\n\t\t\t\t\tproviderId,\n\t\t\t\t\ttype: runtimeCredential(providerId)?.type ?? this.data[providerId].type,\n\t\t\t\t}));\n\t\t\t},\n\t\t\tmodify: (providerId, fn) =>\n\t\t\t\tthis.runCredentialMutation(async () => {\n\t\t\t\t\tlet synchronizedData: AuthStorageData | undefined;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.storage.withLockAsync(async (current) => {\n\t\t\t\t\t\t\tconst data = this.parseStorageData(current);\n\t\t\t\t\t\t\tconst next = await fn(data[providerId] as Credential | undefined);\n\t\t\t\t\t\t\tif (next === undefined) {\n\t\t\t\t\t\t\t\tsynchronizedData = data;\n\t\t\t\t\t\t\t\treturn { result: data[providerId] as Credential | undefined };\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst merged = { ...data, [providerId]: next as AuthCredential };\n\t\t\t\t\t\t\tsynchronizedData = merged;\n\t\t\t\t\t\t\treturn { result: next, next: JSON.stringify(merged, null, 2) };\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (synchronizedData) {\n\t\t\t\t\t\t\tthis.data = synchronizedData;\n\t\t\t\t\t\t\tthis.bumpCredentialVersion(providerId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.loadError = null;\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.recordError(error);\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\tdelete: (providerId) =>\n\t\t\t\tthis.runCredentialMutation(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (this.storage.deleteProviderAsync) {\n\t\t\t\t\t\t\tthis.data = this.parseStorageData(await this.storage.deleteProviderAsync(providerId));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlet synchronizedData: AuthStorageData | undefined;\n\t\t\t\t\t\t\tawait this.storage.withLockAsync(async (current) => {\n\t\t\t\t\t\t\t\tconst data = this.parseStorageData(current);\n\t\t\t\t\t\t\t\tdelete data[providerId];\n\t\t\t\t\t\t\t\tsynchronizedData = data;\n\t\t\t\t\t\t\t\treturn { result: undefined, next: JSON.stringify(data, null, 2) };\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (synchronizedData) this.data = synchronizedData;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.bumpCredentialVersion(providerId);\n\t\t\t\t\t\tthis.loadError = null;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.recordError(error);\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t};\n\t}\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export declare function isCodexTokenInvalidationError(provider: string, errorMessage: string | undefined): boolean;
2
+ export declare function formatCodexProviderError(provider: string, errorMessage: string): string;
3
+ //# sourceMappingURL=codex-errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex-errors.d.ts","sourceRoot":"","sources":["../../src/core/codex-errors.ts"],"names":[],"mappings":"AAIA,wBAAgB,6BAA6B,CAAC,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAEzG;AAED,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAKvF"}
@@ -0,0 +1,12 @@
1
+ const CODEX_INVALIDATED_TOKEN_PATTERN = /\binvalidated\s+(?:oauth|auth)\s+token\b|\btoken_revoked\b/i;
2
+ const CODEX_RECOVERY_GUIDANCE = "This Codex session may no longer be valid. Retry the request once in case the rejection is transient. If it persists, run `/logout` and select OpenAI ChatGPT Plus/Pro. Then run `/login`, authenticate OpenAI ChatGPT Plus/Pro again, and retry the request.";
3
+ export function isCodexTokenInvalidationError(provider, errorMessage) {
4
+ return provider === "openai-codex" && errorMessage !== undefined && CODEX_INVALIDATED_TOKEN_PATTERN.test(errorMessage);
5
+ }
6
+ export function formatCodexProviderError(provider, errorMessage) {
7
+ if (!isCodexTokenInvalidationError(provider, errorMessage) || errorMessage.includes(CODEX_RECOVERY_GUIDANCE)) {
8
+ return errorMessage;
9
+ }
10
+ return `${errorMessage}\n\n${CODEX_RECOVERY_GUIDANCE}`;
11
+ }
12
+ //# sourceMappingURL=codex-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex-errors.js","sourceRoot":"","sources":["../../src/core/codex-errors.ts"],"names":[],"mappings":"AAAA,MAAM,+BAA+B,GAAG,6DAA6D,CAAC;AACtG,MAAM,uBAAuB,GAC5B,+PAA+P,CAAC;AAEjQ,MAAM,UAAU,6BAA6B,CAAC,QAAgB,EAAE,YAAgC;IAC/F,OAAO,QAAQ,KAAK,cAAc,IAAI,YAAY,KAAK,SAAS,IAAI,+BAA+B,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AACxH,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,QAAgB,EAAE,YAAoB;IAC9E,IAAI,CAAC,6BAA6B,CAAC,QAAQ,EAAE,YAAY,CAAC,IAAI,YAAY,CAAC,QAAQ,CAAC,uBAAuB,CAAC,EAAE,CAAC;QAC9G,OAAO,YAAY,CAAC;IACrB,CAAC;IACD,OAAO,GAAG,YAAY,OAAO,uBAAuB,EAAE,CAAC;AACxD,CAAC","sourcesContent":["const CODEX_INVALIDATED_TOKEN_PATTERN = /\\binvalidated\\s+(?:oauth|auth)\\s+token\\b|\\btoken_revoked\\b/i;\nconst CODEX_RECOVERY_GUIDANCE =\n\t\"This Codex session may no longer be valid. Retry the request once in case the rejection is transient. If it persists, run `/logout` and select OpenAI ChatGPT Plus/Pro. Then run `/login`, authenticate OpenAI ChatGPT Plus/Pro again, and retry the request.\";\n\nexport function isCodexTokenInvalidationError(provider: string, errorMessage: string | undefined): boolean {\n\treturn provider === \"openai-codex\" && errorMessage !== undefined && CODEX_INVALIDATED_TOKEN_PATTERN.test(errorMessage);\n}\n\nexport function formatCodexProviderError(provider: string, errorMessage: string): string {\n\tif (!isCodexTokenInvalidationError(provider, errorMessage) || errorMessage.includes(CODEX_RECOVERY_GUIDANCE)) {\n\t\treturn errorMessage;\n\t}\n\treturn `${errorMessage}\\n\\n${CODEX_RECOVERY_GUIDANCE}`;\n}\n"]}
@@ -15,7 +15,7 @@ const WORKFLOW_ADMIN_COMPLETIONS = [
15
15
  const BUNDLED_WORKFLOW_COMPLETION_METADATA = [
16
16
  {
17
17
  name: "deep-research-codebase",
18
- description: "Scout + research-history chain parallel specialist waves → aggregator for deep codebase research.",
18
+ description: "Heavy research for tasks requiring comprehensive, whole-repository context.",
19
19
  inputs: {
20
20
  prompt: { description: "Research question or investigation focus for the codebase.", kind: "string" },
21
21
  max_partitions: { description: "Maximum number of codebase partitions to explore in parallel.", kind: "number" },
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EACN,gCAAgC,EAChC,yBAAyB,EACzB,iCAAiC,GACjC,MAAM,2BAA2B,CAAC;AA+BnC,MAAM,0BAA0B,GAAuB;IACtD,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,mCAAmC,EAAE;IACzF,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,yCAAyC,EAAE;IAC7F,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,2BAA2B,EAAE;IAC3E,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,wDAAwD,EAAE;IAC5G,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,iBAAiB,EAAE;IAC3E,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,kCAAkC,EAAE;IAClF,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,sBAAsB,EAAE;IACxE,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,2BAA2B,EAAE;IAC/E,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,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_GUIDE_COMMAND_NAME,\n\tgetAtomicGuideArgumentCompletions,\n} from \"./atomic-guide-command.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\tgetArgumentCompletions?: (\n\t\targumentPrefix: string,\n\t) => AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;\n}\n\ntype WorkflowInputCompletionMetadata = {\n\tdescription: string;\n\tkind?: \"boolean\" | \"number\" | \"string\";\n};\n\ntype WorkflowCompletionMetadata = {\n\tname: string;\n\tdescription: string;\n\tinputs: Record<string, WorkflowInputCompletionMetadata>;\n};\n\nconst WORKFLOW_ADMIN_COMPLETIONS: AutocompleteItem[] = [\n\t{ value: \"connect \", label: \"connect\", description: \"Attach to a run (picker if no id)\" },\n\t{ value: \"attach \", label: \"attach\", description: \"Open the in-place attach pane on a node\" },\n\t{ value: \"list \", label: \"list\", description: \"List registered workflows\" },\n\t{ value: \"status \", label: \"status\", description: \"List current-session active and retained terminal runs\" },\n\t{ value: \"interrupt \", label: \"interrupt\", description: \"Interrupt a run\" },\n\t{ value: \"quit \", label: \"quit\", description: \"Quit a run and keep it resumable\" },\n\t{ value: \"pause \", label: \"pause\", description: \"Pause a run or stage\" },\n\t{ value: \"resume \", label: \"resume\", description: \"Re-open overlay for a run\" },\n\t{ value: \"inputs \", label: \"inputs\", description: \"Show a workflow's input schema\" },\n\t{ value: \"reload \", label: \"reload\", description: \"Reload workflow resources\" },\n];\n\nconst BUNDLED_WORKFLOW_COMPLETION_METADATA: WorkflowCompletionMetadata[] = [\n\t{\n\t\tname: \"deep-research-codebase\",\n\t\tdescription: \"Scout + research-history chain → parallel specialist waves → aggregator for deep codebase research.\",\n\t\tinputs: {\n\t\t\tprompt: { description: \"Research question or investigation focus for the codebase.\", kind: \"string\" },\n\t\t\tmax_partitions: { description: \"Maximum number of codebase partitions to explore in parallel.\", kind: \"number\" },\n\t\t\tmax_concurrency: { description: \"Maximum number of workflow stages to run concurrently during deep research.\", kind: \"number\" },\n\t\t},\n\t},\n\t{\n\t\tname: \"goal\",\n\t\tdescription: \"Goal Runner workflow with bounded LM turns, acceptance criteria, ledger artifacts, reviewers, and reducer-gated completion.\",\n\t\tinputs: {\n\t\t\tobjective: { description: \"The objective or delta for this Goal Runner workflow run.\", kind: \"string\" },\n\t\t\tacceptance_criteria: { description: \"Original immutable task contract this run must remain consistent with.\", kind: \"string\" },\n\t\t\tmax_turns: { description: \"Maximum worker/review turns before Goal Runner stops as needs_human.\", kind: \"number\" },\n\t\t\tbase_branch: { description: \"Optional branch reviewers compare the current code delta against.\", kind: \"string\" },\n\t\t\tgit_worktree_dir: { description: \"Optional Git worktree path.\", kind: \"string\" },\n\t\t\tcreate_pr: { description: \"Whether to run the final pull-request creation stage after approval.\", kind: \"boolean\" },\n\t\t},\n\t},\n\t{\n\t\tname: \"open-claude-design\",\n\t\tdescription: \"AI-powered design workflow: discovery, reference research, HTML generation, refinement, and handoff.\",\n\t\tinputs: {\n\t\t\tprompt: { description: \"What to design, such as a dashboard, page, component, or prototype.\", kind: \"string\" },\n\t\t\tdiscover_references: { description: \"Discover current reference designs and feed them to generation.\", kind: \"boolean\" },\n\t\t\tmax_refinements: { description: \"Maximum generate/user-feedback loop iterations.\", kind: \"number\" },\n\t\t},\n\t},\n\t{\n\t\tname: \"ralph\",\n\t\tdescription: \"Raw prompt → research → orchestrate → multi-model parallel review loop with bounded iteration.\",\n\t\tinputs: {\n\t\t\tprompt: { description: \"The task or goal to research, execute, and refine.\", kind: \"string\" },\n\t\t\tacceptance_criteria: { description: \"Original immutable task contract this run must remain consistent with.\", kind: \"string\" },\n\t\t\tmax_loops: { description: \"Maximum research/orchestrate/review iterations.\", kind: \"number\" },\n\t\t\tbase_branch: { description: \"Branch reviewers compare the current code delta against.\", kind: \"string\" },\n\t\t\tgit_worktree_dir: { description: \"Optional Git worktree path.\", kind: \"string\" },\n\t\t\tcreate_pr: { description: \"Whether to run the final pull-request creation stage.\", kind: \"boolean\" },\n\t\t},\n\t},\n];\n\nfunction completeWorkflowToken(argumentText: string, candidates: AutocompleteItem[]): AutocompleteItem[] | null {\n\tconst tokenStart = /\\s$/.test(argumentText)\n\t\t? argumentText.length\n\t\t: Math.max(argumentText.lastIndexOf(\" \"), argumentText.lastIndexOf(\"\\t\")) + 1;\n\tconst head = argumentText.slice(0, tokenStart);\n\tconst token = argumentText.slice(tokenStart);\n\tconst normalizedToken = token.trimEnd();\n\tconst filtered = candidates\n\t\t.filter((candidate) => candidate.value.startsWith(token) && candidate.value.trimEnd() !== normalizedToken)\n\t\t.map((candidate) => ({ ...candidate, value: `${head}${candidate.value}` }));\n\treturn filtered.length > 0 ? filtered : null;\n}\n\nfunction bundledWorkflowNameItems(): AutocompleteItem[] {\n\treturn BUNDLED_WORKFLOW_COMPLETION_METADATA.map((workflow) => ({\n\t\tvalue: `${workflow.name} `,\n\t\tlabel: workflow.name,\n\t\tdescription: `Run workflow: ${workflow.name}`,\n\t}));\n}\n\nexport function getBundledWorkflowArgumentCompletions(argumentPrefix: string): AutocompleteItem[] | null {\n\tconst parts = argumentPrefix.trim().split(/\\s+/).filter(Boolean);\n\tconst subcommand = parts[0] ?? \"\";\n\tconst workflowItems = bundledWorkflowNameItems();\n\tif (!argumentPrefix.includes(\" \")) {\n\t\treturn completeWorkflowToken(argumentPrefix, [...WORKFLOW_ADMIN_COMPLETIONS, ...workflowItems]);\n\t}\n\tif (subcommand === \"inputs\") return completeWorkflowToken(argumentPrefix, workflowItems);\n\tif (subcommand === \"interrupt\") {\n\t\treturn completeWorkflowToken(argumentPrefix, [\n\t\t\t{ value: \"--all \", label: \"--all\", description: \"Interrupt all in-flight runs\" },\n\t\t\t{ value: \"--yes \", label: \"--yes\", description: \"Skip confirmation\" },\n\t\t\t{ value: \"-y \", label: \"-y\", description: \"Skip confirmation\" },\n\t\t]);\n\t}\n\tif (subcommand === \"quit\") {\n\t\treturn completeWorkflowToken(argumentPrefix, [\n\t\t\t{ value: \"--all \", label: \"--all\", description: \"Quit and keep all in-flight runs resumable\" },\n\t\t]);\n\t}\n\tif (!subcommand) return completeWorkflowToken(argumentPrefix, [...WORKFLOW_ADMIN_COMPLETIONS, ...workflowItems]);\n\n\tconst workflow = BUNDLED_WORKFLOW_COMPLETION_METADATA.find((candidate) => candidate.name === subcommand);\n\tif (!workflow) return null;\n\tconst tokenStart = /\\s$/.test(argumentPrefix)\n\t\t? argumentPrefix.length\n\t\t: Math.max(argumentPrefix.lastIndexOf(\" \"), argumentPrefix.lastIndexOf(\"\\t\")) + 1;\n\tconst token = argumentPrefix.slice(tokenStart);\n\tconst equalsIndex = token.indexOf(\"=\");\n\tif (equalsIndex > 0) {\n\t\tconst inputName = token.slice(0, equalsIndex);\n\t\tconst input = workflow.inputs[inputName];\n\t\tif (input?.kind !== \"boolean\") return null;\n\t\treturn completeWorkflowToken(argumentPrefix, [\n\t\t\t{ value: `${inputName}=true `, label: \"true\", description: inputName },\n\t\t\t{ value: `${inputName}=false `, label: \"false\", description: inputName },\n\t\t]);\n\t}\n\n\treturn completeWorkflowToken(argumentPrefix, [\n\t\t{ value: \"--no-picker \", label: \"--no-picker\", description: \"Skip interactive input picker\" },\n\t\t{ value: \"--help \", label: \"--help\", description: \"Show this workflow's input schema\" },\n\t\t...Object.entries(workflow.inputs).map(([name, input]) => ({\n\t\t\tvalue: `${name}=`,\n\t\t\tlabel: name,\n\t\t\tdescription: input.description,\n\t\t})),\n\t]);\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for ctrl+p cycling\" },\n\t{ name: \"fast\", description: \"Configure Codex fast mode for chat and workflows\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{\n\t\tname: ATOMIC_GUIDE_COMMAND_NAME,\n\t\tdescription: ATOMIC_GUIDE_COMMAND_DESCRIPTION,\n\t\tgetArgumentCompletions: getAtomicGuideArgumentCompletions,\n\t},\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"trust\", description: \"Save project trust decision for future sessions\" },\n\t{ name: \"login\", description: \"Configure provider authentication\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Compact older context with verbatim line ranges\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"exit\", description: `Exit ${APP_NAME}` },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n\nexport const BUNDLED_EXTENSION_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{\n\t\tname: \"workflow\",\n\t\tdescription: \"Run or inspect Atomic workflows. Usage: /workflow <name> [key=value…] | /workflow [list|status|connect|attach|interrupt|quit|pause|resume|inputs|reload] [args]\",\n\t\tgetArgumentCompletions: getBundledWorkflowArgumentCompletions,\n\t},\n\t{ name: \"run\", description: \"Run a subagent directly: /run agent[output=file] [task] [--bg] [--fork]\" },\n\t{ name: \"chain\", description: \"Run agents in sequence: /chain scout task -> planner [--bg] [--fork]\" },\n\t{ name: \"run-chain\", description: \"Run a saved chain: /run-chain chainName -- task [--bg] [--fork]\" },\n\t{ name: \"parallel\", description: \"Run agents in parallel: /parallel scout task1 -> reviewer task2 [--bg] [--fork]\" },\n\t{ name: \"subagents-doctor\", description: \"Show subagent diagnostics\" },\n\t{ name: \"mcp\", description: \"Show MCP server status\" },\n\t{ name: \"mcp-auth\", description: \"Authenticate with an MCP server (OAuth)\" },\n\t{ name: \"curator\", description: \"Toggle or configure the search curator workflow\" },\n\t{ name: \"google-account\", description: \"Show the active Google account for Gemini Web\" },\n\t{ name: \"search\", description: \"Browse stored web search results\" },\n\t{ name: \"websearch\", description: \"Open web search curator\" },\n\t{ name: \"intercom\", description: \"Open session intercom overlay\" },\n];\n"]}
1
+ {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EACN,gCAAgC,EAChC,yBAAyB,EACzB,iCAAiC,GACjC,MAAM,2BAA2B,CAAC;AA+BnC,MAAM,0BAA0B,GAAuB;IACtD,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,mCAAmC,EAAE;IACzF,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,yCAAyC,EAAE;IAC7F,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,2BAA2B,EAAE;IAC3E,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,wDAAwD,EAAE;IAC5G,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,iBAAiB,EAAE;IAC3E,EAAE,KAAK,EAAE,O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AE,kCAAkC,EAAE;IACnE,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,yBAAyB,EAAE;IAC7D,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,+BAA+B,EAAE;CAClE,CAAC","sourcesContent":["import type { AutocompleteItem } from \"@earendil-works/pi-tui\";\nimport { APP_NAME } from \"../config.ts\";\nimport {\n\tATOMIC_GUIDE_COMMAND_DESCRIPTION,\n\tATOMIC_GUIDE_COMMAND_NAME,\n\tgetAtomicGuideArgumentCompletions,\n} from \"./atomic-guide-command.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\tgetArgumentCompletions?: (\n\t\targumentPrefix: string,\n\t) => AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;\n}\n\ntype WorkflowInputCompletionMetadata = {\n\tdescription: string;\n\tkind?: \"boolean\" | \"number\" | \"string\";\n};\n\ntype WorkflowCompletionMetadata = {\n\tname: string;\n\tdescription: string;\n\tinputs: Record<string, WorkflowInputCompletionMetadata>;\n};\n\nconst WORKFLOW_ADMIN_COMPLETIONS: AutocompleteItem[] = [\n\t{ value: \"connect \", label: \"connect\", description: \"Attach to a run (picker if no id)\" },\n\t{ value: \"attach \", label: \"attach\", description: \"Open the in-place attach pane on a node\" },\n\t{ value: \"list \", label: \"list\", description: \"List registered workflows\" },\n\t{ value: \"status \", label: \"status\", description: \"List current-session active and retained terminal runs\" },\n\t{ value: \"interrupt \", label: \"interrupt\", description: \"Interrupt a run\" },\n\t{ value: \"quit \", label: \"quit\", description: \"Quit a run and keep it resumable\" },\n\t{ value: \"pause \", label: \"pause\", description: \"Pause a run or stage\" },\n\t{ value: \"resume \", label: \"resume\", description: \"Re-open overlay for a run\" },\n\t{ value: \"inputs \", label: \"inputs\", description: \"Show a workflow's input schema\" },\n\t{ value: \"reload \", label: \"reload\", description: \"Reload workflow resources\" },\n];\n\nconst BUNDLED_WORKFLOW_COMPLETION_METADATA: WorkflowCompletionMetadata[] = [\n\t{\n\t\tname: \"deep-research-codebase\",\n\t\tdescription: \"Heavy research for tasks requiring comprehensive, whole-repository context.\",\n\t\tinputs: {\n\t\t\tprompt: { description: \"Research question or investigation focus for the codebase.\", kind: \"string\" },\n\t\t\tmax_partitions: { description: \"Maximum number of codebase partitions to explore in parallel.\", kind: \"number\" },\n\t\t\tmax_concurrency: { description: \"Maximum number of workflow stages to run concurrently during deep research.\", kind: \"number\" },\n\t\t},\n\t},\n\t{\n\t\tname: \"goal\",\n\t\tdescription: \"Goal Runner workflow with bounded LM turns, acceptance criteria, ledger artifacts, reviewers, and reducer-gated completion.\",\n\t\tinputs: {\n\t\t\tobjective: { description: \"The objective or delta for this Goal Runner workflow run.\", kind: \"string\" },\n\t\t\tacceptance_criteria: { description: \"Original immutable task contract this run must remain consistent with.\", kind: \"string\" },\n\t\t\tmax_turns: { description: \"Maximum worker/review turns before Goal Runner stops as needs_human.\", kind: \"number\" },\n\t\t\tbase_branch: { description: \"Optional branch reviewers compare the current code delta against.\", kind: \"string\" },\n\t\t\tgit_worktree_dir: { description: \"Optional Git worktree path.\", kind: \"string\" },\n\t\t\tcreate_pr: { description: \"Whether to run the final pull-request creation stage after approval.\", kind: \"boolean\" },\n\t\t},\n\t},\n\t{\n\t\tname: \"open-claude-design\",\n\t\tdescription: \"AI-powered design workflow: discovery, reference research, HTML generation, refinement, and handoff.\",\n\t\tinputs: {\n\t\t\tprompt: { description: \"What to design, such as a dashboard, page, component, or prototype.\", kind: \"string\" },\n\t\t\tdiscover_references: { description: \"Discover current reference designs and feed them to generation.\", kind: \"boolean\" },\n\t\t\tmax_refinements: { description: \"Maximum generate/user-feedback loop iterations.\", kind: \"number\" },\n\t\t},\n\t},\n\t{\n\t\tname: \"ralph\",\n\t\tdescription: \"Raw prompt → research → orchestrate → multi-model parallel review loop with bounded iteration.\",\n\t\tinputs: {\n\t\t\tprompt: { description: \"The task or goal to research, execute, and refine.\", kind: \"string\" },\n\t\t\tacceptance_criteria: { description: \"Original immutable task contract this run must remain consistent with.\", kind: \"string\" },\n\t\t\tmax_loops: { description: \"Maximum research/orchestrate/review iterations.\", kind: \"number\" },\n\t\t\tbase_branch: { description: \"Branch reviewers compare the current code delta against.\", kind: \"string\" },\n\t\t\tgit_worktree_dir: { description: \"Optional Git worktree path.\", kind: \"string\" },\n\t\t\tcreate_pr: { description: \"Whether to run the final pull-request creation stage.\", kind: \"boolean\" },\n\t\t},\n\t},\n];\n\nfunction completeWorkflowToken(argumentText: string, candidates: AutocompleteItem[]): AutocompleteItem[] | null {\n\tconst tokenStart = /\\s$/.test(argumentText)\n\t\t? argumentText.length\n\t\t: Math.max(argumentText.lastIndexOf(\" \"), argumentText.lastIndexOf(\"\\t\")) + 1;\n\tconst head = argumentText.slice(0, tokenStart);\n\tconst token = argumentText.slice(tokenStart);\n\tconst normalizedToken = token.trimEnd();\n\tconst filtered = candidates\n\t\t.filter((candidate) => candidate.value.startsWith(token) && candidate.value.trimEnd() !== normalizedToken)\n\t\t.map((candidate) => ({ ...candidate, value: `${head}${candidate.value}` }));\n\treturn filtered.length > 0 ? filtered : null;\n}\n\nfunction bundledWorkflowNameItems(): AutocompleteItem[] {\n\treturn BUNDLED_WORKFLOW_COMPLETION_METADATA.map((workflow) => ({\n\t\tvalue: `${workflow.name} `,\n\t\tlabel: workflow.name,\n\t\tdescription: `Run workflow: ${workflow.name}`,\n\t}));\n}\n\nexport function getBundledWorkflowArgumentCompletions(argumentPrefix: string): AutocompleteItem[] | null {\n\tconst parts = argumentPrefix.trim().split(/\\s+/).filter(Boolean);\n\tconst subcommand = parts[0] ?? \"\";\n\tconst workflowItems = bundledWorkflowNameItems();\n\tif (!argumentPrefix.includes(\" \")) {\n\t\treturn completeWorkflowToken(argumentPrefix, [...WORKFLOW_ADMIN_COMPLETIONS, ...workflowItems]);\n\t}\n\tif (subcommand === \"inputs\") return completeWorkflowToken(argumentPrefix, workflowItems);\n\tif (subcommand === \"interrupt\") {\n\t\treturn completeWorkflowToken(argumentPrefix, [\n\t\t\t{ value: \"--all \", label: \"--all\", description: \"Interrupt all in-flight runs\" },\n\t\t\t{ value: \"--yes \", label: \"--yes\", description: \"Skip confirmation\" },\n\t\t\t{ value: \"-y \", label: \"-y\", description: \"Skip confirmation\" },\n\t\t]);\n\t}\n\tif (subcommand === \"quit\") {\n\t\treturn completeWorkflowToken(argumentPrefix, [\n\t\t\t{ value: \"--all \", label: \"--all\", description: \"Quit and keep all in-flight runs resumable\" },\n\t\t]);\n\t}\n\tif (!subcommand) return completeWorkflowToken(argumentPrefix, [...WORKFLOW_ADMIN_COMPLETIONS, ...workflowItems]);\n\n\tconst workflow = BUNDLED_WORKFLOW_COMPLETION_METADATA.find((candidate) => candidate.name === subcommand);\n\tif (!workflow) return null;\n\tconst tokenStart = /\\s$/.test(argumentPrefix)\n\t\t? argumentPrefix.length\n\t\t: Math.max(argumentPrefix.lastIndexOf(\" \"), argumentPrefix.lastIndexOf(\"\\t\")) + 1;\n\tconst token = argumentPrefix.slice(tokenStart);\n\tconst equalsIndex = token.indexOf(\"=\");\n\tif (equalsIndex > 0) {\n\t\tconst inputName = token.slice(0, equalsIndex);\n\t\tconst input = workflow.inputs[inputName];\n\t\tif (input?.kind !== \"boolean\") return null;\n\t\treturn completeWorkflowToken(argumentPrefix, [\n\t\t\t{ value: `${inputName}=true `, label: \"true\", description: inputName },\n\t\t\t{ value: `${inputName}=false `, label: \"false\", description: inputName },\n\t\t]);\n\t}\n\n\treturn completeWorkflowToken(argumentPrefix, [\n\t\t{ value: \"--no-picker \", label: \"--no-picker\", description: \"Skip interactive input picker\" },\n\t\t{ value: \"--help \", label: \"--help\", description: \"Show this workflow's input schema\" },\n\t\t...Object.entries(workflow.inputs).map(([name, input]) => ({\n\t\t\tvalue: `${name}=`,\n\t\t\tlabel: name,\n\t\t\tdescription: input.description,\n\t\t})),\n\t]);\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for ctrl+p cycling\" },\n\t{ name: \"fast\", description: \"Configure Codex fast mode for chat and workflows\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{\n\t\tname: ATOMIC_GUIDE_COMMAND_NAME,\n\t\tdescription: ATOMIC_GUIDE_COMMAND_DESCRIPTION,\n\t\tgetArgumentCompletions: getAtomicGuideArgumentCompletions,\n\t},\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"trust\", description: \"Save project trust decision for future sessions\" },\n\t{ name: \"login\", description: \"Configure provider authentication\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Compact older context with verbatim line ranges\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"exit\", description: `Exit ${APP_NAME}` },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n\nexport const BUNDLED_EXTENSION_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{\n\t\tname: \"workflow\",\n\t\tdescription: \"Run or inspect Atomic workflows. Usage: /workflow <name> [key=value…] | /workflow [list|status|connect|attach|interrupt|quit|pause|resume|inputs|reload] [args]\",\n\t\tgetArgumentCompletions: getBundledWorkflowArgumentCompletions,\n\t},\n\t{ name: \"run\", description: \"Run a subagent directly: /run agent[output=file] [task] [--bg] [--fork]\" },\n\t{ name: \"chain\", description: \"Run agents in sequence: /chain scout task -> planner [--bg] [--fork]\" },\n\t{ name: \"run-chain\", description: \"Run a saved chain: /run-chain chainName -- task [--bg] [--fork]\" },\n\t{ name: \"parallel\", description: \"Run agents in parallel: /parallel scout task1 -> reviewer task2 [--bg] [--fork]\" },\n\t{ name: \"subagents-doctor\", description: \"Show subagent diagnostics\" },\n\t{ name: \"mcp\", description: \"Show MCP server status\" },\n\t{ name: \"mcp-auth\", description: \"Authenticate with an MCP server (OAuth)\" },\n\t{ name: \"curator\", description: \"Toggle or configure the search curator workflow\" },\n\t{ name: \"google-account\", description: \"Show the active Google account for Gemini Web\" },\n\t{ name: \"search\", description: \"Browse stored web search results\" },\n\t{ name: \"websearch\", description: \"Open web search curator\" },\n\t{ name: \"intercom\", description: \"Open session intercom overlay\" },\n];\n"]}
@@ -1,2 +1,3 @@
1
- export {};
1
+ import type { AuthStatus } from "../../core/auth-storage.ts";
2
+ export declare function formatLogoutStatus(providerName: string, authType: "oauth" | "api_key", authStatus: AuthStatus): string;
2
3
  //# sourceMappingURL=interactive-auth-routing.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"interactive-auth-routing.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-auth-routing.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"interactive-auth-routing.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-auth-routing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAK7D,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,MAAM,EACpB,QAAQ,EAAE,OAAO,GAAG,SAAS,EAC7B,UAAU,EAAE,UAAU,GACrB,MAAM,CAOR"}
@@ -1,6 +1,14 @@
1
1
  import { InteractiveModeBase } from "./interactive-mode-base.js";
2
2
  import { ExtensionSelectorComponent, OAuthSelectorComponent } from "./interactive-mode-deps.js";
3
3
  import { BEDROCK_PROVIDER_ID, isApiKeyLoginProvider } from "./interactive-mode-helpers.js";
4
+ export function formatLogoutStatus(providerName, authType, authStatus) {
5
+ const action = authType === "oauth"
6
+ ? `Logged out of ${providerName}`
7
+ : `Removed stored API key for ${providerName}`;
8
+ return authStatus.source
9
+ ? `${action}. Authentication remains active through ${authStatus.label ?? authStatus.source}.`
10
+ : action;
11
+ }
4
12
  InteractiveModeBase.prototype.getLoginProviderOptions = function (authType) {
5
13
  const authStorage = this.session.modelRegistry.authStorage;
6
14
  const oauthProviders = authStorage.getOAuthProviders();
@@ -106,13 +114,10 @@ InteractiveModeBase.prototype.showOAuthSelector = async function (mode) {
106
114
  return;
107
115
  }
108
116
  try {
109
- await this.session.modelRegistry.authStorage.logoutAsync(providerOption.id);
110
- await this.session.modelRegistry.refresh();
117
+ const result = await this.runtimeHost.logoutProvider(providerOption.id);
111
118
  await this.updateAvailableProviderCount();
112
119
  this.setupAutocompleteProvider();
113
- const message = providerOption.authType === "oauth"
114
- ? `Logged out of ${providerOption.name}`
115
- : `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;
120
+ const message = formatLogoutStatus(providerOption.name, providerOption.authType, result.authStatus);
116
121
  this.showStatus(message);
117
122
  }
118
123
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"interactive-auth-routing.js","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-auth-routing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAA6B,0BAA0B,EAA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teractiveModeBase } from \"./interactive-mode-base.ts\";\nimport { type AuthSelectorProvider, ExtensionSelectorComponent, OAuthSelectorComponent } from \"./interactive-mode-deps.ts\";\nimport { BEDROCK_PROVIDER_ID, isApiKeyLoginProvider } from \"./interactive-mode-helpers.ts\";\n\nInteractiveModeBase.prototype.getLoginProviderOptions = function(this: InteractiveModeBase, authType?: \"oauth\" | \"api_key\"): AuthSelectorProvider[] {\n const authStorage = this.session.modelRegistry.authStorage;\n const oauthProviders = authStorage.getOAuthProviders();\n const oauthProviderIds = new Set(\n oauthProviders.map((provider) => provider.id),\n );\n const options: AuthSelectorProvider[] = oauthProviders.map((provider) => ({\n id: provider.id,\n name: provider.loginLabel ?? provider.name,\n authType: \"oauth\",\n }));\n\n const modelProviders = new Set(\n this.session.modelRegistry.getAll().map((model) => model.provider),\n );\n for (const providerId of modelProviders) {\n if (!isApiKeyLoginProvider(providerId, oauthProviderIds)) {\n continue;\n }\n options.push({\n id: providerId,\n name: this.session.modelRegistry.getProviderDisplayName(providerId),\n authType: \"api_key\",\n });\n }\n\n const filteredOptions = authType\n ? options.filter((option) => option.authType === authType)\n : options;\n return filteredOptions.sort((a, b) => a.name.localeCompare(b.name));\n };\n\nInteractiveModeBase.prototype.getLogoutProviderOptions = function(this: InteractiveModeBase): AuthSelectorProvider[] {\n const authStorage = this.session.modelRegistry.authStorage;\n const options: AuthSelectorProvider[] = [];\n\n for (const providerId of authStorage.list()) {\n const credential = authStorage.get(providerId);\n if (!credential) {\n continue;\n }\n options.push({\n id: providerId,\n name: this.session.modelRegistry.getProviderDisplayName(providerId),\n authType: credential.type,\n });\n }\n\n return options.sort((a, b) => a.name.localeCompare(b.name));\n };\n\nInteractiveModeBase.prototype.showLoginAuthTypeSelector = function(this: InteractiveModeBase): void {\n const subscriptionLabel = \"Use a subscription\";\n const apiKeyLabel = \"Use an API key\";\n this.showSelector((done) => {\n const selector = new ExtensionSelectorComponent(\n \"Select authentication method:\",\n [subscriptionLabel, apiKeyLabel],\n (option) => {\n done();\n const authType = option === subscriptionLabel ? \"oauth\" : \"api_key\";\n this.showLoginProviderSelector(authType);\n },\n () => {\n done();\n this.ui.requestRender();\n },\n );\n return { component: selector, focus: selector };\n });\n };\n\nInteractiveModeBase.prototype.showLoginProviderSelector = function(this: InteractiveModeBase, authType: \"oauth\" | \"api_key\"): void {\n const providerOptions = this.getLoginProviderOptions(authType);\n if (providerOptions.length === 0) {\n this.showStatus(\n authType === \"oauth\"\n ? \"No subscription providers available.\"\n : \"No API key providers available.\",\n );\n return;\n }\n\n this.showSelector((done) => {\n const selector = new OAuthSelectorComponent(\n \"login\",\n this.session.modelRegistry.authStorage,\n providerOptions,\n async (providerId: string) => {\n done();\n\n const providerOption = providerOptions.find(\n (provider) => provider.id === providerId,\n );\n if (!providerOption) {\n return;\n }\n\n if (providerOption.authType === \"oauth\") {\n await this.showLoginDialog(providerOption.id, providerOption.name);\n } else if (providerOption.id === BEDROCK_PROVIDER_ID) {\n this.showBedrockSetupDialog(providerOption.id, providerOption.name);\n } else {\n await this.showApiKeyLoginDialog(\n providerOption.id,\n providerOption.name,\n );\n }\n },\n () => {\n done();\n this.showLoginAuthTypeSelector();\n },\n (providerId) =>\n this.session.modelRegistry.getProviderAuthStatus(providerId),\n );\n return { component: selector, focus: selector };\n });\n };\n\nInteractiveModeBase.prototype.showOAuthSelector = async function(this: InteractiveModeBase, mode: \"login\" | \"logout\"): Promise<void> {\n if (mode === \"login\") {\n this.showLoginAuthTypeSelector();\n return;\n }\n\n const providerOptions = this.getLogoutProviderOptions();\n if (providerOptions.length === 0) {\n this.showStatus(\n \"No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.\",\n );\n return;\n }\n\n this.showSelector((done) => {\n const selector = new OAuthSelectorComponent(\n mode,\n this.session.modelRegistry.authStorage,\n providerOptions,\n async (providerId: string) => {\n done();\n\n const providerOption = providerOptions.find(\n (provider) => provider.id === providerId,\n );\n if (!providerOption) {\n return;\n }\n\n try {\n await this.session.modelRegistry.authStorage.logoutAsync(providerOption.id);\n await this.session.modelRegistry.refresh();\n await this.updateAvailableProviderCount();\n this.setupAutocompleteProvider();\n const message =\n providerOption.authType === \"oauth\"\n ? `Logged out of ${providerOption.name}`\n : `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;\n this.showStatus(message);\n } catch (error: unknown) {\n this.showError(\n `Logout failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n () => {\n done();\n this.ui.requestRender();\n },\n );\n return { component: selector, focus: selector };\n });\n };\n"]}
1
+ {"version":3,"file":"interactive-auth-routing.js","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-auth-routing.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAA6B,0BAA0B,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAC3H,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAE3F,MAAM,UAAU,kBAAkB,CAChC,YAAoB,EACpB,QAA6B,EAC7B,UAAsB;IAEtB,MAAM,MAAM,GAAG,QAAQ,KAAK,OAAO;QACjC,CAAC,CAAC,iBAAiB,YAAY,EAAE;QACjC,CAAC,CAAC,8BAA8B,YAAY,EAAE,CAAC;IACjD,OAAO,UAAU,CAAC,MAAM;QACtB,CAAC,CAAC,GAAG,MAAM,2CAA2C,UAAU,CAAC,KAAK,IAAI,UAAU,CAAC,MAAM,GAAG;QAC9F,CAAC,CAAC,MAAM,CAAC;AACb,CAAC;AAED,mBAAmB,CAAC,SAAS,CAAC,uBAAuB,GAAG,UAAoC,QAA8B;IACtH,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,WAAW,CAAC;IAC3D,MAAM,cAAc,GAAG,WAAW,CAAC,iBAAiB,EAAE,CAAC;IACvD,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAC9B,cAAc,CAAC,GAAG,C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cAAc,CAAC,EAAE,CAAC,CAAC;gBACxE,MAAM,IAAI,CAAC,4BAA4B,EAAE,CAAC;gBAC1C,IAAI,CAAC,yBAAyB,EAAE,CAAC;gBACjC,MAAM,OAAO,GAAG,kBAAkB,CAChC,cAAc,CAAC,IAAI,EACnB,cAAc,CAAC,QAAQ,EACvB,MAAM,CAAC,UAAU,CAClB,CAAC;gBACF,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;YAC3B,CAAC;YAAC,OAAO,KAAc,EAAE,CAAC;gBACxB,IAAI,CAAC,SAAS,CACZ,kBAAkB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAC3E,CAAC;YACJ,CAAC;QACH,CAAC,EACD,GAAG,EAAE;YACH,IAAI,EAAE,CAAC;YACP,IAAI,CAAC,EAAE,CAAC,aAAa,EAAE,CAAC;QAC1B,CAAC,CACF,CAAC;QACF,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC","sourcesContent":["import type { AuthStatus } from \"../../core/auth-storage.ts\";\nimport { InteractiveModeBase } from \"./interactive-mode-base.ts\";\nimport { type AuthSelectorProvider, ExtensionSelectorComponent, OAuthSelectorComponent } from \"./interactive-mode-deps.ts\";\nimport { BEDROCK_PROVIDER_ID, isApiKeyLoginProvider } from \"./interactive-mode-helpers.ts\";\n\nexport function formatLogoutStatus(\n providerName: string,\n authType: \"oauth\" | \"api_key\",\n authStatus: AuthStatus,\n): string {\n const action = authType === \"oauth\"\n ? `Logged out of ${providerName}`\n : `Removed stored API key for ${providerName}`;\n return authStatus.source\n ? `${action}. Authentication remains active through ${authStatus.label ?? authStatus.source}.`\n : action;\n}\n\nInteractiveModeBase.prototype.getLoginProviderOptions = function(this: InteractiveModeBase, authType?: \"oauth\" | \"api_key\"): AuthSelectorProvider[] {\n const authStorage = this.session.modelRegistry.authStorage;\n const oauthProviders = authStorage.getOAuthProviders();\n const oauthProviderIds = new Set(\n oauthProviders.map((provider) => provider.id),\n );\n const options: AuthSelectorProvider[] = oauthProviders.map((provider) => ({\n id: provider.id,\n name: provider.loginLabel ?? provider.name,\n authType: \"oauth\",\n }));\n\n const modelProviders = new Set(\n this.session.modelRegistry.getAll().map((model) => model.provider),\n );\n for (const providerId of modelProviders) {\n if (!isApiKeyLoginProvider(providerId, oauthProviderIds)) {\n continue;\n }\n options.push({\n id: providerId,\n name: this.session.modelRegistry.getProviderDisplayName(providerId),\n authType: \"api_key\",\n });\n }\n\n const filteredOptions = authType\n ? options.filter((option) => option.authType === authType)\n : options;\n return filteredOptions.sort((a, b) => a.name.localeCompare(b.name));\n };\n\nInteractiveModeBase.prototype.getLogoutProviderOptions = function(this: InteractiveModeBase): AuthSelectorProvider[] {\n const authStorage = this.session.modelRegistry.authStorage;\n const options: AuthSelectorProvider[] = [];\n\n for (const providerId of authStorage.list()) {\n const credential = authStorage.get(providerId);\n if (!credential) {\n continue;\n }\n options.push({\n id: providerId,\n name: this.session.modelRegistry.getProviderDisplayName(providerId),\n authType: credential.type,\n });\n }\n\n return options.sort((a, b) => a.name.localeCompare(b.name));\n };\n\nInteractiveModeBase.prototype.showLoginAuthTypeSelector = function(this: InteractiveModeBase): void {\n const subscriptionLabel = \"Use a subscription\";\n const apiKeyLabel = \"Use an API key\";\n this.showSelector((done) => {\n const selector = new ExtensionSelectorComponent(\n \"Select authentication method:\",\n [subscriptionLabel, apiKeyLabel],\n (option) => {\n done();\n const authType = option === subscriptionLabel ? \"oauth\" : \"api_key\";\n this.showLoginProviderSelector(authType);\n },\n () => {\n done();\n this.ui.requestRender();\n },\n );\n return { component: selector, focus: selector };\n });\n };\n\nInteractiveModeBase.prototype.showLoginProviderSelector = function(this: InteractiveModeBase, authType: \"oauth\" | \"api_key\"): void {\n const providerOptions = this.getLoginProviderOptions(authType);\n if (providerOptions.length === 0) {\n this.showStatus(\n authType === \"oauth\"\n ? \"No subscription providers available.\"\n : \"No API key providers available.\",\n );\n return;\n }\n\n this.showSelector((done) => {\n const selector = new OAuthSelectorComponent(\n \"login\",\n this.session.modelRegistry.authStorage,\n providerOptions,\n async (providerId: string) => {\n done();\n\n const providerOption = providerOptions.find(\n (provider) => provider.id === providerId,\n );\n if (!providerOption) {\n return;\n }\n\n if (providerOption.authType === \"oauth\") {\n await this.showLoginDialog(providerOption.id, providerOption.name);\n } else if (providerOption.id === BEDROCK_PROVIDER_ID) {\n this.showBedrockSetupDialog(providerOption.id, providerOption.name);\n } else {\n await this.showApiKeyLoginDialog(\n providerOption.id,\n providerOption.name,\n );\n }\n },\n () => {\n done();\n this.showLoginAuthTypeSelector();\n },\n (providerId) =>\n this.session.modelRegistry.getProviderAuthStatus(providerId),\n );\n return { component: selector, focus: selector };\n });\n };\n\nInteractiveModeBase.prototype.showOAuthSelector = async function(this: InteractiveModeBase, mode: \"login\" | \"logout\"): Promise<void> {\n if (mode === \"login\") {\n this.showLoginAuthTypeSelector();\n return;\n }\n\n const providerOptions = this.getLogoutProviderOptions();\n if (providerOptions.length === 0) {\n this.showStatus(\n \"No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.\",\n );\n return;\n }\n\n this.showSelector((done) => {\n const selector = new OAuthSelectorComponent(\n mode,\n this.session.modelRegistry.authStorage,\n providerOptions,\n async (providerId: string) => {\n done();\n\n const providerOption = providerOptions.find(\n (provider) => provider.id === providerId,\n );\n if (!providerOption) {\n return;\n }\n\n try {\n const result = await this.runtimeHost.logoutProvider(providerOption.id);\n await this.updateAvailableProviderCount();\n this.setupAutocompleteProvider();\n const message = formatLogoutStatus(\n providerOption.name,\n providerOption.authType,\n result.authStatus,\n );\n this.showStatus(message);\n } catch (error: unknown) {\n this.showError(\n `Logout failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n () => {\n done();\n this.ui.requestRender();\n },\n );\n return { component: selector, focus: selector };\n });\n };\n"]}