@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
@@ -7,16 +7,28 @@
7
7
  * streaming SSE, and safe tool-call parsing without paid model fallbacks.
8
8
  */
9
9
 
10
- import { LLMProvider } from './base.js';
10
+ import { LLMProvider, type ChatOptions, type ChatResponse, type ChatResponseUsage, type ChatResponseToolCall } from './base.js';
11
11
  import { canonicalModelId } from '../modelIds.js';
12
- import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
12
+ import { scanAndAdaptToolsForProvider, normalizeToolName } from '../tools/toolScanner.js';
13
+ import { stripToolCallMarkup } from '../implementationPlan.js';
13
14
  import {
14
15
  extractTextToolCalls,
15
16
  normalizeOpenAIChatChoiceResponse,
17
+ sanitizeProviderToolId,
16
18
  serializeAndDecodeArguments
17
19
  } from './wireNormalizer.js';
18
- import { normalizeToolName } from '../tools/toolScanner.js';
19
- import type { ChatOptions, ChatResponse, ChatResponseUsage, ChatResponseToolCall } from './base.d.js';
20
+ import {
21
+ MAX_PROVIDER_ERROR_BYTES,
22
+ MAX_PROVIDER_JSON_BYTES,
23
+ MAX_SSE_BUFFER_BYTES,
24
+ ProviderHttpError,
25
+ parseRetryAfterMs,
26
+ readBoundedResponseText,
27
+ redactProviderSecrets,
28
+ resolveTemperature,
29
+ safeProviderFetch
30
+ } from './byokHttp.js';
31
+ import { wantsStreaming } from './byokStream.js';
20
32
 
21
33
  export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
22
34
  export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
@@ -30,9 +42,13 @@ export class FreeModeCostGuardError extends Error {
30
42
  }
31
43
 
32
44
  export class OpenRouterRateLimitError extends Error {
33
- constructor(message: string) {
45
+ public readonly status = 429;
46
+ public readonly retryAfterMs?: number | undefined;
47
+
48
+ constructor(message: string, retryAfterMs?: number | undefined) {
34
49
  super(message);
35
50
  this.name = 'OpenRouterRateLimitError';
51
+ this.retryAfterMs = retryAfterMs;
36
52
  }
37
53
  }
38
54
 
@@ -46,10 +62,12 @@ export class OpenRouterPrivacyConstraintError extends Error {
46
62
  export class OpenRouterProvider extends LLMProvider {
47
63
  public dataCollection: 'deny' | 'allow';
48
64
  public freeOnly: boolean;
65
+ public allowInsecureHttp: boolean;
49
66
 
50
67
  constructor(config: Record<string, any> = {}) {
51
68
  super(config);
52
69
  this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
70
+ this.allowInsecureHttp = config['allowInsecureHttp'] === true;
53
71
  this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
54
72
  this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
55
73
  this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
@@ -65,8 +83,12 @@ export class OpenRouterProvider extends LLMProvider {
65
83
  */
66
84
  public isFreeModel(modelId: string): boolean {
67
85
  const clean = (modelId || '').trim().toLowerCase();
86
+ if (!clean || /[\s?#\x00-\x1f]/.test(clean)) return false;
68
87
  if (clean === 'openrouter/free' || clean === 'free') return true;
69
- if (clean.endsWith(':free')) return true;
88
+ if (clean.endsWith(':free')) {
89
+ const slug = clean.slice(0, -5);
90
+ return slug.length > 0 && !slug.startsWith('/') && !slug.endsWith('/');
91
+ }
70
92
  return false;
71
93
  }
72
94
 
@@ -89,7 +111,7 @@ export class OpenRouterProvider extends LLMProvider {
89
111
  this.assertFreeModel(this.model);
90
112
  }
91
113
 
92
- const apiKey = this.apiKey || process.env.OPENROUTER_API_KEY;
114
+ const apiKey = String(this.apiKey || process.env.OPENROUTER_API_KEY || '').trim();
93
115
  if (!apiKey) {
94
116
  throw new Error(
95
117
  'OpenRouter API key is required. Run /openrouter connect or /setup to connect your OpenRouter account.'
@@ -97,18 +119,23 @@ export class OpenRouterProvider extends LLMProvider {
97
119
  }
98
120
 
99
121
  const preparedMessages = this.prepareMessages(messages);
100
- const shouldStream = typeof options.onChunk === 'function';
122
+ const shouldStream = wantsStreaming(options);
101
123
 
102
124
  const payload: Record<string, any> = {
103
125
  model: this.model,
104
126
  messages: preparedMessages,
105
- temperature: options.temperature ?? 0.1,
127
+ temperature: resolveTemperature(options.temperature, 0.1),
106
128
  stream: shouldStream,
129
+ ...(shouldStream ? { stream_options: { include_usage: true } } : {}),
107
130
  provider: {
108
131
  data_collection: this.dataCollection
109
132
  }
110
133
  };
111
134
 
135
+ if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
136
+ payload['max_tokens'] = Math.floor(options.maxTokens);
137
+ }
138
+
112
139
  if (options['jsonMode']) {
113
140
  payload['response_format'] = { type: 'json_object' };
114
141
  }
@@ -128,45 +155,61 @@ export class OpenRouterProvider extends LLMProvider {
128
155
  'X-Title': 'Causyne Agent'
129
156
  };
130
157
 
131
- let response: Response;
132
158
  const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
133
- const fetchInit: RequestInit = {
159
+ const { response, cleanup } = await safeProviderFetch({
160
+ url: endpoint,
134
161
  method: 'POST',
135
162
  headers,
136
- body: JSON.stringify(payload)
137
- };
138
- if (options.signal) {
139
- fetchInit.signal = options.signal;
140
- }
163
+ body: JSON.stringify(payload),
164
+ signal: options.signal,
165
+ timeoutMs: typeof options['timeoutMs'] === 'number' ? options['timeoutMs'] : undefined,
166
+ providerLabel: 'OpenRouter',
167
+ secrets: [apiKey],
168
+ hasApiKey: true,
169
+ allowInsecureHttp: this.allowInsecureHttp
170
+ });
141
171
 
142
172
  try {
143
- response = await fetch(endpoint, fetchInit);
144
- } catch (err: any) {
145
- if (err?.name === 'AbortError' || options.signal?.aborted) {
146
- throw err;
173
+ if (!response.ok) {
174
+ const rawError = await readBoundedResponseText(response, MAX_PROVIDER_ERROR_BYTES, {
175
+ truncate: true,
176
+ label: 'OpenRouter'
177
+ }).catch(() => '');
178
+ const cleanError = redactProviderSecrets(rawError, [apiKey]);
179
+ const retryAfterHeader = (response as unknown as { headers?: { get?: (k: string) => string | null } }).headers?.get?.('retry-after');
180
+ const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
181
+ this.handleHttpErrors(response.status, cleanError, retryAfterMs);
147
182
  }
148
- throw new Error(`OpenRouter network connection error: ${err?.message || err}`);
149
- }
150
-
151
- if (!response.ok) {
152
- const errorText = await response.text().catch(() => '');
153
- this.handleHttpErrors(response.status, errorText);
154
- }
155
183
 
156
- if (shouldStream && response.body) {
157
- return this.handleStreamingResponse(response, options, freeFormPaths);
158
- } else {
159
- return this.handleJsonResponse(response, freeFormPaths);
184
+ const contentType = ((response as unknown as { headers?: { get?: (k: string) => string | null } }).headers?.get?.('content-type') ?? '')
185
+ .split(';')[0]?.trim().toLowerCase() ?? '';
186
+ const isJsonReply = contentType === 'application/json' || contentType.endsWith('+json');
187
+ if (shouldStream && response.body && !isJsonReply) {
188
+ return await this.handleStreamingResponse(response, options, freeFormPaths, apiKey);
189
+ } else {
190
+ const res = await this.handleJsonResponse(response, freeFormPaths, apiKey);
191
+ if (shouldStream) {
192
+ if (res.reasoningContent) options.onReasoningChunk?.(res.reasoningContent);
193
+ if (res.content) options.onChunk?.(res.content);
194
+ }
195
+ return res;
196
+ }
197
+ } finally {
198
+ cleanup();
160
199
  }
161
200
  }
162
201
 
163
202
  /**
164
203
  * Map HTTP error codes into user-friendly and security-preserving exceptions.
165
204
  */
166
- private handleHttpErrors(status: number, errorText: string): never {
205
+ private handleHttpErrors(status: number, errorText: string, retryAfterMs?: number): never {
167
206
  if (status === 429) {
207
+ const retryNote = retryAfterMs !== undefined
208
+ ? ` Retry after ${Math.ceil(retryAfterMs / 1000)}s.`
209
+ : '';
168
210
  throw new OpenRouterRateLimitError(
169
- 'OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.'
211
+ `OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.${retryNote}`,
212
+ retryAfterMs
170
213
  );
171
214
  }
172
215
 
@@ -181,12 +224,13 @@ export class OpenRouterProvider extends LLMProvider {
181
224
  }
182
225
  if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
183
226
  throw new OpenRouterRateLimitError(
184
- 'OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.'
227
+ 'OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.',
228
+ retryAfterMs
185
229
  );
186
230
  }
187
231
  }
188
232
 
189
- throw new Error(`OpenRouter API Error (${status}): ${errorText}`);
233
+ throw new ProviderHttpError(`OpenRouter API Error (${status}): ${errorText}`, { status, retryAfterMs });
190
234
  }
191
235
 
192
236
  /**
@@ -194,9 +238,31 @@ export class OpenRouterProvider extends LLMProvider {
194
238
  */
195
239
  private async handleJsonResponse(
196
240
  response: Response,
197
- freeFormPaths?: Map<string, string[][]>
241
+ freeFormPaths?: Map<string, string[][]>,
242
+ apiKey?: string
198
243
  ): Promise<ChatResponse> {
199
- const data = (await response.json()) as any;
244
+ let data: any;
245
+ if (!response.body && typeof response.text !== 'function' && typeof response.json === 'function') {
246
+ data = await response.json();
247
+ } else {
248
+ const rawText = await readBoundedResponseText(response, MAX_PROVIDER_JSON_BYTES, {
249
+ truncate: false,
250
+ label: 'OpenRouter'
251
+ });
252
+ const cleanText = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
253
+ try {
254
+ data = JSON.parse(cleanText);
255
+ } catch {
256
+ const preview = redactProviderSecrets(rawText.slice(0, 240), [apiKey]);
257
+ throw new Error(`OpenRouter returned a non-JSON response (HTTP ${response.status}): ${preview}`);
258
+ }
259
+ }
260
+ if (data && typeof data === 'object' && data.error && typeof data.error === 'object') {
261
+ const rawErr = typeof data.error.message === 'string' ? data.error.message : JSON.stringify(data.error);
262
+ const cleanErr = redactProviderSecrets(rawErr, [apiKey]);
263
+ const code = typeof data.error.code === 'number' ? data.error.code : 502;
264
+ this.handleHttpErrors(code, cleanErr);
265
+ }
200
266
  const normalized = normalizeOpenAIChatChoiceResponse(data, {
201
267
  prefix: 'call_openrouter',
202
268
  ...(freeFormPaths ? { freeFormPaths } : {})
@@ -217,7 +283,8 @@ export class OpenRouterProvider extends LLMProvider {
217
283
  private async handleStreamingResponse(
218
284
  response: Response,
219
285
  options: ChatOptions,
220
- freeFormPaths?: Map<string, string[][]>
286
+ freeFormPaths?: Map<string, string[][]>,
287
+ apiKey?: string
221
288
  ): Promise<ChatResponse> {
222
289
  const reader = response.body!.getReader();
223
290
  const decoder = new TextDecoder('utf-8');
@@ -225,79 +292,114 @@ export class OpenRouterProvider extends LLMProvider {
225
292
  let content = '';
226
293
  let reasoningContent = '';
227
294
  let buffer = '';
295
+ let totalBytes = 0;
228
296
  const toolCallsMap = new Map<number, { id: string; name: string; arguments: string }>();
229
297
  let rawUsage: any = null;
230
298
 
299
+ const processLine = (line: string): void => {
300
+ const stripped = line.charCodeAt(0) === 0xfeff ? line.slice(1) : line;
301
+ const trimmed = stripped.trim();
302
+ if (!trimmed || trimmed.startsWith(':')) return; // Skip comments/keepalive
303
+ if (trimmed === 'data: [DONE]' || trimmed === 'data:[DONE]') return;
304
+
305
+ if (trimmed.startsWith('data:')) {
306
+ const jsonStr = trimmed.slice(5).replace(/^ /, '');
307
+ let parsed: any;
308
+ try {
309
+ parsed = JSON.parse(jsonStr);
310
+ } catch {
311
+ return;
312
+ }
313
+ if (!parsed || typeof parsed !== 'object') return;
314
+ if (parsed.error && typeof parsed.error === 'object') {
315
+ const rawErr = typeof parsed.error.message === 'string' ? parsed.error.message : JSON.stringify(parsed.error);
316
+ const cleanErr = redactProviderSecrets(rawErr, [apiKey]);
317
+ const code = typeof parsed.error.code === 'number' ? parsed.error.code : 502;
318
+ this.handleHttpErrors(code, cleanErr);
319
+ }
320
+
321
+ if (parsed.usage) {
322
+ rawUsage = parsed.usage;
323
+ }
324
+
325
+ const choice = parsed.choices?.[0];
326
+ if (!choice) return;
327
+
328
+ const delta = choice.delta;
329
+ if (delta) {
330
+ // 1. Text chunk
331
+ if (delta.content) {
332
+ content += delta.content;
333
+ if (options.onChunk) {
334
+ options.onChunk(delta.content);
335
+ }
336
+ }
337
+
338
+ // 2. Reasoning chunk
339
+ const reasoning = delta.reasoning || delta.reasoning_content;
340
+ if (reasoning) {
341
+ reasoningContent += reasoning;
342
+ if (options.onReasoningChunk) {
343
+ options.onReasoningChunk(reasoning);
344
+ }
345
+ }
346
+
347
+ // 3. Tool calls assembly
348
+ if (Array.isArray(delta.tool_calls)) {
349
+ for (const tc of delta.tool_calls) {
350
+ if (!tc || typeof tc !== 'object') continue;
351
+ const idx = typeof tc.index === 'number' && Number.isInteger(tc.index) && tc.index >= 0
352
+ ? tc.index
353
+ : Math.max(-1, ...toolCallsMap.keys()) + 1;
354
+ let existing = toolCallsMap.get(idx);
355
+ if (!existing) {
356
+ existing = { id: sanitizeProviderToolId(tc.id, 'call_openrouter', idx), name: '', arguments: '' };
357
+ toolCallsMap.set(idx, existing);
358
+ }
359
+ if (typeof tc.id === 'string' && tc.id) existing.id = sanitizeProviderToolId(tc.id, 'call_openrouter', idx);
360
+ if (typeof tc.function?.name === 'string') existing.name += tc.function.name;
361
+ if (typeof tc.function?.arguments === 'string') existing.arguments += tc.function.arguments;
362
+ }
363
+ }
364
+ }
365
+ }
366
+ };
367
+
231
368
  try {
232
369
  while (true) {
233
370
  if (options.signal?.aborted) {
234
371
  await reader.cancel().catch(() => {});
235
- break;
372
+ const abortErr = new Error('OpenRouter request aborted');
373
+ abortErr.name = 'AbortError';
374
+ throw abortErr;
236
375
  }
237
376
 
238
377
  const { done, value } = await reader.read();
239
378
  if (done) break;
379
+ if (!value) continue;
380
+
381
+ totalBytes += value.byteLength;
382
+ if (totalBytes > MAX_PROVIDER_JSON_BYTES) {
383
+ await reader.cancel().catch(() => {});
384
+ throw new Error(`OpenRouter stream exceeded maximum allowed size (${MAX_PROVIDER_JSON_BYTES} bytes).`);
385
+ }
240
386
 
241
387
  buffer += decoder.decode(value, { stream: true });
388
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
389
+ await reader.cancel().catch(() => {});
390
+ throw new Error(`OpenRouter SSE buffer exceeded maximum allowed size (${MAX_SSE_BUFFER_BYTES} bytes).`);
391
+ }
242
392
  const lines = buffer.split('\n');
243
393
  buffer = lines.pop() || '';
244
394
 
245
395
  for (const line of lines) {
246
- const trimmed = line.trim();
247
- if (!trimmed || trimmed.startsWith(':')) continue; // Skip comments/keepalive
248
- if (trimmed === 'data: [DONE]') continue;
249
-
250
- if (trimmed.startsWith('data: ')) {
251
- const jsonStr = trimmed.slice(6);
252
- let parsed: any;
253
- try {
254
- parsed = JSON.parse(jsonStr);
255
- } catch {
256
- continue;
257
- }
258
-
259
- if (parsed.usage) {
260
- rawUsage = parsed.usage;
261
- }
262
-
263
- const choice = parsed.choices?.[0];
264
- if (!choice) continue;
265
-
266
- const delta = choice.delta;
267
- if (delta) {
268
- // 1. Text chunk
269
- if (delta.content) {
270
- content += delta.content;
271
- if (options.onChunk) {
272
- options.onChunk(delta.content);
273
- }
274
- }
275
-
276
- // 2. Reasoning chunk
277
- const reasoning = delta.reasoning || delta.reasoning_content;
278
- if (reasoning) {
279
- reasoningContent += reasoning;
280
- if (options.onReasoningChunk) {
281
- options.onReasoningChunk(reasoning);
282
- }
283
- }
284
-
285
- // 3. Tool calls assembly
286
- if (Array.isArray(delta.tool_calls)) {
287
- for (const tc of delta.tool_calls) {
288
- const idx = typeof tc.index === 'number' ? tc.index : toolCallsMap.size;
289
- let existing = toolCallsMap.get(idx);
290
- if (!existing) {
291
- existing = { id: tc.id || `call_${idx}_${Date.now()}`, name: '', arguments: '' };
292
- toolCallsMap.set(idx, existing);
293
- }
294
- if (tc.id) existing.id = tc.id;
295
- if (tc.function?.name) existing.name += tc.function.name;
296
- if (tc.function?.arguments) existing.arguments += tc.function.arguments;
297
- }
298
- }
299
- }
300
- }
396
+ processLine(line);
397
+ }
398
+ }
399
+ buffer += decoder.decode();
400
+ if (buffer.trim()) {
401
+ for (const line of buffer.split('\n')) {
402
+ processLine(line);
301
403
  }
302
404
  }
303
405
  } finally {
@@ -305,11 +407,13 @@ export class OpenRouterProvider extends LLMProvider {
305
407
  }
306
408
 
307
409
  const toolCalls: ChatResponseToolCall[] = [];
308
- for (const item of toolCallsMap.values()) {
410
+ const sortedItems = [...toolCallsMap.entries()].sort((a, b) => a[0] - b[0]);
411
+ for (const [idx, item] of sortedItems) {
309
412
  if (item.name) {
310
413
  const cleanName = normalizeToolName(item.name);
414
+ if (!cleanName) continue;
311
415
  toolCalls.push({
312
- id: item.id,
416
+ id: sanitizeProviderToolId(item.id, 'call_openrouter', idx),
313
417
  type: 'function',
314
418
  function: {
315
419
  name: cleanName,
@@ -320,9 +424,10 @@ export class OpenRouterProvider extends LLMProvider {
320
424
  }
321
425
 
322
426
  if (toolCalls.length === 0 && content) {
323
- const extracted = extractTextToolCalls(content, 'call_text', freeFormPaths);
427
+ const extracted = extractTextToolCalls(content, 'call_openrouter_text', freeFormPaths);
324
428
  if (extracted.length > 0) {
325
429
  toolCalls.push(...extracted);
430
+ content = stripToolCallMarkup(content).trim();
326
431
  }
327
432
  }
328
433
 
@@ -29,6 +29,12 @@ export class PiProvider extends LLMProvider {
29
29
  const prompt = this.formatter.formatConversation(messages, options.tools || [])
30
30
  .replace('over ACP.', 'over Pi RPC.');
31
31
  return new Promise((resolve, reject) => {
32
+ if (options.signal?.aborted) {
33
+ const err = new Error('Pi request aborted');
34
+ err.name = 'AbortError';
35
+ reject(err);
36
+ return;
37
+ }
32
38
  const child = spawn(this.command, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'],
33
39
  env: process.env, shell: false });
34
40
  let buffer = '';
@@ -34,6 +34,12 @@ export class PiProvider extends LLMProvider {
34
34
  .replace('over ACP.', 'over Pi RPC.');
35
35
 
36
36
  return new Promise<ChatResponse>((resolve, reject) => {
37
+ if (options.signal?.aborted) {
38
+ const err = new Error('Pi request aborted');
39
+ err.name = 'AbortError';
40
+ reject(err);
41
+ return;
42
+ }
37
43
  const child = spawn(this.command, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'],
38
44
  env: process.env, shell: false });
39
45
  let buffer = '';
@@ -3,79 +3,105 @@ 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
-
7
- // Direct DashScope API connection for BYOK (unlike dashscope.js which is the proxy for Free Demo)
6
+ import { requireApiKey, resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
7
+ import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
8
8
  export class QwenByokProvider extends LLMProvider {
9
- constructor(config) {
10
- super(config);
11
- // Use International/Singapore endpoint by default, allow override via config
12
- let url = config.baseUrl || 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
13
- if (url.endsWith('/v1')) url += '/chat/completions';
14
- else if (url.endsWith('/v1/')) url += 'chat/completions';
15
-
16
- this.baseUrl = url;
17
- this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['qwen']);
18
- this.apiKey = config.apiKey;
19
- this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7'];
20
- // Qwen exposes audio on the omni and dedicated audio families only; the
21
- // -vl- vision models are image-in, text-out and reject an audio block.
22
- this.audioModels = ['-omni', 'qwen-audio', 'qwen2-audio'];
23
- }
24
-
25
- async chat(messages, options = {}) {
26
- const sanitizedMessages = this.prepareMessages(messages);
27
-
28
- const payload = {
29
- model: this.model,
30
- messages: sanitizedMessages,
31
- temperature: options.temperature || 0.1,
32
- };
33
-
34
- if (options.jsonMode) {
35
- payload.response_format = { type: 'json_object' };
36
- }
37
-
38
- let freeFormPaths = new Map();
39
- if (options.tools && options.tools.length > 0) {
40
- const scanReport = scanAndAdaptToolsForProvider(options.tools, 'qwen');
41
- payload.tools = scanReport.adaptedTools;
42
- payload.tool_choice = "auto";
43
- freeFormPaths = scanReport.freeFormPaths;
9
+ allowInsecureHttp;
10
+ constructor(config = {}) {
11
+ super(config);
12
+ let url = (typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '') || 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
13
+ try {
14
+ const parsed = new URL(url);
15
+ if (parsed.pathname.endsWith('/v1')) {
16
+ parsed.pathname += '/chat/completions';
17
+ url = parsed.toString();
18
+ }
19
+ else if (parsed.pathname.endsWith('/v1/')) {
20
+ parsed.pathname += 'chat/completions';
21
+ url = parsed.toString();
22
+ }
23
+ }
24
+ catch {
25
+ if (url.endsWith('/v1'))
26
+ url += '/chat/completions';
27
+ else if (url.endsWith('/v1/'))
28
+ url += 'chat/completions';
29
+ }
30
+ this.baseUrl = url;
31
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
32
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['qwen']) || '');
33
+ this.apiKey = config.apiKey;
34
+ this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7'];
35
+ this.audioModels = ['-omni', 'qwen-audio', 'qwen2-audio'];
44
36
  }
45
-
46
- const response = await fetch(this.baseUrl, {
47
- method: 'POST',
48
- headers: {
49
- 'Content-Type': 'application/json',
50
- 'Authorization': `Bearer ${this.apiKey}`
51
- },
52
- body: JSON.stringify(payload)
53
- });
54
-
55
- if (!response.ok) {
56
- const errorData = await response.text();
57
-
58
- // Enterprise Error Handling: Detect Workspace-bound API Key configuration errors
59
- if (response.status === 401 && this.apiKey && this.apiKey.startsWith('sk-ws-')) {
60
- if (!this.baseUrl.includes('ws-')) {
61
- throw new Error(`\n[QWEN WORKSPACE CONFIGURATION ERROR]\n\nYou are using a Workspace-bound API Key (starts with sk-ws-), but you haven't configured your Workspace Base URL!\n\nAlibaba requires a specific URL for these keys.\n\nHOW TO FIX THIS:\n1. Open your computer terminal.\n2. Run command: causyne-agent config\n3. When asked for 'Custom Base URL', paste your Workspace URL from Alibaba (e.g. https://{Your-Workspace-ID}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions).\n\nAlternatively, use a Standard API Key (starts with sk-) which does not require a custom URL.`);
37
+ async chat(messages, options = {}) {
38
+ const apiKey = requireApiKey(this.apiKey, 'Qwen DashScope');
39
+ const sanitizedMessages = this.prepareMessages(messages);
40
+ const payload = {
41
+ model: this.model,
42
+ messages: sanitizedMessages,
43
+ temperature: resolveTemperature(options.temperature, 0.1)
44
+ };
45
+ if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
46
+ payload['max_tokens'] = Math.floor(options.maxTokens);
47
+ }
48
+ if (options.jsonMode) {
49
+ payload['response_format'] = { type: 'json_object' };
50
+ }
51
+ let freeFormPaths = new Map();
52
+ if (options.tools && options.tools.length > 0) {
53
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'qwen');
54
+ payload['tools'] = scanReport.adaptedTools;
55
+ payload['tool_choice'] = 'auto';
56
+ freeFormPaths = scanReport.freeFormPaths;
62
57
  }
63
- }
64
-
65
- throw new Error(`Qwen DashScope API Error (${response.status}): ${errorData}`);
58
+ const endpoint = this.baseUrl || 'https://dashscope-intl.aliyuncs.com/compatible-mode/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: 'Qwen DashScope',
69
+ secrets: [apiKey],
70
+ hasApiKey: true,
71
+ allowInsecureHttp: this.allowInsecureHttp,
72
+ onHttpError: ({ status }) => {
73
+ let hostHasWorkspace = false;
74
+ try {
75
+ hostHasWorkspace = new URL(endpoint).hostname.includes('ws-');
76
+ }
77
+ catch {
78
+ hostHasWorkspace = false;
79
+ }
80
+ if (status === 401 && apiKey.startsWith('sk-ws-') && !hostHasWorkspace) {
81
+ throw new Error('\n[QWEN WORKSPACE CONFIGURATION ERROR]\n\nYou are using a Workspace-bound API Key (starts with sk-ws-), but you have not configured your Workspace Base URL.\n\nAlibaba requires a specific URL for these keys.\n\nHOW TO FIX THIS:\n1. Open your computer terminal.\n2. Run command: causyne config\n3. When asked for Custom Base URL, paste your Workspace URL from Alibaba (e.g. https://{Your-Workspace-ID}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions).\n\nAlternatively, use a Standard API Key (starts with sk-) which does not require a custom URL.');
82
+ }
83
+ }
84
+ };
85
+ const data = wantsStreaming(options)
86
+ ? await streamOpenAICompatibleChat({
87
+ ...requestOpts,
88
+ payload,
89
+ onChunk: options.onChunk,
90
+ onReasoningChunk: options.onReasoningChunk
91
+ })
92
+ : await safeProviderFetchJson({
93
+ ...requestOpts,
94
+ body: JSON.stringify(payload)
95
+ });
96
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
97
+ prefix: 'call_qwen',
98
+ freeFormPaths
99
+ });
100
+ return {
101
+ content: normalized.content,
102
+ toolCalls: normalized.toolCalls,
103
+ reasoningContent: normalized.reasoningContent,
104
+ usage: this.normalizeUsage(normalized.rawUsage)
105
+ };
66
106
  }
67
-
68
- const data = await response.json();
69
- const normalized = normalizeOpenAIChatChoiceResponse(data, {
70
- prefix: 'call_qwen',
71
- freeFormPaths
72
- });
73
-
74
- return {
75
- content: normalized.content,
76
- toolCalls: normalized.toolCalls,
77
- reasoningContent: normalized.reasoningContent,
78
- usage: this.normalizeUsage(normalized.rawUsage)
79
- };
80
- }
81
107
  }