@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,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 {
@@ -16,7 +16,7 @@ import {
16
16
  resolveToolCallEnvelopeArguments,
17
17
  stripToolCallMarkup
18
18
  } from '../implementationPlan.js';
19
- import type { ChatResponseToolCall } from './base.d.js';
19
+ import type { ChatResponseToolCall } from './base.js';
20
20
 
21
21
  export interface NormalizedChoiceResult {
22
22
  content: string;
@@ -26,6 +26,7 @@ export interface NormalizedChoiceResult {
26
26
  }
27
27
 
28
28
  const VALID_ID_CHARS = /[^a-zA-Z0-9_-]/g;
29
+ let toolIdSequence = 0;
29
30
 
30
31
  function isPlainObject(value: unknown): value is Record<string, unknown> {
31
32
  return value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -61,7 +62,10 @@ export function sanitizeProviderToolId(rawId: unknown, prefix = 'call', index =
61
62
  ? rawId.trim().replace(VALID_ID_CHARS, '_')
62
63
  : '';
63
64
  if (cleaned.length > 0) return cleaned.slice(0, 64);
64
- return `${prefix.replace(VALID_ID_CHARS, '_')}_${Date.now()}_${index}`.slice(0, 64);
65
+ const safePrefix = (typeof prefix === 'string' ? prefix.replace(VALID_ID_CHARS, '_') : '') || 'call';
66
+ const safeIndex = typeof index === 'number' && Number.isFinite(index) ? Math.max(0, Math.floor(index)) : 0;
67
+ toolIdSequence = (toolIdSequence + 1) % 100_000;
68
+ return `${safePrefix}_${Date.now()}_${safeIndex}_${toolIdSequence}`.slice(0, 64);
65
69
  }
66
70
 
67
71
  function resolveFreeFormPaths(
@@ -75,6 +79,18 @@ function resolveFreeFormPaths(
75
79
  /**
76
80
  * Serialize arguments cleanly to a JSON string while decoding any adapted free-form paths.
77
81
  */
82
+ function safeCloneObject(obj: Record<string, unknown>): Record<string, unknown> {
83
+ try {
84
+ return structuredClone(obj);
85
+ } catch {
86
+ try {
87
+ return JSON.parse(JSON.stringify(obj)) as Record<string, unknown>;
88
+ } catch {
89
+ return { ...obj };
90
+ }
91
+ }
92
+ }
93
+
78
94
  export function serializeAndDecodeArguments(
79
95
  rawArgs: unknown,
80
96
  toolName: string,
@@ -82,13 +98,18 @@ export function serializeAndDecodeArguments(
82
98
  ): string {
83
99
  const paths = resolveFreeFormPaths(toolName, freeFormPaths);
84
100
  if (typeof rawArgs === 'string') {
101
+ if (rawArgs.trim().length === 0) return '{}';
85
102
  if (!paths || paths.length === 0) return rawArgs;
86
103
  const obj = safeParseJsonObject(rawArgs);
87
104
  if (Object.keys(obj).length === 0) return rawArgs;
88
- const decoded = decodeFreeFormArguments(structuredClone(obj), paths);
89
- return JSON.stringify(decoded);
105
+ const decoded = decodeFreeFormArguments(safeCloneObject(obj), paths);
106
+ try {
107
+ return JSON.stringify(decoded);
108
+ } catch {
109
+ return rawArgs;
110
+ }
90
111
  }
91
- const obj = isPlainObject(rawArgs) ? structuredClone(rawArgs) : {};
112
+ const obj = isPlainObject(rawArgs) ? safeCloneObject(rawArgs) : {};
92
113
  const finalObj = paths && paths.length > 0 ? decodeFreeFormArguments(obj, paths) : obj;
93
114
  try {
94
115
  return JSON.stringify(finalObj);
@@ -108,14 +129,20 @@ export function extractTextToolCalls(
108
129
  const calls: ChatResponseToolCall[] = [];
109
130
  if (!text || typeof text !== 'string') return calls;
110
131
  let index = 0;
132
+ const seenIds = new Set<string>();
111
133
  for (const parsed of extractToolCallJsonObjects(text)) {
112
134
  const fnObj = isPlainObject(parsed['function']) ? parsed['function'] : null;
113
135
  const rawName = String(parsed['name'] || parsed['tool'] || fnObj?.['name'] || '').trim();
114
136
  if (!rawName) continue;
115
137
  const name = normalizeToolName(rawName);
138
+ if (!name) continue;
116
139
  const rawArgs = resolveToolCallEnvelopeArguments(parsed);
140
+ let id = sanitizeProviderToolId(parsed['id'], prefix, index);
141
+ if (seenIds.has(id)) id = `${id.slice(0, 56)}_${index}`;
142
+ seenIds.add(id);
143
+ index++;
117
144
  calls.push({
118
- id: sanitizeProviderToolId(parsed['id'], prefix, index++),
145
+ id,
119
146
  type: 'function',
120
147
  function: {
121
148
  name,
@@ -136,6 +163,7 @@ export function normalizeOpenAIToolCalls(
136
163
  ): ChatResponseToolCall[] {
137
164
  if (!Array.isArray(rawCalls)) return [];
138
165
  const normalized: ChatResponseToolCall[] = [];
166
+ const seenIds = new Set<string>();
139
167
  for (let i = 0; i < rawCalls.length; i++) {
140
168
  const tc = rawCalls[i];
141
169
  if (!isPlainObject(tc)) continue;
@@ -143,9 +171,13 @@ export function normalizeOpenAIToolCalls(
143
171
  const rawName = String(fnObj?.['name'] || tc['name'] || '').trim();
144
172
  if (!rawName) continue;
145
173
  const name = normalizeToolName(rawName);
174
+ if (!name) continue;
146
175
  const rawArgs = fnObj ? fnObj['arguments'] : tc['arguments'];
176
+ let id = sanitizeProviderToolId(tc['id'], prefix, i);
177
+ if (seenIds.has(id)) id = `${id.slice(0, 56)}_${i}`;
178
+ seenIds.add(id);
147
179
  normalized.push({
148
- id: sanitizeProviderToolId(tc['id'], prefix, i),
180
+ id,
149
181
  type: 'function',
150
182
  function: {
151
183
  name,
@@ -181,10 +213,24 @@ export function normalizeOpenAIChatChoiceResponse(
181
213
  const choice = isPlainObject(payload['choices'][0]) ? payload['choices'][0] : null;
182
214
  const message = choice && isPlainObject(choice['message']) ? choice['message'] : null;
183
215
  if (message) {
184
- content = typeof message['content'] === 'string' ? message['content'] : '';
216
+ if (typeof message['content'] === 'string') {
217
+ content = message['content'];
218
+ } else if (Array.isArray(message['content'])) {
219
+ content = (message['content'] as unknown[])
220
+ .map((part) => (isPlainObject(part) && typeof part['text'] === 'string' ? part['text'] : ''))
221
+ .filter(Boolean)
222
+ .join('');
223
+ }
185
224
  rawToolCalls = message['tool_calls'];
186
- const rc = message['reasoning_content'] ?? message['reasoning'];
187
- reasoningContent = typeof rc === 'string' ? rc : '';
225
+ const rc = message['reasoning_content'] ?? message['reasoning'] ?? message['thinking'];
226
+ if (typeof rc === 'string') {
227
+ reasoningContent = rc;
228
+ } else if (Array.isArray(message['reasoning_details'])) {
229
+ reasoningContent = (message['reasoning_details'] as unknown[])
230
+ .map((d) => (isPlainObject(d) ? (typeof d['text'] === 'string' ? d['text'] : (typeof d['summary'] === 'string' ? d['summary'] : '')) : ''))
231
+ .filter(Boolean)
232
+ .join('\n');
233
+ }
188
234
  }
189
235
  }
190
236
 
@@ -234,7 +280,7 @@ export function prepareMessagesForAnthropic(
234
280
  for (const msg of messages) {
235
281
  if (!isPlainObject(msg)) continue;
236
282
  if (msg['role'] === 'system') {
237
- const { spillPath: _spill, ...rest } = msg;
283
+ const { spillPath: _spill, thinking_blocks: _tb, reasoning_content: _rc, ...rest } = msg;
238
284
  prepared.push(rest);
239
285
  continue;
240
286
  }
@@ -256,7 +302,17 @@ export function prepareMessagesForAnthropic(
256
302
  export function normalizeMessagesForOllama(messages: unknown[]): any[] {
257
303
  if (!Array.isArray(messages)) return [];
258
304
  return messages.map((msg) => {
259
- if (!isPlainObject(msg) || msg['role'] !== 'assistant' || !Array.isArray(msg['tool_calls'])) {
305
+ if (!isPlainObject(msg)) return msg;
306
+ if (msg['role'] === 'tool' && typeof msg['content'] !== 'string') {
307
+ let str = '';
308
+ try {
309
+ str = msg['content'] == null ? '' : JSON.stringify(msg['content']);
310
+ } catch {
311
+ str = String(msg['content'] ?? '');
312
+ }
313
+ return { ...msg, content: str };
314
+ }
315
+ if (msg['role'] !== 'assistant' || !Array.isArray(msg['tool_calls'])) {
260
316
  return msg;
261
317
  }
262
318
  return {