@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.ts ADDED
@@ -0,0 +1,342 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { canonicalModelId } from './modelIds.js';
5
+ import { DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
6
+ import { causyneHome } from './utils/paths.js';
7
+ import {
8
+ ensureVaultDir,
9
+ atomicWriteSecretFileSync,
10
+ encryptVaultSecret,
11
+ decryptVaultSecret,
12
+ isEncryptedVaultSecret
13
+ } from './configVault.js';
14
+
15
+ export interface DetectedProviderConfig {
16
+ provider: string;
17
+ model: string;
18
+ apiKey: string;
19
+ }
20
+
21
+ export type CausyneConfig = Record<string, any>;
22
+
23
+ const MAX_CONFIG_BYTES = 2 * 1024 * 1024;
24
+ const FORBIDDEN_CONFIG_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
25
+
26
+ function configDir(): string {
27
+ return causyneHome();
28
+ }
29
+ function configFile(): string {
30
+ return path.join(causyneHome(), 'config.json');
31
+ }
32
+ function keyFile(): string {
33
+ return path.join(causyneHome(), '.vault_key');
34
+ }
35
+
36
+ function ensureConfigDir(): void {
37
+ ensureVaultDir(configDir());
38
+ }
39
+
40
+ function encryptString(text: string): string {
41
+ return encryptVaultSecret(text, keyFile());
42
+ }
43
+
44
+ function decryptString(encryptedText: string): string {
45
+ return decryptVaultSecret(encryptedText, keyFile());
46
+ }
47
+
48
+ export function loadConfig(): CausyneConfig {
49
+ ensureConfigDir();
50
+ const file = configFile();
51
+ const hadExistingFile = fs.existsSync(file);
52
+ if (hadExistingFile) {
53
+ try {
54
+ const stat = fs.lstatSync(file);
55
+ if (stat.isSymbolicLink() || !stat.isFile()) {
56
+ throw new Error('Refusing to load symlink or non-regular config.json');
57
+ }
58
+ if (stat.size > MAX_CONFIG_BYTES) {
59
+ throw new Error(`config.json exceeds maximum size (${MAX_CONFIG_BYTES} bytes)`);
60
+ }
61
+ const rawText = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
62
+ const parsedRaw: unknown = JSON.parse(rawText);
63
+ if (!parsedRaw || typeof parsedRaw !== 'object' || Array.isArray(parsedRaw)) {
64
+ throw new Error('config.json must contain a JSON object');
65
+ }
66
+ const parsed = parsedRaw as CausyneConfig;
67
+ let needsEncryptedResave = false;
68
+ let hadDecryptFailure = false;
69
+
70
+ if (typeof parsed.apiKey === 'string' && parsed.apiKey) {
71
+ if (!isEncryptedVaultSecret(parsed.apiKey)) {
72
+ needsEncryptedResave = true;
73
+ } else {
74
+ const decrypted = decryptString(parsed.apiKey);
75
+ if (!decrypted) hadDecryptFailure = true;
76
+ parsed.apiKey = decrypted;
77
+ }
78
+ }
79
+
80
+ if (parsed.providerKeys && typeof parsed.providerKeys === 'object' && !Array.isArray(parsed.providerKeys)) {
81
+ for (const [provider, keyVal] of Object.entries(parsed.providerKeys)) {
82
+ if (FORBIDDEN_CONFIG_KEYS.has(provider)) {
83
+ delete parsed.providerKeys[provider];
84
+ continue;
85
+ }
86
+ if (typeof keyVal === 'string' && keyVal) {
87
+ if (!isEncryptedVaultSecret(keyVal)) {
88
+ needsEncryptedResave = true;
89
+ } else {
90
+ const decrypted = decryptString(keyVal);
91
+ if (!decrypted) hadDecryptFailure = true;
92
+ parsed.providerKeys[provider] = decrypted;
93
+ }
94
+ }
95
+ }
96
+ }
97
+
98
+ if (needsEncryptedResave && !hadDecryptFailure) {
99
+ saveConfig(parsed);
100
+ }
101
+
102
+ if (typeof parsed.apiKey === 'string' && parsed.apiKey && typeof parsed.provider === 'string' && parsed.provider && !FORBIDDEN_CONFIG_KEYS.has(parsed.provider)) {
103
+ if (!parsed.providerKeys || typeof parsed.providerKeys !== 'object' || Array.isArray(parsed.providerKeys)) {
104
+ parsed.providerKeys = {};
105
+ }
106
+ if (!parsed.providerKeys[parsed.provider]) {
107
+ parsed.providerKeys[parsed.provider] = parsed.apiKey;
108
+ }
109
+ }
110
+
111
+ if (typeof parsed.model === 'string' && parsed.model.trim()) {
112
+ const canonicalModel = canonicalModelId(parsed.model);
113
+ if (canonicalModel !== parsed.model) {
114
+ parsed.model = canonicalModel;
115
+ if (!hadDecryptFailure) saveConfig(parsed);
116
+ }
117
+ }
118
+
119
+ if ((parsed.provider === 'dashscope' || parsed.provider === 'dashscope-byok') && !parsed.apiKey && !hadDecryptFailure) {
120
+ const envDetected = detectEnvironmentProvider();
121
+ if (envDetected && envDetected.apiKey) {
122
+ parsed.provider = envDetected.provider;
123
+ parsed.model = envDetected.model;
124
+ parsed.apiKey = envDetected.apiKey;
125
+ } else if (envDetected) {
126
+ parsed.provider = envDetected.provider;
127
+ parsed.model = envDetected.model;
128
+ saveConfig(parsed);
129
+ } else {
130
+ parsed.provider = '';
131
+ parsed.model = '';
132
+ saveConfig(parsed);
133
+ }
134
+ }
135
+
136
+ return parsed;
137
+ } catch (e: unknown) {
138
+ console.error('Error reading config.json:', e);
139
+ }
140
+ }
141
+
142
+ const envDetected = detectEnvironmentProvider();
143
+ const defaultConfig: CausyneConfig = {
144
+ provider: envDetected ? envDetected.provider : '',
145
+ model: envDetected ? envDetected.model : '',
146
+ apiKey: envDetected ? envDetected.apiKey : '',
147
+ autonomyMode: 'B',
148
+ tokenBudget: {
149
+ enabled: false,
150
+ maxTokensPerTask: 500000,
151
+ maxTokensPerDay: 2000000,
152
+ maxCostUsd: 5.00,
153
+ warningThreshold: 0.8,
154
+ hardStop: true
155
+ }
156
+ };
157
+ if (!hadExistingFile && (!envDetected || !envDetected.apiKey)) {
158
+ saveConfig(defaultConfig);
159
+ }
160
+ return defaultConfig;
161
+ }
162
+
163
+ function readEnvSecret(value: string | undefined): string {
164
+ return typeof value === 'string' ? value.trim() : '';
165
+ }
166
+
167
+ export function detectEnvironmentProvider(): DetectedProviderConfig | null {
168
+ const env = process.env;
169
+ const geminiKey = readEnvSecret(env.GEMINI_API_KEY) || readEnvSecret(env.GOOGLE_API_KEY);
170
+ if (geminiKey) {
171
+ return {
172
+ provider: 'gemini',
173
+ apiKey: geminiKey,
174
+ model: DEFAULT_MODEL_BY_PROVIDER.gemini || ''
175
+ };
176
+ }
177
+ const anthropicKey = readEnvSecret(env.ANTHROPIC_API_KEY);
178
+ if (anthropicKey) {
179
+ return {
180
+ provider: 'anthropic',
181
+ apiKey: anthropicKey,
182
+ model: DEFAULT_MODEL_BY_PROVIDER.anthropic || ''
183
+ };
184
+ }
185
+ const openaiKey = readEnvSecret(env.OPENAI_API_KEY);
186
+ if (openaiKey) {
187
+ return {
188
+ provider: 'openai',
189
+ apiKey: openaiKey,
190
+ model: DEFAULT_MODEL_BY_PROVIDER.openai || ''
191
+ };
192
+ }
193
+ const deepseekKey = readEnvSecret(env.DEEPSEEK_API_KEY);
194
+ if (deepseekKey) {
195
+ return {
196
+ provider: 'deepseek',
197
+ apiKey: deepseekKey,
198
+ model: DEFAULT_MODEL_BY_PROVIDER.deepseek || ''
199
+ };
200
+ }
201
+ const xaiKey = readEnvSecret(env.XAI_API_KEY) || readEnvSecret(env.GROK_API_KEY);
202
+ if (xaiKey) {
203
+ return {
204
+ provider: 'xai',
205
+ apiKey: xaiKey,
206
+ model: DEFAULT_MODEL_BY_PROVIDER.xai || ''
207
+ };
208
+ }
209
+ const moonshotKey = readEnvSecret(env.MOONSHOT_API_KEY);
210
+ if (moonshotKey) {
211
+ return {
212
+ provider: 'moonshot',
213
+ apiKey: moonshotKey,
214
+ model: DEFAULT_MODEL_BY_PROVIDER.moonshot || ''
215
+ };
216
+ }
217
+ const dashscopeKey = readEnvSecret(env.DASHSCOPE_API_KEY) || readEnvSecret(env.QWEN_API_KEY);
218
+ if (dashscopeKey) {
219
+ return {
220
+ provider: 'dashscope-byok',
221
+ apiKey: dashscopeKey,
222
+ model: DEFAULT_MODEL_BY_PROVIDER['dashscope-byok'] || ''
223
+ };
224
+ }
225
+
226
+ return detectLocalAgentProvider();
227
+ }
228
+
229
+ function checkBinarySync(binaryName: string): boolean {
230
+ if (typeof binaryName !== 'string' || !binaryName.trim() || /[\r\n\0]/.test(binaryName)) {
231
+ return false;
232
+ }
233
+ const trimmed = binaryName.trim();
234
+ if (path.isAbsolute(trimmed)) {
235
+ try {
236
+ if (!fs.statSync(trimmed).isFile()) return false;
237
+ if (process.platform !== 'win32') fs.accessSync(trimmed, fs.constants.X_OK);
238
+ return true;
239
+ } catch {
240
+ return false;
241
+ }
242
+ }
243
+ if (trimmed.includes('..') || trimmed.includes('/') || trimmed.includes('\\')) {
244
+ return false;
245
+ }
246
+ const envPath = process.env.PATH || process.env.Path || '';
247
+ const delimiter = process.platform === 'win32' ? ';' : ':';
248
+ const home = os.homedir();
249
+ const fallbackDirs = [
250
+ ...(home && path.isAbsolute(home) ? [
251
+ path.join(home, '.local', 'bin'),
252
+ path.join(home, '.antigravity', 'antigravity', 'bin'),
253
+ path.join(home, '.gemini', 'antigravity-ide', 'bin'),
254
+ path.join(home, '.opencode', 'bin')
255
+ ] : []),
256
+ '/Applications/Antigravity.app/Contents/Resources/app/bin',
257
+ '/Applications/Antigravity IDE.app/Contents/Resources/app/bin'
258
+ ];
259
+ const dirs = [...envPath.split(delimiter), ...fallbackDirs];
260
+ const extensions = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
261
+
262
+ for (const rawDir of dirs) {
263
+ const dir = rawDir.trim();
264
+ if (!dir || !path.isAbsolute(dir)) continue;
265
+ for (const ext of extensions) {
266
+ const full = path.join(dir, `${trimmed}${ext}`);
267
+ try {
268
+ if (fs.statSync(full).isFile()) {
269
+ if (process.platform !== 'win32') fs.accessSync(full, fs.constants.X_OK);
270
+ return true;
271
+ }
272
+ } catch {
273
+ // ignore inaccessible or non-executable entry
274
+ }
275
+ }
276
+ }
277
+ return false;
278
+ }
279
+
280
+ export function detectLocalAgentProvider(): DetectedProviderConfig | null {
281
+ if (checkBinarySync('agy') || checkBinarySync('antigravity')) {
282
+ return {
283
+ provider: 'antigravity',
284
+ model: DEFAULT_MODEL_BY_PROVIDER.antigravity || 'Gemini 3.8 Flash (Low)',
285
+ apiKey: ''
286
+ };
287
+ }
288
+ if (checkBinarySync('opencode')) {
289
+ return {
290
+ provider: 'acp/opencode',
291
+ model: DEFAULT_MODEL_BY_PROVIDER['acp/opencode'] || '',
292
+ apiKey: ''
293
+ };
294
+ }
295
+ if (checkBinarySync('claude')) {
296
+ return {
297
+ provider: 'acp/claude',
298
+ model: DEFAULT_MODEL_BY_PROVIDER['acp/claude'] || '',
299
+ apiKey: ''
300
+ };
301
+ }
302
+ if (checkBinarySync('codex')) {
303
+ return {
304
+ provider: 'acp/codex',
305
+ model: DEFAULT_MODEL_BY_PROVIDER['acp/codex'] || '',
306
+ apiKey: ''
307
+ };
308
+ }
309
+ if (checkBinarySync('ollama')) {
310
+ return {
311
+ provider: 'ollama',
312
+ model: DEFAULT_MODEL_BY_PROVIDER.ollama || 'llama3.3',
313
+ apiKey: ''
314
+ };
315
+ }
316
+ return null;
317
+ }
318
+
319
+ export function saveConfig(config: CausyneConfig): void {
320
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
321
+ throw new Error('saveConfig requires a plain configuration object');
322
+ }
323
+ ensureConfigDir();
324
+ const configToSave = JSON.parse(JSON.stringify(config)) as CausyneConfig;
325
+ if (typeof configToSave.apiKey === 'string' && configToSave.apiKey) {
326
+ configToSave.apiKey = encryptString(configToSave.apiKey);
327
+ }
328
+ if (configToSave.providerKeys && typeof configToSave.providerKeys === 'object' && !Array.isArray(configToSave.providerKeys)) {
329
+ for (const [provider, keyVal] of Object.entries(configToSave.providerKeys)) {
330
+ if (FORBIDDEN_CONFIG_KEYS.has(provider)) {
331
+ delete configToSave.providerKeys[provider];
332
+ continue;
333
+ }
334
+ if (typeof keyVal === 'string' && keyVal) {
335
+ configToSave.providerKeys[provider] = encryptString(keyVal);
336
+ }
337
+ }
338
+ }
339
+
340
+ const file = configFile();
341
+ atomicWriteSecretFileSync(file, JSON.stringify(configToSave, null, 2));
342
+ }
@@ -17,14 +17,25 @@ export const VAULT_GCM_IV_BYTES = 12;
17
17
  export const VAULT_LEGACY_GCM_IV_BYTES = 16;
18
18
  export const VAULT_GCM_AUTH_TAG_BYTES = 16;
19
19
  export const VAULT_ENC_PREFIX = 'ENC:';
20
+ const MAX_SECRET_HEX_CHARS = 1_048_576;
21
+ const STRICT_HEX_PATTERN = /^[0-9a-fA-F]+$/;
20
22
  export function isEncryptedVaultSecret(value) {
21
23
  return typeof value === 'string' && value.startsWith(VAULT_ENC_PREFIX);
22
24
  }
23
25
  export function ensureVaultDir(dir) {
26
+ if (typeof dir !== 'string' || !dir.trim() || dir.includes('\0')) {
27
+ throw new Error('Invalid vault directory path');
28
+ }
24
29
  const resolved = path.resolve(dir);
25
30
  if (!fs.existsSync(resolved)) {
26
31
  fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
27
32
  }
33
+ else {
34
+ const stat = fs.lstatSync(resolved);
35
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
36
+ throw new Error('Refusing to use symlink or non-directory as vault directory');
37
+ }
38
+ }
28
39
  if (process.platform !== 'win32') {
29
40
  try {
30
41
  fs.chmodSync(resolved, 0o700);
@@ -39,17 +50,34 @@ export function ensureVaultDir(dir) {
39
50
  * a unique sibling temporary file with mode `0o600` followed by atomic rename.
40
51
  */
41
52
  export function atomicWriteSecretFileSync(targetPath, content) {
53
+ if (typeof targetPath !== 'string' || !targetPath.trim() || targetPath.includes('\0')) {
54
+ throw new Error('Invalid secret target file path');
55
+ }
42
56
  const resolved = path.resolve(targetPath);
43
57
  const dir = path.dirname(resolved);
44
58
  ensureVaultDir(dir);
59
+ try {
60
+ const existing = fs.lstatSync(resolved);
61
+ if (existing.isSymbolicLink() || !existing.isFile()) {
62
+ throw new Error('Refusing to overwrite symlink or non-regular secret file');
63
+ }
64
+ }
65
+ catch (err) {
66
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
67
+ if (code !== 'ENOENT')
68
+ throw err;
69
+ }
45
70
  const suffix = `${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
46
71
  const tempPath = path.join(dir, `.${path.basename(resolved)}.${suffix}.tmp`);
47
72
  try {
48
- if (typeof content === 'string') {
49
- fs.writeFileSync(tempPath, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
73
+ const payload = typeof content === 'string' ? Buffer.from(content, 'utf8') : content;
74
+ const fd = fs.openSync(tempPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
75
+ try {
76
+ fs.writeSync(fd, payload, 0, payload.length);
77
+ fs.fsyncSync(fd);
50
78
  }
51
- else {
52
- fs.writeFileSync(tempPath, content, { mode: 0o600, flag: 'wx' });
79
+ finally {
80
+ fs.closeSync(fd);
53
81
  }
54
82
  if (process.platform !== 'win32') {
55
83
  try {
@@ -97,6 +125,10 @@ export function getOrCreateVaultKey(keyFilePath, keychainOptions) {
97
125
  }
98
126
  // If a file key already exists, migrate it cleanly into the OS Keychain
99
127
  if (fs.existsSync(resolved)) {
128
+ const stat = fs.lstatSync(resolved);
129
+ if (stat.isSymbolicLink() || !stat.isFile()) {
130
+ throw new Error('Refusing to read symlink or non-regular vault key file.');
131
+ }
100
132
  const existingFileKey = fs.readFileSync(resolved);
101
133
  if (existingFileKey.length === VAULT_KEY_BYTES) {
102
134
  const stored = saveVaultKeyToKeychain(vaultDir, existingFileKey, keychainOptions);
@@ -117,6 +149,10 @@ export function getOrCreateVaultKey(keyFilePath, keychainOptions) {
117
149
  // Non-strict (`on`/`auto`) degrades cleanly to atomic 0600 file storage below
118
150
  }
119
151
  if (fs.existsSync(resolved)) {
152
+ const stat = fs.lstatSync(resolved);
153
+ if (stat.isSymbolicLink() || !stat.isFile()) {
154
+ throw new Error('Refusing to read symlink or non-regular vault key file.');
155
+ }
120
156
  if (process.platform !== 'win32') {
121
157
  try {
122
158
  fs.chmodSync(resolved, 0o600);
@@ -148,6 +184,18 @@ export function getOrCreateVaultKey(keyFilePath, keychainOptions) {
148
184
  catch (err) {
149
185
  const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
150
186
  if (code === 'EEXIST') {
187
+ const stat = fs.lstatSync(resolved);
188
+ if (stat.isSymbolicLink() || !stat.isFile()) {
189
+ throw new Error('Refusing to read symlink or non-regular vault key file.');
190
+ }
191
+ if (process.platform !== 'win32') {
192
+ try {
193
+ fs.chmodSync(resolved, 0o600);
194
+ }
195
+ catch {
196
+ // Ignore chmod errors
197
+ }
198
+ }
151
199
  const raced = fs.readFileSync(resolved);
152
200
  if (raced.length === VAULT_KEY_BYTES)
153
201
  return raced;
@@ -159,25 +207,35 @@ export function getOrCreateVaultKey(keyFilePath, keychainOptions) {
159
207
  * Encrypts a plaintext secret using AES-256-GCM with a NIST-standard 12-byte IV.
160
208
  */
161
209
  export function encryptVaultSecret(text, keyFilePath) {
162
- if (!text)
210
+ if (typeof text !== 'string' || !text)
163
211
  return text;
164
212
  if (isEncryptedVaultSecret(text))
165
213
  return text;
166
214
  const key = getOrCreateVaultKey(keyFilePath);
167
- const iv = crypto.randomBytes(VAULT_GCM_IV_BYTES);
168
- const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
169
- let encrypted = cipher.update(text, 'utf8', 'hex');
170
- encrypted += cipher.final('hex');
171
- const authTag = cipher.getAuthTag().toString('hex');
172
- return `${VAULT_ENC_PREFIX}${iv.toString('hex')}:${authTag}:${encrypted}`;
215
+ try {
216
+ const iv = crypto.randomBytes(VAULT_GCM_IV_BYTES);
217
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
218
+ let encrypted = cipher.update(text, 'utf8', 'hex');
219
+ encrypted += cipher.final('hex');
220
+ const authTag = cipher.getAuthTag().toString('hex');
221
+ return `${VAULT_ENC_PREFIX}${iv.toString('hex')}:${authTag}:${encrypted}`;
222
+ }
223
+ finally {
224
+ key.fill(0);
225
+ }
173
226
  }
174
227
  /**
175
228
  * Decrypts an `ENC:` secret produced with either the standard 12-byte GCM IV
176
229
  * or legacy 16-byte GCM IV. Returns empty string on authentication failure.
177
230
  */
178
231
  export function decryptVaultSecret(encryptedText, keyFilePath) {
179
- if (!encryptedText || !isEncryptedVaultSecret(encryptedText))
232
+ if (typeof encryptedText !== 'string' || !encryptedText)
233
+ return '';
234
+ if (!isEncryptedVaultSecret(encryptedText))
180
235
  return encryptedText;
236
+ if (encryptedText.length > MAX_SECRET_HEX_CHARS)
237
+ return '';
238
+ let key = null;
181
239
  try {
182
240
  const parts = encryptedText.split(':');
183
241
  if (parts.length !== 4)
@@ -185,13 +243,18 @@ export function decryptVaultSecret(encryptedText, keyFilePath) {
185
243
  const ivHex = parts[1] ?? '';
186
244
  const authTagHex = parts[2] ?? '';
187
245
  const ciphertextHex = parts[3] ?? '';
188
- const iv = Buffer.from(ivHex, 'hex');
189
- const authTag = Buffer.from(authTagHex, 'hex');
190
- if ((iv.length !== VAULT_GCM_IV_BYTES && iv.length !== VAULT_LEGACY_GCM_IV_BYTES) ||
191
- authTag.length !== VAULT_GCM_AUTH_TAG_BYTES) {
246
+ if (!STRICT_HEX_PATTERN.test(ivHex) ||
247
+ !STRICT_HEX_PATTERN.test(authTagHex) ||
248
+ (ciphertextHex.length > 0 && (ciphertextHex.length % 2 !== 0 || !STRICT_HEX_PATTERN.test(ciphertextHex)))) {
249
+ return '';
250
+ }
251
+ if ((ivHex.length !== VAULT_GCM_IV_BYTES * 2 && ivHex.length !== VAULT_LEGACY_GCM_IV_BYTES * 2) ||
252
+ authTagHex.length !== VAULT_GCM_AUTH_TAG_BYTES * 2) {
192
253
  return '';
193
254
  }
194
- const key = getOrCreateVaultKey(keyFilePath);
255
+ const iv = Buffer.from(ivHex, 'hex');
256
+ const authTag = Buffer.from(authTagHex, 'hex');
257
+ key = getOrCreateVaultKey(keyFilePath);
195
258
  const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
196
259
  decipher.setAuthTag(authTag);
197
260
  let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
@@ -201,4 +264,8 @@ export function decryptVaultSecret(encryptedText, keyFilePath) {
201
264
  catch {
202
265
  return '';
203
266
  }
267
+ finally {
268
+ if (key)
269
+ key.fill(0);
270
+ }
204
271
  }