@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.
- package/README.md +3 -3
- package/package.json +1 -1
- package/src/acp/agentCatalog.js +81 -26
- package/src/acp/agentCatalog.ts +73 -29
- package/src/acp/client.js +210 -53
- package/src/acp/client.ts +202 -52
- package/src/acp/peerProfiles.js +55 -22
- package/src/acp/peerProfiles.ts +51 -22
- package/src/acp/protocol.js +37 -8
- package/src/acp/protocol.ts +30 -8
- package/src/acp/server.js +123 -25
- package/src/acp/server.ts +124 -24
- package/src/agent/errorClassifier.js +6 -2
- package/src/agent/errorClassifier.ts +6 -2
- package/src/agentLoop.js +11 -5
- package/src/agentLoop.ts +11 -5
- package/src/approvalGrants.js +19 -7
- package/src/approvalGrants.ts +20 -7
- package/src/approvalPolicy.js +48 -15
- package/src/approvalPolicy.ts +46 -15
- package/src/autoUpdate.js +5 -2
- package/src/autoUpdate.ts +5 -2
- package/src/browser/causyneBrowser.js +3 -2
- package/src/browser/causyneBrowser.ts +3 -2
- package/src/browser/searchProviders.js +1 -1
- package/src/browser/searchProviders.ts +1 -1
- package/src/config.js +287 -250
- package/src/config.ts +342 -0
- package/src/configVault.js +84 -17
- package/src/configVault.ts +77 -17
- package/src/continuum/compactor.js +2 -1
- package/src/continuum/compactor.ts +2 -1
- package/src/continuum/sanitizer.js +10 -3
- package/src/continuum/sanitizer.ts +9 -3
- package/src/continuum/ui/continuumPickerView.js +3 -2
- package/src/continuum/ui/continuumPickerView.ts +3 -2
- package/src/cortex/vectorDb.js +26 -15
- package/src/cortex/vectorDb.ts +26 -16
- package/src/creative/liveBridge.js +7 -5
- package/src/creative/liveBridge.ts +7 -5
- package/src/creative/studioScripts.js +16 -5
- package/src/creative/studioScripts.ts +14 -5
- package/src/decisionPolicy.js +16 -4
- package/src/decisionPolicy.ts +14 -4
- package/src/documentEngine/antiSlopAuditor.js +10 -5
- package/src/documentEngine/antiSlopAuditor.ts +11 -5
- package/src/documentEngine/documentForge.js +47 -15
- package/src/documentEngine/documentForge.ts +43 -14
- package/src/engines/design.js +2 -1
- package/src/engines/design.ts +2 -1
- package/src/engines/film.js +4 -4
- package/src/engines/film.ts +2 -2
- package/src/engines/light.js +2 -1
- package/src/engines/light.ts +2 -1
- package/src/engines/registry.js +1 -1
- package/src/engines/registry.ts +1 -1
- package/src/engines/reverseHarness.js +4 -3
- package/src/engines/reverseHarness.ts +4 -3
- package/src/headlessCli.js +2 -1
- package/src/headlessCli.ts +2 -1
- package/src/historyPruner.js +3 -2
- package/src/historyPruner.ts +3 -2
- package/src/hooks.js +3 -0
- package/src/hooks.ts +3 -0
- package/src/implementationPlan.js +21 -11
- package/src/implementationPlan.ts +21 -11
- package/src/infra/atomicWriter.js +4 -1
- package/src/infra/atomicWriter.ts +4 -1
- package/src/launchIntent.js +1 -1
- package/src/launchIntent.ts +1 -1
- package/src/memory/scopedFacts.js +1 -1
- package/src/memory/scopedFacts.ts +1 -1
- package/src/memory/symbolFolder.js +1 -1
- package/src/memory/symbolFolder.ts +1 -1
- package/src/modelRouter.js +1 -1
- package/src/modelRouter.ts +1 -1
- package/src/observer/evidence.js +10 -4
- package/src/observer/evidence.ts +10 -4
- package/src/osKeychain.js +62 -8
- package/src/osKeychain.ts +50 -8
- package/src/perception.js +3 -2
- package/src/perception.ts +3 -2
- package/src/planCache.js +2 -2
- package/src/planCache.ts +2 -2
- package/src/pluginsFactory/pluginsFactory.js +19 -11
- package/src/pluginsFactory/pluginsFactory.ts +18 -11
- package/src/promptMentions.js +2 -2
- package/src/promptMentions.ts +2 -2
- package/src/providers/acp.js +1 -1
- package/src/providers/acp.ts +1 -1
- package/src/providers/anthropic.js +327 -401
- package/src/providers/anthropic.ts +386 -0
- package/src/providers/antigravity.js +10 -4
- package/src/providers/antigravity.ts +10 -4
- package/src/providers/base.js +221 -319
- package/src/providers/base.ts +340 -0
- package/src/providers/byokHttp.js +58 -15
- package/src/providers/byokHttp.ts +59 -16
- package/src/providers/byokStream.js +142 -51
- package/src/providers/byokStream.ts +146 -42
- package/src/providers/dashscope-byok.js +97 -89
- package/src/providers/dashscope-byok.ts +114 -0
- package/src/providers/deepseek.js +73 -72
- package/src/providers/deepseek.ts +99 -0
- package/src/providers/factory.js +35 -28
- package/src/providers/factory.ts +40 -0
- package/src/providers/gemini.js +227 -278
- package/src/providers/gemini.ts +261 -0
- package/src/providers/loopGuard.js +9 -5
- package/src/providers/loopGuard.ts +10 -5
- package/src/providers/moonshot.js +70 -72
- package/src/providers/moonshot.ts +93 -0
- package/src/providers/muse.js +82 -152
- package/src/providers/muse.ts +122 -0
- package/src/providers/ollama.js +114 -106
- package/src/providers/ollama.ts +135 -0
- package/src/providers/openai-compatible.js +113 -96
- package/src/providers/openai-compatible.ts +139 -0
- package/src/providers/openai.js +22 -15
- package/src/providers/openai.ts +30 -0
- package/src/providers/openrouter.js +136 -74
- package/src/providers/openrouter.ts +133 -72
- package/src/providers/pi.js +6 -0
- package/src/providers/pi.ts +6 -0
- package/src/providers/qwen-byok.js +96 -87
- package/src/providers/qwen-byok.ts +113 -0
- package/src/providers/toolContracts.js +40 -14
- package/src/providers/toolContracts.ts +35 -14
- package/src/providers/wireNormalizer.js +78 -11
- package/src/providers/wireNormalizer.ts +68 -12
- package/src/providers/xai.js +73 -72
- package/src/providers/xai.ts +97 -0
- package/src/reliability/assetEvidence.js +4 -2
- package/src/reliability/assetEvidence.ts +4 -2
- package/src/sandbox.js +489 -554
- package/src/sandbox.ts +552 -0
- package/src/sandboxPolicy.js +95 -16
- package/src/sandboxPolicy.ts +97 -16
- package/src/sessionJournal.js +8 -3
- package/src/sessionJournal.ts +9 -3
- package/src/skills/skillResourceSafety.js +19 -8
- package/src/skills/skillResourceSafety.ts +16 -7
- package/src/skillsManager.js +3 -3
- package/src/skillsManager.ts +3 -3
- package/src/smartToolsUse.js +28 -4
- package/src/smartToolsUse.ts +29 -7
- package/src/stallGuard.js +45 -22
- package/src/stallGuard.ts +46 -22
- package/src/subagentJournal.js +6 -4
- package/src/subagentJournal.ts +6 -4
- package/src/textDiff.js +6 -1
- package/src/textDiff.ts +6 -1
- package/src/timeMachine.js +7 -1
- package/src/timeMachine.ts +7 -1
- package/src/tokenTracker.js +43 -28
- package/src/tokenTracker.ts +44 -30
- package/src/toolPacks.js +3 -1
- package/src/toolPacks.ts +3 -1
- package/src/tools/archive.js +245 -35
- package/src/tools/archive.ts +244 -35
- package/src/tools/computerUse.js +7 -3
- package/src/tools/computerUse.ts +7 -3
- package/src/tools/creativeApps.js +13 -8
- package/src/tools/creativeApps.ts +22 -9
- package/src/tools/deferredMcpSearch.js +26 -14
- package/src/tools/deferredMcpSearch.ts +26 -14
- package/src/tools/desktopOpen.js +69 -10
- package/src/tools/desktopOpen.ts +70 -11
- package/src/tools/documentForge.js +167 -82
- package/src/tools/documentForge.ts +169 -84
- package/src/tools/fsEdit.js +101 -30
- package/src/tools/fsEdit.ts +105 -32
- package/src/tools/fsFind.js +8 -5
- package/src/tools/fsFind.ts +7 -4
- package/src/tools/fsRead.js +119 -13
- package/src/tools/fsRead.ts +124 -13
- package/src/tools/fsWrite.js +17 -5
- package/src/tools/fsWrite.ts +17 -7
- package/src/tools/generateMediaViaApi.js +82 -19
- package/src/tools/generateMediaViaApi.ts +80 -19
- package/src/tools/memoryRecall.js +62 -11
- package/src/tools/memoryRecall.ts +70 -13
- package/src/tools/memoryWrite.js +27 -14
- package/src/tools/memoryWrite.ts +30 -14
- package/src/tools/multiEdit.js +100 -30
- package/src/tools/multiEdit.ts +104 -32
- package/src/tools/nativeEngine.js +33 -18
- package/src/tools/nativeEngine.ts +31 -18
- package/src/tools/openSourceToolProvisioner.js +49 -14
- package/src/tools/openSourceToolProvisioner.ts +54 -15
- package/src/tools/osSandbox.js +54 -14
- package/src/tools/osSandbox.ts +48 -14
- package/src/tools/payloadSanitizer.js +40 -8
- package/src/tools/payloadSanitizer.ts +39 -8
- package/src/tools/peerAgent.js +96 -34
- package/src/tools/peerAgent.ts +114 -37
- package/src/tools/pluginsFactory.js +38 -6
- package/src/tools/pluginsFactory.ts +42 -6
- package/src/tools/readNativeSkill.js +10 -8
- package/src/tools/readNativeSkill.ts +10 -8
- package/src/tools/requestDecision.js +10 -3
- package/src/tools/requestDecision.ts +10 -3
- package/src/tools/resolveAutomator.js +91 -17
- package/src/tools/resolveAutomator.ts +102 -17
- package/src/tools/reverseEngineering.js +168 -41
- package/src/tools/reverseEngineering.ts +161 -41
- package/src/tools/sysRun.js +69 -29
- package/src/tools/sysRun.ts +66 -24
- package/src/tools/toolDispatch.js +24 -1
- package/src/tools/toolDispatch.ts +21 -1
- package/src/tools/toolOutputStore.js +62 -23
- package/src/tools/toolOutputStore.ts +56 -23
- package/src/tools/toolScanner.js +13 -10
- package/src/tools/toolScanner.ts +13 -10
- package/src/tools/toolSelfRepair.js +94 -28
- package/src/tools/toolSelfRepair.ts +96 -28
- package/src/tools/uiForge.js +71 -6
- package/src/tools/uiForge.ts +74 -6
- package/src/tools/viewImage.js +62 -17
- package/src/tools/viewImage.ts +57 -12
- package/src/tools/visionInspector.js +15 -3
- package/src/tools/visionInspector.ts +15 -3
- package/src/tools/walkerSafety.js +2 -0
- package/src/tools/walkerSafety.ts +1 -0
- package/src/tools/webFetch.js +105 -10
- package/src/tools/webFetch.ts +105 -11
- package/src/tui/banner.js +3 -2
- package/src/tui/banner.ts +3 -2
- package/src/tui/consoleGuard.js +12 -4
- package/src/tui/consoleGuard.ts +9 -4
- package/src/tui/messageInteraction.js +2 -3
- package/src/tui/messageInteraction.ts +2 -3
- package/src/tui/modelPicker.js +1 -0
- package/src/tui/modelPicker.ts +1 -0
- package/src/tui/overlay.js +3 -1
- package/src/tui/overlay.ts +3 -1
- package/src/tui/sessionPicker.js +3 -2
- package/src/tui/sessionPicker.ts +3 -2
- package/src/tui/sessionPickerView.js +7 -1
- package/src/tui/sessionPickerView.ts +6 -1
- package/src/tui/toolOutputNormalizer.js +2 -3
- package/src/tui/toolOutputNormalizer.ts +4 -3
- package/src/tui/viewport.js +4 -4
- package/src/tui/viewport.ts +5 -5
- package/src/tui/workspaceIdentity.js +2 -1
- package/src/tui/workspaceIdentity.ts +2 -1
- package/src/uncertainty.js +8 -3
- package/src/uncertainty.ts +8 -3
- package/src/utils/paths.js +8 -5
- package/src/utils/paths.ts +9 -7
- package/src/vfeTracker.js +9 -3
- package/src/vfeTracker.ts +9 -3
- package/src/config.d.ts +0 -2
- package/src/providers/base.d.ts +0 -94
- package/src/providers/factory.d.ts +0 -1
- package/src/sandbox.d.ts +0 -1
package/src/providers/gemini.js
CHANGED
|
@@ -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
|
-
|
|
6
|
-
|
|
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
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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
|
-
|
|
156
|
-
|
|
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
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
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
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
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
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
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
|
-
|
|
277
|
-
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
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
|
}
|