@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,340 @@
|
|
|
1
|
+
import { canonicalModelId } from '../modelIds.js';
|
|
2
|
+
import type { RequestPermissionRequest, RequestPermissionResponse } from '../acp/protocol.js';
|
|
3
|
+
|
|
4
|
+
export interface ProviderConfig {
|
|
5
|
+
apiKey?: string | undefined;
|
|
6
|
+
model?: string | undefined;
|
|
7
|
+
baseUrl?: string | undefined;
|
|
8
|
+
provider?: string | undefined;
|
|
9
|
+
command?: string | undefined;
|
|
10
|
+
args?: string[] | undefined;
|
|
11
|
+
peer?: string | undefined;
|
|
12
|
+
supportsVision?: boolean | undefined;
|
|
13
|
+
supportsAudio?: boolean | undefined;
|
|
14
|
+
allowInsecureHttp?: boolean | undefined;
|
|
15
|
+
reasoningEffort?: string | null | undefined;
|
|
16
|
+
showReasoning?: boolean | undefined;
|
|
17
|
+
reasoningBudgetTokens?: number | null | undefined;
|
|
18
|
+
enableToolSearch?: boolean | undefined;
|
|
19
|
+
enablePromptCaching?: boolean | undefined;
|
|
20
|
+
promptCacheTtl?: string | undefined;
|
|
21
|
+
[key: string]: any;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ChatResponseUsage {
|
|
25
|
+
promptTokens: number;
|
|
26
|
+
completionTokens: number;
|
|
27
|
+
cachedPromptTokens?: number | undefined;
|
|
28
|
+
uncachedPromptTokens?: number | undefined;
|
|
29
|
+
cacheWriteMultiplier?: number | undefined;
|
|
30
|
+
cacheWriteTokens?: number | undefined;
|
|
31
|
+
measurement?: 'provider_reported' | 'text_estimate' | undefined;
|
|
32
|
+
cacheMeasurement?: 'provider_reported' | 'unavailable' | undefined;
|
|
33
|
+
measurementScope?: 'last_model_call' | 'peer_reported' | undefined;
|
|
34
|
+
totalTokens?: number | undefined;
|
|
35
|
+
thinkingTokens?: number | undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ChatResponseToolCall {
|
|
39
|
+
id: string;
|
|
40
|
+
type: string;
|
|
41
|
+
function: {
|
|
42
|
+
name: string;
|
|
43
|
+
arguments: string;
|
|
44
|
+
};
|
|
45
|
+
thoughtSignature?: string | undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface ChatResponseAction {
|
|
49
|
+
id?: string | undefined;
|
|
50
|
+
name: string;
|
|
51
|
+
status: 'running' | 'completed' | 'failed';
|
|
52
|
+
detail?: string | undefined;
|
|
53
|
+
parameters?: Record<string, unknown> | undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface ChatResponse {
|
|
57
|
+
content: string;
|
|
58
|
+
usage: ChatResponseUsage;
|
|
59
|
+
toolCalls?: ChatResponseToolCall[] | undefined;
|
|
60
|
+
reasoningContent?: string | undefined;
|
|
61
|
+
thinkingBlocks?: any[] | undefined;
|
|
62
|
+
externalActions?: ChatResponseAction[] | undefined;
|
|
63
|
+
toolRoutingError?: { tool: string; message: string; parameters?: Record<string, unknown> | undefined } | undefined;
|
|
64
|
+
incompleteTurn?: boolean | undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ChatOptions {
|
|
68
|
+
onPeerPermission?: ((request: RequestPermissionRequest) => Promise<RequestPermissionResponse['outcome']>) | undefined;
|
|
69
|
+
onPeerFileRead?: ((file: string, options?: { line?: number; limit?: number }) => Promise<string>) | undefined;
|
|
70
|
+
onPeerFileWrite?: ((file: string, content: string) => Promise<void>) | undefined;
|
|
71
|
+
peerMcpServers?: unknown[] | undefined;
|
|
72
|
+
tokenBudgetBasis?: 'total' | 'noncached' | undefined;
|
|
73
|
+
tools?: any[] | undefined;
|
|
74
|
+
temperature?: number | undefined;
|
|
75
|
+
maxTokens?: number | undefined;
|
|
76
|
+
jsonMode?: boolean | undefined;
|
|
77
|
+
timeoutMs?: number | undefined;
|
|
78
|
+
maxRetries?: number | undefined;
|
|
79
|
+
signal?: AbortSignal | undefined;
|
|
80
|
+
onChunk?: ((chunk: string) => void) | undefined;
|
|
81
|
+
onReasoningChunk?: ((chunk: string) => void) | undefined;
|
|
82
|
+
onNativeAction?: ((action: ChatResponseAction) => void) | undefined;
|
|
83
|
+
onPlanUpdate?: ((plan: unknown) => void) | undefined;
|
|
84
|
+
coreToolCount?: number | undefined;
|
|
85
|
+
[key: string]: any;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Fields the agent loop attaches to messages for its own bookkeeping. They must
|
|
89
|
+
// never reach a provider API, which rejects unknown message properties.
|
|
90
|
+
const INTERNAL_MESSAGE_FIELDS: readonly string[] = ['cacheAnchor', 'spillPath'];
|
|
91
|
+
|
|
92
|
+
// Container formats each vendor accepts for audio input.
|
|
93
|
+
const AUDIO_MIME_BY_FORMAT: Record<string, string> = {
|
|
94
|
+
wav: 'audio/wav',
|
|
95
|
+
mp3: 'audio/mpeg',
|
|
96
|
+
m4a: 'audio/mp4',
|
|
97
|
+
aac: 'audio/aac',
|
|
98
|
+
ogg: 'audio/ogg',
|
|
99
|
+
flac: 'audio/flac',
|
|
100
|
+
webm: 'audio/webm'
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/** Map a container format token to the MIME type a provider expects. */
|
|
104
|
+
export function mimeTypeForAudioFormat(format: unknown): string {
|
|
105
|
+
const key = String(format || '').trim().toLowerCase();
|
|
106
|
+
return Object.hasOwn(AUDIO_MIME_BY_FORMAT, key) ? AUDIO_MIME_BY_FORMAT[key]! : 'audio/wav';
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Map a MIME type to the short format token OpenAI's input_audio expects.
|
|
111
|
+
*/
|
|
112
|
+
export function audioFormatForMimeType(mimeType: unknown): string {
|
|
113
|
+
const mime = String(mimeType || '').toLowerCase().split(';')[0]?.trim() || '';
|
|
114
|
+
for (const [format, candidate] of Object.entries(AUDIO_MIME_BY_FORMAT)) {
|
|
115
|
+
if (candidate === mime) return format;
|
|
116
|
+
}
|
|
117
|
+
if (mime === 'audio/mp3' || mime === 'audio/x-mpeg') return 'mp3';
|
|
118
|
+
if (mime === 'audio/x-wav' || mime === 'audio/wave') return 'wav';
|
|
119
|
+
if (mime === 'audio/x-m4a') return 'm4a';
|
|
120
|
+
if (mime === 'audio/x-flac') return 'flac';
|
|
121
|
+
if (mime === 'audio/x-aac') return 'aac';
|
|
122
|
+
return 'wav';
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** True for an audio content block in either the OpenAI or the Gemini shape. */
|
|
126
|
+
export function isAudioBlock(block: any): boolean {
|
|
127
|
+
if (!block || typeof block !== 'object') return false;
|
|
128
|
+
if (block.type === 'input_audio') return true;
|
|
129
|
+
return Boolean(block.inlineData && String(block.inlineData.mimeType || '').startsWith('audio/'));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export class LLMProvider {
|
|
133
|
+
apiKey?: string | undefined;
|
|
134
|
+
model: string;
|
|
135
|
+
baseUrl?: string | undefined;
|
|
136
|
+
visionModels: string[];
|
|
137
|
+
imagePayloadFormat: string;
|
|
138
|
+
visionOverride: boolean | null;
|
|
139
|
+
audioModels: string[];
|
|
140
|
+
audioPayloadFormat: string;
|
|
141
|
+
maxAudioSeconds: number | null;
|
|
142
|
+
maxAudioBytes: number | null;
|
|
143
|
+
audioOverride: boolean | null;
|
|
144
|
+
preserveThinkingBlocks: boolean;
|
|
145
|
+
preserveReasoningContent: boolean;
|
|
146
|
+
|
|
147
|
+
constructor(config?: ProviderConfig | null) {
|
|
148
|
+
const cfg: ProviderConfig = config && typeof config === 'object' ? config : {};
|
|
149
|
+
this.apiKey = cfg.apiKey;
|
|
150
|
+
this.model = String(canonicalModelId(cfg.model ?? '') || '');
|
|
151
|
+
this.baseUrl = cfg.baseUrl;
|
|
152
|
+
this.visionModels = [];
|
|
153
|
+
this.imagePayloadFormat = 'openai';
|
|
154
|
+
this.visionOverride = typeof cfg.supportsVision === 'boolean'
|
|
155
|
+
? cfg.supportsVision
|
|
156
|
+
: null;
|
|
157
|
+
this.audioModels = [];
|
|
158
|
+
this.audioPayloadFormat = 'openai';
|
|
159
|
+
this.maxAudioSeconds = null;
|
|
160
|
+
this.maxAudioBytes = null;
|
|
161
|
+
this.audioOverride = typeof cfg.supportsAudio === 'boolean'
|
|
162
|
+
? cfg.supportsAudio
|
|
163
|
+
: null;
|
|
164
|
+
this.preserveThinkingBlocks = false;
|
|
165
|
+
this.preserveReasoningContent = true;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
get supportsVision(): boolean {
|
|
169
|
+
if (this.visionOverride !== null) return this.visionOverride;
|
|
170
|
+
const model = (this.model || '').toLowerCase();
|
|
171
|
+
return this.visionModels.some(prefix => prefix === '*' || model.includes(prefix));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
audioAlternative(): string | null {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async transcribeAudio(_base64?: string, _mimeType?: string, _options?: Record<string, any>): Promise<string | null> {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
get canTranscribe(): boolean {
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
get supportsAudio(): boolean {
|
|
187
|
+
if (this.audioOverride !== null) return this.audioOverride;
|
|
188
|
+
const model = (this.model || '').toLowerCase();
|
|
189
|
+
return this.audioModels.some(prefix => prefix === '*' || model.includes(prefix));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async chat(_messages: any[], _options: ChatOptions = {}): Promise<ChatResponse> {
|
|
193
|
+
throw new Error('chat() must be implemented by provider');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
prepareMessages(messages: any[]): any[] {
|
|
197
|
+
const clean = this.stripInternalFields(messages);
|
|
198
|
+
|
|
199
|
+
const shaped = this.supportsVision
|
|
200
|
+
? clean.map(msg => this.normalizeImageBlocks(msg))
|
|
201
|
+
: clean.map(msg => this.flattenToTextOnly(msg));
|
|
202
|
+
|
|
203
|
+
return this.supportsAudio
|
|
204
|
+
? shaped.map(msg => this.normalizeAudioBlocks(msg))
|
|
205
|
+
: shaped.map(msg => this.stripAudioBlocks(msg));
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
normalizeAudioBlocks(msg: any): any {
|
|
209
|
+
if (!Array.isArray(msg.content)) return msg;
|
|
210
|
+
|
|
211
|
+
const content = msg.content.map((block: any) => {
|
|
212
|
+
if (!block || typeof block !== 'object') return block;
|
|
213
|
+
|
|
214
|
+
if (this.audioPayloadFormat === 'gemini') {
|
|
215
|
+
if (block.type === 'input_audio') {
|
|
216
|
+
return {
|
|
217
|
+
inlineData: {
|
|
218
|
+
mimeType: mimeTypeForAudioFormat(block.input_audio?.format),
|
|
219
|
+
data: block.input_audio?.data
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
return block;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (block.inlineData && String(block.inlineData.mimeType || '').startsWith('audio/')) {
|
|
227
|
+
return {
|
|
228
|
+
type: 'input_audio',
|
|
229
|
+
input_audio: {
|
|
230
|
+
data: block.inlineData.data,
|
|
231
|
+
format: audioFormatForMimeType(block.inlineData.mimeType)
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
return block;
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
return { ...msg, content };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
stripAudioBlocks(msg: any): any {
|
|
242
|
+
if (!Array.isArray(msg.content)) return msg;
|
|
243
|
+
if (!msg.content.some(isAudioBlock)) return msg;
|
|
244
|
+
|
|
245
|
+
const content = msg.content
|
|
246
|
+
.filter((block: any) => !isAudioBlock(block))
|
|
247
|
+
.concat([{
|
|
248
|
+
type: 'text',
|
|
249
|
+
text: '[Audio content removed — the selected model cannot process audio. Causyne transcribed the request on-device instead where possible.]'
|
|
250
|
+
}]);
|
|
251
|
+
|
|
252
|
+
return { ...msg, content };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
normalizeImageBlocks(msg: any): any {
|
|
256
|
+
if (!Array.isArray(msg.content)) return msg;
|
|
257
|
+
if (this.imagePayloadFormat === 'anthropic') {
|
|
258
|
+
const content = msg.content.map((block: any) => {
|
|
259
|
+
if (block && block.type === 'image_url' && typeof block.image_url?.url === 'string') {
|
|
260
|
+
const commaIdx = block.image_url.url.indexOf('base64,');
|
|
261
|
+
if (commaIdx !== -1 && block.image_url.url.startsWith('data:')) {
|
|
262
|
+
const rawMedia = (block.image_url.url.slice(5, commaIdx).split(';')[0] || 'image/png').trim().toLowerCase();
|
|
263
|
+
const mediaType = rawMedia === 'image/jpg' ? 'image/jpeg' : rawMedia;
|
|
264
|
+
const data = block.image_url.url.slice(commaIdx + 7);
|
|
265
|
+
if (data) return { type: 'image', source: { type: 'base64', media_type: mediaType, data } };
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return block;
|
|
269
|
+
});
|
|
270
|
+
return { ...msg, content };
|
|
271
|
+
}
|
|
272
|
+
if (this.imagePayloadFormat !== 'openai') return msg;
|
|
273
|
+
|
|
274
|
+
const content = msg.content.map((block: any) => {
|
|
275
|
+
if (block && block.type === 'image' && block.source?.type === 'base64' && typeof block.source.data === 'string' && block.source.data) {
|
|
276
|
+
const mime = typeof block.source.media_type === 'string' && block.source.media_type ? block.source.media_type : 'image/png';
|
|
277
|
+
return {
|
|
278
|
+
type: 'image_url',
|
|
279
|
+
image_url: { url: `data:${mime};base64,${block.source.data}` }
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
return block;
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
return { ...msg, content };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
flattenToTextOnly(msg: any): any {
|
|
289
|
+
if (!Array.isArray(msg.content)) return msg;
|
|
290
|
+
|
|
291
|
+
const audioBlocks = this.supportsAudio ? msg.content.filter(isAudioBlock) : [];
|
|
292
|
+
|
|
293
|
+
const textParts = msg.content
|
|
294
|
+
.filter((block: any) => block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string')
|
|
295
|
+
.map((block: any) => block.text);
|
|
296
|
+
|
|
297
|
+
const text = textParts.join('\n') ||
|
|
298
|
+
'[Image content removed — not supported by this model]';
|
|
299
|
+
|
|
300
|
+
if (audioBlocks.length === 0) return { ...msg, content: text };
|
|
301
|
+
|
|
302
|
+
return { ...msg, content: [{ type: 'text', text }, ...audioBlocks] };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
stripInternalFields(messages: any[]): any[] {
|
|
306
|
+
if (!Array.isArray(messages)) return [];
|
|
307
|
+
const fieldsToStrip: string[] = [...INTERNAL_MESSAGE_FIELDS, 'thoughtSignature'];
|
|
308
|
+
if (!this.preserveThinkingBlocks) fieldsToStrip.push('thinking_blocks');
|
|
309
|
+
if (!this.preserveReasoningContent) fieldsToStrip.push('reasoning_content');
|
|
310
|
+
return messages.filter((msg) => msg && typeof msg === 'object').map(msg => {
|
|
311
|
+
let needsCopy = false;
|
|
312
|
+
for (const field of fieldsToStrip) {
|
|
313
|
+
if (field in msg) { needsCopy = true; break; }
|
|
314
|
+
}
|
|
315
|
+
if (!needsCopy) return msg;
|
|
316
|
+
|
|
317
|
+
const clean = { ...msg };
|
|
318
|
+
for (const field of fieldsToStrip) delete clean[field];
|
|
319
|
+
return clean;
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
normalizeUsage(rawUsage: any): ChatResponseUsage {
|
|
324
|
+
const nonNeg = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
|
|
325
|
+
const promptTokens = nonNeg(rawUsage?.prompt_tokens);
|
|
326
|
+
const completionTokens = nonNeg(rawUsage?.completion_tokens);
|
|
327
|
+
const rawCached =
|
|
328
|
+
rawUsage?.prompt_tokens_details?.cached_tokens ??
|
|
329
|
+
rawUsage?.prompt_cache_hit_tokens ??
|
|
330
|
+
rawUsage?.cache_read_input_tokens ??
|
|
331
|
+
0;
|
|
332
|
+
const cachedPromptTokens = Math.min(nonNeg(rawCached), promptTokens);
|
|
333
|
+
|
|
334
|
+
return {
|
|
335
|
+
promptTokens,
|
|
336
|
+
completionTokens,
|
|
337
|
+
cachedPromptTokens
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
}
|
|
@@ -31,7 +31,12 @@ export class ProviderHttpError extends Error {
|
|
|
31
31
|
* Preserve explicit `0` temperature (unlike `options.temperature || 0.1`).
|
|
32
32
|
*/
|
|
33
33
|
export function resolveTemperature(value, fallback = 0.1) {
|
|
34
|
-
|
|
34
|
+
const safeFallback = typeof fallback === 'number' && Number.isFinite(fallback)
|
|
35
|
+
? Math.min(2, Math.max(0, fallback))
|
|
36
|
+
: 0.1;
|
|
37
|
+
if (typeof value !== 'number' || !Number.isFinite(value))
|
|
38
|
+
return safeFallback;
|
|
39
|
+
return Math.min(2, Math.max(0, value));
|
|
35
40
|
}
|
|
36
41
|
/**
|
|
37
42
|
* Validate that a required cloud BYOK API key is present before issuing a request.
|
|
@@ -41,6 +46,9 @@ export function requireApiKey(apiKey, providerLabel) {
|
|
|
41
46
|
if (!trimmed) {
|
|
42
47
|
throw new Error(`${providerLabel} API requires a valid API key (BYOK mode). Configure it with \`causyne config\`.`);
|
|
43
48
|
}
|
|
49
|
+
if (/[\r\n\0]/.test(trimmed)) {
|
|
50
|
+
throw new Error(`${providerLabel} API key contains invalid control characters.`);
|
|
51
|
+
}
|
|
44
52
|
return trimmed;
|
|
45
53
|
}
|
|
46
54
|
/**
|
|
@@ -56,8 +64,15 @@ export function isLoopbackHost(rawHostname) {
|
|
|
56
64
|
.replace(/\.$/, '');
|
|
57
65
|
if (!host)
|
|
58
66
|
return false;
|
|
59
|
-
if (host === 'localhost'
|
|
67
|
+
if (host === 'localhost'
|
|
68
|
+
|| host.endsWith('.localhost')
|
|
69
|
+
|| host === '::1'
|
|
70
|
+
|| host === '0:0:0:0:0:0:0:1'
|
|
71
|
+
|| /^::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(host))
|
|
60
72
|
return true;
|
|
73
|
+
if (host.startsWith('::ffff:127.')) {
|
|
74
|
+
return isLoopbackHost(host.slice(7));
|
|
75
|
+
}
|
|
61
76
|
if (host.startsWith('127.')) {
|
|
62
77
|
const octets = host.split('.');
|
|
63
78
|
return octets.length === 4 && octets.every((part) => {
|
|
@@ -80,6 +95,9 @@ export function validateProviderEndpointUrl(rawUrl, options = {}) {
|
|
|
80
95
|
if (!trimmed) {
|
|
81
96
|
throw new Error(`${label} endpoint URL is required.`);
|
|
82
97
|
}
|
|
98
|
+
if (/[\x00-\x1f\x7f]/.test(trimmed)) {
|
|
99
|
+
throw new Error(`${label} endpoint URL contains invalid control characters.`);
|
|
100
|
+
}
|
|
83
101
|
let parsed;
|
|
84
102
|
try {
|
|
85
103
|
parsed = new URL(trimmed);
|
|
@@ -93,11 +111,17 @@ export function validateProviderEndpointUrl(rawUrl, options = {}) {
|
|
|
93
111
|
if (parsed.username || parsed.password) {
|
|
94
112
|
throw new Error(`${label} endpoint URL must not embed credentials.`);
|
|
95
113
|
}
|
|
114
|
+
for (const param of parsed.searchParams.keys()) {
|
|
115
|
+
const lowered = param.toLowerCase();
|
|
116
|
+
if (lowered === 'key' || lowered === 'api_key' || lowered === 'apikey' || lowered === 'access_token') {
|
|
117
|
+
throw new Error(`${label} endpoint URL must not embed API keys in query parameters.`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
96
120
|
if (parsed.protocol === 'http:'
|
|
97
121
|
&& options.hasApiKey === true
|
|
98
122
|
&& options.allowInsecureHttp !== true
|
|
99
123
|
&& !isLoopbackHost(parsed.hostname)) {
|
|
100
|
-
throw new Error(`${label} refused to send an API key over unencrypted remote HTTP (${parsed.hostname}). Use https:// or set allowInsecureHttp: true for a trusted private network.`);
|
|
124
|
+
throw new Error(`${label} refused to send an API key over unencrypted remote HTTP (${safeDisplay(parsed.hostname)}). Use https:// or set allowInsecureHttp: true for a trusted private network.`);
|
|
101
125
|
}
|
|
102
126
|
return parsed.toString();
|
|
103
127
|
}
|
|
@@ -110,11 +134,11 @@ export function parseRetryAfterMs(headerValue) {
|
|
|
110
134
|
const trimmed = headerValue.trim();
|
|
111
135
|
if (!trimmed)
|
|
112
136
|
return undefined;
|
|
113
|
-
if (/^\d
|
|
137
|
+
if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
|
|
114
138
|
const seconds = Number(trimmed);
|
|
115
139
|
if (!Number.isFinite(seconds) || seconds < 0)
|
|
116
140
|
return undefined;
|
|
117
|
-
return Math.min(seconds * 1000, 300_000);
|
|
141
|
+
return Math.min(Math.ceil(seconds * 1000), 300_000);
|
|
118
142
|
}
|
|
119
143
|
const parsedDate = Date.parse(trimmed);
|
|
120
144
|
if (Number.isFinite(parsedDate)) {
|
|
@@ -144,7 +168,8 @@ export function redactProviderSecrets(rawText, secrets = []) {
|
|
|
144
168
|
// Linear-time token masks (no nested quantifiers / zero ReDoS risk).
|
|
145
169
|
text = text.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{6,}/gi, 'Bearer [REDACTED]');
|
|
146
170
|
text = text.replace(/([?&](?:api_?)?key=)[^&\s"']+/gi, '$1[REDACTED]');
|
|
147
|
-
text = text.replace(/\b(?:
|
|
171
|
+
text = text.replace(/\b(x-(?:goog-)?api-key\s*[:=]\s*)[A-Za-z0-9._~+/=-]{6,}/gi, '$1[REDACTED]');
|
|
172
|
+
text = text.replace(/\b(?:sk-[A-Za-z0-9_-]{12,}|AIza[A-Za-z0-9_-]{20,}|xai-[A-Za-z0-9_-]{12,}|gsk_[A-Za-z0-9_-]{12,}|ya29\.[A-Za-z0-9._-]{16,})\b/g, '[REDACTED]');
|
|
148
173
|
if (text.length > MAX_PROVIDER_ERROR_CHARS) {
|
|
149
174
|
return `${text.slice(0, MAX_PROVIDER_ERROR_CHARS)}…`;
|
|
150
175
|
}
|
|
@@ -172,7 +197,11 @@ async function cancelBodySafely(response) {
|
|
|
172
197
|
* hostile or misconfigured upstream cannot exhaust host RAM.
|
|
173
198
|
*/
|
|
174
199
|
export async function readBoundedResponseText(response, maxBytes, options = {}) {
|
|
175
|
-
|
|
200
|
+
if (!response)
|
|
201
|
+
return '';
|
|
202
|
+
const limit = typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes >= 1
|
|
203
|
+
? Math.floor(maxBytes)
|
|
204
|
+
: MAX_PROVIDER_JSON_BYTES;
|
|
176
205
|
const declaredLen = getHeaderCaseInsensitive(response, 'content-length');
|
|
177
206
|
if (!options.truncate && declaredLen && /^\d+$/.test(declaredLen.trim())) {
|
|
178
207
|
const contentLength = Number(declaredLen.trim());
|
|
@@ -217,7 +246,7 @@ export async function readBoundedResponseText(response, maxBytes, options = {})
|
|
|
217
246
|
const byteLen = Buffer.byteLength(text, 'utf8');
|
|
218
247
|
if (byteLen > limit) {
|
|
219
248
|
if (options.truncate)
|
|
220
|
-
return text.
|
|
249
|
+
return Buffer.from(text, 'utf8').subarray(0, limit).toString('utf8');
|
|
221
250
|
throw new Error(`${options.label || 'Provider'} response exceeded maximum allowed size (${limit} bytes).`);
|
|
222
251
|
}
|
|
223
252
|
return text;
|
|
@@ -244,9 +273,7 @@ function isAbortLikeError(err) {
|
|
|
244
273
|
* - Secret redaction on thrown network errors
|
|
245
274
|
*/
|
|
246
275
|
export async function safeProviderFetch(options) {
|
|
247
|
-
const hasKey = options.hasApiKey ??
|
|
248
|
-
|| options.headers?.['x-api-key']
|
|
249
|
-
|| options.headers?.['x-goog-api-key']);
|
|
276
|
+
const hasKey = options.hasApiKey ?? Object.entries(options.headers ?? {}).some(([k, v]) => /^(?:authorization|x-api-key|x-goog-api-key)$/i.test(k) && Boolean(v));
|
|
250
277
|
const safeUrl = validateProviderEndpointUrl(options.url, {
|
|
251
278
|
hasApiKey: hasKey,
|
|
252
279
|
allowInsecureHttp: options.allowInsecureHttp,
|
|
@@ -283,8 +310,15 @@ export async function safeProviderFetch(options) {
|
|
|
283
310
|
redirect: 'error',
|
|
284
311
|
signal: controller.signal
|
|
285
312
|
};
|
|
286
|
-
if (options.headers)
|
|
313
|
+
if (options.headers) {
|
|
314
|
+
for (const [headerName, headerVal] of Object.entries(options.headers)) {
|
|
315
|
+
if (/[\r\n\0]/.test(headerName) || (typeof headerVal === 'string' && /[\r\n\0]/.test(headerVal))) {
|
|
316
|
+
cleanup();
|
|
317
|
+
throw new Error(`${options.providerLabel} request header contains invalid control characters.`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
287
320
|
fetchInit.headers = options.headers;
|
|
321
|
+
}
|
|
288
322
|
if (options.body !== undefined)
|
|
289
323
|
fetchInit.body = options.body;
|
|
290
324
|
try {
|
|
@@ -308,7 +342,9 @@ export async function safeProviderFetch(options) {
|
|
|
308
342
|
throw new Error(`${options.providerLabel} refused an HTTP redirect to protect API credentials.`);
|
|
309
343
|
}
|
|
310
344
|
const safeMsg = redactProviderSecrets(rawMsg, options.secrets);
|
|
311
|
-
|
|
345
|
+
const safeCause = causeMsg ? redactProviderSecrets(causeMsg, options.secrets) : '';
|
|
346
|
+
const detail = safeCause && !safeMsg.includes(safeCause) ? `${safeMsg} (${safeCause})` : safeMsg;
|
|
347
|
+
throw new Error(`${options.providerLabel} network error: ${detail}`);
|
|
312
348
|
}
|
|
313
349
|
}
|
|
314
350
|
/**
|
|
@@ -337,11 +373,18 @@ export async function safeProviderFetchJson(options) {
|
|
|
337
373
|
}
|
|
338
374
|
// Minimal unit-test mocks may supply `.json()` without `.body` or `.text()`.
|
|
339
375
|
if (!response.body && typeof response.text !== 'function' && typeof response.json === 'function') {
|
|
340
|
-
|
|
376
|
+
try {
|
|
377
|
+
return (await response.json());
|
|
378
|
+
}
|
|
379
|
+
catch (err) {
|
|
380
|
+
const safeErr = redactProviderSecrets(err instanceof Error ? err.message : String(err), options.secrets);
|
|
381
|
+
throw new Error(`${options.providerLabel} returned a non-JSON response (HTTP ${response.status}): ${safeErr}`);
|
|
382
|
+
}
|
|
341
383
|
}
|
|
342
384
|
const rawText = await readBoundedResponseText(response, options.maxBytes ?? MAX_PROVIDER_JSON_BYTES, { truncate: false, label: options.providerLabel });
|
|
385
|
+
const cleanText = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
|
|
343
386
|
try {
|
|
344
|
-
return JSON.parse(
|
|
387
|
+
return JSON.parse(cleanText);
|
|
345
388
|
}
|
|
346
389
|
catch {
|
|
347
390
|
const preview = redactProviderSecrets(rawText.slice(0, 240), options.secrets);
|