@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
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { canonicalModelId } from '../modelIds.js';
|
|
2
|
+
import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
|
|
3
|
+
import { LLMProvider, mimeTypeForAudioFormat, type ChatOptions, type ChatResponse, type ChatResponseToolCall, type ProviderConfig } from './base.js';
|
|
4
|
+
import {
|
|
5
|
+
scanAndAdaptToolsForProvider,
|
|
6
|
+
adaptSchemaForGemini,
|
|
7
|
+
isEmptyObjectSchema,
|
|
8
|
+
normalizeToolName
|
|
9
|
+
} from '../tools/toolScanner.js';
|
|
10
|
+
import {
|
|
11
|
+
safeParseJsonObject,
|
|
12
|
+
sanitizeProviderToolId,
|
|
13
|
+
serializeAndDecodeArguments
|
|
14
|
+
} from './wireNormalizer.js';
|
|
15
|
+
import {
|
|
16
|
+
requireApiKey,
|
|
17
|
+
resolveTemperature,
|
|
18
|
+
safeProviderFetchJson
|
|
19
|
+
} from './byokHttp.js';
|
|
20
|
+
import { streamGeminiGenerateContent, wantsStreaming } from './byokStream.js';
|
|
21
|
+
|
|
22
|
+
export { adaptSchemaForGemini, isEmptyObjectSchema };
|
|
23
|
+
|
|
24
|
+
export function geminiUsageToOpenAIShape(usageMetadata: Record<string, any> | null | undefined): {
|
|
25
|
+
prompt_tokens: number;
|
|
26
|
+
completion_tokens: number;
|
|
27
|
+
prompt_tokens_details: { cached_tokens: number };
|
|
28
|
+
} {
|
|
29
|
+
const nonNeg = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
|
|
30
|
+
const prompt = nonNeg(usageMetadata?.['promptTokenCount']);
|
|
31
|
+
const candidates = nonNeg(usageMetadata?.['candidatesTokenCount']);
|
|
32
|
+
const thoughts = nonNeg(usageMetadata?.['thoughtsTokenCount']);
|
|
33
|
+
const total = nonNeg(usageMetadata?.['totalTokenCount']);
|
|
34
|
+
const cached = nonNeg(usageMetadata?.['cachedContentTokenCount']);
|
|
35
|
+
|
|
36
|
+
const completion = total > prompt ? total - prompt : candidates + thoughts;
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
prompt_tokens: prompt,
|
|
40
|
+
completion_tokens: completion,
|
|
41
|
+
prompt_tokens_details: { cached_tokens: cached }
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class GeminiProvider extends LLMProvider {
|
|
46
|
+
allowInsecureHttp: boolean;
|
|
47
|
+
|
|
48
|
+
constructor(config: ProviderConfig = {}) {
|
|
49
|
+
super(config);
|
|
50
|
+
this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['gemini']) || '');
|
|
51
|
+
this.allowInsecureHttp = config.allowInsecureHttp === true;
|
|
52
|
+
const customUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
|
|
53
|
+
if (customUrl) {
|
|
54
|
+
try {
|
|
55
|
+
const parsed = new URL(customUrl);
|
|
56
|
+
parsed.searchParams.delete('key');
|
|
57
|
+
this.baseUrl = parsed.toString();
|
|
58
|
+
} catch {
|
|
59
|
+
this.baseUrl = customUrl;
|
|
60
|
+
}
|
|
61
|
+
} else {
|
|
62
|
+
this.baseUrl = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(this.model)}:generateContent`;
|
|
63
|
+
}
|
|
64
|
+
this.visionModels = ['gemini-'];
|
|
65
|
+
this.imagePayloadFormat = 'gemini';
|
|
66
|
+
this.audioModels = ['gemini-'];
|
|
67
|
+
this.audioPayloadFormat = 'gemini';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
|
|
71
|
+
messages = this.prepareMessages(messages);
|
|
72
|
+
const systemParts: Array<{ text: string }> = [];
|
|
73
|
+
const contents: Array<{ role: string; parts: Array<Record<string, any>> }> = [];
|
|
74
|
+
const toolNameById = new Map<string, string>();
|
|
75
|
+
|
|
76
|
+
for (const msg of messages) {
|
|
77
|
+
if (msg.role === 'system') {
|
|
78
|
+
const text = typeof msg.content === 'string'
|
|
79
|
+
? msg.content
|
|
80
|
+
: JSON.stringify(msg.content);
|
|
81
|
+
if (text) systemParts.push({ text });
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const role = msg.role === 'assistant' ? 'model' : 'user';
|
|
86
|
+
|
|
87
|
+
if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
|
|
88
|
+
const parts: Array<Record<string, any>> = [];
|
|
89
|
+
if (typeof msg.content === 'string' && msg.content) parts.push({ text: msg.content });
|
|
90
|
+
for (const tc of msg.tool_calls) {
|
|
91
|
+
if (!tc || typeof tc !== 'object') continue;
|
|
92
|
+
const normalizedName = normalizeToolName(tc.function?.name || '');
|
|
93
|
+
if (!normalizedName) continue;
|
|
94
|
+
if (typeof tc.id === 'string' && tc.id) toolNameById.set(tc.id, normalizedName);
|
|
95
|
+
const fcPart: Record<string, any> = {
|
|
96
|
+
functionCall: {
|
|
97
|
+
name: normalizedName,
|
|
98
|
+
args: safeParseJsonObject(tc.function?.arguments)
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
const sig = typeof tc.thoughtSignature === 'string' ? tc.thoughtSignature : (typeof tc.thought_signature === 'string' ? tc.thought_signature : undefined);
|
|
102
|
+
if (sig) fcPart['thoughtSignature'] = sig;
|
|
103
|
+
parts.push(fcPart);
|
|
104
|
+
}
|
|
105
|
+
if (parts.length > 0) contents.push({ role, parts });
|
|
106
|
+
} else if (msg.role === 'tool') {
|
|
107
|
+
const resolvedName = normalizeToolName(msg.name || (typeof msg.tool_call_id === 'string' ? toolNameById.get(msg.tool_call_id) : '') || 'tool');
|
|
108
|
+
const responsePart = {
|
|
109
|
+
functionResponse: {
|
|
110
|
+
name: resolvedName,
|
|
111
|
+
response: { result: msg.content ?? '' }
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const lastEntry = contents[contents.length - 1];
|
|
115
|
+
if (lastEntry && lastEntry.role === 'user' && Array.isArray(lastEntry.parts) && lastEntry.parts[0]?.['functionResponse']) {
|
|
116
|
+
lastEntry.parts.push(responsePart);
|
|
117
|
+
} else {
|
|
118
|
+
contents.push({
|
|
119
|
+
role: 'user',
|
|
120
|
+
parts: [responsePart]
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
} else {
|
|
124
|
+
if (Array.isArray(msg.content)) {
|
|
125
|
+
const rawMapped = msg.content.map((part: any) => {
|
|
126
|
+
if (!part || typeof part !== 'object') return null;
|
|
127
|
+
if (part.type === 'text') return { text: typeof part.text === 'string' ? part.text : '' };
|
|
128
|
+
if (part.type === 'image_url') {
|
|
129
|
+
const rawUrl = typeof part.image_url?.url === 'string' ? part.image_url.url : '';
|
|
130
|
+
const marker = rawUrl.indexOf('base64,');
|
|
131
|
+
if (rawUrl.startsWith('data:') && marker !== -1) {
|
|
132
|
+
const mime = rawUrl.slice(5, marker).split(';')[0] || 'image/png';
|
|
133
|
+
const b64 = rawUrl.slice(marker + 7);
|
|
134
|
+
if (b64) return { inlineData: { mimeType: mime, data: b64 } };
|
|
135
|
+
}
|
|
136
|
+
return { text: '' };
|
|
137
|
+
}
|
|
138
|
+
if (part.type === 'image' && part.source?.type === 'base64') {
|
|
139
|
+
return { inlineData: { mimeType: part.source.media_type, data: part.source.data } };
|
|
140
|
+
}
|
|
141
|
+
if (part.type === 'input_audio') {
|
|
142
|
+
return {
|
|
143
|
+
inlineData: {
|
|
144
|
+
mimeType: mimeTypeForAudioFormat(part.input_audio?.format),
|
|
145
|
+
data: part.input_audio?.data
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
if (part.inlineData) return part;
|
|
150
|
+
return null;
|
|
151
|
+
}).filter((p: any): p is Record<string, any> => p !== null);
|
|
152
|
+
const mappedParts = rawMapped.length > 0 ? rawMapped : [{ text: '' }];
|
|
153
|
+
contents.push({ role, parts: mappedParts });
|
|
154
|
+
} else {
|
|
155
|
+
const scalar = typeof msg.content === 'string' ? msg.content : (msg.content == null ? '' : JSON.stringify(msg.content));
|
|
156
|
+
contents.push({ role, parts: [{ text: scalar }] });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const apiKey = requireApiKey(this.apiKey, 'Gemini');
|
|
162
|
+
const generationConfig: Record<string, any> = {
|
|
163
|
+
temperature: resolveTemperature(options.temperature, 0.1)
|
|
164
|
+
};
|
|
165
|
+
if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
|
|
166
|
+
generationConfig['maxOutputTokens'] = Math.floor(options.maxTokens);
|
|
167
|
+
}
|
|
168
|
+
if (options.jsonMode) {
|
|
169
|
+
generationConfig['responseMimeType'] = 'application/json';
|
|
170
|
+
}
|
|
171
|
+
const payload: Record<string, any> = {
|
|
172
|
+
contents,
|
|
173
|
+
generationConfig
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
if (systemParts.length > 0) {
|
|
177
|
+
payload['systemInstruction'] = { parts: systemParts };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
let freeFormPaths = new Map<string, string[][]>();
|
|
181
|
+
if (options.tools && options.tools.length > 0) {
|
|
182
|
+
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'gemini');
|
|
183
|
+
payload['tools'] = [{
|
|
184
|
+
functionDeclarations: scanReport.adaptedTools
|
|
185
|
+
}];
|
|
186
|
+
freeFormPaths = scanReport.freeFormPaths;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const endpoint = this.baseUrl || `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(this.model)}:generateContent`;
|
|
190
|
+
const requestOpts = {
|
|
191
|
+
url: endpoint,
|
|
192
|
+
method: 'POST',
|
|
193
|
+
headers: {
|
|
194
|
+
'Content-Type': 'application/json',
|
|
195
|
+
'x-goog-api-key': apiKey
|
|
196
|
+
},
|
|
197
|
+
signal: options.signal,
|
|
198
|
+
timeoutMs: options.timeoutMs,
|
|
199
|
+
providerLabel: 'Gemini',
|
|
200
|
+
secrets: [apiKey],
|
|
201
|
+
hasApiKey: true,
|
|
202
|
+
allowInsecureHttp: this.allowInsecureHttp
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
const data: Record<string, any> = wantsStreaming(options)
|
|
206
|
+
? await streamGeminiGenerateContent({
|
|
207
|
+
...requestOpts,
|
|
208
|
+
payload,
|
|
209
|
+
onChunk: options.onChunk,
|
|
210
|
+
onReasoningChunk: options.onReasoningChunk
|
|
211
|
+
})
|
|
212
|
+
: await safeProviderFetchJson({
|
|
213
|
+
...requestOpts,
|
|
214
|
+
body: JSON.stringify(payload)
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
const firstCandidate = data['candidates']?.[0];
|
|
218
|
+
if (!firstCandidate) {
|
|
219
|
+
const blockReason = data['promptFeedback']?.blockReason;
|
|
220
|
+
const detail = typeof blockReason === 'string' && blockReason ? ` (blockReason: ${blockReason})` : '';
|
|
221
|
+
throw new Error(`No candidate returned from Gemini${detail}`);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
let content = '';
|
|
225
|
+
let reasoningContent = typeof data['reasoningContent'] === 'string' ? data['reasoningContent'] : '';
|
|
226
|
+
const toolCalls: ChatResponseToolCall[] = [];
|
|
227
|
+
const candidateParts = Array.isArray(firstCandidate.content?.parts) ? firstCandidate.content.parts : [];
|
|
228
|
+
|
|
229
|
+
for (const part of candidateParts) {
|
|
230
|
+
if (!part || typeof part !== 'object') continue;
|
|
231
|
+
if (typeof part.text === 'string' && part.text) {
|
|
232
|
+
if (part.thought === true) {
|
|
233
|
+
reasoningContent += part.text;
|
|
234
|
+
} else {
|
|
235
|
+
content += part.text;
|
|
236
|
+
}
|
|
237
|
+
} else if (part.functionCall && typeof part.functionCall === 'object') {
|
|
238
|
+
const callName = normalizeToolName(part.functionCall.name || '');
|
|
239
|
+
if (!callName) continue;
|
|
240
|
+
const serializedArgs = serializeAndDecodeArguments(part.functionCall.args || {}, callName, freeFormPaths);
|
|
241
|
+
const sig = typeof part.thoughtSignature === 'string' ? part.thoughtSignature : (typeof part.thought_signature === 'string' ? part.thought_signature : undefined);
|
|
242
|
+
toolCalls.push({
|
|
243
|
+
id: sanitizeProviderToolId(part.functionCall.id, 'call_gemini', toolCalls.length),
|
|
244
|
+
type: 'function',
|
|
245
|
+
function: {
|
|
246
|
+
name: callName,
|
|
247
|
+
arguments: serializedArgs
|
|
248
|
+
},
|
|
249
|
+
...(sig ? { thoughtSignature: sig } : {})
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return {
|
|
255
|
+
content: content.trim(),
|
|
256
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
257
|
+
...(reasoningContent.trim() ? { reasoningContent: reasoningContent.trim() } : {}),
|
|
258
|
+
usage: this.normalizeUsage(geminiUsageToOpenAIShape(data['usageMetadata']))
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* @file src/providers/loopGuard.ts
|
|
3
3
|
* Causyne Agent — Sliding-Window Loop Guard & Context Overflow Detector
|
|
4
4
|
*
|
|
5
|
-
*
|
|
5
|
+
* Causyne native sliding-window turn protection and context-overflow classification.
|
|
6
6
|
* Protects against conversational bounce-back, self-sustaining loops, and
|
|
7
7
|
* accurately detects context overflow without false positives from auth tokens.
|
|
8
8
|
*
|
|
@@ -20,17 +20,21 @@ const CONTEXT_OVERFLOW_PHRASES = [
|
|
|
20
20
|
'context window is full',
|
|
21
21
|
'prompt token count exceeds',
|
|
22
22
|
'string too long for context',
|
|
23
|
-
'payload too large'
|
|
23
|
+
'payload too large',
|
|
24
|
+
'exceeds the maximum number of tokens',
|
|
25
|
+
'maximum prompt length',
|
|
26
|
+
'input token count exceeds'
|
|
24
27
|
];
|
|
25
28
|
export class CausyneLoopGuard {
|
|
26
29
|
timestamps = [];
|
|
27
30
|
inCooldownUntil = 0;
|
|
28
31
|
config;
|
|
29
32
|
constructor(customConfig) {
|
|
33
|
+
const positiveInt = (val, fallback) => typeof val === 'number' && Number.isFinite(val) && val >= 1 ? Math.floor(val) : fallback;
|
|
30
34
|
this.config = {
|
|
31
|
-
maxEvents: customConfig?.maxEvents
|
|
32
|
-
windowMs: customConfig?.windowMs
|
|
33
|
-
cooldownMs: customConfig?.cooldownMs
|
|
35
|
+
maxEvents: positiveInt(customConfig?.maxEvents, 15),
|
|
36
|
+
windowMs: positiveInt(customConfig?.windowMs, 120_000),
|
|
37
|
+
cooldownMs: positiveInt(customConfig?.cooldownMs, 300_000)
|
|
34
38
|
};
|
|
35
39
|
}
|
|
36
40
|
recordAction() {
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* @file src/providers/loopGuard.ts
|
|
3
3
|
* Causyne Agent — Sliding-Window Loop Guard & Context Overflow Detector
|
|
4
4
|
*
|
|
5
|
-
*
|
|
5
|
+
* Causyne native sliding-window turn protection and context-overflow classification.
|
|
6
6
|
* Protects against conversational bounce-back, self-sustaining loops, and
|
|
7
7
|
* accurately detects context overflow without false positives from auth tokens.
|
|
8
8
|
*
|
|
@@ -33,7 +33,10 @@ const CONTEXT_OVERFLOW_PHRASES: readonly string[] = [
|
|
|
33
33
|
'context window is full',
|
|
34
34
|
'prompt token count exceeds',
|
|
35
35
|
'string too long for context',
|
|
36
|
-
'payload too large'
|
|
36
|
+
'payload too large',
|
|
37
|
+
'exceeds the maximum number of tokens',
|
|
38
|
+
'maximum prompt length',
|
|
39
|
+
'input token count exceeds'
|
|
37
40
|
];
|
|
38
41
|
|
|
39
42
|
export class CausyneLoopGuard {
|
|
@@ -42,10 +45,12 @@ export class CausyneLoopGuard {
|
|
|
42
45
|
private readonly config: LoopGuardConfig;
|
|
43
46
|
|
|
44
47
|
constructor(customConfig?: Partial<LoopGuardConfig>) {
|
|
48
|
+
const positiveInt = (val: unknown, fallback: number): number =>
|
|
49
|
+
typeof val === 'number' && Number.isFinite(val) && val >= 1 ? Math.floor(val) : fallback;
|
|
45
50
|
this.config = {
|
|
46
|
-
maxEvents: customConfig?.maxEvents
|
|
47
|
-
windowMs: customConfig?.windowMs
|
|
48
|
-
cooldownMs: customConfig?.cooldownMs
|
|
51
|
+
maxEvents: positiveInt(customConfig?.maxEvents, 15),
|
|
52
|
+
windowMs: positiveInt(customConfig?.windowMs, 120_000),
|
|
53
|
+
cooldownMs: positiveInt(customConfig?.cooldownMs, 300_000)
|
|
49
54
|
};
|
|
50
55
|
}
|
|
51
56
|
|
|
@@ -3,80 +3,78 @@ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
|
|
|
3
3
|
import { LLMProvider } from './base.js';
|
|
4
4
|
import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
|
|
5
5
|
import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
|
|
6
|
-
import {
|
|
7
|
-
requireApiKey,
|
|
8
|
-
resolveTemperature,
|
|
9
|
-
safeProviderFetchJson
|
|
10
|
-
} from './byokHttp.js';
|
|
6
|
+
import { requireApiKey, resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
|
|
11
7
|
import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
|
|
12
|
-
|
|
13
8
|
export class MoonshotProvider extends LLMProvider {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
async chat(messages, options = {}) {
|
|
24
|
-
const apiKey = requireApiKey(this.apiKey, 'Moonshot AI (Kimi)');
|
|
25
|
-
const sanitizedMessages = this.prepareMessages(messages);
|
|
26
|
-
|
|
27
|
-
const payload = {
|
|
28
|
-
model: this.model,
|
|
29
|
-
messages: sanitizedMessages,
|
|
30
|
-
temperature: resolveTemperature(options.temperature, 0.1),
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
if (options.jsonMode) {
|
|
34
|
-
payload.response_format = { type: 'json_object' };
|
|
9
|
+
allowInsecureHttp;
|
|
10
|
+
constructor(config = {}) {
|
|
11
|
+
super(config);
|
|
12
|
+
const customUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
|
|
13
|
+
this.baseUrl = customUrl || 'https://api.moonshot.ai/v1/chat/completions';
|
|
14
|
+
this.allowInsecureHttp = config.allowInsecureHttp === true;
|
|
15
|
+
this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['moonshot']) || '');
|
|
16
|
+
this.visionModels = ['kimi-k3', 'kimi-k2.5', 'vision'];
|
|
17
|
+
this.audioModels = [];
|
|
35
18
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
19
|
+
async chat(messages, options = {}) {
|
|
20
|
+
const apiKey = requireApiKey(this.apiKey, 'Moonshot AI (Kimi)');
|
|
21
|
+
const sanitizedMessages = this.prepareMessages(messages);
|
|
22
|
+
const isThinkingModel = (this.model || '').trim().toLowerCase().includes('-thinking');
|
|
23
|
+
const payload = {
|
|
24
|
+
model: this.model,
|
|
25
|
+
messages: sanitizedMessages
|
|
26
|
+
};
|
|
27
|
+
if (!isThinkingModel) {
|
|
28
|
+
payload['temperature'] = resolveTemperature(options.temperature, 0.1);
|
|
29
|
+
}
|
|
30
|
+
if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
|
|
31
|
+
payload['max_tokens'] = Math.floor(options.maxTokens);
|
|
32
|
+
}
|
|
33
|
+
if (options.jsonMode) {
|
|
34
|
+
payload['response_format'] = { type: 'json_object' };
|
|
35
|
+
}
|
|
36
|
+
let freeFormPaths = new Map();
|
|
37
|
+
if (options.tools && options.tools.length > 0) {
|
|
38
|
+
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'moonshot');
|
|
39
|
+
payload['tools'] = scanReport.adaptedTools;
|
|
40
|
+
payload['tool_choice'] = 'auto';
|
|
41
|
+
freeFormPaths = scanReport.freeFormPaths;
|
|
42
|
+
}
|
|
43
|
+
const endpoint = this.baseUrl || 'https://api.moonshot.ai/v1/chat/completions';
|
|
44
|
+
const requestOpts = {
|
|
45
|
+
url: endpoint,
|
|
46
|
+
method: 'POST',
|
|
47
|
+
headers: {
|
|
48
|
+
'Content-Type': 'application/json',
|
|
49
|
+
'Authorization': `Bearer ${apiKey}`
|
|
50
|
+
},
|
|
51
|
+
signal: options.signal,
|
|
52
|
+
timeoutMs: options.timeoutMs,
|
|
53
|
+
providerLabel: 'Moonshot AI',
|
|
54
|
+
secrets: [apiKey],
|
|
55
|
+
hasApiKey: true,
|
|
56
|
+
allowInsecureHttp: this.allowInsecureHttp
|
|
57
|
+
};
|
|
58
|
+
const data = wantsStreaming(options)
|
|
59
|
+
? await streamOpenAICompatibleChat({
|
|
60
|
+
...requestOpts,
|
|
61
|
+
payload,
|
|
62
|
+
onChunk: options.onChunk,
|
|
63
|
+
onReasoningChunk: options.onReasoningChunk
|
|
64
|
+
})
|
|
65
|
+
: await safeProviderFetchJson({
|
|
66
|
+
...requestOpts,
|
|
67
|
+
body: JSON.stringify(payload)
|
|
68
|
+
});
|
|
69
|
+
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
70
|
+
prefix: 'call_moonshot',
|
|
71
|
+
freeFormPaths
|
|
69
72
|
});
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
toolCalls: normalized.toolCalls,
|
|
78
|
-
reasoningContent: normalized.reasoningContent,
|
|
79
|
-
usage: this.normalizeUsage(normalized.rawUsage)
|
|
80
|
-
};
|
|
81
|
-
}
|
|
73
|
+
return {
|
|
74
|
+
content: normalized.content,
|
|
75
|
+
toolCalls: normalized.toolCalls,
|
|
76
|
+
reasoningContent: normalized.reasoningContent,
|
|
77
|
+
usage: this.normalizeUsage(normalized.rawUsage)
|
|
78
|
+
};
|
|
79
|
+
}
|
|
82
80
|
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { canonicalModelId } from '../modelIds.js';
|
|
2
|
+
import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
|
|
3
|
+
import { LLMProvider, type ChatOptions, type ChatResponse, type ProviderConfig } from './base.js';
|
|
4
|
+
import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
|
|
5
|
+
import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
|
|
6
|
+
import {
|
|
7
|
+
requireApiKey,
|
|
8
|
+
resolveTemperature,
|
|
9
|
+
safeProviderFetchJson
|
|
10
|
+
} from './byokHttp.js';
|
|
11
|
+
import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
|
|
12
|
+
|
|
13
|
+
export class MoonshotProvider extends LLMProvider {
|
|
14
|
+
allowInsecureHttp: boolean;
|
|
15
|
+
|
|
16
|
+
constructor(config: ProviderConfig = {}) {
|
|
17
|
+
super(config);
|
|
18
|
+
const customUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
|
|
19
|
+
this.baseUrl = customUrl || 'https://api.moonshot.ai/v1/chat/completions';
|
|
20
|
+
this.allowInsecureHttp = config.allowInsecureHttp === true;
|
|
21
|
+
this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['moonshot']) || '');
|
|
22
|
+
this.visionModels = ['kimi-k3', 'kimi-k2.5', 'vision'];
|
|
23
|
+
this.audioModels = [];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
|
|
27
|
+
const apiKey = requireApiKey(this.apiKey, 'Moonshot AI (Kimi)');
|
|
28
|
+
const sanitizedMessages = this.prepareMessages(messages);
|
|
29
|
+
|
|
30
|
+
const isThinkingModel = (this.model || '').trim().toLowerCase().includes('-thinking');
|
|
31
|
+
const payload: Record<string, any> = {
|
|
32
|
+
model: this.model,
|
|
33
|
+
messages: sanitizedMessages
|
|
34
|
+
};
|
|
35
|
+
if (!isThinkingModel) {
|
|
36
|
+
payload['temperature'] = resolveTemperature(options.temperature, 0.1);
|
|
37
|
+
}
|
|
38
|
+
if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
|
|
39
|
+
payload['max_tokens'] = Math.floor(options.maxTokens);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (options.jsonMode) {
|
|
43
|
+
payload['response_format'] = { type: 'json_object' };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let freeFormPaths = new Map<string, string[][]>();
|
|
47
|
+
if (options.tools && options.tools.length > 0) {
|
|
48
|
+
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'moonshot');
|
|
49
|
+
payload['tools'] = scanReport.adaptedTools;
|
|
50
|
+
payload['tool_choice'] = 'auto';
|
|
51
|
+
freeFormPaths = scanReport.freeFormPaths;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const endpoint = this.baseUrl || 'https://api.moonshot.ai/v1/chat/completions';
|
|
55
|
+
const requestOpts = {
|
|
56
|
+
url: endpoint,
|
|
57
|
+
method: 'POST',
|
|
58
|
+
headers: {
|
|
59
|
+
'Content-Type': 'application/json',
|
|
60
|
+
'Authorization': `Bearer ${apiKey}`
|
|
61
|
+
},
|
|
62
|
+
signal: options.signal,
|
|
63
|
+
timeoutMs: options.timeoutMs,
|
|
64
|
+
providerLabel: 'Moonshot AI',
|
|
65
|
+
secrets: [apiKey],
|
|
66
|
+
hasApiKey: true,
|
|
67
|
+
allowInsecureHttp: this.allowInsecureHttp
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const data = wantsStreaming(options)
|
|
71
|
+
? await streamOpenAICompatibleChat({
|
|
72
|
+
...requestOpts,
|
|
73
|
+
payload,
|
|
74
|
+
onChunk: options.onChunk,
|
|
75
|
+
onReasoningChunk: options.onReasoningChunk
|
|
76
|
+
})
|
|
77
|
+
: await safeProviderFetchJson({
|
|
78
|
+
...requestOpts,
|
|
79
|
+
body: JSON.stringify(payload)
|
|
80
|
+
});
|
|
81
|
+
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
82
|
+
prefix: 'call_moonshot',
|
|
83
|
+
freeFormPaths
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
content: normalized.content,
|
|
88
|
+
toolCalls: normalized.toolCalls,
|
|
89
|
+
reasoningContent: normalized.reasoningContent,
|
|
90
|
+
usage: this.normalizeUsage(normalized.rawUsage)
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
}
|