@causyne/agent 1.20.120 → 1.20.122

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 (276) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +117 -0
  14. package/src/agent/errorClassifier.ts +165 -0
  15. package/src/agent/promptIntent.js +200 -0
  16. package/src/agent/promptIntent.ts +203 -0
  17. package/src/agent/toolArgValidator.js +97 -0
  18. package/src/agent/toolArgValidator.ts +112 -0
  19. package/src/agentLoop.js +33 -344
  20. package/src/agentLoop.ts +51 -352
  21. package/src/approvalGrants.js +19 -7
  22. package/src/approvalGrants.ts +20 -7
  23. package/src/approvalPolicy.js +48 -15
  24. package/src/approvalPolicy.ts +46 -15
  25. package/src/autoUpdate.js +116 -10
  26. package/src/autoUpdate.ts +149 -10
  27. package/src/browser/causyneBrowser.js +3 -2
  28. package/src/browser/causyneBrowser.ts +3 -2
  29. package/src/browser/searchProviders.js +1 -1
  30. package/src/browser/searchProviders.ts +1 -1
  31. package/src/cliMode.js +16 -2
  32. package/src/commands.js +10 -9
  33. package/src/config.js +288 -272
  34. package/src/config.ts +342 -0
  35. package/src/configVault.js +271 -0
  36. package/src/configVault.ts +273 -0
  37. package/src/continuum/compactor.js +2 -1
  38. package/src/continuum/compactor.ts +2 -1
  39. package/src/continuum/sanitizer.js +10 -3
  40. package/src/continuum/sanitizer.ts +9 -3
  41. package/src/continuum/ui/continuumPickerView.js +3 -2
  42. package/src/continuum/ui/continuumPickerView.ts +3 -2
  43. package/src/core/contextCompactor.js +70 -11
  44. package/src/core/contextCompactor.ts +83 -11
  45. package/src/cortex/vectorDb.js +26 -15
  46. package/src/cortex/vectorDb.ts +26 -16
  47. package/src/creative/liveBridge.js +7 -5
  48. package/src/creative/liveBridge.ts +7 -5
  49. package/src/creative/studioScripts.js +16 -5
  50. package/src/creative/studioScripts.ts +14 -5
  51. package/src/decisionPolicy.js +16 -4
  52. package/src/decisionPolicy.ts +14 -4
  53. package/src/documentEngine/antiSlopAuditor.js +10 -5
  54. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  55. package/src/documentEngine/documentForge.js +47 -15
  56. package/src/documentEngine/documentForge.ts +43 -14
  57. package/src/dynamicCatalogue.js +42 -73
  58. package/src/dynamicCatalogue.ts +74 -60
  59. package/src/engines/design.js +2 -1
  60. package/src/engines/design.ts +2 -1
  61. package/src/engines/film.js +4 -4
  62. package/src/engines/film.ts +2 -2
  63. package/src/engines/light.js +2 -1
  64. package/src/engines/light.ts +2 -1
  65. package/src/engines/registry.js +1 -1
  66. package/src/engines/registry.ts +1 -1
  67. package/src/engines/reverseHarness.js +4 -3
  68. package/src/engines/reverseHarness.ts +4 -3
  69. package/src/entrypoint.js +77 -4
  70. package/src/headlessCli.js +305 -0
  71. package/src/headlessCli.ts +381 -0
  72. package/src/historyPruner.js +3 -2
  73. package/src/historyPruner.ts +3 -2
  74. package/src/hooks.js +3 -0
  75. package/src/hooks.ts +3 -0
  76. package/src/implementationPlan.js +21 -11
  77. package/src/implementationPlan.ts +21 -11
  78. package/src/infra/atomicWriter.js +4 -1
  79. package/src/infra/atomicWriter.ts +4 -1
  80. package/src/launchIntent.js +1 -1
  81. package/src/launchIntent.ts +1 -1
  82. package/src/mcp/mcpClient.js +38 -11
  83. package/src/mcp/mcpClient.ts +44 -11
  84. package/src/mcp/mcpRegistry.js +2 -5
  85. package/src/mcp/mcpRegistry.ts +2 -5
  86. package/src/mcp/mcpSecurity.js +189 -0
  87. package/src/mcp/mcpSecurity.ts +190 -0
  88. package/src/memory/scopedFacts.js +1 -1
  89. package/src/memory/scopedFacts.ts +1 -1
  90. package/src/memory/symbolFolder.js +1 -1
  91. package/src/memory/symbolFolder.ts +1 -1
  92. package/src/modelRouter.js +1 -1
  93. package/src/modelRouter.ts +1 -1
  94. package/src/observer/evidence.js +10 -4
  95. package/src/observer/evidence.ts +10 -4
  96. package/src/osKeychain.js +263 -0
  97. package/src/osKeychain.ts +287 -0
  98. package/src/perception.js +3 -2
  99. package/src/perception.ts +3 -2
  100. package/src/planCache.js +2 -2
  101. package/src/planCache.ts +2 -2
  102. package/src/pluginsFactory/pluginsFactory.js +19 -11
  103. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  104. package/src/promptMentions.js +2 -2
  105. package/src/promptMentions.ts +2 -2
  106. package/src/providers/acp.js +1 -1
  107. package/src/providers/acp.ts +1 -1
  108. package/src/providers/anthropic.js +328 -385
  109. package/src/providers/anthropic.ts +386 -0
  110. package/src/providers/antigravity.js +10 -4
  111. package/src/providers/antigravity.ts +10 -4
  112. package/src/providers/base.js +221 -319
  113. package/src/providers/base.ts +340 -0
  114. package/src/providers/byokHttp.js +397 -0
  115. package/src/providers/byokHttp.ts +497 -0
  116. package/src/providers/byokStream.js +748 -0
  117. package/src/providers/byokStream.ts +863 -0
  118. package/src/providers/dashscope-byok.js +98 -81
  119. package/src/providers/dashscope-byok.ts +114 -0
  120. package/src/providers/deepseek.js +74 -64
  121. package/src/providers/deepseek.ts +99 -0
  122. package/src/providers/factory.js +35 -28
  123. package/src/providers/factory.ts +40 -0
  124. package/src/providers/gemini.js +229 -253
  125. package/src/providers/gemini.ts +261 -0
  126. package/src/providers/loopGuard.js +9 -5
  127. package/src/providers/loopGuard.ts +10 -5
  128. package/src/providers/moonshot.js +71 -64
  129. package/src/providers/moonshot.ts +93 -0
  130. package/src/providers/muse.js +82 -152
  131. package/src/providers/muse.ts +122 -0
  132. package/src/providers/ollama.js +116 -93
  133. package/src/providers/ollama.ts +135 -0
  134. package/src/providers/openai-compatible.js +114 -65
  135. package/src/providers/openai-compatible.ts +139 -0
  136. package/src/providers/openai.js +22 -15
  137. package/src/providers/openai.ts +30 -0
  138. package/src/providers/openrouter.js +194 -98
  139. package/src/providers/openrouter.ts +202 -97
  140. package/src/providers/pi.js +6 -0
  141. package/src/providers/pi.ts +6 -0
  142. package/src/providers/qwen-byok.js +97 -71
  143. package/src/providers/qwen-byok.ts +113 -0
  144. package/src/providers/toolContracts.js +40 -14
  145. package/src/providers/toolContracts.ts +35 -14
  146. package/src/providers/wireNormalizer.js +78 -11
  147. package/src/providers/wireNormalizer.ts +68 -12
  148. package/src/providers/xai.js +74 -64
  149. package/src/providers/xai.ts +97 -0
  150. package/src/reliability/assetEvidence.js +4 -2
  151. package/src/reliability/assetEvidence.ts +4 -2
  152. package/src/sandbox.js +486 -530
  153. package/src/sandbox.ts +552 -0
  154. package/src/sandboxPolicy.js +1287 -0
  155. package/src/sandboxPolicy.ts +1381 -0
  156. package/src/sessionJournal.js +55 -3
  157. package/src/sessionJournal.ts +58 -3
  158. package/src/skills/skillResourceSafety.js +19 -8
  159. package/src/skills/skillResourceSafety.ts +16 -7
  160. package/src/skillsManager.js +3 -3
  161. package/src/skillsManager.ts +3 -3
  162. package/src/smartToolsUse.js +28 -4
  163. package/src/smartToolsUse.ts +29 -7
  164. package/src/stallGuard.js +45 -22
  165. package/src/stallGuard.ts +46 -22
  166. package/src/subagentJournal.js +6 -4
  167. package/src/subagentJournal.ts +6 -4
  168. package/src/textDiff.js +6 -1
  169. package/src/textDiff.ts +6 -1
  170. package/src/timeMachine.js +7 -1
  171. package/src/timeMachine.ts +7 -1
  172. package/src/tokenTracker.js +43 -28
  173. package/src/tokenTracker.ts +44 -30
  174. package/src/toolPacks.js +3 -1
  175. package/src/toolPacks.ts +3 -1
  176. package/src/tools/archive.js +245 -35
  177. package/src/tools/archive.ts +244 -35
  178. package/src/tools/computerUse.js +7 -3
  179. package/src/tools/computerUse.ts +7 -3
  180. package/src/tools/creativeApps.js +13 -8
  181. package/src/tools/creativeApps.ts +22 -9
  182. package/src/tools/deferredMcpSearch.js +26 -14
  183. package/src/tools/deferredMcpSearch.ts +26 -14
  184. package/src/tools/desktopOpen.js +69 -10
  185. package/src/tools/desktopOpen.ts +70 -11
  186. package/src/tools/documentForge.js +167 -82
  187. package/src/tools/documentForge.ts +169 -84
  188. package/src/tools/fsEdit.js +101 -30
  189. package/src/tools/fsEdit.ts +105 -32
  190. package/src/tools/fsFind.js +8 -5
  191. package/src/tools/fsFind.ts +7 -4
  192. package/src/tools/fsRead.js +119 -13
  193. package/src/tools/fsRead.ts +124 -13
  194. package/src/tools/fsWrite.js +17 -5
  195. package/src/tools/fsWrite.ts +17 -7
  196. package/src/tools/generateMediaViaApi.js +82 -19
  197. package/src/tools/generateMediaViaApi.ts +80 -19
  198. package/src/tools/memoryRecall.js +62 -11
  199. package/src/tools/memoryRecall.ts +70 -13
  200. package/src/tools/memoryWrite.js +27 -14
  201. package/src/tools/memoryWrite.ts +30 -14
  202. package/src/tools/multiEdit.js +100 -30
  203. package/src/tools/multiEdit.ts +104 -32
  204. package/src/tools/nativeEngine.js +33 -18
  205. package/src/tools/nativeEngine.ts +31 -18
  206. package/src/tools/openSourceToolProvisioner.js +49 -14
  207. package/src/tools/openSourceToolProvisioner.ts +54 -15
  208. package/src/tools/osSandbox.js +513 -0
  209. package/src/tools/osSandbox.ts +588 -0
  210. package/src/tools/payloadSanitizer.js +40 -8
  211. package/src/tools/payloadSanitizer.ts +39 -8
  212. package/src/tools/peerAgent.js +96 -34
  213. package/src/tools/peerAgent.ts +114 -37
  214. package/src/tools/persistentShell.js +8 -3
  215. package/src/tools/pluginsFactory.js +38 -6
  216. package/src/tools/pluginsFactory.ts +42 -6
  217. package/src/tools/readNativeSkill.js +10 -8
  218. package/src/tools/readNativeSkill.ts +10 -8
  219. package/src/tools/requestDecision.js +10 -3
  220. package/src/tools/requestDecision.ts +10 -3
  221. package/src/tools/resolveAutomator.js +91 -17
  222. package/src/tools/resolveAutomator.ts +102 -17
  223. package/src/tools/reverseEngineering.js +168 -41
  224. package/src/tools/reverseEngineering.ts +161 -41
  225. package/src/tools/subprocessEnv.js +197 -0
  226. package/src/tools/subprocessEnv.ts +212 -0
  227. package/src/tools/sysRun.js +108 -35
  228. package/src/tools/sysRun.ts +119 -31
  229. package/src/tools/toolDispatch.js +24 -1
  230. package/src/tools/toolDispatch.ts +21 -1
  231. package/src/tools/toolOutputStore.js +62 -23
  232. package/src/tools/toolOutputStore.ts +56 -23
  233. package/src/tools/toolScanner.js +13 -10
  234. package/src/tools/toolScanner.ts +13 -10
  235. package/src/tools/toolSelfRepair.js +94 -28
  236. package/src/tools/toolSelfRepair.ts +96 -28
  237. package/src/tools/uiForge.js +71 -6
  238. package/src/tools/uiForge.ts +74 -6
  239. package/src/tools/viewImage.js +62 -17
  240. package/src/tools/viewImage.ts +57 -12
  241. package/src/tools/visionInspector.js +15 -3
  242. package/src/tools/visionInspector.ts +15 -3
  243. package/src/tools/walkerSafety.js +2 -0
  244. package/src/tools/walkerSafety.ts +1 -0
  245. package/src/tools/webFetch.js +105 -10
  246. package/src/tools/webFetch.ts +105 -11
  247. package/src/tui/banner.js +3 -2
  248. package/src/tui/banner.ts +3 -2
  249. package/src/tui/consoleGuard.js +12 -4
  250. package/src/tui/consoleGuard.ts +9 -4
  251. package/src/tui/messageInteraction.js +2 -3
  252. package/src/tui/messageInteraction.ts +2 -3
  253. package/src/tui/modelPicker.js +1 -0
  254. package/src/tui/modelPicker.ts +1 -0
  255. package/src/tui/overlay.js +3 -1
  256. package/src/tui/overlay.ts +3 -1
  257. package/src/tui/sessionPicker.js +3 -2
  258. package/src/tui/sessionPicker.ts +3 -2
  259. package/src/tui/sessionPickerView.js +7 -1
  260. package/src/tui/sessionPickerView.ts +6 -1
  261. package/src/tui/toolOutputNormalizer.js +2 -3
  262. package/src/tui/toolOutputNormalizer.ts +4 -3
  263. package/src/tui/viewport.js +4 -4
  264. package/src/tui/viewport.ts +5 -5
  265. package/src/tui/workspaceIdentity.js +2 -1
  266. package/src/tui/workspaceIdentity.ts +2 -1
  267. package/src/uncertainty.js +8 -3
  268. package/src/uncertainty.ts +8 -3
  269. package/src/utils/paths.js +8 -5
  270. package/src/utils/paths.ts +9 -7
  271. package/src/vfeTracker.js +9 -3
  272. package/src/vfeTracker.ts +9 -3
  273. package/src/config.d.ts +0 -2
  274. package/src/providers/base.d.ts +0 -94
  275. package/src/providers/factory.d.ts +0 -1
  276. package/src/sandbox.d.ts +0 -1
package/src/config.js CHANGED
@@ -1,304 +1,320 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import os from 'os';
4
- import crypto from 'crypto';
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
5
4
  import { canonicalModelId } from './modelIds.js';
6
5
  import { DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
7
6
  import { causyneHome } from './utils/paths.js';
8
-
7
+ import { ensureVaultDir, atomicWriteSecretFileSync, encryptVaultSecret, decryptVaultSecret, isEncryptedVaultSecret } from './configVault.js';
8
+ const MAX_CONFIG_BYTES = 2 * 1024 * 1024;
9
+ const FORBIDDEN_CONFIG_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
9
10
  function configDir() {
10
- return causyneHome();
11
+ return causyneHome();
11
12
  }
12
13
  function configFile() {
13
- return path.join(causyneHome(), 'config.json');
14
+ return path.join(causyneHome(), 'config.json');
14
15
  }
15
16
  function keyFile() {
16
- return path.join(causyneHome(), '.vault_key');
17
+ return path.join(causyneHome(), '.vault_key');
17
18
  }
18
-
19
19
  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
- }
20
+ ensureVaultDir(configDir());
25
21
  }
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);
36
- }
37
-
38
22
  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}`;
23
+ return encryptVaultSecret(text, keyFile());
48
24
  }
49
-
50
25
  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
- }
26
+ return decryptVaultSecret(encryptedText, keyFile());
68
27
  }
69
-
70
28
  export function loadConfig() {
71
- ensureConfigDir();
72
- const file = configFile();
73
- if (fs.existsSync(file)) {
74
- try {
75
- 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
85
- } else {
86
- parsed.apiKey = decryptString(parsed.apiKey);
87
- }
88
- }
89
-
90
- // Decrypt provider-specific API keys if stored
91
- if (parsed.providerKeys && typeof parsed.providerKeys === 'object') {
92
- for (const [provider, keyVal] of Object.entries(parsed.providerKeys)) {
93
- if (typeof keyVal === 'string' && keyVal) {
94
- parsed.providerKeys[provider] = decryptString(keyVal);
95
- }
96
- }
97
- }
98
- if (parsed.apiKey && parsed.provider) {
99
- parsed.providerKeys = parsed.providerKeys || {};
100
- if (!parsed.providerKeys[parsed.provider]) {
101
- parsed.providerKeys[parsed.provider] = parsed.apiKey;
29
+ ensureConfigDir();
30
+ const file = configFile();
31
+ const hadExistingFile = fs.existsSync(file);
32
+ if (hadExistingFile) {
33
+ try {
34
+ const stat = fs.lstatSync(file);
35
+ if (stat.isSymbolicLink() || !stat.isFile()) {
36
+ throw new Error('Refusing to load symlink or non-regular config.json');
37
+ }
38
+ if (stat.size > MAX_CONFIG_BYTES) {
39
+ throw new Error(`config.json exceeds maximum size (${MAX_CONFIG_BYTES} bytes)`);
40
+ }
41
+ const rawText = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
42
+ const parsedRaw = JSON.parse(rawText);
43
+ if (!parsedRaw || typeof parsedRaw !== 'object' || Array.isArray(parsedRaw)) {
44
+ throw new Error('config.json must contain a JSON object');
45
+ }
46
+ const parsed = parsedRaw;
47
+ let needsEncryptedResave = false;
48
+ let hadDecryptFailure = false;
49
+ if (typeof parsed.apiKey === 'string' && parsed.apiKey) {
50
+ if (!isEncryptedVaultSecret(parsed.apiKey)) {
51
+ needsEncryptedResave = true;
52
+ }
53
+ else {
54
+ const decrypted = decryptString(parsed.apiKey);
55
+ if (!decrypted)
56
+ hadDecryptFailure = true;
57
+ parsed.apiKey = decrypted;
58
+ }
59
+ }
60
+ if (parsed.providerKeys && typeof parsed.providerKeys === 'object' && !Array.isArray(parsed.providerKeys)) {
61
+ for (const [provider, keyVal] of Object.entries(parsed.providerKeys)) {
62
+ if (FORBIDDEN_CONFIG_KEYS.has(provider)) {
63
+ delete parsed.providerKeys[provider];
64
+ continue;
65
+ }
66
+ if (typeof keyVal === 'string' && keyVal) {
67
+ if (!isEncryptedVaultSecret(keyVal)) {
68
+ needsEncryptedResave = true;
69
+ }
70
+ else {
71
+ const decrypted = decryptString(keyVal);
72
+ if (!decrypted)
73
+ hadDecryptFailure = true;
74
+ parsed.providerKeys[provider] = decrypted;
75
+ }
76
+ }
77
+ }
78
+ }
79
+ if (needsEncryptedResave && !hadDecryptFailure) {
80
+ saveConfig(parsed);
81
+ }
82
+ if (typeof parsed.apiKey === 'string' && parsed.apiKey && typeof parsed.provider === 'string' && parsed.provider && !FORBIDDEN_CONFIG_KEYS.has(parsed.provider)) {
83
+ if (!parsed.providerKeys || typeof parsed.providerKeys !== 'object' || Array.isArray(parsed.providerKeys)) {
84
+ parsed.providerKeys = {};
85
+ }
86
+ if (!parsed.providerKeys[parsed.provider]) {
87
+ parsed.providerKeys[parsed.provider] = parsed.apiKey;
88
+ }
89
+ }
90
+ if (typeof parsed.model === 'string' && parsed.model.trim()) {
91
+ const canonicalModel = canonicalModelId(parsed.model);
92
+ if (canonicalModel !== parsed.model) {
93
+ parsed.model = canonicalModel;
94
+ if (!hadDecryptFailure)
95
+ saveConfig(parsed);
96
+ }
97
+ }
98
+ if ((parsed.provider === 'dashscope' || parsed.provider === 'dashscope-byok') && !parsed.apiKey && !hadDecryptFailure) {
99
+ const envDetected = detectEnvironmentProvider();
100
+ if (envDetected && envDetected.apiKey) {
101
+ parsed.provider = envDetected.provider;
102
+ parsed.model = envDetected.model;
103
+ parsed.apiKey = envDetected.apiKey;
104
+ }
105
+ else if (envDetected) {
106
+ parsed.provider = envDetected.provider;
107
+ parsed.model = envDetected.model;
108
+ saveConfig(parsed);
109
+ }
110
+ else {
111
+ parsed.provider = '';
112
+ parsed.model = '';
113
+ saveConfig(parsed);
114
+ }
115
+ }
116
+ return parsed;
102
117
  }
103
- }
104
-
105
- // Self-heal a model id written before src/modelIds.js existed.
106
- const canonicalModel = canonicalModelId(parsed.model);
107
- if (canonicalModel !== parsed.model) {
108
- parsed.model = canonicalModel;
109
- saveConfig(parsed);
110
- }
111
-
112
- // Self-heal legacy unconfigured DashScope bug:
113
- // 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.
115
- if ((parsed.provider === 'dashscope' || parsed.provider === 'dashscope-byok') && !parsed.apiKey) {
116
- const envDetected = detectEnvironmentProvider();
117
- if (envDetected) {
118
- parsed.provider = envDetected.provider;
119
- parsed.model = envDetected.model;
120
- parsed.apiKey = envDetected.apiKey;
121
- } else {
122
- parsed.provider = '';
123
- parsed.model = '';
118
+ catch (e) {
119
+ console.error('Error reading config.json:', e);
124
120
  }
125
- saveConfig(parsed);
126
- }
127
-
128
- return parsed;
129
- } catch (e) {
130
- console.error('Error reading config.json:', e);
131
121
  }
132
- }
133
-
134
- // Default config: auto-detect from environment if available, otherwise unconfigured
135
- const envDetected = detectEnvironmentProvider();
136
- const defaultConfig = {
137
- provider: envDetected ? envDetected.provider : '',
138
- model: envDetected ? envDetected.model : '',
139
- apiKey: envDetected ? envDetected.apiKey : '',
140
- autonomyMode: 'B',
141
- tokenBudget: {
142
- enabled: false,
143
- maxTokensPerTask: 500000,
144
- maxTokensPerDay: 2000000,
145
- maxCostUsd: 5.00, // Hard stop if cost exceeds this in BYOK mode
146
- warningThreshold: 0.8,
147
- hardStop: true
122
+ const envDetected = detectEnvironmentProvider();
123
+ const defaultConfig = {
124
+ provider: envDetected ? envDetected.provider : '',
125
+ model: envDetected ? envDetected.model : '',
126
+ apiKey: envDetected ? envDetected.apiKey : '',
127
+ autonomyMode: 'B',
128
+ tokenBudget: {
129
+ enabled: false,
130
+ maxTokensPerTask: 500000,
131
+ maxTokensPerDay: 2000000,
132
+ maxCostUsd: 5.00,
133
+ warningThreshold: 0.8,
134
+ hardStop: true
135
+ }
136
+ };
137
+ if (!hadExistingFile && (!envDetected || !envDetected.apiKey)) {
138
+ saveConfig(defaultConfig);
148
139
  }
149
- };
150
- saveConfig(defaultConfig);
151
- return defaultConfig;
140
+ return defaultConfig;
141
+ }
142
+ function readEnvSecret(value) {
143
+ return typeof value === 'string' ? value.trim() : '';
152
144
  }
153
-
154
- /**
155
- * Auto-detect available API keys from environment variables.
156
- * Precedence matches frontier capability: Gemini, Anthropic, OpenAI, DeepSeek, xAI, Moonshot, Qwen/DashScope.
157
- */
158
145
  export function detectEnvironmentProvider() {
159
- const env = process.env;
160
- if (env.GEMINI_API_KEY || env.GOOGLE_API_KEY) {
161
- return {
162
- provider: 'gemini',
163
- apiKey: env.GEMINI_API_KEY || env.GOOGLE_API_KEY || '',
164
- model: DEFAULT_MODEL_BY_PROVIDER.gemini
165
- };
166
- }
167
- if (env.ANTHROPIC_API_KEY) {
168
- return {
169
- provider: 'anthropic',
170
- apiKey: env.ANTHROPIC_API_KEY,
171
- model: DEFAULT_MODEL_BY_PROVIDER.anthropic
172
- };
173
- }
174
- if (env.OPENAI_API_KEY) {
175
- return {
176
- provider: 'openai',
177
- apiKey: env.OPENAI_API_KEY,
178
- model: DEFAULT_MODEL_BY_PROVIDER.openai
179
- };
180
- }
181
- if (env.DEEPSEEK_API_KEY) {
182
- return {
183
- provider: 'deepseek',
184
- apiKey: env.DEEPSEEK_API_KEY,
185
- model: DEFAULT_MODEL_BY_PROVIDER.deepseek
186
- };
187
- }
188
- if (env.XAI_API_KEY || env.GROK_API_KEY) {
189
- return {
190
- provider: 'xai',
191
- apiKey: env.XAI_API_KEY || env.GROK_API_KEY || '',
192
- model: DEFAULT_MODEL_BY_PROVIDER.xai
193
- };
194
- }
195
- if (env.MOONSHOT_API_KEY) {
196
- return {
197
- provider: 'moonshot',
198
- apiKey: env.MOONSHOT_API_KEY,
199
- model: DEFAULT_MODEL_BY_PROVIDER.moonshot
200
- };
201
- }
202
- if (env.DASHSCOPE_API_KEY || env.QWEN_API_KEY) {
203
- return {
204
- provider: 'dashscope-byok',
205
- apiKey: env.DASHSCOPE_API_KEY || env.QWEN_API_KEY || '',
206
- model: DEFAULT_MODEL_BY_PROVIDER['dashscope-byok']
207
- };
208
- }
209
-
210
- // If no environment API keys found, auto-detect installed local sovereign agents
211
- return detectLocalAgentProvider();
146
+ const env = process.env;
147
+ const geminiKey = readEnvSecret(env.GEMINI_API_KEY) || readEnvSecret(env.GOOGLE_API_KEY);
148
+ if (geminiKey) {
149
+ return {
150
+ provider: 'gemini',
151
+ apiKey: geminiKey,
152
+ model: DEFAULT_MODEL_BY_PROVIDER.gemini || ''
153
+ };
154
+ }
155
+ const anthropicKey = readEnvSecret(env.ANTHROPIC_API_KEY);
156
+ if (anthropicKey) {
157
+ return {
158
+ provider: 'anthropic',
159
+ apiKey: anthropicKey,
160
+ model: DEFAULT_MODEL_BY_PROVIDER.anthropic || ''
161
+ };
162
+ }
163
+ const openaiKey = readEnvSecret(env.OPENAI_API_KEY);
164
+ if (openaiKey) {
165
+ return {
166
+ provider: 'openai',
167
+ apiKey: openaiKey,
168
+ model: DEFAULT_MODEL_BY_PROVIDER.openai || ''
169
+ };
170
+ }
171
+ const deepseekKey = readEnvSecret(env.DEEPSEEK_API_KEY);
172
+ if (deepseekKey) {
173
+ return {
174
+ provider: 'deepseek',
175
+ apiKey: deepseekKey,
176
+ model: DEFAULT_MODEL_BY_PROVIDER.deepseek || ''
177
+ };
178
+ }
179
+ const xaiKey = readEnvSecret(env.XAI_API_KEY) || readEnvSecret(env.GROK_API_KEY);
180
+ if (xaiKey) {
181
+ return {
182
+ provider: 'xai',
183
+ apiKey: xaiKey,
184
+ model: DEFAULT_MODEL_BY_PROVIDER.xai || ''
185
+ };
186
+ }
187
+ const moonshotKey = readEnvSecret(env.MOONSHOT_API_KEY);
188
+ if (moonshotKey) {
189
+ return {
190
+ provider: 'moonshot',
191
+ apiKey: moonshotKey,
192
+ model: DEFAULT_MODEL_BY_PROVIDER.moonshot || ''
193
+ };
194
+ }
195
+ const dashscopeKey = readEnvSecret(env.DASHSCOPE_API_KEY) || readEnvSecret(env.QWEN_API_KEY);
196
+ if (dashscopeKey) {
197
+ return {
198
+ provider: 'dashscope-byok',
199
+ apiKey: dashscopeKey,
200
+ model: DEFAULT_MODEL_BY_PROVIDER['dashscope-byok'] || ''
201
+ };
202
+ }
203
+ return detectLocalAgentProvider();
212
204
  }
213
-
214
205
  function checkBinarySync(binaryName) {
215
- if (path.isAbsolute(binaryName)) {
216
- return fs.existsSync(binaryName);
217
- }
218
- const envPath = process.env.PATH || '';
219
- const delimiter = process.platform === 'win32' ? ';' : ':';
220
- const home = process.env.HOME || '';
221
- const fallbackDirs = [
222
- path.join(home, '.local', 'bin'),
223
- path.join(home, '.antigravity', 'antigravity', 'bin'),
224
- path.join(home, '.gemini', 'antigravity-ide', 'bin'),
225
- path.join(home, '.opencode', 'bin'),
226
- '/Applications/Antigravity.app/Contents/Resources/app/bin',
227
- '/Applications/Antigravity IDE.app/Contents/Resources/app/bin'
228
- ];
229
- const dirs = [...envPath.split(delimiter), ...fallbackDirs];
230
- const extensions = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
231
-
232
- for (const dir of dirs) {
233
- if (!dir) continue;
234
- for (const ext of extensions) {
235
- const full = path.join(dir, `${binaryName}${ext}`);
236
- try {
237
- if (fs.existsSync(full) && fs.statSync(full).isFile()) {
238
- return true;
206
+ if (typeof binaryName !== 'string' || !binaryName.trim() || /[\r\n\0]/.test(binaryName)) {
207
+ return false;
208
+ }
209
+ const trimmed = binaryName.trim();
210
+ if (path.isAbsolute(trimmed)) {
211
+ try {
212
+ if (!fs.statSync(trimmed).isFile())
213
+ return false;
214
+ if (process.platform !== 'win32')
215
+ fs.accessSync(trimmed, fs.constants.X_OK);
216
+ return true;
217
+ }
218
+ catch {
219
+ return false;
220
+ }
221
+ }
222
+ if (trimmed.includes('..') || trimmed.includes('/') || trimmed.includes('\\')) {
223
+ return false;
224
+ }
225
+ const envPath = process.env.PATH || process.env.Path || '';
226
+ const delimiter = process.platform === 'win32' ? ';' : ':';
227
+ const home = os.homedir();
228
+ const fallbackDirs = [
229
+ ...(home && path.isAbsolute(home) ? [
230
+ path.join(home, '.local', 'bin'),
231
+ path.join(home, '.antigravity', 'antigravity', 'bin'),
232
+ path.join(home, '.gemini', 'antigravity-ide', 'bin'),
233
+ path.join(home, '.opencode', 'bin')
234
+ ] : []),
235
+ '/Applications/Antigravity.app/Contents/Resources/app/bin',
236
+ '/Applications/Antigravity IDE.app/Contents/Resources/app/bin'
237
+ ];
238
+ const dirs = [...envPath.split(delimiter), ...fallbackDirs];
239
+ const extensions = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
240
+ for (const rawDir of dirs) {
241
+ const dir = rawDir.trim();
242
+ if (!dir || !path.isAbsolute(dir))
243
+ continue;
244
+ for (const ext of extensions) {
245
+ const full = path.join(dir, `${trimmed}${ext}`);
246
+ try {
247
+ if (fs.statSync(full).isFile()) {
248
+ if (process.platform !== 'win32')
249
+ fs.accessSync(full, fs.constants.X_OK);
250
+ return true;
251
+ }
252
+ }
253
+ catch {
254
+ // ignore inaccessible or non-executable entry
255
+ }
239
256
  }
240
- } catch {}
241
257
  }
242
- }
243
- return false;
258
+ return false;
244
259
  }
245
-
246
260
  export function detectLocalAgentProvider() {
247
- if (checkBinarySync('agy') || checkBinarySync('antigravity')) {
248
- return {
249
- provider: 'antigravity',
250
- model: DEFAULT_MODEL_BY_PROVIDER.antigravity || 'Gemini 3.8 Flash (Low)',
251
- apiKey: ''
252
- };
253
- }
254
- if (checkBinarySync('opencode')) {
255
- return {
256
- provider: 'acp/opencode',
257
- model: DEFAULT_MODEL_BY_PROVIDER['acp/opencode'],
258
- apiKey: ''
259
- };
260
- }
261
- if (checkBinarySync('claude')) {
262
- return {
263
- provider: 'acp/claude',
264
- model: DEFAULT_MODEL_BY_PROVIDER['acp/claude'],
265
- apiKey: ''
266
- };
267
- }
268
- if (checkBinarySync('codex')) {
269
- return {
270
- provider: 'acp/codex',
271
- model: DEFAULT_MODEL_BY_PROVIDER['acp/codex'],
272
- apiKey: ''
273
- };
274
- }
275
- if (checkBinarySync('ollama')) {
276
- return {
277
- provider: 'ollama',
278
- model: DEFAULT_MODEL_BY_PROVIDER.ollama || 'llama3.3',
279
- apiKey: ''
280
- };
281
- }
282
- return null;
261
+ if (checkBinarySync('agy') || checkBinarySync('antigravity')) {
262
+ return {
263
+ provider: 'antigravity',
264
+ model: DEFAULT_MODEL_BY_PROVIDER.antigravity || 'Gemini 3.8 Flash (Low)',
265
+ apiKey: ''
266
+ };
267
+ }
268
+ if (checkBinarySync('opencode')) {
269
+ return {
270
+ provider: 'acp/opencode',
271
+ model: DEFAULT_MODEL_BY_PROVIDER['acp/opencode'] || '',
272
+ apiKey: ''
273
+ };
274
+ }
275
+ if (checkBinarySync('claude')) {
276
+ return {
277
+ provider: 'acp/claude',
278
+ model: DEFAULT_MODEL_BY_PROVIDER['acp/claude'] || '',
279
+ apiKey: ''
280
+ };
281
+ }
282
+ if (checkBinarySync('codex')) {
283
+ return {
284
+ provider: 'acp/codex',
285
+ model: DEFAULT_MODEL_BY_PROVIDER['acp/codex'] || '',
286
+ apiKey: ''
287
+ };
288
+ }
289
+ if (checkBinarySync('ollama')) {
290
+ return {
291
+ provider: 'ollama',
292
+ model: DEFAULT_MODEL_BY_PROVIDER.ollama || 'llama3.3',
293
+ apiKey: ''
294
+ };
295
+ }
296
+ return null;
283
297
  }
284
-
285
298
  export function saveConfig(config) {
286
- ensureConfigDir();
287
- // SECURITY: Deep copy to avoid mutating the in-memory config
288
- const configToSave = JSON.parse(JSON.stringify(config));
289
- if (configToSave.apiKey) {
290
- configToSave.apiKey = encryptString(configToSave.apiKey);
291
- }
292
- if (configToSave.providerKeys && typeof configToSave.providerKeys === 'object') {
293
- for (const [provider, keyVal] of Object.entries(configToSave.providerKeys)) {
294
- if (typeof keyVal === 'string' && keyVal) {
295
- configToSave.providerKeys[provider] = encryptString(keyVal);
296
- }
299
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
300
+ throw new Error('saveConfig requires a plain configuration object');
301
+ }
302
+ ensureConfigDir();
303
+ const configToSave = JSON.parse(JSON.stringify(config));
304
+ if (typeof configToSave.apiKey === 'string' && configToSave.apiKey) {
305
+ configToSave.apiKey = encryptString(configToSave.apiKey);
306
+ }
307
+ if (configToSave.providerKeys && typeof configToSave.providerKeys === 'object' && !Array.isArray(configToSave.providerKeys)) {
308
+ for (const [provider, keyVal] of Object.entries(configToSave.providerKeys)) {
309
+ if (FORBIDDEN_CONFIG_KEYS.has(provider)) {
310
+ delete configToSave.providerKeys[provider];
311
+ continue;
312
+ }
313
+ if (typeof keyVal === 'string' && keyVal) {
314
+ configToSave.providerKeys[provider] = encryptString(keyVal);
315
+ }
316
+ }
297
317
  }
298
- }
299
-
300
- // SECURITY: Config file contains encrypted keys, must be 0600 (owner read/write only)
301
- 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
318
+ const file = configFile();
319
+ atomicWriteSecretFileSync(file, JSON.stringify(configToSave, null, 2));
304
320
  }