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