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