@quilltap/plugin-utils 1.0.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,236 @@
1
+ import { ToolCallRequest, UniversalTool, AnthropicToolDefinition, GoogleToolDefinition } from '@quilltap/plugin-types';
2
+ export { AnthropicToolDefinition, GoogleToolDefinition, OpenAIToolDefinition, ToolCall, ToolCallRequest, ToolFormatOptions, ToolResult, UniversalTool } from '@quilltap/plugin-types';
3
+
4
+ /**
5
+ * Tool Call Parsers
6
+ *
7
+ * Provider-specific parsers for extracting tool calls from LLM responses.
8
+ * Each parser converts from a provider's native format to the standardized
9
+ * ToolCallRequest format.
10
+ *
11
+ * @module @quilltap/plugin-utils/tools/parsers
12
+ */
13
+
14
+ /**
15
+ * Supported tool call response formats
16
+ */
17
+ type ToolCallFormat = 'openai' | 'anthropic' | 'google' | 'auto';
18
+ /**
19
+ * Parse OpenAI format tool calls from LLM response
20
+ *
21
+ * Extracts tool calls from OpenAI/Grok API responses which return
22
+ * tool_calls in the message object.
23
+ *
24
+ * Expected response structures:
25
+ * - `response.tool_calls` (direct)
26
+ * - `response.choices[0].message.tool_calls` (nested)
27
+ *
28
+ * @param response - The raw response from provider API
29
+ * @returns Array of parsed tool call requests
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * const response = await openai.chat.completions.create({...});
34
+ * const toolCalls = parseOpenAIToolCalls(response);
35
+ * // Returns: [{ name: 'search_web', arguments: { query: 'hello' } }]
36
+ * ```
37
+ */
38
+ declare function parseOpenAIToolCalls(response: unknown): ToolCallRequest[];
39
+ /**
40
+ * Parse Anthropic format tool calls from LLM response
41
+ *
42
+ * Extracts tool calls from Anthropic API responses which return
43
+ * tool_use blocks in the content array.
44
+ *
45
+ * Expected response structure:
46
+ * - `response.content` array with `{ type: 'tool_use', name, input }`
47
+ *
48
+ * @param response - The raw response from provider API
49
+ * @returns Array of parsed tool call requests
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * const response = await anthropic.messages.create({...});
54
+ * const toolCalls = parseAnthropicToolCalls(response);
55
+ * // Returns: [{ name: 'search_web', arguments: { query: 'hello' } }]
56
+ * ```
57
+ */
58
+ declare function parseAnthropicToolCalls(response: unknown): ToolCallRequest[];
59
+ /**
60
+ * Parse Google Gemini format tool calls from LLM response
61
+ *
62
+ * Extracts tool calls from Google Gemini API responses which return
63
+ * functionCall objects in the parts array.
64
+ *
65
+ * Expected response structure:
66
+ * - `response.candidates[0].content.parts` array with `{ functionCall: { name, args } }`
67
+ *
68
+ * @param response - The raw response from provider API
69
+ * @returns Array of parsed tool call requests
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * const response = await gemini.generateContent({...});
74
+ * const toolCalls = parseGoogleToolCalls(response);
75
+ * // Returns: [{ name: 'search_web', arguments: { query: 'hello' } }]
76
+ * ```
77
+ */
78
+ declare function parseGoogleToolCalls(response: unknown): ToolCallRequest[];
79
+ /**
80
+ * Detect the format of a tool call response
81
+ *
82
+ * Analyzes the response structure to determine which provider format it uses.
83
+ *
84
+ * @param response - The raw response from a provider API
85
+ * @returns The detected format, or null if unrecognized
86
+ */
87
+ declare function detectToolCallFormat(response: unknown): ToolCallFormat | null;
88
+ /**
89
+ * Parse tool calls with auto-detection or explicit format
90
+ *
91
+ * A unified parser that can either auto-detect the response format
92
+ * or use a specified format. This is useful when you're not sure
93
+ * which provider's response you're handling.
94
+ *
95
+ * @param response - The raw response from a provider API
96
+ * @param format - The format to use: 'openai', 'anthropic', 'google', or 'auto'
97
+ * @returns Array of parsed tool call requests
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * // Auto-detect format
102
+ * const toolCalls = parseToolCalls(response, 'auto');
103
+ *
104
+ * // Or specify format explicitly
105
+ * const toolCalls = parseToolCalls(response, 'openai');
106
+ * ```
107
+ */
108
+ declare function parseToolCalls(response: unknown, format?: ToolCallFormat): ToolCallRequest[];
109
+ /**
110
+ * Check if a response contains tool calls
111
+ *
112
+ * Quick check to determine if a response has any tool calls
113
+ * without fully parsing them.
114
+ *
115
+ * @param response - The raw response from a provider API
116
+ * @returns True if the response contains tool calls
117
+ */
118
+ declare function hasToolCalls(response: unknown): boolean;
119
+
120
+ /**
121
+ * Tool Format Converters
122
+ *
123
+ * Utilities for converting between different provider tool formats.
124
+ * The universal format (OpenAI-style) serves as the baseline for all conversions.
125
+ *
126
+ * @module @quilltap/plugin-utils/tools/converters
127
+ */
128
+
129
+ /**
130
+ * Convert OpenAI/Universal format tool to Anthropic format
131
+ *
132
+ * Anthropic uses a tool_use format with:
133
+ * - name: string
134
+ * - description: string
135
+ * - input_schema: JSON schema object
136
+ *
137
+ * @param tool - Universal tool in OpenAI format
138
+ * @returns Tool formatted for Anthropic's tool_use
139
+ *
140
+ * @example
141
+ * ```typescript
142
+ * const anthropicTool = convertToAnthropicFormat(universalTool);
143
+ * // Returns: {
144
+ * // name: 'search_web',
145
+ * // description: 'Search the web',
146
+ * // input_schema: {
147
+ * // type: 'object',
148
+ * // properties: { query: { type: 'string' } },
149
+ * // required: ['query']
150
+ * // }
151
+ * // }
152
+ * ```
153
+ */
154
+ declare function convertToAnthropicFormat(tool: UniversalTool): AnthropicToolDefinition;
155
+ /**
156
+ * Convert OpenAI/Universal format tool to Google Gemini format
157
+ *
158
+ * Google uses a function calling format with:
159
+ * - name: string
160
+ * - description: string
161
+ * - parameters: JSON schema object
162
+ *
163
+ * @param tool - Universal tool in OpenAI format
164
+ * @returns Tool formatted for Google's functionCall
165
+ *
166
+ * @example
167
+ * ```typescript
168
+ * const googleTool = convertToGoogleFormat(universalTool);
169
+ * // Returns: {
170
+ * // name: 'search_web',
171
+ * // description: 'Search the web',
172
+ * // parameters: {
173
+ * // type: 'object',
174
+ * // properties: { query: { type: 'string' } },
175
+ * // required: ['query']
176
+ * // }
177
+ * // }
178
+ * ```
179
+ */
180
+ declare function convertToGoogleFormat(tool: UniversalTool): GoogleToolDefinition;
181
+ /**
182
+ * Convert Anthropic format tool to Universal/OpenAI format
183
+ *
184
+ * @param tool - Anthropic format tool
185
+ * @returns Tool in universal OpenAI format
186
+ */
187
+ declare function convertFromAnthropicFormat(tool: AnthropicToolDefinition): UniversalTool;
188
+ /**
189
+ * Convert Google format tool to Universal/OpenAI format
190
+ *
191
+ * @param tool - Google format tool
192
+ * @returns Tool in universal OpenAI format
193
+ */
194
+ declare function convertFromGoogleFormat(tool: GoogleToolDefinition): UniversalTool;
195
+ /**
196
+ * Apply prompt/description length limit to a tool
197
+ *
198
+ * Modifies a tool's description if it exceeds maxBytes, appending a warning
199
+ * that the description was truncated. This is useful for providers with
200
+ * strict token limits.
201
+ *
202
+ * @param tool - Tool object (any format) with a description property
203
+ * @param maxBytes - Maximum bytes allowed for description (including warning)
204
+ * @returns Modified tool with truncated description if needed
205
+ *
206
+ * @example
207
+ * ```typescript
208
+ * const limitedTool = applyDescriptionLimit(tool, 500);
209
+ * // If description > 500 bytes, truncates and adds warning
210
+ * ```
211
+ */
212
+ declare function applyDescriptionLimit<T extends {
213
+ description: string;
214
+ }>(tool: T, maxBytes: number): T;
215
+ /**
216
+ * Target format for tool conversion
217
+ */
218
+ type ToolConvertTarget = 'openai' | 'anthropic' | 'google';
219
+ /**
220
+ * Convert a universal tool to a specific provider format
221
+ *
222
+ * @param tool - Universal tool in OpenAI format
223
+ * @param target - Target provider format
224
+ * @returns Tool in the target format
225
+ */
226
+ declare function convertToolTo(tool: UniversalTool, target: ToolConvertTarget): UniversalTool | AnthropicToolDefinition | GoogleToolDefinition;
227
+ /**
228
+ * Convert multiple tools to a specific provider format
229
+ *
230
+ * @param tools - Array of universal tools
231
+ * @param target - Target provider format
232
+ * @returns Array of tools in the target format
233
+ */
234
+ declare function convertToolsTo(tools: UniversalTool[], target: ToolConvertTarget): Array<UniversalTool | AnthropicToolDefinition | GoogleToolDefinition>;
235
+
236
+ export { type ToolCallFormat, type ToolConvertTarget, applyDescriptionLimit, convertFromAnthropicFormat, convertFromGoogleFormat, convertToAnthropicFormat, convertToGoogleFormat, convertToolTo, convertToolsTo, detectToolCallFormat, hasToolCalls, parseAnthropicToolCalls, parseGoogleToolCalls, parseOpenAIToolCalls, parseToolCalls };
@@ -0,0 +1,266 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/tools/index.ts
21
+ var tools_exports = {};
22
+ __export(tools_exports, {
23
+ applyDescriptionLimit: () => applyDescriptionLimit,
24
+ convertFromAnthropicFormat: () => convertFromAnthropicFormat,
25
+ convertFromGoogleFormat: () => convertFromGoogleFormat,
26
+ convertToAnthropicFormat: () => convertToAnthropicFormat,
27
+ convertToGoogleFormat: () => convertToGoogleFormat,
28
+ convertToolTo: () => convertToolTo,
29
+ convertToolsTo: () => convertToolsTo,
30
+ detectToolCallFormat: () => detectToolCallFormat,
31
+ hasToolCalls: () => hasToolCalls,
32
+ parseAnthropicToolCalls: () => parseAnthropicToolCalls,
33
+ parseGoogleToolCalls: () => parseGoogleToolCalls,
34
+ parseOpenAIToolCalls: () => parseOpenAIToolCalls,
35
+ parseToolCalls: () => parseToolCalls
36
+ });
37
+ module.exports = __toCommonJS(tools_exports);
38
+
39
+ // src/tools/parsers.ts
40
+ function parseOpenAIToolCalls(response) {
41
+ const toolCalls = [];
42
+ try {
43
+ const resp = response;
44
+ let toolCallsArray = resp?.tool_calls;
45
+ if (!toolCallsArray) {
46
+ const choices = resp?.choices;
47
+ toolCallsArray = choices?.[0]?.message?.tool_calls;
48
+ }
49
+ if (toolCallsArray && Array.isArray(toolCallsArray) && toolCallsArray.length > 0) {
50
+ for (const toolCall of toolCallsArray) {
51
+ const tc = toolCall;
52
+ if (tc.type === "function" && tc.function) {
53
+ toolCalls.push({
54
+ name: tc.function.name,
55
+ arguments: JSON.parse(tc.function.arguments || "{}")
56
+ });
57
+ }
58
+ }
59
+ }
60
+ } catch (error) {
61
+ console.error("[plugin-utils] Error parsing OpenAI tool calls:", error);
62
+ }
63
+ return toolCalls;
64
+ }
65
+ function parseAnthropicToolCalls(response) {
66
+ const toolCalls = [];
67
+ try {
68
+ const resp = response;
69
+ if (!resp?.content || !Array.isArray(resp.content)) {
70
+ return toolCalls;
71
+ }
72
+ for (const block of resp.content) {
73
+ const b = block;
74
+ if (b.type === "tool_use" && b.name) {
75
+ toolCalls.push({
76
+ name: b.name,
77
+ arguments: b.input || {}
78
+ });
79
+ }
80
+ }
81
+ } catch (error) {
82
+ console.error("[plugin-utils] Error parsing Anthropic tool calls:", error);
83
+ }
84
+ return toolCalls;
85
+ }
86
+ function parseGoogleToolCalls(response) {
87
+ const toolCalls = [];
88
+ try {
89
+ const resp = response;
90
+ const candidates = resp?.candidates;
91
+ const parts = candidates?.[0]?.content?.parts;
92
+ if (!parts || !Array.isArray(parts)) {
93
+ return toolCalls;
94
+ }
95
+ for (const part of parts) {
96
+ const p = part;
97
+ if (p.functionCall) {
98
+ toolCalls.push({
99
+ name: p.functionCall.name,
100
+ arguments: p.functionCall.args || {}
101
+ });
102
+ }
103
+ }
104
+ } catch (error) {
105
+ console.error("[plugin-utils] Error parsing Google tool calls:", error);
106
+ }
107
+ return toolCalls;
108
+ }
109
+ function detectToolCallFormat(response) {
110
+ if (!response || typeof response !== "object") {
111
+ return null;
112
+ }
113
+ const resp = response;
114
+ if (resp.tool_calls && Array.isArray(resp.tool_calls)) {
115
+ return "openai";
116
+ }
117
+ const choices = resp.choices;
118
+ if (choices?.[0]?.message?.tool_calls) {
119
+ return "openai";
120
+ }
121
+ if (resp.content && Array.isArray(resp.content)) {
122
+ const hasToolUse = resp.content.some(
123
+ (block) => block.type === "tool_use"
124
+ );
125
+ if (hasToolUse) {
126
+ return "anthropic";
127
+ }
128
+ }
129
+ const candidates = resp.candidates;
130
+ if (candidates?.[0]?.content?.parts) {
131
+ const hasFunctionCall = candidates[0].content.parts.some((part) => part.functionCall);
132
+ if (hasFunctionCall) {
133
+ return "google";
134
+ }
135
+ }
136
+ return null;
137
+ }
138
+ function parseToolCalls(response, format = "auto") {
139
+ let actualFormat = format;
140
+ if (format === "auto") {
141
+ actualFormat = detectToolCallFormat(response);
142
+ if (!actualFormat) {
143
+ return [];
144
+ }
145
+ }
146
+ switch (actualFormat) {
147
+ case "openai":
148
+ return parseOpenAIToolCalls(response);
149
+ case "anthropic":
150
+ return parseAnthropicToolCalls(response);
151
+ case "google":
152
+ return parseGoogleToolCalls(response);
153
+ default:
154
+ return [];
155
+ }
156
+ }
157
+ function hasToolCalls(response) {
158
+ const format = detectToolCallFormat(response);
159
+ return format !== null;
160
+ }
161
+
162
+ // src/tools/converters.ts
163
+ function convertToAnthropicFormat(tool) {
164
+ return {
165
+ name: tool.function.name,
166
+ description: tool.function.description,
167
+ input_schema: {
168
+ type: "object",
169
+ properties: tool.function.parameters.properties,
170
+ required: tool.function.parameters.required
171
+ }
172
+ };
173
+ }
174
+ function convertToGoogleFormat(tool) {
175
+ return {
176
+ name: tool.function.name,
177
+ description: tool.function.description,
178
+ parameters: {
179
+ type: "object",
180
+ properties: tool.function.parameters.properties,
181
+ required: tool.function.parameters.required
182
+ }
183
+ };
184
+ }
185
+ function convertFromAnthropicFormat(tool) {
186
+ return {
187
+ type: "function",
188
+ function: {
189
+ name: tool.name,
190
+ description: tool.description ?? "",
191
+ parameters: {
192
+ type: "object",
193
+ properties: tool.input_schema.properties,
194
+ required: tool.input_schema.required ?? []
195
+ }
196
+ }
197
+ };
198
+ }
199
+ function convertFromGoogleFormat(tool) {
200
+ return {
201
+ type: "function",
202
+ function: {
203
+ name: tool.name,
204
+ description: tool.description,
205
+ parameters: {
206
+ type: "object",
207
+ properties: tool.parameters.properties,
208
+ required: tool.parameters.required
209
+ }
210
+ }
211
+ };
212
+ }
213
+ function applyDescriptionLimit(tool, maxBytes) {
214
+ if (!tool || !tool.description) {
215
+ return tool;
216
+ }
217
+ const warningText = " [Note: description truncated due to length limit]";
218
+ const maxDescBytes = maxBytes - Buffer.byteLength(warningText);
219
+ if (maxDescBytes <= 0) {
220
+ console.warn("[plugin-utils] Length limit too small for warning text:", maxBytes);
221
+ return tool;
222
+ }
223
+ const descBytes = Buffer.byteLength(tool.description);
224
+ if (descBytes > maxBytes) {
225
+ let truncated = tool.description;
226
+ while (Buffer.byteLength(truncated) > maxDescBytes && truncated.length > 0) {
227
+ truncated = truncated.slice(0, -1);
228
+ }
229
+ return {
230
+ ...tool,
231
+ description: truncated + warningText
232
+ };
233
+ }
234
+ return tool;
235
+ }
236
+ function convertToolTo(tool, target) {
237
+ switch (target) {
238
+ case "anthropic":
239
+ return convertToAnthropicFormat(tool);
240
+ case "google":
241
+ return convertToGoogleFormat(tool);
242
+ case "openai":
243
+ default:
244
+ return tool;
245
+ }
246
+ }
247
+ function convertToolsTo(tools, target) {
248
+ return tools.map((tool) => convertToolTo(tool, target));
249
+ }
250
+ // Annotate the CommonJS export names for ESM import in node:
251
+ 0 && (module.exports = {
252
+ applyDescriptionLimit,
253
+ convertFromAnthropicFormat,
254
+ convertFromGoogleFormat,
255
+ convertToAnthropicFormat,
256
+ convertToGoogleFormat,
257
+ convertToolTo,
258
+ convertToolsTo,
259
+ detectToolCallFormat,
260
+ hasToolCalls,
261
+ parseAnthropicToolCalls,
262
+ parseGoogleToolCalls,
263
+ parseOpenAIToolCalls,
264
+ parseToolCalls
265
+ });
266
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/tools/index.ts","../../src/tools/parsers.ts","../../src/tools/converters.ts"],"sourcesContent":["/**\n * Tool Utilities\n *\n * Exports all tool-related utilities for parsing and converting\n * tool calls between different LLM provider formats.\n *\n * @module @quilltap/plugin-utils/tools\n */\n\n// Re-export types\nexport type {\n OpenAIToolDefinition,\n UniversalTool,\n AnthropicToolDefinition,\n GoogleToolDefinition,\n ToolCall,\n ToolCallRequest,\n ToolResult,\n ToolFormatOptions,\n} from './types';\n\n// Export parsers\nexport {\n parseToolCalls,\n parseOpenAIToolCalls,\n parseAnthropicToolCalls,\n parseGoogleToolCalls,\n detectToolCallFormat,\n hasToolCalls,\n} from './parsers';\n\nexport type { ToolCallFormat } from './parsers';\n\n// Export converters\nexport {\n convertToAnthropicFormat,\n convertToGoogleFormat,\n convertFromAnthropicFormat,\n convertFromGoogleFormat,\n convertToolTo,\n convertToolsTo,\n applyDescriptionLimit,\n} from './converters';\n\nexport type { ToolConvertTarget } from './converters';\n","/**\n * Tool Call Parsers\n *\n * Provider-specific parsers for extracting tool calls from LLM responses.\n * Each parser converts from a provider's native format to the standardized\n * ToolCallRequest format.\n *\n * @module @quilltap/plugin-utils/tools/parsers\n */\n\nimport type { ToolCallRequest } from '@quilltap/plugin-types';\n\n/**\n * Supported tool call response formats\n */\nexport type ToolCallFormat = 'openai' | 'anthropic' | 'google' | 'auto';\n\n/**\n * Parse OpenAI format tool calls from LLM response\n *\n * Extracts tool calls from OpenAI/Grok API responses which return\n * tool_calls in the message object.\n *\n * Expected response structures:\n * - `response.tool_calls` (direct)\n * - `response.choices[0].message.tool_calls` (nested)\n *\n * @param response - The raw response from provider API\n * @returns Array of parsed tool call requests\n *\n * @example\n * ```typescript\n * const response = await openai.chat.completions.create({...});\n * const toolCalls = parseOpenAIToolCalls(response);\n * // Returns: [{ name: 'search_web', arguments: { query: 'hello' } }]\n * ```\n */\nexport function parseOpenAIToolCalls(response: unknown): ToolCallRequest[] {\n const toolCalls: ToolCallRequest[] = [];\n\n try {\n const resp = response as Record<string, unknown>;\n\n // Handle direct tool_calls array\n let toolCallsArray = resp?.tool_calls as unknown[] | undefined;\n\n // Check nested structure from streaming responses\n if (!toolCallsArray) {\n const choices = resp?.choices as\n | Array<{ message?: { tool_calls?: unknown[] } }>\n | undefined;\n toolCallsArray = choices?.[0]?.message?.tool_calls;\n }\n\n if (toolCallsArray && Array.isArray(toolCallsArray) && toolCallsArray.length > 0) {\n for (const toolCall of toolCallsArray) {\n const tc = toolCall as {\n type?: string;\n function?: { name: string; arguments: string };\n };\n\n if (tc.type === 'function' && tc.function) {\n toolCalls.push({\n name: tc.function.name,\n arguments: JSON.parse(tc.function.arguments || '{}'),\n });\n }\n }\n }\n } catch (error) {\n // Log error but don't throw - return empty array\n console.error('[plugin-utils] Error parsing OpenAI tool calls:', error);\n }\n\n return toolCalls;\n}\n\n/**\n * Parse Anthropic format tool calls from LLM response\n *\n * Extracts tool calls from Anthropic API responses which return\n * tool_use blocks in the content array.\n *\n * Expected response structure:\n * - `response.content` array with `{ type: 'tool_use', name, input }`\n *\n * @param response - The raw response from provider API\n * @returns Array of parsed tool call requests\n *\n * @example\n * ```typescript\n * const response = await anthropic.messages.create({...});\n * const toolCalls = parseAnthropicToolCalls(response);\n * // Returns: [{ name: 'search_web', arguments: { query: 'hello' } }]\n * ```\n */\nexport function parseAnthropicToolCalls(response: unknown): ToolCallRequest[] {\n const toolCalls: ToolCallRequest[] = [];\n\n try {\n const resp = response as Record<string, unknown>;\n\n if (!resp?.content || !Array.isArray(resp.content)) {\n return toolCalls;\n }\n\n for (const block of resp.content) {\n const b = block as { type?: string; name?: string; input?: Record<string, unknown> };\n\n if (b.type === 'tool_use' && b.name) {\n toolCalls.push({\n name: b.name,\n arguments: b.input || {},\n });\n }\n }\n } catch (error) {\n console.error('[plugin-utils] Error parsing Anthropic tool calls:', error);\n }\n\n return toolCalls;\n}\n\n/**\n * Parse Google Gemini format tool calls from LLM response\n *\n * Extracts tool calls from Google Gemini API responses which return\n * functionCall objects in the parts array.\n *\n * Expected response structure:\n * - `response.candidates[0].content.parts` array with `{ functionCall: { name, args } }`\n *\n * @param response - The raw response from provider API\n * @returns Array of parsed tool call requests\n *\n * @example\n * ```typescript\n * const response = await gemini.generateContent({...});\n * const toolCalls = parseGoogleToolCalls(response);\n * // Returns: [{ name: 'search_web', arguments: { query: 'hello' } }]\n * ```\n */\nexport function parseGoogleToolCalls(response: unknown): ToolCallRequest[] {\n const toolCalls: ToolCallRequest[] = [];\n\n try {\n const resp = response as Record<string, unknown>;\n const candidates = resp?.candidates as\n | Array<{ content?: { parts?: unknown[] } }>\n | undefined;\n const parts = candidates?.[0]?.content?.parts;\n\n if (!parts || !Array.isArray(parts)) {\n return toolCalls;\n }\n\n for (const part of parts) {\n const p = part as {\n functionCall?: { name: string; args?: Record<string, unknown> };\n };\n\n if (p.functionCall) {\n toolCalls.push({\n name: p.functionCall.name,\n arguments: p.functionCall.args || {},\n });\n }\n }\n } catch (error) {\n console.error('[plugin-utils] Error parsing Google tool calls:', error);\n }\n\n return toolCalls;\n}\n\n/**\n * Detect the format of a tool call response\n *\n * Analyzes the response structure to determine which provider format it uses.\n *\n * @param response - The raw response from a provider API\n * @returns The detected format, or null if unrecognized\n */\nexport function detectToolCallFormat(response: unknown): ToolCallFormat | null {\n if (!response || typeof response !== 'object') {\n return null;\n }\n\n const resp = response as Record<string, unknown>;\n\n // OpenAI format: has tool_calls directly or in choices[0].message\n if (resp.tool_calls && Array.isArray(resp.tool_calls)) {\n return 'openai';\n }\n\n const choices = resp.choices as Array<{ message?: { tool_calls?: unknown[] } }> | undefined;\n if (choices?.[0]?.message?.tool_calls) {\n return 'openai';\n }\n\n // Anthropic format: has content array with tool_use type\n if (resp.content && Array.isArray(resp.content)) {\n const hasToolUse = (resp.content as Array<{ type?: string }>).some(\n (block) => block.type === 'tool_use'\n );\n if (hasToolUse) {\n return 'anthropic';\n }\n }\n\n // Google format: has candidates[0].content.parts with functionCall\n const candidates = resp.candidates as\n | Array<{ content?: { parts?: Array<{ functionCall?: unknown }> } }>\n | undefined;\n if (candidates?.[0]?.content?.parts) {\n const hasFunctionCall = candidates[0].content.parts.some((part) => part.functionCall);\n if (hasFunctionCall) {\n return 'google';\n }\n }\n\n return null;\n}\n\n/**\n * Parse tool calls with auto-detection or explicit format\n *\n * A unified parser that can either auto-detect the response format\n * or use a specified format. This is useful when you're not sure\n * which provider's response you're handling.\n *\n * @param response - The raw response from a provider API\n * @param format - The format to use: 'openai', 'anthropic', 'google', or 'auto'\n * @returns Array of parsed tool call requests\n *\n * @example\n * ```typescript\n * // Auto-detect format\n * const toolCalls = parseToolCalls(response, 'auto');\n *\n * // Or specify format explicitly\n * const toolCalls = parseToolCalls(response, 'openai');\n * ```\n */\nexport function parseToolCalls(\n response: unknown,\n format: ToolCallFormat = 'auto'\n): ToolCallRequest[] {\n let actualFormat: ToolCallFormat | null = format;\n\n if (format === 'auto') {\n actualFormat = detectToolCallFormat(response);\n if (!actualFormat) {\n return [];\n }\n }\n\n switch (actualFormat) {\n case 'openai':\n return parseOpenAIToolCalls(response);\n case 'anthropic':\n return parseAnthropicToolCalls(response);\n case 'google':\n return parseGoogleToolCalls(response);\n default:\n return [];\n }\n}\n\n/**\n * Check if a response contains tool calls\n *\n * Quick check to determine if a response has any tool calls\n * without fully parsing them.\n *\n * @param response - The raw response from a provider API\n * @returns True if the response contains tool calls\n */\nexport function hasToolCalls(response: unknown): boolean {\n const format = detectToolCallFormat(response);\n return format !== null;\n}\n","/**\n * Tool Format Converters\n *\n * Utilities for converting between different provider tool formats.\n * The universal format (OpenAI-style) serves as the baseline for all conversions.\n *\n * @module @quilltap/plugin-utils/tools/converters\n */\n\nimport type {\n UniversalTool,\n AnthropicToolDefinition,\n GoogleToolDefinition,\n} from '@quilltap/plugin-types';\n\n/**\n * Convert OpenAI/Universal format tool to Anthropic format\n *\n * Anthropic uses a tool_use format with:\n * - name: string\n * - description: string\n * - input_schema: JSON schema object\n *\n * @param tool - Universal tool in OpenAI format\n * @returns Tool formatted for Anthropic's tool_use\n *\n * @example\n * ```typescript\n * const anthropicTool = convertToAnthropicFormat(universalTool);\n * // Returns: {\n * // name: 'search_web',\n * // description: 'Search the web',\n * // input_schema: {\n * // type: 'object',\n * // properties: { query: { type: 'string' } },\n * // required: ['query']\n * // }\n * // }\n * ```\n */\nexport function convertToAnthropicFormat(tool: UniversalTool): AnthropicToolDefinition {\n return {\n name: tool.function.name,\n description: tool.function.description,\n input_schema: {\n type: 'object',\n properties: tool.function.parameters.properties,\n required: tool.function.parameters.required,\n },\n };\n}\n\n/**\n * Convert OpenAI/Universal format tool to Google Gemini format\n *\n * Google uses a function calling format with:\n * - name: string\n * - description: string\n * - parameters: JSON schema object\n *\n * @param tool - Universal tool in OpenAI format\n * @returns Tool formatted for Google's functionCall\n *\n * @example\n * ```typescript\n * const googleTool = convertToGoogleFormat(universalTool);\n * // Returns: {\n * // name: 'search_web',\n * // description: 'Search the web',\n * // parameters: {\n * // type: 'object',\n * // properties: { query: { type: 'string' } },\n * // required: ['query']\n * // }\n * // }\n * ```\n */\nexport function convertToGoogleFormat(tool: UniversalTool): GoogleToolDefinition {\n return {\n name: tool.function.name,\n description: tool.function.description,\n parameters: {\n type: 'object',\n properties: tool.function.parameters.properties,\n required: tool.function.parameters.required,\n },\n };\n}\n\n/**\n * Convert Anthropic format tool to Universal/OpenAI format\n *\n * @param tool - Anthropic format tool\n * @returns Tool in universal OpenAI format\n */\nexport function convertFromAnthropicFormat(tool: AnthropicToolDefinition): UniversalTool {\n return {\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description ?? '',\n parameters: {\n type: 'object',\n properties: tool.input_schema.properties,\n required: tool.input_schema.required ?? [],\n },\n },\n };\n}\n\n/**\n * Convert Google format tool to Universal/OpenAI format\n *\n * @param tool - Google format tool\n * @returns Tool in universal OpenAI format\n */\nexport function convertFromGoogleFormat(tool: GoogleToolDefinition): UniversalTool {\n return {\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: 'object',\n properties: tool.parameters.properties,\n required: tool.parameters.required,\n },\n },\n };\n}\n\n/**\n * Apply prompt/description length limit to a tool\n *\n * Modifies a tool's description if it exceeds maxBytes, appending a warning\n * that the description was truncated. This is useful for providers with\n * strict token limits.\n *\n * @param tool - Tool object (any format) with a description property\n * @param maxBytes - Maximum bytes allowed for description (including warning)\n * @returns Modified tool with truncated description if needed\n *\n * @example\n * ```typescript\n * const limitedTool = applyDescriptionLimit(tool, 500);\n * // If description > 500 bytes, truncates and adds warning\n * ```\n */\nexport function applyDescriptionLimit<T extends { description: string }>(\n tool: T,\n maxBytes: number\n): T {\n if (!tool || !tool.description) {\n return tool;\n }\n\n const warningText = ' [Note: description truncated due to length limit]';\n const maxDescBytes = maxBytes - Buffer.byteLength(warningText);\n\n if (maxDescBytes <= 0) {\n console.warn('[plugin-utils] Length limit too small for warning text:', maxBytes);\n return tool;\n }\n\n const descBytes = Buffer.byteLength(tool.description);\n\n if (descBytes > maxBytes) {\n // Truncate description to fit within the byte limit\n let truncated = tool.description;\n while (Buffer.byteLength(truncated) > maxDescBytes && truncated.length > 0) {\n truncated = truncated.slice(0, -1);\n }\n\n return {\n ...tool,\n description: truncated + warningText,\n };\n }\n\n return tool;\n}\n\n/**\n * Target format for tool conversion\n */\nexport type ToolConvertTarget = 'openai' | 'anthropic' | 'google';\n\n/**\n * Convert a universal tool to a specific provider format\n *\n * @param tool - Universal tool in OpenAI format\n * @param target - Target provider format\n * @returns Tool in the target format\n */\nexport function convertToolTo(\n tool: UniversalTool,\n target: ToolConvertTarget\n): UniversalTool | AnthropicToolDefinition | GoogleToolDefinition {\n switch (target) {\n case 'anthropic':\n return convertToAnthropicFormat(tool);\n case 'google':\n return convertToGoogleFormat(tool);\n case 'openai':\n default:\n return tool;\n }\n}\n\n/**\n * Convert multiple tools to a specific provider format\n *\n * @param tools - Array of universal tools\n * @param target - Target provider format\n * @returns Array of tools in the target format\n */\nexport function convertToolsTo(\n tools: UniversalTool[],\n target: ToolConvertTarget\n): Array<UniversalTool | AnthropicToolDefinition | GoogleToolDefinition> {\n return tools.map((tool) => convertToolTo(tool, target));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqCO,SAAS,qBAAqB,UAAsC;AACzE,QAAM,YAA+B,CAAC;AAEtC,MAAI;AACF,UAAM,OAAO;AAGb,QAAI,iBAAiB,MAAM;AAG3B,QAAI,CAAC,gBAAgB;AACnB,YAAM,UAAU,MAAM;AAGtB,uBAAiB,UAAU,CAAC,GAAG,SAAS;AAAA,IAC1C;AAEA,QAAI,kBAAkB,MAAM,QAAQ,cAAc,KAAK,eAAe,SAAS,GAAG;AAChF,iBAAW,YAAY,gBAAgB;AACrC,cAAM,KAAK;AAKX,YAAI,GAAG,SAAS,cAAc,GAAG,UAAU;AACzC,oBAAU,KAAK;AAAA,YACb,MAAM,GAAG,SAAS;AAAA,YAClB,WAAW,KAAK,MAAM,GAAG,SAAS,aAAa,IAAI;AAAA,UACrD,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,MAAM,mDAAmD,KAAK;AAAA,EACxE;AAEA,SAAO;AACT;AAqBO,SAAS,wBAAwB,UAAsC;AAC5E,QAAM,YAA+B,CAAC;AAEtC,MAAI;AACF,UAAM,OAAO;AAEb,QAAI,CAAC,MAAM,WAAW,CAAC,MAAM,QAAQ,KAAK,OAAO,GAAG;AAClD,aAAO;AAAA,IACT;AAEA,eAAW,SAAS,KAAK,SAAS;AAChC,YAAM,IAAI;AAEV,UAAI,EAAE,SAAS,cAAc,EAAE,MAAM;AACnC,kBAAU,KAAK;AAAA,UACb,MAAM,EAAE;AAAA,UACR,WAAW,EAAE,SAAS,CAAC;AAAA,QACzB,CAAC;AAAA,MACH;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