|
| 1 | +// packages/agentos/src/api/tool-adapter.ts |
| 2 | +import type { ITool, ToolExecutionResult, ToolExecutionContext, JSONSchemaObject } from '../core/tools/ITool.js'; |
| 3 | + |
| 4 | +export interface ToolDefinition { |
| 5 | + description?: string; |
| 6 | + parameters?: Record<string, unknown>; |
| 7 | + execute?: (args: any) => Promise<any>; |
| 8 | +} |
| 9 | + |
| 10 | +export type ToolDefinitionMap = Record<string, ToolDefinition | ITool>; |
| 11 | + |
| 12 | +/** |
| 13 | + * Adapts Zod schemas, JSON Schema objects, and ITool instances into ITool[]. |
| 14 | + */ |
| 15 | +export function adaptTools(tools: ToolDefinitionMap | undefined): ITool[] { |
| 16 | + if (!tools) return []; |
| 17 | + const result: ITool[] = []; |
| 18 | + |
| 19 | + for (const [name, def] of Object.entries(tools)) { |
| 20 | + // ITool pass-through (has inputSchema + execute as ITool signature) |
| 21 | + if ('inputSchema' in def && 'id' in def) { |
| 22 | + result.push(def as ITool); |
| 23 | + continue; |
| 24 | + } |
| 25 | + |
| 26 | + const td = def as ToolDefinition; |
| 27 | + let schema: JSONSchemaObject; |
| 28 | + |
| 29 | + if (td.parameters && '_def' in (td.parameters as any)) { |
| 30 | + // Zod schema — convert to JSON Schema |
| 31 | + try { |
| 32 | + const { zodToJsonSchema } = require('zod-to-json-schema') as any; |
| 33 | + schema = zodToJsonSchema(td.parameters) as JSONSchemaObject; |
| 34 | + } catch { |
| 35 | + // zod-to-json-schema not installed — use basic extraction |
| 36 | + schema = { type: 'object', properties: {} }; |
| 37 | + } |
| 38 | + } else { |
| 39 | + schema = (td.parameters ?? { type: 'object', properties: {} }) as JSONSchemaObject; |
| 40 | + } |
| 41 | + |
| 42 | + const executeFn = td.execute ?? (async () => ({ success: true })); |
| 43 | + |
| 44 | + result.push({ |
| 45 | + id: `${name}-v1`, |
| 46 | + name, |
| 47 | + displayName: name.replace(/([A-Z])/g, ' $1').replace(/^./, s => s.toUpperCase()).trim(), |
| 48 | + description: td.description ?? '', |
| 49 | + inputSchema: schema, |
| 50 | + hasSideEffects: false, |
| 51 | + async execute(args: any, _ctx: ToolExecutionContext): Promise<ToolExecutionResult> { |
| 52 | + try { |
| 53 | + const output = await executeFn(args); |
| 54 | + return { success: true, output }; |
| 55 | + } catch (err: any) { |
| 56 | + return { success: false, error: err?.message ?? String(err) }; |
| 57 | + } |
| 58 | + }, |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | + return result; |
| 63 | +} |
0 commit comments