@causyne/agent 1.20.120 → 1.20.121

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 (59) hide show
  1. package/package.json +1 -1
  2. package/src/agent/errorClassifier.js +113 -0
  3. package/src/agent/errorClassifier.ts +161 -0
  4. package/src/agent/promptIntent.js +200 -0
  5. package/src/agent/promptIntent.ts +203 -0
  6. package/src/agent/toolArgValidator.js +97 -0
  7. package/src/agent/toolArgValidator.ts +112 -0
  8. package/src/agentLoop.js +22 -339
  9. package/src/agentLoop.ts +40 -347
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/cliMode.js +16 -2
  13. package/src/commands.js +10 -9
  14. package/src/config.js +42 -63
  15. package/src/configVault.js +204 -0
  16. package/src/configVault.ts +213 -0
  17. package/src/core/contextCompactor.js +70 -11
  18. package/src/core/contextCompactor.ts +83 -11
  19. package/src/dynamicCatalogue.js +42 -73
  20. package/src/dynamicCatalogue.ts +74 -60
  21. package/src/entrypoint.js +77 -4
  22. package/src/headlessCli.js +304 -0
  23. package/src/headlessCli.ts +380 -0
  24. package/src/mcp/mcpClient.js +38 -11
  25. package/src/mcp/mcpClient.ts +44 -11
  26. package/src/mcp/mcpRegistry.js +2 -5
  27. package/src/mcp/mcpRegistry.ts +2 -5
  28. package/src/mcp/mcpSecurity.js +189 -0
  29. package/src/mcp/mcpSecurity.ts +190 -0
  30. package/src/osKeychain.js +209 -0
  31. package/src/osKeychain.ts +245 -0
  32. package/src/providers/anthropic.js +28 -11
  33. package/src/providers/byokHttp.js +354 -0
  34. package/src/providers/byokHttp.ts +454 -0
  35. package/src/providers/byokStream.js +657 -0
  36. package/src/providers/byokStream.ts +759 -0
  37. package/src/providers/dashscope-byok.js +34 -25
  38. package/src/providers/deepseek.js +31 -22
  39. package/src/providers/gemini.js +40 -13
  40. package/src/providers/moonshot.js +31 -22
  41. package/src/providers/muse.js +10 -10
  42. package/src/providers/ollama.js +25 -10
  43. package/src/providers/openai-compatible.js +46 -14
  44. package/src/providers/openrouter.js +63 -29
  45. package/src/providers/openrouter.ts +73 -29
  46. package/src/providers/qwen-byok.js +33 -16
  47. package/src/providers/xai.js +31 -22
  48. package/src/sandbox.js +77 -56
  49. package/src/sandboxPolicy.js +1208 -0
  50. package/src/sandboxPolicy.ts +1300 -0
  51. package/src/sessionJournal.js +47 -0
  52. package/src/sessionJournal.ts +49 -0
  53. package/src/tools/osSandbox.js +473 -0
  54. package/src/tools/osSandbox.ts +554 -0
  55. package/src/tools/persistentShell.js +8 -3
  56. package/src/tools/subprocessEnv.js +197 -0
  57. package/src/tools/subprocessEnv.ts +212 -0
  58. package/src/tools/sysRun.js +39 -6
  59. package/src/tools/sysRun.ts +53 -7
package/src/autoUpdate.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  // passed as argv arrays with shell disabled, and the only accepted package is
6
6
  // the public @causyne/agent package from the npm registry.
7
7
 
8
+ import crypto from 'node:crypto';
8
9
  import fs from 'node:fs';
9
10
  import path from 'node:path';
10
11
  import { fileURLToPath } from 'node:url';
@@ -13,6 +14,8 @@ import { spawnSync, type SpawnSyncReturns } from 'node:child_process';
13
14
  import { UI } from './utils/cli_ui.js';
14
15
  import { causyneHome } from './utils/paths.js';
15
16
  import { getPackageVersion } from './version.js';
17
+ import { probeOsSandbox, resolveOsSandboxMode } from './tools/osSandbox.js';
18
+ import { probeOsKeychain, resolveKeychainMode } from './osKeychain.js';
16
19
 
17
20
  const PACKAGE_NAME = '@causyne/agent';
18
21
  const REGISTRY_LATEST = 'https://registry.npmjs.org/@causyne%2fagent/latest';
@@ -46,6 +49,15 @@ export interface CheckUpdateOptions {
46
49
  timeoutMs?: number;
47
50
  signal?: AbortSignal;
48
51
  env?: NodeJS.ProcessEnv;
52
+ requireProvenance?: boolean;
53
+ }
54
+
55
+ export interface VerifiedReleaseMetadata {
56
+ version: string;
57
+ tarballUrl?: string | undefined;
58
+ integrity?: string | undefined;
59
+ provenanceVerified: boolean;
60
+ attestationUrl?: string | undefined;
49
61
  }
50
62
 
51
63
  export interface SelfUpdateOptions extends CheckUpdateOptions {
@@ -61,6 +73,8 @@ export interface CheckResult {
61
73
  current: string;
62
74
  latest: string;
63
75
  available: boolean;
76
+ provenanceVerified?: boolean | undefined;
77
+ integrity?: string | undefined;
64
78
  }
65
79
 
66
80
  export interface UpdateResult extends InstallationInfo {
@@ -76,6 +90,8 @@ export interface DiagnosisResult extends InstallationInfo {
76
90
  current?: string | undefined;
77
91
  latest?: string | null | undefined;
78
92
  available?: boolean | undefined;
93
+ provenanceVerified?: boolean | undefined;
94
+ integrity?: string | undefined;
79
95
  autoUpdates: boolean;
80
96
  error?: string | undefined;
81
97
  }
@@ -202,21 +218,128 @@ function writeState(state: UpdateState, options: { stateFile?: string; env?: Nod
202
218
  }
203
219
  }
204
220
 
205
- export async function latestPackageVersion(options: CheckUpdateOptions = {}): Promise<string> {
221
+ const SRI_PATTERN = /^(sha512|sha384|sha256)-([A-Za-z0-9+/]+={0,2})$/;
222
+
223
+ function isOfficialRegistryHttpsUrl(rawUrl: unknown): rawUrl is string {
224
+ if (typeof rawUrl !== 'string' || !rawUrl.trim()) return false;
225
+ try {
226
+ const parsed = new URL(rawUrl.trim());
227
+ return parsed.protocol === 'https:' && parsed.hostname === 'registry.npmjs.org';
228
+ } catch {
229
+ return false;
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Verifies constant-time SRI integrity (`sha512-...`, `sha384-...`, or `sha256-...`)
235
+ * of a downloaded tarball buffer against the registry-declared integrity string.
236
+ */
237
+ export function verifyTarballIntegrity(data: Buffer, expectedIntegrity: string): boolean {
238
+ if (!Buffer.isBuffer(data) || typeof expectedIntegrity !== 'string') return false;
239
+ const match = expectedIntegrity.trim().match(SRI_PATTERN);
240
+ if (!match) return false;
241
+ const algorithm = match[1]!;
242
+ const expectedDigest = Buffer.from(match[2]!, 'base64');
243
+ const actualDigest = crypto.createHash(algorithm).update(data).digest();
244
+ if (expectedDigest.length !== actualDigest.length) return false;
245
+ return crypto.timingSafeEqual(expectedDigest, actualDigest);
246
+ }
247
+
248
+ /**
249
+ * Validates npm registry metadata for `@causyne/agent`, enforcing official HTTPS
250
+ * tarball origin, valid SRI integrity format, and optional Sigstore provenance
251
+ * attestation checks (`requireProvenance` or `CAUSYNE_REQUIRE_PROVENANCE=1`).
252
+ */
253
+ export function verifyRegistryMetadataIntegrity(
254
+ metadata: unknown,
255
+ options: { requireProvenance?: boolean | undefined } = {}
256
+ ): VerifiedReleaseMetadata {
257
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {
258
+ throw new Error('npm registry returned invalid package metadata');
259
+ }
260
+ const record = metadata as {
261
+ name?: unknown;
262
+ version?: unknown;
263
+ dist?: {
264
+ tarball?: unknown;
265
+ integrity?: unknown;
266
+ attestations?: {
267
+ url?: unknown;
268
+ provenance?: { predicateType?: unknown };
269
+ };
270
+ };
271
+ };
272
+
273
+ if (record.name !== PACKAGE_NAME || typeof record.version !== 'string' || !versionParts(record.version)) {
274
+ throw new Error('npm registry returned invalid package metadata');
275
+ }
276
+
277
+ let tarballUrl: string | undefined;
278
+ let integrity: string | undefined;
279
+ let attestationUrl: string | undefined;
280
+ let provenanceVerified = false;
281
+
282
+ if (record.dist !== undefined) {
283
+ if (!record.dist || typeof record.dist !== 'object' || Array.isArray(record.dist)) {
284
+ throw new Error('npm registry returned malformed dist metadata');
285
+ }
286
+ if (record.dist.tarball !== undefined) {
287
+ if (!isOfficialRegistryHttpsUrl(record.dist.tarball)) {
288
+ throw new Error('npm registry tarball URL must use HTTPS on registry.npmjs.org');
289
+ }
290
+ tarballUrl = record.dist.tarball;
291
+ }
292
+ if (record.dist.integrity !== undefined) {
293
+ if (typeof record.dist.integrity !== 'string' || !SRI_PATTERN.test(record.dist.integrity.trim())) {
294
+ throw new Error('npm registry returned malformed SRI integrity digest');
295
+ }
296
+ integrity = record.dist.integrity.trim();
297
+ }
298
+ if (record.dist.attestations && typeof record.dist.attestations === 'object') {
299
+ const attUrl = record.dist.attestations.url;
300
+ const predicateType = record.dist.attestations.provenance?.predicateType;
301
+ if (isOfficialRegistryHttpsUrl(attUrl) && typeof predicateType === 'string' && predicateType.length > 0) {
302
+ attestationUrl = attUrl;
303
+ provenanceVerified = true;
304
+ }
305
+ }
306
+ }
307
+
308
+ if (options.requireProvenance && !provenanceVerified) {
309
+ throw new Error(`Release ${PACKAGE_NAME}@${record.version} lacks verified npm provenance attestations.`);
310
+ }
311
+
312
+ return {
313
+ version: record.version,
314
+ ...(tarballUrl ? { tarballUrl } : {}),
315
+ ...(integrity ? { integrity } : {}),
316
+ provenanceVerified,
317
+ ...(attestationUrl ? { attestationUrl } : {})
318
+ };
319
+ }
320
+
321
+ export async function latestPackageRelease(options: CheckUpdateOptions = {}): Promise<VerifiedReleaseMetadata> {
206
322
  const fetchImpl = options.fetchImpl || globalThis.fetch;
207
323
  if (typeof fetchImpl !== 'function') throw new Error('This Node.js runtime has no fetch implementation.');
208
324
  const timeoutMs = options.timeoutMs || 3500;
209
325
  const signal = options.signal || AbortSignal.timeout(timeoutMs);
326
+ const env = options.env || process.env;
327
+ const requireProvenance = options.requireProvenance
328
+ ?? (env.CAUSYNE_REQUIRE_PROVENANCE === '1' || env.CAUSYNE_REQUIRE_PROVENANCE === 'true');
329
+
210
330
  const response = await fetchImpl(REGISTRY_LATEST, {
211
331
  headers: { accept: 'application/json', 'user-agent': `causyne/${getPackageVersion()}` },
332
+ redirect: 'error',
212
333
  signal
213
334
  });
214
335
  if (!response.ok) throw new Error(`npm registry returned HTTP ${response.status}`);
215
- const metadata = (await response.json()) as { name?: string; version?: string };
216
- if (metadata.name !== PACKAGE_NAME || !versionParts(metadata.version)) {
217
- throw new Error('npm registry returned invalid package metadata');
218
- }
219
- return metadata.version as string;
336
+ const metadata: unknown = await response.json();
337
+ return verifyRegistryMetadataIntegrity(metadata, { requireProvenance });
338
+ }
339
+
340
+ export async function latestPackageVersion(options: CheckUpdateOptions = {}): Promise<string> {
341
+ const release = await latestPackageRelease(options);
342
+ return release.version;
220
343
  }
221
344
 
222
345
  function installLatest(info: InstallationInfo, options: SelfUpdateOptions = {}): void {
@@ -260,8 +383,14 @@ function installLatest(info: InstallationInfo, options: SelfUpdateOptions = {}):
260
383
 
261
384
  export async function checkForUpdate(options: CheckUpdateOptions = {}): Promise<CheckResult> {
262
385
  const current = options.currentVersion || getPackageVersion();
263
- const latest = await latestPackageVersion(options);
264
- return { current, latest, available: compareVersions(latest, current) > 0 };
386
+ const release = await latestPackageRelease(options);
387
+ return {
388
+ current,
389
+ latest: release.version,
390
+ available: compareVersions(release.version, current) > 0,
391
+ provenanceVerified: release.provenanceVerified,
392
+ ...(release.integrity ? { integrity: release.integrity } : {})
393
+ };
265
394
  }
266
395
 
267
396
  export async function runSelfUpdate(verbose: boolean = false, options: SelfUpdateOptions = {}): Promise<UpdateResult> {
@@ -344,14 +473,21 @@ export async function diagnoseInstallation(options: CheckUpdateOptions = {}): Pr
344
473
  }
345
474
 
346
475
  export function formatDoctorReport(status: DiagnosisResult, runtime: typeof process = process): string {
476
+ const sandboxCap = probeOsSandbox();
477
+ const sandboxMode = resolveOsSandboxMode(runtime.env);
478
+ const keychainCap = probeOsKeychain({ env: runtime.env });
479
+ const keychainMode = resolveKeychainMode(runtime.env);
347
480
  const rows = [
348
481
  `Version : ${status.current || 'unknown'}`,
349
482
  `Latest : ${status.latest || `unavailable (${status.error || 'unknown error'})`}`,
483
+ `Provenance : ${status.provenanceVerified ? 'verified (npm Sigstore attestation)' : 'unverified / not reported'}`,
350
484
  `Installation : ${status.type}`,
351
485
  `Package root : ${status.packageRoot}`,
352
486
  `NPM command : ${status.npmCommand}`,
353
487
  `Node.js : ${runtime.version}`,
354
488
  `Platform : ${runtime.platform} ${runtime.arch}`,
489
+ `OS Sandbox : ${sandboxMode.mode} (backend: ${sandboxCap.backend}${sandboxCap.available ? ', available' : ', unavailable'})`,
490
+ `OS Keychain : ${keychainMode} (backend: ${keychainCap.backend}${keychainCap.available ? ', available' : ', unavailable'})`,
355
491
  `Auto updates : ${status.autoUpdates ? 'enabled' : 'disabled'}`,
356
492
  `Workspace : ${runtime.cwd()}`
357
493
  ];
package/src/cliMode.js CHANGED
@@ -27,6 +27,7 @@ import { isAcpProvider } from './providers/acp.js';
27
27
  import { isPiProvider } from './providers/pi.js';
28
28
  import { isAntigravityProvider } from './providers/antigravity.js';
29
29
  import { loadLocalImageAttachment } from './tui/clipboardImage.js';
30
+ import { runHeadlessTask, parsePermissionMode, parseMaxTurns } from './headlessCli.js';
30
31
 
31
32
  // One themed source for the art.
32
33
  //
@@ -255,13 +256,26 @@ async function runHomeAction(action, { prompt, conn, finish, loop }) {
255
256
  }
256
257
  }
257
258
 
258
- export async function runTask(task) {
259
+ export async function runTask(task, options = {}) {
260
+ if (options && (options.print || options.outputFormat)) {
261
+ await runHeadlessTask(task, options);
262
+ return;
263
+ }
264
+
259
265
  console.log(`\x1b[1m\x1b[36m[TASK]\x1b[0m Executing...\nTask: ${task}`);
260
266
 
261
267
  const conn = new LocalCLIConnection();
262
268
  const taskId = `cli_task_${Date.now()}`;
263
269
 
264
- const loop = new AgentLoop(conn, taskId, task);
270
+ const loopOptions = {};
271
+ if (options?.provider) loopOptions.provider = options.provider;
272
+ if (options?.model) loopOptions.model = options.model;
273
+ const loop = new AgentLoop(conn, taskId, task, loopOptions);
274
+
275
+ const permMode = parsePermissionMode(options?.permissionMode);
276
+ if (permMode) loop.autonomyOverride = permMode;
277
+ const maxTurns = parseMaxTurns(options?.maxTurns);
278
+ if (maxTurns !== undefined) loop.maxStepsCeiling = maxTurns;
265
279
 
266
280
  // Local human-in-the-loop, showing WHAT is being approved (see L6).
267
281
  loop.waitForApproval = makeApprovalHandler(conn);
package/src/commands.js CHANGED
@@ -45,7 +45,7 @@ import {
45
45
  import fs from 'fs';
46
46
  import os from 'os';
47
47
  import path from 'path';
48
- import { execSync } from 'child_process';
48
+ import { execFileSync } from 'child_process';
49
49
  import { runCopyCommand, runPasteCommand } from './tui/chatboxClipboard.js';
50
50
  import { loadLocalImageAttachment, formatByteSize } from './tui/clipboardImage.js';
51
51
  import { getPackageVersion } from './version.js';
@@ -539,7 +539,7 @@ export const COMMANDS = [
539
539
  let isGit = fs.existsSync(path.join(ws, '.git'));
540
540
  if (!isGit) {
541
541
  try {
542
- execSync('git rev-parse --is-inside-work-tree', { cwd: ws, stdio: 'pipe' });
542
+ execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: ws, stdio: 'pipe' });
543
543
  isGit = true;
544
544
  } catch {
545
545
  isGit = false;
@@ -550,19 +550,20 @@ export const COMMANDS = [
550
550
  return ok(`Workspace "${ws}" is not a git repository.`);
551
551
  }
552
552
 
553
- const status = execSync('git status --short', { cwd: ws, encoding: 'utf8' }).trim();
553
+ const status = execFileSync('git', ['status', '--short'], { cwd: ws, encoding: 'utf8' }).trim();
554
554
  if (!status) {
555
555
  return ok('Working tree is clean. No uncommitted changes in this workspace.');
556
556
  }
557
557
 
558
- let diffCmd = 'git diff';
558
+ let diffArgs = ['diff'];
559
559
  if (sub === 'staged' || sub === '--cached') {
560
- diffCmd = 'git diff --cached';
560
+ diffArgs = ['diff', '--cached'];
561
561
  } else if (sub === 'stat') {
562
- diffCmd = 'git diff --stat HEAD';
562
+ diffArgs = ['diff', '--stat', 'HEAD'];
563
563
  }
564
+ const diffCmd = `git ${diffArgs.join(' ')}`;
564
565
 
565
- const diffOutput = execSync(diffCmd, { cwd: ws, encoding: 'utf8', maxBuffer: 1024 * 1024 }).trim();
566
+ const diffOutput = execFileSync('git', diffArgs, { cwd: ws, encoding: 'utf8', maxBuffer: 1024 * 1024 }).trim();
566
567
  const header = `Git Status (${ws}):\n${status}\n\n${'─'.repeat(50)}\n${diffCmd}:\n`;
567
568
  return ok(diffOutput ? `${header}\n${diffOutput}` : `${header}\n(no file diff for ${diffCmd})`);
568
569
  } catch (err) {
@@ -2288,7 +2289,7 @@ export const COMMANDS = [
2288
2289
  promptText = `Please review ${target} for security vulnerabilities, logic correctness, performance, and best practices.`;
2289
2290
  } else {
2290
2291
  try {
2291
- const status = execSync('git status --short', { cwd: ws, encoding: 'utf8' }).trim();
2292
+ const status = execFileSync('git', ['status', '--short'], { cwd: ws, encoding: 'utf8' }).trim();
2292
2293
  if (!status) {
2293
2294
  return ok('Working tree is clean. To review a specific file, run: /review <path>');
2294
2295
  }
@@ -2429,7 +2430,7 @@ export const COMMANDS = [
2429
2430
  const ws = ctx.loop?.workspaceRoot || process.cwd();
2430
2431
  let isGit = false;
2431
2432
  try {
2432
- execSync('git rev-parse --is-inside-work-tree', { cwd: ws, stdio: 'pipe' });
2433
+ execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: ws, stdio: 'pipe' });
2433
2434
  isGit = true;
2434
2435
  } catch {}
2435
2436
  lines.push(` ✓ Workspace root : ${ws}`);
package/src/config.js CHANGED
@@ -1,10 +1,15 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
- import os from 'os';
4
- import crypto from 'crypto';
5
3
  import { canonicalModelId } from './modelIds.js';
6
4
  import { DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
7
5
  import { causyneHome } from './utils/paths.js';
6
+ import {
7
+ ensureVaultDir,
8
+ atomicWriteSecretFileSync,
9
+ encryptVaultSecret,
10
+ decryptVaultSecret,
11
+ isEncryptedVaultSecret
12
+ } from './configVault.js';
8
13
 
9
14
  function configDir() {
10
15
  return causyneHome();
@@ -17,54 +22,15 @@ function keyFile() {
17
22
  }
18
23
 
19
24
  function ensureConfigDir() {
20
- const dir = configDir();
21
- if (!fs.existsSync(dir)) {
22
- // SECURITY: Directory must only be accessible by the owner
23
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
24
- }
25
- }
26
-
27
- function getVaultKey() {
28
- ensureConfigDir();
29
- const kf = keyFile();
30
- if (!fs.existsSync(kf)) {
31
- const key = crypto.randomBytes(32);
32
- fs.writeFileSync(kf, key, { mode: 0o600 });
33
- return key;
34
- }
35
- return fs.readFileSync(kf);
25
+ ensureVaultDir(configDir());
36
26
  }
37
27
 
38
28
  function encryptString(text) {
39
- if (!text) return text;
40
- if (text.startsWith('ENC:')) return text; // Already encrypted
41
- const key = getVaultKey();
42
- const iv = crypto.randomBytes(16);
43
- const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
44
- let encrypted = cipher.update(text, 'utf8', 'hex');
45
- encrypted += cipher.final('hex');
46
- const authTag = cipher.getAuthTag().toString('hex');
47
- return `ENC:${iv.toString('hex')}:${authTag}:${encrypted}`;
29
+ return encryptVaultSecret(text, keyFile());
48
30
  }
49
31
 
50
32
  function decryptString(encryptedText) {
51
- if (!encryptedText || !encryptedText.startsWith('ENC:')) return encryptedText;
52
- try {
53
- const parts = encryptedText.split(':');
54
- if (parts.length !== 4) return '';
55
- const iv = Buffer.from(parts[1], 'hex');
56
- const authTag = Buffer.from(parts[2], 'hex');
57
- const encrypted = parts[3];
58
- const key = getVaultKey();
59
- const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
60
- decipher.setAuthTag(authTag);
61
- let decrypted = decipher.update(encrypted, 'hex', 'utf8');
62
- decrypted += decipher.final('utf8');
63
- return decrypted;
64
- } catch (e) {
65
- console.error('Failed to decrypt API key:', e);
66
- return '';
67
- }
33
+ return decryptVaultSecret(encryptedText, keyFile());
68
34
  }
69
35
 
70
36
  export function loadConfig() {
@@ -73,28 +39,34 @@ export function loadConfig() {
73
39
  if (fs.existsSync(file)) {
74
40
  try {
75
41
  const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
76
-
77
- // Decrypt API key into memory
78
- if (parsed.apiKey) {
79
- if (!parsed.apiKey.startsWith('ENC:')) {
80
- // Found legacy plaintext key. We must encrypt it and re-save immediately.
81
- const plaintext = parsed.apiKey;
82
- parsed.apiKey = encryptString(plaintext);
83
- saveConfig(parsed); // Re-saves safely encrypted
84
- parsed.apiKey = plaintext; // Keep plaintext in memory for this session
42
+ let needsEncryptedResave = false;
43
+
44
+ // Decrypt API key into memory; flag legacy plaintext keys for immediate encrypted re-save.
45
+ if (typeof parsed.apiKey === 'string' && parsed.apiKey) {
46
+ if (!isEncryptedVaultSecret(parsed.apiKey)) {
47
+ needsEncryptedResave = true;
85
48
  } else {
86
49
  parsed.apiKey = decryptString(parsed.apiKey);
87
50
  }
88
51
  }
89
52
 
90
- // Decrypt provider-specific API keys if stored
53
+ // Decrypt provider-specific API keys if stored; also re-encrypt any legacy plaintext entries.
91
54
  if (parsed.providerKeys && typeof parsed.providerKeys === 'object') {
92
55
  for (const [provider, keyVal] of Object.entries(parsed.providerKeys)) {
93
56
  if (typeof keyVal === 'string' && keyVal) {
94
- parsed.providerKeys[provider] = decryptString(keyVal);
57
+ if (!isEncryptedVaultSecret(keyVal)) {
58
+ needsEncryptedResave = true;
59
+ } else {
60
+ parsed.providerKeys[provider] = decryptString(keyVal);
61
+ }
95
62
  }
96
63
  }
97
64
  }
65
+
66
+ if (needsEncryptedResave) {
67
+ saveConfig(parsed);
68
+ }
69
+
98
70
  if (parsed.apiKey && parsed.provider) {
99
71
  parsed.providerKeys = parsed.providerKeys || {};
100
72
  if (!parsed.providerKeys[parsed.provider]) {
@@ -111,18 +83,23 @@ export function loadConfig() {
111
83
 
112
84
  // Self-heal legacy unconfigured DashScope bug:
113
85
  // If config was written with provider 'dashscope' or 'dashscope-byok' but without an apiKey,
114
- // it was an unintended default from older builds. Heal to an environment key or unconfigured.
86
+ // it was an unintended default from older builds. Heal to an environment key (in-memory only,
87
+ // never persisting transient env secrets to disk) or unconfigured.
115
88
  if ((parsed.provider === 'dashscope' || parsed.provider === 'dashscope-byok') && !parsed.apiKey) {
116
89
  const envDetected = detectEnvironmentProvider();
117
- if (envDetected) {
90
+ if (envDetected && envDetected.apiKey) {
118
91
  parsed.provider = envDetected.provider;
119
92
  parsed.model = envDetected.model;
120
93
  parsed.apiKey = envDetected.apiKey;
94
+ } else if (envDetected) {
95
+ parsed.provider = envDetected.provider;
96
+ parsed.model = envDetected.model;
97
+ saveConfig(parsed);
121
98
  } else {
122
99
  parsed.provider = '';
123
100
  parsed.model = '';
101
+ saveConfig(parsed);
124
102
  }
125
- saveConfig(parsed);
126
103
  }
127
104
 
128
105
  return parsed;
@@ -131,7 +108,8 @@ export function loadConfig() {
131
108
  }
132
109
  }
133
110
 
134
- // Default config: auto-detect from environment if available, otherwise unconfigured
111
+ // Default config: auto-detect from environment if available, otherwise unconfigured.
112
+ // Transient environment API keys stay strictly in memory and are NEVER persisted to disk.
135
113
  const envDetected = detectEnvironmentProvider();
136
114
  const defaultConfig = {
137
115
  provider: envDetected ? envDetected.provider : '',
@@ -147,7 +125,9 @@ export function loadConfig() {
147
125
  hardStop: true
148
126
  }
149
127
  };
150
- saveConfig(defaultConfig);
128
+ if (!envDetected || !envDetected.apiKey) {
129
+ saveConfig(defaultConfig);
130
+ }
151
131
  return defaultConfig;
152
132
  }
153
133
 
@@ -297,8 +277,7 @@ export function saveConfig(config) {
297
277
  }
298
278
  }
299
279
 
300
- // SECURITY: Config file contains encrypted keys, must be 0600 (owner read/write only)
280
+ // SECURITY: Config file contains encrypted keys, written atomically with 0600 permissions
301
281
  const file = configFile();
302
- fs.writeFileSync(file, JSON.stringify(configToSave, null, 2), { encoding: 'utf8', mode: 0o600 });
303
- fs.chmodSync(file, 0o600); // Enforce on existing files
282
+ atomicWriteSecretFileSync(file, JSON.stringify(configToSave, null, 2));
304
283
  }