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