@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.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
+ }
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Causyne Agent — Atomic Config Vault & AES-256-GCM Secret Protection
3
+ *
4
+ * Hardens local BYOK credential storage (`~/.causyne/config.json` & `.vault_key`):
5
+ * 1. Atomic write-temp-chmod-rename (`atomicWriteSecretFileSync`) to prevent
6
+ * truncated/corrupted config files on crash or concurrent writes.
7
+ * 2. Strict `0o700` vault directory and `0o600` secret file permissions on POSIX.
8
+ * 3. NIST SP 800-38D standard 12-byte (96-bit) IV for new AES-256-GCM ciphertexts,
9
+ * while preserving full decryption compatibility with legacy 16-byte IV records.
10
+ */
11
+ import crypto from 'node:crypto';
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { loadVaultKeyFromKeychain, resolveKeychainMode, saveVaultKeyToKeychain } from './osKeychain.js';
15
+ export const VAULT_KEY_BYTES = 32;
16
+ export const VAULT_GCM_IV_BYTES = 12;
17
+ export const VAULT_LEGACY_GCM_IV_BYTES = 16;
18
+ export const VAULT_GCM_AUTH_TAG_BYTES = 16;
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]+$/;
22
+ export function isEncryptedVaultSecret(value) {
23
+ return typeof value === 'string' && value.startsWith(VAULT_ENC_PREFIX);
24
+ }
25
+ export function ensureVaultDir(dir) {
26
+ if (typeof dir !== 'string' || !dir.trim() || dir.includes('\0')) {
27
+ throw new Error('Invalid vault directory path');
28
+ }
29
+ const resolved = path.resolve(dir);
30
+ if (!fs.existsSync(resolved)) {
31
+ fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
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
+ }
39
+ if (process.platform !== 'win32') {
40
+ try {
41
+ fs.chmodSync(resolved, 0o700);
42
+ }
43
+ catch {
44
+ // Best-effort permission tightening on platforms that restrict chmod
45
+ }
46
+ }
47
+ }
48
+ /**
49
+ * Atomically writes a secret-bearing file (`config.json` or `.vault_key`) using
50
+ * a unique sibling temporary file with mode `0o600` followed by atomic rename.
51
+ */
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
+ }
56
+ const resolved = path.resolve(targetPath);
57
+ const dir = path.dirname(resolved);
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
+ }
70
+ const suffix = `${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
71
+ const tempPath = path.join(dir, `.${path.basename(resolved)}.${suffix}.tmp`);
72
+ try {
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);
78
+ }
79
+ finally {
80
+ fs.closeSync(fd);
81
+ }
82
+ if (process.platform !== 'win32') {
83
+ try {
84
+ fs.chmodSync(tempPath, 0o600);
85
+ }
86
+ catch {
87
+ // Ignore chmod errors on non-POSIX mounts
88
+ }
89
+ }
90
+ fs.renameSync(tempPath, resolved);
91
+ if (process.platform !== 'win32') {
92
+ try {
93
+ fs.chmodSync(resolved, 0o600);
94
+ }
95
+ catch {
96
+ // Ignore chmod errors on non-POSIX mounts
97
+ }
98
+ }
99
+ }
100
+ catch (err) {
101
+ try {
102
+ if (fs.existsSync(tempPath))
103
+ fs.unlinkSync(tempPath);
104
+ }
105
+ catch {
106
+ // Ignore temp cleanup failure
107
+ }
108
+ throw err;
109
+ }
110
+ }
111
+ /**
112
+ * Loads or atomically initializes the 256-bit local vault key with `0o600` permissions.
113
+ * When `CAUSYNE_KEYCHAIN=on|auto|strict` is enabled, uses the OS Keychain backend
114
+ * first (migrating an existing file key if present) and fails closed on `strict`.
115
+ */
116
+ export function getOrCreateVaultKey(keyFilePath, keychainOptions) {
117
+ const resolved = path.resolve(keyFilePath);
118
+ const vaultDir = path.dirname(resolved);
119
+ ensureVaultDir(vaultDir);
120
+ const keychainMode = resolveKeychainMode(keychainOptions?.env ?? process.env);
121
+ if (keychainMode !== 'off') {
122
+ const fromKeychain = loadVaultKeyFromKeychain(vaultDir, keychainOptions);
123
+ if (fromKeychain && fromKeychain.length === VAULT_KEY_BYTES) {
124
+ return fromKeychain;
125
+ }
126
+ // If a file key already exists, migrate it cleanly into the OS Keychain
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
+ }
132
+ const existingFileKey = fs.readFileSync(resolved);
133
+ if (existingFileKey.length === VAULT_KEY_BYTES) {
134
+ const stored = saveVaultKeyToKeychain(vaultDir, existingFileKey, keychainOptions);
135
+ if (stored || keychainMode !== 'strict') {
136
+ return existingFileKey;
137
+ }
138
+ throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but storing the vault key failed.');
139
+ }
140
+ }
141
+ // Generate a fresh key and persist into OS Keychain
142
+ const generated = crypto.randomBytes(VAULT_KEY_BYTES);
143
+ if (saveVaultKeyToKeychain(vaultDir, generated, keychainOptions)) {
144
+ return generated;
145
+ }
146
+ if (keychainMode === 'strict') {
147
+ throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but OS keychain storage is unavailable.');
148
+ }
149
+ // Non-strict (`on`/`auto`) degrades cleanly to atomic 0600 file storage below
150
+ }
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
+ }
156
+ if (process.platform !== 'win32') {
157
+ try {
158
+ fs.chmodSync(resolved, 0o600);
159
+ }
160
+ catch {
161
+ // Ignore chmod errors on non-POSIX mounts
162
+ }
163
+ }
164
+ const existing = fs.readFileSync(resolved);
165
+ if (existing.length !== VAULT_KEY_BYTES) {
166
+ throw new Error(`Invalid vault key length (${existing.length} bytes; expected ${VAULT_KEY_BYTES}).`);
167
+ }
168
+ return existing;
169
+ }
170
+ const freshKey = crypto.randomBytes(VAULT_KEY_BYTES);
171
+ try {
172
+ // Exclusive create first so concurrent startups do not clobber each other's key
173
+ fs.writeFileSync(resolved, freshKey, { mode: 0o600, flag: 'wx' });
174
+ if (process.platform !== 'win32') {
175
+ try {
176
+ fs.chmodSync(resolved, 0o600);
177
+ }
178
+ catch {
179
+ // Ignore chmod errors
180
+ }
181
+ }
182
+ return freshKey;
183
+ }
184
+ catch (err) {
185
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
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
+ }
199
+ const raced = fs.readFileSync(resolved);
200
+ if (raced.length === VAULT_KEY_BYTES)
201
+ return raced;
202
+ }
203
+ throw err;
204
+ }
205
+ }
206
+ /**
207
+ * Encrypts a plaintext secret using AES-256-GCM with a NIST-standard 12-byte IV.
208
+ */
209
+ export function encryptVaultSecret(text, keyFilePath) {
210
+ if (typeof text !== 'string' || !text)
211
+ return text;
212
+ if (isEncryptedVaultSecret(text))
213
+ return text;
214
+ const key = getOrCreateVaultKey(keyFilePath);
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
+ }
226
+ }
227
+ /**
228
+ * Decrypts an `ENC:` secret produced with either the standard 12-byte GCM IV
229
+ * or legacy 16-byte GCM IV. Returns empty string on authentication failure.
230
+ */
231
+ export function decryptVaultSecret(encryptedText, keyFilePath) {
232
+ if (typeof encryptedText !== 'string' || !encryptedText)
233
+ return '';
234
+ if (!isEncryptedVaultSecret(encryptedText))
235
+ return encryptedText;
236
+ if (encryptedText.length > MAX_SECRET_HEX_CHARS)
237
+ return '';
238
+ let key = null;
239
+ try {
240
+ const parts = encryptedText.split(':');
241
+ if (parts.length !== 4)
242
+ return '';
243
+ const ivHex = parts[1] ?? '';
244
+ const authTagHex = parts[2] ?? '';
245
+ const ciphertextHex = parts[3] ?? '';
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) {
253
+ return '';
254
+ }
255
+ const iv = Buffer.from(ivHex, 'hex');
256
+ const authTag = Buffer.from(authTagHex, 'hex');
257
+ key = getOrCreateVaultKey(keyFilePath);
258
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
259
+ decipher.setAuthTag(authTag);
260
+ let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
261
+ decrypted += decipher.final('utf8');
262
+ return decrypted;
263
+ }
264
+ catch {
265
+ return '';
266
+ }
267
+ finally {
268
+ if (key)
269
+ key.fill(0);
270
+ }
271
+ }