@robota-sdk/agent-tools 3.0.0-beta.62 → 3.0.0-beta.64

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.
@@ -1,142 +1,136 @@
1
- import { IToolRegistry, ITool, IToolSchema, TToolParameters, TUniversalValue, IFunctionTool, TToolExecutor, IEventService, IToolExecutionContext, IToolResult, IParameterValidationResult, IOpenAPIToolConfig } from '@robota-sdk/agent-core';
1
+ import { IEventService, IFunctionTool, IOpenAPIToolConfig, IParameterValidationResult, ITool, IToolExecutionContext, IToolRegistry, IToolResult, IToolSchema, TToolExecutor, TToolParameters, TUniversalValue } from "@robota-sdk/agent-core";
2
2
 
3
+ //#region src/types/tool-result.d.ts
3
4
  /**
4
5
  * Result returned by a CLI tool invocation
5
6
  */
6
7
  interface TToolResult {
7
- success: boolean;
8
- output: string;
9
- error?: string;
10
- exitCode?: number;
11
- /** Start line number of the edit in the original file (Edit tool only) */
12
- startLine?: number;
8
+ success: boolean;
9
+ output: string;
10
+ error?: string;
11
+ exitCode?: number;
12
+ /** Start line number of the edit in the original file (Edit tool only) */
13
+ startLine?: number;
13
14
  }
14
-
15
+ //#endregion
16
+ //#region src/registry/tool-registry.d.ts
15
17
  /**
16
18
  * Tool registry implementation
17
19
  * Manages tool registration, validation, and retrieval
18
20
  */
19
21
  declare class ToolRegistry implements IToolRegistry {
20
- private tools;
21
- /**
22
- * Register a tool
23
- */
24
- register(tool: ITool): void;
25
- /**
26
- * Unregister a tool
27
- */
28
- unregister(name: string): void;
29
- /**
30
- * Get tool by name
31
- */
32
- get(name: string): ITool | undefined;
33
- /**
34
- * Get all registered tools
35
- */
36
- getAll(): ITool[];
37
- /**
38
- * Get tool schemas
39
- */
40
- getSchemas(): IToolSchema[];
41
- /**
42
- * Check if tool exists
43
- */
44
- has(name: string): boolean;
45
- /**
46
- * Clear all tools
47
- */
48
- clear(): void;
49
- /**
50
- * Get tool names
51
- */
52
- getToolNames(): string[];
53
- /**
54
- * Get tools by pattern
55
- */
56
- getToolsByPattern(pattern: string | RegExp): ITool[];
57
- /**
58
- * Get tool count
59
- */
60
- size(): number;
61
- /**
62
- * Validate tool schema
63
- */
64
- private validateToolSchema;
22
+ private tools;
23
+ /**
24
+ * Register a tool
25
+ */
26
+ register(tool: ITool): void;
27
+ /**
28
+ * Unregister a tool
29
+ */
30
+ unregister(name: string): void;
31
+ /**
32
+ * Get tool by name
33
+ */
34
+ get(name: string): ITool | undefined;
35
+ /**
36
+ * Get all registered tools
37
+ */
38
+ getAll(): ITool[];
39
+ /**
40
+ * Get tool schemas
41
+ */
42
+ getSchemas(): IToolSchema[];
43
+ /**
44
+ * Check if tool exists
45
+ */
46
+ has(name: string): boolean;
47
+ /**
48
+ * Clear all tools
49
+ */
50
+ clear(): void;
51
+ /**
52
+ * Get tool names
53
+ */
54
+ getToolNames(): string[];
55
+ /**
56
+ * Get tools by pattern
57
+ */
58
+ getToolsByPattern(pattern: string | RegExp): ITool[];
59
+ /**
60
+ * Get tool count
61
+ */
62
+ size(): number;
63
+ /**
64
+ * Validate tool schema
65
+ */
66
+ private validateToolSchema;
65
67
  }
66
-
67
- /**
68
- * FunctionTool - Type definitions for Facade pattern implementation
69
- *
70
- * REASON: Complex Zod schema type compatibility requires separation of concerns
71
- * ALTERNATIVES_CONSIDERED:
72
- * 1. Fix all Zod undefined issues in single file (creates maintenance burden)
73
- * 2. Use any types strategically (reduces type safety)
74
- * 3. Remove Zod support entirely (breaks existing functionality)
75
- * 4. Create complex conditional types (adds cognitive overhead)
76
- * 5. Use type assertions everywhere (increases runtime risk)
77
- * NOTE: Tool functionality is now integrated into @robota-sdk/agent-tools package
78
- */
79
-
68
+ //#endregion
69
+ //#region src/implementations/function-tool/types.d.ts
80
70
  /**
81
71
  * Zod schema compatibility types
72
+ *
73
+ * Widened to `unknown` so that actual Zod schemas (ZodObject<...>) are structurally
74
+ * assignable without `as unknown as IZodSchema` casts at call sites.
82
75
  */
83
76
  interface IZodParseResult {
84
- success: boolean;
85
- data?: TToolParameters;
86
- error?: string | Error;
77
+ success: boolean;
78
+ data?: unknown;
79
+ error?: unknown;
87
80
  }
88
81
  interface IZodSchemaDef {
89
- typeName?: string;
90
- innerType?: IZodSchema;
91
- valueType?: IZodSchema;
92
- checks?: Array<{
93
- kind: string;
94
- value?: TUniversalValue;
95
- }>;
96
- shape?: () => Record<string, IZodSchema>;
97
- type?: IZodSchema;
98
- values?: TUniversalValue[];
99
- description?: string;
100
- unknownKeys?: 'passthrough' | 'strip' | 'strict';
82
+ typeName?: string;
83
+ innerType?: IZodSchema;
84
+ valueType?: IZodSchema;
85
+ checks?: Array<{
86
+ kind: string;
87
+ value?: TUniversalValue;
88
+ }>;
89
+ shape?: () => Record<string, IZodSchema>;
90
+ type?: IZodSchema;
91
+ values?: TUniversalValue[];
92
+ description?: string;
93
+ unknownKeys?: 'passthrough' | 'strip' | 'strict';
101
94
  }
102
95
  interface IZodSchema {
103
- parse(value: TToolParameters): TToolParameters;
104
- safeParse(value: TToolParameters): IZodParseResult;
105
- _def?: IZodSchemaDef;
96
+ parse(value: unknown): unknown;
97
+ safeParse(value: unknown): IZodParseResult;
98
+ _def?: IZodSchemaDef;
106
99
  }
107
100
  /**
108
101
  * Parameter type validation options
109
102
  */
110
103
  interface IFunctionToolValidationOptions {
111
- strict?: boolean;
112
- allowUnknown?: boolean;
113
- validateTypes?: boolean;
104
+ strict?: boolean;
105
+ allowUnknown?: boolean;
106
+ validateTypes?: boolean;
114
107
  }
115
108
  /**
116
109
  * Schema conversion options
117
110
  */
118
111
  interface ISchemaConversionOptions {
119
- includeDescription?: boolean;
120
- strictTypes?: boolean;
121
- allowAdditionalProperties?: boolean;
112
+ includeDescription?: boolean;
113
+ strictTypes?: boolean;
114
+ allowAdditionalProperties?: boolean;
122
115
  }
123
116
  /**
124
117
  * Tool execution metadata
125
118
  */
126
119
  interface IFunctionToolExecutionMetadata {
127
- executionTime: number;
128
- toolName: string;
129
- parameters: TToolParameters;
120
+ executionTime: number;
121
+ toolName: string;
122
+ parameters: TToolParameters;
130
123
  }
131
124
  /**
132
125
  * Tool result with metadata
133
126
  */
134
127
  interface IFunctionToolResult {
135
- success: boolean;
136
- data: TUniversalValue;
137
- metadata?: IFunctionToolExecutionMetadata;
128
+ success: boolean;
129
+ data: TUniversalValue;
130
+ metadata?: IFunctionToolExecutionMetadata;
138
131
  }
139
-
132
+ //#endregion
133
+ //#region src/implementations/function-tool.d.ts
140
134
  /**
141
135
  * Function tool implementation
142
136
  * Wraps a JavaScript function as a tool with schema validation
@@ -145,40 +139,40 @@ interface IFunctionToolResult {
145
139
  * circular runtime dependency (tools → agents → tools).
146
140
  */
147
141
  declare class FunctionTool implements IFunctionTool {
148
- readonly schema: IToolSchema;
149
- readonly fn: TToolExecutor;
150
- private eventService;
151
- constructor(schema: IToolSchema, fn: TToolExecutor);
152
- /**
153
- * Get tool name
154
- */
155
- getName(): string;
156
- /**
157
- * Set EventService for post-construction injection.
158
- * Accepts EventService as-is without transformation.
159
- * Caller is responsible for providing properly configured EventService.
160
- */
161
- setEventService(eventService: IEventService | undefined): void;
162
- /**
163
- * Execute the function tool
164
- */
165
- execute(parameters: TToolParameters, context?: IToolExecutionContext): Promise<IToolResult>;
166
- /**
167
- * Validate parameters (simple boolean result)
168
- */
169
- validate(parameters: TToolParameters): boolean;
170
- /**
171
- * Validate tool parameters with detailed result
172
- */
173
- validateParameters(parameters: TToolParameters): IParameterValidationResult;
174
- /**
175
- * Get tool description
176
- */
177
- getDescription(): string;
178
- /**
179
- * Validate constructor inputs
180
- */
181
- private validateConstructorInputs;
142
+ readonly schema: IToolSchema;
143
+ readonly fn: TToolExecutor;
144
+ private eventService;
145
+ constructor(schema: IToolSchema, fn: TToolExecutor);
146
+ /**
147
+ * Get tool name
148
+ */
149
+ getName(): string;
150
+ /**
151
+ * Set EventService for post-construction injection.
152
+ * Accepts EventService as-is without transformation.
153
+ * Caller is responsible for providing properly configured EventService.
154
+ */
155
+ setEventService(eventService: IEventService | undefined): void;
156
+ /**
157
+ * Execute the function tool
158
+ */
159
+ execute(parameters: TToolParameters, context?: IToolExecutionContext): Promise<IToolResult>;
160
+ /**
161
+ * Validate parameters (simple boolean result)
162
+ */
163
+ validate(parameters: TToolParameters): boolean;
164
+ /**
165
+ * Validate tool parameters with detailed result
166
+ */
167
+ validateParameters(parameters: TToolParameters): IParameterValidationResult;
168
+ /**
169
+ * Get tool description
170
+ */
171
+ getDescription(): string;
172
+ /**
173
+ * Validate constructor inputs
174
+ */
175
+ private validateConstructorInputs;
182
176
  }
183
177
  /**
184
178
  * Helper function to create a function tool from a simple function
@@ -188,7 +182,8 @@ declare function createFunctionTool(name: string, description: string, parameter
188
182
  * Helper function to create a function tool from Zod schema
189
183
  */
190
184
  declare function createZodFunctionTool(name: string, description: string, zodSchema: IZodSchema, fn: TToolExecutor): FunctionTool;
191
-
185
+ //#endregion
186
+ //#region src/implementations/openapi-tool.d.ts
192
187
  /**
193
188
  * OpenAPI tool implementation
194
189
  * Executes API calls based on OpenAPI 3.0 specifications
@@ -197,72 +192,61 @@ declare function createZodFunctionTool(name: string, description: string, zodSch
197
192
  * circular runtime dependency (tools → agents → tools).
198
193
  */
199
194
  declare class OpenAPITool implements ITool {
200
- readonly schema: IToolSchema;
201
- private readonly apiSpec;
202
- private readonly operationId;
203
- private readonly baseURL;
204
- private readonly config;
205
- private eventService;
206
- constructor(config: IOpenAPIToolConfig);
207
- /**
208
- * Execute the OpenAPI tool
209
- */
210
- execute(parameters: TToolParameters, context?: IToolExecutionContext): Promise<IToolResult>;
211
- /**
212
- * Validate tool parameters
213
- */
214
- validate(parameters: TToolParameters): boolean;
215
- /**
216
- * Validate tool parameters with detailed result
217
- */
218
- validateParameters(parameters: TToolParameters): IParameterValidationResult;
219
- /**
220
- * Get tool name
221
- */
222
- getName(): string;
223
- /**
224
- * Set EventService for post-construction injection.
225
- */
226
- setEventService(eventService: IEventService | undefined): void;
227
- /**
228
- * Get tool description
229
- */
230
- getDescription(): string;
231
- /**
232
- * Execute the actual API call
233
- * @private
234
- */
235
- private executeAPICall;
236
- /**
237
- * Build HTTP request configuration from OpenAPI operation and parameters
238
- */
239
- private buildRequestConfig;
240
- /**
241
- * Create tool schema from OpenAPI operation specification
242
- */
243
- private createSchemaFromOpenAPI;
195
+ readonly schema: IToolSchema;
196
+ private readonly apiSpec;
197
+ private readonly operationId;
198
+ private readonly baseURL;
199
+ private readonly config;
200
+ private eventService;
201
+ constructor(config: IOpenAPIToolConfig);
202
+ /**
203
+ * Execute the OpenAPI tool
204
+ */
205
+ execute(parameters: TToolParameters, context?: IToolExecutionContext): Promise<IToolResult>;
206
+ /**
207
+ * Validate tool parameters
208
+ */
209
+ validate(parameters: TToolParameters): boolean;
210
+ /**
211
+ * Validate tool parameters with detailed result
212
+ */
213
+ validateParameters(parameters: TToolParameters): IParameterValidationResult;
214
+ /**
215
+ * Get tool name
216
+ */
217
+ getName(): string;
218
+ /**
219
+ * Set EventService for post-construction injection.
220
+ */
221
+ setEventService(eventService: IEventService | undefined): void;
222
+ /**
223
+ * Get tool description
224
+ */
225
+ getDescription(): string;
226
+ /**
227
+ * Execute the actual API call
228
+ * @private
229
+ */
230
+ private executeAPICall;
231
+ /**
232
+ * Build HTTP request configuration from OpenAPI operation and parameters
233
+ */
234
+ private buildRequestConfig;
235
+ /**
236
+ * Create tool schema from OpenAPI operation specification
237
+ */
238
+ private createSchemaFromOpenAPI;
244
239
  }
245
240
  /**
246
241
  * Factory function to create OpenAPI tools from specification
247
242
  */
248
243
  declare function createOpenAPITool(config: IOpenAPIToolConfig): OpenAPITool;
249
-
250
- /**
251
- * FunctionTool - Schema conversion utilities for Facade pattern
252
- *
253
- * REASON: Complex Zod to JSON schema conversion requires isolated utility functions
254
- * ALTERNATIVES_CONSIDERED:
255
- * 1. Keep conversion logic in main class (violates single responsibility)
256
- * 2. Use third-party library (adds external dependency)
257
- * 3. Manual conversion each time (code duplication)
258
- * 4. Runtime type checking only (loses compile-time safety)
259
- * 5. Remove Zod support (breaks backward compatibility)
260
- * TODO: Consider caching conversion results for performance
261
- */
262
-
244
+ //#endregion
245
+ //#region src/implementations/function-tool/schema-converter.d.ts
263
246
  /**
264
247
  * Convert Zod schema to JSON Schema format with safe undefined handling
265
248
  */
266
249
  declare function zodToJsonSchema(schema: IZodSchema, options?: ISchemaConversionOptions): IToolSchema['parameters'];
267
-
250
+ //#endregion
268
251
  export { FunctionTool, type IFunctionToolExecutionMetadata, type IFunctionToolResult, type IFunctionToolValidationOptions, type ISchemaConversionOptions, type IZodParseResult, type IZodSchema, type IZodSchemaDef, OpenAPITool, type TToolResult, ToolRegistry, createFunctionTool, createOpenAPITool, createZodFunctionTool, zodToJsonSchema };
252
+ //# sourceMappingURL=browser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser.d.ts","names":[],"sources":["../../src/types/tool-result.ts","../../src/registry/tool-registry.ts","../../src/implementations/function-tool/types.ts","../../src/implementations/function-tool.ts","../../src/implementations/openapi-tool.ts","../../src/implementations/function-tool/schema-converter.ts"],"mappings":";;;;;;UAGiB,WAAA;EACf,OAAA;EACA,MAAA;EACA,KAAA;EACA,QAAA;EAFA;EAIA,SAAA;AAAA;;;;AANF;;;cCMa,YAAA,YAAwB,aAAA;EAAA,QAC3B,KAAA;EDLR;;;ECUA,QAAA,CAAS,IAAA,EAAM,KAAA;EDNN;AAAA;;ECmCT,UAAA,CAAW,IAAA;;AAnCb;;EAgDE,GAAA,CAAI,IAAA,WAAe,KAAA;EA1CJ;;;EAiDf,MAAA,CAAA,GAAU,KAAA;EAkD0B;;;EA3CpC,UAAA,CAAA,GAAc,WAAA;EA9DkC;;;EAkFhD,GAAA,CAAI,IAAA;EA5EW;;;EAmFf,KAAA,CAAA;EAzCA;;;EAkDA,YAAA,CAAA;EA3CU;;;EAkDV,iBAAA,CAAkB,OAAA,WAAkB,MAAA,GAAS,KAAA;EAvBzC;;;EA+BJ,IAAA,CAAA;EARoC;;;EAAA,QAe5B,kBAAA;AAA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BAkBM,kBAAA,CACd,IAAA,UACA,WAAA,UACA,UAAA,EAAY,WAAA,gBACZ,EAAA,EAAI,aAAA,GACH,YAAA;;;;iBAaa,qBAAA,CACd,IAAA,UACA,WAAA,UACA,SAAA,EAAW,UAAA,EACX,EAAA,EAAI,aAAA,GACH,YAAA;;;;AHpLH;;;;;;cIsBa,WAAA,YAAuB,KAAA;EAAA,SACzB,MAAA,EAAQ,WAAA;EAAA,iBACA,OAAA;EAAA,iBACA,WAAA;EAAA,iBACA,OAAA;EAAA,iBACA,MAAA;EAAA,QACT,YAAA;cAEI,MAAA,EAAQ,kBAAA;EHxBT;;;EG8CL,OAAA,CACJ,UAAA,EAAY,eAAA,EACZ,OAAA,GAAU,qBAAA,GACT,OAAA,CAAQ,WAAA;EHDQ;;;EGkDnB,QAAA,CAAS,UAAA,EAAY,eAAA;EHOwB;;;EGA7C,kBAAA,CAAmB,UAAA,EAAY,eAAA,GAAkB,0BAAA;EHzGd;;;EG4HnC,OAAA,CAAA;EHtHS;;;EG6HT,eAAA,CAAgB,YAAA,EAAc,aAAA;EHnF1B;;;EG0FJ,cAAA,CAAA;EH5EA;;;;EAAA,QGoFc,cAAA;EHhDd;;;EAAA,QGmEQ,kBAAA;EH5DqC;;;EAAA,QGqJrC,uBAAA;AAAA;;;;iBAgBM,iBAAA,CAAkB,MAAA,EAAQ,kBAAA,GAAqB,WAAW;;;;;;iBC/P1D,eAAA,CACd,MAAA,EAAQ,UAAA,EACR,OAAA,GAAS,wBAAA,GACR,WAAA"}
@@ -1 +1,2 @@
1
- import {ValidationError,logger,ToolExecutionError}from'@robota-sdk/agent-core';var S=class{tools=new Map;register(e){if(!e.schema?.name)throw new ValidationError("Tool must have a valid schema with name");let t=e.schema.name;this.validateToolSchema(e.schema),this.tools.has(t)&&logger.warn(`Tool "${t}" is already registered, overriding`,{toolName:t,existingTool:this.tools.get(t)?.constructor.name}),this.tools.set(t,e),logger.debug(`Tool "${t}" registered successfully`,{toolName:t,toolType:e.constructor.name,parameters:Object.keys(e.schema.parameters?.properties||{})});}unregister(e){if(!this.tools.has(e)){logger.warn(`Attempted to unregister non-existent tool "${e}"`);return}this.tools.delete(e),logger.debug(`Tool "${e}" unregistered successfully`);}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSchemas(){let e=this.getAll();return logger.debug("[TOOL-FLOW] ToolRegistry.getSchemas() - Tools before schema extraction",{count:e.length,tools:e.map(t=>({name:t.schema?.name??"unnamed",hasSchema:!!t.schema,schemaType:typeof t.schema,toolType:t.constructor?.name||"unknown"}))}),this.getAll().map(t=>t.schema)}has(e){return this.tools.has(e)}clear(){let e=this.tools.size;this.tools.clear(),logger.debug(`Cleared ${e} tools from registry`);}getToolNames(){return Array.from(this.tools.keys())}getToolsByPattern(e){let t=typeof e=="string"?new RegExp(e):e;return this.getAll().filter(o=>t.test(o.schema.name))}size(){return this.tools.size}validateToolSchema(e){if(!e.name||typeof e.name!="string")throw new ValidationError("Tool schema must have a valid name");if(!e.description||typeof e.description!="string")throw new ValidationError("Tool schema must have a description");if(!e.parameters||typeof e.parameters!="object"||e.parameters===null||Array.isArray(e.parameters))throw new ValidationError("Tool schema must have parameters object");if(e.parameters.type!=="object")throw new ValidationError('Tool parameters type must be "object"');if(e.parameters.properties)for(let t of Object.keys(e.parameters.properties)){let o=e.parameters.properties[t];if(!o?.type)throw new ValidationError(`Parameter "${t}" must have a type`);if(!["string","number","boolean","array","object"].includes(o.type))throw new ValidationError(`Parameter "${t}" has invalid type "${o.type}"`)}if(e.parameters.required){let t=e.parameters.properties||{};for(let o of e.parameters.required)if(!t[o])throw new ValidationError(`Required parameter "${o}" is not defined in properties`)}}};function v(r,e={}){let t={},o=[],n=r._def;if(!n)throw new Error("Zod schema is missing _def; cannot convert to JSON schema.");if(n.typeName==="ZodObject"&&n.shape){let a=typeof n.shape=="function"?n.shape():n.shape;for(let[s,i]of Object.entries(a)){let c=f(i);t[s]=c,Z(i)&&o.push(s);}}return {type:"object",properties:t,required:o,...(e.allowAdditionalProperties||n.unknownKeys==="passthrough")&&{additionalProperties:true}}}function f(r){let e=r._def;if(!e)throw new Error("Zod type is missing _def; cannot convert to JSON schema.");let t={};switch(e.description&&(t.description=e.description),e.typeName){case "ZodString":return {type:"string",...t};case "ZodNumber":return {type:"number",...t};case "ZodBoolean":return {type:"boolean",...t};case "ZodArray":{if(!e.type)throw new Error("ZodArray is missing item type; cannot convert to JSON schema.");return {type:"array",items:f(e.type),...t}}case "ZodObject":return {type:"object",...t};case "ZodEnum":{let o=e.values;if(!o||!Array.isArray(o))throw new Error("ZodEnum is missing enum values; cannot convert to JSON schema.");return {type:"string",enum:o,...t}}case "ZodOptional":if(e.innerType)return {...f(e.innerType),...t};throw new Error("ZodOptional is missing innerType; cannot convert to JSON schema.");case "ZodNullable":if(e.innerType)return {...f(e.innerType),...t};throw new Error("ZodNullable is missing innerType; cannot convert to JSON schema.");case "ZodDefault":if(e.innerType)return {...f(e.innerType),...t};throw new Error("ZodDefault is missing innerType; cannot convert to JSON schema.");case "ZodRecord":return e.valueType?{type:"object",additionalProperties:f(e.valueType),...t}:{type:"object",additionalProperties:{type:"string"},...t};default:throw new Error(`Unsupported Zod type: ${String(e.typeName)}`)}}function Z(r){let e=r._def;if(!e)throw new Error("Zod schema is missing _def; cannot determine required fields.");return e.typeName!=="ZodOptional"&&e.typeName!=="ZodNullable"&&e.typeName!=="ZodDefault"}function w(r,e,t){switch(t.type){case "string":if(typeof e!="string")return `Parameter "${r}" must be a string, got ${typeof e}`;break;case "number":if(typeof e!="number"||isNaN(e))return `Parameter "${r}" must be a number, got ${typeof e}`;break;case "boolean":if(typeof e!="boolean")return `Parameter "${r}" must be a boolean, got ${typeof e}`;break;case "array":if(!Array.isArray(e))return `Parameter "${r}" must be an array, got ${typeof e}`;if(t.items)for(let n=0;n<e.length;n++){let a=w(`${r}[${n}]`,e[n],t.items);if(a)return a}break;case "object":if(typeof e!="object"||e===null||Array.isArray(e))return `Parameter "${r}" must be an object, got ${typeof e}`;break}if(t.enum&&t.enum.length>0){let n=t.enum,a=false;for(let s of n)if(e===s){a=true;break}if(!a)return `Parameter "${r}" must be one of: ${n.join(", ")}, got ${e}`}}function I(r,e,t,o){let n=[];for(let a of e)a in r||n.push(`Missing required parameter: ${a}`);for(let[a,s]of Object.entries(r)){let i=t[a];if(!i){if(o===true)continue;if(o&&typeof o=="object"){let p=w(a,s,o);p&&n.push(p);continue}n.push(`Unknown parameter: ${a}`);continue}let c=w(a,s,i);c&&n.push(c);}return n}function E(r,e,t,o){let n=I(r,e,t,o);return {isValid:n.length===0,errors:n}}var T=class{schema;fn;eventService;constructor(e,t){this.schema=e,this.fn=t,this.validateConstructorInputs();}getName(){return this.schema.name}setEventService(e){this.eventService=e;}async execute(e,t){let o=this.schema.name;if(!this.validate(e)){let i=I(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties);throw new ValidationError(`Invalid parameters for tool "${o}": ${i.join(", ")}`)}let n=Date.now(),a;try{a=await this.fn(e,t);}catch(i){throw i instanceof ToolExecutionError||i instanceof ValidationError?i:new ToolExecutionError(`Function tool execution failed: ${i instanceof Error?i.message:String(i)}`,o,i instanceof Error?i:new Error(String(i)),{parameterCount:Object.keys(e||{}).length,hasContext:!!t})}let s=Date.now()-n;return {success:true,data:a,metadata:{executionTime:s,toolName:o,parameters:e}}}validate(e){return I(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties).length===0}validateParameters(e){return E(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties)}getDescription(){return this.schema.description}validateConstructorInputs(){if(!this.schema)throw new ValidationError("Tool schema is required");if(!this.fn||typeof this.fn!="function")throw new ValidationError("Tool function is required and must be a function");if(!this.schema.name)throw new ValidationError("Tool schema must have a name")}};function N(r,e,t,o){let n={name:r,description:e,parameters:t};return new T(n,o)}function C(r,e,t,o){let n=v(t),a={name:r,description:e,parameters:n},s=async(i,c)=>{let p=t.safeParse(i);if(!p.success)throw new ValidationError(`Zod validation failed: ${p.error}`);let d=await o(p.data||i,c);return typeof d=="string"?d:JSON.stringify(d)};return new T(a,s)}var k=["get","post","put","delete","patch","head","options"];function O(r,e){for(let[t,o]of Object.entries(r.paths||{}))if(o)for(let n of k){let a=o[n];if(a?.operationId===e)return {method:n,path:t,operation:a}}}function U(r){switch(r){case "string":return "string";case "number":return "number";case "integer":return "integer";case "boolean":return "boolean";case "array":return "array";case "object":return "object";default:return "string"}}function P(r){if("$ref"in r)return {type:"object"};let e={type:U(r.type)};if(r.description&&(e.description=r.description),r.enum&&(e.enum=r.enum),r.minimum!==void 0&&(e.minimum=r.minimum),r.maximum!==void 0&&(e.maximum=r.maximum),r.pattern&&(e.pattern=r.pattern),r.format&&(e.format=r.format),r.default!==void 0&&(e.default=r.default),r.type==="array"&&r.items&&(e.items=P(r.items)),r.type==="object"&&r.properties){e.properties={};for(let[t,o]of Object.entries(r.properties))e.properties[t]=P(o);r.required&&r.required.length>0&&(e.required=r.required);}return e}function D(r){let e=r.schema;return P(e)}function j(r,e){let t={},o=[],n=e.parameters||[];for(let s of n)t[s.name]=D(s),s.required&&o.push(s.name);if(e.requestBody){let i=e.requestBody.content?.["application/json"];if(i?.schema){let c=P(i.schema);if(c.type==="object"&&c.properties){Object.assign(t,c.properties);let p=c;p.required&&o.push(...p.required);}}}let a={type:"object",properties:t};return o.length>0&&(a.required=o),{name:r,description:e.summary||e.description||`OpenAPI operation: ${r}`,parameters:a}}var b=class{schema;apiSpec;operationId;baseURL;config;eventService;constructor(e){if(this.config=e,typeof e.spec!="object"||e.spec===null||typeof e.spec.openapi!="string"||typeof e.spec.paths!="object")throw new Error('Invalid OpenAPI spec: must contain "openapi" (string) and "paths" (object) fields');this.apiSpec=e.spec,this.operationId=e.operationId,this.baseURL=e.baseURL,this.schema=this.createSchemaFromOpenAPI();}async execute(e,t){let o=this.schema.name,n=this.validateParameters(e);if(!n.isValid)throw new ValidationError(`Invalid parameters for OpenAPI tool "${o}": ${n.errors.join(", ")}`);try{let a=Date.now(),s=await this.executeAPICall(e,t),i=Date.now()-a;return {success:!0,data:s,metadata:{executionTime:i,toolName:o,operationId:this.operationId,baseURL:this.baseURL}}}catch(a){if(a instanceof ToolExecutionError||a instanceof ValidationError)throw a;let s=a instanceof Error?a:new Error(String(a));throw new ToolExecutionError(`OpenAPI tool execution failed: ${s.message}`,o,s,{operationId:this.operationId,baseURL:this.baseURL,parametersCount:Object.keys(e).length})}}validate(e){return this.validateParameters(e).isValid}validateParameters(e){let t=this.schema.parameters.required||[],o=[];for(let n of t)n in e||o.push(`Missing required parameter: ${n}`);return {isValid:o.length===0,errors:o}}getName(){return this.schema.name}setEventService(e){this.eventService=e;}getDescription(){return this.schema.description}async executeAPICall(e,t){let o=O(this.apiSpec,this.operationId);throw o?(this.buildRequestConfig(o,e),new Error("Not implemented: actual API execution is not yet available")):new Error(`Operation ${this.operationId} not found in OpenAPI spec`)}buildRequestConfig(e,t){let{method:o,path:n,operation:a}=e,s=this.baseURL+n,i={},c,p=a.parameters||[];for(let m of p){let l=t[m.name];if(l===void 0&&m.required)throw new Error(`Required parameter ${m.name} is missing`);if(l!==void 0)switch(m.in){case "path":s=s.replace(`{${m.name}}`,encodeURIComponent(String(l)));break;case "query":{let g=s.includes("?")?"&":"?";s+=`${g}${m.name}=${encodeURIComponent(String(l))}`;break}case "header":i[m.name]=String(l);break}}if(["post","put","patch"].includes(o)&&a.requestBody&&a.requestBody.content?.["application/json"]){i["Content-Type"]="application/json";let g={};for(let[x,$]of Object.entries(t))p.some(q=>q.name===x)||(g[x]=$);c=JSON.stringify(g);}if(this.config.auth)switch(this.config.auth.type){case "bearer":i.Authorization=`Bearer ${this.config.auth.token}`;break;case "apiKey":{let m=this.config.auth.header||"X-API-Key";i[m]=this.config.auth.apiKey||"";break}}let d={method:o,url:s,headers:i};return c!==void 0&&(d.body=c),d}createSchemaFromOpenAPI(){let e=O(this.apiSpec,this.operationId);if(!e)throw new Error(`[STRICT-POLICY][EMITTER-CONTRACT] OpenAPI operation not found: ${this.operationId}. Emitter contract must provide a valid operationId present in the OpenAPI document.`);return j(this.operationId,e.operation)}};function F(r){return new b(r)}export{T as FunctionTool,b as OpenAPITool,S as ToolRegistry,N as createFunctionTool,F as createOpenAPITool,C as createZodFunctionTool,v as zodToJsonSchema};
1
+ import{ToolExecutionError as e,ValidationError as t,logger as n}from"@robota-sdk/agent-core";var r=class{tools=new Map;register(e){if(!e.schema?.name)throw new t(`Tool must have a valid schema with name`);let r=e.schema.name;this.validateToolSchema(e.schema),this.tools.has(r)&&n.warn(`Tool "${r}" is already registered, overriding`,{toolName:r,existingTool:this.tools.get(r)?.constructor.name}),this.tools.set(r,e),n.debug(`Tool "${r}" registered successfully`,{toolName:r,toolType:e.constructor.name,parameters:Object.keys(e.schema.parameters?.properties||{})})}unregister(e){if(!this.tools.has(e)){n.warn(`Attempted to unregister non-existent tool "${e}"`);return}this.tools.delete(e),n.debug(`Tool "${e}" unregistered successfully`)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSchemas(){let e=this.getAll();return n.debug(`[TOOL-FLOW] ToolRegistry.getSchemas() - Tools before schema extraction`,{count:e.length,tools:e.map(e=>({name:e.schema?.name??`unnamed`,hasSchema:!!e.schema,schemaType:typeof e.schema,toolType:e.constructor?.name||`unknown`}))}),this.getAll().map(e=>e.schema)}has(e){return this.tools.has(e)}clear(){let e=this.tools.size;this.tools.clear(),n.debug(`Cleared ${e} tools from registry`)}getToolNames(){return Array.from(this.tools.keys())}getToolsByPattern(e){let t=typeof e==`string`?new RegExp(e):e;return this.getAll().filter(e=>t.test(e.schema.name))}size(){return this.tools.size}validateToolSchema(e){if(!e.name||typeof e.name!=`string`)throw new t(`Tool schema must have a valid name`);if(!e.description||typeof e.description!=`string`)throw new t(`Tool schema must have a description`);if(!e.parameters||typeof e.parameters!=`object`||e.parameters===null||Array.isArray(e.parameters))throw new t(`Tool schema must have parameters object`);if(e.parameters.type!==`object`)throw new t(`Tool parameters type must be "object"`);if(e.parameters.properties)for(let n of Object.keys(e.parameters.properties)){let r=e.parameters.properties[n];if(!r?.type)throw new t(`Parameter "${n}" must have a type`);if(![`string`,`number`,`boolean`,`array`,`object`].includes(r.type))throw new t(`Parameter "${n}" has invalid type "${r.type}"`)}if(e.parameters.required){let n=e.parameters.properties||{};for(let r of e.parameters.required)if(!n[r])throw new t(`Required parameter "${r}" is not defined in properties`)}}};function i(e,t={}){let n={},r=[],i=e._def;if(!i)throw Error(`Zod schema is missing _def; cannot convert to JSON schema.`);if(i.typeName===`ZodObject`&&i.shape){let e=typeof i.shape==`function`?i.shape():i.shape;for(let[t,i]of Object.entries(e))n[t]=a(i),o(i)&&r.push(t)}return{type:`object`,properties:n,required:r,...(t.allowAdditionalProperties||i.unknownKeys===`passthrough`)&&{additionalProperties:!0}}}function a(e){let t=e._def;if(!t)throw Error(`Zod type is missing _def; cannot convert to JSON schema.`);let n={};switch(t.description&&(n.description=t.description),t.typeName){case`ZodString`:return{type:`string`,...n};case`ZodNumber`:return{type:`number`,...n};case`ZodBoolean`:return{type:`boolean`,...n};case`ZodArray`:if(!t.type)throw Error(`ZodArray is missing item type; cannot convert to JSON schema.`);return{type:`array`,items:a(t.type),...n};case`ZodObject`:return{type:`object`,...n};case`ZodEnum`:{let e=t.values;if(!e||!Array.isArray(e))throw Error(`ZodEnum is missing enum values; cannot convert to JSON schema.`);return{type:`string`,enum:e,...n}}case`ZodOptional`:if(t.innerType)return{...a(t.innerType),...n};throw Error(`ZodOptional is missing innerType; cannot convert to JSON schema.`);case`ZodNullable`:if(t.innerType)return{...a(t.innerType),...n};throw Error(`ZodNullable is missing innerType; cannot convert to JSON schema.`);case`ZodDefault`:if(t.innerType)return{...a(t.innerType),...n};throw Error(`ZodDefault is missing innerType; cannot convert to JSON schema.`);case`ZodRecord`:return t.valueType?{type:`object`,additionalProperties:a(t.valueType),...n}:{type:`object`,additionalProperties:{type:`string`},...n};default:throw Error(`Unsupported Zod type: ${String(t.typeName)}`)}}function o(e){let t=e._def;if(!t)throw Error(`Zod schema is missing _def; cannot determine required fields.`);return t.typeName!==`ZodOptional`&&t.typeName!==`ZodNullable`&&t.typeName!==`ZodDefault`}function s(e,t,n){switch(n.type){case`string`:if(typeof t!=`string`)return`Parameter "${e}" must be a string, got ${typeof t}`;break;case`number`:if(typeof t!=`number`||isNaN(t))return`Parameter "${e}" must be a number, got ${typeof t}`;break;case`boolean`:if(typeof t!=`boolean`)return`Parameter "${e}" must be a boolean, got ${typeof t}`;break;case`array`:if(!Array.isArray(t))return`Parameter "${e}" must be an array, got ${typeof t}`;if(n.items)for(let r=0;r<t.length;r++){let i=s(`${e}[${r}]`,t[r],n.items);if(i)return i}break;case`object`:if(typeof t!=`object`||!t||Array.isArray(t))return`Parameter "${e}" must be an object, got ${typeof t}`;break}if(n.enum&&n.enum.length>0){let r=n.enum,i=!1;for(let e of r)if(t===e){i=!0;break}if(!i)return`Parameter "${e}" must be one of: ${r.join(`, `)}, got ${t}`}}function c(e,t,n,r){let i=[];for(let n of t)n in e||i.push(`Missing required parameter: ${n}`);for(let[t,a]of Object.entries(e)){let e=n[t];if(!e){if(r===!0)continue;if(r&&typeof r==`object`){let e=s(t,a,r);e&&i.push(e);continue}i.push(`Unknown parameter: ${t}`);continue}let o=s(t,a,e);o&&i.push(o)}return i}function l(e,t,n,r){let i=c(e,t,n,r);return{isValid:i.length===0,errors:i}}var u=class{schema;fn;eventService;constructor(e,t){this.schema=e,this.fn=t,this.validateConstructorInputs()}getName(){return this.schema.name}setEventService(e){this.eventService=e}async execute(n,r){let i=this.schema.name;if(!this.validate(n))throw new t(`Invalid parameters for tool "${i}": ${c(n,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties).join(`, `)}`);let a=Date.now(),o;try{o=await this.fn(n,r)}catch(a){throw a instanceof e||a instanceof t?a:new e(`Function tool execution failed: ${a instanceof Error?a.message:String(a)}`,i,a instanceof Error?a:Error(String(a)),{parameterCount:Object.keys(n||{}).length,hasContext:!!r})}let s=Date.now()-a;return{success:!0,data:o,metadata:{executionTime:s,toolName:i,parameters:n}}}validate(e){return c(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties).length===0}validateParameters(e){return l(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties)}getDescription(){return this.schema.description}validateConstructorInputs(){if(!this.schema)throw new t(`Tool schema is required`);if(!this.fn||typeof this.fn!=`function`)throw new t(`Tool function is required and must be a function`);if(!this.schema.name)throw new t(`Tool schema must have a name`)}};function d(e,t,n,r){return new u({name:e,description:t,parameters:n},r)}function f(e,n,r,a){return new u({name:e,description:n,parameters:i(r)},async(e,n)=>{let i=r.safeParse(e);if(!i.success)throw new t(`Zod validation failed: ${i.error}`);let o=await a(i.data||e,n);return typeof o==`string`?o:JSON.stringify(o)})}const p=[`get`,`post`,`put`,`delete`,`patch`,`head`,`options`];function m(e,t){for(let[n,r]of Object.entries(e.paths||{}))if(r)for(let e of p){let i=r[e];if(i?.operationId===t)return{method:e,path:n,operation:i}}}function h(e){switch(e){case`string`:return`string`;case`number`:return`number`;case`integer`:return`integer`;case`boolean`:return`boolean`;case`array`:return`array`;case`object`:return`object`;default:return`string`}}function g(e){if(`$ref`in e)return{type:`object`};let t={type:h(e.type)};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.default!==void 0&&(t.default=e.default),e.type===`array`&&e.items&&(t.items=g(e.items)),e.type===`object`&&e.properties){t.properties={};for(let[n,r]of Object.entries(e.properties))t.properties[n]=g(r);e.required&&e.required.length>0&&(t.required=e.required)}return t}function _(e){let t=e.schema;return g(t)}function v(e,t){let n={},r=[],i=t.parameters||[];for(let e of i)n[e.name]=_(e),e.required&&r.push(e.name);if(t.requestBody){let e=t.requestBody.content?.[`application/json`];if(e?.schema){let t=g(e.schema);if(t.type===`object`&&t.properties){Object.assign(n,t.properties);let e=t;e.required&&r.push(...e.required)}}}let a={type:`object`,properties:n};return r.length>0&&(a.required=r),{name:e,description:t.summary||t.description||`OpenAPI operation: ${e}`,parameters:a}}var y=class{schema;apiSpec;operationId;baseURL;config;eventService;constructor(e){if(this.config=e,typeof e.spec!=`object`||e.spec===null||typeof e.spec.openapi!=`string`||typeof e.spec.paths!=`object`)throw Error(`Invalid OpenAPI spec: must contain "openapi" (string) and "paths" (object) fields`);this.apiSpec=e.spec,this.operationId=e.operationId,this.baseURL=e.baseURL,this.schema=this.createSchemaFromOpenAPI()}async execute(n,r){let i=this.schema.name,a=this.validateParameters(n);if(!a.isValid)throw new t(`Invalid parameters for OpenAPI tool "${i}": ${a.errors.join(`, `)}`);try{let e=Date.now();return{success:!0,data:await this.executeAPICall(n,r),metadata:{executionTime:Date.now()-e,toolName:i,operationId:this.operationId,baseURL:this.baseURL}}}catch(r){if(r instanceof e||r instanceof t)throw r;let a=r instanceof Error?r:Error(String(r));throw new e(`OpenAPI tool execution failed: ${a.message}`,i,a,{operationId:this.operationId,baseURL:this.baseURL,parametersCount:Object.keys(n).length})}}validate(e){return this.validateParameters(e).isValid}validateParameters(e){let t=this.schema.parameters.required||[],n=[];for(let r of t)r in e||n.push(`Missing required parameter: ${r}`);return{isValid:n.length===0,errors:n}}getName(){return this.schema.name}setEventService(e){this.eventService=e}getDescription(){return this.schema.description}async executeAPICall(e,t){let n=m(this.apiSpec,this.operationId);throw n?(this.buildRequestConfig(n,e),Error(`Not implemented: actual API execution is not yet available`)):Error(`Operation ${this.operationId} not found in OpenAPI spec`)}buildRequestConfig(e,t){let{method:n,path:r,operation:i}=e,a=this.baseURL+r,o={},s,c=i.parameters||[];for(let e of c){let n=t[e.name];if(n===void 0&&e.required)throw Error(`Required parameter ${e.name} is missing`);if(n!==void 0)switch(e.in){case`path`:a=a.replace(`{${e.name}}`,encodeURIComponent(String(n)));break;case`query`:{let t=a.includes(`?`)?`&`:`?`;a+=`${t}${e.name}=${encodeURIComponent(String(n))}`;break}case`header`:o[e.name]=String(n);break}}if([`post`,`put`,`patch`].includes(n)&&i.requestBody&&i.requestBody.content?.[`application/json`]){o[`Content-Type`]=`application/json`;let e={};for(let[n,r]of Object.entries(t))c.some(e=>e.name===n)||(e[n]=r);s=JSON.stringify(e)}if(this.config.auth)switch(this.config.auth.type){case`bearer`:o.Authorization=`Bearer ${this.config.auth.token}`;break;case`apiKey`:{let e=this.config.auth.header||`X-API-Key`;o[e]=this.config.auth.apiKey||``;break}}let l={method:n,url:a,headers:o};return s!==void 0&&(l.body=s),l}createSchemaFromOpenAPI(){let e=m(this.apiSpec,this.operationId);if(!e)throw Error(`[STRICT-POLICY][EMITTER-CONTRACT] OpenAPI operation not found: ${this.operationId}. Emitter contract must provide a valid operationId present in the OpenAPI document.`);return v(this.operationId,e.operation)}};function b(e){return new y(e)}export{u as FunctionTool,y as OpenAPITool,r as ToolRegistry,d as createFunctionTool,b as createOpenAPITool,f as createZodFunctionTool,i as zodToJsonSchema};
2
+ //# sourceMappingURL=browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser.js","names":[],"sources":["../../src/registry/tool-registry.ts","../../src/implementations/function-tool/schema-converter.ts","../../src/implementations/function-tool/parameter-validator.ts","../../src/implementations/function-tool.ts","../../src/implementations/openapi-schema-converter.ts","../../src/implementations/openapi-tool.ts"],"sourcesContent":["import type { ITool, IToolRegistry } from '@robota-sdk/agent-core';\nimport type { IToolSchema } from '@robota-sdk/agent-core';\nimport { ValidationError } from '@robota-sdk/agent-core';\nimport { logger } from '@robota-sdk/agent-core';\n\n/**\n * Tool registry implementation\n * Manages tool registration, validation, and retrieval\n */\nexport class ToolRegistry implements IToolRegistry {\n private tools = new Map<string, ITool>();\n\n /**\n * Register a tool\n */\n register(tool: ITool): void {\n if (!tool.schema?.name) {\n throw new ValidationError('Tool must have a valid schema with name');\n }\n\n const toolName = tool.schema.name;\n\n // Validate tool schema\n this.validateToolSchema(tool.schema);\n\n // Check for duplicate registration\n if (this.tools.has(toolName)) {\n logger.warn(`Tool \"${toolName}\" is already registered, overriding`, {\n toolName,\n existingTool: this.tools.get(toolName)?.constructor.name,\n });\n }\n\n this.tools.set(toolName, tool);\n logger.debug(`Tool \"${toolName}\" registered successfully`, {\n toolName,\n toolType: tool.constructor.name,\n parameters: Object.keys(tool.schema.parameters?.properties || {}),\n });\n }\n\n /**\n * Unregister a tool\n */\n unregister(name: string): void {\n if (!this.tools.has(name)) {\n logger.warn(`Attempted to unregister non-existent tool \"${name}\"`);\n return;\n }\n\n this.tools.delete(name);\n logger.debug(`Tool \"${name}\" unregistered successfully`);\n }\n\n /**\n * Get tool by name\n */\n get(name: string): ITool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Get all registered tools\n */\n getAll(): ITool[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get tool schemas\n */\n getSchemas(): IToolSchema[] {\n const tools = this.getAll();\n\n // 🔍 [TOOL-FLOW] ToolRegistry.getSchemas() - Extracting schemas from tools\n logger.debug('[TOOL-FLOW] ToolRegistry.getSchemas() - Tools before schema extraction', {\n count: tools.length,\n tools: tools.map((t) => ({\n name: t.schema?.name ?? 'unnamed',\n hasSchema: !!t.schema,\n schemaType: typeof t.schema,\n toolType: t.constructor?.name || 'unknown',\n })),\n });\n\n return this.getAll().map((tool) => tool.schema);\n }\n\n /**\n * Check if tool exists\n */\n has(name: string): boolean {\n return this.tools.has(name);\n }\n\n /**\n * Clear all tools\n */\n clear(): void {\n const toolCount = this.tools.size;\n this.tools.clear();\n logger.debug(`Cleared ${toolCount} tools from registry`);\n }\n\n /**\n * Get tool names\n */\n getToolNames(): string[] {\n return Array.from(this.tools.keys());\n }\n\n /**\n * Get tools by pattern\n */\n getToolsByPattern(pattern: string | RegExp): ITool[] {\n const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;\n return this.getAll().filter((tool) => regex.test(tool.schema.name));\n }\n\n /**\n * Get tool count\n */\n size(): number {\n return this.tools.size;\n }\n\n /**\n * Validate tool schema\n */\n private validateToolSchema(schema: IToolSchema): void {\n if (!schema.name || typeof schema.name !== 'string') {\n throw new ValidationError('Tool schema must have a valid name');\n }\n\n if (!schema.description || typeof schema.description !== 'string') {\n throw new ValidationError('Tool schema must have a description');\n }\n\n if (\n !schema.parameters ||\n typeof schema.parameters !== 'object' ||\n schema.parameters === null ||\n Array.isArray(schema.parameters)\n ) {\n throw new ValidationError('Tool schema must have parameters object');\n }\n\n if (schema.parameters.type !== 'object') {\n throw new ValidationError('Tool parameters type must be \"object\"');\n }\n\n // Validate parameter properties\n if (schema.parameters.properties) {\n for (const propName of Object.keys(schema.parameters.properties)) {\n const propSchema = schema.parameters.properties[propName];\n if (!propSchema?.type) {\n throw new ValidationError(`Parameter \"${propName}\" must have a type`);\n }\n\n const validTypes = ['string', 'number', 'boolean', 'array', 'object'];\n if (!validTypes.includes(propSchema.type)) {\n throw new ValidationError(\n `Parameter \"${propName}\" has invalid type \"${propSchema.type}\"`,\n );\n }\n }\n }\n\n // Validate required fields exist in properties\n if (schema.parameters.required) {\n const properties = schema.parameters.properties || {};\n for (const requiredField of schema.parameters.required) {\n if (!properties[requiredField]) {\n throw new ValidationError(\n `Required parameter \"${requiredField}\" is not defined in properties`,\n );\n }\n }\n }\n }\n}\n","/**\n * FunctionTool - Schema conversion utilities for Facade pattern\n *\n * REASON: Complex Zod to JSON schema conversion requires isolated utility functions\n * ALTERNATIVES_CONSIDERED:\n * 1. Keep conversion logic in main class (violates single responsibility)\n * 2. Use third-party library (adds external dependency)\n * 3. Manual conversion each time (code duplication)\n * 4. Runtime type checking only (loses compile-time safety)\n * 5. Remove Zod support (breaks backward compatibility)\n * TODO: Consider caching conversion results for performance\n */\n\nimport type {\n IToolSchema,\n IParameterSchema,\n TJSONSchemaEnum,\n TUniversalValue,\n} from '@robota-sdk/agent-core';\nimport type { IZodSchema, ISchemaConversionOptions } from './types';\n\n/**\n * Convert Zod schema to JSON Schema format with safe undefined handling\n */\nexport function zodToJsonSchema(\n schema: IZodSchema,\n options: ISchemaConversionOptions = {},\n): IToolSchema['parameters'] {\n const properties: Record<string, IParameterSchema> = {};\n const required: string[] = [];\n\n // Safe access to schema definition (no fallback).\n const schemaDef = schema._def;\n if (!schemaDef) {\n throw new Error('Zod schema is missing _def; cannot convert to JSON schema.');\n }\n\n // Handle object schemas with shape\n if (schemaDef.typeName === 'ZodObject' && schemaDef.shape) {\n // In Zod v3, shape is a property, not a function\n const shape = typeof schemaDef.shape === 'function' ? schemaDef.shape() : schemaDef.shape;\n\n for (const [key, typeObj] of Object.entries(shape)) {\n const property = convertZodTypeToProperty(typeObj);\n properties[key] = property;\n\n // Check if field is required (not optional/nullable)\n if (isRequiredField(typeObj)) {\n required.push(key);\n }\n }\n }\n\n return {\n type: 'object',\n properties,\n required,\n ...((options.allowAdditionalProperties || schemaDef.unknownKeys === 'passthrough') && {\n additionalProperties: true,\n }),\n };\n}\n\n/**\n * Convert individual Zod type to parameter schema with safe undefined handling\n */\nfunction convertZodTypeToProperty(typeObj: IZodSchema): IParameterSchema {\n // Safe access to type definition\n const typeDef = typeObj._def;\n if (!typeDef) {\n throw new Error('Zod type is missing _def; cannot convert to JSON schema.');\n }\n\n const base: Partial<IParameterSchema> = {};\n\n // Add description if available\n if (typeDef.description) {\n base.description = typeDef.description;\n }\n\n // Handle different Zod types\n switch (typeDef.typeName) {\n case 'ZodString':\n return { type: 'string', ...base };\n\n case 'ZodNumber':\n return { type: 'number', ...base };\n\n case 'ZodBoolean':\n return { type: 'boolean', ...base };\n\n case 'ZodArray': {\n if (!typeDef.type) {\n throw new Error('ZodArray is missing item type; cannot convert to JSON schema.');\n }\n const arrayItems = convertZodTypeToProperty(typeDef.type);\n return {\n type: 'array',\n items: arrayItems,\n ...base,\n };\n }\n\n case 'ZodObject':\n return { type: 'object', ...base };\n\n case 'ZodEnum': {\n const enumValues = typeDef.values;\n if (!enumValues || !Array.isArray(enumValues)) {\n throw new Error('ZodEnum is missing enum values; cannot convert to JSON schema.');\n }\n return {\n type: 'string',\n enum: enumValues as TJSONSchemaEnum,\n ...base,\n };\n }\n\n case 'ZodOptional':\n // Handle optional types by recursion\n if (typeDef.innerType) {\n const innerProperty = convertZodTypeToProperty(typeDef.innerType);\n return { ...innerProperty, ...base };\n }\n throw new Error('ZodOptional is missing innerType; cannot convert to JSON schema.');\n\n case 'ZodNullable':\n // Handle nullable types\n if (typeDef.innerType) {\n const innerProperty = convertZodTypeToProperty(typeDef.innerType);\n return { ...innerProperty, ...base };\n }\n throw new Error('ZodNullable is missing innerType; cannot convert to JSON schema.');\n\n case 'ZodDefault':\n // Handle default values by processing the inner type\n if (typeDef.innerType) {\n const innerProperty = convertZodTypeToProperty(typeDef.innerType);\n return { ...innerProperty, ...base };\n }\n throw new Error('ZodDefault is missing innerType; cannot convert to JSON schema.');\n\n case 'ZodRecord':\n // Handle Record<string, T> → JSON Schema additionalProperties\n if (typeDef.valueType) {\n const valueProperty = convertZodTypeToProperty(typeDef.valueType);\n return { type: 'object', additionalProperties: valueProperty, ...base };\n }\n return { type: 'object', additionalProperties: { type: 'string' }, ...base };\n\n default:\n throw new Error(`Unsupported Zod type: ${String(typeDef.typeName)}`);\n }\n}\n\n/**\n * Check if a Zod field is required (not optional or nullable)\n */\nfunction isRequiredField(typeObj: IZodSchema): boolean {\n const typeDef = typeObj._def;\n if (!typeDef) {\n throw new Error('Zod schema is missing _def; cannot determine required fields.');\n }\n\n // Field is optional if it's ZodOptional, ZodNullable, or ZodDefault\n return (\n typeDef.typeName !== 'ZodOptional' &&\n typeDef.typeName !== 'ZodNullable' &&\n typeDef.typeName !== 'ZodDefault'\n );\n}\n\n/**\n * Safely extract enum values from Zod schema\n */\nexport function extractEnumValues(schema: IZodSchema): TUniversalValue[] {\n const typeDef = schema._def;\n if (!typeDef) {\n throw new Error('Zod schema is missing _def; cannot extract enum values.');\n }\n if (!typeDef.values || !Array.isArray(typeDef.values)) {\n throw new Error('ZodEnum schema is missing enum values; cannot extract enum values.');\n }\n return typeDef.values;\n}\n\n/**\n * Check if schema has validation constraints\n */\nexport function hasValidationConstraints(schema: IZodSchema): boolean {\n const typeDef = schema._def;\n if (!typeDef) {\n throw new Error('Zod schema is missing _def; cannot determine validation constraints.');\n }\n\n return !!(typeDef.checks && typeDef.checks.length > 0);\n}\n\n/**\n * Safe schema type name extraction\n */\nexport function getSchemaTypeName(schema: IZodSchema): string {\n const typeDef = schema._def;\n if (!typeDef) {\n throw new Error('Zod schema is missing _def; cannot determine schema type name.');\n }\n if (!typeDef.typeName) {\n throw new Error('Zod schema has empty typeName; cannot determine schema type name.');\n }\n return typeDef.typeName;\n}\n","import type {\n IParameterSchema,\n TToolParameters,\n IParameterValidationResult,\n} from '@robota-sdk/agent-core';\nimport type { TUniversalValue } from '@robota-sdk/agent-core';\n\n/**\n * Validate individual parameter type against its schema.\n * Returns an error string if invalid, undefined if valid.\n */\nexport function validateParameterType(\n key: string,\n value: TUniversalValue,\n schema: IParameterSchema,\n): string | undefined {\n const expectedType = schema['type'];\n\n switch (expectedType) {\n case 'string':\n if (typeof value !== 'string') {\n return `Parameter \"${key}\" must be a string, got ${typeof value}`;\n }\n break;\n\n case 'number':\n if (typeof value !== 'number' || isNaN(value)) {\n return `Parameter \"${key}\" must be a number, got ${typeof value}`;\n }\n break;\n\n case 'boolean':\n if (typeof value !== 'boolean') {\n return `Parameter \"${key}\" must be a boolean, got ${typeof value}`;\n }\n break;\n\n case 'array':\n if (!Array.isArray(value)) {\n return `Parameter \"${key}\" must be an array, got ${typeof value}`;\n }\n // Check array items if specified\n if (schema.items) {\n for (let i = 0; i < value.length; i++) {\n const itemError = validateParameterType(`${key}[${i}]`, value[i], schema.items);\n if (itemError) {\n return itemError;\n }\n }\n }\n break;\n\n case 'object':\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return `Parameter \"${key}\" must be an object, got ${typeof value}`;\n }\n break;\n }\n\n // Check enum constraints\n if (schema.enum && schema.enum.length > 0) {\n const enumValues = schema.enum;\n let isValidEnum = false;\n\n // Type-safe enum checking based on JSONSchemaEnum type\n for (const enumValue of enumValues) {\n if (value === enumValue) {\n isValidEnum = true;\n break;\n }\n }\n\n if (!isValidEnum) {\n return `Parameter \"${key}\" must be one of: ${enumValues.join(', ')}, got ${value}`;\n }\n }\n\n return undefined;\n}\n\n/**\n * Collect all validation errors for the given parameters against a schema.\n */\nexport function getValidationErrors(\n parameters: TToolParameters,\n schemaRequired: string[],\n schemaProperties: Record<string, IParameterSchema>,\n additionalProperties?: boolean | IParameterSchema,\n): string[] {\n const errors: string[] = [];\n\n // Check required parameters\n for (const field of schemaRequired) {\n if (!(field in parameters)) {\n errors.push(`Missing required parameter: ${field}`);\n }\n }\n\n // Check parameter types and constraints\n for (const [key, value] of Object.entries(parameters)) {\n const paramSchema = schemaProperties[key];\n if (!paramSchema) {\n if (additionalProperties === true) {\n continue;\n }\n if (additionalProperties && typeof additionalProperties === 'object') {\n const additionalTypeError = validateParameterType(key, value, additionalProperties);\n if (additionalTypeError) errors.push(additionalTypeError);\n continue;\n }\n errors.push(`Unknown parameter: ${key}`);\n continue;\n }\n\n const typeError = validateParameterType(key, value, paramSchema);\n if (typeError) {\n errors.push(typeError);\n }\n }\n\n return errors;\n}\n\n/**\n * Validate parameters and return a structured result.\n */\nexport function validateToolParameters(\n parameters: TToolParameters,\n schemaRequired: string[],\n schemaProperties: Record<string, IParameterSchema>,\n additionalProperties?: boolean | IParameterSchema,\n): IParameterValidationResult {\n const errors = getValidationErrors(\n parameters,\n schemaRequired,\n schemaProperties,\n additionalProperties,\n );\n return {\n isValid: errors.length === 0,\n errors,\n };\n}\n","import type {\n IFunctionTool,\n IToolResult,\n IToolExecutionContext,\n IParameterValidationResult,\n TToolExecutor,\n TToolParameters,\n IEventService,\n} from '@robota-sdk/agent-core';\nimport type { IToolSchema } from '@robota-sdk/agent-core';\nimport { ToolExecutionError, ValidationError } from '@robota-sdk/agent-core';\nimport type { TUniversalValue } from '@robota-sdk/agent-core';\n\n// Import from Facade pattern modules for type safety\nimport type { IZodSchema } from './function-tool/types';\nimport { zodToJsonSchema } from './function-tool/schema-converter';\nimport { getValidationErrors, validateToolParameters } from './function-tool/parameter-validator';\n\n/**\n * Function tool implementation\n * Wraps a JavaScript function as a tool with schema validation\n *\n * Implements IFunctionTool without extending AbstractTool to avoid\n * circular runtime dependency (tools → agents → tools).\n */\nexport class FunctionTool implements IFunctionTool {\n readonly schema: IToolSchema;\n readonly fn: TToolExecutor;\n private eventService: IEventService | undefined;\n\n constructor(schema: IToolSchema, fn: TToolExecutor) {\n this.schema = schema;\n this.fn = fn;\n this.validateConstructorInputs();\n }\n\n /**\n * Get tool name\n */\n getName(): string {\n return this.schema.name;\n }\n\n /**\n * Set EventService for post-construction injection.\n * Accepts EventService as-is without transformation.\n * Caller is responsible for providing properly configured EventService.\n */\n setEventService(eventService: IEventService | undefined): void {\n this.eventService = eventService;\n }\n\n /**\n * Execute the function tool\n */\n async execute(\n parameters: TToolParameters,\n context?: IToolExecutionContext,\n ): Promise<IToolResult> {\n const toolName = this.schema.name;\n\n // Validate parameters before execution\n if (!this.validate(parameters)) {\n const errors = getValidationErrors(\n parameters,\n this.schema.parameters.required || [],\n this.schema.parameters.properties || {},\n this.schema.parameters.additionalProperties,\n );\n throw new ValidationError(`Invalid parameters for tool \"${toolName}\": ${errors.join(', ')}`);\n }\n\n // Execute the function\n const startTime = Date.now();\n let result: TUniversalValue;\n try {\n result = await this.fn(parameters, context);\n } catch (error) {\n if (error instanceof ToolExecutionError || error instanceof ValidationError) {\n throw error;\n }\n\n throw new ToolExecutionError(\n `Function tool execution failed: ${error instanceof Error ? error.message : String(error)}`,\n toolName,\n error instanceof Error ? error : new Error(String(error)),\n {\n parameterCount: Object.keys(parameters || {}).length,\n hasContext: !!context,\n },\n );\n }\n\n const executionTime = Date.now() - startTime;\n\n return {\n success: true,\n data: result,\n metadata: {\n executionTime,\n toolName,\n parameters,\n },\n };\n }\n\n /**\n * Validate parameters (simple boolean result)\n */\n validate(parameters: TToolParameters): boolean {\n return (\n getValidationErrors(\n parameters,\n this.schema.parameters.required || [],\n this.schema.parameters.properties || {},\n this.schema.parameters.additionalProperties,\n ).length === 0\n );\n }\n\n /**\n * Validate tool parameters with detailed result\n */\n validateParameters(parameters: TToolParameters): IParameterValidationResult {\n return validateToolParameters(\n parameters,\n this.schema.parameters.required || [],\n this.schema.parameters.properties || {},\n this.schema.parameters.additionalProperties,\n );\n }\n\n /**\n * Get tool description\n */\n getDescription(): string {\n return this.schema.description;\n }\n\n /**\n * Validate constructor inputs\n */\n private validateConstructorInputs(): void {\n if (!this.schema) {\n throw new ValidationError('Tool schema is required');\n }\n\n if (!this.fn || typeof this.fn !== 'function') {\n throw new ValidationError('Tool function is required and must be a function');\n }\n\n if (!this.schema.name) {\n throw new ValidationError('Tool schema must have a name');\n }\n }\n}\n\n/**\n * Helper function to create a function tool from a simple function\n */\nexport function createFunctionTool(\n name: string,\n description: string,\n parameters: IToolSchema['parameters'],\n fn: TToolExecutor,\n): FunctionTool {\n const schema: IToolSchema = {\n name,\n description,\n parameters,\n };\n\n return new FunctionTool(schema, fn);\n}\n\n/**\n * Helper function to create a function tool from Zod schema\n */\nexport function createZodFunctionTool(\n name: string,\n description: string,\n zodSchema: IZodSchema,\n fn: TToolExecutor,\n): FunctionTool {\n // Use comprehensive Zod to JSON schema conversion\n const parameters = zodToJsonSchema(zodSchema);\n\n const schema: IToolSchema = {\n name,\n description,\n parameters,\n };\n\n // Wrap the function with validation and ensure proper parameter handling\n const wrappedFn: TToolExecutor = async (\n parameters: TToolParameters,\n context?: IToolExecutionContext,\n ): Promise<TUniversalValue> => {\n // Use Zod for runtime validation\n const parseResult = zodSchema.safeParse(parameters);\n if (!parseResult.success) {\n throw new ValidationError(`Zod validation failed: ${parseResult.error}`);\n }\n\n const result = await fn((parseResult.data as TToolParameters) || parameters, context);\n // Ensure result is always a string for consistency with core package\n return typeof result === 'string' ? result : JSON.stringify(result);\n };\n\n return new FunctionTool(schema, wrappedFn);\n}\n\n// zodToJsonSchema function moved to Facade pattern schema-converter module\n","import type { IParameterSchema } from '@robota-sdk/agent-core';\nimport type { IToolSchema } from '@robota-sdk/agent-core';\nimport type { OpenAPIV3 } from 'openapi-types';\n\n/**\n * OpenAPI operation method types\n */\nexport type THTTPMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options';\n\n/**\n * HTTP methods to search when scanning OpenAPI paths\n */\nexport const HTTP_METHODS: THTTPMethod[] = [\n 'get',\n 'post',\n 'put',\n 'delete',\n 'patch',\n 'head',\n 'options',\n];\n\n/**\n * Find an operation in the OpenAPI spec by operationId\n */\nexport function findOperation(\n apiSpec: OpenAPIV3.Document,\n operationId: string,\n): { method: THTTPMethod; path: string; operation: OpenAPIV3.OperationObject } | undefined {\n for (const [path, pathItem] of Object.entries(apiSpec.paths || {})) {\n if (!pathItem) continue;\n\n for (const method of HTTP_METHODS) {\n const operation = (pathItem as Record<string, OpenAPIV3.OperationObject | undefined>)[method];\n if (operation?.operationId === operationId) {\n return { method, path, operation };\n }\n }\n }\n return undefined;\n}\n\n/**\n * Map OpenAPI type to JSON schema type\n */\nexport function mapOpenAPIType(type: string | undefined): IParameterSchema['type'] {\n switch (type) {\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'integer':\n return 'integer';\n case 'boolean':\n return 'boolean';\n case 'array':\n return 'array';\n case 'object':\n return 'object';\n default:\n return 'string';\n }\n}\n\n/**\n * Convert OpenAPI schema to parameter schema\n */\nexport function convertOpenAPISchemaToParameterSchema(\n schema: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject,\n): IParameterSchema {\n // Handle reference objects\n if ('$ref' in schema) {\n // For now, treat references as generic objects\n return { type: 'object' };\n }\n\n const result: IParameterSchema = {\n type: mapOpenAPIType(schema.type),\n };\n\n if (schema.description) {\n result.description = schema.description;\n }\n\n if (schema.enum) {\n result.enum = schema.enum as (string | number | boolean)[];\n }\n\n if (schema.minimum !== undefined) {\n result.minimum = schema.minimum;\n }\n\n if (schema.maximum !== undefined) {\n result.maximum = schema.maximum;\n }\n\n if (schema.pattern) {\n result.pattern = schema.pattern;\n }\n\n if (schema.format) {\n result.format = schema.format;\n }\n\n if (schema.default !== undefined) {\n result.default = schema.default;\n }\n\n // Handle array items\n if (schema.type === 'array' && schema.items) {\n result.items = convertOpenAPISchemaToParameterSchema(schema.items);\n }\n\n // Handle object properties\n if (schema.type === 'object' && schema.properties) {\n result.properties = {};\n for (const [propName, propSchema] of Object.entries(schema.properties)) {\n result.properties[propName] = convertOpenAPISchemaToParameterSchema(propSchema);\n }\n\n if (schema.required && schema.required.length > 0) {\n (result as { required?: string[] }).required = schema.required;\n }\n }\n\n return result;\n}\n\n/**\n * Convert OpenAPI parameter object to tool parameter schema\n */\nexport function convertOpenAPIParamToSchema(param: OpenAPIV3.ParameterObject): IParameterSchema {\n const schema = param.schema as OpenAPIV3.SchemaObject;\n return convertOpenAPISchemaToParameterSchema(schema);\n}\n\n/**\n * Create a tool schema from an OpenAPI operation specification\n */\nexport function createSchemaFromOperation(\n operationId: string,\n opSpec: OpenAPIV3.OperationObject,\n): IToolSchema {\n const properties: Record<string, IParameterSchema> = {};\n const required: string[] = [];\n\n // Convert OpenAPI parameters to tool schema\n const params = (opSpec.parameters as OpenAPIV3.ParameterObject[]) || [];\n for (const param of params) {\n properties[param.name] = convertOpenAPIParamToSchema(param);\n if (param.required) {\n required.push(param.name);\n }\n }\n\n // Handle request body for POST/PUT/PATCH operations\n if (opSpec.requestBody) {\n const requestBody = opSpec.requestBody as OpenAPIV3.RequestBodyObject;\n const jsonContent = requestBody.content?.['application/json'];\n if (jsonContent?.schema) {\n const bodySchema = convertOpenAPISchemaToParameterSchema(jsonContent.schema);\n if (bodySchema.type === 'object' && bodySchema.properties) {\n Object.assign(properties, bodySchema.properties);\n // Handle required properties for object schemas\n const schemaWithRequired = bodySchema as IParameterSchema & { required?: string[] };\n if (schemaWithRequired.required) {\n required.push(...schemaWithRequired.required);\n }\n }\n }\n }\n\n const schemaParams: {\n type: 'object';\n properties: Record<string, IParameterSchema>;\n required?: string[];\n } = {\n type: 'object',\n properties,\n };\n\n if (required.length > 0) {\n schemaParams.required = required;\n }\n\n return {\n name: operationId,\n description: opSpec.summary || opSpec.description || `OpenAPI operation: ${operationId}`,\n parameters: schemaParams,\n };\n}\n","import type {\n ITool,\n IToolResult,\n IToolExecutionContext,\n IOpenAPIToolConfig,\n TToolParameters,\n IParameterValidationResult,\n IEventService,\n} from '@robota-sdk/agent-core';\nimport type { IToolSchema } from '@robota-sdk/agent-core';\nimport type { OpenAPIV3 } from 'openapi-types';\nimport { ToolExecutionError, ValidationError } from '@robota-sdk/agent-core';\nimport {\n type THTTPMethod,\n findOperation,\n createSchemaFromOperation,\n} from './openapi-schema-converter';\n\n/**\n * OpenAPI tool implementation\n * Executes API calls based on OpenAPI 3.0 specifications\n *\n * Implements ITool without extending AbstractTool to avoid\n * circular runtime dependency (tools → agents → tools).\n */\nexport class OpenAPITool implements ITool {\n readonly schema: IToolSchema;\n private readonly apiSpec: OpenAPIV3.Document;\n private readonly operationId: string;\n private readonly baseURL: string;\n private readonly config: IOpenAPIToolConfig;\n private eventService: IEventService | undefined;\n\n constructor(config: IOpenAPIToolConfig) {\n this.config = config;\n // Runtime validation of required OpenAPI 3.x fields before cast\n if (\n typeof config.spec !== 'object' ||\n config.spec === null ||\n typeof config.spec.openapi !== 'string' ||\n typeof config.spec.paths !== 'object'\n ) {\n throw new Error(\n 'Invalid OpenAPI spec: must contain \"openapi\" (string) and \"paths\" (object) fields',\n );\n }\n this.apiSpec = config.spec as OpenAPIV3.Document;\n this.operationId = config.operationId;\n this.baseURL = config.baseURL;\n this.schema = this.createSchemaFromOpenAPI();\n }\n\n /**\n * Execute the OpenAPI tool\n */\n async execute(\n parameters: TToolParameters,\n context?: IToolExecutionContext,\n ): Promise<IToolResult> {\n const toolName = this.schema.name;\n\n // Validate parameters\n const validation = this.validateParameters(parameters);\n if (!validation.isValid) {\n throw new ValidationError(\n `Invalid parameters for OpenAPI tool \"${toolName}\": ${validation.errors.join(', ')}`,\n );\n }\n\n try {\n // Execute the API call\n const startTime = Date.now();\n const result = await this.executeAPICall(parameters, context);\n const executionTime = Date.now() - startTime;\n\n return {\n success: true,\n data: result,\n metadata: {\n executionTime,\n toolName,\n operationId: this.operationId,\n baseURL: this.baseURL,\n },\n };\n } catch (error) {\n if (error instanceof ToolExecutionError || error instanceof ValidationError) {\n throw error;\n }\n\n const safeError = error instanceof Error ? error : new Error(String(error));\n throw new ToolExecutionError(\n `OpenAPI tool execution failed: ${safeError.message}`,\n toolName,\n safeError,\n {\n operationId: this.operationId,\n baseURL: this.baseURL,\n parametersCount: Object.keys(parameters).length,\n },\n );\n }\n }\n\n /**\n * Validate tool parameters\n */\n validate(parameters: TToolParameters): boolean {\n return this.validateParameters(parameters).isValid;\n }\n\n /**\n * Validate tool parameters with detailed result\n */\n validateParameters(parameters: TToolParameters): IParameterValidationResult {\n const required = this.schema.parameters.required || [];\n const errors: string[] = [];\n\n for (const field of required) {\n if (!(field in parameters)) {\n errors.push(`Missing required parameter: ${field}`);\n }\n }\n\n return {\n isValid: errors.length === 0,\n errors,\n };\n }\n\n /**\n * Get tool name\n */\n getName(): string {\n return this.schema.name;\n }\n\n /**\n * Set EventService for post-construction injection.\n */\n setEventService(eventService: IEventService | undefined): void {\n this.eventService = eventService;\n }\n\n /**\n * Get tool description\n */\n getDescription(): string {\n return this.schema.description;\n }\n\n /**\n * Execute the actual API call\n * @private\n */\n private async executeAPICall(\n parameters: TToolParameters,\n _context?: IToolExecutionContext,\n ): Promise<never> {\n // Find the operation in the OpenAPI spec\n const operation = findOperation(this.apiSpec, this.operationId);\n if (!operation) {\n throw new Error(`Operation ${this.operationId} not found in OpenAPI spec`);\n }\n\n // Build the HTTP request\n this.buildRequestConfig(operation, parameters);\n\n throw new Error('Not implemented: actual API execution is not yet available');\n }\n\n /**\n * Build HTTP request configuration from OpenAPI operation and parameters\n */\n private buildRequestConfig(\n opInfo: { method: THTTPMethod; path: string; operation: OpenAPIV3.OperationObject },\n parameters: TToolParameters,\n ): { method: THTTPMethod; url: string; headers: Record<string, string>; body?: string } {\n const { method, path, operation } = opInfo;\n\n let url = this.baseURL + path;\n const headers: Record<string, string> = {};\n let body: string | undefined;\n\n // Process parameters based on their location\n const params = (operation.parameters as OpenAPIV3.ParameterObject[]) || [];\n\n for (const param of params) {\n const value = parameters[param.name];\n if (value === undefined && param.required) {\n throw new Error(`Required parameter ${param.name} is missing`);\n }\n\n if (value !== undefined) {\n switch (param.in) {\n case 'path':\n url = url.replace(`{${param.name}}`, encodeURIComponent(String(value)));\n break;\n case 'query': {\n const separator = url.includes('?') ? '&' : '?';\n url += `${separator}${param.name}=${encodeURIComponent(String(value))}`;\n break;\n }\n case 'header':\n headers[param.name] = String(value);\n break;\n }\n }\n }\n\n // Handle request body for POST/PUT/PATCH operations\n if (['post', 'put', 'patch'].includes(method) && operation.requestBody) {\n const requestBody = operation.requestBody as OpenAPIV3.RequestBodyObject;\n const jsonContent = requestBody.content?.['application/json'];\n if (jsonContent) {\n headers['Content-Type'] = 'application/json';\n // Extract body parameters (those not in path/query/header)\n const bodyParams: TToolParameters = {};\n for (const [key, value] of Object.entries(parameters)) {\n const isParamUsed = params.some((p) => p.name === key);\n if (!isParamUsed) {\n bodyParams[key] = value;\n }\n }\n body = JSON.stringify(bodyParams);\n }\n }\n\n // Add authentication headers if configured\n if (this.config.auth) {\n switch (this.config.auth.type) {\n case 'bearer':\n headers['Authorization'] = `Bearer ${this.config.auth.token}`;\n break;\n case 'apiKey': {\n const headerName = this.config.auth.header || 'X-API-Key';\n headers[headerName] = this.config.auth.apiKey || '';\n break;\n }\n }\n }\n\n const result: {\n method: THTTPMethod;\n url: string;\n headers: Record<string, string>;\n body?: string;\n } = {\n method,\n url,\n headers,\n };\n\n if (body !== undefined) {\n result.body = body;\n }\n\n return result;\n }\n\n /**\n * Create tool schema from OpenAPI operation specification\n */\n private createSchemaFromOpenAPI(): IToolSchema {\n const operation = findOperation(this.apiSpec, this.operationId);\n if (!operation) {\n throw new Error(\n `[STRICT-POLICY][EMITTER-CONTRACT] OpenAPI operation not found: ${this.operationId}. ` +\n `Emitter contract must provide a valid operationId present in the OpenAPI document.`,\n );\n }\n\n return createSchemaFromOperation(this.operationId, operation.operation);\n }\n}\n\n/**\n * Factory function to create OpenAPI tools from specification\n */\nexport function createOpenAPITool(config: IOpenAPIToolConfig): OpenAPITool {\n return new OpenAPITool(config);\n}\n"],"mappings":"6FASA,IAAa,EAAb,KAAmD,CACjD,MAAgB,IAAI,IAKpB,SAAS,EAAmB,CAC1B,GAAI,CAAC,EAAK,QAAQ,KAChB,MAAM,IAAI,EAAgB,yCAAyC,EAGrE,IAAM,EAAW,EAAK,OAAO,KAG7B,KAAK,mBAAmB,EAAK,MAAM,EAG/B,KAAK,MAAM,IAAI,CAAQ,GACzB,EAAO,KAAK,SAAS,EAAS,qCAAsC,CAClE,WACA,aAAc,KAAK,MAAM,IAAI,CAAQ,GAAG,YAAY,IACtD,CAAC,EAGH,KAAK,MAAM,IAAI,EAAU,CAAI,EAC7B,EAAO,MAAM,SAAS,EAAS,2BAA4B,CACzD,WACA,SAAU,EAAK,YAAY,KAC3B,WAAY,OAAO,KAAK,EAAK,OAAO,YAAY,YAAc,CAAC,CAAC,CAClE,CAAC,CACH,CAKA,WAAW,EAAoB,CAC7B,GAAI,CAAC,KAAK,MAAM,IAAI,CAAI,EAAG,CACzB,EAAO,KAAK,8CAA8C,EAAK,EAAE,EACjE,MACF,CAEA,KAAK,MAAM,OAAO,CAAI,EACtB,EAAO,MAAM,SAAS,EAAK,4BAA4B,CACzD,CAKA,IAAI,EAAiC,CACnC,OAAO,KAAK,MAAM,IAAI,CAAI,CAC5B,CAKA,QAAkB,CAChB,OAAO,MAAM,KAAK,KAAK,MAAM,OAAO,CAAC,CACvC,CAKA,YAA4B,CAC1B,IAAM,EAAQ,KAAK,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