@causyne/agent 1.20.121 → 1.20.122

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +6 -2
  14. package/src/agent/errorClassifier.ts +6 -2
  15. package/src/agentLoop.js +11 -5
  16. package/src/agentLoop.ts +11 -5
  17. package/src/approvalGrants.js +19 -7
  18. package/src/approvalGrants.ts +20 -7
  19. package/src/approvalPolicy.js +48 -15
  20. package/src/approvalPolicy.ts +46 -15
  21. package/src/autoUpdate.js +5 -2
  22. package/src/autoUpdate.ts +5 -2
  23. package/src/browser/causyneBrowser.js +3 -2
  24. package/src/browser/causyneBrowser.ts +3 -2
  25. package/src/browser/searchProviders.js +1 -1
  26. package/src/browser/searchProviders.ts +1 -1
  27. package/src/config.js +287 -250
  28. package/src/config.ts +342 -0
  29. package/src/configVault.js +84 -17
  30. package/src/configVault.ts +77 -17
  31. package/src/continuum/compactor.js +2 -1
  32. package/src/continuum/compactor.ts +2 -1
  33. package/src/continuum/sanitizer.js +10 -3
  34. package/src/continuum/sanitizer.ts +9 -3
  35. package/src/continuum/ui/continuumPickerView.js +3 -2
  36. package/src/continuum/ui/continuumPickerView.ts +3 -2
  37. package/src/cortex/vectorDb.js +26 -15
  38. package/src/cortex/vectorDb.ts +26 -16
  39. package/src/creative/liveBridge.js +7 -5
  40. package/src/creative/liveBridge.ts +7 -5
  41. package/src/creative/studioScripts.js +16 -5
  42. package/src/creative/studioScripts.ts +14 -5
  43. package/src/decisionPolicy.js +16 -4
  44. package/src/decisionPolicy.ts +14 -4
  45. package/src/documentEngine/antiSlopAuditor.js +10 -5
  46. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  47. package/src/documentEngine/documentForge.js +47 -15
  48. package/src/documentEngine/documentForge.ts +43 -14
  49. package/src/engines/design.js +2 -1
  50. package/src/engines/design.ts +2 -1
  51. package/src/engines/film.js +4 -4
  52. package/src/engines/film.ts +2 -2
  53. package/src/engines/light.js +2 -1
  54. package/src/engines/light.ts +2 -1
  55. package/src/engines/registry.js +1 -1
  56. package/src/engines/registry.ts +1 -1
  57. package/src/engines/reverseHarness.js +4 -3
  58. package/src/engines/reverseHarness.ts +4 -3
  59. package/src/headlessCli.js +2 -1
  60. package/src/headlessCli.ts +2 -1
  61. package/src/historyPruner.js +3 -2
  62. package/src/historyPruner.ts +3 -2
  63. package/src/hooks.js +3 -0
  64. package/src/hooks.ts +3 -0
  65. package/src/implementationPlan.js +21 -11
  66. package/src/implementationPlan.ts +21 -11
  67. package/src/infra/atomicWriter.js +4 -1
  68. package/src/infra/atomicWriter.ts +4 -1
  69. package/src/launchIntent.js +1 -1
  70. package/src/launchIntent.ts +1 -1
  71. package/src/memory/scopedFacts.js +1 -1
  72. package/src/memory/scopedFacts.ts +1 -1
  73. package/src/memory/symbolFolder.js +1 -1
  74. package/src/memory/symbolFolder.ts +1 -1
  75. package/src/modelRouter.js +1 -1
  76. package/src/modelRouter.ts +1 -1
  77. package/src/observer/evidence.js +10 -4
  78. package/src/observer/evidence.ts +10 -4
  79. package/src/osKeychain.js +62 -8
  80. package/src/osKeychain.ts +50 -8
  81. package/src/perception.js +3 -2
  82. package/src/perception.ts +3 -2
  83. package/src/planCache.js +2 -2
  84. package/src/planCache.ts +2 -2
  85. package/src/pluginsFactory/pluginsFactory.js +19 -11
  86. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  87. package/src/promptMentions.js +2 -2
  88. package/src/promptMentions.ts +2 -2
  89. package/src/providers/acp.js +1 -1
  90. package/src/providers/acp.ts +1 -1
  91. package/src/providers/anthropic.js +327 -401
  92. package/src/providers/anthropic.ts +386 -0
  93. package/src/providers/antigravity.js +10 -4
  94. package/src/providers/antigravity.ts +10 -4
  95. package/src/providers/base.js +221 -319
  96. package/src/providers/base.ts +340 -0
  97. package/src/providers/byokHttp.js +58 -15
  98. package/src/providers/byokHttp.ts +59 -16
  99. package/src/providers/byokStream.js +142 -51
  100. package/src/providers/byokStream.ts +146 -42
  101. package/src/providers/dashscope-byok.js +97 -89
  102. package/src/providers/dashscope-byok.ts +114 -0
  103. package/src/providers/deepseek.js +73 -72
  104. package/src/providers/deepseek.ts +99 -0
  105. package/src/providers/factory.js +35 -28
  106. package/src/providers/factory.ts +40 -0
  107. package/src/providers/gemini.js +227 -278
  108. package/src/providers/gemini.ts +261 -0
  109. package/src/providers/loopGuard.js +9 -5
  110. package/src/providers/loopGuard.ts +10 -5
  111. package/src/providers/moonshot.js +70 -72
  112. package/src/providers/moonshot.ts +93 -0
  113. package/src/providers/muse.js +82 -152
  114. package/src/providers/muse.ts +122 -0
  115. package/src/providers/ollama.js +114 -106
  116. package/src/providers/ollama.ts +135 -0
  117. package/src/providers/openai-compatible.js +113 -96
  118. package/src/providers/openai-compatible.ts +139 -0
  119. package/src/providers/openai.js +22 -15
  120. package/src/providers/openai.ts +30 -0
  121. package/src/providers/openrouter.js +136 -74
  122. package/src/providers/openrouter.ts +133 -72
  123. package/src/providers/pi.js +6 -0
  124. package/src/providers/pi.ts +6 -0
  125. package/src/providers/qwen-byok.js +96 -87
  126. package/src/providers/qwen-byok.ts +113 -0
  127. package/src/providers/toolContracts.js +40 -14
  128. package/src/providers/toolContracts.ts +35 -14
  129. package/src/providers/wireNormalizer.js +78 -11
  130. package/src/providers/wireNormalizer.ts +68 -12
  131. package/src/providers/xai.js +73 -72
  132. package/src/providers/xai.ts +97 -0
  133. package/src/reliability/assetEvidence.js +4 -2
  134. package/src/reliability/assetEvidence.ts +4 -2
  135. package/src/sandbox.js +489 -554
  136. package/src/sandbox.ts +552 -0
  137. package/src/sandboxPolicy.js +95 -16
  138. package/src/sandboxPolicy.ts +97 -16
  139. package/src/sessionJournal.js +8 -3
  140. package/src/sessionJournal.ts +9 -3
  141. package/src/skills/skillResourceSafety.js +19 -8
  142. package/src/skills/skillResourceSafety.ts +16 -7
  143. package/src/skillsManager.js +3 -3
  144. package/src/skillsManager.ts +3 -3
  145. package/src/smartToolsUse.js +28 -4
  146. package/src/smartToolsUse.ts +29 -7
  147. package/src/stallGuard.js +45 -22
  148. package/src/stallGuard.ts +46 -22
  149. package/src/subagentJournal.js +6 -4
  150. package/src/subagentJournal.ts +6 -4
  151. package/src/textDiff.js +6 -1
  152. package/src/textDiff.ts +6 -1
  153. package/src/timeMachine.js +7 -1
  154. package/src/timeMachine.ts +7 -1
  155. package/src/tokenTracker.js +43 -28
  156. package/src/tokenTracker.ts +44 -30
  157. package/src/toolPacks.js +3 -1
  158. package/src/toolPacks.ts +3 -1
  159. package/src/tools/archive.js +245 -35
  160. package/src/tools/archive.ts +244 -35
  161. package/src/tools/computerUse.js +7 -3
  162. package/src/tools/computerUse.ts +7 -3
  163. package/src/tools/creativeApps.js +13 -8
  164. package/src/tools/creativeApps.ts +22 -9
  165. package/src/tools/deferredMcpSearch.js +26 -14
  166. package/src/tools/deferredMcpSearch.ts +26 -14
  167. package/src/tools/desktopOpen.js +69 -10
  168. package/src/tools/desktopOpen.ts +70 -11
  169. package/src/tools/documentForge.js +167 -82
  170. package/src/tools/documentForge.ts +169 -84
  171. package/src/tools/fsEdit.js +101 -30
  172. package/src/tools/fsEdit.ts +105 -32
  173. package/src/tools/fsFind.js +8 -5
  174. package/src/tools/fsFind.ts +7 -4
  175. package/src/tools/fsRead.js +119 -13
  176. package/src/tools/fsRead.ts +124 -13
  177. package/src/tools/fsWrite.js +17 -5
  178. package/src/tools/fsWrite.ts +17 -7
  179. package/src/tools/generateMediaViaApi.js +82 -19
  180. package/src/tools/generateMediaViaApi.ts +80 -19
  181. package/src/tools/memoryRecall.js +62 -11
  182. package/src/tools/memoryRecall.ts +70 -13
  183. package/src/tools/memoryWrite.js +27 -14
  184. package/src/tools/memoryWrite.ts +30 -14
  185. package/src/tools/multiEdit.js +100 -30
  186. package/src/tools/multiEdit.ts +104 -32
  187. package/src/tools/nativeEngine.js +33 -18
  188. package/src/tools/nativeEngine.ts +31 -18
  189. package/src/tools/openSourceToolProvisioner.js +49 -14
  190. package/src/tools/openSourceToolProvisioner.ts +54 -15
  191. package/src/tools/osSandbox.js +54 -14
  192. package/src/tools/osSandbox.ts +48 -14
  193. package/src/tools/payloadSanitizer.js +40 -8
  194. package/src/tools/payloadSanitizer.ts +39 -8
  195. package/src/tools/peerAgent.js +96 -34
  196. package/src/tools/peerAgent.ts +114 -37
  197. package/src/tools/pluginsFactory.js +38 -6
  198. package/src/tools/pluginsFactory.ts +42 -6
  199. package/src/tools/readNativeSkill.js +10 -8
  200. package/src/tools/readNativeSkill.ts +10 -8
  201. package/src/tools/requestDecision.js +10 -3
  202. package/src/tools/requestDecision.ts +10 -3
  203. package/src/tools/resolveAutomator.js +91 -17
  204. package/src/tools/resolveAutomator.ts +102 -17
  205. package/src/tools/reverseEngineering.js +168 -41
  206. package/src/tools/reverseEngineering.ts +161 -41
  207. package/src/tools/sysRun.js +69 -29
  208. package/src/tools/sysRun.ts +66 -24
  209. package/src/tools/toolDispatch.js +24 -1
  210. package/src/tools/toolDispatch.ts +21 -1
  211. package/src/tools/toolOutputStore.js +62 -23
  212. package/src/tools/toolOutputStore.ts +56 -23
  213. package/src/tools/toolScanner.js +13 -10
  214. package/src/tools/toolScanner.ts +13 -10
  215. package/src/tools/toolSelfRepair.js +94 -28
  216. package/src/tools/toolSelfRepair.ts +96 -28
  217. package/src/tools/uiForge.js +71 -6
  218. package/src/tools/uiForge.ts +74 -6
  219. package/src/tools/viewImage.js +62 -17
  220. package/src/tools/viewImage.ts +57 -12
  221. package/src/tools/visionInspector.js +15 -3
  222. package/src/tools/visionInspector.ts +15 -3
  223. package/src/tools/walkerSafety.js +2 -0
  224. package/src/tools/walkerSafety.ts +1 -0
  225. package/src/tools/webFetch.js +105 -10
  226. package/src/tools/webFetch.ts +105 -11
  227. package/src/tui/banner.js +3 -2
  228. package/src/tui/banner.ts +3 -2
  229. package/src/tui/consoleGuard.js +12 -4
  230. package/src/tui/consoleGuard.ts +9 -4
  231. package/src/tui/messageInteraction.js +2 -3
  232. package/src/tui/messageInteraction.ts +2 -3
  233. package/src/tui/modelPicker.js +1 -0
  234. package/src/tui/modelPicker.ts +1 -0
  235. package/src/tui/overlay.js +3 -1
  236. package/src/tui/overlay.ts +3 -1
  237. package/src/tui/sessionPicker.js +3 -2
  238. package/src/tui/sessionPicker.ts +3 -2
  239. package/src/tui/sessionPickerView.js +7 -1
  240. package/src/tui/sessionPickerView.ts +6 -1
  241. package/src/tui/toolOutputNormalizer.js +2 -3
  242. package/src/tui/toolOutputNormalizer.ts +4 -3
  243. package/src/tui/viewport.js +4 -4
  244. package/src/tui/viewport.ts +5 -5
  245. package/src/tui/workspaceIdentity.js +2 -1
  246. package/src/tui/workspaceIdentity.ts +2 -1
  247. package/src/uncertainty.js +8 -3
  248. package/src/uncertainty.ts +8 -3
  249. package/src/utils/paths.js +8 -5
  250. package/src/utils/paths.ts +9 -7
  251. package/src/vfeTracker.js +9 -3
  252. package/src/vfeTracker.ts +9 -3
  253. package/src/config.d.ts +0 -2
  254. package/src/providers/base.d.ts +0 -94
  255. package/src/providers/factory.d.ts +0 -1
  256. package/src/sandbox.d.ts +0 -1
@@ -16,7 +16,7 @@ import {
16
16
  resolveToolCallEnvelopeArguments,
17
17
  stripToolCallMarkup
18
18
  } from '../implementationPlan.js';
19
- import type { ChatResponseToolCall } from './base.d.js';
19
+ import type { ChatResponseToolCall } from './base.js';
20
20
 
21
21
  export interface NormalizedChoiceResult {
22
22
  content: string;
@@ -26,6 +26,7 @@ export interface NormalizedChoiceResult {
26
26
  }
27
27
 
28
28
  const VALID_ID_CHARS = /[^a-zA-Z0-9_-]/g;
29
+ let toolIdSequence = 0;
29
30
 
30
31
  function isPlainObject(value: unknown): value is Record<string, unknown> {
31
32
  return value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -61,7 +62,10 @@ export function sanitizeProviderToolId(rawId: unknown, prefix = 'call', index =
61
62
  ? rawId.trim().replace(VALID_ID_CHARS, '_')
62
63
  : '';
63
64
  if (cleaned.length > 0) return cleaned.slice(0, 64);
64
- return `${prefix.replace(VALID_ID_CHARS, '_')}_${Date.now()}_${index}`.slice(0, 64);
65
+ const safePrefix = (typeof prefix === 'string' ? prefix.replace(VALID_ID_CHARS, '_') : '') || 'call';
66
+ const safeIndex = typeof index === 'number' && Number.isFinite(index) ? Math.max(0, Math.floor(index)) : 0;
67
+ toolIdSequence = (toolIdSequence + 1) % 100_000;
68
+ return `${safePrefix}_${Date.now()}_${safeIndex}_${toolIdSequence}`.slice(0, 64);
65
69
  }
66
70
 
67
71
  function resolveFreeFormPaths(
@@ -75,6 +79,18 @@ function resolveFreeFormPaths(
75
79
  /**
76
80
  * Serialize arguments cleanly to a JSON string while decoding any adapted free-form paths.
77
81
  */
82
+ function safeCloneObject(obj: Record<string, unknown>): Record<string, unknown> {
83
+ try {
84
+ return structuredClone(obj);
85
+ } catch {
86
+ try {
87
+ return JSON.parse(JSON.stringify(obj)) as Record<string, unknown>;
88
+ } catch {
89
+ return { ...obj };
90
+ }
91
+ }
92
+ }
93
+
78
94
  export function serializeAndDecodeArguments(
79
95
  rawArgs: unknown,
80
96
  toolName: string,
@@ -82,13 +98,18 @@ export function serializeAndDecodeArguments(
82
98
  ): string {
83
99
  const paths = resolveFreeFormPaths(toolName, freeFormPaths);
84
100
  if (typeof rawArgs === 'string') {
101
+ if (rawArgs.trim().length === 0) return '{}';
85
102
  if (!paths || paths.length === 0) return rawArgs;
86
103
  const obj = safeParseJsonObject(rawArgs);
87
104
  if (Object.keys(obj).length === 0) return rawArgs;
88
- const decoded = decodeFreeFormArguments(structuredClone(obj), paths);
89
- return JSON.stringify(decoded);
105
+ const decoded = decodeFreeFormArguments(safeCloneObject(obj), paths);
106
+ try {
107
+ return JSON.stringify(decoded);
108
+ } catch {
109
+ return rawArgs;
110
+ }
90
111
  }
91
- const obj = isPlainObject(rawArgs) ? structuredClone(rawArgs) : {};
112
+ const obj = isPlainObject(rawArgs) ? safeCloneObject(rawArgs) : {};
92
113
  const finalObj = paths && paths.length > 0 ? decodeFreeFormArguments(obj, paths) : obj;
93
114
  try {
94
115
  return JSON.stringify(finalObj);
@@ -108,14 +129,20 @@ export function extractTextToolCalls(
108
129
  const calls: ChatResponseToolCall[] = [];
109
130
  if (!text || typeof text !== 'string') return calls;
110
131
  let index = 0;
132
+ const seenIds = new Set<string>();
111
133
  for (const parsed of extractToolCallJsonObjects(text)) {
112
134
  const fnObj = isPlainObject(parsed['function']) ? parsed['function'] : null;
113
135
  const rawName = String(parsed['name'] || parsed['tool'] || fnObj?.['name'] || '').trim();
114
136
  if (!rawName) continue;
115
137
  const name = normalizeToolName(rawName);
138
+ if (!name) continue;
116
139
  const rawArgs = resolveToolCallEnvelopeArguments(parsed);
140
+ let id = sanitizeProviderToolId(parsed['id'], prefix, index);
141
+ if (seenIds.has(id)) id = `${id.slice(0, 56)}_${index}`;
142
+ seenIds.add(id);
143
+ index++;
117
144
  calls.push({
118
- id: sanitizeProviderToolId(parsed['id'], prefix, index++),
145
+ id,
119
146
  type: 'function',
120
147
  function: {
121
148
  name,
@@ -136,6 +163,7 @@ export function normalizeOpenAIToolCalls(
136
163
  ): ChatResponseToolCall[] {
137
164
  if (!Array.isArray(rawCalls)) return [];
138
165
  const normalized: ChatResponseToolCall[] = [];
166
+ const seenIds = new Set<string>();
139
167
  for (let i = 0; i < rawCalls.length; i++) {
140
168
  const tc = rawCalls[i];
141
169
  if (!isPlainObject(tc)) continue;
@@ -143,9 +171,13 @@ export function normalizeOpenAIToolCalls(
143
171
  const rawName = String(fnObj?.['name'] || tc['name'] || '').trim();
144
172
  if (!rawName) continue;
145
173
  const name = normalizeToolName(rawName);
174
+ if (!name) continue;
146
175
  const rawArgs = fnObj ? fnObj['arguments'] : tc['arguments'];
176
+ let id = sanitizeProviderToolId(tc['id'], prefix, i);
177
+ if (seenIds.has(id)) id = `${id.slice(0, 56)}_${i}`;
178
+ seenIds.add(id);
147
179
  normalized.push({
148
- id: sanitizeProviderToolId(tc['id'], prefix, i),
180
+ id,
149
181
  type: 'function',
150
182
  function: {
151
183
  name,
@@ -181,10 +213,24 @@ export function normalizeOpenAIChatChoiceResponse(
181
213
  const choice = isPlainObject(payload['choices'][0]) ? payload['choices'][0] : null;
182
214
  const message = choice && isPlainObject(choice['message']) ? choice['message'] : null;
183
215
  if (message) {
184
- content = typeof message['content'] === 'string' ? message['content'] : '';
216
+ if (typeof message['content'] === 'string') {
217
+ content = message['content'];
218
+ } else if (Array.isArray(message['content'])) {
219
+ content = (message['content'] as unknown[])
220
+ .map((part) => (isPlainObject(part) && typeof part['text'] === 'string' ? part['text'] : ''))
221
+ .filter(Boolean)
222
+ .join('');
223
+ }
185
224
  rawToolCalls = message['tool_calls'];
186
- const rc = message['reasoning_content'] ?? message['reasoning'];
187
- reasoningContent = typeof rc === 'string' ? rc : '';
225
+ const rc = message['reasoning_content'] ?? message['reasoning'] ?? message['thinking'];
226
+ if (typeof rc === 'string') {
227
+ reasoningContent = rc;
228
+ } else if (Array.isArray(message['reasoning_details'])) {
229
+ reasoningContent = (message['reasoning_details'] as unknown[])
230
+ .map((d) => (isPlainObject(d) ? (typeof d['text'] === 'string' ? d['text'] : (typeof d['summary'] === 'string' ? d['summary'] : '')) : ''))
231
+ .filter(Boolean)
232
+ .join('\n');
233
+ }
188
234
  }
189
235
  }
190
236
 
@@ -234,7 +280,7 @@ export function prepareMessagesForAnthropic(
234
280
  for (const msg of messages) {
235
281
  if (!isPlainObject(msg)) continue;
236
282
  if (msg['role'] === 'system') {
237
- const { spillPath: _spill, ...rest } = msg;
283
+ const { spillPath: _spill, thinking_blocks: _tb, reasoning_content: _rc, ...rest } = msg;
238
284
  prepared.push(rest);
239
285
  continue;
240
286
  }
@@ -256,7 +302,17 @@ export function prepareMessagesForAnthropic(
256
302
  export function normalizeMessagesForOllama(messages: unknown[]): any[] {
257
303
  if (!Array.isArray(messages)) return [];
258
304
  return messages.map((msg) => {
259
- if (!isPlainObject(msg) || msg['role'] !== 'assistant' || !Array.isArray(msg['tool_calls'])) {
305
+ if (!isPlainObject(msg)) return msg;
306
+ if (msg['role'] === 'tool' && typeof msg['content'] !== 'string') {
307
+ let str = '';
308
+ try {
309
+ str = msg['content'] == null ? '' : JSON.stringify(msg['content']);
310
+ } catch {
311
+ str = String(msg['content'] ?? '');
312
+ }
313
+ return { ...msg, content: str };
314
+ }
315
+ if (msg['role'] !== 'assistant' || !Array.isArray(msg['tool_calls'])) {
260
316
  return msg;
261
317
  }
262
318
  return {
@@ -3,80 +3,81 @@ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
4
  import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
5
5
  import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
6
- import {
7
- requireApiKey,
8
- resolveTemperature,
9
- safeProviderFetchJson
10
- } from './byokHttp.js';
6
+ import { requireApiKey, resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
11
7
  import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
12
-
13
8
  export class XAIProvider extends LLMProvider {
14
- constructor(config) {
15
- super(config);
16
- this.baseUrl = 'https://api.x.ai/v1/chat/completions';
17
- this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['xai']);
18
- this.visionModels = ['grok-4', 'vision'];
19
- // Grok has no audio input block on the chat completions API.
20
- this.audioModels = [];
21
- }
22
-
23
- async chat(messages, options = {}) {
24
- const apiKey = requireApiKey(this.apiKey, 'xAI (Grok)');
25
- const sanitizedMessages = this.prepareMessages(messages);
26
-
27
- const payload = {
28
- model: this.model,
29
- messages: sanitizedMessages,
30
- temperature: resolveTemperature(options.temperature, 0.1),
31
- };
32
-
33
- if (options.jsonMode) {
34
- payload.response_format = { type: 'json_object' };
9
+ allowInsecureHttp;
10
+ reasoningEffort;
11
+ constructor(config = {}) {
12
+ super(config);
13
+ const customUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
14
+ this.baseUrl = customUrl || 'https://api.x.ai/v1/chat/completions';
15
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
16
+ const rawEffort = typeof config.reasoningEffort === 'string' ? config.reasoningEffort.trim().toLowerCase() : '';
17
+ this.reasoningEffort = rawEffort === 'low' || rawEffort === 'high' ? rawEffort : null;
18
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['xai']) || '');
19
+ this.visionModels = ['grok-4', 'vision'];
20
+ this.audioModels = [];
35
21
  }
36
-
37
- let freeFormPaths = new Map();
38
- if (options.tools && options.tools.length > 0) {
39
- const scanReport = scanAndAdaptToolsForProvider(options.tools, 'xai');
40
- payload.tools = scanReport.adaptedTools;
41
- payload.tool_choice = "auto";
42
- freeFormPaths = scanReport.freeFormPaths;
43
- }
44
-
45
- const requestOpts = {
46
- url: this.baseUrl,
47
- method: 'POST',
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
- };
58
-
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)
22
+ async chat(messages, options = {}) {
23
+ const apiKey = requireApiKey(this.apiKey, 'xAI (Grok)');
24
+ const sanitizedMessages = this.prepareMessages(messages);
25
+ const payload = {
26
+ model: this.model,
27
+ messages: sanitizedMessages,
28
+ temperature: resolveTemperature(options.temperature, 0.1)
29
+ };
30
+ if (this.reasoningEffort && (this.model || '').toLowerCase().includes('grok-3-mini')) {
31
+ payload['reasoning_effort'] = this.reasoningEffort;
32
+ }
33
+ if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
34
+ payload['max_tokens'] = Math.floor(options.maxTokens);
35
+ }
36
+ if (options.jsonMode) {
37
+ payload['response_format'] = { type: 'json_object' };
38
+ }
39
+ let freeFormPaths = new Map();
40
+ if (options.tools && options.tools.length > 0) {
41
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'xai');
42
+ payload['tools'] = scanReport.adaptedTools;
43
+ payload['tool_choice'] = 'auto';
44
+ freeFormPaths = scanReport.freeFormPaths;
45
+ }
46
+ const endpoint = this.baseUrl || 'https://api.x.ai/v1/chat/completions';
47
+ const requestOpts = {
48
+ url: endpoint,
49
+ method: 'POST',
50
+ headers: {
51
+ 'Content-Type': 'application/json',
52
+ 'Authorization': `Bearer ${apiKey}`
53
+ },
54
+ signal: options.signal,
55
+ timeoutMs: options.timeoutMs,
56
+ providerLabel: 'xAI',
57
+ secrets: [apiKey],
58
+ hasApiKey: true,
59
+ allowInsecureHttp: this.allowInsecureHttp
60
+ };
61
+ const data = wantsStreaming(options)
62
+ ? await streamOpenAICompatibleChat({
63
+ ...requestOpts,
64
+ payload,
65
+ onChunk: options.onChunk,
66
+ onReasoningChunk: options.onReasoningChunk
67
+ })
68
+ : await safeProviderFetchJson({
69
+ ...requestOpts,
70
+ body: JSON.stringify(payload)
71
+ });
72
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
73
+ prefix: 'call_xai',
74
+ freeFormPaths
69
75
  });
70
- const normalized = normalizeOpenAIChatChoiceResponse(data, {
71
- prefix: 'call_xai',
72
- freeFormPaths
73
- });
74
-
75
- return {
76
- content: normalized.content,
77
- toolCalls: normalized.toolCalls,
78
- reasoningContent: normalized.reasoningContent,
79
- usage: this.normalizeUsage(normalized.rawUsage)
80
- };
81
- }
76
+ return {
77
+ content: normalized.content,
78
+ toolCalls: normalized.toolCalls,
79
+ reasoningContent: normalized.reasoningContent,
80
+ usage: this.normalizeUsage(normalized.rawUsage)
81
+ };
82
+ }
82
83
  }
@@ -0,0 +1,97 @@
1
+ import { canonicalModelId } from '../modelIds.js';
2
+ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
+ import { LLMProvider, type ChatOptions, type ChatResponse, type ProviderConfig } from './base.js';
4
+ import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
5
+ import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
6
+ import {
7
+ requireApiKey,
8
+ resolveTemperature,
9
+ safeProviderFetchJson
10
+ } from './byokHttp.js';
11
+ import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
12
+
13
+ export class XAIProvider extends LLMProvider {
14
+ allowInsecureHttp: boolean;
15
+ reasoningEffort: string | null;
16
+
17
+ constructor(config: ProviderConfig = {}) {
18
+ super(config);
19
+ const customUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
20
+ this.baseUrl = customUrl || 'https://api.x.ai/v1/chat/completions';
21
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
22
+ const rawEffort = typeof config.reasoningEffort === 'string' ? config.reasoningEffort.trim().toLowerCase() : '';
23
+ this.reasoningEffort = rawEffort === 'low' || rawEffort === 'high' ? rawEffort : null;
24
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['xai']) || '');
25
+ this.visionModels = ['grok-4', 'vision'];
26
+ this.audioModels = [];
27
+ }
28
+
29
+ override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
30
+ const apiKey = requireApiKey(this.apiKey, 'xAI (Grok)');
31
+ const sanitizedMessages = this.prepareMessages(messages);
32
+
33
+ const payload: Record<string, any> = {
34
+ model: this.model,
35
+ messages: sanitizedMessages,
36
+ temperature: resolveTemperature(options.temperature, 0.1)
37
+ };
38
+
39
+ if (this.reasoningEffort && (this.model || '').toLowerCase().includes('grok-3-mini')) {
40
+ payload['reasoning_effort'] = this.reasoningEffort;
41
+ }
42
+ if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
43
+ payload['max_tokens'] = Math.floor(options.maxTokens);
44
+ }
45
+
46
+ if (options.jsonMode) {
47
+ payload['response_format'] = { type: 'json_object' };
48
+ }
49
+
50
+ let freeFormPaths = new Map<string, string[][]>();
51
+ if (options.tools && options.tools.length > 0) {
52
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'xai');
53
+ payload['tools'] = scanReport.adaptedTools;
54
+ payload['tool_choice'] = 'auto';
55
+ freeFormPaths = scanReport.freeFormPaths;
56
+ }
57
+
58
+ const endpoint = this.baseUrl || 'https://api.x.ai/v1/chat/completions';
59
+ const requestOpts = {
60
+ url: endpoint,
61
+ method: 'POST',
62
+ headers: {
63
+ 'Content-Type': 'application/json',
64
+ 'Authorization': `Bearer ${apiKey}`
65
+ },
66
+ signal: options.signal,
67
+ timeoutMs: options.timeoutMs,
68
+ providerLabel: 'xAI',
69
+ secrets: [apiKey],
70
+ hasApiKey: true,
71
+ allowInsecureHttp: this.allowInsecureHttp
72
+ };
73
+
74
+ const data = wantsStreaming(options)
75
+ ? await streamOpenAICompatibleChat({
76
+ ...requestOpts,
77
+ payload,
78
+ onChunk: options.onChunk,
79
+ onReasoningChunk: options.onReasoningChunk
80
+ })
81
+ : await safeProviderFetchJson({
82
+ ...requestOpts,
83
+ body: JSON.stringify(payload)
84
+ });
85
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
86
+ prefix: 'call_xai',
87
+ freeFormPaths
88
+ });
89
+
90
+ return {
91
+ content: normalized.content,
92
+ toolCalls: normalized.toolCalls,
93
+ reasoningContent: normalized.reasoningContent,
94
+ usage: this.normalizeUsage(normalized.rawUsage)
95
+ };
96
+ }
97
+ }
@@ -52,7 +52,7 @@ export async function inspectRequestedImageAssets({ prompt, workspaceRoot, webAr
52
52
  for (const candidate of paths) {
53
53
  if (typeof candidate !== 'string' || !/\.(html?|css)$/i.test(candidate))
54
54
  continue;
55
- const physical = await fs.realpath(path.resolve(candidate)).catch(() => null);
55
+ const physical = await fs.realpath(path.resolve(workspace, candidate)).catch(() => null);
56
56
  if (!physical || !within(workspace, physical))
57
57
  continue;
58
58
  const stat = await fs.stat(physical).catch(() => null);
@@ -79,7 +79,9 @@ export async function inspectRequestedImageAssets({ prompt, workspaceRoot, webAr
79
79
  catch {
80
80
  continue;
81
81
  }
82
- const image = path.resolve(path.dirname(sourceFile), decoded);
82
+ const image = decoded.startsWith('/')
83
+ ? path.resolve(workspace, decoded.replace(/^\/+/, ''))
84
+ : path.resolve(path.dirname(sourceFile), decoded);
83
85
  try {
84
86
  const physical = await fs.realpath(image);
85
87
  if (!within(workspace, physical))
@@ -65,7 +65,7 @@ export async function inspectRequestedImageAssets({ prompt, workspaceRoot, webAr
65
65
  const candidates: string[] = [];
66
66
  for (const candidate of paths) {
67
67
  if (typeof candidate !== 'string' || !/\.(html?|css)$/i.test(candidate)) continue;
68
- const physical = await fs.realpath(path.resolve(candidate)).catch(() => null);
68
+ const physical = await fs.realpath(path.resolve(workspace, candidate)).catch(() => null);
69
69
  if (!physical || !within(workspace, physical)) continue;
70
70
  const stat = await fs.stat(physical).catch(() => null);
71
71
  if (stat?.isFile() && stat.size <= 1_000_000) candidates.push(physical);
@@ -83,7 +83,9 @@ export async function inspectRequestedImageAssets({ prompt, workspaceRoot, webAr
83
83
  if (/^(?:https?:|data:|\/\/|blob:)/i.test(ref)) continue;
84
84
  let decoded: string;
85
85
  try { decoded = decodeURIComponent(ref.split(/[?#]/)[0] ?? ''); } catch { continue; }
86
- const image = path.resolve(path.dirname(sourceFile), decoded);
86
+ const image = decoded.startsWith('/')
87
+ ? path.resolve(workspace, decoded.replace(/^\/+/, ''))
88
+ : path.resolve(path.dirname(sourceFile), decoded);
87
89
  try {
88
90
  const physical = await fs.realpath(image);
89
91
  if (!within(workspace, physical)) continue;