@causyne/agent 1.20.118 → 1.20.120
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/agentLoop.js +29 -12
- package/src/agentLoop.ts +29 -16
- 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 +1 -1
- package/src/commands.js +5 -13
- package/src/creative/liveBridge.js +34 -1
- package/src/creative/liveBridge.ts +28 -1
- package/src/observer/evidence.js +23 -0
- package/src/observer/evidence.ts +21 -0
- package/src/providers/anthropic.js +33 -17
- package/src/providers/base.js +14 -0
- package/src/providers/dashscope-byok.js +13 -7
- package/src/providers/deepseek.js +13 -18
- package/src/providers/gemini.js +33 -25
- package/src/providers/moonshot.js +13 -12
- package/src/providers/ollama.js +21 -21
- package/src/providers/openai-compatible.js +12 -19
- package/src/providers/openrouter.js +20 -90
- package/src/providers/openrouter.ts +31 -94
- package/src/providers/qwen-byok.js +13 -7
- 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 +13 -12
- 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/registry.js +13 -0
- 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,7 @@ 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';
|
|
5
6
|
|
|
6
7
|
export class XAIProvider extends LLMProvider {
|
|
7
8
|
constructor(config) {
|
|
@@ -37,10 +38,12 @@ export class XAIProvider extends LLMProvider {
|
|
|
37
38
|
throw new Error(`xAI (Grok) API requires a valid API key (BYOK mode). Please set it in your configuration.`);
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
|
|
41
|
+
let freeFormPaths = new Map();
|
|
42
|
+
if (options.tools && options.tools.length > 0) {
|
|
41
43
|
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'xai');
|
|
42
44
|
payload.tools = scanReport.adaptedTools;
|
|
43
45
|
payload.tool_choice = "auto";
|
|
46
|
+
freeFormPaths = scanReport.freeFormPaths;
|
|
44
47
|
}
|
|
45
48
|
|
|
46
49
|
const response = await fetch(this.baseUrl, {
|
|
@@ -55,18 +58,16 @@ export class XAIProvider extends LLMProvider {
|
|
|
55
58
|
}
|
|
56
59
|
|
|
57
60
|
const data = await response.json();
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
toolCalls = data.choices[0].message.tool_calls || [];
|
|
64
|
-
}
|
|
65
|
-
|
|
61
|
+
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
62
|
+
prefix: 'call_xai',
|
|
63
|
+
freeFormPaths
|
|
64
|
+
});
|
|
65
|
+
|
|
66
66
|
return {
|
|
67
|
-
content: content,
|
|
68
|
-
toolCalls:
|
|
69
|
-
|
|
67
|
+
content: normalized.content,
|
|
68
|
+
toolCalls: normalized.toolCalls,
|
|
69
|
+
reasoningContent: normalized.reasoningContent,
|
|
70
|
+
usage: this.normalizeUsage(normalized.rawUsage)
|
|
70
71
|
};
|
|
71
72
|
}
|
|
72
73
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BrowserCapabilityError, causyneBrowser, getSupportedSearchMacros } from '../browser/causyneBrowser.js';
|
|
1
|
+
import { BrowserBatchError, BrowserCapabilityError, causyneBrowser, getSupportedSearchMacros } from '../browser/causyneBrowser.js';
|
|
2
2
|
const SUPPORTED_ACTION_TYPES = [
|
|
3
3
|
'newTab', 'new_tab',
|
|
4
4
|
'switchTab', 'switch_tab',
|
|
@@ -116,6 +116,18 @@ export const browserAct = {
|
|
|
116
116
|
return { success: true, output: JSON.stringify(results, null, 2), data: results };
|
|
117
117
|
}
|
|
118
118
|
catch (error) {
|
|
119
|
+
if (error instanceof BrowserBatchError) {
|
|
120
|
+
return {
|
|
121
|
+
success: false,
|
|
122
|
+
error: error.message,
|
|
123
|
+
code: 'BROWSER_BATCH_PARTIAL_FAILURE',
|
|
124
|
+
failedActionIndex: error.failedActionIndex,
|
|
125
|
+
failedActionType: error.failedActionType,
|
|
126
|
+
completedActions: error.completedActions,
|
|
127
|
+
output: JSON.stringify(error.completedActions, null, 2),
|
|
128
|
+
retryGuidance: 'Do not repeat the completed browser actions. Inspect current page state and resume from the failed operation.'
|
|
129
|
+
};
|
|
130
|
+
}
|
|
119
131
|
if (error instanceof BrowserCapabilityError) {
|
|
120
132
|
return { success: false, error: error.message, requiresConsent: error.requiresConsent };
|
|
121
133
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
|
+
BrowserBatchError,
|
|
2
3
|
BrowserCapabilityError,
|
|
3
4
|
causyneBrowser,
|
|
4
5
|
getSupportedSearchMacros,
|
|
@@ -130,6 +131,18 @@ export const browserAct = {
|
|
|
130
131
|
const results = await causyneBrowser({ workspace }).run(actions, { workspace });
|
|
131
132
|
return { success: true, output: JSON.stringify(results, null, 2), data: results };
|
|
132
133
|
} catch (error) {
|
|
134
|
+
if (error instanceof BrowserBatchError) {
|
|
135
|
+
return {
|
|
136
|
+
success: false,
|
|
137
|
+
error: error.message,
|
|
138
|
+
code: 'BROWSER_BATCH_PARTIAL_FAILURE',
|
|
139
|
+
failedActionIndex: error.failedActionIndex,
|
|
140
|
+
failedActionType: error.failedActionType,
|
|
141
|
+
completedActions: error.completedActions,
|
|
142
|
+
output: JSON.stringify(error.completedActions, null, 2),
|
|
143
|
+
retryGuidance: 'Do not repeat the completed browser actions. Inspect current page state and resume from the failed operation.'
|
|
144
|
+
};
|
|
145
|
+
}
|
|
133
146
|
if (error instanceof BrowserCapabilityError) {
|
|
134
147
|
return { success: false, error: error.message, requiresConsent: error.requiresConsent };
|
|
135
148
|
}
|
|
@@ -158,7 +158,8 @@ export const creativeApps = {
|
|
|
158
158
|
description: 'Unreal UProperty name for remote_control property read/write.'
|
|
159
159
|
},
|
|
160
160
|
propertyValue: {
|
|
161
|
-
|
|
161
|
+
type: ['string', 'number', 'boolean', 'object', 'array'],
|
|
162
|
+
description: 'Value to write for Unreal remote_control property access (string, number, boolean, object, or array; JSON-encoded strings like "42", "true", "{\\"X\\":1}", or "[1,2]" are decoded to native types, or wrap in JSON quotes like "\\"42\\"" for a literal numeric string).'
|
|
162
163
|
},
|
|
163
164
|
parameters: {
|
|
164
165
|
type: 'object',
|
|
@@ -165,7 +165,8 @@ export const creativeApps = {
|
|
|
165
165
|
description: 'Unreal UProperty name for remote_control property read/write.'
|
|
166
166
|
},
|
|
167
167
|
propertyValue: {
|
|
168
|
-
|
|
168
|
+
type: ['string', 'number', 'boolean', 'object', 'array'],
|
|
169
|
+
description: 'Value to write for Unreal remote_control property access (string, number, boolean, object, or array; JSON-encoded strings like "42", "true", "{\\"X\\":1}", or "[1,2]" are decoded to native types, or wrap in JSON quotes like "\\"42\\"" for a literal numeric string).'
|
|
169
170
|
},
|
|
170
171
|
parameters: {
|
|
171
172
|
type: 'object',
|