@causyne/agent 1.20.117 → 1.20.120

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 (82) hide show
  1. package/package.json +7 -2
  2. package/src/agentLoop.js +29 -12
  3. package/src/agentLoop.ts +29 -16
  4. package/src/browser/causyneBrowser.js +231 -136
  5. package/src/browser/causyneBrowser.ts +229 -140
  6. package/src/browser/searchProviders.js +41 -30
  7. package/src/browser/searchProviders.ts +24 -14
  8. package/src/browser/workspacePathSafety.js +50 -0
  9. package/src/browser/workspacePathSafety.ts +50 -0
  10. package/src/browser/workspacePreview.js +27 -4
  11. package/src/browser/workspacePreview.ts +28 -4
  12. package/src/cliMode.js +20 -4
  13. package/src/commands.js +12 -14
  14. package/src/creative/liveBridge.js +34 -1
  15. package/src/creative/liveBridge.ts +28 -1
  16. package/src/observer/evidence.js +23 -0
  17. package/src/observer/evidence.ts +21 -0
  18. package/src/plugins/pluginManager.js +74 -0
  19. package/src/providers/anthropic.js +33 -17
  20. package/src/providers/base.js +14 -0
  21. package/src/providers/dashscope-byok.js +13 -7
  22. package/src/providers/deepseek.js +13 -18
  23. package/src/providers/gemini.js +33 -25
  24. package/src/providers/moonshot.js +13 -12
  25. package/src/providers/ollama.js +21 -21
  26. package/src/providers/openai-compatible.js +12 -19
  27. package/src/providers/openrouter.js +20 -90
  28. package/src/providers/openrouter.ts +31 -94
  29. package/src/providers/qwen-byok.js +13 -7
  30. package/src/providers/toolContracts.js +9 -3
  31. package/src/providers/toolContracts.ts +9 -3
  32. package/src/providers/wireNormalizer.js +238 -0
  33. package/src/providers/wireNormalizer.ts +279 -0
  34. package/src/providers/xai.js +13 -12
  35. package/src/reporting.js +12 -4
  36. package/src/skillsManager.js +3 -2
  37. package/src/skillsManager.ts +3 -2
  38. package/src/tools/browserAutomator.js +13 -1
  39. package/src/tools/browserAutomator.ts +13 -0
  40. package/src/tools/creativeApps.js +2 -1
  41. package/src/tools/creativeApps.ts +2 -1
  42. package/src/tools/gameAssetFetcher.js +130 -26
  43. package/src/tools/gameAssetHarvester.js +80 -58
  44. package/src/tools/nativeEngine.js +1 -1
  45. package/src/tools/nativeEngine.ts +1 -1
  46. package/src/tools/pluginManager.js +17 -2
  47. package/src/tools/registry.js +13 -0
  48. package/src/tools/toolScanner.js +596 -140
  49. package/src/tools/toolScanner.ts +665 -147
  50. package/src/tools/toolSelfRepair.js +243 -114
  51. package/src/tools/toolSelfRepair.ts +262 -111
  52. package/src/tools/webFetch.js +161 -24
  53. package/src/tools/webFetch.ts +157 -22
  54. package/src/tools/webSearch.js +33 -4
  55. package/src/tools/webSearch.ts +27 -4
  56. package/src/tui/composerControls.js +16 -3
  57. package/src/tui/composerControls.ts +14 -3
  58. package/src/tui/prompt.js +122 -16
  59. package/src/tui/sessionPicker.js +132 -35
  60. package/src/tui/sessionPicker.ts +153 -32
  61. package/src/tui/sessionPickerView.js +277 -34
  62. package/src/tui/sessionPickerView.ts +328 -34
  63. package/src/tui/statusLine.js +3 -0
  64. package/src/tui/statusLine.ts +5 -0
  65. package/src/tui/usageCard.js +119 -47
  66. package/src/tui/usageCard.ts +133 -49
  67. package/src/tui/workspaceIdentity.js +133 -0
  68. package/src/tui/workspaceIdentity.ts +146 -0
  69. package/src/tui/workspaceSwitch.js +2 -0
  70. package/src/tui/workspaceSwitch.ts +1 -0
  71. package/src/verification/boundedExplorer.js +119 -0
  72. package/src/verification/cliProbe.js +116 -0
  73. package/src/verification/featureMap.js +78 -0
  74. package/src/verification/interactivePty.js +188 -0
  75. package/src/verification/propertyProbe.js +121 -0
  76. package/src/verification/ptyProbe.js +125 -0
  77. package/src/verification/skillCatalog.d.ts +1 -0
  78. package/src/verification/skillCatalog.js +60 -0
  79. package/src/verification/statechart.js +143 -0
  80. package/src/verification/uiRuntime.js +57 -0
  81. package/src/verificationPlan.js +1 -1
  82. package/src/verificationPlan.ts +1 -1
@@ -2,36 +2,150 @@
2
2
  * Causyne Agent — Universal Tool Scanner & Compatibility Layer (toolsScan)
3
3
  *
4
4
  * Scans tool definitions for cross-vendor compatibility issues across LLM
5
- * providers (Gemini, Anthropic, OpenAI, DeepSeek, Ollama, Qwen, etc.) and
6
- * adapts them dynamically to each provider's wire format without degrading
7
- * or altering the tool's underlying functionality.
5
+ * providers (Gemini, Anthropic, OpenAI, DeepSeek, Ollama, Qwen, DashScope,
6
+ * Moonshot, xAI, Muse, OpenRouter, Antigravity, ACP, Pi) and compiles them
7
+ * deterministically into every provider's wire format without degrading or
8
+ * altering the tool's underlying functionality.
8
9
  */
10
+ import { createHash } from 'node:crypto';
11
+ export const ALL_PROVIDER_DIALECTS = [
12
+ 'openai',
13
+ 'openai-compatible',
14
+ 'anthropic',
15
+ 'gemini',
16
+ 'deepseek',
17
+ 'qwen',
18
+ 'dashscope',
19
+ 'moonshot',
20
+ 'xai',
21
+ 'muse',
22
+ 'openrouter',
23
+ 'ollama',
24
+ 'antigravity',
25
+ 'acp',
26
+ 'pi'
27
+ ];
9
28
  const FREE_FORM_NOTE = ' Pass this as a JSON object encoded in a string, for example {"key":"value"}.';
29
+ const POLYMORPHIC_ARRAY_NOTE = ' For multiple items, pass a JSON array encoded as a string, e.g. ["a","b"].';
30
+ const POLYMORPHIC_VALUE_NOTE = ' Pass non-string values (number, boolean, object, or array) encoded as JSON.';
10
31
  const TOOL_NAME_REGEX = /^[a-zA-Z0-9_-]{1,64}$/;
32
+ const META_AND_COMBINATOR_KEYS = new Set([
33
+ '$schema',
34
+ '$id',
35
+ '$defs',
36
+ 'definitions',
37
+ '$ref',
38
+ '$comment',
39
+ 'oneOf',
40
+ 'anyOf',
41
+ 'allOf',
42
+ 'not',
43
+ 'if',
44
+ 'then',
45
+ 'else',
46
+ 'dependentRequired',
47
+ 'dependentSchemas',
48
+ 'patternProperties',
49
+ 'examples'
50
+ ]);
51
+ const GEMINI_FORBIDDEN_KEYS = new Set([
52
+ ...META_AND_COMBINATOR_KEYS,
53
+ 'additionalProperties',
54
+ 'default',
55
+ 'const',
56
+ 'nullable',
57
+ 'exclusiveMinimum',
58
+ 'exclusiveMaximum',
59
+ 'multipleOf',
60
+ 'contentEncoding',
61
+ 'contentMediaType',
62
+ 'readOnly',
63
+ 'writeOnly',
64
+ 'deprecated',
65
+ 'minLength',
66
+ 'maxLength',
67
+ 'minProperties',
68
+ 'maxProperties',
69
+ 'uniqueItems'
70
+ ]);
71
+ function isPlainObject(value) {
72
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
73
+ }
11
74
  /**
12
- * Standardize tool name to match the wire grammar [a-zA-Z0-9_-]{1,64}.
75
+ * Standardize tool name to match the universal wire grammar ^[a-zA-Z0-9_-]{1,64}$.
13
76
  */
14
77
  export function normalizeToolName(name) {
15
- return String(name || '').replace(/\./g, '_');
78
+ const sanitized = String(name || '').trim().replace(/[^a-zA-Z0-9_-]/g, '_');
79
+ if (!sanitized)
80
+ return 'tool';
81
+ if (sanitized.length <= 64)
82
+ return sanitized;
83
+ const suffix = createHash('sha256').update(sanitized).digest('hex').slice(0, 6);
84
+ return `${sanitized.slice(0, 57)}_${suffix}`;
16
85
  }
17
86
  /**
18
87
  * Check if a schema node represents an empty object with no properties declared.
19
88
  */
20
89
  export function isEmptyObjectSchema(schema) {
21
- if (!schema || typeof schema !== 'object')
90
+ if (!isPlainObject(schema))
22
91
  return false;
23
- const s = schema;
24
- return s['type'] === 'object' && (!s['properties'] || Object.keys(s['properties']).length === 0);
92
+ return schema['type'] === 'object' && (!isPlainObject(schema['properties']) || Object.keys(schema['properties']).length === 0);
93
+ }
94
+ function appendDescriptionNote(base, note) {
95
+ const text = typeof base === 'string' ? base.trim() : '';
96
+ if (!text)
97
+ return note.trim();
98
+ if (text.includes(note.trim()))
99
+ return text;
100
+ return `${text}${note.startsWith(' ') ? '' : ' '}${note}`;
101
+ }
102
+ function inferPrimitiveTypeFromEnum(values) {
103
+ if (values.length === 0)
104
+ return 'string';
105
+ const types = new Set(values.map((v) => {
106
+ if (typeof v === 'number')
107
+ return Number.isInteger(v) ? 'integer' : 'number';
108
+ if (typeof v === 'boolean')
109
+ return 'boolean';
110
+ return 'string';
111
+ }));
112
+ if (types.size === 1) {
113
+ return Array.from(types)[0] || 'string';
114
+ }
115
+ return 'string';
116
+ }
117
+ function resolveLocalRef(ref, defs, activeRefs) {
118
+ if (!ref || activeRefs.has(ref))
119
+ return null;
120
+ let key = null;
121
+ if (ref.startsWith('#/$defs/')) {
122
+ key = ref.slice('#/$defs/'.length);
123
+ }
124
+ else if (ref.startsWith('#/definitions/')) {
125
+ key = ref.slice('#/definitions/'.length);
126
+ }
127
+ if (!key)
128
+ return null;
129
+ const target = defs[key];
130
+ return isPlainObject(target) ? target : null;
131
+ }
132
+ function pushRewrittenPath(rewritten, path) {
133
+ if (path.length === 0)
134
+ return;
135
+ const key = path.join('\0');
136
+ if (!rewritten.some((existing) => existing.join('\0') === key)) {
137
+ rewritten.push([...path]);
138
+ }
25
139
  }
26
140
  /**
27
- * Recursively inspect a schema for provider incompatibilities.
141
+ * Recursively inspect a schema for raw or residual provider incompatibilities.
28
142
  */
29
143
  function inspectSchemaForProvider(toolName, schema, path, provider, issues) {
30
- if (!schema || typeof schema !== 'object')
144
+ if (!isPlainObject(schema))
31
145
  return;
32
- const s = schema;
33
146
  const pathStr = path.join('.');
34
- if (s['type'] === 'array' && !s['items']) {
147
+ const isGemini = provider === 'gemini';
148
+ if (schema['type'] === 'array' && !schema['items']) {
35
149
  issues.push({
36
150
  tool: toolName,
37
151
  path: pathStr,
@@ -40,17 +154,51 @@ function inspectSchemaForProvider(toolName, schema, path, provider, issues) {
40
154
  severity: 'error'
41
155
  });
42
156
  }
43
- if (Array.isArray(s['type'])) {
157
+ if (Array.isArray(schema['type'])) {
44
158
  issues.push({
45
159
  tool: toolName,
46
160
  path: pathStr,
47
161
  code: 'UNION_TYPE_ARRAY',
48
- message: `Union type array [${s['type'].join(', ')}] at '${pathStr}' is unsupported by OpenAPI 3.0 / Gemini / DeepSeek.`,
162
+ message: `Union type array [${schema['type'].join(', ')}] at '${pathStr}' is unsupported by OpenAPI 3.0 / Gemini / DeepSeek.`,
49
163
  severity: 'warning'
50
164
  });
51
165
  }
52
- if (provider === 'gemini') {
53
- if ('additionalProperties' in s) {
166
+ if (Array.isArray(schema['oneOf']) || Array.isArray(schema['anyOf']) || Array.isArray(schema['allOf']) || 'not' in schema) {
167
+ issues.push({
168
+ tool: toolName,
169
+ path: pathStr,
170
+ code: 'UNSUPPORTED_COMBINATOR',
171
+ message: `Schema combinator (oneOf/anyOf/allOf/not) at '${pathStr}' must be compiled for universal provider compatibility.`,
172
+ severity: isGemini ? 'error' : 'warning'
173
+ });
174
+ }
175
+ const hasCombinator = Boolean(schema['oneOf'] || schema['anyOf'] || schema['allOf']);
176
+ const isRootSchema = path.length === 1 && path[0] === 'parameters';
177
+ if (!isRootSchema && !schema['type'] && !isPlainObject(schema['properties']) && !schema['items'] && !hasCombinator && !('$ref' in schema)) {
178
+ issues.push({
179
+ tool: toolName,
180
+ path: pathStr,
181
+ code: 'MISSING_TYPE',
182
+ message: `Schema at '${pathStr}' declares no 'type', properties, or combinator.`,
183
+ severity: isGemini ? 'error' : 'warning'
184
+ });
185
+ }
186
+ if (schema['type'] === 'object' && Array.isArray(schema['required']) && isPlainObject(schema['properties'])) {
187
+ const props = schema['properties'];
188
+ for (const req of schema['required']) {
189
+ if (typeof req === 'string' && !(req in props)) {
190
+ issues.push({
191
+ tool: toolName,
192
+ path: `${pathStr}.required.${req}`,
193
+ code: 'REQUIRED_PROPERTY_MISSING',
194
+ message: `'required' entry "${req}" at '${pathStr}' is absent from 'properties'.`,
195
+ severity: 'warning'
196
+ });
197
+ }
198
+ }
199
+ }
200
+ if (isGemini) {
201
+ if ('additionalProperties' in schema) {
54
202
  issues.push({
55
203
  tool: toolName,
56
204
  path: pathStr,
@@ -59,7 +207,7 @@ function inspectSchemaForProvider(toolName, schema, path, provider, issues) {
59
207
  severity: 'error'
60
208
  });
61
209
  }
62
- if (s['type'] === 'object' && (!s['properties'] || Object.keys(s['properties']).length === 0)) {
210
+ if (schema['type'] === 'object' && (!isPlainObject(schema['properties']) || Object.keys(schema['properties']).length === 0)) {
63
211
  issues.push({
64
212
  tool: toolName,
65
213
  path: pathStr,
@@ -68,101 +216,363 @@ function inspectSchemaForProvider(toolName, schema, path, provider, issues) {
68
216
  severity: 'error'
69
217
  });
70
218
  }
71
- if ('$ref' in s || 'definitions' in s || 'patternProperties' in s) {
219
+ if (Array.isArray(schema['enum']) && (schema['type'] !== 'string' || schema['enum'].some((v) => typeof v !== 'string'))) {
72
220
  issues.push({
73
221
  tool: toolName,
74
222
  path: pathStr,
75
- code: 'GEMINI_UNSUPPORTED_KEYWORDS',
76
- message: `Unsupported JSON Schema keyword at '${pathStr}' in Gemini.`,
223
+ code: 'GEMINI_NON_STRING_ENUM',
224
+ message: `Non-string enum at '${pathStr}' is rejected by Gemini OpenAPI Schema.`,
77
225
  severity: 'warning'
78
226
  });
79
227
  }
228
+ for (const key of Object.keys(schema)) {
229
+ if (key !== 'additionalProperties' && GEMINI_FORBIDDEN_KEYS.has(key)) {
230
+ issues.push({
231
+ tool: toolName,
232
+ path: pathStr,
233
+ code: 'GEMINI_UNSUPPORTED_KEYWORDS',
234
+ message: `Unsupported JSON Schema keyword '${key}' at '${pathStr}' in Gemini.`,
235
+ severity: key === 'default' || key === '$schema' ? 'error' : 'warning'
236
+ });
237
+ break;
238
+ }
239
+ }
80
240
  }
81
- if (s['properties'] && typeof s['properties'] === 'object') {
82
- for (const [propKey, propVal] of Object.entries(s['properties'])) {
241
+ if (isPlainObject(schema['properties'])) {
242
+ for (const [propKey, propVal] of Object.entries(schema['properties'])) {
83
243
  inspectSchemaForProvider(toolName, propVal, [...path, propKey], provider, issues);
84
244
  }
85
245
  }
86
- if (s['items'] && typeof s['items'] === 'object') {
87
- inspectSchemaForProvider(toolName, s['items'], [...path, '[]'], provider, issues);
246
+ if (isPlainObject(schema['items'])) {
247
+ inspectSchemaForProvider(toolName, schema['items'], [...path, '[]'], provider, issues);
248
+ }
249
+ for (const comb of ['oneOf', 'anyOf', 'allOf']) {
250
+ const arr = schema[comb];
251
+ if (Array.isArray(arr)) {
252
+ arr.forEach((branch, idx) => {
253
+ inspectSchemaForProvider(toolName, branch, [...path, `${comb}[${idx}]`], provider, issues);
254
+ });
255
+ }
88
256
  }
89
257
  }
90
- /**
91
- * Adapt a schema into Gemini's strict OpenAPI 3.0 subset without losing capability.
92
- * Free-form objects are converted to stringified JSON schemas and recorded.
93
- */
94
- export function adaptSchemaForGemini(schema, path, rewritten) {
258
+ function mergeAllOfBranches(branches, dialect, path, rewritten, defs, activeRefs, parent) {
259
+ const mergedProps = isPlainObject(parent['properties'])
260
+ ? { ...parent['properties'] }
261
+ : {};
262
+ const mergedRequired = new Set(Array.isArray(parent['required']) ? parent['required'].filter((x) => typeof x === 'string') : []);
263
+ const descriptions = typeof parent['description'] === 'string' && parent['description'].trim()
264
+ ? [parent['description'].trim()]
265
+ : [];
266
+ let resolvedType = parent['type'];
267
+ for (const branch of branches) {
268
+ const adaptedBranch = compileSchemaNode(branch, dialect, path, rewritten, defs, activeRefs);
269
+ if (!isPlainObject(adaptedBranch))
270
+ continue;
271
+ if (typeof adaptedBranch['description'] === 'string' && adaptedBranch['description'].trim() && !descriptions.includes(adaptedBranch['description'].trim())) {
272
+ descriptions.push(adaptedBranch['description'].trim());
273
+ }
274
+ if (!resolvedType && adaptedBranch['type'])
275
+ resolvedType = adaptedBranch['type'];
276
+ if (isPlainObject(adaptedBranch['properties'])) {
277
+ Object.assign(mergedProps, adaptedBranch['properties']);
278
+ }
279
+ if (Array.isArray(adaptedBranch['required'])) {
280
+ for (const req of adaptedBranch['required']) {
281
+ if (typeof req === 'string')
282
+ mergedRequired.add(req);
283
+ }
284
+ }
285
+ }
286
+ const result = {};
287
+ if (descriptions.length > 0)
288
+ result['description'] = descriptions.join(' ');
289
+ const propKeys = Object.keys(mergedProps);
290
+ if (resolvedType === 'object' || propKeys.length > 0) {
291
+ result['type'] = 'object';
292
+ result['properties'] = mergedProps;
293
+ const validReq = Array.from(mergedRequired).filter((k) => k in mergedProps);
294
+ if (validReq.length > 0)
295
+ result['required'] = validReq;
296
+ }
297
+ else if (typeof resolvedType === 'string') {
298
+ result['type'] = resolvedType;
299
+ }
300
+ else {
301
+ result['type'] = 'string';
302
+ result['description'] = appendDescriptionNote(result['description'], POLYMORPHIC_VALUE_NOTE);
303
+ pushRewrittenPath(rewritten, path);
304
+ }
305
+ return result;
306
+ }
307
+ function collapseUnionVariants(variants, dialect, path, rewritten, defs, activeRefs, parent) {
308
+ const nonNull = variants.filter((entry) => !(isPlainObject(entry) && entry['type'] === 'null'));
309
+ const isNullable = nonNull.length < variants.length;
310
+ const baseDesc = typeof parent['description'] === 'string' ? parent['description'] : undefined;
311
+ if (nonNull.length === 0) {
312
+ pushRewrittenPath(rewritten, path);
313
+ return {
314
+ type: 'string',
315
+ description: appendDescriptionNote(baseDesc, POLYMORPHIC_VALUE_NOTE)
316
+ };
317
+ }
318
+ if (nonNull.length === 1) {
319
+ const single = isPlainObject(nonNull[0]) ? { ...nonNull[0] } : {};
320
+ if (baseDesc && !single['description'])
321
+ single['description'] = baseDesc;
322
+ if (isNullable && typeof single['description'] === 'string') {
323
+ single['description'] = appendDescriptionNote(single['description'], ' (optional/nullable)');
324
+ }
325
+ return compileSchemaNode(single, dialect, path, rewritten, defs, activeRefs);
326
+ }
327
+ const compiledBranches = nonNull.map((branch) => compileSchemaNode(branch, dialect, path, rewritten, defs, activeRefs)).filter(isPlainObject);
328
+ const branchTypes = Array.from(new Set(compiledBranches.map((b) => typeof b['type'] === 'string' ? b['type'] : 'string')));
329
+ if (branchTypes.length === 1 && branchTypes[0] === 'object') {
330
+ const mergedProps = {};
331
+ let commonRequired = null;
332
+ for (const branch of compiledBranches) {
333
+ if (isPlainObject(branch['properties'])) {
334
+ Object.assign(mergedProps, branch['properties']);
335
+ }
336
+ const reqs = new Set(Array.isArray(branch['required']) ? branch['required'].filter((x) => typeof x === 'string') : []);
337
+ if (commonRequired === null) {
338
+ commonRequired = reqs;
339
+ }
340
+ else {
341
+ const intersected = new Set();
342
+ for (const k of commonRequired) {
343
+ if (reqs.has(k))
344
+ intersected.add(k);
345
+ }
346
+ commonRequired = intersected;
347
+ }
348
+ }
349
+ const validReq = commonRequired ? Array.from(commonRequired).filter((k) => k in mergedProps) : [];
350
+ const result = {
351
+ type: 'object',
352
+ properties: mergedProps
353
+ };
354
+ if (baseDesc)
355
+ result['description'] = baseDesc;
356
+ if (validReq.length > 0)
357
+ result['required'] = validReq;
358
+ return isEmptyObjectSchema(result) && dialect === 'gemini'
359
+ ? (() => {
360
+ pushRewrittenPath(rewritten, path);
361
+ return { type: 'string', description: appendDescriptionNote(baseDesc, FREE_FORM_NOTE) };
362
+ })()
363
+ : result;
364
+ }
365
+ if (branchTypes.length === 1 && (branchTypes[0] === 'string' || branchTypes[0] === 'number' || branchTypes[0] === 'integer' || branchTypes[0] === 'boolean')) {
366
+ const singleType = branchTypes[0];
367
+ const result = { type: singleType };
368
+ const enumSet = new Set();
369
+ let allHaveStringEnums = true;
370
+ for (const branch of compiledBranches) {
371
+ if (Array.isArray(branch['enum']) && branch['enum'].every((v) => typeof v === 'string')) {
372
+ for (const v of branch['enum'])
373
+ enumSet.add(v);
374
+ }
375
+ else {
376
+ allHaveStringEnums = false;
377
+ }
378
+ }
379
+ if (baseDesc)
380
+ result['description'] = baseDesc;
381
+ if (allHaveStringEnums && enumSet.size > 0 && singleType === 'string') {
382
+ result['enum'] = Array.from(enumSet);
383
+ }
384
+ return result;
385
+ }
386
+ // Incompatible multi-type union (e.g. oneOf: [string, array<string>]) -> universal string with JSON decoding
387
+ pushRewrittenPath(rewritten, path);
388
+ const includesArray = branchTypes.includes('array');
389
+ const note = includesArray ? POLYMORPHIC_ARRAY_NOTE : POLYMORPHIC_VALUE_NOTE;
390
+ return {
391
+ type: 'string',
392
+ description: appendDescriptionNote(baseDesc, note)
393
+ };
394
+ }
395
+ function compileSchemaNode(schema, dialect, path, rewritten, defs, activeRefs) {
95
396
  if (Array.isArray(schema)) {
96
- return schema.map((entry) => adaptSchemaForGemini(entry, path, rewritten));
397
+ return schema.map((entry) => compileSchemaNode(entry, dialect, path, rewritten, defs, activeRefs));
97
398
  }
98
- if (schema === null || typeof schema !== 'object') {
399
+ if (!isPlainObject(schema)) {
99
400
  return schema;
100
401
  }
101
- const s = schema;
402
+ const localDefs = {
403
+ ...defs,
404
+ ...(isPlainObject(schema['$defs']) ? schema['$defs'] : {}),
405
+ ...(isPlainObject(schema['definitions']) ? schema['definitions'] : {})
406
+ };
407
+ if (typeof schema['$ref'] === 'string') {
408
+ const refTarget = resolveLocalRef(schema['$ref'], localDefs, activeRefs);
409
+ if (!refTarget) {
410
+ pushRewrittenPath(rewritten, path);
411
+ return {
412
+ type: 'string',
413
+ description: appendDescriptionNote(schema['description'], FREE_FORM_NOTE)
414
+ };
415
+ }
416
+ const nextActive = new Set(activeRefs);
417
+ nextActive.add(schema['$ref']);
418
+ const mergedRef = {
419
+ ...refTarget,
420
+ ...(typeof schema['description'] === 'string' ? { description: schema['description'] } : {})
421
+ };
422
+ return compileSchemaNode(mergedRef, dialect, path, rewritten, localDefs, nextActive);
423
+ }
424
+ if (Array.isArray(schema['allOf']) && schema['allOf'].length > 0) {
425
+ return mergeAllOfBranches(schema['allOf'], dialect, path, rewritten, localDefs, activeRefs, schema);
426
+ }
427
+ if (Array.isArray(schema['oneOf']) && schema['oneOf'].length > 0) {
428
+ return collapseUnionVariants(schema['oneOf'], dialect, path, rewritten, localDefs, activeRefs, schema);
429
+ }
430
+ if (Array.isArray(schema['anyOf']) && schema['anyOf'].length > 0) {
431
+ return collapseUnionVariants(schema['anyOf'], dialect, path, rewritten, localDefs, activeRefs, schema);
432
+ }
433
+ // Handle nested empty objects on Gemini anywhere in the tree (properties, items, combinators).
434
+ // Skip flattening root schema itself (path.length === 0): root parameterless tools omit parameters on Gemini.
435
+ if (dialect === 'gemini' && path.length > 0 && isEmptyObjectSchema(schema)) {
436
+ pushRewrittenPath(rewritten, path);
437
+ return {
438
+ type: 'string',
439
+ description: appendDescriptionNote(schema['description'] || 'Free-form object.', FREE_FORM_NOTE)
440
+ };
441
+ }
442
+ const forbidden = dialect === 'gemini' ? GEMINI_FORBIDDEN_KEYS : META_AND_COMBINATOR_KEYS;
102
443
  const adapted = {};
103
- for (const [key, value] of Object.entries(s)) {
104
- // 1. Strip additionalProperties (strictly rejected by Gemini)
105
- if (key === 'additionalProperties')
106
- continue;
107
- // 2. Strip unsupported keywords in Gemini OpenAPI
108
- if (key === '$ref' || key === 'definitions' || key === 'patternProperties')
444
+ for (const [key, value] of Object.entries(schema)) {
445
+ if (forbidden.has(key))
109
446
  continue;
110
- // 3. Handle union types (e.g. type: ["string", "number"])
111
447
  if (key === 'type' && Array.isArray(value)) {
112
- const types = value;
113
- const safeType = types.find((t) => t !== 'null') || 'string';
448
+ const types = value.filter((t) => typeof t === 'string');
449
+ const nonNull = types.filter((t) => t !== 'null');
450
+ const safeType = nonNull.includes('string') ? 'string' : (nonNull[0] || 'string');
114
451
  adapted['type'] = safeType;
115
- if (!adapted['description'] && s['description']) {
116
- adapted['description'] = `${s['description']} (accepts ${types.join(' or ')})`;
452
+ if (nonNull.length > 1) {
453
+ pushRewrittenPath(rewritten, path);
454
+ }
455
+ if (schema['description'] || nonNull.length > 1) {
456
+ const descBase = typeof adapted['description'] === 'string'
457
+ ? adapted['description']
458
+ : typeof schema['description'] === 'string'
459
+ ? schema['description']
460
+ : '';
461
+ adapted['description'] = appendDescriptionNote(descBase, ` (accepts ${types.join(' or ')})`);
117
462
  }
118
463
  continue;
119
464
  }
120
- // 4. Handle nested properties
121
- if (key === 'properties' && value && typeof value === 'object') {
122
- const properties = {};
123
- for (const [name, child] of Object.entries(value)) {
124
- const childPath = [...path, name];
125
- if (isEmptyObjectSchema(child)) {
126
- rewritten.push(childPath);
127
- const childObj = (child && typeof child === 'object' ? child : {});
128
- properties[name] = {
129
- type: 'string',
130
- description: (childObj['description'] || 'Free-form object.') + FREE_FORM_NOTE
131
- };
132
- }
133
- else {
134
- properties[name] = adaptSchemaForGemini(child, childPath, rewritten);
135
- }
465
+ if (key === 'properties' && isPlainObject(value)) {
466
+ const props = {};
467
+ for (const [propName, child] of Object.entries(value)) {
468
+ props[propName] = compileSchemaNode(child, dialect, [...path, propName], rewritten, localDefs, activeRefs);
136
469
  }
137
- adapted['properties'] = properties;
470
+ adapted['properties'] = props;
138
471
  continue;
139
472
  }
140
- // 5. Handle array items
141
473
  if (key === 'items') {
142
- adapted['items'] = adaptSchemaForGemini(value, [...path, '[]'], rewritten);
474
+ adapted['items'] = compileSchemaNode(value, dialect, [...path, '[]'], rewritten, localDefs, activeRefs);
475
+ continue;
476
+ }
477
+ if (key === 'enum' && Array.isArray(value)) {
478
+ adapted['enum'] = value;
143
479
  continue;
144
480
  }
145
- adapted[key] = adaptSchemaForGemini(value, path, rewritten);
481
+ adapted[key] = isPlainObject(value) || Array.isArray(value)
482
+ ? compileSchemaNode(value, dialect, path, rewritten, localDefs, activeRefs)
483
+ : value;
484
+ }
485
+ // Handle const values gracefully after stripping const on Gemini
486
+ if ('const' in schema && !('enum' in adapted) && typeof schema['const'] === 'string') {
487
+ if (!adapted['type'])
488
+ adapted['type'] = 'string';
489
+ adapted['enum'] = [schema['const']];
490
+ }
491
+ else if ('default' in schema && dialect === 'gemini' && typeof adapted['description'] === 'string') {
492
+ const defText = `default: ${String(schema['default'])}`;
493
+ if (!adapted['description'].toLowerCase().includes('default')) {
494
+ adapted['description'] = appendDescriptionNote(adapted['description'], ` (${defText})`);
495
+ }
496
+ }
497
+ // Repair typeless leaf schemas (e.g. dynamic MCP or legacy tools lacking 'type')
498
+ if (!adapted['type']) {
499
+ if (isPlainObject(adapted['properties'])) {
500
+ adapted['type'] = 'object';
501
+ }
502
+ else if (adapted['items']) {
503
+ adapted['type'] = 'array';
504
+ }
505
+ else if (Array.isArray(adapted['enum'])) {
506
+ adapted['type'] = inferPrimitiveTypeFromEnum(adapted['enum']);
507
+ }
508
+ else {
509
+ adapted['type'] = 'string';
510
+ adapted['description'] = appendDescriptionNote(adapted['description'], POLYMORPHIC_VALUE_NOTE);
511
+ pushRewrittenPath(rewritten, path);
512
+ }
513
+ }
514
+ if (adapted['type'] === 'object' && !isPlainObject(adapted['properties'])) {
515
+ adapted['properties'] = {};
516
+ }
517
+ if (adapted['type'] === 'array' && !adapted['items']) {
518
+ adapted['items'] = { type: 'string' };
519
+ }
520
+ // Gemini OpenAPI Schema only accepts enum on string properties with string items
521
+ if (dialect === 'gemini' && Array.isArray(adapted['enum'])) {
522
+ const nonStringEnum = adapted['enum'].some((item) => typeof item !== 'string');
523
+ if (adapted['type'] !== 'string' || nonStringEnum) {
524
+ const allowed = adapted['enum'].map((v) => String(v)).join(', ');
525
+ delete adapted['enum'];
526
+ adapted['description'] = appendDescriptionNote(adapted['description'], ` Allowed values: ${allowed}.`);
527
+ }
528
+ }
529
+ if (adapted['type'] === 'object' && Array.isArray(adapted['required']) && isPlainObject(adapted['properties'])) {
530
+ const props = adapted['properties'];
531
+ const filtered = adapted['required'].filter((k) => typeof k === 'string' && k in props);
532
+ if (filtered.length > 0) {
533
+ adapted['required'] = filtered;
534
+ }
535
+ else {
536
+ delete adapted['required'];
537
+ }
146
538
  }
147
539
  return adapted;
148
540
  }
541
+ /**
542
+ * Compile an arbitrary schema into a dialect-clean schema without changing behavior
543
+ * when the schema is already clean.
544
+ */
545
+ export function normalizeUniversalSchema(schema, path = [], rewritten = [], dialect = 'strict_json') {
546
+ return compileSchemaNode(schema, dialect, path, rewritten, {}, new Set());
547
+ }
548
+ /**
549
+ * Adapt a schema into Gemini's strict OpenAPI 3.0 subset without losing capability.
550
+ * Free-form objects and incompatible unions are compiled to stringified JSON schemas and recorded.
551
+ */
552
+ export function adaptSchemaForGemini(schema, path = [], rewritten = []) {
553
+ return compileSchemaNode(schema, 'gemini', path, rewritten, {}, new Set());
554
+ }
149
555
  /**
150
556
  * Adapt a tool schema into Anthropic's Messages API format.
151
557
  */
152
558
  export function adaptSchemaForAnthropic(toolObj, options = {}) {
153
559
  const rawParams = toolObj.parameters || toolObj.input_schema || {};
154
- let schema = typeof rawParams === 'object' && rawParams !== null ? { ...rawParams } : { type: 'object', properties: {} };
155
- if (schema.type !== 'object') {
560
+ let schema = isPlainObject(rawParams) ? { ...rawParams } : { type: 'object', properties: {} };
561
+ if (schema['type'] !== 'object' && !isPlainObject(schema['properties']) && !schema['allOf']) {
156
562
  schema = { type: 'object', properties: {} };
157
563
  }
158
- if (!schema.properties) {
159
- schema.properties = {};
564
+ else if (!schema['type']) {
565
+ schema['type'] = 'object';
566
+ }
567
+ if (!isPlainObject(schema['properties']) && !schema['allOf']) {
568
+ schema['properties'] = {};
160
569
  }
161
- // Handle union types for clean typing
162
- const cleanSchema = cleanUnionTypes(schema);
570
+ const rewritten = options.rewritten ?? [];
571
+ const cleanSchema = compileSchemaNode(schema, 'strict_json', [], rewritten, {}, new Set());
572
+ const name = normalizeToolName(toolObj.name);
163
573
  const declaration = {
164
- name: normalizeToolName(toolObj.name),
165
- description: toolObj.description || '',
574
+ name,
575
+ description: toolObj.description || `Tool ${name}`,
166
576
  input_schema: cleanSchema
167
577
  };
168
578
  if (options.deferLoading) {
@@ -171,23 +581,28 @@ export function adaptSchemaForAnthropic(toolObj, options = {}) {
171
581
  return declaration;
172
582
  }
173
583
  /**
174
- * Adapt a tool schema into OpenAI / OpenAI-Compatible (DeepSeek, XAI, Mistral, etc.) format.
584
+ * Adapt a tool schema into OpenAI / OpenAI-Compatible (DeepSeek, xAI, Moonshot, Qwen, Muse, OpenRouter) format.
175
585
  */
176
- export function adaptSchemaForOpenAI(toolObj) {
586
+ export function adaptSchemaForOpenAI(toolObj, options = {}) {
177
587
  const rawParams = toolObj.parameters || toolObj.input_schema || {};
178
- let parameters = typeof rawParams === 'object' && rawParams !== null ? { ...rawParams } : { type: 'object', properties: {} };
179
- if (parameters.type !== 'object') {
588
+ let parameters = isPlainObject(rawParams) ? { ...rawParams } : { type: 'object', properties: {} };
589
+ if (parameters['type'] !== 'object' && !isPlainObject(parameters['properties']) && !parameters['allOf']) {
180
590
  parameters = { type: 'object', properties: {} };
181
591
  }
182
- if (!parameters.properties) {
183
- parameters.properties = {};
592
+ else if (!parameters['type']) {
593
+ parameters['type'] = 'object';
184
594
  }
185
- const cleanParams = cleanUnionTypes(parameters);
595
+ if (!isPlainObject(parameters['properties']) && !parameters['allOf']) {
596
+ parameters['properties'] = {};
597
+ }
598
+ const rewritten = options.rewritten ?? [];
599
+ const cleanParams = compileSchemaNode(parameters, 'strict_json', [], rewritten, {}, new Set());
600
+ const name = normalizeToolName(toolObj.name);
186
601
  return {
187
602
  type: 'function',
188
603
  function: {
189
- name: normalizeToolName(toolObj.name),
190
- description: toolObj.description || '',
604
+ name,
605
+ description: toolObj.description || `Tool ${name}`,
191
606
  parameters: cleanParams
192
607
  }
193
608
  };
@@ -195,59 +610,49 @@ export function adaptSchemaForOpenAI(toolObj) {
195
610
  /**
196
611
  * Adapt a tool schema into Ollama format (clean, straightforward parameters).
197
612
  */
198
- export function adaptSchemaForOllama(toolObj) {
199
- return adaptSchemaForOpenAI(toolObj);
613
+ export function adaptSchemaForOllama(toolObj, options = {}) {
614
+ return adaptSchemaForOpenAI(toolObj, options);
200
615
  }
201
- /**
202
- * Replaces union type arrays with single safe base types for providers that reject union types.
203
- */
204
- function cleanUnionTypes(schema) {
205
- if (Array.isArray(schema)) {
206
- return schema.map(cleanUnionTypes);
207
- }
208
- if (!schema || typeof schema !== 'object') {
209
- return schema;
210
- }
211
- const s = { ...schema };
212
- if (Array.isArray(s['type'])) {
213
- const types = s['type'];
214
- s['type'] = types.find((t) => t !== 'null') || 'string';
215
- if (s['description']) {
216
- s['description'] = `${s['description']} (accepts ${types.join(' or ')})`;
217
- }
218
- }
219
- if (s['properties'] && typeof s['properties'] === 'object') {
220
- const props = {};
221
- for (const [k, v] of Object.entries(s['properties'])) {
222
- props[k] = cleanUnionTypes(v);
223
- }
224
- s['properties'] = props;
225
- }
226
- if (s['items']) {
227
- s['items'] = cleanUnionTypes(s['items']);
228
- }
229
- return s;
616
+ function extractAdaptedParameters(adapted, provider) {
617
+ if (!isPlainObject(adapted))
618
+ return undefined;
619
+ const p = provider.toLowerCase();
620
+ if (p === 'anthropic')
621
+ return adapted['input_schema'];
622
+ if (p === 'gemini')
623
+ return adapted['parameters'];
624
+ if (p === 'antigravity' || p === 'agy')
625
+ return adapted['parameters'];
626
+ if (p.startsWith('acp') || p === 'pi')
627
+ return adapted['inputSchema'];
628
+ if (isPlainObject(adapted['function']))
629
+ return adapted['function']['parameters'];
630
+ return adapted['parameters'];
230
631
  }
231
632
  /**
232
633
  * Scans a set of tool definitions for compatibility with a specific provider,
233
- * and generates adapted definitions that are 100% compliant.
634
+ * adapts every tool cleanly to the provider's dialect without degrading capability,
635
+ * and re-verifies that 0 residual dialect violations survive compilation.
234
636
  */
235
637
  export function scanAndAdaptToolsForProvider(tools, provider, options = {}) {
236
638
  const normProvider = provider.toLowerCase();
237
639
  const issues = [];
640
+ const residualIssues = [];
238
641
  const adaptedTools = [];
239
642
  const freeFormPaths = new Map();
643
+ const repairedToolsSet = new Set();
240
644
  const isGemini = normProvider === 'gemini';
241
645
  const isAnthropic = normProvider === 'anthropic';
242
646
  const isOllama = normProvider === 'ollama';
243
647
  const isAntigravity = normProvider === 'antigravity' || normProvider === 'agy';
244
- const isAcp = normProvider.startsWith('acp');
648
+ const isAcp = normProvider.startsWith('acp') || normProvider === 'pi';
245
649
  for (let index = 0; index < tools.length; index++) {
246
650
  const t = tools[index];
247
651
  if (!t)
248
652
  continue;
249
- const toolObj = (t.function ? t.function : t);
653
+ const toolObj = (isPlainObject(t.function) ? t.function : t);
250
654
  const name = normalizeToolName(toolObj.name);
655
+ const description = toolObj.description || `Tool ${name}`;
251
656
  if (!TOOL_NAME_REGEX.test(name)) {
252
657
  issues.push({
253
658
  tool: name,
@@ -267,75 +672,126 @@ export function scanAndAdaptToolsForProvider(tools, provider, options = {}) {
267
672
  });
268
673
  }
269
674
  const rawSchema = toolObj.parameters || toolObj.input_schema;
675
+ const rawIssueStart = issues.length;
270
676
  inspectSchemaForProvider(name, rawSchema, ['parameters'], normProvider, issues);
677
+ if (issues.length > rawIssueStart) {
678
+ repairedToolsSet.add(name);
679
+ }
680
+ const rewritten = [];
681
+ let adapted;
271
682
  if (isGemini) {
272
- const declaration = {
273
- name,
274
- description: toolObj.description || ''
275
- };
683
+ const declaration = { name, description };
276
684
  if (rawSchema && !isEmptyObjectSchema(rawSchema)) {
277
- const rewritten = [];
278
685
  declaration['parameters'] = adaptSchemaForGemini(rawSchema, [], rewritten);
279
- if (rewritten.length > 0) {
280
- freeFormPaths.set(name, rewritten);
281
- }
282
686
  }
283
- adaptedTools.push(declaration);
687
+ adapted = declaration;
284
688
  }
285
689
  else if (isAnthropic) {
286
690
  const deferLoading = Boolean(options.useToolSearch &&
287
691
  typeof options.coreToolCount === 'number' &&
288
692
  index >= options.coreToolCount);
289
- adaptedTools.push(adaptSchemaForAnthropic(toolObj, { deferLoading }));
693
+ adapted = adaptSchemaForAnthropic(toolObj, { deferLoading, rewritten });
290
694
  }
291
695
  else if (isOllama) {
292
- adaptedTools.push(adaptSchemaForOllama(toolObj));
696
+ adapted = adaptSchemaForOllama(toolObj, { rewritten });
293
697
  }
294
698
  else if (isAntigravity) {
295
- const cleanParams = cleanUnionTypes(rawSchema || { type: 'object', properties: {} });
296
- adaptedTools.push({
699
+ const cleanParams = compileSchemaNode(rawSchema || { type: 'object', properties: {} }, 'strict_json', [], rewritten, {}, new Set());
700
+ adapted = {
297
701
  name,
298
- description: toolObj.description || '',
702
+ description,
299
703
  parameters: cleanParams,
300
704
  snippet: `<tool_call>{"name": "${name}", "arguments": { ... }}</tool_call>`
301
- });
705
+ };
302
706
  }
303
707
  else if (isAcp) {
304
- const cleanParams = cleanUnionTypes(rawSchema || { type: 'object', properties: {} });
305
- adaptedTools.push({
708
+ const cleanParams = compileSchemaNode(rawSchema || { type: 'object', properties: {} }, 'strict_json', [], rewritten, {}, new Set());
709
+ adapted = {
306
710
  name,
307
- description: toolObj.description || '',
711
+ description,
308
712
  inputSchema: cleanParams
309
- });
713
+ };
310
714
  }
311
715
  else {
312
- // Default to OpenAI / OpenAI-Compatible (DeepSeek, XAI, Mistral, etc.)
313
- adaptedTools.push(adaptSchemaForOpenAI(toolObj));
716
+ adapted = adaptSchemaForOpenAI(toolObj, { rewritten });
717
+ }
718
+ if (rewritten.length > 0) {
719
+ freeFormPaths.set(name, rewritten);
720
+ repairedToolsSet.add(name);
721
+ }
722
+ adaptedTools.push(adapted);
723
+ // Post-adaptation verification (toolsScan closed-loop guarantee)
724
+ if (!TOOL_NAME_REGEX.test(name)) {
725
+ residualIssues.push({
726
+ tool: name,
727
+ path: 'name',
728
+ code: 'RESIDUAL_INVALID_TOOL_NAME',
729
+ message: `Adapted tool name "${name}" violates ^[a-zA-Z0-9_-]{1,64}$`,
730
+ severity: 'error'
731
+ });
732
+ }
733
+ const adaptedParams = extractAdaptedParameters(adapted, normProvider);
734
+ if (adaptedParams) {
735
+ inspectSchemaForProvider(name, adaptedParams, ['parameters'], normProvider, residualIssues);
314
736
  }
315
737
  }
316
738
  const incompatibleCount = issues.filter((i) => i.severity === 'error').length;
739
+ const residualIncompatibleCount = residualIssues.filter((i) => i.severity === 'error').length;
740
+ const repairedTools = Array.from(repairedToolsSet);
317
741
  return {
318
742
  provider: normProvider,
319
743
  totalTools: tools.length,
320
- compatibleTools: tools.length - incompatibleCount,
744
+ compatibleTools: Math.max(0, tools.length - incompatibleCount),
321
745
  incompatibleCount,
322
746
  issues,
747
+ residualIssues,
748
+ residualIncompatibleCount,
749
+ repairedTools,
750
+ repairedCount: repairedTools.length,
751
+ universalReady: residualIncompatibleCount === 0,
323
752
  adaptedTools,
324
753
  freeFormPaths
325
754
  };
326
755
  }
327
756
  /**
328
- * Decode free-form arguments that were stringified for Gemini back into native objects.
757
+ * Audit a full tool catalogue across all supported LLM providers offline (`toolsScan`).
758
+ */
759
+ export function scanAllProvidersCompatibility(tools, providers = ALL_PROVIDER_DIALECTS) {
760
+ const reports = {};
761
+ let allUniversalReady = true;
762
+ for (const provider of providers) {
763
+ const report = scanAndAdaptToolsForProvider(tools, provider);
764
+ reports[provider] = report;
765
+ if (!report.universalReady || report.adaptedTools.length !== tools.length) {
766
+ allUniversalReady = false;
767
+ }
768
+ }
769
+ return {
770
+ totalTools: tools.length,
771
+ providersScanned: providers.length,
772
+ allUniversalReady,
773
+ reports
774
+ };
775
+ }
776
+ /**
777
+ * Decode adapted free-form / polymorphic JSON string arguments back into native values.
778
+ * Only parses structured JSON containers ({...}, [...]) or quoted strings so plain filenames
779
+ * or text strings such as "index.html" or "42" are preserved intact.
329
780
  */
330
781
  export function decodeFreeFormArguments(args, paths) {
331
782
  if (!args || !paths || paths.length === 0)
332
783
  return args;
333
- for (const path of paths) {
334
- applyAtPath(args, path, (value) => {
784
+ for (const argPath of paths) {
785
+ applyAtPath(args, argPath, (value) => {
335
786
  if (typeof value !== 'string')
336
787
  return value;
788
+ const trimmed = value.trim();
789
+ const isStructuredJson = (trimmed.startsWith('{') && trimmed.endsWith('}')) ||
790
+ (trimmed.startsWith('[') && trimmed.endsWith(']'));
791
+ if (!isStructuredJson)
792
+ return value;
337
793
  try {
338
- return JSON.parse(value);
794
+ return JSON.parse(trimmed);
339
795
  }
340
796
  catch {
341
797
  return value;