@causyne/agent 1.13.0 → 1.14.0

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.
@@ -0,0 +1,451 @@
1
+ /**
2
+ * Causyne Agent — Universal Tool Scanner & Compatibility Layer (toolsScan)
3
+ *
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.
8
+ */
9
+
10
+ export interface ToolDefinition {
11
+ name: string;
12
+ description?: string;
13
+ parameters?: Record<string, unknown>;
14
+ input_schema?: Record<string, unknown>;
15
+ function?: {
16
+ name: string;
17
+ description?: string;
18
+ parameters?: Record<string, unknown>;
19
+ };
20
+ [key: string]: unknown;
21
+ }
22
+
23
+ export interface ToolScanIssue {
24
+ tool: string;
25
+ path: string;
26
+ code: string;
27
+ message: string;
28
+ severity: 'error' | 'warning' | 'info';
29
+ }
30
+
31
+ export interface ToolScanReport {
32
+ provider: string;
33
+ totalTools: number;
34
+ compatibleTools: number;
35
+ incompatibleCount: number;
36
+ issues: ToolScanIssue[];
37
+ adaptedTools: unknown[];
38
+ freeFormPaths: Map<string, string[][]>;
39
+ }
40
+
41
+ const FREE_FORM_NOTE = ' Pass this as a JSON object encoded in a string, for example {"key":"value"}.';
42
+ const TOOL_NAME_REGEX = /^[a-zA-Z0-9_-]{1,64}$/;
43
+
44
+ /**
45
+ * Standardize tool name to match the wire grammar [a-zA-Z0-9_-]{1,64}.
46
+ */
47
+ export function normalizeToolName(name: string): string {
48
+ return String(name || '').replace(/\./g, '_');
49
+ }
50
+
51
+ /**
52
+ * Check if a schema node represents an empty object with no properties declared.
53
+ */
54
+ export function isEmptyObjectSchema(schema: unknown): boolean {
55
+ if (!schema || typeof schema !== 'object') return false;
56
+ const s = schema as Record<string, unknown>;
57
+ return s['type'] === 'object' && (!s['properties'] || Object.keys(s['properties'] as object).length === 0);
58
+ }
59
+
60
+ /**
61
+ * Recursively inspect a schema for provider incompatibilities.
62
+ */
63
+ function inspectSchemaForProvider(
64
+ toolName: string,
65
+ schema: unknown,
66
+ path: string[],
67
+ provider: string,
68
+ issues: ToolScanIssue[]
69
+ ): void {
70
+ if (!schema || typeof schema !== 'object') return;
71
+ const s = schema as Record<string, unknown>;
72
+ const pathStr = path.join('.');
73
+
74
+ if (s['type'] === 'array' && !s['items']) {
75
+ issues.push({
76
+ tool: toolName,
77
+ path: pathStr,
78
+ code: 'ARRAY_MISSING_ITEMS',
79
+ message: `Array schema at '${pathStr}' lacks 'items' definition.`,
80
+ severity: 'error'
81
+ });
82
+ }
83
+
84
+ if (Array.isArray(s['type'])) {
85
+ issues.push({
86
+ tool: toolName,
87
+ path: pathStr,
88
+ code: 'UNION_TYPE_ARRAY',
89
+ message: `Union type array [${(s['type'] as string[]).join(', ')}] at '${pathStr}' is unsupported by OpenAPI 3.0 / Gemini / DeepSeek.`,
90
+ severity: 'warning'
91
+ });
92
+ }
93
+
94
+ if (provider === 'gemini') {
95
+ if ('additionalProperties' in s) {
96
+ issues.push({
97
+ tool: toolName,
98
+ path: pathStr,
99
+ code: 'GEMINI_ADDITIONAL_PROPERTIES',
100
+ message: `'additionalProperties' at '${pathStr}' is forbidden in Gemini OpenAPI 3.0 subset.`,
101
+ severity: 'error'
102
+ });
103
+ }
104
+
105
+ if (s['type'] === 'object' && (!s['properties'] || Object.keys(s['properties'] as object).length === 0)) {
106
+ issues.push({
107
+ tool: toolName,
108
+ path: pathStr,
109
+ code: 'GEMINI_EMPTY_OBJECT_SCHEMA',
110
+ message: `Empty object schema at '${pathStr}' without declared properties is rejected by Gemini.`,
111
+ severity: 'error'
112
+ });
113
+ }
114
+
115
+ if ('$ref' in s || 'definitions' in s || 'patternProperties' in s) {
116
+ issues.push({
117
+ tool: toolName,
118
+ path: pathStr,
119
+ code: 'GEMINI_UNSUPPORTED_KEYWORDS',
120
+ message: `Unsupported JSON Schema keyword at '${pathStr}' in Gemini.`,
121
+ severity: 'warning'
122
+ });
123
+ }
124
+ }
125
+
126
+ if (s['properties'] && typeof s['properties'] === 'object') {
127
+ for (const [propKey, propVal] of Object.entries(s['properties'] as Record<string, unknown>)) {
128
+ inspectSchemaForProvider(toolName, propVal, [...path, propKey], provider, issues);
129
+ }
130
+ }
131
+
132
+ if (s['items'] && typeof s['items'] === 'object') {
133
+ inspectSchemaForProvider(toolName, s['items'], [...path, '[]'], provider, issues);
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Adapt a schema into Gemini's strict OpenAPI 3.0 subset without losing capability.
139
+ * Free-form objects are converted to stringified JSON schemas and recorded.
140
+ */
141
+ export function adaptSchemaForGemini(
142
+ schema: unknown,
143
+ path: string[],
144
+ rewritten: string[][]
145
+ ): Record<string, unknown> | unknown[] | unknown {
146
+ if (Array.isArray(schema)) {
147
+ return schema.map((entry: unknown) => adaptSchemaForGemini(entry, path, rewritten));
148
+ }
149
+ if (schema === null || typeof schema !== 'object') {
150
+ return schema;
151
+ }
152
+
153
+ const s = schema as Record<string, unknown>;
154
+ const adapted: Record<string, unknown> = {};
155
+
156
+ for (const [key, value] of Object.entries(s)) {
157
+ // 1. Strip additionalProperties (strictly rejected by Gemini)
158
+ if (key === 'additionalProperties') continue;
159
+
160
+ // 2. Strip unsupported keywords in Gemini OpenAPI
161
+ if (key === '$ref' || key === 'definitions' || key === 'patternProperties') continue;
162
+
163
+ // 3. Handle union types (e.g. type: ["string", "number"])
164
+ if (key === 'type' && Array.isArray(value)) {
165
+ const types = value as string[];
166
+ const safeType = types.find((t) => t !== 'null') || 'string';
167
+ adapted['type'] = safeType;
168
+ if (!adapted['description'] && s['description']) {
169
+ adapted['description'] = `${s['description']} (accepts ${types.join(' or ')})`;
170
+ }
171
+ continue;
172
+ }
173
+
174
+ // 4. Handle nested properties
175
+ if (key === 'properties' && value && typeof value === 'object') {
176
+ const properties: Record<string, unknown> = {};
177
+ for (const [name, child] of Object.entries(value as Record<string, unknown>)) {
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
+ }
189
+ }
190
+ adapted['properties'] = properties;
191
+ continue;
192
+ }
193
+
194
+ // 5. Handle array items
195
+ if (key === 'items') {
196
+ adapted['items'] = adaptSchemaForGemini(value, [...path, '[]'], rewritten);
197
+ continue;
198
+ }
199
+
200
+ adapted[key] = adaptSchemaForGemini(value, path, rewritten);
201
+ }
202
+
203
+ return adapted;
204
+ }
205
+
206
+ /**
207
+ * Adapt a tool schema into Anthropic's Messages API format.
208
+ */
209
+ export function adaptSchemaForAnthropic(
210
+ toolObj: ToolDefinition,
211
+ options: { deferLoading?: boolean } = {}
212
+ ): Record<string, unknown> {
213
+ const rawParams = toolObj.parameters || toolObj.input_schema || {};
214
+ let schema = typeof rawParams === 'object' && rawParams !== null ? { ...rawParams } : { type: 'object', properties: {} };
215
+
216
+ if (schema.type !== 'object') {
217
+ schema = { type: 'object', properties: {} };
218
+ }
219
+ if (!schema.properties) {
220
+ schema.properties = {};
221
+ }
222
+
223
+ // Handle union types for clean typing
224
+ const cleanSchema = cleanUnionTypes(schema);
225
+
226
+ const declaration: Record<string, unknown> = {
227
+ name: normalizeToolName(toolObj.name),
228
+ description: toolObj.description || '',
229
+ input_schema: cleanSchema
230
+ };
231
+
232
+ if (options.deferLoading) {
233
+ declaration['defer_loading'] = true;
234
+ }
235
+
236
+ return declaration;
237
+ }
238
+
239
+ /**
240
+ * Adapt a tool schema into OpenAI / OpenAI-Compatible (DeepSeek, XAI, Mistral, etc.) format.
241
+ */
242
+ export function adaptSchemaForOpenAI(
243
+ toolObj: ToolDefinition
244
+ ): { type: 'function'; function: { name: string; description: string; parameters: Record<string, unknown> } } {
245
+ const rawParams = toolObj.parameters || toolObj.input_schema || {};
246
+ let parameters = typeof rawParams === 'object' && rawParams !== null ? { ...rawParams } : { type: 'object', properties: {} };
247
+
248
+ if (parameters.type !== 'object') {
249
+ parameters = { type: 'object', properties: {} };
250
+ }
251
+ if (!parameters.properties) {
252
+ parameters.properties = {};
253
+ }
254
+
255
+ const cleanParams = cleanUnionTypes(parameters) as Record<string, unknown>;
256
+
257
+ return {
258
+ type: 'function',
259
+ function: {
260
+ name: normalizeToolName(toolObj.name),
261
+ description: toolObj.description || '',
262
+ parameters: cleanParams
263
+ }
264
+ };
265
+ }
266
+
267
+ /**
268
+ * Adapt a tool schema into Ollama format (clean, straightforward parameters).
269
+ */
270
+ export function adaptSchemaForOllama(
271
+ toolObj: ToolDefinition
272
+ ): { type: 'function'; function: { name: string; description: string; parameters: Record<string, unknown> } } {
273
+ return adaptSchemaForOpenAI(toolObj);
274
+ }
275
+
276
+ /**
277
+ * Replaces union type arrays with single safe base types for providers that reject union types.
278
+ */
279
+ function cleanUnionTypes(schema: unknown): unknown {
280
+ if (Array.isArray(schema)) {
281
+ return schema.map(cleanUnionTypes);
282
+ }
283
+ if (!schema || typeof schema !== 'object') {
284
+ return schema;
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;
309
+ }
310
+
311
+ /**
312
+ * Scans a set of tool definitions for compatibility with a specific provider,
313
+ * and generates adapted definitions that are 100% compliant.
314
+ */
315
+ export function scanAndAdaptToolsForProvider(
316
+ tools: ToolDefinition[],
317
+ provider: string,
318
+ options: {
319
+ coreToolCount?: number;
320
+ useToolSearch?: boolean;
321
+ } = {}
322
+ ): ToolScanReport {
323
+ const normProvider = provider.toLowerCase();
324
+ const issues: ToolScanIssue[] = [];
325
+ const adaptedTools: unknown[] = [];
326
+ const freeFormPaths = new Map<string, string[][]>();
327
+
328
+ const isGemini = normProvider === 'gemini';
329
+ const isAnthropic = normProvider === 'anthropic';
330
+ const isOllama = normProvider === 'ollama';
331
+
332
+ for (let index = 0; index < tools.length; index++) {
333
+ const t = tools[index];
334
+ if (!t) continue;
335
+ const toolObj = (t.function ? t.function : t) as ToolDefinition;
336
+ const name = normalizeToolName(toolObj.name);
337
+
338
+ if (!TOOL_NAME_REGEX.test(name)) {
339
+ issues.push({
340
+ tool: name,
341
+ path: 'name',
342
+ code: 'INVALID_TOOL_NAME',
343
+ message: `Tool name "${name}" violates grammar ^[a-zA-Z0-9_-]{1,64}$`,
344
+ severity: 'error'
345
+ });
346
+ }
347
+
348
+ if (!toolObj.description) {
349
+ issues.push({
350
+ tool: name,
351
+ path: 'description',
352
+ code: 'MISSING_TOOL_DESCRIPTION',
353
+ message: `Tool "${name}" is missing a description.`,
354
+ severity: 'warning'
355
+ });
356
+ }
357
+
358
+ const rawSchema = toolObj.parameters || toolObj.input_schema;
359
+ inspectSchemaForProvider(name, rawSchema, ['parameters'], normProvider, issues);
360
+
361
+ if (isGemini) {
362
+ const declaration: Record<string, unknown> = {
363
+ name,
364
+ description: toolObj.description || ''
365
+ };
366
+
367
+ if (rawSchema && !isEmptyObjectSchema(rawSchema)) {
368
+ const rewritten: string[][] = [];
369
+ declaration['parameters'] = adaptSchemaForGemini(rawSchema, [], rewritten);
370
+ if (rewritten.length > 0) {
371
+ freeFormPaths.set(name, rewritten);
372
+ }
373
+ }
374
+ adaptedTools.push(declaration);
375
+ } else if (isAnthropic) {
376
+ const deferLoading = Boolean(
377
+ options.useToolSearch &&
378
+ typeof options.coreToolCount === 'number' &&
379
+ index >= options.coreToolCount
380
+ );
381
+ adaptedTools.push(adaptSchemaForAnthropic(toolObj, { deferLoading }));
382
+ } else if (isOllama) {
383
+ adaptedTools.push(adaptSchemaForOllama(toolObj));
384
+ } else {
385
+ // Default to OpenAI / OpenAI-Compatible (DeepSeek, XAI, Mistral, etc.)
386
+ adaptedTools.push(adaptSchemaForOpenAI(toolObj));
387
+ }
388
+ }
389
+
390
+ const incompatibleCount = issues.filter((i) => i.severity === 'error').length;
391
+
392
+ return {
393
+ provider: normProvider,
394
+ totalTools: tools.length,
395
+ compatibleTools: tools.length - incompatibleCount,
396
+ incompatibleCount,
397
+ issues,
398
+ adaptedTools,
399
+ freeFormPaths
400
+ };
401
+ }
402
+
403
+ /**
404
+ * Decode free-form arguments that were stringified for Gemini back into native objects.
405
+ */
406
+ export function decodeFreeFormArguments(
407
+ args: Record<string, unknown>,
408
+ paths: string[][]
409
+ ): Record<string, unknown> {
410
+ if (!args || !paths || paths.length === 0) return args;
411
+
412
+ for (const path of paths) {
413
+ applyAtPath(args, path, (value: unknown) => {
414
+ if (typeof value !== 'string') return value;
415
+ try {
416
+ return JSON.parse(value);
417
+ } catch {
418
+ return value;
419
+ }
420
+ });
421
+ }
422
+
423
+ return args;
424
+ }
425
+
426
+ function applyAtPath(
427
+ node: unknown,
428
+ path: string[],
429
+ transform: (val: unknown) => unknown
430
+ ): void {
431
+ if (node === null || typeof node !== 'object') return;
432
+ const target = node as Record<string, unknown>;
433
+
434
+ const [head, ...rest] = path;
435
+ if (!head) return;
436
+
437
+ if (head === '[]') {
438
+ if (!Array.isArray(node)) return;
439
+ for (const entry of node) applyAtPath(entry, rest, transform);
440
+ return;
441
+ }
442
+
443
+ if (rest.length === 0) {
444
+ if (head in target) {
445
+ target[head] = transform(target[head]);
446
+ }
447
+ return;
448
+ }
449
+
450
+ applyAtPath(target[head], rest, transform);
451
+ }