@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
@@ -0,0 +1,40 @@
1
+ import type { LLMProvider, ProviderConfig } from './base.js';
2
+ import { OpenAIProvider } from './openai.js';
3
+ import { AnthropicProvider } from './anthropic.js';
4
+ import { GeminiProvider } from './gemini.js';
5
+ import { OllamaProvider } from './ollama.js';
6
+ import { OpenAICompatibleProvider } from './openai-compatible.js';
7
+ import { DeepSeekProvider } from './deepseek.js';
8
+ import { QwenByokProvider } from './qwen-byok.js';
9
+ import { DashscopeByokProvider } from './dashscope-byok.js';
10
+ import { XAIProvider } from './xai.js';
11
+ import { MoonshotProvider } from './moonshot.js';
12
+ import { MuseProvider } from './muse.js';
13
+ import { AcpProvider, isAcpProvider } from './acp.js';
14
+ import { PiProvider, isPiProvider } from './pi.js';
15
+ import { AntigravityProvider, isAntigravityProvider } from './antigravity.js';
16
+ import { OpenRouterProvider } from './openrouter.js';
17
+
18
+ export function createProvider(config: ProviderConfig | null | undefined): LLMProvider {
19
+ if (!config || typeof config !== 'object') {
20
+ throw new Error('API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.');
21
+ }
22
+ const p = typeof config.provider === 'string' ? config.provider.trim().toLowerCase() : undefined;
23
+ if (p === 'openai') return new OpenAIProvider(config);
24
+ if (p === 'anthropic') return new AnthropicProvider(config);
25
+ if (p === 'gemini') return new GeminiProvider(config);
26
+ if (p === 'ollama') return new OllamaProvider(config);
27
+ if (p === 'deepseek') return new DeepSeekProvider(config);
28
+ if (p === 'dashscope-byok' || p === 'dashscope') return new DashscopeByokProvider(config);
29
+ if (p === 'qwen') return new QwenByokProvider(config);
30
+ if (p === 'openai-compatible') return new OpenAICompatibleProvider(config);
31
+ if (p === 'xai' || p === 'grok') return new XAIProvider(config);
32
+ if (p === 'moonshot' || p === 'kimi') return new MoonshotProvider(config);
33
+ if (p === 'muse' || p === 'meta') return new MuseProvider(config);
34
+ if (p === 'openrouter' || p === 'openrouter-free') return new OpenRouterProvider(config);
35
+ if (isAcpProvider(p)) return new AcpProvider(config);
36
+ if (isPiProvider(p)) return new PiProvider(config);
37
+ if (isAntigravityProvider(p)) return new AntigravityProvider(config);
38
+
39
+ throw new Error('API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.');
40
+ }
@@ -1,270 +1,246 @@
1
1
  import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider, mimeTypeForAudioFormat } from './base.js';
4
- import {
5
- scanAndAdaptToolsForProvider,
6
- decodeFreeFormArguments,
7
- adaptSchemaForGemini,
8
- isEmptyObjectSchema,
9
- normalizeToolName
10
- } from '../tools/toolScanner.js';
11
- import {
12
- safeParseJsonObject,
13
- sanitizeProviderToolId,
14
- serializeAndDecodeArguments
15
- } from './wireNormalizer.js';
16
-
4
+ import { scanAndAdaptToolsForProvider, adaptSchemaForGemini, isEmptyObjectSchema, normalizeToolName } from '../tools/toolScanner.js';
5
+ import { safeParseJsonObject, sanitizeProviderToolId, serializeAndDecodeArguments } from './wireNormalizer.js';
6
+ import { requireApiKey, resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
7
+ import { streamGeminiGenerateContent, wantsStreaming } from './byokStream.js';
17
8
  export { adaptSchemaForGemini, isEmptyObjectSchema };
18
-
19
- // Gemini's FunctionDeclaration schema is an OpenAPI subset, and it is strict in
20
- // two ways that matter here:
21
- // 1. `additionalProperties` is not part of the subset.
22
- // 2. An OBJECT that declares no properties is rejected.
23
- // Crucially, one bad declaration fails the *entire* request — so a single
24
- // free-form object anywhere in the 69-tool catalogue takes every tool down with
25
- // it. `web_fetch.headers` is exactly that shape and web_fetch is a CORE tool,
26
- // which meant Gemini could not complete step one of any task at all.
27
- //
28
- // Rather than delete those parameters and lose the capability, free-form maps
29
- // travel as JSON strings and are decoded again on the way back, so the tool
30
- // still receives a real object. The paths that were rewritten are recorded per
31
- // tool so the decode knows exactly where to look. Handled universally via toolScanner.
32
-
33
- function applyAtPath(node, path, transform) {
34
- if (node === null || typeof node !== 'object') return;
35
-
36
- const [head, ...rest] = path;
37
-
38
- if (head === '[]') {
39
- if (!Array.isArray(node)) return;
40
- for (const entry of node) applyAtPath(entry, rest, transform);
41
- return;
42
- }
43
-
44
- if (rest.length === 0) {
45
- if (head in node) node[head] = transform(node[head]);
46
- return;
47
- }
48
-
49
- applyAtPath(node[head], rest, transform);
50
- }
51
-
52
- /**
53
- * Translate Gemini's `usageMetadata` into the OpenAI-shaped object that
54
- * `LLMProvider.normalizeUsage()` consumes, so every provider ends up on one
55
- * normalisation path instead of Gemini hand-rolling its own.
56
- *
57
- * TWO BUGS THIS FIXES, both in the cost the user is shown:
58
- *
59
- * 1. `cachedContentTokenCount` was dropped entirely. Gemini caches implicitly
60
- * on a stable prefix, so the cache WAS working and `calculateCost()` IS
61
- * cache-aware — it was simply fed a zero, and every cached token was
62
- * displayed at the full input rate instead of 0.5x. Overstating the bill is
63
- * how a user concludes Causyne is expensive and goes direct instead.
64
- *
65
- * 2. `thoughtsTokenCount` was dropped, and thinking tokens ARE billed as
66
- * output ("Response pricing is the sum of output tokens and thinking
67
- * tokens"). That understated the bill — the worse direction, because the
68
- * real invoice then exceeds what Causyne promised.
69
- *
70
- * WHY `totalTokenCount` IS THE ANCHOR: whether `thoughtsTokenCount` is already
71
- * folded into `candidatesTokenCount` DIFFERS BY BACKEND — it is on the Gemini
72
- * API and is not on Vertex AI, and reports exist of the Gemini API behaving
73
- * both ways across model versions. Deriving completion as `total - prompt` is
74
- * correct under either convention; adding thoughts to candidates is correct
75
- * under only one and double-counts under the other. The sum is used only when
76
- * the total is missing or incoherent, where overstating is the safer error.
77
- *
78
- * @param {object} usageMetadata Gemini's usage block, possibly undefined.
79
- * @returns {object} OpenAI-shaped usage for normalizeUsage().
80
- */
81
9
  export function geminiUsageToOpenAIShape(usageMetadata) {
82
- const prompt = usageMetadata?.promptTokenCount || 0;
83
- const candidates = usageMetadata?.candidatesTokenCount || 0;
84
- const thoughts = usageMetadata?.thoughtsTokenCount || 0;
85
- const total = usageMetadata?.totalTokenCount || 0;
86
-
87
- const completion = total > prompt ? total - prompt : candidates + thoughts;
88
-
89
- return {
90
- prompt_tokens: prompt,
91
- completion_tokens: completion,
92
- // normalizeUsage() clamps this to prompt_tokens, which also protects
93
- // against a backend that reports the cached count OUTSIDE the prompt total.
94
- prompt_tokens_details: { cached_tokens: usageMetadata?.cachedContentTokenCount || 0 }
95
- };
10
+ const nonNeg = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
11
+ const prompt = nonNeg(usageMetadata?.['promptTokenCount']);
12
+ const candidates = nonNeg(usageMetadata?.['candidatesTokenCount']);
13
+ const thoughts = nonNeg(usageMetadata?.['thoughtsTokenCount']);
14
+ const total = nonNeg(usageMetadata?.['totalTokenCount']);
15
+ const cached = nonNeg(usageMetadata?.['cachedContentTokenCount']);
16
+ const completion = total > prompt ? total - prompt : candidates + thoughts;
17
+ return {
18
+ prompt_tokens: prompt,
19
+ completion_tokens: completion,
20
+ prompt_tokens_details: { cached_tokens: cached }
21
+ };
96
22
  }
97
-
98
23
  export class GeminiProvider extends LLMProvider {
99
- constructor(config) {
100
- super(config);
101
- this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['gemini']);
102
- this.baseUrl = `https://generativelanguage.googleapis.com/v1beta/models/${this.model}:generateContent?key=${this.apiKey}`;
103
- // Every Gemini model from 1.5 onward accepts image input.
104
- this.visionModels = ['gemini-'];
105
- this.imagePayloadFormat = 'gemini';
106
- // Gemini takes audio the same way it takes images — inlineData with a real
107
- // MIME type — across the whole gemini- family, and accepts m4a/aac natively,
108
-
109
- // smaller than WAV, so it clears the transport ceiling far more often.
110
- this.audioModels = ['gemini-'];
111
- this.audioPayloadFormat = 'gemini';
112
- }
113
-
114
- async chat(messages, options = {}) {
115
- messages = this.prepareMessages(messages);
116
- // Map OpenAI messages to Gemini contents.
117
- // System blocks ACCUMULATE. Assigning instead of appending meant that with
118
- // the agent's three-block system stack only the last block survived: the
119
- // core SYSTEM_PROMPT, the capability-pack catalogue and every playbook were
120
- // silently discarded on every single Gemini request.
121
- const systemParts = [];
122
- const contents = [];
123
-
124
- for (const msg of messages) {
125
- if (msg.role === 'system') {
126
- const text = typeof msg.content === 'string'
127
- ? msg.content
128
- : JSON.stringify(msg.content);
129
- if (text) systemParts.push({ text });
130
- continue;
131
- }
132
-
133
- const role = msg.role === 'assistant' ? 'model' : 'user';
134
-
135
- if (msg.tool_calls) {
136
- // The assistant's own words travel with its calls. Dropping the text
137
- // meant the model's stated reasoning never re-entered the history.
138
- const parts = [];
139
- if (msg.content) parts.push({ text: String(msg.content) });
140
- for (const tc of msg.tool_calls) {
141
- parts.push({
142
- functionCall: {
143
- name: normalizeToolName(tc.function?.name || ''),
144
- args: safeParseJsonObject(tc.function?.arguments)
24
+ allowInsecureHttp;
25
+ constructor(config = {}) {
26
+ super(config);
27
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['gemini']) || '');
28
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
29
+ const customUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
30
+ if (customUrl) {
31
+ try {
32
+ const parsed = new URL(customUrl);
33
+ parsed.searchParams.delete('key');
34
+ this.baseUrl = parsed.toString();
35
+ }
36
+ catch {
37
+ this.baseUrl = customUrl;
145
38
  }
146
- });
147
39
  }
148
- contents.push({ role, parts });
149
- } else if (msg.role === 'tool') {
150
- // Batch consecutive tool responses into a single 'user' message for parallel calls.
151
- const responsePart = {
152
- functionResponse: {
153
- name: normalizeToolName(msg.name || ''),
154
- response: { result: msg.content ?? '' }
155
- }
156
- };
157
- const lastEntry = contents[contents.length - 1];
158
- if (lastEntry && lastEntry.role === 'user' && Array.isArray(lastEntry.parts) && lastEntry.parts[0]?.functionResponse) {
159
- lastEntry.parts.push(responsePart);
160
- } else {
161
- contents.push({
162
- role: 'user',
163
- parts: [responsePart]
164
- });
40
+ else {
41
+ this.baseUrl = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(this.model)}:generateContent`;
165
42
  }
166
- } else {
167
- if (Array.isArray(msg.content)) {
168
- const mappedParts = msg.content.map(part => {
169
- if (part.type === 'text') return { text: part.text };
170
- if (part.type === 'image_url') {
171
- const b64 = part.image_url.url.split('base64,')[1];
172
- const mime = part.image_url.url.split(';')[0].replace('data:', '');
173
- return { inlineData: { mimeType: mime, data: b64 } };
43
+ this.visionModels = ['gemini-'];
44
+ this.imagePayloadFormat = 'gemini';
45
+ this.audioModels = ['gemini-'];
46
+ this.audioPayloadFormat = 'gemini';
47
+ }
48
+ async chat(messages, options = {}) {
49
+ messages = this.prepareMessages(messages);
50
+ const systemParts = [];
51
+ const contents = [];
52
+ const toolNameById = new Map();
53
+ for (const msg of messages) {
54
+ if (msg.role === 'system') {
55
+ const text = typeof msg.content === 'string'
56
+ ? msg.content
57
+ : JSON.stringify(msg.content);
58
+ if (text)
59
+ systemParts.push({ text });
60
+ continue;
174
61
  }
175
- // Anthropic-shaped image block. Without this branch it fell through
176
- // to the empty-text default and the image vanished silently.
177
- if (part.type === 'image' && part.source?.type === 'base64') {
178
- return { inlineData: { mimeType: part.source.media_type, data: part.source.data } };
62
+ const role = msg.role === 'assistant' ? 'model' : 'user';
63
+ if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
64
+ const parts = [];
65
+ if (typeof msg.content === 'string' && msg.content)
66
+ parts.push({ text: msg.content });
67
+ for (const tc of msg.tool_calls) {
68
+ if (!tc || typeof tc !== 'object')
69
+ continue;
70
+ const normalizedName = normalizeToolName(tc.function?.name || '');
71
+ if (!normalizedName)
72
+ continue;
73
+ if (typeof tc.id === 'string' && tc.id)
74
+ toolNameById.set(tc.id, normalizedName);
75
+ const fcPart = {
76
+ functionCall: {
77
+ name: normalizedName,
78
+ args: safeParseJsonObject(tc.function?.arguments)
79
+ }
80
+ };
81
+ const sig = typeof tc.thoughtSignature === 'string' ? tc.thoughtSignature : (typeof tc.thought_signature === 'string' ? tc.thought_signature : undefined);
82
+ if (sig)
83
+ fcPart['thoughtSignature'] = sig;
84
+ parts.push(fcPart);
85
+ }
86
+ if (parts.length > 0)
87
+ contents.push({ role, parts });
179
88
  }
180
- // Audio normalised by prepareMessages already arrives as inlineData;
181
- // this branch covers an input_audio block replayed from history that
182
- // predates the normaliser. The MIME type is derived from the clip's
183
- // real container instead of the old hardcoded audio/mp4, which
184
-
185
- if (part.type === 'input_audio') {
186
- return {
187
- inlineData: {
188
- mimeType: mimeTypeForAudioFormat(part.input_audio?.format),
189
- data: part.input_audio?.data
89
+ else if (msg.role === 'tool') {
90
+ const resolvedName = normalizeToolName(msg.name || (typeof msg.tool_call_id === 'string' ? toolNameById.get(msg.tool_call_id) : '') || 'tool');
91
+ const responsePart = {
92
+ functionResponse: {
93
+ name: resolvedName,
94
+ response: { result: msg.content ?? '' }
95
+ }
96
+ };
97
+ const lastEntry = contents[contents.length - 1];
98
+ if (lastEntry && lastEntry.role === 'user' && Array.isArray(lastEntry.parts) && lastEntry.parts[0]?.['functionResponse']) {
99
+ lastEntry.parts.push(responsePart);
100
+ }
101
+ else {
102
+ contents.push({
103
+ role: 'user',
104
+ parts: [responsePart]
105
+ });
106
+ }
107
+ }
108
+ else {
109
+ if (Array.isArray(msg.content)) {
110
+ const rawMapped = msg.content.map((part) => {
111
+ if (!part || typeof part !== 'object')
112
+ return null;
113
+ if (part.type === 'text')
114
+ return { text: typeof part.text === 'string' ? part.text : '' };
115
+ if (part.type === 'image_url') {
116
+ const rawUrl = typeof part.image_url?.url === 'string' ? part.image_url.url : '';
117
+ const marker = rawUrl.indexOf('base64,');
118
+ if (rawUrl.startsWith('data:') && marker !== -1) {
119
+ const mime = rawUrl.slice(5, marker).split(';')[0] || 'image/png';
120
+ const b64 = rawUrl.slice(marker + 7);
121
+ if (b64)
122
+ return { inlineData: { mimeType: mime, data: b64 } };
123
+ }
124
+ return { text: '' };
125
+ }
126
+ if (part.type === 'image' && part.source?.type === 'base64') {
127
+ return { inlineData: { mimeType: part.source.media_type, data: part.source.data } };
128
+ }
129
+ if (part.type === 'input_audio') {
130
+ return {
131
+ inlineData: {
132
+ mimeType: mimeTypeForAudioFormat(part.input_audio?.format),
133
+ data: part.input_audio?.data
134
+ }
135
+ };
136
+ }
137
+ if (part.inlineData)
138
+ return part;
139
+ return null;
140
+ }).filter((p) => p !== null);
141
+ const mappedParts = rawMapped.length > 0 ? rawMapped : [{ text: '' }];
142
+ contents.push({ role, parts: mappedParts });
143
+ }
144
+ else {
145
+ const scalar = typeof msg.content === 'string' ? msg.content : (msg.content == null ? '' : JSON.stringify(msg.content));
146
+ contents.push({ role, parts: [{ text: scalar }] });
190
147
  }
191
- };
192
148
  }
193
- if (part.inlineData) return part;
194
- return { text: '' };
195
- });
196
- contents.push({ role, parts: mappedParts });
197
- } else {
198
- contents.push({ role, parts: [{ text: msg.content ?? '' }] });
199
149
  }
200
- }
201
- }
202
-
203
- const payload = {
204
- contents,
205
- generationConfig: {
206
- temperature: options.temperature || 0.1,
207
- }
208
- };
209
-
210
- if (systemParts.length > 0) {
211
- payload.systemInstruction = { parts: systemParts };
212
- }
213
-
214
- // Map tools using the universal toolScanner
215
- let freeFormPaths = new Map();
216
-
217
- if (options.tools && options.tools.length > 0) {
218
- const scanReport = scanAndAdaptToolsForProvider(options.tools, 'gemini');
219
- payload.tools = [{
220
- functionDeclarations: scanReport.adaptedTools
221
- }];
222
- freeFormPaths = scanReport.freeFormPaths;
223
- }
224
-
225
- const response = await fetch(this.baseUrl, {
226
- method: 'POST',
227
- headers: { 'Content-Type': 'application/json' },
228
- body: JSON.stringify(payload)
229
- });
230
-
231
- if (!response.ok) {
232
- const errorData = await response.text();
233
- throw new Error(`Gemini API Error (${response.status}): ${errorData}`);
234
- }
235
-
236
- const data = await response.json();
237
-
238
- const firstCandidate = data.candidates?.[0];
239
- if (!firstCandidate) {
240
- throw new Error('No candidate returned from Gemini');
241
- }
242
-
243
- let content = '';
244
- let toolCalls = [];
245
- const candidateParts = Array.isArray(firstCandidate.content?.parts) ? firstCandidate.content.parts : [];
246
-
247
- for (const part of candidateParts) {
248
- if (part.text) {
249
- content += part.text;
250
- } else if (part.functionCall) {
251
- const callName = normalizeToolName(part.functionCall.name || '');
252
- const serializedArgs = serializeAndDecodeArguments(part.functionCall.args || {}, callName, freeFormPaths);
253
- toolCalls.push({
254
- id: sanitizeProviderToolId(part.functionCall.id, 'call_gemini', toolCalls.length),
255
- type: 'function',
256
- function: {
257
- name: callName,
258
- arguments: serializedArgs
259
- }
260
- });
261
- }
150
+ const apiKey = requireApiKey(this.apiKey, 'Gemini');
151
+ const generationConfig = {
152
+ temperature: resolveTemperature(options.temperature, 0.1)
153
+ };
154
+ if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
155
+ generationConfig['maxOutputTokens'] = Math.floor(options.maxTokens);
156
+ }
157
+ if (options.jsonMode) {
158
+ generationConfig['responseMimeType'] = 'application/json';
159
+ }
160
+ const payload = {
161
+ contents,
162
+ generationConfig
163
+ };
164
+ if (systemParts.length > 0) {
165
+ payload['systemInstruction'] = { parts: systemParts };
166
+ }
167
+ let freeFormPaths = new Map();
168
+ if (options.tools && options.tools.length > 0) {
169
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'gemini');
170
+ payload['tools'] = [{
171
+ functionDeclarations: scanReport.adaptedTools
172
+ }];
173
+ freeFormPaths = scanReport.freeFormPaths;
174
+ }
175
+ const endpoint = this.baseUrl || `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(this.model)}:generateContent`;
176
+ const requestOpts = {
177
+ url: endpoint,
178
+ method: 'POST',
179
+ headers: {
180
+ 'Content-Type': 'application/json',
181
+ 'x-goog-api-key': apiKey
182
+ },
183
+ signal: options.signal,
184
+ timeoutMs: options.timeoutMs,
185
+ providerLabel: 'Gemini',
186
+ secrets: [apiKey],
187
+ hasApiKey: true,
188
+ allowInsecureHttp: this.allowInsecureHttp
189
+ };
190
+ const data = wantsStreaming(options)
191
+ ? await streamGeminiGenerateContent({
192
+ ...requestOpts,
193
+ payload,
194
+ onChunk: options.onChunk,
195
+ onReasoningChunk: options.onReasoningChunk
196
+ })
197
+ : await safeProviderFetchJson({
198
+ ...requestOpts,
199
+ body: JSON.stringify(payload)
200
+ });
201
+ const firstCandidate = data['candidates']?.[0];
202
+ if (!firstCandidate) {
203
+ const blockReason = data['promptFeedback']?.blockReason;
204
+ const detail = typeof blockReason === 'string' && blockReason ? ` (blockReason: ${blockReason})` : '';
205
+ throw new Error(`No candidate returned from Gemini${detail}`);
206
+ }
207
+ let content = '';
208
+ let reasoningContent = typeof data['reasoningContent'] === 'string' ? data['reasoningContent'] : '';
209
+ const toolCalls = [];
210
+ const candidateParts = Array.isArray(firstCandidate.content?.parts) ? firstCandidate.content.parts : [];
211
+ for (const part of candidateParts) {
212
+ if (!part || typeof part !== 'object')
213
+ continue;
214
+ if (typeof part.text === 'string' && part.text) {
215
+ if (part.thought === true) {
216
+ reasoningContent += part.text;
217
+ }
218
+ else {
219
+ content += part.text;
220
+ }
221
+ }
222
+ else if (part.functionCall && typeof part.functionCall === 'object') {
223
+ const callName = normalizeToolName(part.functionCall.name || '');
224
+ if (!callName)
225
+ continue;
226
+ const serializedArgs = serializeAndDecodeArguments(part.functionCall.args || {}, callName, freeFormPaths);
227
+ const sig = typeof part.thoughtSignature === 'string' ? part.thoughtSignature : (typeof part.thought_signature === 'string' ? part.thought_signature : undefined);
228
+ toolCalls.push({
229
+ id: sanitizeProviderToolId(part.functionCall.id, 'call_gemini', toolCalls.length),
230
+ type: 'function',
231
+ function: {
232
+ name: callName,
233
+ arguments: serializedArgs
234
+ },
235
+ ...(sig ? { thoughtSignature: sig } : {})
236
+ });
237
+ }
238
+ }
239
+ return {
240
+ content: content.trim(),
241
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
242
+ ...(reasoningContent.trim() ? { reasoningContent: reasoningContent.trim() } : {}),
243
+ usage: this.normalizeUsage(geminiUsageToOpenAIShape(data['usageMetadata']))
244
+ };
262
245
  }
263
-
264
- return {
265
- content: content.trim(),
266
- toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
267
- usage: this.normalizeUsage(geminiUsageToOpenAIShape(data.usageMetadata))
268
- };
269
- }
270
246
  }