@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.
- 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 +117 -0
- package/src/agent/errorClassifier.ts +165 -0
- package/src/agent/promptIntent.js +200 -0
- package/src/agent/promptIntent.ts +203 -0
- package/src/agent/toolArgValidator.js +97 -0
- package/src/agent/toolArgValidator.ts +112 -0
- package/src/agentLoop.js +33 -344
- package/src/agentLoop.ts +51 -352
- 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 +116 -10
- package/src/autoUpdate.ts +149 -10
- 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/cliMode.js +16 -2
- package/src/commands.js +10 -9
- package/src/config.js +288 -272
- package/src/config.ts +342 -0
- package/src/configVault.js +271 -0
- package/src/configVault.ts +273 -0
- 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/core/contextCompactor.js +70 -11
- package/src/core/contextCompactor.ts +83 -11
- 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/dynamicCatalogue.js +42 -73
- package/src/dynamicCatalogue.ts +74 -60
- 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/entrypoint.js +77 -4
- package/src/headlessCli.js +305 -0
- package/src/headlessCli.ts +381 -0
- 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/mcp/mcpClient.js +38 -11
- package/src/mcp/mcpClient.ts +44 -11
- package/src/mcp/mcpRegistry.js +2 -5
- package/src/mcp/mcpRegistry.ts +2 -5
- package/src/mcp/mcpSecurity.js +189 -0
- package/src/mcp/mcpSecurity.ts +190 -0
- 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 +263 -0
- package/src/osKeychain.ts +287 -0
- 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 +328 -385
- 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 +397 -0
- package/src/providers/byokHttp.ts +497 -0
- package/src/providers/byokStream.js +748 -0
- package/src/providers/byokStream.ts +863 -0
- package/src/providers/dashscope-byok.js +98 -81
- package/src/providers/dashscope-byok.ts +114 -0
- package/src/providers/deepseek.js +74 -64
- 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 +229 -253
- 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 +71 -64
- 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 +116 -93
- package/src/providers/ollama.ts +135 -0
- package/src/providers/openai-compatible.js +114 -65
- 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 +194 -98
- package/src/providers/openrouter.ts +202 -97
- package/src/providers/pi.js +6 -0
- package/src/providers/pi.ts +6 -0
- package/src/providers/qwen-byok.js +97 -71
- 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 +74 -64
- 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 +486 -530
- package/src/sandbox.ts +552 -0
- package/src/sandboxPolicy.js +1287 -0
- package/src/sandboxPolicy.ts +1381 -0
- package/src/sessionJournal.js +55 -3
- package/src/sessionJournal.ts +58 -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 +513 -0
- package/src/tools/osSandbox.ts +588 -0
- 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/persistentShell.js +8 -3
- 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/subprocessEnv.js +197 -0
- package/src/tools/subprocessEnv.ts +212 -0
- package/src/tools/sysRun.js +108 -35
- package/src/tools/sysRun.ts +119 -31
- 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
|
@@ -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
|
+
}
|
package/src/providers/gemini.js
CHANGED
|
@@ -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
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
149
|
-
|
|
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
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
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
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
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
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
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
|
}
|