@causyne/agent 1.20.118 → 1.20.121
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/package.json +1 -1
- package/src/agent/errorClassifier.js +113 -0
- package/src/agent/errorClassifier.ts +161 -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 +51 -351
- package/src/agentLoop.ts +69 -363
- package/src/autoUpdate.js +111 -8
- package/src/autoUpdate.ts +144 -8
- package/src/browser/causyneBrowser.js +231 -136
- package/src/browser/causyneBrowser.ts +229 -140
- package/src/browser/searchProviders.js +41 -30
- package/src/browser/searchProviders.ts +24 -14
- package/src/browser/workspacePathSafety.js +50 -0
- package/src/browser/workspacePathSafety.ts +50 -0
- package/src/browser/workspacePreview.js +27 -4
- package/src/browser/workspacePreview.ts +28 -4
- package/src/cliMode.js +17 -3
- package/src/commands.js +15 -22
- package/src/config.js +42 -63
- package/src/configVault.js +204 -0
- package/src/configVault.ts +213 -0
- package/src/core/contextCompactor.js +70 -11
- package/src/core/contextCompactor.ts +83 -11
- package/src/creative/liveBridge.js +34 -1
- package/src/creative/liveBridge.ts +28 -1
- package/src/dynamicCatalogue.js +42 -73
- package/src/dynamicCatalogue.ts +74 -60
- package/src/entrypoint.js +77 -4
- package/src/headlessCli.js +304 -0
- package/src/headlessCli.ts +380 -0
- 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/observer/evidence.js +23 -0
- package/src/observer/evidence.ts +21 -0
- package/src/osKeychain.js +209 -0
- package/src/osKeychain.ts +245 -0
- package/src/providers/anthropic.js +61 -28
- package/src/providers/base.js +14 -0
- package/src/providers/byokHttp.js +354 -0
- package/src/providers/byokHttp.ts +454 -0
- package/src/providers/byokStream.js +657 -0
- package/src/providers/byokStream.ts +759 -0
- package/src/providers/dashscope-byok.js +47 -32
- package/src/providers/deepseek.js +43 -39
- package/src/providers/gemini.js +73 -38
- package/src/providers/moonshot.js +43 -33
- package/src/providers/muse.js +10 -10
- package/src/providers/ollama.js +46 -31
- package/src/providers/openai-compatible.js +57 -32
- package/src/providers/openrouter.js +77 -113
- package/src/providers/openrouter.ts +99 -118
- package/src/providers/qwen-byok.js +46 -23
- package/src/providers/toolContracts.js +9 -3
- package/src/providers/toolContracts.ts +9 -3
- package/src/providers/wireNormalizer.js +238 -0
- package/src/providers/wireNormalizer.ts +279 -0
- package/src/providers/xai.js +43 -33
- package/src/sandbox.js +77 -56
- package/src/sandboxPolicy.js +1208 -0
- package/src/sandboxPolicy.ts +1300 -0
- package/src/sessionJournal.js +47 -0
- package/src/sessionJournal.ts +49 -0
- package/src/tools/browserAutomator.js +13 -1
- package/src/tools/browserAutomator.ts +13 -0
- package/src/tools/creativeApps.js +2 -1
- package/src/tools/creativeApps.ts +2 -1
- package/src/tools/gameAssetFetcher.js +130 -26
- package/src/tools/gameAssetHarvester.js +80 -58
- package/src/tools/nativeEngine.js +1 -1
- package/src/tools/nativeEngine.ts +1 -1
- package/src/tools/osSandbox.js +473 -0
- package/src/tools/osSandbox.ts +554 -0
- package/src/tools/persistentShell.js +8 -3
- package/src/tools/registry.js +13 -0
- package/src/tools/subprocessEnv.js +197 -0
- package/src/tools/subprocessEnv.ts +212 -0
- package/src/tools/sysRun.js +39 -6
- package/src/tools/sysRun.ts +53 -7
- package/src/tools/toolScanner.js +596 -140
- package/src/tools/toolScanner.ts +665 -147
- package/src/tools/toolSelfRepair.js +243 -114
- package/src/tools/toolSelfRepair.ts +262 -111
- package/src/tools/webFetch.js +161 -24
- package/src/tools/webFetch.ts +157 -22
- package/src/tools/webSearch.js +33 -4
- package/src/tools/webSearch.ts +27 -4
- package/src/tui/sessionPicker.js +132 -35
- package/src/tui/sessionPicker.ts +153 -32
- package/src/tui/sessionPickerView.js +277 -34
- package/src/tui/sessionPickerView.ts +328 -34
- package/src/tui/statusLine.js +3 -0
- package/src/tui/statusLine.ts +5 -0
- package/src/tui/workspaceIdentity.js +133 -0
- package/src/tui/workspaceIdentity.ts +146 -0
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — Universal Provider Wire Normalizer
|
|
3
|
+
*
|
|
4
|
+
* Shared pure helpers for all LLM provider adapters so tool definitions,
|
|
5
|
+
* historical tool calls, multimodal blocks, and responses follow one
|
|
6
|
+
* lossless universal contract without duplicating normalization code.
|
|
7
|
+
*/
|
|
8
|
+
import { normalizeToolName, decodeFreeFormArguments } from '../tools/toolScanner.js';
|
|
9
|
+
import { repairJsonArguments } from '../tools/toolSelfRepair.js';
|
|
10
|
+
import { extractToolCallJsonObjects, resolveToolCallEnvelopeArguments, stripToolCallMarkup } from '../implementationPlan.js';
|
|
11
|
+
const VALID_ID_CHARS = /[^a-zA-Z0-9_-]/g;
|
|
12
|
+
function isPlainObject(value) {
|
|
13
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Safely parse tool arguments (JSON string, malformed JSON string, or object) into an object.
|
|
17
|
+
* Never throws on malformed historical messages.
|
|
18
|
+
*/
|
|
19
|
+
export function safeParseJsonObject(raw) {
|
|
20
|
+
if (isPlainObject(raw))
|
|
21
|
+
return raw;
|
|
22
|
+
if (typeof raw !== 'string')
|
|
23
|
+
return {};
|
|
24
|
+
const trimmed = raw.trim();
|
|
25
|
+
if (!trimmed || trimmed === '{}')
|
|
26
|
+
return {};
|
|
27
|
+
try {
|
|
28
|
+
const parsed = JSON.parse(trimmed);
|
|
29
|
+
if (isPlainObject(parsed))
|
|
30
|
+
return parsed;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// Fall through to deterministic syntax recovery
|
|
34
|
+
}
|
|
35
|
+
const repaired = repairJsonArguments(trimmed);
|
|
36
|
+
if (!repaired.error && isPlainObject(repaired.args)) {
|
|
37
|
+
return repaired.args;
|
|
38
|
+
}
|
|
39
|
+
return {};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Guarantee a valid tool call ID matching ^[a-zA-Z0-9_-]{1,64}$.
|
|
43
|
+
*/
|
|
44
|
+
export function sanitizeProviderToolId(rawId, prefix = 'call', index = 0) {
|
|
45
|
+
const cleaned = typeof rawId === 'string'
|
|
46
|
+
? rawId.trim().replace(VALID_ID_CHARS, '_')
|
|
47
|
+
: '';
|
|
48
|
+
if (cleaned.length > 0)
|
|
49
|
+
return cleaned.slice(0, 64);
|
|
50
|
+
return `${prefix.replace(VALID_ID_CHARS, '_')}_${Date.now()}_${index}`.slice(0, 64);
|
|
51
|
+
}
|
|
52
|
+
function resolveFreeFormPaths(toolName, freeFormPaths) {
|
|
53
|
+
if (!freeFormPaths || freeFormPaths.size === 0)
|
|
54
|
+
return undefined;
|
|
55
|
+
return freeFormPaths.get(normalizeToolName(toolName)) || freeFormPaths.get(toolName);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Serialize arguments cleanly to a JSON string while decoding any adapted free-form paths.
|
|
59
|
+
*/
|
|
60
|
+
export function serializeAndDecodeArguments(rawArgs, toolName, freeFormPaths) {
|
|
61
|
+
const paths = resolveFreeFormPaths(toolName, freeFormPaths);
|
|
62
|
+
if (typeof rawArgs === 'string') {
|
|
63
|
+
if (!paths || paths.length === 0)
|
|
64
|
+
return rawArgs;
|
|
65
|
+
const obj = safeParseJsonObject(rawArgs);
|
|
66
|
+
if (Object.keys(obj).length === 0)
|
|
67
|
+
return rawArgs;
|
|
68
|
+
const decoded = decodeFreeFormArguments(structuredClone(obj), paths);
|
|
69
|
+
return JSON.stringify(decoded);
|
|
70
|
+
}
|
|
71
|
+
const obj = isPlainObject(rawArgs) ? structuredClone(rawArgs) : {};
|
|
72
|
+
const finalObj = paths && paths.length > 0 ? decodeFreeFormArguments(obj, paths) : obj;
|
|
73
|
+
try {
|
|
74
|
+
return JSON.stringify(finalObj);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return '{}';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Extract tool calls embedded as <tool_call>{...}</tool_call> text envelopes.
|
|
82
|
+
*/
|
|
83
|
+
export function extractTextToolCalls(text, prefix = 'call_text', freeFormPaths) {
|
|
84
|
+
const calls = [];
|
|
85
|
+
if (!text || typeof text !== 'string')
|
|
86
|
+
return calls;
|
|
87
|
+
let index = 0;
|
|
88
|
+
for (const parsed of extractToolCallJsonObjects(text)) {
|
|
89
|
+
const fnObj = isPlainObject(parsed['function']) ? parsed['function'] : null;
|
|
90
|
+
const rawName = String(parsed['name'] || parsed['tool'] || fnObj?.['name'] || '').trim();
|
|
91
|
+
if (!rawName)
|
|
92
|
+
continue;
|
|
93
|
+
const name = normalizeToolName(rawName);
|
|
94
|
+
const rawArgs = resolveToolCallEnvelopeArguments(parsed);
|
|
95
|
+
calls.push({
|
|
96
|
+
id: sanitizeProviderToolId(parsed['id'], prefix, index++),
|
|
97
|
+
type: 'function',
|
|
98
|
+
function: {
|
|
99
|
+
name,
|
|
100
|
+
arguments: serializeAndDecodeArguments(rawArgs, name, freeFormPaths)
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return calls;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Normalize native OpenAI / Ollama / proxy tool_calls into one canonical Causyne contract.
|
|
108
|
+
*/
|
|
109
|
+
export function normalizeOpenAIToolCalls(rawCalls, freeFormPaths, prefix = 'call') {
|
|
110
|
+
if (!Array.isArray(rawCalls))
|
|
111
|
+
return [];
|
|
112
|
+
const normalized = [];
|
|
113
|
+
for (let i = 0; i < rawCalls.length; i++) {
|
|
114
|
+
const tc = rawCalls[i];
|
|
115
|
+
if (!isPlainObject(tc))
|
|
116
|
+
continue;
|
|
117
|
+
const fnObj = isPlainObject(tc['function']) ? tc['function'] : null;
|
|
118
|
+
const rawName = String(fnObj?.['name'] || tc['name'] || '').trim();
|
|
119
|
+
if (!rawName)
|
|
120
|
+
continue;
|
|
121
|
+
const name = normalizeToolName(rawName);
|
|
122
|
+
const rawArgs = fnObj ? fnObj['arguments'] : tc['arguments'];
|
|
123
|
+
normalized.push({
|
|
124
|
+
id: sanitizeProviderToolId(tc['id'], prefix, i),
|
|
125
|
+
type: 'function',
|
|
126
|
+
function: {
|
|
127
|
+
name,
|
|
128
|
+
arguments: serializeAndDecodeArguments(rawArgs ?? {}, name, freeFormPaths)
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
return normalized;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Normalize an OpenAI-compatible (or DeepSeek proxy) JSON response into standard ChatResponse parts,
|
|
136
|
+
* including automatic fallback extraction of XML <tool_call> text envelopes.
|
|
137
|
+
*/
|
|
138
|
+
export function normalizeOpenAIChatChoiceResponse(data, options = {}) {
|
|
139
|
+
const payload = isPlainObject(data) ? data : {};
|
|
140
|
+
const prefix = options.prefix || 'call';
|
|
141
|
+
let content = '';
|
|
142
|
+
let reasoningContent = '';
|
|
143
|
+
let rawToolCalls = undefined;
|
|
144
|
+
if (payload['reply'] !== undefined) {
|
|
145
|
+
content = typeof payload['reply'] === 'string' ? payload['reply'] : '';
|
|
146
|
+
rawToolCalls = payload['tool_calls'];
|
|
147
|
+
}
|
|
148
|
+
else if (Array.isArray(payload['choices']) && payload['choices'].length > 0) {
|
|
149
|
+
const choice = isPlainObject(payload['choices'][0]) ? payload['choices'][0] : null;
|
|
150
|
+
const message = choice && isPlainObject(choice['message']) ? choice['message'] : null;
|
|
151
|
+
if (message) {
|
|
152
|
+
content = typeof message['content'] === 'string' ? message['content'] : '';
|
|
153
|
+
rawToolCalls = message['tool_calls'];
|
|
154
|
+
const rc = message['reasoning_content'] ?? message['reasoning'];
|
|
155
|
+
reasoningContent = typeof rc === 'string' ? rc : '';
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
let toolCalls = normalizeOpenAIToolCalls(rawToolCalls, options.freeFormPaths, prefix);
|
|
159
|
+
if (toolCalls.length === 0 && content) {
|
|
160
|
+
const extracted = extractTextToolCalls(content, `${prefix}_text`, options.freeFormPaths);
|
|
161
|
+
if (extracted.length > 0) {
|
|
162
|
+
toolCalls = extracted;
|
|
163
|
+
if (options.stripToolMarkup !== false) {
|
|
164
|
+
content = stripToolCallMarkup(content).trim();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const rawUsage = isPlainObject(payload['usage'])
|
|
169
|
+
? payload['usage']
|
|
170
|
+
: { prompt_tokens: 0, completion_tokens: 0 };
|
|
171
|
+
const result = {
|
|
172
|
+
content,
|
|
173
|
+
rawUsage
|
|
174
|
+
};
|
|
175
|
+
if (toolCalls.length > 0)
|
|
176
|
+
result.toolCalls = toolCalls;
|
|
177
|
+
if (reasoningContent)
|
|
178
|
+
result.reasoningContent = reasoningContent;
|
|
179
|
+
return result;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Prepare messages for Anthropic: runs multimodal image/audio normalization and strips internal
|
|
183
|
+
* fields from non-system turns while preserving `cacheAnchor` on `system` turns so Anthropic's
|
|
184
|
+
* cache_control placement remains intact.
|
|
185
|
+
*/
|
|
186
|
+
export function prepareMessagesForAnthropic(provider, messages) {
|
|
187
|
+
if (!Array.isArray(messages))
|
|
188
|
+
return [];
|
|
189
|
+
const prepared = [];
|
|
190
|
+
for (const msg of messages) {
|
|
191
|
+
if (!isPlainObject(msg))
|
|
192
|
+
continue;
|
|
193
|
+
if (msg['role'] === 'system') {
|
|
194
|
+
const { spillPath: _spill, ...rest } = msg;
|
|
195
|
+
prepared.push(rest);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
const [cleaned] = provider.stripInternalFields([msg]);
|
|
199
|
+
const visual = provider.supportsVision
|
|
200
|
+
? provider.normalizeImageBlocks(cleaned)
|
|
201
|
+
: provider.flattenToTextOnly(cleaned);
|
|
202
|
+
const audioReady = provider.supportsAudio
|
|
203
|
+
? provider.normalizeAudioBlocks(visual)
|
|
204
|
+
: provider.stripAudioBlocks(visual);
|
|
205
|
+
prepared.push(audioReady);
|
|
206
|
+
}
|
|
207
|
+
return prepared;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Convert OpenAI JSON-string tool_calls arguments into objects for Ollama `/api/chat` history.
|
|
211
|
+
*/
|
|
212
|
+
export function normalizeMessagesForOllama(messages) {
|
|
213
|
+
if (!Array.isArray(messages))
|
|
214
|
+
return [];
|
|
215
|
+
return messages.map((msg) => {
|
|
216
|
+
if (!isPlainObject(msg) || msg['role'] !== 'assistant' || !Array.isArray(msg['tool_calls'])) {
|
|
217
|
+
return msg;
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
...msg,
|
|
221
|
+
tool_calls: msg['tool_calls'].map((tc) => {
|
|
222
|
+
if (!isPlainObject(tc))
|
|
223
|
+
return tc;
|
|
224
|
+
const fn = isPlainObject(tc['function']) ? tc['function'] : null;
|
|
225
|
+
if (!fn)
|
|
226
|
+
return tc;
|
|
227
|
+
return {
|
|
228
|
+
...tc,
|
|
229
|
+
function: {
|
|
230
|
+
...fn,
|
|
231
|
+
name: normalizeToolName(String(fn['name'] || '')),
|
|
232
|
+
arguments: safeParseJsonObject(fn['arguments'])
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
})
|
|
236
|
+
};
|
|
237
|
+
});
|
|
238
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — Universal Provider Wire Normalizer
|
|
3
|
+
*
|
|
4
|
+
* Shared pure helpers for all LLM provider adapters so tool definitions,
|
|
5
|
+
* historical tool calls, multimodal blocks, and responses follow one
|
|
6
|
+
* lossless universal contract without duplicating normalization code.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
normalizeToolName,
|
|
11
|
+
decodeFreeFormArguments
|
|
12
|
+
} from '../tools/toolScanner.js';
|
|
13
|
+
import { repairJsonArguments } from '../tools/toolSelfRepair.js';
|
|
14
|
+
import {
|
|
15
|
+
extractToolCallJsonObjects,
|
|
16
|
+
resolveToolCallEnvelopeArguments,
|
|
17
|
+
stripToolCallMarkup
|
|
18
|
+
} from '../implementationPlan.js';
|
|
19
|
+
import type { ChatResponseToolCall } from './base.d.js';
|
|
20
|
+
|
|
21
|
+
export interface NormalizedChoiceResult {
|
|
22
|
+
content: string;
|
|
23
|
+
toolCalls?: ChatResponseToolCall[];
|
|
24
|
+
reasoningContent?: string;
|
|
25
|
+
rawUsage: Record<string, unknown>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const VALID_ID_CHARS = /[^a-zA-Z0-9_-]/g;
|
|
29
|
+
|
|
30
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
31
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Safely parse tool arguments (JSON string, malformed JSON string, or object) into an object.
|
|
36
|
+
* Never throws on malformed historical messages.
|
|
37
|
+
*/
|
|
38
|
+
export function safeParseJsonObject(raw: unknown): Record<string, unknown> {
|
|
39
|
+
if (isPlainObject(raw)) return raw;
|
|
40
|
+
if (typeof raw !== 'string') return {};
|
|
41
|
+
const trimmed = raw.trim();
|
|
42
|
+
if (!trimmed || trimmed === '{}') return {};
|
|
43
|
+
try {
|
|
44
|
+
const parsed = JSON.parse(trimmed);
|
|
45
|
+
if (isPlainObject(parsed)) return parsed;
|
|
46
|
+
} catch {
|
|
47
|
+
// Fall through to deterministic syntax recovery
|
|
48
|
+
}
|
|
49
|
+
const repaired = repairJsonArguments(trimmed);
|
|
50
|
+
if (!repaired.error && isPlainObject(repaired.args)) {
|
|
51
|
+
return repaired.args;
|
|
52
|
+
}
|
|
53
|
+
return {};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Guarantee a valid tool call ID matching ^[a-zA-Z0-9_-]{1,64}$.
|
|
58
|
+
*/
|
|
59
|
+
export function sanitizeProviderToolId(rawId: unknown, prefix = 'call', index = 0): string {
|
|
60
|
+
const cleaned = typeof rawId === 'string'
|
|
61
|
+
? rawId.trim().replace(VALID_ID_CHARS, '_')
|
|
62
|
+
: '';
|
|
63
|
+
if (cleaned.length > 0) return cleaned.slice(0, 64);
|
|
64
|
+
return `${prefix.replace(VALID_ID_CHARS, '_')}_${Date.now()}_${index}`.slice(0, 64);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function resolveFreeFormPaths(
|
|
68
|
+
toolName: string,
|
|
69
|
+
freeFormPaths?: Map<string, string[][]>
|
|
70
|
+
): string[][] | undefined {
|
|
71
|
+
if (!freeFormPaths || freeFormPaths.size === 0) return undefined;
|
|
72
|
+
return freeFormPaths.get(normalizeToolName(toolName)) || freeFormPaths.get(toolName);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Serialize arguments cleanly to a JSON string while decoding any adapted free-form paths.
|
|
77
|
+
*/
|
|
78
|
+
export function serializeAndDecodeArguments(
|
|
79
|
+
rawArgs: unknown,
|
|
80
|
+
toolName: string,
|
|
81
|
+
freeFormPaths?: Map<string, string[][]>
|
|
82
|
+
): string {
|
|
83
|
+
const paths = resolveFreeFormPaths(toolName, freeFormPaths);
|
|
84
|
+
if (typeof rawArgs === 'string') {
|
|
85
|
+
if (!paths || paths.length === 0) return rawArgs;
|
|
86
|
+
const obj = safeParseJsonObject(rawArgs);
|
|
87
|
+
if (Object.keys(obj).length === 0) return rawArgs;
|
|
88
|
+
const decoded = decodeFreeFormArguments(structuredClone(obj), paths);
|
|
89
|
+
return JSON.stringify(decoded);
|
|
90
|
+
}
|
|
91
|
+
const obj = isPlainObject(rawArgs) ? structuredClone(rawArgs) : {};
|
|
92
|
+
const finalObj = paths && paths.length > 0 ? decodeFreeFormArguments(obj, paths) : obj;
|
|
93
|
+
try {
|
|
94
|
+
return JSON.stringify(finalObj);
|
|
95
|
+
} catch {
|
|
96
|
+
return '{}';
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Extract tool calls embedded as <tool_call>{...}</tool_call> text envelopes.
|
|
102
|
+
*/
|
|
103
|
+
export function extractTextToolCalls(
|
|
104
|
+
text: string,
|
|
105
|
+
prefix = 'call_text',
|
|
106
|
+
freeFormPaths?: Map<string, string[][]>
|
|
107
|
+
): ChatResponseToolCall[] {
|
|
108
|
+
const calls: ChatResponseToolCall[] = [];
|
|
109
|
+
if (!text || typeof text !== 'string') return calls;
|
|
110
|
+
let index = 0;
|
|
111
|
+
for (const parsed of extractToolCallJsonObjects(text)) {
|
|
112
|
+
const fnObj = isPlainObject(parsed['function']) ? parsed['function'] : null;
|
|
113
|
+
const rawName = String(parsed['name'] || parsed['tool'] || fnObj?.['name'] || '').trim();
|
|
114
|
+
if (!rawName) continue;
|
|
115
|
+
const name = normalizeToolName(rawName);
|
|
116
|
+
const rawArgs = resolveToolCallEnvelopeArguments(parsed);
|
|
117
|
+
calls.push({
|
|
118
|
+
id: sanitizeProviderToolId(parsed['id'], prefix, index++),
|
|
119
|
+
type: 'function',
|
|
120
|
+
function: {
|
|
121
|
+
name,
|
|
122
|
+
arguments: serializeAndDecodeArguments(rawArgs, name, freeFormPaths)
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return calls;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Normalize native OpenAI / Ollama / proxy tool_calls into one canonical Causyne contract.
|
|
131
|
+
*/
|
|
132
|
+
export function normalizeOpenAIToolCalls(
|
|
133
|
+
rawCalls: unknown,
|
|
134
|
+
freeFormPaths?: Map<string, string[][]>,
|
|
135
|
+
prefix = 'call'
|
|
136
|
+
): ChatResponseToolCall[] {
|
|
137
|
+
if (!Array.isArray(rawCalls)) return [];
|
|
138
|
+
const normalized: ChatResponseToolCall[] = [];
|
|
139
|
+
for (let i = 0; i < rawCalls.length; i++) {
|
|
140
|
+
const tc = rawCalls[i];
|
|
141
|
+
if (!isPlainObject(tc)) continue;
|
|
142
|
+
const fnObj = isPlainObject(tc['function']) ? tc['function'] : null;
|
|
143
|
+
const rawName = String(fnObj?.['name'] || tc['name'] || '').trim();
|
|
144
|
+
if (!rawName) continue;
|
|
145
|
+
const name = normalizeToolName(rawName);
|
|
146
|
+
const rawArgs = fnObj ? fnObj['arguments'] : tc['arguments'];
|
|
147
|
+
normalized.push({
|
|
148
|
+
id: sanitizeProviderToolId(tc['id'], prefix, i),
|
|
149
|
+
type: 'function',
|
|
150
|
+
function: {
|
|
151
|
+
name,
|
|
152
|
+
arguments: serializeAndDecodeArguments(rawArgs ?? {}, name, freeFormPaths)
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
return normalized;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Normalize an OpenAI-compatible (or DeepSeek proxy) JSON response into standard ChatResponse parts,
|
|
161
|
+
* including automatic fallback extraction of XML <tool_call> text envelopes.
|
|
162
|
+
*/
|
|
163
|
+
export function normalizeOpenAIChatChoiceResponse(
|
|
164
|
+
data: unknown,
|
|
165
|
+
options: {
|
|
166
|
+
prefix?: string;
|
|
167
|
+
freeFormPaths?: Map<string, string[][]>;
|
|
168
|
+
stripToolMarkup?: boolean;
|
|
169
|
+
} = {}
|
|
170
|
+
): NormalizedChoiceResult {
|
|
171
|
+
const payload = isPlainObject(data) ? data : {};
|
|
172
|
+
const prefix = options.prefix || 'call';
|
|
173
|
+
let content = '';
|
|
174
|
+
let reasoningContent = '';
|
|
175
|
+
let rawToolCalls: unknown = undefined;
|
|
176
|
+
|
|
177
|
+
if (payload['reply'] !== undefined) {
|
|
178
|
+
content = typeof payload['reply'] === 'string' ? payload['reply'] : '';
|
|
179
|
+
rawToolCalls = payload['tool_calls'];
|
|
180
|
+
} else if (Array.isArray(payload['choices']) && payload['choices'].length > 0) {
|
|
181
|
+
const choice = isPlainObject(payload['choices'][0]) ? payload['choices'][0] : null;
|
|
182
|
+
const message = choice && isPlainObject(choice['message']) ? choice['message'] : null;
|
|
183
|
+
if (message) {
|
|
184
|
+
content = typeof message['content'] === 'string' ? message['content'] : '';
|
|
185
|
+
rawToolCalls = message['tool_calls'];
|
|
186
|
+
const rc = message['reasoning_content'] ?? message['reasoning'];
|
|
187
|
+
reasoningContent = typeof rc === 'string' ? rc : '';
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let toolCalls = normalizeOpenAIToolCalls(rawToolCalls, options.freeFormPaths, prefix);
|
|
192
|
+
if (toolCalls.length === 0 && content) {
|
|
193
|
+
const extracted = extractTextToolCalls(content, `${prefix}_text`, options.freeFormPaths);
|
|
194
|
+
if (extracted.length > 0) {
|
|
195
|
+
toolCalls = extracted;
|
|
196
|
+
if (options.stripToolMarkup !== false) {
|
|
197
|
+
content = stripToolCallMarkup(content).trim();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const rawUsage = isPlainObject(payload['usage'])
|
|
203
|
+
? payload['usage']
|
|
204
|
+
: { prompt_tokens: 0, completion_tokens: 0 };
|
|
205
|
+
|
|
206
|
+
const result: NormalizedChoiceResult = {
|
|
207
|
+
content,
|
|
208
|
+
rawUsage
|
|
209
|
+
};
|
|
210
|
+
if (toolCalls.length > 0) result.toolCalls = toolCalls;
|
|
211
|
+
if (reasoningContent) result.reasoningContent = reasoningContent;
|
|
212
|
+
return result;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Prepare messages for Anthropic: runs multimodal image/audio normalization and strips internal
|
|
217
|
+
* fields from non-system turns while preserving `cacheAnchor` on `system` turns so Anthropic's
|
|
218
|
+
* cache_control placement remains intact.
|
|
219
|
+
*/
|
|
220
|
+
export function prepareMessagesForAnthropic(
|
|
221
|
+
provider: {
|
|
222
|
+
supportsVision: boolean;
|
|
223
|
+
supportsAudio: boolean;
|
|
224
|
+
normalizeImageBlocks: (msg: any) => any;
|
|
225
|
+
flattenToTextOnly: (msg: any) => any;
|
|
226
|
+
normalizeAudioBlocks: (msg: any) => any;
|
|
227
|
+
stripAudioBlocks: (msg: any) => any;
|
|
228
|
+
stripInternalFields: (msgs: any[]) => any[];
|
|
229
|
+
},
|
|
230
|
+
messages: unknown[]
|
|
231
|
+
): any[] {
|
|
232
|
+
if (!Array.isArray(messages)) return [];
|
|
233
|
+
const prepared: any[] = [];
|
|
234
|
+
for (const msg of messages) {
|
|
235
|
+
if (!isPlainObject(msg)) continue;
|
|
236
|
+
if (msg['role'] === 'system') {
|
|
237
|
+
const { spillPath: _spill, ...rest } = msg;
|
|
238
|
+
prepared.push(rest);
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
const [cleaned] = provider.stripInternalFields([msg]);
|
|
242
|
+
const visual = provider.supportsVision
|
|
243
|
+
? provider.normalizeImageBlocks(cleaned)
|
|
244
|
+
: provider.flattenToTextOnly(cleaned);
|
|
245
|
+
const audioReady = provider.supportsAudio
|
|
246
|
+
? provider.normalizeAudioBlocks(visual)
|
|
247
|
+
: provider.stripAudioBlocks(visual);
|
|
248
|
+
prepared.push(audioReady);
|
|
249
|
+
}
|
|
250
|
+
return prepared;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Convert OpenAI JSON-string tool_calls arguments into objects for Ollama `/api/chat` history.
|
|
255
|
+
*/
|
|
256
|
+
export function normalizeMessagesForOllama(messages: unknown[]): any[] {
|
|
257
|
+
if (!Array.isArray(messages)) return [];
|
|
258
|
+
return messages.map((msg) => {
|
|
259
|
+
if (!isPlainObject(msg) || msg['role'] !== 'assistant' || !Array.isArray(msg['tool_calls'])) {
|
|
260
|
+
return msg;
|
|
261
|
+
}
|
|
262
|
+
return {
|
|
263
|
+
...msg,
|
|
264
|
+
tool_calls: (msg['tool_calls'] as unknown[]).map((tc) => {
|
|
265
|
+
if (!isPlainObject(tc)) return tc;
|
|
266
|
+
const fn = isPlainObject(tc['function']) ? tc['function'] : null;
|
|
267
|
+
if (!fn) return tc;
|
|
268
|
+
return {
|
|
269
|
+
...tc,
|
|
270
|
+
function: {
|
|
271
|
+
...fn,
|
|
272
|
+
name: normalizeToolName(String(fn['name'] || '')),
|
|
273
|
+
arguments: safeParseJsonObject(fn['arguments'])
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
})
|
|
277
|
+
};
|
|
278
|
+
});
|
|
279
|
+
}
|
package/src/providers/xai.js
CHANGED
|
@@ -2,6 +2,13 @@ import { canonicalModelId } from '../modelIds.js';
|
|
|
2
2
|
import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
|
|
3
3
|
import { LLMProvider } from './base.js';
|
|
4
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';
|
|
5
12
|
|
|
6
13
|
export class XAIProvider extends LLMProvider {
|
|
7
14
|
constructor(config) {
|
|
@@ -14,59 +21,62 @@ export class XAIProvider extends LLMProvider {
|
|
|
14
21
|
}
|
|
15
22
|
|
|
16
23
|
async chat(messages, options = {}) {
|
|
24
|
+
const apiKey = requireApiKey(this.apiKey, 'xAI (Grok)');
|
|
17
25
|
const sanitizedMessages = this.prepareMessages(messages);
|
|
18
26
|
|
|
19
27
|
const payload = {
|
|
20
28
|
model: this.model,
|
|
21
29
|
messages: sanitizedMessages,
|
|
22
|
-
temperature: options.temperature
|
|
30
|
+
temperature: resolveTemperature(options.temperature, 0.1),
|
|
23
31
|
};
|
|
24
32
|
|
|
25
33
|
if (options.jsonMode) {
|
|
26
34
|
payload.response_format = { type: 'json_object' };
|
|
27
35
|
}
|
|
28
|
-
|
|
29
|
-
let headers = {
|
|
30
|
-
'Content-Type': 'application/json'
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
if (this.apiKey) {
|
|
34
|
-
headers['Authorization'] = `Bearer ${this.apiKey}`;
|
|
35
|
-
} else {
|
|
36
|
-
// EXPLICIT BYOK CONSTRAINT
|
|
37
|
-
throw new Error(`xAI (Grok) API requires a valid API key (BYOK mode). Please set it in your configuration.`);
|
|
38
|
-
}
|
|
39
36
|
|
|
40
|
-
|
|
37
|
+
let freeFormPaths = new Map();
|
|
38
|
+
if (options.tools && options.tools.length > 0) {
|
|
41
39
|
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'xai');
|
|
42
40
|
payload.tools = scanReport.adaptedTools;
|
|
43
41
|
payload.tool_choice = "auto";
|
|
42
|
+
freeFormPaths = scanReport.freeFormPaths;
|
|
44
43
|
}
|
|
45
44
|
|
|
46
|
-
const
|
|
45
|
+
const requestOpts = {
|
|
46
|
+
url: this.baseUrl,
|
|
47
47
|
method: 'POST',
|
|
48
|
-
headers:
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
headers: {
|
|
49
|
+
'Content-Type': 'application/json',
|
|
50
|
+
'Authorization': `Bearer ${apiKey}`
|
|
51
|
+
},
|
|
52
|
+
signal: options.signal,
|
|
53
|
+
timeoutMs: options.timeoutMs,
|
|
54
|
+
providerLabel: 'xAI',
|
|
55
|
+
secrets: [apiKey],
|
|
56
|
+
hasApiKey: true
|
|
57
|
+
};
|
|
51
58
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
59
|
+
const data = wantsStreaming(options)
|
|
60
|
+
? await streamOpenAICompatibleChat({
|
|
61
|
+
...requestOpts,
|
|
62
|
+
payload,
|
|
63
|
+
onChunk: options.onChunk,
|
|
64
|
+
onReasoningChunk: options.onReasoningChunk
|
|
65
|
+
})
|
|
66
|
+
: await safeProviderFetchJson({
|
|
67
|
+
...requestOpts,
|
|
68
|
+
body: JSON.stringify(payload)
|
|
69
|
+
});
|
|
70
|
+
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
71
|
+
prefix: 'call_xai',
|
|
72
|
+
freeFormPaths
|
|
73
|
+
});
|
|
56
74
|
|
|
57
|
-
const data = await response.json();
|
|
58
|
-
let content = '';
|
|
59
|
-
let toolCalls = [];
|
|
60
|
-
|
|
61
|
-
if (data.choices && data.choices[0] && data.choices[0].message) {
|
|
62
|
-
content = data.choices[0].message.content || '';
|
|
63
|
-
toolCalls = data.choices[0].message.tool_calls || [];
|
|
64
|
-
}
|
|
65
|
-
|
|
66
75
|
return {
|
|
67
|
-
content: content,
|
|
68
|
-
toolCalls:
|
|
69
|
-
|
|
76
|
+
content: normalized.content,
|
|
77
|
+
toolCalls: normalized.toolCalls,
|
|
78
|
+
reasoningContent: normalized.reasoningContent,
|
|
79
|
+
usage: this.normalizeUsage(normalized.rawUsage)
|
|
70
80
|
};
|
|
71
81
|
}
|
|
72
82
|
}
|