@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
@@ -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,96 +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
- 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
- // Direct DashScope API connection for BYOK (unlike dashscope.js which is the proxy for Free Demo)
14
8
  export class QwenByokProvider extends LLMProvider {
15
- constructor(config) {
16
- super(config);
17
- // Use International/Singapore endpoint by default, allow override via config
18
- let url = config.baseUrl || 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
19
- if (url.endsWith('/v1')) url += '/chat/completions';
20
- else if (url.endsWith('/v1/')) url += 'chat/completions';
21
-
22
- this.baseUrl = url;
23
- this.allowInsecureHttp = config.allowInsecureHttp === true;
24
- this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['qwen']);
25
- this.apiKey = config.apiKey;
26
- this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7'];
27
- // Qwen exposes audio on the omni and dedicated audio families only; the
28
- // -vl- vision models are image-in, text-out and reject an audio block.
29
- this.audioModels = ['-omni', 'qwen-audio', 'qwen2-audio'];
30
- }
31
-
32
- async chat(messages, options = {}) {
33
- const apiKey = requireApiKey(this.apiKey, 'Qwen DashScope');
34
- const sanitizedMessages = this.prepareMessages(messages);
35
-
36
- const payload = {
37
- model: this.model,
38
- messages: sanitizedMessages,
39
- temperature: resolveTemperature(options.temperature, 0.1),
40
- };
41
-
42
- if (options.jsonMode) {
43
- payload.response_format = { type: 'json_object' };
44
- }
45
-
46
- let freeFormPaths = new Map();
47
- if (options.tools && options.tools.length > 0) {
48
- const scanReport = scanAndAdaptToolsForProvider(options.tools, 'qwen');
49
- payload.tools = scanReport.adaptedTools;
50
- payload.tool_choice = "auto";
51
- 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'];
52
36
  }
53
-
54
- const requestOpts = {
55
- url: this.baseUrl,
56
- method: 'POST',
57
- headers: {
58
- 'Content-Type': 'application/json',
59
- 'Authorization': `Bearer ${apiKey}`
60
- },
61
- signal: options.signal,
62
- timeoutMs: options.timeoutMs,
63
- providerLabel: 'Qwen DashScope',
64
- secrets: [apiKey],
65
- hasApiKey: true,
66
- allowInsecureHttp: this.allowInsecureHttp,
67
- onHttpError: ({ status }) => {
68
- // Enterprise Error Handling: Detect Workspace-bound API Key configuration errors
69
- if (status === 401 && apiKey.startsWith('sk-ws-') && !this.baseUrl.includes('ws-')) {
70
- 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);
71
47
  }
72
- }
73
- };
74
-
75
- const data = wantsStreaming(options)
76
- ? await streamOpenAICompatibleChat({
77
- ...requestOpts,
78
- payload,
79
- onChunk: options.onChunk,
80
- onReasoningChunk: options.onReasoningChunk
81
- })
82
- : await safeProviderFetchJson({
83
- ...requestOpts,
84
- body: JSON.stringify(payload)
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;
57
+ }
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
85
99
  });
86
- const normalized = normalizeOpenAIChatChoiceResponse(data, {
87
- prefix: 'call_qwen',
88
- freeFormPaths
89
- });
90
-
91
- return {
92
- content: normalized.content,
93
- toolCalls: normalized.toolCalls,
94
- reasoningContent: normalized.reasoningContent,
95
- usage: this.normalizeUsage(normalized.rawUsage)
96
- };
97
- }
100
+ return {
101
+ content: normalized.content,
102
+ toolCalls: normalized.toolCalls,
103
+ reasoningContent: normalized.reasoningContent,
104
+ usage: this.normalizeUsage(normalized.rawUsage)
105
+ };
106
+ }
98
107
  }
@@ -0,0 +1,113 @@
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 QwenByokProvider extends LLMProvider {
14
+ allowInsecureHttp: boolean;
15
+
16
+ constructor(config: ProviderConfig = {}) {
17
+ super(config);
18
+ let url = (typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '') || 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
19
+ try {
20
+ const parsed = new URL(url);
21
+ if (parsed.pathname.endsWith('/v1')) {
22
+ parsed.pathname += '/chat/completions';
23
+ url = parsed.toString();
24
+ } else if (parsed.pathname.endsWith('/v1/')) {
25
+ parsed.pathname += 'chat/completions';
26
+ url = parsed.toString();
27
+ }
28
+ } catch {
29
+ if (url.endsWith('/v1')) url += '/chat/completions';
30
+ else if (url.endsWith('/v1/')) url += 'chat/completions';
31
+ }
32
+
33
+ this.baseUrl = url;
34
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
35
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['qwen']) || '');
36
+ this.apiKey = config.apiKey;
37
+ this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7'];
38
+ this.audioModels = ['-omni', 'qwen-audio', 'qwen2-audio'];
39
+ }
40
+
41
+ override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
42
+ const apiKey = requireApiKey(this.apiKey, 'Qwen DashScope');
43
+ const sanitizedMessages = this.prepareMessages(messages);
44
+
45
+ const payload: Record<string, any> = {
46
+ model: this.model,
47
+ messages: sanitizedMessages,
48
+ temperature: resolveTemperature(options.temperature, 0.1)
49
+ };
50
+
51
+ if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
52
+ payload['max_tokens'] = Math.floor(options.maxTokens);
53
+ }
54
+
55
+ if (options.jsonMode) {
56
+ payload['response_format'] = { type: 'json_object' };
57
+ }
58
+
59
+ let freeFormPaths = new Map<string, string[][]>();
60
+ if (options.tools && options.tools.length > 0) {
61
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'qwen');
62
+ payload['tools'] = scanReport.adaptedTools;
63
+ payload['tool_choice'] = 'auto';
64
+ freeFormPaths = scanReport.freeFormPaths;
65
+ }
66
+
67
+ const endpoint = this.baseUrl || 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
68
+ const requestOpts = {
69
+ url: endpoint,
70
+ method: 'POST',
71
+ headers: {
72
+ 'Content-Type': 'application/json',
73
+ 'Authorization': `Bearer ${apiKey}`
74
+ },
75
+ signal: options.signal,
76
+ timeoutMs: options.timeoutMs,
77
+ providerLabel: 'Qwen DashScope',
78
+ secrets: [apiKey],
79
+ hasApiKey: true,
80
+ allowInsecureHttp: this.allowInsecureHttp,
81
+ onHttpError: ({ status }: { status: number }) => {
82
+ let hostHasWorkspace = false;
83
+ try { hostHasWorkspace = new URL(endpoint).hostname.includes('ws-'); } catch { hostHasWorkspace = false; }
84
+ if (status === 401 && apiKey.startsWith('sk-ws-') && !hostHasWorkspace) {
85
+ 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.');
86
+ }
87
+ }
88
+ };
89
+
90
+ const data = wantsStreaming(options)
91
+ ? await streamOpenAICompatibleChat({
92
+ ...requestOpts,
93
+ payload,
94
+ onChunk: options.onChunk,
95
+ onReasoningChunk: options.onReasoningChunk
96
+ })
97
+ : await safeProviderFetchJson({
98
+ ...requestOpts,
99
+ body: JSON.stringify(payload)
100
+ });
101
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
102
+ prefix: 'call_qwen',
103
+ freeFormPaths
104
+ });
105
+
106
+ return {
107
+ content: normalized.content,
108
+ toolCalls: normalized.toolCalls,
109
+ reasoningContent: normalized.reasoningContent,
110
+ usage: this.normalizeUsage(normalized.rawUsage)
111
+ };
112
+ }
113
+ }
@@ -3,27 +3,52 @@ import { normalizeToolName, normalizeUniversalSchema } from '../tools/toolScanne
3
3
  const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
4
4
  /** Preserve constraints and nested schemas while compiling union/combinator edge cases safely. */
5
5
  export function normalizeToolContracts(tools) {
6
- return tools.map(raw => {
6
+ if (!Array.isArray(tools))
7
+ return [];
8
+ const byName = new Map();
9
+ for (const raw of tools) {
7
10
  const tool = object(raw);
8
11
  const fn = object(tool.function);
9
- const rawName = String(tool.name || fn.name || '');
12
+ const rawName = typeof tool.name === 'string' ? tool.name : (typeof fn.name === 'string' ? fn.name : '');
13
+ const name = rawName.trim() ? normalizeToolName(rawName.trim()) : '';
14
+ if (!name)
15
+ continue;
16
+ const rawDesc = typeof tool.description === 'string' ? tool.description : (typeof fn.description === 'string' ? fn.description : '');
10
17
  const rawParams = object(tool.parameters || tool.input_schema || fn.parameters);
11
18
  const cleanParams = Object.keys(rawParams).length > 0
12
19
  ? object(normalizeUniversalSchema(rawParams, [], [], 'strict_json'))
13
20
  : rawParams;
14
- return {
15
- name: rawName ? normalizeToolName(rawName) : '',
16
- description: String(tool.description || fn.description || ''),
21
+ byName.set(name, {
22
+ name,
23
+ description: rawDesc,
17
24
  parameters: cleanParams
18
- };
19
- }).filter(tool => tool.name).sort((a, b) => a.name.localeCompare(b.name));
25
+ });
26
+ }
27
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
20
28
  }
21
29
  export function contractFingerprint(value) {
22
- const stable = (item) => Array.isArray(item) ? item.map(stable)
23
- : item !== null && typeof item === 'object'
24
- ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b)).map(([key, val]) => [key, stable(val)]))
25
- : item;
26
- return createHash('sha256').update(JSON.stringify(stable(value))).digest('hex');
30
+ const seen = new WeakSet();
31
+ const stable = (item) => {
32
+ if (typeof item === 'bigint')
33
+ return item.toString();
34
+ if (item === null || typeof item !== 'object')
35
+ return item;
36
+ if (seen.has(item))
37
+ return '[Circular]';
38
+ seen.add(item);
39
+ try {
40
+ if (Array.isArray(item))
41
+ return item.map(stable);
42
+ return Object.fromEntries(Object.entries(item)
43
+ .sort(([a], [b]) => a.localeCompare(b))
44
+ .map(([key, val]) => [key, stable(val)]));
45
+ }
46
+ finally {
47
+ seen.delete(item);
48
+ }
49
+ };
50
+ const serialized = JSON.stringify(stable(value)) ?? 'undefined';
51
+ return createHash('sha256').update(serialized).digest('hex');
27
52
  }
28
53
  export function formatToolContracts(tools) {
29
54
  return normalizeToolContracts(tools).map(tool => JSON.stringify(tool)).join('\n');
@@ -31,9 +56,10 @@ export function formatToolContracts(tools) {
31
56
  /** Current allowlist plus only changed contracts, for peers retaining their own history. */
32
57
  export function toolContractUpdate(tools, previous) {
33
58
  const current = normalizeToolContracts(tools);
34
- const before = new Map(normalizeToolContracts(previous).map(tool => [tool.name, contractFingerprint(tool)]));
35
- if (contractFingerprint(current) === contractFingerprint(normalizeToolContracts(previous)))
59
+ const prevNormalized = normalizeToolContracts(previous);
60
+ if (contractFingerprint(current) === contractFingerprint(prevNormalized))
36
61
  return '';
62
+ const before = new Map(prevNormalized.map(tool => [tool.name, contractFingerprint(tool)]));
37
63
  const changed = current.filter(tool => before.get(tool.name) !== contractFingerprint(tool));
38
64
  return '[Current Causyne tools — replaces the prior host allowlist only; peer-native tools remain available]\n'
39
65
  + JSON.stringify(current.map(tool => tool.name))
@@ -13,28 +13,48 @@ const object = (value: unknown): JsonObject =>
13
13
 
14
14
  /** Preserve constraints and nested schemas while compiling union/combinator edge cases safely. */
15
15
  export function normalizeToolContracts(tools: readonly unknown[]): ToolContract[] {
16
- return tools.map(raw => {
16
+ if (!Array.isArray(tools)) return [];
17
+ const byName = new Map<string, ToolContract>();
18
+ for (const raw of tools) {
17
19
  const tool = object(raw);
18
20
  const fn = object(tool.function);
19
- const rawName = String(tool.name || fn.name || '');
21
+ const rawName = typeof tool.name === 'string' ? tool.name : (typeof fn.name === 'string' ? fn.name : '');
22
+ const name = rawName.trim() ? normalizeToolName(rawName.trim()) : '';
23
+ if (!name) continue;
24
+ const rawDesc = typeof tool.description === 'string' ? tool.description : (typeof fn.description === 'string' ? fn.description : '');
20
25
  const rawParams = object(tool.parameters || tool.input_schema || fn.parameters);
21
26
  const cleanParams = Object.keys(rawParams).length > 0
22
27
  ? object(normalizeUniversalSchema(rawParams, [], [], 'strict_json'))
23
28
  : rawParams;
24
- return {
25
- name: rawName ? normalizeToolName(rawName) : '',
26
- description: String(tool.description || fn.description || ''),
29
+ byName.set(name, {
30
+ name,
31
+ description: rawDesc,
27
32
  parameters: cleanParams
28
- };
29
- }).filter(tool => tool.name).sort((a, b) => a.name.localeCompare(b.name));
33
+ });
34
+ }
35
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
30
36
  }
31
37
 
32
38
  export function contractFingerprint(value: unknown): string {
33
- const stable = (item: unknown): unknown => Array.isArray(item) ? item.map(stable)
34
- : item !== null && typeof item === 'object'
35
- ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b)).map(([key, val]) => [key, stable(val)]))
36
- : item;
37
- return createHash('sha256').update(JSON.stringify(stable(value))).digest('hex');
39
+ const seen = new WeakSet<object>();
40
+ const stable = (item: unknown): unknown => {
41
+ if (typeof item === 'bigint') return item.toString();
42
+ if (item === null || typeof item !== 'object') return item;
43
+ if (seen.has(item)) return '[Circular]';
44
+ seen.add(item);
45
+ try {
46
+ if (Array.isArray(item)) return item.map(stable);
47
+ return Object.fromEntries(
48
+ Object.entries(item)
49
+ .sort(([a], [b]) => a.localeCompare(b))
50
+ .map(([key, val]) => [key, stable(val)])
51
+ );
52
+ } finally {
53
+ seen.delete(item);
54
+ }
55
+ };
56
+ const serialized = JSON.stringify(stable(value)) ?? 'undefined';
57
+ return createHash('sha256').update(serialized).digest('hex');
38
58
  }
39
59
 
40
60
  export function formatToolContracts(tools: readonly unknown[]): string {
@@ -44,8 +64,9 @@ export function formatToolContracts(tools: readonly unknown[]): string {
44
64
  /** Current allowlist plus only changed contracts, for peers retaining their own history. */
45
65
  export function toolContractUpdate(tools: readonly unknown[], previous: readonly unknown[]): string {
46
66
  const current = normalizeToolContracts(tools);
47
- const before = new Map(normalizeToolContracts(previous).map(tool => [tool.name, contractFingerprint(tool)]));
48
- if (contractFingerprint(current) === contractFingerprint(normalizeToolContracts(previous))) return '';
67
+ const prevNormalized = normalizeToolContracts(previous);
68
+ if (contractFingerprint(current) === contractFingerprint(prevNormalized)) return '';
69
+ const before = new Map(prevNormalized.map(tool => [tool.name, contractFingerprint(tool)]));
49
70
  const changed = current.filter(tool => before.get(tool.name) !== contractFingerprint(tool));
50
71
  return '[Current Causyne tools — replaces the prior host allowlist only; peer-native tools remain available]\n'
51
72
  + JSON.stringify(current.map(tool => tool.name))
@@ -9,6 +9,7 @@ import { normalizeToolName, decodeFreeFormArguments } from '../tools/toolScanner
9
9
  import { repairJsonArguments } from '../tools/toolSelfRepair.js';
10
10
  import { extractToolCallJsonObjects, resolveToolCallEnvelopeArguments, stripToolCallMarkup } from '../implementationPlan.js';
11
11
  const VALID_ID_CHARS = /[^a-zA-Z0-9_-]/g;
12
+ let toolIdSequence = 0;
12
13
  function isPlainObject(value) {
13
14
  return value !== null && typeof value === 'object' && !Array.isArray(value);
14
15
  }
@@ -47,7 +48,10 @@ export function sanitizeProviderToolId(rawId, prefix = 'call', index = 0) {
47
48
  : '';
48
49
  if (cleaned.length > 0)
49
50
  return cleaned.slice(0, 64);
50
- return `${prefix.replace(VALID_ID_CHARS, '_')}_${Date.now()}_${index}`.slice(0, 64);
51
+ const safePrefix = (typeof prefix === 'string' ? prefix.replace(VALID_ID_CHARS, '_') : '') || 'call';
52
+ const safeIndex = typeof index === 'number' && Number.isFinite(index) ? Math.max(0, Math.floor(index)) : 0;
53
+ toolIdSequence = (toolIdSequence + 1) % 100_000;
54
+ return `${safePrefix}_${Date.now()}_${safeIndex}_${toolIdSequence}`.slice(0, 64);
51
55
  }
52
56
  function resolveFreeFormPaths(toolName, freeFormPaths) {
53
57
  if (!freeFormPaths || freeFormPaths.size === 0)
@@ -57,18 +61,38 @@ function resolveFreeFormPaths(toolName, freeFormPaths) {
57
61
  /**
58
62
  * Serialize arguments cleanly to a JSON string while decoding any adapted free-form paths.
59
63
  */
64
+ function safeCloneObject(obj) {
65
+ try {
66
+ return structuredClone(obj);
67
+ }
68
+ catch {
69
+ try {
70
+ return JSON.parse(JSON.stringify(obj));
71
+ }
72
+ catch {
73
+ return { ...obj };
74
+ }
75
+ }
76
+ }
60
77
  export function serializeAndDecodeArguments(rawArgs, toolName, freeFormPaths) {
61
78
  const paths = resolveFreeFormPaths(toolName, freeFormPaths);
62
79
  if (typeof rawArgs === 'string') {
80
+ if (rawArgs.trim().length === 0)
81
+ return '{}';
63
82
  if (!paths || paths.length === 0)
64
83
  return rawArgs;
65
84
  const obj = safeParseJsonObject(rawArgs);
66
85
  if (Object.keys(obj).length === 0)
67
86
  return rawArgs;
68
- const decoded = decodeFreeFormArguments(structuredClone(obj), paths);
69
- return JSON.stringify(decoded);
87
+ const decoded = decodeFreeFormArguments(safeCloneObject(obj), paths);
88
+ try {
89
+ return JSON.stringify(decoded);
90
+ }
91
+ catch {
92
+ return rawArgs;
93
+ }
70
94
  }
71
- const obj = isPlainObject(rawArgs) ? structuredClone(rawArgs) : {};
95
+ const obj = isPlainObject(rawArgs) ? safeCloneObject(rawArgs) : {};
72
96
  const finalObj = paths && paths.length > 0 ? decodeFreeFormArguments(obj, paths) : obj;
73
97
  try {
74
98
  return JSON.stringify(finalObj);
@@ -85,15 +109,23 @@ export function extractTextToolCalls(text, prefix = 'call_text', freeFormPaths)
85
109
  if (!text || typeof text !== 'string')
86
110
  return calls;
87
111
  let index = 0;
112
+ const seenIds = new Set();
88
113
  for (const parsed of extractToolCallJsonObjects(text)) {
89
114
  const fnObj = isPlainObject(parsed['function']) ? parsed['function'] : null;
90
115
  const rawName = String(parsed['name'] || parsed['tool'] || fnObj?.['name'] || '').trim();
91
116
  if (!rawName)
92
117
  continue;
93
118
  const name = normalizeToolName(rawName);
119
+ if (!name)
120
+ continue;
94
121
  const rawArgs = resolveToolCallEnvelopeArguments(parsed);
122
+ let id = sanitizeProviderToolId(parsed['id'], prefix, index);
123
+ if (seenIds.has(id))
124
+ id = `${id.slice(0, 56)}_${index}`;
125
+ seenIds.add(id);
126
+ index++;
95
127
  calls.push({
96
- id: sanitizeProviderToolId(parsed['id'], prefix, index++),
128
+ id,
97
129
  type: 'function',
98
130
  function: {
99
131
  name,
@@ -110,6 +142,7 @@ export function normalizeOpenAIToolCalls(rawCalls, freeFormPaths, prefix = 'call
110
142
  if (!Array.isArray(rawCalls))
111
143
  return [];
112
144
  const normalized = [];
145
+ const seenIds = new Set();
113
146
  for (let i = 0; i < rawCalls.length; i++) {
114
147
  const tc = rawCalls[i];
115
148
  if (!isPlainObject(tc))
@@ -119,9 +152,15 @@ export function normalizeOpenAIToolCalls(rawCalls, freeFormPaths, prefix = 'call
119
152
  if (!rawName)
120
153
  continue;
121
154
  const name = normalizeToolName(rawName);
155
+ if (!name)
156
+ continue;
122
157
  const rawArgs = fnObj ? fnObj['arguments'] : tc['arguments'];
158
+ let id = sanitizeProviderToolId(tc['id'], prefix, i);
159
+ if (seenIds.has(id))
160
+ id = `${id.slice(0, 56)}_${i}`;
161
+ seenIds.add(id);
123
162
  normalized.push({
124
- id: sanitizeProviderToolId(tc['id'], prefix, i),
163
+ id,
125
164
  type: 'function',
126
165
  function: {
127
166
  name,
@@ -149,10 +188,26 @@ export function normalizeOpenAIChatChoiceResponse(data, options = {}) {
149
188
  const choice = isPlainObject(payload['choices'][0]) ? payload['choices'][0] : null;
150
189
  const message = choice && isPlainObject(choice['message']) ? choice['message'] : null;
151
190
  if (message) {
152
- content = typeof message['content'] === 'string' ? message['content'] : '';
191
+ if (typeof message['content'] === 'string') {
192
+ content = message['content'];
193
+ }
194
+ else if (Array.isArray(message['content'])) {
195
+ content = message['content']
196
+ .map((part) => (isPlainObject(part) && typeof part['text'] === 'string' ? part['text'] : ''))
197
+ .filter(Boolean)
198
+ .join('');
199
+ }
153
200
  rawToolCalls = message['tool_calls'];
154
- const rc = message['reasoning_content'] ?? message['reasoning'];
155
- reasoningContent = typeof rc === 'string' ? rc : '';
201
+ const rc = message['reasoning_content'] ?? message['reasoning'] ?? message['thinking'];
202
+ if (typeof rc === 'string') {
203
+ reasoningContent = rc;
204
+ }
205
+ else if (Array.isArray(message['reasoning_details'])) {
206
+ reasoningContent = message['reasoning_details']
207
+ .map((d) => (isPlainObject(d) ? (typeof d['text'] === 'string' ? d['text'] : (typeof d['summary'] === 'string' ? d['summary'] : '')) : ''))
208
+ .filter(Boolean)
209
+ .join('\n');
210
+ }
156
211
  }
157
212
  }
158
213
  let toolCalls = normalizeOpenAIToolCalls(rawToolCalls, options.freeFormPaths, prefix);
@@ -191,7 +246,7 @@ export function prepareMessagesForAnthropic(provider, messages) {
191
246
  if (!isPlainObject(msg))
192
247
  continue;
193
248
  if (msg['role'] === 'system') {
194
- const { spillPath: _spill, ...rest } = msg;
249
+ const { spillPath: _spill, thinking_blocks: _tb, reasoning_content: _rc, ...rest } = msg;
195
250
  prepared.push(rest);
196
251
  continue;
197
252
  }
@@ -213,7 +268,19 @@ export function normalizeMessagesForOllama(messages) {
213
268
  if (!Array.isArray(messages))
214
269
  return [];
215
270
  return messages.map((msg) => {
216
- if (!isPlainObject(msg) || msg['role'] !== 'assistant' || !Array.isArray(msg['tool_calls'])) {
271
+ if (!isPlainObject(msg))
272
+ return msg;
273
+ if (msg['role'] === 'tool' && typeof msg['content'] !== 'string') {
274
+ let str = '';
275
+ try {
276
+ str = msg['content'] == null ? '' : JSON.stringify(msg['content']);
277
+ }
278
+ catch {
279
+ str = String(msg['content'] ?? '');
280
+ }
281
+ return { ...msg, content: str };
282
+ }
283
+ if (msg['role'] !== 'assistant' || !Array.isArray(msg['tool_calls'])) {
217
284
  return msg;
218
285
  }
219
286
  return {