@openrouter/sdk 0.1.27 → 0.2.9

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.
Files changed (146) hide show
  1. package/biome.json +171 -0
  2. package/esm/funcs/callModel.d.ts +7 -7
  3. package/esm/funcs/callModel.js +35 -23
  4. package/esm/funcs/embeddingsGenerate.js +2 -4
  5. package/esm/funcs/oAuthCreateAuthorizationUrl.d.ts +3 -3
  6. package/esm/funcs/oAuthCreateAuthorizationUrl.js +30 -14
  7. package/esm/funcs/oAuthCreateSHA256CodeChallenge.d.ts +2 -2
  8. package/esm/funcs/oAuthCreateSHA256CodeChallenge.js +13 -12
  9. package/esm/hooks/registration.d.ts +2 -2
  10. package/esm/hooks/registration.js +1 -2
  11. package/esm/lib/config.d.ts +3 -3
  12. package/esm/lib/config.js +3 -3
  13. package/esm/lib/encodings.d.ts +1 -0
  14. package/esm/lib/encodings.js +12 -1
  15. package/esm/lib/response-wrapper.d.ts +17 -5
  16. package/esm/lib/response-wrapper.js +119 -68
  17. package/esm/lib/reusable-stream.js +26 -7
  18. package/esm/lib/stream-transformers.d.ts +3 -3
  19. package/esm/lib/stream-transformers.js +43 -41
  20. package/esm/lib/tool-executor.d.ts +9 -9
  21. package/esm/lib/tool-executor.js +9 -9
  22. package/esm/lib/tool-orchestrator.d.ts +3 -3
  23. package/esm/lib/tool-orchestrator.js +39 -19
  24. package/esm/lib/tool-types.d.ts +26 -25
  25. package/esm/lib/tool-types.js +3 -3
  26. package/esm/models/chatcompletionfinishreason.d.ts +13 -0
  27. package/esm/models/chatcompletionfinishreason.js +14 -0
  28. package/esm/models/chatgenerationparams.d.ts +16 -4
  29. package/esm/models/chatgenerationparams.js +16 -4
  30. package/esm/models/chatmessagecontentitem.d.ts +2 -19
  31. package/esm/models/chatmessagecontentitem.js +6 -9
  32. package/esm/models/chatmessagecontentitemaudio.d.ts +1 -16
  33. package/esm/models/chatmessagecontentitemaudio.js +2 -16
  34. package/esm/models/chatmessagecontentitemcachecontrol.d.ts +29 -0
  35. package/esm/models/chatmessagecontentitemcachecontrol.js +33 -0
  36. package/esm/models/chatmessagecontentitemtext.d.ts +3 -0
  37. package/esm/models/chatmessagecontentitemtext.js +12 -0
  38. package/esm/models/chatmessagecontentitemvideo.d.ts +23 -11
  39. package/esm/models/chatmessagecontentitemvideo.js +24 -11
  40. package/esm/models/chatresponsechoice.d.ts +1 -21
  41. package/esm/models/chatresponsechoice.js +1 -25
  42. package/esm/models/chatstreamingchoice.d.ts +16 -0
  43. package/esm/models/chatstreamingchoice.js +24 -0
  44. package/esm/models/chatstreamingresponsechunk.d.ts +1 -1
  45. package/esm/models/chatstreamingresponsechunk.js +1 -1
  46. package/esm/models/completionchoice.d.ts +2 -0
  47. package/esm/models/completionchoice.js +3 -0
  48. package/esm/models/completioncreateparams.d.ts +4 -4
  49. package/esm/models/completioncreateparams.js +4 -4
  50. package/esm/models/completionresponse.d.ts +1 -0
  51. package/esm/models/completionresponse.js +1 -0
  52. package/esm/models/filecitation.d.ts +2 -11
  53. package/esm/models/filecitation.js +2 -9
  54. package/esm/models/filepath.d.ts +2 -11
  55. package/esm/models/filepath.js +2 -10
  56. package/esm/models/index.d.ts +3 -2
  57. package/esm/models/index.js +3 -2
  58. package/esm/models/message.d.ts +2 -2
  59. package/esm/models/message.js +1 -1
  60. package/esm/models/openairesponsesannotation.d.ts +2 -2
  61. package/esm/models/openairesponsesannotation.js +2 -2
  62. package/esm/models/openairesponsesinputunion.d.ts +5 -45
  63. package/esm/models/openairesponsesinputunion.js +20 -20
  64. package/esm/models/openairesponsesrefusalcontent.d.ts +2 -11
  65. package/esm/models/openairesponsesrefusalcontent.js +2 -9
  66. package/esm/models/openresponseseasyinputmessage.d.ts +6 -54
  67. package/esm/models/openresponseseasyinputmessage.js +12 -12
  68. package/esm/models/openresponseserrorevent.d.ts +1 -8
  69. package/esm/models/openresponseserrorevent.js +1 -6
  70. package/esm/models/openresponsesimagegencallcompleted.d.ts +1 -8
  71. package/esm/models/openresponsesimagegencallcompleted.js +1 -6
  72. package/esm/models/openresponsesimagegencallgenerating.d.ts +1 -8
  73. package/esm/models/openresponsesimagegencallgenerating.js +1 -6
  74. package/esm/models/openresponsesimagegencallinprogress.d.ts +1 -8
  75. package/esm/models/openresponsesimagegencallinprogress.js +1 -6
  76. package/esm/models/openresponsesimagegencallpartialimage.d.ts +1 -8
  77. package/esm/models/openresponsesimagegencallpartialimage.js +1 -6
  78. package/esm/models/openresponsesinputmessageitem.d.ts +4 -36
  79. package/esm/models/openresponsesinputmessageitem.js +8 -8
  80. package/esm/models/openresponsesnonstreamingresponse.d.ts +1 -7
  81. package/esm/models/openresponsesnonstreamingresponse.js +1 -6
  82. package/esm/models/openresponsesreasoningdeltaevent.d.ts +1 -8
  83. package/esm/models/openresponsesreasoningdeltaevent.js +1 -6
  84. package/esm/models/openresponsesreasoningdoneevent.d.ts +1 -8
  85. package/esm/models/openresponsesreasoningdoneevent.js +1 -6
  86. package/esm/models/openresponsesreasoningsummarypartaddedevent.d.ts +1 -8
  87. package/esm/models/openresponsesreasoningsummarypartaddedevent.js +1 -6
  88. package/esm/models/openresponsesreasoningsummarytextdeltaevent.d.ts +1 -8
  89. package/esm/models/openresponsesreasoningsummarytextdeltaevent.js +1 -6
  90. package/esm/models/openresponsesreasoningsummarytextdoneevent.d.ts +1 -8
  91. package/esm/models/openresponsesreasoningsummarytextdoneevent.js +1 -6
  92. package/esm/models/openresponsesrequest.d.ts +26 -44
  93. package/esm/models/openresponsesrequest.js +15 -32
  94. package/esm/models/openresponsesstreamevent.d.ts +30 -125
  95. package/esm/models/openresponsesstreamevent.js +34 -119
  96. package/esm/models/openresponseswebsearch20250826tool.d.ts +2 -11
  97. package/esm/models/openresponseswebsearch20250826tool.js +2 -9
  98. package/esm/models/openresponseswebsearchpreview20250311tool.d.ts +2 -11
  99. package/esm/models/openresponseswebsearchpreview20250311tool.js +2 -9
  100. package/esm/models/openresponseswebsearchpreviewtool.d.ts +2 -11
  101. package/esm/models/openresponseswebsearchpreviewtool.js +2 -9
  102. package/esm/models/openresponseswebsearchtool.d.ts +2 -11
  103. package/esm/models/openresponseswebsearchtool.js +2 -9
  104. package/esm/models/operations/createembeddings.d.ts +5 -21
  105. package/esm/models/operations/createembeddings.js +3 -22
  106. package/esm/models/operations/getcredits.d.ts +16 -1
  107. package/esm/models/operations/getcredits.js +17 -1
  108. package/esm/models/operations/getparameters.d.ts +5 -1
  109. package/esm/models/operations/getparameters.js +5 -1
  110. package/esm/models/providername.d.ts +5 -1
  111. package/esm/models/providername.js +5 -1
  112. package/esm/models/responseformattextconfig.d.ts +2 -2
  113. package/esm/models/responseformattextconfig.js +2 -2
  114. package/esm/models/responseinputaudio.d.ts +3 -11
  115. package/esm/models/responseinputaudio.js +2 -9
  116. package/esm/models/responseinputfile.d.ts +2 -11
  117. package/esm/models/responseinputfile.js +2 -9
  118. package/esm/models/responseinputimage.d.ts +3 -11
  119. package/esm/models/responseinputimage.js +2 -9
  120. package/esm/models/responseinputtext.d.ts +2 -11
  121. package/esm/models/responseinputtext.js +2 -9
  122. package/esm/models/responseoutputtext.d.ts +2 -11
  123. package/esm/models/responseoutputtext.js +2 -9
  124. package/esm/models/responsesformatjsonobject.d.ts +2 -11
  125. package/esm/models/responsesformatjsonobject.js +2 -9
  126. package/esm/models/responsesformattext.d.ts +2 -11
  127. package/esm/models/responsesformattext.js +2 -9
  128. package/esm/models/responsesformattextjsonschemaconfig.d.ts +2 -11
  129. package/esm/models/responsesformattextjsonschemaconfig.js +2 -9
  130. package/esm/models/responsesoutputitem.d.ts +13 -1
  131. package/esm/models/responsesoutputitem.js +6 -6
  132. package/esm/models/urlcitation.d.ts +2 -11
  133. package/esm/models/urlcitation.js +2 -9
  134. package/esm/sdk/oauth.d.ts +2 -2
  135. package/esm/sdk/oauth.js +2 -3
  136. package/esm/sdk/sdk.d.ts +9 -8
  137. package/esm/types/unrecognized.d.ts +7 -1
  138. package/esm/types/unrecognized.js +9 -1
  139. package/jsr.json +1 -1
  140. package/package.json +1 -1
  141. package/tsconfig.json +0 -1
  142. package/vitest.config.ts +14 -8
  143. package/esm/models/chatmessagecontentitemfile.d.ts +0 -36
  144. package/esm/models/chatmessagecontentitemfile.js +0 -51
  145. package/esm/models/videourl.d.ts +0 -17
  146. package/esm/models/videourl.js +0 -21
@@ -4,7 +4,7 @@
4
4
  export async function* extractTextDeltas(stream) {
5
5
  const consumer = stream.createConsumer();
6
6
  for await (const event of consumer) {
7
- if ("type" in event && event.type === "response.output_text.delta") {
7
+ if ('type' in event && event.type === 'response.output_text.delta') {
8
8
  const deltaEvent = event;
9
9
  if (deltaEvent.delta) {
10
10
  yield deltaEvent.delta;
@@ -18,7 +18,7 @@ export async function* extractTextDeltas(stream) {
18
18
  export async function* extractReasoningDeltas(stream) {
19
19
  const consumer = stream.createConsumer();
20
20
  for await (const event of consumer) {
21
- if ("type" in event && event.type === "response.reasoning_text.delta") {
21
+ if ('type' in event && event.type === 'response.reasoning_text.delta') {
22
22
  const deltaEvent = event;
23
23
  if (deltaEvent.delta) {
24
24
  yield deltaEvent.delta;
@@ -32,7 +32,7 @@ export async function* extractReasoningDeltas(stream) {
32
32
  export async function* extractToolDeltas(stream) {
33
33
  const consumer = stream.createConsumer();
34
34
  for await (const event of consumer) {
35
- if ("type" in event && event.type === "response.function_call_arguments.delta") {
35
+ if ('type' in event && event.type === 'response.function_call_arguments.delta') {
36
36
  const deltaEvent = event;
37
37
  if (deltaEvent.delta) {
38
38
  yield deltaEvent.delta;
@@ -47,35 +47,38 @@ export async function* extractToolDeltas(stream) {
47
47
  export async function* buildMessageStream(stream) {
48
48
  const consumer = stream.createConsumer();
49
49
  // Track the accumulated text
50
- let currentText = "";
50
+ let currentText = '';
51
51
  let hasStarted = false;
52
52
  for await (const event of consumer) {
53
- if (!("type" in event))
53
+ if (!('type' in event)) {
54
54
  continue;
55
+ }
55
56
  switch (event.type) {
56
- case "response.output_item.added": {
57
+ case 'response.output_item.added': {
57
58
  const itemEvent = event;
58
- if (itemEvent.item && "type" in itemEvent.item && itemEvent.item.type === "message") {
59
+ if (itemEvent.item && 'type' in itemEvent.item && itemEvent.item.type === 'message') {
59
60
  hasStarted = true;
60
- currentText = "";
61
+ currentText = '';
61
62
  }
62
63
  break;
63
64
  }
64
- case "response.output_text.delta": {
65
+ case 'response.output_text.delta': {
65
66
  const deltaEvent = event;
66
67
  if (hasStarted && deltaEvent.delta) {
67
68
  currentText += deltaEvent.delta;
68
69
  // Yield updated message
69
70
  yield {
70
- role: "assistant",
71
+ role: 'assistant',
71
72
  content: currentText,
72
73
  };
73
74
  }
74
75
  break;
75
76
  }
76
- case "response.output_item.done": {
77
+ case 'response.output_item.done': {
77
78
  const itemDoneEvent = event;
78
- if (itemDoneEvent.item && "type" in itemDoneEvent.item && itemDoneEvent.item.type === "message") {
79
+ if (itemDoneEvent.item &&
80
+ 'type' in itemDoneEvent.item &&
81
+ itemDoneEvent.item.type === 'message') {
79
82
  // Yield final complete message
80
83
  const outputMessage = itemDoneEvent.item;
81
84
  yield convertToAssistantMessage(outputMessage);
@@ -91,24 +94,25 @@ export async function* buildMessageStream(stream) {
91
94
  export async function consumeStreamForCompletion(stream) {
92
95
  const consumer = stream.createConsumer();
93
96
  for await (const event of consumer) {
94
- if (!("type" in event))
97
+ if (!('type' in event)) {
95
98
  continue;
96
- if (event.type === "response.completed") {
99
+ }
100
+ if (event.type === 'response.completed') {
97
101
  const completedEvent = event;
98
102
  return completedEvent.response;
99
103
  }
100
- if (event.type === "response.failed") {
104
+ if (event.type === 'response.failed') {
101
105
  const failedEvent = event;
102
106
  // The failed event contains the full response with error information
103
107
  throw new Error(`Response failed: ${JSON.stringify(failedEvent.response.error)}`);
104
108
  }
105
- if (event.type === "response.incomplete") {
109
+ if (event.type === 'response.incomplete') {
106
110
  const incompleteEvent = event;
107
111
  // Return the incomplete response
108
112
  return incompleteEvent.response;
109
113
  }
110
114
  }
111
- throw new Error("Stream ended without completion event");
115
+ throw new Error('Stream ended without completion event');
112
116
  }
113
117
  /**
114
118
  * Convert ResponsesOutputMessage to AssistantMessage (chat format)
@@ -116,11 +120,11 @@ export async function consumeStreamForCompletion(stream) {
116
120
  function convertToAssistantMessage(outputMessage) {
117
121
  // Extract text content
118
122
  const textContent = outputMessage.content
119
- .filter((part) => "type" in part && part.type === "output_text")
123
+ .filter((part) => 'type' in part && part.type === 'output_text')
120
124
  .map((part) => part.text)
121
- .join("");
125
+ .join('');
122
126
  return {
123
- role: "assistant",
127
+ role: 'assistant',
124
128
  content: textContent || null,
125
129
  };
126
130
  }
@@ -128,9 +132,9 @@ function convertToAssistantMessage(outputMessage) {
128
132
  * Extract the first message from a completed response
129
133
  */
130
134
  export function extractMessageFromResponse(response) {
131
- const messageItem = response.output.find((item) => "type" in item && item.type === "message");
135
+ const messageItem = response.output.find((item) => 'type' in item && item.type === 'message');
132
136
  if (!messageItem) {
133
- throw new Error("No message found in response output");
137
+ throw new Error('No message found in response output');
134
138
  }
135
139
  return convertToAssistantMessage(messageItem);
136
140
  }
@@ -145,10 +149,10 @@ export function extractTextFromResponse(response) {
145
149
  // Otherwise, extract from the first message (convert to AssistantMessage which has string content)
146
150
  const message = extractMessageFromResponse(response);
147
151
  // AssistantMessage.content is string | Array | null | undefined
148
- if (typeof message.content === "string") {
152
+ if (typeof message.content === 'string') {
149
153
  return message.content;
150
154
  }
151
- return "";
155
+ return '';
152
156
  }
153
157
  /**
154
158
  * Extract all tool calls from a completed response
@@ -157,7 +161,7 @@ export function extractTextFromResponse(response) {
157
161
  export function extractToolCallsFromResponse(response) {
158
162
  const toolCalls = [];
159
163
  for (const item of response.output) {
160
- if ("type" in item && item.type === "function_call") {
164
+ if ('type' in item && item.type === 'function_call') {
161
165
  const functionCallItem = item;
162
166
  try {
163
167
  const parsedArguments = JSON.parse(functionCallItem.arguments);
@@ -167,8 +171,7 @@ export function extractToolCallsFromResponse(response) {
167
171
  arguments: parsedArguments,
168
172
  });
169
173
  }
170
- catch (error) {
171
- console.error(`Failed to parse tool call arguments for ${functionCallItem.name}:`, error);
174
+ catch (_error) {
172
175
  // Include the tool call with unparsed arguments
173
176
  toolCalls.push({
174
177
  id: functionCallItem.callId,
@@ -189,24 +192,23 @@ export async function* buildToolCallStream(stream) {
189
192
  // Track tool calls being built
190
193
  const toolCallsInProgress = new Map();
191
194
  for await (const event of consumer) {
192
- if (!("type" in event))
195
+ if (!('type' in event)) {
193
196
  continue;
197
+ }
194
198
  switch (event.type) {
195
- case "response.output_item.added": {
199
+ case 'response.output_item.added': {
196
200
  const itemEvent = event;
197
- if (itemEvent.item &&
198
- "type" in itemEvent.item &&
199
- itemEvent.item.type === "function_call") {
201
+ if (itemEvent.item && 'type' in itemEvent.item && itemEvent.item.type === 'function_call') {
200
202
  const functionCallItem = itemEvent.item;
201
203
  toolCallsInProgress.set(functionCallItem.callId, {
202
204
  id: functionCallItem.callId,
203
205
  name: functionCallItem.name,
204
- argumentsAccumulated: "",
206
+ argumentsAccumulated: '',
205
207
  });
206
208
  }
207
209
  break;
208
210
  }
209
- case "response.function_call_arguments.delta": {
211
+ case 'response.function_call_arguments.delta': {
210
212
  const deltaEvent = event;
211
213
  const toolCall = toolCallsInProgress.get(deltaEvent.itemId);
212
214
  if (toolCall && deltaEvent.delta) {
@@ -214,7 +216,7 @@ export async function* buildToolCallStream(stream) {
214
216
  }
215
217
  break;
216
218
  }
217
- case "response.function_call_arguments.done": {
219
+ case 'response.function_call_arguments.done': {
218
220
  const doneEvent = event;
219
221
  const toolCall = toolCallsInProgress.get(doneEvent.itemId);
220
222
  if (toolCall) {
@@ -227,7 +229,7 @@ export async function* buildToolCallStream(stream) {
227
229
  arguments: parsedArguments,
228
230
  };
229
231
  }
230
- catch (error) {
232
+ catch (_error) {
231
233
  // Yield with unparsed arguments if parsing fails
232
234
  yield {
233
235
  id: toolCall.id,
@@ -240,11 +242,11 @@ export async function* buildToolCallStream(stream) {
240
242
  }
241
243
  break;
242
244
  }
243
- case "response.output_item.done": {
245
+ case 'response.output_item.done': {
244
246
  const itemDoneEvent = event;
245
247
  if (itemDoneEvent.item &&
246
- "type" in itemDoneEvent.item &&
247
- itemDoneEvent.item.type === "function_call") {
248
+ 'type' in itemDoneEvent.item &&
249
+ itemDoneEvent.item.type === 'function_call') {
248
250
  const functionCallItem = itemDoneEvent.item;
249
251
  // Yield final tool call if we haven't already
250
252
  if (toolCallsInProgress.has(functionCallItem.callId)) {
@@ -256,7 +258,7 @@ export async function* buildToolCallStream(stream) {
256
258
  arguments: parsedArguments,
257
259
  };
258
260
  }
259
- catch (error) {
261
+ catch (_error) {
260
262
  yield {
261
263
  id: functionCallItem.callId,
262
264
  name: functionCallItem.name,
@@ -275,6 +277,6 @@ export async function* buildToolCallStream(stream) {
275
277
  * Check if a response contains any tool calls
276
278
  */
277
279
  export function responseHasToolCalls(response) {
278
- return response.output.some((item) => "type" in item && item.type === "function_call");
280
+ return response.output.some((item) => 'type' in item && item.type === 'function_call');
279
281
  }
280
282
  //# sourceMappingURL=stream-transformers.js.map
@@ -1,13 +1,13 @@
1
- import { type ZodType } from "zod/v4";
2
- import { EnhancedTool, ToolExecutionResult, ParsedToolCall, APITool, TurnContext } from "./tool-types.js";
1
+ import type { ZodType } from 'zod/v4';
2
+ import type { APITool, Tool, ParsedToolCall, ToolExecutionResult, TurnContext } from './tool-types.js';
3
3
  /**
4
4
  * Convert a Zod schema to JSON Schema using Zod v4's toJSONSchema function
5
5
  */
6
- export declare function convertZodToJsonSchema(zodSchema: ZodType): Record<string, any>;
6
+ export declare function convertZodToJsonSchema(zodSchema: ZodType): Record<string, unknown>;
7
7
  /**
8
- * Convert enhanced tools to OpenRouter API format
8
+ * Convert tools to OpenRouter API format
9
9
  */
10
- export declare function convertEnhancedToolsToAPIFormat(tools: EnhancedTool[]): APITool[];
10
+ export declare function convertToolsToAPIFormat(tools: Tool[]): APITool[];
11
11
  /**
12
12
  * Validate tool input against Zod schema
13
13
  * @throws ZodError if validation fails
@@ -25,23 +25,23 @@ export declare function parseToolCallArguments(argumentsString: string): unknown
25
25
  /**
26
26
  * Execute a regular (non-generator) tool
27
27
  */
28
- export declare function executeRegularTool(tool: EnhancedTool, toolCall: ParsedToolCall, context: TurnContext): Promise<ToolExecutionResult>;
28
+ export declare function executeRegularTool(tool: Tool, toolCall: ParsedToolCall, context: TurnContext): Promise<ToolExecutionResult>;
29
29
  /**
30
30
  * Execute a generator tool and collect preliminary and final results
31
31
  * - Intermediate yields are validated against eventSchema (preliminary events)
32
32
  * - Last yield is validated against outputSchema (final result sent to model)
33
33
  * - Generator must emit at least one value
34
34
  */
35
- export declare function executeGeneratorTool(tool: EnhancedTool, toolCall: ParsedToolCall, context: TurnContext, onPreliminaryResult?: (toolCallId: string, result: unknown) => void): Promise<ToolExecutionResult>;
35
+ export declare function executeGeneratorTool(tool: Tool, toolCall: ParsedToolCall, context: TurnContext, onPreliminaryResult?: (toolCallId: string, result: unknown) => void): Promise<ToolExecutionResult>;
36
36
  /**
37
37
  * Execute a tool call
38
38
  * Automatically detects if it's a regular or generator tool
39
39
  */
40
- export declare function executeTool(tool: EnhancedTool, toolCall: ParsedToolCall, context: TurnContext, onPreliminaryResult?: (toolCallId: string, result: unknown) => void): Promise<ToolExecutionResult>;
40
+ export declare function executeTool(tool: Tool, toolCall: ParsedToolCall, context: TurnContext, onPreliminaryResult?: (toolCallId: string, result: unknown) => void): Promise<ToolExecutionResult>;
41
41
  /**
42
42
  * Find a tool by name in the tools array
43
43
  */
44
- export declare function findToolByName(tools: EnhancedTool[], name: string): EnhancedTool | undefined;
44
+ export declare function findToolByName(tools: Tool[], name: string): Tool | undefined;
45
45
  /**
46
46
  * Format tool execution result as a string for sending to the model
47
47
  */
@@ -1,20 +1,20 @@
1
- import { ZodError, toJSONSchema } from "zod/v4";
2
- import { hasExecuteFunction, isGeneratorTool, isRegularExecuteTool, } from "./tool-types.js";
1
+ import { toJSONSchema, ZodError } from 'zod/v4';
2
+ import { hasExecuteFunction, isGeneratorTool, isRegularExecuteTool } from './tool-types.js';
3
3
  /**
4
4
  * Convert a Zod schema to JSON Schema using Zod v4's toJSONSchema function
5
5
  */
6
6
  export function convertZodToJsonSchema(zodSchema) {
7
7
  const jsonSchema = toJSONSchema(zodSchema, {
8
- target: "openapi-3.0",
8
+ target: 'openapi-3.0',
9
9
  });
10
10
  return jsonSchema;
11
11
  }
12
12
  /**
13
- * Convert enhanced tools to OpenRouter API format
13
+ * Convert tools to OpenRouter API format
14
14
  */
15
- export function convertEnhancedToolsToAPIFormat(tools) {
15
+ export function convertToolsToAPIFormat(tools) {
16
16
  return tools.map((tool) => ({
17
- type: "function",
17
+ type: 'function',
18
18
  name: tool.function.name,
19
19
  description: tool.function.description || null,
20
20
  strict: null,
@@ -54,7 +54,7 @@ export async function executeRegularTool(tool, toolCall, context) {
54
54
  throw new Error(`Tool "${toolCall.name}" is not a regular execute tool or has no execute function`);
55
55
  }
56
56
  try {
57
- // Validate input
57
+ // Validate input - the schema validation ensures type safety at runtime
58
58
  const validatedInput = validateToolInput(tool.function.inputSchema, toolCall.arguments);
59
59
  // Execute tool with context
60
60
  const result = await Promise.resolve(tool.function.execute(validatedInput, context));
@@ -93,7 +93,7 @@ export async function executeGeneratorTool(tool, toolCall, context, onPreliminar
93
93
  throw new Error(`Tool "${toolCall.name}" is not a generator tool`);
94
94
  }
95
95
  try {
96
- // Validate input
96
+ // Validate input - the schema validation ensures type safety at runtime
97
97
  const validatedInput = validateToolInput(tool.function.inputSchema, toolCall.arguments);
98
98
  // Execute generator and collect all results
99
99
  const preliminaryResults = [];
@@ -171,7 +171,7 @@ export function formatToolResultForModel(result) {
171
171
  export function formatToolExecutionError(error, toolCall) {
172
172
  if (error instanceof ZodError) {
173
173
  const issues = error.issues.map((issue) => ({
174
- path: issue.path.join("."),
174
+ path: issue.path.join('.'),
175
175
  message: issue.message,
176
176
  }));
177
177
  return `Tool "${toolCall.name}" validation error:\n${JSON.stringify(issues, null, 2)}`;
@@ -1,5 +1,5 @@
1
- import * as models from "../models/index.js";
2
- import { EnhancedTool, ToolExecutionResult } from "./tool-types.js";
1
+ import type * as models from '../models/index.js';
2
+ import type { APITool, Tool, ToolExecutionResult } from './tool-types.js';
3
3
  /**
4
4
  * Options for tool execution
5
5
  */
@@ -27,7 +27,7 @@ export interface ToolOrchestrationResult {
27
27
  * @param options - Execution options
28
28
  * @returns Result containing final response and all execution data
29
29
  */
30
- export declare function executeToolLoop(sendRequest: (input: models.OpenResponsesInput, tools: any[]) => Promise<models.OpenResponsesNonStreamingResponse>, initialInput: models.OpenResponsesInput, tools: EnhancedTool[], apiTools: any[], options?: ToolExecutionOptions): Promise<ToolOrchestrationResult>;
30
+ export declare function executeToolLoop(sendRequest: (input: models.OpenResponsesInput, tools: APITool[]) => Promise<models.OpenResponsesNonStreamingResponse>, initialInput: models.OpenResponsesInput, tools: Tool[], apiTools: APITool[], options?: ToolExecutionOptions): Promise<ToolOrchestrationResult>;
31
31
  /**
32
32
  * Convert tool execution results to a map for easy lookup
33
33
  */
@@ -1,6 +1,6 @@
1
- import { hasExecuteFunction, } from "./tool-types.js";
2
- import { executeTool, findToolByName, } from "./tool-executor.js";
3
- import { extractToolCallsFromResponse, responseHasToolCalls, } from "./stream-transformers.js";
1
+ import { extractToolCallsFromResponse, responseHasToolCalls } from './stream-transformers.js';
2
+ import { executeTool, findToolByName } from './tool-executor.js';
3
+ import { hasExecuteFunction } from './tool-types.js';
4
4
  /**
5
5
  * Execute tool calls and manage multi-turn conversations
6
6
  * This orchestrates the loop of: request -> tool calls -> execute -> send results -> repeat
@@ -40,23 +40,21 @@ export async function executeToolLoop(sendRequest, initialInput, tools, apiTools
40
40
  if (!hasExecutableTools) {
41
41
  break;
42
42
  }
43
- // Execute all tool calls
44
- const roundResults = [];
45
- for (const toolCall of toolCalls) {
43
+ // Execute all tool calls in parallel (parallel tool calling)
44
+ const toolCallPromises = toolCalls.map(async (toolCall) => {
46
45
  const tool = findToolByName(tools, toolCall.name);
47
46
  if (!tool) {
48
47
  // Tool not found in definitions
49
- roundResults.push({
48
+ return {
50
49
  toolCallId: toolCall.id,
51
50
  toolName: toolCall.name,
52
51
  result: null,
53
52
  error: new Error(`Tool "${toolCall.name}" not found in tool definitions`),
54
- });
55
- continue;
53
+ };
56
54
  }
57
55
  if (!hasExecuteFunction(tool)) {
58
- // Tool has no execute function - skip
59
- continue;
56
+ // Tool has no execute function - return null to filter out
57
+ return null;
60
58
  }
61
59
  // Build turn context
62
60
  const turnContext = {
@@ -64,9 +62,33 @@ export async function executeToolLoop(sendRequest, initialInput, tools, apiTools
64
62
  messageHistory: conversationInput,
65
63
  };
66
64
  // Execute the tool
67
- const result = await executeTool(tool, toolCall, turnContext, onPreliminaryResult);
68
- roundResults.push(result);
69
- }
65
+ return executeTool(tool, toolCall, turnContext, onPreliminaryResult);
66
+ });
67
+ // Wait for all tool executions to complete in parallel
68
+ const settledResults = await Promise.allSettled(toolCallPromises);
69
+ // Process settled results, handling both fulfilled and rejected promises
70
+ const roundResults = [];
71
+ settledResults.forEach((settled, i) => {
72
+ const toolCall = toolCalls[i];
73
+ if (!toolCall)
74
+ return;
75
+ if (settled.status === "fulfilled") {
76
+ if (settled.value !== null) {
77
+ roundResults.push(settled.value);
78
+ }
79
+ }
80
+ else {
81
+ // Promise rejected - create error result
82
+ roundResults.push({
83
+ toolCallId: toolCall.id,
84
+ toolName: toolCall.name,
85
+ result: null,
86
+ error: settled.reason instanceof Error
87
+ ? settled.reason
88
+ : new Error(String(settled.reason)),
89
+ });
90
+ }
91
+ });
70
92
  toolExecutionResults.push(...roundResults);
71
93
  // Build array input with all output from previous response plus tool results
72
94
  // The API expects continuation via previousResponseId, not by including outputs
@@ -109,11 +131,11 @@ export function summarizeToolExecutions(results) {
109
131
  }
110
132
  else {
111
133
  const prelimCount = result.preliminaryResults?.length ?? 0;
112
- const prelimInfo = prelimCount > 0 ? ` (${prelimCount} preliminary results)` : "";
134
+ const prelimInfo = prelimCount > 0 ? ` (${prelimCount} preliminary results)` : '';
113
135
  lines.push(`✅ ${result.toolName} (${result.toolCallId}): SUCCESS${prelimInfo}`);
114
136
  }
115
137
  }
116
- return lines.join("\n");
138
+ return lines.join('\n');
117
139
  }
118
140
  /**
119
141
  * Check if any tool executions had errors
@@ -125,8 +147,6 @@ export function hasToolExecutionErrors(results) {
125
147
  * Get all tool execution errors
126
148
  */
127
149
  export function getToolExecutionErrors(results) {
128
- return results
129
- .filter((result) => result.error !== undefined)
130
- .map((result) => result.error);
150
+ return results.filter((result) => result.error !== undefined).map((result) => result.error);
131
151
  }
132
152
  //# sourceMappingURL=tool-orchestrator.js.map
@@ -1,6 +1,7 @@
1
- import { z, type ZodType, type ZodObject, type ZodRawShape } from "zod/v4";
2
- import * as models from "../models/index.js";
3
- import type { OpenResponsesStreamEvent } from "../models/index.js";
1
+ import type { ZodObject, ZodRawShape, ZodType, z } from 'zod/v4';
2
+ import type * as models from '../models/index.js';
3
+ import type { OpenResponsesStreamEvent } from '../models/index.js';
4
+ import type { ResponseWrapper } from './response-wrapper.js';
4
5
  /**
5
6
  * Tool type enum for enhanced tools
6
7
  */
@@ -32,7 +33,7 @@ export interface BaseToolFunction<TInput extends ZodObject<ZodRawShape>> {
32
33
  /**
33
34
  * Regular tool with synchronous or asynchronous execute function and optional outputSchema
34
35
  */
35
- export interface ToolFunctionWithExecute<TInput extends ZodObject<ZodRawShape>, TOutput extends ZodType = ZodType<any>> extends BaseToolFunction<TInput> {
36
+ export interface ToolFunctionWithExecute<TInput extends ZodObject<ZodRawShape>, TOutput extends ZodType = ZodType<unknown>> extends BaseToolFunction<TInput> {
36
37
  outputSchema?: TOutput;
37
38
  execute: (params: z.infer<TInput>, context?: TurnContext) => Promise<z.infer<TOutput>> | z.infer<TOutput>;
38
39
  }
@@ -54,7 +55,7 @@ export interface ToolFunctionWithExecute<TInput extends ZodObject<ZodRawShape>,
54
55
  * }
55
56
  * ```
56
57
  */
57
- export interface ToolFunctionWithGenerator<TInput extends ZodObject<ZodRawShape>, TEvent extends ZodType = ZodType<any>, TOutput extends ZodType = ZodType<any>> extends BaseToolFunction<TInput> {
58
+ export interface ToolFunctionWithGenerator<TInput extends ZodObject<ZodRawShape>, TEvent extends ZodType = ZodType<unknown>, TOutput extends ZodType = ZodType<unknown>> extends BaseToolFunction<TInput> {
58
59
  eventSchema: TEvent;
59
60
  outputSchema: TOutput;
60
61
  execute: (params: z.infer<TInput>, context?: TurnContext) => AsyncGenerator<z.infer<TEvent>>;
@@ -62,46 +63,46 @@ export interface ToolFunctionWithGenerator<TInput extends ZodObject<ZodRawShape>
62
63
  /**
63
64
  * Manual tool without execute function - requires manual handling by developer
64
65
  */
65
- export interface ManualToolFunction<TInput extends ZodObject<ZodRawShape>, TOutput extends ZodType = ZodType<any>> extends BaseToolFunction<TInput> {
66
+ export interface ManualToolFunction<TInput extends ZodObject<ZodRawShape>, TOutput extends ZodType = ZodType<unknown>> extends BaseToolFunction<TInput> {
66
67
  outputSchema?: TOutput;
67
68
  }
68
69
  /**
69
70
  * Tool with execute function (regular or generator)
70
71
  */
71
- export type ToolWithExecute<TInput extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, TOutput extends ZodType = ZodType<any>> = {
72
+ export type ToolWithExecute<TInput extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, TOutput extends ZodType = ZodType<unknown>> = {
72
73
  type: ToolType.Function;
73
74
  function: ToolFunctionWithExecute<TInput, TOutput>;
74
75
  };
75
76
  /**
76
77
  * Tool with generator execute function
77
78
  */
78
- export type ToolWithGenerator<TInput extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, TEvent extends ZodType = ZodType<any>, TOutput extends ZodType = ZodType<any>> = {
79
+ export type ToolWithGenerator<TInput extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, TEvent extends ZodType = ZodType<unknown>, TOutput extends ZodType = ZodType<unknown>> = {
79
80
  type: ToolType.Function;
80
81
  function: ToolFunctionWithGenerator<TInput, TEvent, TOutput>;
81
82
  };
82
83
  /**
83
84
  * Tool without execute function (manual handling)
84
85
  */
85
- export type ManualTool<TInput extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, TOutput extends ZodType = ZodType<any>> = {
86
+ export type ManualTool<TInput extends ZodObject<ZodRawShape> = ZodObject<ZodRawShape>, TOutput extends ZodType = ZodType<unknown>> = {
86
87
  type: ToolType.Function;
87
88
  function: ManualToolFunction<TInput, TOutput>;
88
89
  };
89
90
  /**
90
91
  * Union type of all enhanced tool types
91
92
  */
92
- export type EnhancedTool = ToolWithExecute<any, any> | ToolWithGenerator<any, any> | ManualTool<any, any>;
93
+ export type Tool = ToolWithExecute<ZodObject<ZodRawShape>, ZodType<unknown>> | ToolWithGenerator<ZodObject<ZodRawShape>, ZodType<unknown>, ZodType<unknown>> | ManualTool<ZodObject<ZodRawShape>, ZodType<unknown>>;
93
94
  /**
94
95
  * Type guard to check if a tool has an execute function
95
96
  */
96
- export declare function hasExecuteFunction(tool: EnhancedTool): tool is ToolWithExecute | ToolWithGenerator;
97
+ export declare function hasExecuteFunction(tool: Tool): tool is ToolWithExecute | ToolWithGenerator;
97
98
  /**
98
99
  * Type guard to check if a tool uses a generator (has eventSchema)
99
100
  */
100
- export declare function isGeneratorTool(tool: EnhancedTool): tool is ToolWithGenerator;
101
+ export declare function isGeneratorTool(tool: Tool): tool is ToolWithGenerator;
101
102
  /**
102
103
  * Type guard to check if a tool is a regular execution tool (not generator)
103
104
  */
104
- export declare function isRegularExecuteTool(tool: EnhancedTool): tool is ToolWithExecute;
105
+ export declare function isRegularExecuteTool(tool: Tool): tool is ToolWithExecute;
105
106
  /**
106
107
  * Parsed tool call from API response
107
108
  */
@@ -128,8 +129,8 @@ export type MaxToolRounds = number | ((context: TurnContext) => boolean);
128
129
  * Result of executeTools operation
129
130
  */
130
131
  export interface ExecuteToolsResult {
131
- finalResponse: any;
132
- allResponses: any[];
132
+ finalResponse: ResponseWrapper;
133
+ allResponses: ResponseWrapper[];
133
134
  toolResults: Map<string, {
134
135
  result: unknown;
135
136
  preliminaryResults?: unknown[];
@@ -140,19 +141,19 @@ export interface ExecuteToolsResult {
140
141
  * Matches OpenResponsesRequestToolFunction structure
141
142
  */
142
143
  export interface APITool {
143
- type: "function";
144
+ type: 'function';
144
145
  name: string;
145
146
  description?: string | null;
146
147
  strict?: boolean | null;
147
148
  parameters: {
148
- [k: string]: any | null;
149
+ [k: string]: unknown;
149
150
  } | null;
150
151
  }
151
152
  /**
152
153
  * Tool preliminary result event emitted during generator tool execution
153
154
  */
154
155
  export type ToolPreliminaryResultEvent = {
155
- type: "tool.preliminary_result";
156
+ type: 'tool.preliminary_result';
156
157
  toolCallId: string;
157
158
  result: unknown;
158
159
  timestamp: number;
@@ -171,10 +172,10 @@ export declare function isToolPreliminaryResultEvent(event: EnhancedResponseStre
171
172
  * Includes both argument deltas and preliminary results
172
173
  */
173
174
  export type ToolStreamEvent = {
174
- type: "delta";
175
+ type: 'delta';
175
176
  content: string;
176
177
  } | {
177
- type: "preliminary_result";
178
+ type: 'preliminary_result';
178
179
  toolCallId: string;
179
180
  result: unknown;
180
181
  };
@@ -183,17 +184,17 @@ export type ToolStreamEvent = {
183
184
  * Includes content deltas, completion events, and tool preliminary results
184
185
  */
185
186
  export type ChatStreamEvent = {
186
- type: "content.delta";
187
+ type: 'content.delta';
187
188
  delta: string;
188
189
  } | {
189
- type: "message.complete";
190
- response: any;
190
+ type: 'message.complete';
191
+ response: models.OpenResponsesNonStreamingResponse;
191
192
  } | {
192
- type: "tool.preliminary_result";
193
+ type: 'tool.preliminary_result';
193
194
  toolCallId: string;
194
195
  result: unknown;
195
196
  } | {
196
197
  type: string;
197
- event: any;
198
+ event: OpenResponsesStreamEvent;
198
199
  };
199
200
  //# sourceMappingURL=tool-types.d.ts.map
@@ -9,13 +9,13 @@ export var ToolType;
9
9
  * Type guard to check if a tool has an execute function
10
10
  */
11
11
  export function hasExecuteFunction(tool) {
12
- return "execute" in tool.function && typeof tool.function.execute === "function";
12
+ return 'execute' in tool.function && typeof tool.function.execute === 'function';
13
13
  }
14
14
  /**
15
15
  * Type guard to check if a tool uses a generator (has eventSchema)
16
16
  */
17
17
  export function isGeneratorTool(tool) {
18
- return "eventSchema" in tool.function;
18
+ return 'eventSchema' in tool.function;
19
19
  }
20
20
  /**
21
21
  * Type guard to check if a tool is a regular execution tool (not generator)
@@ -27,6 +27,6 @@ export function isRegularExecuteTool(tool) {
27
27
  * Type guard to check if an event is a tool preliminary result event
28
28
  */
29
29
  export function isToolPreliminaryResultEvent(event) {
30
- return event.type === "tool.preliminary_result";
30
+ return event.type === 'tool.preliminary_result';
31
31
  }
32
32
  //# sourceMappingURL=tool-types.js.map
@@ -0,0 +1,13 @@
1
+ import * as z from "zod/v4";
2
+ import { OpenEnum } from "../types/enums.js";
3
+ export declare const ChatCompletionFinishReason: {
4
+ readonly ToolCalls: "tool_calls";
5
+ readonly Stop: "stop";
6
+ readonly Length: "length";
7
+ readonly ContentFilter: "content_filter";
8
+ readonly Error: "error";
9
+ };
10
+ export type ChatCompletionFinishReason = OpenEnum<typeof ChatCompletionFinishReason>;
11
+ /** @internal */
12
+ export declare const ChatCompletionFinishReason$inboundSchema: z.ZodType<ChatCompletionFinishReason, unknown>;
13
+ //# sourceMappingURL=chatcompletionfinishreason.d.ts.map