@causyne/agent 1.20.120 → 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 (276) 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 +117 -0
  14. package/src/agent/errorClassifier.ts +165 -0
  15. package/src/agent/promptIntent.js +200 -0
  16. package/src/agent/promptIntent.ts +203 -0
  17. package/src/agent/toolArgValidator.js +97 -0
  18. package/src/agent/toolArgValidator.ts +112 -0
  19. package/src/agentLoop.js +33 -344
  20. package/src/agentLoop.ts +51 -352
  21. package/src/approvalGrants.js +19 -7
  22. package/src/approvalGrants.ts +20 -7
  23. package/src/approvalPolicy.js +48 -15
  24. package/src/approvalPolicy.ts +46 -15
  25. package/src/autoUpdate.js +116 -10
  26. package/src/autoUpdate.ts +149 -10
  27. package/src/browser/causyneBrowser.js +3 -2
  28. package/src/browser/causyneBrowser.ts +3 -2
  29. package/src/browser/searchProviders.js +1 -1
  30. package/src/browser/searchProviders.ts +1 -1
  31. package/src/cliMode.js +16 -2
  32. package/src/commands.js +10 -9
  33. package/src/config.js +288 -272
  34. package/src/config.ts +342 -0
  35. package/src/configVault.js +271 -0
  36. package/src/configVault.ts +273 -0
  37. package/src/continuum/compactor.js +2 -1
  38. package/src/continuum/compactor.ts +2 -1
  39. package/src/continuum/sanitizer.js +10 -3
  40. package/src/continuum/sanitizer.ts +9 -3
  41. package/src/continuum/ui/continuumPickerView.js +3 -2
  42. package/src/continuum/ui/continuumPickerView.ts +3 -2
  43. package/src/core/contextCompactor.js +70 -11
  44. package/src/core/contextCompactor.ts +83 -11
  45. package/src/cortex/vectorDb.js +26 -15
  46. package/src/cortex/vectorDb.ts +26 -16
  47. package/src/creative/liveBridge.js +7 -5
  48. package/src/creative/liveBridge.ts +7 -5
  49. package/src/creative/studioScripts.js +16 -5
  50. package/src/creative/studioScripts.ts +14 -5
  51. package/src/decisionPolicy.js +16 -4
  52. package/src/decisionPolicy.ts +14 -4
  53. package/src/documentEngine/antiSlopAuditor.js +10 -5
  54. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  55. package/src/documentEngine/documentForge.js +47 -15
  56. package/src/documentEngine/documentForge.ts +43 -14
  57. package/src/dynamicCatalogue.js +42 -73
  58. package/src/dynamicCatalogue.ts +74 -60
  59. package/src/engines/design.js +2 -1
  60. package/src/engines/design.ts +2 -1
  61. package/src/engines/film.js +4 -4
  62. package/src/engines/film.ts +2 -2
  63. package/src/engines/light.js +2 -1
  64. package/src/engines/light.ts +2 -1
  65. package/src/engines/registry.js +1 -1
  66. package/src/engines/registry.ts +1 -1
  67. package/src/engines/reverseHarness.js +4 -3
  68. package/src/engines/reverseHarness.ts +4 -3
  69. package/src/entrypoint.js +77 -4
  70. package/src/headlessCli.js +305 -0
  71. package/src/headlessCli.ts +381 -0
  72. package/src/historyPruner.js +3 -2
  73. package/src/historyPruner.ts +3 -2
  74. package/src/hooks.js +3 -0
  75. package/src/hooks.ts +3 -0
  76. package/src/implementationPlan.js +21 -11
  77. package/src/implementationPlan.ts +21 -11
  78. package/src/infra/atomicWriter.js +4 -1
  79. package/src/infra/atomicWriter.ts +4 -1
  80. package/src/launchIntent.js +1 -1
  81. package/src/launchIntent.ts +1 -1
  82. package/src/mcp/mcpClient.js +38 -11
  83. package/src/mcp/mcpClient.ts +44 -11
  84. package/src/mcp/mcpRegistry.js +2 -5
  85. package/src/mcp/mcpRegistry.ts +2 -5
  86. package/src/mcp/mcpSecurity.js +189 -0
  87. package/src/mcp/mcpSecurity.ts +190 -0
  88. package/src/memory/scopedFacts.js +1 -1
  89. package/src/memory/scopedFacts.ts +1 -1
  90. package/src/memory/symbolFolder.js +1 -1
  91. package/src/memory/symbolFolder.ts +1 -1
  92. package/src/modelRouter.js +1 -1
  93. package/src/modelRouter.ts +1 -1
  94. package/src/observer/evidence.js +10 -4
  95. package/src/observer/evidence.ts +10 -4
  96. package/src/osKeychain.js +263 -0
  97. package/src/osKeychain.ts +287 -0
  98. package/src/perception.js +3 -2
  99. package/src/perception.ts +3 -2
  100. package/src/planCache.js +2 -2
  101. package/src/planCache.ts +2 -2
  102. package/src/pluginsFactory/pluginsFactory.js +19 -11
  103. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  104. package/src/promptMentions.js +2 -2
  105. package/src/promptMentions.ts +2 -2
  106. package/src/providers/acp.js +1 -1
  107. package/src/providers/acp.ts +1 -1
  108. package/src/providers/anthropic.js +328 -385
  109. package/src/providers/anthropic.ts +386 -0
  110. package/src/providers/antigravity.js +10 -4
  111. package/src/providers/antigravity.ts +10 -4
  112. package/src/providers/base.js +221 -319
  113. package/src/providers/base.ts +340 -0
  114. package/src/providers/byokHttp.js +397 -0
  115. package/src/providers/byokHttp.ts +497 -0
  116. package/src/providers/byokStream.js +748 -0
  117. package/src/providers/byokStream.ts +863 -0
  118. package/src/providers/dashscope-byok.js +98 -81
  119. package/src/providers/dashscope-byok.ts +114 -0
  120. package/src/providers/deepseek.js +74 -64
  121. package/src/providers/deepseek.ts +99 -0
  122. package/src/providers/factory.js +35 -28
  123. package/src/providers/factory.ts +40 -0
  124. package/src/providers/gemini.js +229 -253
  125. package/src/providers/gemini.ts +261 -0
  126. package/src/providers/loopGuard.js +9 -5
  127. package/src/providers/loopGuard.ts +10 -5
  128. package/src/providers/moonshot.js +71 -64
  129. package/src/providers/moonshot.ts +93 -0
  130. package/src/providers/muse.js +82 -152
  131. package/src/providers/muse.ts +122 -0
  132. package/src/providers/ollama.js +116 -93
  133. package/src/providers/ollama.ts +135 -0
  134. package/src/providers/openai-compatible.js +114 -65
  135. package/src/providers/openai-compatible.ts +139 -0
  136. package/src/providers/openai.js +22 -15
  137. package/src/providers/openai.ts +30 -0
  138. package/src/providers/openrouter.js +194 -98
  139. package/src/providers/openrouter.ts +202 -97
  140. package/src/providers/pi.js +6 -0
  141. package/src/providers/pi.ts +6 -0
  142. package/src/providers/qwen-byok.js +97 -71
  143. package/src/providers/qwen-byok.ts +113 -0
  144. package/src/providers/toolContracts.js +40 -14
  145. package/src/providers/toolContracts.ts +35 -14
  146. package/src/providers/wireNormalizer.js +78 -11
  147. package/src/providers/wireNormalizer.ts +68 -12
  148. package/src/providers/xai.js +74 -64
  149. package/src/providers/xai.ts +97 -0
  150. package/src/reliability/assetEvidence.js +4 -2
  151. package/src/reliability/assetEvidence.ts +4 -2
  152. package/src/sandbox.js +486 -530
  153. package/src/sandbox.ts +552 -0
  154. package/src/sandboxPolicy.js +1287 -0
  155. package/src/sandboxPolicy.ts +1381 -0
  156. package/src/sessionJournal.js +55 -3
  157. package/src/sessionJournal.ts +58 -3
  158. package/src/skills/skillResourceSafety.js +19 -8
  159. package/src/skills/skillResourceSafety.ts +16 -7
  160. package/src/skillsManager.js +3 -3
  161. package/src/skillsManager.ts +3 -3
  162. package/src/smartToolsUse.js +28 -4
  163. package/src/smartToolsUse.ts +29 -7
  164. package/src/stallGuard.js +45 -22
  165. package/src/stallGuard.ts +46 -22
  166. package/src/subagentJournal.js +6 -4
  167. package/src/subagentJournal.ts +6 -4
  168. package/src/textDiff.js +6 -1
  169. package/src/textDiff.ts +6 -1
  170. package/src/timeMachine.js +7 -1
  171. package/src/timeMachine.ts +7 -1
  172. package/src/tokenTracker.js +43 -28
  173. package/src/tokenTracker.ts +44 -30
  174. package/src/toolPacks.js +3 -1
  175. package/src/toolPacks.ts +3 -1
  176. package/src/tools/archive.js +245 -35
  177. package/src/tools/archive.ts +244 -35
  178. package/src/tools/computerUse.js +7 -3
  179. package/src/tools/computerUse.ts +7 -3
  180. package/src/tools/creativeApps.js +13 -8
  181. package/src/tools/creativeApps.ts +22 -9
  182. package/src/tools/deferredMcpSearch.js +26 -14
  183. package/src/tools/deferredMcpSearch.ts +26 -14
  184. package/src/tools/desktopOpen.js +69 -10
  185. package/src/tools/desktopOpen.ts +70 -11
  186. package/src/tools/documentForge.js +167 -82
  187. package/src/tools/documentForge.ts +169 -84
  188. package/src/tools/fsEdit.js +101 -30
  189. package/src/tools/fsEdit.ts +105 -32
  190. package/src/tools/fsFind.js +8 -5
  191. package/src/tools/fsFind.ts +7 -4
  192. package/src/tools/fsRead.js +119 -13
  193. package/src/tools/fsRead.ts +124 -13
  194. package/src/tools/fsWrite.js +17 -5
  195. package/src/tools/fsWrite.ts +17 -7
  196. package/src/tools/generateMediaViaApi.js +82 -19
  197. package/src/tools/generateMediaViaApi.ts +80 -19
  198. package/src/tools/memoryRecall.js +62 -11
  199. package/src/tools/memoryRecall.ts +70 -13
  200. package/src/tools/memoryWrite.js +27 -14
  201. package/src/tools/memoryWrite.ts +30 -14
  202. package/src/tools/multiEdit.js +100 -30
  203. package/src/tools/multiEdit.ts +104 -32
  204. package/src/tools/nativeEngine.js +33 -18
  205. package/src/tools/nativeEngine.ts +31 -18
  206. package/src/tools/openSourceToolProvisioner.js +49 -14
  207. package/src/tools/openSourceToolProvisioner.ts +54 -15
  208. package/src/tools/osSandbox.js +513 -0
  209. package/src/tools/osSandbox.ts +588 -0
  210. package/src/tools/payloadSanitizer.js +40 -8
  211. package/src/tools/payloadSanitizer.ts +39 -8
  212. package/src/tools/peerAgent.js +96 -34
  213. package/src/tools/peerAgent.ts +114 -37
  214. package/src/tools/persistentShell.js +8 -3
  215. package/src/tools/pluginsFactory.js +38 -6
  216. package/src/tools/pluginsFactory.ts +42 -6
  217. package/src/tools/readNativeSkill.js +10 -8
  218. package/src/tools/readNativeSkill.ts +10 -8
  219. package/src/tools/requestDecision.js +10 -3
  220. package/src/tools/requestDecision.ts +10 -3
  221. package/src/tools/resolveAutomator.js +91 -17
  222. package/src/tools/resolveAutomator.ts +102 -17
  223. package/src/tools/reverseEngineering.js +168 -41
  224. package/src/tools/reverseEngineering.ts +161 -41
  225. package/src/tools/subprocessEnv.js +197 -0
  226. package/src/tools/subprocessEnv.ts +212 -0
  227. package/src/tools/sysRun.js +108 -35
  228. package/src/tools/sysRun.ts +119 -31
  229. package/src/tools/toolDispatch.js +24 -1
  230. package/src/tools/toolDispatch.ts +21 -1
  231. package/src/tools/toolOutputStore.js +62 -23
  232. package/src/tools/toolOutputStore.ts +56 -23
  233. package/src/tools/toolScanner.js +13 -10
  234. package/src/tools/toolScanner.ts +13 -10
  235. package/src/tools/toolSelfRepair.js +94 -28
  236. package/src/tools/toolSelfRepair.ts +96 -28
  237. package/src/tools/uiForge.js +71 -6
  238. package/src/tools/uiForge.ts +74 -6
  239. package/src/tools/viewImage.js +62 -17
  240. package/src/tools/viewImage.ts +57 -12
  241. package/src/tools/visionInspector.js +15 -3
  242. package/src/tools/visionInspector.ts +15 -3
  243. package/src/tools/walkerSafety.js +2 -0
  244. package/src/tools/walkerSafety.ts +1 -0
  245. package/src/tools/webFetch.js +105 -10
  246. package/src/tools/webFetch.ts +105 -11
  247. package/src/tui/banner.js +3 -2
  248. package/src/tui/banner.ts +3 -2
  249. package/src/tui/consoleGuard.js +12 -4
  250. package/src/tui/consoleGuard.ts +9 -4
  251. package/src/tui/messageInteraction.js +2 -3
  252. package/src/tui/messageInteraction.ts +2 -3
  253. package/src/tui/modelPicker.js +1 -0
  254. package/src/tui/modelPicker.ts +1 -0
  255. package/src/tui/overlay.js +3 -1
  256. package/src/tui/overlay.ts +3 -1
  257. package/src/tui/sessionPicker.js +3 -2
  258. package/src/tui/sessionPicker.ts +3 -2
  259. package/src/tui/sessionPickerView.js +7 -1
  260. package/src/tui/sessionPickerView.ts +6 -1
  261. package/src/tui/toolOutputNormalizer.js +2 -3
  262. package/src/tui/toolOutputNormalizer.ts +4 -3
  263. package/src/tui/viewport.js +4 -4
  264. package/src/tui/viewport.ts +5 -5
  265. package/src/tui/workspaceIdentity.js +2 -1
  266. package/src/tui/workspaceIdentity.ts +2 -1
  267. package/src/uncertainty.js +8 -3
  268. package/src/uncertainty.ts +8 -3
  269. package/src/utils/paths.js +8 -5
  270. package/src/utils/paths.ts +9 -7
  271. package/src/vfeTracker.js +9 -3
  272. package/src/vfeTracker.ts +9 -3
  273. package/src/config.d.ts +0 -2
  274. package/src/providers/base.d.ts +0 -94
  275. package/src/providers/factory.d.ts +0 -1
  276. package/src/sandbox.d.ts +0 -1
@@ -0,0 +1,135 @@
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 {
6
+ normalizeMessagesForOllama,
7
+ normalizeOpenAIToolCalls,
8
+ extractTextToolCalls
9
+ } from './wireNormalizer.js';
10
+ import { stripToolCallMarkup } from '../implementationPlan.js';
11
+ import { resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
12
+ import { streamOllamaChat, wantsStreaming } from './byokStream.js';
13
+
14
+ export class OllamaProvider extends LLMProvider {
15
+ allowInsecureHttp: boolean;
16
+
17
+ constructor(config: ProviderConfig = {}) {
18
+ super(config);
19
+ const rawUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
20
+ let resolvedUrl = rawUrl || 'http://localhost:11434/api/chat';
21
+ if (rawUrl) {
22
+ try {
23
+ const parsed = new URL(rawUrl);
24
+ if (parsed.pathname === '' || parsed.pathname === '/') {
25
+ parsed.pathname = '/api/chat';
26
+ resolvedUrl = parsed.toString();
27
+ }
28
+ } catch {
29
+ resolvedUrl = rawUrl;
30
+ }
31
+ }
32
+ this.baseUrl = resolvedUrl;
33
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
34
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['ollama']) || '');
35
+ this.visionModels = ['llava', 'vision', 'bakllava', 'moondream', 'minicpm-v', 'gemma3', 'qwen2.5vl', 'qwen3-vl'];
36
+ this.audioModels = [];
37
+ }
38
+
39
+ override normalizeImageBlocks(msg: any): any {
40
+ if (!Array.isArray(msg.content)) return msg;
41
+
42
+ const text: string[] = [];
43
+ const images: string[] = [];
44
+
45
+ for (const block of msg.content) {
46
+ if (!block || typeof block !== 'object') continue;
47
+ if (block.type === 'text' && typeof block.text === 'string') {
48
+ text.push(block.text);
49
+ } else if (block.type === 'image' && block.source?.type === 'base64') {
50
+ images.push(block.source.data);
51
+ } else if (block.type === 'image_url' && typeof block.image_url?.url === 'string') {
52
+ const encoded = block.image_url.url.split('base64,')[1];
53
+ if (encoded) images.push(encoded);
54
+ }
55
+ }
56
+
57
+ const normalized: Record<string, any> = { ...msg, content: text.join('\n') };
58
+ if (images.length > 0) normalized['images'] = images;
59
+ return normalized;
60
+ }
61
+
62
+ override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
63
+ const sanitizedMessages = normalizeMessagesForOllama(this.prepareMessages(messages));
64
+
65
+ const ollamaOptions: Record<string, any> = {
66
+ temperature: resolveTemperature(options.temperature, 0.1)
67
+ };
68
+ if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
69
+ ollamaOptions['num_predict'] = Math.floor(options.maxTokens);
70
+ }
71
+ const payload: Record<string, any> = {
72
+ model: this.model,
73
+ messages: sanitizedMessages,
74
+ stream: false,
75
+ options: ollamaOptions,
76
+ ...(options.jsonMode ? { format: 'json' } : {})
77
+ };
78
+
79
+ let freeFormPaths = new Map<string, string[][]>();
80
+ if (options.tools && options.tools.length > 0) {
81
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'ollama');
82
+ payload['tools'] = scanReport.adaptedTools;
83
+ freeFormPaths = scanReport.freeFormPaths;
84
+ }
85
+
86
+ const endpoint = this.baseUrl || 'http://localhost:11434/api/chat';
87
+ const trimmedKey = typeof this.apiKey === 'string' ? this.apiKey.trim() : '';
88
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
89
+ if (trimmedKey) headers['Authorization'] = `Bearer ${trimmedKey}`;
90
+ const requestOpts = {
91
+ url: endpoint,
92
+ method: 'POST',
93
+ headers,
94
+ signal: options.signal,
95
+ timeoutMs: options.timeoutMs,
96
+ providerLabel: 'Ollama',
97
+ secrets: trimmedKey ? [trimmedKey] : [],
98
+ hasApiKey: Boolean(trimmedKey),
99
+ allowInsecureHttp: this.allowInsecureHttp
100
+ };
101
+
102
+ const data: Record<string, any> = wantsStreaming(options)
103
+ ? await streamOllamaChat({
104
+ ...requestOpts,
105
+ payload,
106
+ onChunk: options.onChunk,
107
+ onReasoningChunk: options.onReasoningChunk
108
+ })
109
+ : await safeProviderFetchJson({
110
+ ...requestOpts,
111
+ body: JSON.stringify(payload)
112
+ });
113
+
114
+ let content = typeof data['message']?.content === 'string' ? data['message'].content : '';
115
+ const reasoningContent = typeof data['message']?.thinking === 'string' ? data['message'].thinking.trim() : '';
116
+ let toolCalls = normalizeOpenAIToolCalls(data['message']?.tool_calls, freeFormPaths, 'call_ollama');
117
+ if (toolCalls.length === 0 && content) {
118
+ const extracted = extractTextToolCalls(content, 'call_ollama_text', freeFormPaths);
119
+ if (extracted.length > 0) {
120
+ toolCalls = extracted;
121
+ content = stripToolCallMarkup(content).trim();
122
+ }
123
+ }
124
+
125
+ return {
126
+ content,
127
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
128
+ ...(reasoningContent ? { reasoningContent } : {}),
129
+ usage: {
130
+ promptTokens: typeof data['prompt_eval_count'] === 'number' && Number.isFinite(data['prompt_eval_count']) && data['prompt_eval_count'] > 0 ? data['prompt_eval_count'] : 0,
131
+ completionTokens: typeof data['eval_count'] === 'number' && Number.isFinite(data['eval_count']) && data['eval_count'] > 0 ? data['eval_count'] : 0
132
+ }
133
+ };
134
+ }
135
+ }
@@ -3,74 +3,123 @@ 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
-
6
+ import { isLoopbackHost, requireApiKey, resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
7
+ import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
7
8
  export class OpenAICompatibleProvider extends LLMProvider {
8
- constructor(config) {
9
- super(config);
10
-
11
- // A custom endpoint can serve anything, so guessing from the model id would
12
- // be wrong as often as right. config.supportsAudio is the deliberate opt-in,
13
- // exactly as config.supportsVision already is for images.
14
- this.audioModels = [];
15
- // 'low' | 'medium' | 'high' | 'off'. Unset means: do not send the parameter.
16
- this.reasoningEffort = config.reasoningEffort || null;
17
- this.baseUrl = config.baseUrl || 'https://api.openai.com/v1/chat/completions';
18
- this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['openai']);
19
- }
20
-
21
- async chat(messages, options = {}) {
22
- const preparedMessages = this.prepareMessages(messages);
23
- const payload = {
24
- model: this.model,
25
- messages: preparedMessages,
26
- temperature: options.temperature || 0.1,
27
- };
28
-
29
- // Reasoning models take an effort dial. Sending it to a model that does not
30
- // support it is rejected, so it only goes out when the user configured it —
31
- // a custom OpenAI-compatible endpoint may serve anything, and this provider
32
- // cannot know the model list in advance.
33
- if (this.reasoningEffort && this.reasoningEffort !== 'off') {
34
- payload.reasoning_effort = this.reasoningEffort;
9
+ reasoningEffort;
10
+ allowInsecureHttp;
11
+ providerLabel;
12
+ constructor(config = {}) {
13
+ super(config);
14
+ this.audioModels = [];
15
+ const rawEffort = typeof config.reasoningEffort === 'string' ? config.reasoningEffort.trim().toLowerCase() : '';
16
+ this.reasoningEffort = rawEffort || null;
17
+ const rawUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
18
+ let resolvedUrl = rawUrl || 'https://api.openai.com/v1/chat/completions';
19
+ if (rawUrl) {
20
+ try {
21
+ const parsed = new URL(rawUrl);
22
+ if (parsed.pathname === '/v1' || parsed.pathname === '/v1/') {
23
+ parsed.pathname = '/v1/chat/completions';
24
+ resolvedUrl = parsed.toString();
25
+ }
26
+ }
27
+ catch {
28
+ resolvedUrl = rawUrl;
29
+ }
30
+ }
31
+ this.baseUrl = resolvedUrl;
32
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
33
+ this.providerLabel = 'OpenAI-Compatible';
34
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['openai']) || '');
35
35
  }
36
-
37
- if (options.jsonMode) {
38
- payload.response_format = { type: 'json_object' };
36
+ rejectsSamplingParameters() {
37
+ return false;
39
38
  }
40
-
41
- let freeFormPaths = new Map();
42
- if (options.tools && options.tools.length > 0) {
43
- const scanReport = scanAndAdaptToolsForProvider(options.tools, 'openai');
44
- payload.tools = scanReport.adaptedTools;
45
- payload.tool_choice = "auto";
46
- freeFormPaths = scanReport.freeFormPaths;
39
+ usesMaxCompletionTokens() {
40
+ return false;
47
41
  }
48
-
49
- const response = await fetch(this.baseUrl, {
50
- method: 'POST',
51
- headers: {
52
- 'Content-Type': 'application/json',
53
- 'Authorization': `Bearer ${this.apiKey}`
54
- },
55
- body: JSON.stringify(payload)
56
- });
57
-
58
- if (!response.ok) {
59
- const errorData = await response.text();
60
- throw new Error(`OpenAI-Compatible API Error (${response.status}): ${errorData}`);
42
+ async chat(messages, options = {}) {
43
+ const opts = options && typeof options === 'object' ? options : {};
44
+ const preparedMessages = this.prepareMessages(messages);
45
+ const payload = {
46
+ model: this.model,
47
+ messages: preparedMessages
48
+ };
49
+ if (!this.rejectsSamplingParameters()) {
50
+ payload['temperature'] = resolveTemperature(opts.temperature, 0.1);
51
+ }
52
+ if (this.reasoningEffort && this.reasoningEffort !== 'off') {
53
+ payload['reasoning_effort'] = this.reasoningEffort;
54
+ }
55
+ if (typeof opts.maxTokens === 'number' && Number.isFinite(opts.maxTokens) && opts.maxTokens >= 1) {
56
+ const tokenLimit = Math.floor(opts.maxTokens);
57
+ if (this.usesMaxCompletionTokens()) {
58
+ payload['max_completion_tokens'] = tokenLimit;
59
+ }
60
+ else {
61
+ payload['max_tokens'] = tokenLimit;
62
+ }
63
+ }
64
+ if (opts.jsonMode) {
65
+ payload['response_format'] = { type: 'json_object' };
66
+ }
67
+ let freeFormPaths = new Map();
68
+ if (Array.isArray(opts.tools) && opts.tools.length > 0) {
69
+ const scanReport = scanAndAdaptToolsForProvider(opts.tools, 'openai');
70
+ payload['tools'] = scanReport.adaptedTools;
71
+ payload['tool_choice'] = 'auto';
72
+ freeFormPaths = scanReport.freeFormPaths;
73
+ }
74
+ const headers = {
75
+ 'Content-Type': 'application/json'
76
+ };
77
+ const trimmedKey = typeof this.apiKey === 'string' ? this.apiKey.trim() : '';
78
+ const endpoint = this.baseUrl || 'https://api.openai.com/v1/chat/completions';
79
+ let isLocalEndpoint = false;
80
+ try {
81
+ isLocalEndpoint = isLoopbackHost(new URL(endpoint).hostname);
82
+ }
83
+ catch {
84
+ isLocalEndpoint = false;
85
+ }
86
+ if (trimmedKey) {
87
+ headers['Authorization'] = `Bearer ${trimmedKey}`;
88
+ }
89
+ else if (!isLocalEndpoint) {
90
+ requireApiKey(this.apiKey, this.providerLabel);
91
+ }
92
+ const requestOpts = {
93
+ url: endpoint,
94
+ method: 'POST',
95
+ headers,
96
+ signal: opts.signal,
97
+ timeoutMs: opts.timeoutMs,
98
+ providerLabel: this.providerLabel,
99
+ secrets: trimmedKey ? [trimmedKey] : [],
100
+ hasApiKey: Boolean(trimmedKey),
101
+ allowInsecureHttp: this.allowInsecureHttp
102
+ };
103
+ const data = wantsStreaming(opts)
104
+ ? await streamOpenAICompatibleChat({
105
+ ...requestOpts,
106
+ payload,
107
+ onChunk: opts.onChunk,
108
+ onReasoningChunk: opts.onReasoningChunk
109
+ })
110
+ : await safeProviderFetchJson({
111
+ ...requestOpts,
112
+ body: JSON.stringify(payload)
113
+ });
114
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
115
+ prefix: 'call_oai',
116
+ freeFormPaths
117
+ });
118
+ return {
119
+ content: normalized.content,
120
+ toolCalls: normalized.toolCalls,
121
+ reasoningContent: normalized.reasoningContent,
122
+ usage: this.normalizeUsage(normalized.rawUsage)
123
+ };
61
124
  }
62
-
63
- const data = await response.json();
64
- const normalized = normalizeOpenAIChatChoiceResponse(data, {
65
- prefix: 'call_oai',
66
- freeFormPaths
67
- });
68
-
69
- return {
70
- content: normalized.content,
71
- toolCalls: normalized.toolCalls,
72
- reasoningContent: normalized.reasoningContent,
73
- usage: this.normalizeUsage(normalized.rawUsage)
74
- };
75
- }
76
125
  }
@@ -0,0 +1,139 @@
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
+ isLoopbackHost,
8
+ requireApiKey,
9
+ resolveTemperature,
10
+ safeProviderFetchJson
11
+ } from './byokHttp.js';
12
+ import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
13
+
14
+ export class OpenAICompatibleProvider extends LLMProvider {
15
+ reasoningEffort: string | null;
16
+ allowInsecureHttp: boolean;
17
+ providerLabel: string;
18
+
19
+ constructor(config: ProviderConfig = {}) {
20
+ super(config);
21
+ this.audioModels = [];
22
+ const rawEffort = typeof config.reasoningEffort === 'string' ? config.reasoningEffort.trim().toLowerCase() : '';
23
+ this.reasoningEffort = rawEffort || null;
24
+ const rawUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
25
+ let resolvedUrl = rawUrl || 'https://api.openai.com/v1/chat/completions';
26
+ if (rawUrl) {
27
+ try {
28
+ const parsed = new URL(rawUrl);
29
+ if (parsed.pathname === '/v1' || parsed.pathname === '/v1/') {
30
+ parsed.pathname = '/v1/chat/completions';
31
+ resolvedUrl = parsed.toString();
32
+ }
33
+ } catch {
34
+ resolvedUrl = rawUrl;
35
+ }
36
+ }
37
+ this.baseUrl = resolvedUrl;
38
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
39
+ this.providerLabel = 'OpenAI-Compatible';
40
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['openai']) || '');
41
+ }
42
+
43
+ rejectsSamplingParameters(): boolean {
44
+ return false;
45
+ }
46
+
47
+ usesMaxCompletionTokens(): boolean {
48
+ return false;
49
+ }
50
+
51
+ override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
52
+ const opts = options && typeof options === 'object' ? options : {};
53
+ const preparedMessages = this.prepareMessages(messages);
54
+ const payload: Record<string, any> = {
55
+ model: this.model,
56
+ messages: preparedMessages
57
+ };
58
+ if (!this.rejectsSamplingParameters()) {
59
+ payload['temperature'] = resolveTemperature(opts.temperature, 0.1);
60
+ }
61
+
62
+ if (this.reasoningEffort && this.reasoningEffort !== 'off') {
63
+ payload['reasoning_effort'] = this.reasoningEffort;
64
+ }
65
+
66
+ if (typeof opts.maxTokens === 'number' && Number.isFinite(opts.maxTokens) && opts.maxTokens >= 1) {
67
+ const tokenLimit = Math.floor(opts.maxTokens);
68
+ if (this.usesMaxCompletionTokens()) {
69
+ payload['max_completion_tokens'] = tokenLimit;
70
+ } else {
71
+ payload['max_tokens'] = tokenLimit;
72
+ }
73
+ }
74
+
75
+ if (opts.jsonMode) {
76
+ payload['response_format'] = { type: 'json_object' };
77
+ }
78
+
79
+ let freeFormPaths = new Map<string, string[][]>();
80
+ if (Array.isArray(opts.tools) && opts.tools.length > 0) {
81
+ const scanReport = scanAndAdaptToolsForProvider(opts.tools, 'openai');
82
+ payload['tools'] = scanReport.adaptedTools;
83
+ payload['tool_choice'] = 'auto';
84
+ freeFormPaths = scanReport.freeFormPaths;
85
+ }
86
+
87
+ const headers: Record<string, string> = {
88
+ 'Content-Type': 'application/json'
89
+ };
90
+ const trimmedKey = typeof this.apiKey === 'string' ? this.apiKey.trim() : '';
91
+ const endpoint = this.baseUrl || 'https://api.openai.com/v1/chat/completions';
92
+ let isLocalEndpoint = false;
93
+ try {
94
+ isLocalEndpoint = isLoopbackHost(new URL(endpoint).hostname);
95
+ } catch {
96
+ isLocalEndpoint = false;
97
+ }
98
+ if (trimmedKey) {
99
+ headers['Authorization'] = `Bearer ${trimmedKey}`;
100
+ } else if (!isLocalEndpoint) {
101
+ requireApiKey(this.apiKey, this.providerLabel);
102
+ }
103
+
104
+ const requestOpts = {
105
+ url: endpoint,
106
+ method: 'POST',
107
+ headers,
108
+ signal: opts.signal,
109
+ timeoutMs: opts.timeoutMs,
110
+ providerLabel: this.providerLabel,
111
+ secrets: trimmedKey ? [trimmedKey] : [],
112
+ hasApiKey: Boolean(trimmedKey),
113
+ allowInsecureHttp: this.allowInsecureHttp
114
+ };
115
+
116
+ const data = wantsStreaming(opts)
117
+ ? await streamOpenAICompatibleChat({
118
+ ...requestOpts,
119
+ payload,
120
+ onChunk: opts.onChunk,
121
+ onReasoningChunk: opts.onReasoningChunk
122
+ })
123
+ : await safeProviderFetchJson({
124
+ ...requestOpts,
125
+ body: JSON.stringify(payload)
126
+ });
127
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
128
+ prefix: 'call_oai',
129
+ freeFormPaths
130
+ });
131
+
132
+ return {
133
+ content: normalized.content,
134
+ toolCalls: normalized.toolCalls,
135
+ reasoningContent: normalized.reasoningContent,
136
+ usage: this.normalizeUsage(normalized.rawUsage)
137
+ };
138
+ }
139
+ }
@@ -1,20 +1,27 @@
1
1
  import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { OpenAICompatibleProvider } from './openai-compatible.js';
4
-
5
4
  export class OpenAIProvider extends OpenAICompatibleProvider {
6
- constructor(config) {
7
- super(config);
8
- this.baseUrl = 'https://api.openai.com/v1/chat/completions';
9
- this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['openai']);
10
- this.visionModels = ['*'];
11
- this.imagePayloadFormat = 'openai';
12
- // Vision is '*' but audio is emphatically NOT. OpenAI accepts input_audio
13
- // only on the audio-capable families; the text models reject the block
14
- // outright, so copying visionModels here would 400 on every ordinary chat
15
- // model. Audio input is also limited to wav and mp3 containers, which is
16
-
17
- this.audioModels = ['gpt-4o-audio', 'gpt-4o-mini-audio', 'gpt-audio', 'gpt-realtime'];
18
- this.audioPayloadFormat = 'openai';
19
- }
5
+ constructor(config = {}) {
6
+ super(config);
7
+ if (!config.baseUrl)
8
+ this.baseUrl = 'https://api.openai.com/v1/chat/completions';
9
+ this.providerLabel = 'OpenAI';
10
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['openai']) || '');
11
+ this.visionModels = ['*'];
12
+ this.imagePayloadFormat = 'openai';
13
+ this.audioModels = ['gpt-4o-audio', 'gpt-4o-mini-audio', 'gpt-audio', 'gpt-realtime'];
14
+ this.audioPayloadFormat = 'openai';
15
+ const allowedEfforts = new Set(['low', 'medium', 'high', 'xhigh', 'minimal', 'none', 'off']);
16
+ if (this.reasoningEffort && !allowedEfforts.has(this.reasoningEffort)) {
17
+ this.reasoningEffort = null;
18
+ }
19
+ }
20
+ rejectsSamplingParameters() {
21
+ const lowered = (this.model || '').trim().toLowerCase();
22
+ return /^o[134](?:$|[-.])/.test(lowered);
23
+ }
24
+ usesMaxCompletionTokens() {
25
+ return this.rejectsSamplingParameters();
26
+ }
20
27
  }
@@ -0,0 +1,30 @@
1
+ import { canonicalModelId } from '../modelIds.js';
2
+ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
+ import type { ProviderConfig } from './base.js';
4
+ import { OpenAICompatibleProvider } from './openai-compatible.js';
5
+
6
+ export class OpenAIProvider extends OpenAICompatibleProvider {
7
+ constructor(config: ProviderConfig = {}) {
8
+ super(config);
9
+ if (!config.baseUrl) this.baseUrl = 'https://api.openai.com/v1/chat/completions';
10
+ this.providerLabel = 'OpenAI';
11
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['openai']) || '');
12
+ this.visionModels = ['*'];
13
+ this.imagePayloadFormat = 'openai';
14
+ this.audioModels = ['gpt-4o-audio', 'gpt-4o-mini-audio', 'gpt-audio', 'gpt-realtime'];
15
+ this.audioPayloadFormat = 'openai';
16
+ const allowedEfforts = new Set(['low', 'medium', 'high', 'xhigh', 'minimal', 'none', 'off']);
17
+ if (this.reasoningEffort && !allowedEfforts.has(this.reasoningEffort)) {
18
+ this.reasoningEffort = null;
19
+ }
20
+ }
21
+
22
+ override rejectsSamplingParameters(): boolean {
23
+ const lowered = (this.model || '').trim().toLowerCase();
24
+ return /^o[134](?:$|[-.])/.test(lowered);
25
+ }
26
+
27
+ override usesMaxCompletionTokens(): boolean {
28
+ return this.rejectsSamplingParameters();
29
+ }
30
+ }