@causyne/agent 1.20.117 → 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.
Files changed (82) hide show
  1. package/package.json +7 -2
  2. package/src/agentLoop.js +29 -12
  3. package/src/agentLoop.ts +29 -16
  4. package/src/browser/causyneBrowser.js +231 -136
  5. package/src/browser/causyneBrowser.ts +229 -140
  6. package/src/browser/searchProviders.js +41 -30
  7. package/src/browser/searchProviders.ts +24 -14
  8. package/src/browser/workspacePathSafety.js +50 -0
  9. package/src/browser/workspacePathSafety.ts +50 -0
  10. package/src/browser/workspacePreview.js +27 -4
  11. package/src/browser/workspacePreview.ts +28 -4
  12. package/src/cliMode.js +20 -4
  13. package/src/commands.js +12 -14
  14. package/src/creative/liveBridge.js +34 -1
  15. package/src/creative/liveBridge.ts +28 -1
  16. package/src/observer/evidence.js +23 -0
  17. package/src/observer/evidence.ts +21 -0
  18. package/src/plugins/pluginManager.js +74 -0
  19. package/src/providers/anthropic.js +33 -17
  20. package/src/providers/base.js +14 -0
  21. package/src/providers/dashscope-byok.js +13 -7
  22. package/src/providers/deepseek.js +13 -18
  23. package/src/providers/gemini.js +33 -25
  24. package/src/providers/moonshot.js +13 -12
  25. package/src/providers/ollama.js +21 -21
  26. package/src/providers/openai-compatible.js +12 -19
  27. package/src/providers/openrouter.js +20 -90
  28. package/src/providers/openrouter.ts +31 -94
  29. package/src/providers/qwen-byok.js +13 -7
  30. package/src/providers/toolContracts.js +9 -3
  31. package/src/providers/toolContracts.ts +9 -3
  32. package/src/providers/wireNormalizer.js +238 -0
  33. package/src/providers/wireNormalizer.ts +279 -0
  34. package/src/providers/xai.js +13 -12
  35. package/src/reporting.js +12 -4
  36. package/src/skillsManager.js +3 -2
  37. package/src/skillsManager.ts +3 -2
  38. package/src/tools/browserAutomator.js +13 -1
  39. package/src/tools/browserAutomator.ts +13 -0
  40. package/src/tools/creativeApps.js +2 -1
  41. package/src/tools/creativeApps.ts +2 -1
  42. package/src/tools/gameAssetFetcher.js +130 -26
  43. package/src/tools/gameAssetHarvester.js +80 -58
  44. package/src/tools/nativeEngine.js +1 -1
  45. package/src/tools/nativeEngine.ts +1 -1
  46. package/src/tools/pluginManager.js +17 -2
  47. package/src/tools/registry.js +13 -0
  48. package/src/tools/toolScanner.js +596 -140
  49. package/src/tools/toolScanner.ts +665 -147
  50. package/src/tools/toolSelfRepair.js +243 -114
  51. package/src/tools/toolSelfRepair.ts +262 -111
  52. package/src/tools/webFetch.js +161 -24
  53. package/src/tools/webFetch.ts +157 -22
  54. package/src/tools/webSearch.js +33 -4
  55. package/src/tools/webSearch.ts +27 -4
  56. package/src/tui/composerControls.js +16 -3
  57. package/src/tui/composerControls.ts +14 -3
  58. package/src/tui/prompt.js +122 -16
  59. package/src/tui/sessionPicker.js +132 -35
  60. package/src/tui/sessionPicker.ts +153 -32
  61. package/src/tui/sessionPickerView.js +277 -34
  62. package/src/tui/sessionPickerView.ts +328 -34
  63. package/src/tui/statusLine.js +3 -0
  64. package/src/tui/statusLine.ts +5 -0
  65. package/src/tui/usageCard.js +119 -47
  66. package/src/tui/usageCard.ts +133 -49
  67. package/src/tui/workspaceIdentity.js +133 -0
  68. package/src/tui/workspaceIdentity.ts +146 -0
  69. package/src/tui/workspaceSwitch.js +2 -0
  70. package/src/tui/workspaceSwitch.ts +1 -0
  71. package/src/verification/boundedExplorer.js +119 -0
  72. package/src/verification/cliProbe.js +116 -0
  73. package/src/verification/featureMap.js +78 -0
  74. package/src/verification/interactivePty.js +188 -0
  75. package/src/verification/propertyProbe.js +121 -0
  76. package/src/verification/ptyProbe.js +125 -0
  77. package/src/verification/skillCatalog.d.ts +1 -0
  78. package/src/verification/skillCatalog.js +60 -0
  79. package/src/verification/statechart.js +143 -0
  80. package/src/verification/uiRuntime.js +57 -0
  81. package/src/verificationPlan.js +1 -1
  82. package/src/verificationPlan.ts +1 -1
@@ -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
+ }
@@ -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
- if (options.tools) {
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
- 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
-
61
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
62
+ prefix: 'call_xai',
63
+ freeFormPaths
64
+ });
65
+
66
66
  return {
67
- content: content,
68
- toolCalls: (toolCalls && toolCalls.length > 0) ? toolCalls : undefined,
69
- usage: this.normalizeUsage(data.usage || { prompt_tokens: 0, completion_tokens: 0 })
67
+ content: normalized.content,
68
+ toolCalls: normalized.toolCalls,
69
+ reasoningContent: normalized.reasoningContent,
70
+ usage: this.normalizeUsage(normalized.rawUsage)
70
71
  };
71
72
  }
72
73
  }
package/src/reporting.js CHANGED
@@ -339,20 +339,28 @@ export function formatUptime(ms) {
339
339
  */
340
340
  export function buildStatusText({ loop = null } = {}) {
341
341
  const config = loadConfig();
342
+ const liveConfig = loop?.config || {};
343
+ const provider = liveConfig.provider || config.provider || 'default';
344
+ const model = liveConfig.model || config.model || 'default';
345
+ const autonomyMode = liveConfig.autonomyMode || config.autonomyMode || 'C';
346
+ const tier = liveConfig.tier || config.tier || 'premium';
342
347
  const lines = ['Status'];
343
348
 
344
349
  lines.push(' Runtime : local desktop');
345
350
 
346
- lines.push(` Provider / model : ${config.provider || 'default'} / ${config.model || 'default'}`);
347
- lines.push(` Autonomy mode : ${config.autonomyMode || 'C'}`);
348
- lines.push(` Tier : ${config.tier || 'premium'}`);
351
+ if (loop?.memoryManager?.sessionId) {
352
+ lines.push(` Session : ${loop.memoryManager.sessionId}`);
353
+ }
354
+ lines.push(` Provider / model : ${provider} / ${model}`);
355
+ lines.push(` Autonomy mode : ${autonomyMode}`);
356
+ lines.push(` Tier : ${tier}`);
349
357
 
350
358
  if (loop && loop.sandbox) {
351
359
  const sandbox = loop.sandbox;
352
360
  lines.push(` Workspace scope : ${sandbox.grantAllAccess ? 'ALL ACCESS' : (sandbox.workspacePaths || []).join(', ')}`);
353
361
  }
354
362
 
355
- if (!config.apiKey && config.provider !== 'ollama' && !isAcpProvider(config.provider) && !isAntigravityProvider(config.provider)) {
363
+ if (!liveConfig.apiKey && !config.apiKey && provider !== 'ollama' && !isAcpProvider(provider) && !isAntigravityProvider(provider)) {
356
364
  lines.push('');
357
365
  lines.push(' No API key is set. Run `causyne config`.');
358
366
  }
@@ -1,9 +1,10 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { COMPILED_SKILLS } from './compiledSkills.js';
4
+ import { VERIFICATION_SKILLS } from './verification/skillCatalog.js';
4
5
  import { loadUserSkills } from './userSkills.js';
5
6
  import { getPluginSkills } from './plugins/pluginManager.js';
6
- const compiledSkillsCatalog = COMPILED_SKILLS;
7
+ const compiledSkillsCatalog = { ...COMPILED_SKILLS, verification: VERIFICATION_SKILLS };
7
8
  // User skills are read from disk, and the disk is slow relative to how often
8
9
  // these functions are called (every completion keystroke asks for the
9
10
  // catalogue). Cache for a moment so typing stays instant, but keep the window
@@ -80,7 +81,7 @@ const DOMAIN_INDICATORS = {
80
81
  // Design and security are not properties of a file layout — an agent writing a
81
82
  // UI needs the anti-slop direction whether or not a tailwind config exists, and
82
83
  // input validation matters whether or not the repository has a SECURITY.md.
83
- const UNIVERSAL_DOMAINS = ['design', 'security'];
84
+ const UNIVERSAL_DOMAINS = ['design', 'security', 'verification'];
84
85
  // Ceiling on how many skill descriptions may enter the system prompt.
85
86
  //
86
87
  // With 100 skills, injecting every description of every detected domain would
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
 
4
4
  import { COMPILED_SKILLS } from './compiledSkills.js';
5
+ import { VERIFICATION_SKILLS } from './verification/skillCatalog.js';
5
6
  import { loadUserSkills, type UserSkill } from './userSkills.js';
6
7
  import { getPluginSkills } from './plugins/pluginManager.js';
7
8
 
@@ -19,7 +20,7 @@ interface CompiledSkillItem {
19
20
  content: string;
20
21
  }
21
22
 
22
- const compiledSkillsCatalog = COMPILED_SKILLS as unknown as Record<string, Record<string, CompiledSkillItem>>;
23
+ const compiledSkillsCatalog = { ...COMPILED_SKILLS, verification: VERIFICATION_SKILLS } as unknown as Record<string, Record<string, CompiledSkillItem>>;
23
24
 
24
25
  // User skills are read from disk, and the disk is slow relative to how often
25
26
  // these functions are called (every completion keystroke asks for the
@@ -100,7 +101,7 @@ const DOMAIN_INDICATORS: Record<string, string[]> = {
100
101
  // Design and security are not properties of a file layout — an agent writing a
101
102
  // UI needs the anti-slop direction whether or not a tailwind config exists, and
102
103
  // input validation matters whether or not the repository has a SECURITY.md.
103
- const UNIVERSAL_DOMAINS = ['design', 'security'];
104
+ const UNIVERSAL_DOMAINS = ['design', 'security', 'verification'];
104
105
 
105
106
  // Ceiling on how many skill descriptions may enter the system prompt.
106
107
  //
@@ -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
  }