@openrouter/agent 0.1.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.
Files changed (98) hide show
  1. package/README.md +367 -0
  2. package/esm/api-shape-helpers/claude-message.d.ts +218 -0
  3. package/esm/api-shape-helpers/claude-message.d.ts.map +1 -0
  4. package/esm/api-shape-helpers/claude-message.js +6 -0
  5. package/esm/api-shape-helpers/claude-message.js.map +1 -0
  6. package/esm/index.d.ts +22 -0
  7. package/esm/index.d.ts.map +1 -0
  8. package/esm/index.js +27 -0
  9. package/esm/index.js.map +1 -0
  10. package/esm/inner-loop/call-model.d.ts +67 -0
  11. package/esm/inner-loop/call-model.d.ts.map +1 -0
  12. package/esm/inner-loop/call-model.js +116 -0
  13. package/esm/inner-loop/call-model.js.map +1 -0
  14. package/esm/lib/anthropic-compat.d.ts +51 -0
  15. package/esm/lib/anthropic-compat.d.ts.map +1 -0
  16. package/esm/lib/anthropic-compat.js +216 -0
  17. package/esm/lib/anthropic-compat.js.map +1 -0
  18. package/esm/lib/anthropic-compat.test.d.ts +2 -0
  19. package/esm/lib/anthropic-compat.test.d.ts.map +1 -0
  20. package/esm/lib/anthropic-compat.test.js +668 -0
  21. package/esm/lib/anthropic-compat.test.js.map +1 -0
  22. package/esm/lib/async-params.d.ts +107 -0
  23. package/esm/lib/async-params.d.ts.map +1 -0
  24. package/esm/lib/async-params.js +94 -0
  25. package/esm/lib/async-params.js.map +1 -0
  26. package/esm/lib/chat-compat.d.ts +46 -0
  27. package/esm/lib/chat-compat.d.ts.map +1 -0
  28. package/esm/lib/chat-compat.js +111 -0
  29. package/esm/lib/chat-compat.js.map +1 -0
  30. package/esm/lib/chat-compat.test.d.ts +2 -0
  31. package/esm/lib/chat-compat.test.d.ts.map +1 -0
  32. package/esm/lib/chat-compat.test.js +405 -0
  33. package/esm/lib/chat-compat.test.js.map +1 -0
  34. package/esm/lib/claude-constants.d.ts +22 -0
  35. package/esm/lib/claude-constants.d.ts.map +1 -0
  36. package/esm/lib/claude-constants.js +20 -0
  37. package/esm/lib/claude-constants.js.map +1 -0
  38. package/esm/lib/claude-type-guards.d.ts +10 -0
  39. package/esm/lib/claude-type-guards.d.ts.map +1 -0
  40. package/esm/lib/claude-type-guards.js +68 -0
  41. package/esm/lib/claude-type-guards.js.map +1 -0
  42. package/esm/lib/conversation-state.d.ts +61 -0
  43. package/esm/lib/conversation-state.d.ts.map +1 -0
  44. package/esm/lib/conversation-state.js +230 -0
  45. package/esm/lib/conversation-state.js.map +1 -0
  46. package/esm/lib/model-result.d.ts +370 -0
  47. package/esm/lib/model-result.d.ts.map +1 -0
  48. package/esm/lib/model-result.js +1483 -0
  49. package/esm/lib/model-result.js.map +1 -0
  50. package/esm/lib/next-turn-params.d.ts +30 -0
  51. package/esm/lib/next-turn-params.d.ts.map +1 -0
  52. package/esm/lib/next-turn-params.js +129 -0
  53. package/esm/lib/next-turn-params.js.map +1 -0
  54. package/esm/lib/reusable-stream.d.ts +39 -0
  55. package/esm/lib/reusable-stream.d.ts.map +1 -0
  56. package/esm/lib/reusable-stream.js +192 -0
  57. package/esm/lib/reusable-stream.js.map +1 -0
  58. package/esm/lib/stop-conditions.d.ts +80 -0
  59. package/esm/lib/stop-conditions.d.ts.map +1 -0
  60. package/esm/lib/stop-conditions.js +104 -0
  61. package/esm/lib/stop-conditions.js.map +1 -0
  62. package/esm/lib/stream-transformers.d.ts +109 -0
  63. package/esm/lib/stream-transformers.d.ts.map +1 -0
  64. package/esm/lib/stream-transformers.js +856 -0
  65. package/esm/lib/stream-transformers.js.map +1 -0
  66. package/esm/lib/stream-type-guards.d.ts +29 -0
  67. package/esm/lib/stream-type-guards.d.ts.map +1 -0
  68. package/esm/lib/stream-type-guards.js +85 -0
  69. package/esm/lib/stream-type-guards.js.map +1 -0
  70. package/esm/lib/tool-context.d.ts +68 -0
  71. package/esm/lib/tool-context.d.ts.map +1 -0
  72. package/esm/lib/tool-context.js +188 -0
  73. package/esm/lib/tool-context.js.map +1 -0
  74. package/esm/lib/tool-event-broadcaster.d.ts +44 -0
  75. package/esm/lib/tool-event-broadcaster.d.ts.map +1 -0
  76. package/esm/lib/tool-event-broadcaster.js +162 -0
  77. package/esm/lib/tool-event-broadcaster.js.map +1 -0
  78. package/esm/lib/tool-executor.d.ts +73 -0
  79. package/esm/lib/tool-executor.d.ts.map +1 -0
  80. package/esm/lib/tool-executor.js +267 -0
  81. package/esm/lib/tool-executor.js.map +1 -0
  82. package/esm/lib/tool-orchestrator.d.ts +50 -0
  83. package/esm/lib/tool-orchestrator.d.ts.map +1 -0
  84. package/esm/lib/tool-orchestrator.js +180 -0
  85. package/esm/lib/tool-orchestrator.js.map +1 -0
  86. package/esm/lib/tool-types.d.ts +572 -0
  87. package/esm/lib/tool-types.d.ts.map +1 -0
  88. package/esm/lib/tool-types.js +80 -0
  89. package/esm/lib/tool-types.js.map +1 -0
  90. package/esm/lib/tool.d.ts +108 -0
  91. package/esm/lib/tool.d.ts.map +1 -0
  92. package/esm/lib/tool.js +84 -0
  93. package/esm/lib/tool.js.map +1 -0
  94. package/esm/lib/turn-context.d.ts +50 -0
  95. package/esm/lib/turn-context.d.ts.map +1 -0
  96. package/esm/lib/turn-context.js +61 -0
  97. package/esm/lib/turn-context.js.map +1 -0
  98. package/package.json +125 -0
@@ -0,0 +1,162 @@
1
+ /**
2
+ * A push-based event broadcaster that supports multiple concurrent consumers.
3
+ * Similar to ReusableReadableStream but for push-based events from tool execution.
4
+ *
5
+ * Each consumer gets their own position in the buffer and receives all events
6
+ * from their join point onward. This enables real-time streaming of generator
7
+ * tool preliminary results to multiple consumers simultaneously.
8
+ *
9
+ * @template T - The event type being broadcast
10
+ */
11
+ export class ToolEventBroadcaster {
12
+ constructor() {
13
+ this.buffer = [];
14
+ this.consumers = new Map();
15
+ this.nextConsumerId = 0;
16
+ this.isComplete = false;
17
+ this.completionError = null;
18
+ }
19
+ /**
20
+ * Push a new event to all consumers.
21
+ * Events are buffered so late-joining consumers can catch up.
22
+ */
23
+ push(event) {
24
+ if (this.isComplete) {
25
+ return;
26
+ }
27
+ this.buffer.push(event);
28
+ this.notifyWaitingConsumers();
29
+ }
30
+ /**
31
+ * Mark the broadcaster as complete - no more events will be pushed.
32
+ * Optionally pass an error to signal failure to all consumers.
33
+ * Cleans up buffer and consumers after completion.
34
+ */
35
+ complete(error) {
36
+ this.isComplete = true;
37
+ this.completionError = error ?? null;
38
+ this.notifyWaitingConsumers();
39
+ // Schedule cleanup after consumers have processed completion
40
+ queueMicrotask(() => this.cleanup());
41
+ }
42
+ /**
43
+ * Clean up resources after all consumers have finished.
44
+ * Called automatically after complete(), but can be called manually.
45
+ */
46
+ cleanup() {
47
+ // Only cleanup if complete and all consumers are done
48
+ if (this.isComplete && this.consumers.size === 0) {
49
+ this.buffer = [];
50
+ }
51
+ }
52
+ /**
53
+ * Create a new consumer that can independently iterate over events.
54
+ * Consumers can join at any time and will receive events from position 0.
55
+ * Multiple consumers can be created and will all receive the same events.
56
+ */
57
+ createConsumer() {
58
+ const consumerId = this.nextConsumerId++;
59
+ const state = {
60
+ position: 0,
61
+ waitingPromise: null,
62
+ cancelled: false,
63
+ };
64
+ this.consumers.set(consumerId, state);
65
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
66
+ const self = this;
67
+ return {
68
+ async next() {
69
+ const consumer = self.consumers.get(consumerId);
70
+ if (!consumer) {
71
+ return {
72
+ done: true,
73
+ value: undefined,
74
+ };
75
+ }
76
+ if (consumer.cancelled) {
77
+ return {
78
+ done: true,
79
+ value: undefined,
80
+ };
81
+ }
82
+ // Return buffered event if available
83
+ if (consumer.position < self.buffer.length) {
84
+ const value = self.buffer[consumer.position];
85
+ consumer.position++;
86
+ return {
87
+ done: false,
88
+ value,
89
+ };
90
+ }
91
+ // If complete and caught up, we're done
92
+ if (self.isComplete) {
93
+ self.consumers.delete(consumerId);
94
+ self.cleanup();
95
+ if (self.completionError) {
96
+ throw self.completionError;
97
+ }
98
+ return {
99
+ done: true,
100
+ value: undefined,
101
+ };
102
+ }
103
+ // Set up waiting promise FIRST to avoid race condition
104
+ const waitPromise = new Promise((resolve, reject) => {
105
+ consumer.waitingPromise = {
106
+ resolve,
107
+ reject,
108
+ };
109
+ // Immediately check if we should resolve after setting up promise
110
+ if (self.isComplete || self.completionError || consumer.position < self.buffer.length) {
111
+ resolve();
112
+ }
113
+ });
114
+ await waitPromise;
115
+ consumer.waitingPromise = null;
116
+ // Recursively try again after waking up
117
+ return this.next();
118
+ },
119
+ async return() {
120
+ const consumer = self.consumers.get(consumerId);
121
+ if (consumer) {
122
+ consumer.cancelled = true;
123
+ self.consumers.delete(consumerId);
124
+ self.cleanup();
125
+ }
126
+ return {
127
+ done: true,
128
+ value: undefined,
129
+ };
130
+ },
131
+ async throw(e) {
132
+ const consumer = self.consumers.get(consumerId);
133
+ if (consumer) {
134
+ consumer.cancelled = true;
135
+ self.consumers.delete(consumerId);
136
+ self.cleanup();
137
+ }
138
+ throw e;
139
+ },
140
+ [Symbol.asyncIterator]() {
141
+ return this;
142
+ },
143
+ };
144
+ }
145
+ /**
146
+ * Notify all waiting consumers that new data is available or stream completed
147
+ */
148
+ notifyWaitingConsumers() {
149
+ for (const consumer of this.consumers.values()) {
150
+ if (consumer.waitingPromise) {
151
+ if (this.completionError) {
152
+ consumer.waitingPromise.reject(this.completionError);
153
+ }
154
+ else {
155
+ consumer.waitingPromise.resolve();
156
+ }
157
+ consumer.waitingPromise = null;
158
+ }
159
+ }
160
+ }
161
+ }
162
+ //# sourceMappingURL=tool-event-broadcaster.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-event-broadcaster.js","sourceRoot":"","sources":["../../src/lib/tool-event-broadcaster.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,OAAO,oBAAoB;IAAjC;QACU,WAAM,GAAQ,EAAE,CAAC;QACjB,cAAS,GAAG,IAAI,GAAG,EAAyB,CAAC;QAC7C,mBAAc,GAAG,CAAC,CAAC;QACnB,eAA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CAAC,cAAc,CAAC,OAAO,EAAE,CAAC;gBACpC,CAAC;gBACD,QAAQ,CAAC,cAAc,GAAG,IAAI,CAAC;YACjC,CAAC;QACH,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,73 @@
1
+ import type { $ZodObject, $ZodShape, $ZodType } from 'zod/v4/core';
2
+ import type { APITool, ParsedToolCall, Tool, ToolExecutionResult, TurnContext } from './tool-types.js';
3
+ import * as z4 from 'zod/v4';
4
+ import { type ToolContextStore } from './tool-context.js';
5
+ export declare const ZodError: z4.z.core.$constructor<z4.ZodError<unknown>, z4.z.core.$ZodIssue[]>;
6
+ /**
7
+ * Recursively remove keys prefixed with ~ from an object.
8
+ * These are metadata properties (like ~standard from Standard Schema)
9
+ * that should not be sent to downstream providers.
10
+ * @see https://github.com/OpenRouterTeam/typescript-sdk/issues/131
11
+ *
12
+ * When given a Record<string, unknown>, returns Record<string, unknown>.
13
+ * When given unknown, returns unknown (preserves primitives, null, etc).
14
+ */
15
+ export declare function sanitizeJsonSchema(obj: Record<string, unknown>): Record<string, unknown>;
16
+ export declare function sanitizeJsonSchema(obj: unknown): unknown;
17
+ /**
18
+ * Convert a Zod schema to JSON Schema using Zod v4's toJSONSchema function.
19
+ * Accepts ZodType from the main zod package for user compatibility.
20
+ * The resulting schema is sanitized to remove metadata properties (like ~standard)
21
+ * that would cause 400 errors with downstream providers.
22
+ */
23
+ export declare function convertZodToJsonSchema(zodSchema: $ZodType): Record<string, unknown>;
24
+ /**
25
+ * Convert tools to OpenRouter API format
26
+ * Accepts readonly arrays for better type compatibility
27
+ */
28
+ export declare function convertToolsToAPIFormat(tools: readonly Tool[]): APITool[];
29
+ /**
30
+ * Validate tool input against Zod schema
31
+ * @throws ZodError if validation fails
32
+ */
33
+ export declare function validateToolInput<T>(schema: $ZodType<T>, args: unknown): T;
34
+ /**
35
+ * Validate tool output against Zod schema
36
+ * @throws ZodError if validation fails
37
+ */
38
+ export declare function validateToolOutput<T>(schema: $ZodType<T>, result: unknown): T;
39
+ /**
40
+ * Parse tool call arguments from JSON string.
41
+ * Treats empty/whitespace-only strings as an empty object — some providers
42
+ * return `arguments: ""` for tools that take no parameters.
43
+ */
44
+ export declare function parseToolCallArguments(argumentsString: string): unknown;
45
+ /**
46
+ * Execute a regular (non-generator) tool
47
+ */
48
+ export declare function executeRegularTool(tool: Tool, toolCall: ParsedToolCall<Tool>, context: TurnContext, contextStore?: ToolContextStore, sharedSchema?: $ZodObject<$ZodShape>): Promise<ToolExecutionResult<Tool>>;
49
+ /**
50
+ * Execute a generator tool and collect preliminary and final results
51
+ * - Intermediate yields are validated against eventSchema (preliminary events)
52
+ * - Last yield is validated against outputSchema (final result sent to model)
53
+ * - Generator must emit at least one value
54
+ */
55
+ export declare function executeGeneratorTool(tool: Tool, toolCall: ParsedToolCall<Tool>, context: TurnContext, onPreliminaryResult?: (toolCallId: string, result: unknown) => void, contextStore?: ToolContextStore, sharedSchema?: $ZodObject<$ZodShape>): Promise<ToolExecutionResult<Tool>>;
56
+ /**
57
+ * Execute a tool call
58
+ * Automatically detects if it's a regular or generator tool
59
+ */
60
+ export declare function executeTool(tool: Tool, toolCall: ParsedToolCall<Tool>, context: TurnContext, onPreliminaryResult?: (toolCallId: string, result: unknown) => void, contextStore?: ToolContextStore, sharedSchema?: $ZodObject<$ZodShape>): Promise<ToolExecutionResult<Tool>>;
61
+ /**
62
+ * Find a tool by name in the tools array
63
+ */
64
+ export declare function findToolByName(tools: Tool[], name: string): Tool | undefined;
65
+ /**
66
+ * Format tool execution result as a string for sending to the model
67
+ */
68
+ export declare function formatToolResultForModel(result: ToolExecutionResult<Tool>): string;
69
+ /**
70
+ * Create a user-friendly error message for tool execution errors
71
+ */
72
+ export declare function formatToolExecutionError(error: Error, toolCall: ParsedToolCall<Tool>): string;
73
+ //# sourceMappingURL=tool-executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-executor.d.ts","sourceRoot":"","sources":["../../src/lib/tool-executor.ts"],"names":[],"mapp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{ buildToolExecuteContext } from './tool-context.js';
3
+ import { hasExecuteFunction, isGeneratorTool, isRegularExecuteTool } from './tool-types.js';
4
+ // Re-export ZodError for convenience
5
+ export const ZodError = z4.ZodError;
6
+ /**
7
+ * Typeguard to check if a value is a non-null object (not an array).
8
+ */
9
+ function isNonNullObject(value) {
10
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
11
+ }
12
+ export function sanitizeJsonSchema(obj) {
13
+ if (obj === null || typeof obj !== 'object') {
14
+ return obj;
15
+ }
16
+ if (Array.isArray(obj)) {
17
+ return obj.map(sanitizeJsonSchema);
18
+ }
19
+ // At this point, obj is a non-null, non-array object
20
+ // Use typeguard to narrow the type for type-safe property access
21
+ if (!isNonNullObject(obj)) {
22
+ return obj;
23
+ }
24
+ const result = {};
25
+ for (const key of Object.keys(obj)) {
26
+ if (!key.startsWith('~')) {
27
+ result[key] = sanitizeJsonSchema(obj[key]);
28
+ }
29
+ }
30
+ return result;
31
+ }
32
+ /**
33
+ * Typeguard to check if a value is a valid Zod schema compatible with zod/v4.
34
+ * Zod schemas have a _zod property that contains schema metadata.
35
+ */
36
+ function isZodSchema(value) {
37
+ if (typeof value !== 'object' || value === null) {
38
+ return false;
39
+ }
40
+ if (!('_zod' in value)) {
41
+ return false;
42
+ }
43
+ // After the 'in' check, TypeScript knows value has _zod property
44
+ return typeof value._zod === 'object';
45
+ }
46
+ /**
47
+ * Convert a Zod schema to JSON Schema using Zod v4's toJSONSchema function.
48
+ * Accepts ZodType from the main zod package for user compatibility.
49
+ * The resulting schema is sanitized to remove metadata properties (like ~standard)
50
+ * that would cause 400 errors with downstream providers.
51
+ */
52
+ export function convertZodToJsonSchema(zodSchema) {
53
+ if (!isZodSchema(zodSchema)) {
54
+ throw new Error('Invalid Zod schema provided');
55
+ }
56
+ // Use draft-7 as it's closest to OpenAPI 3.0's JSON Schema variant
57
+ const jsonSchema = z4.toJSONSchema(zodSchema, {
58
+ target: 'draft-7',
59
+ });
60
+ // jsonSchema is always a Record<string, unknown> from toJSONSchema
61
+ // The overloaded sanitizeJsonSchema preserves this type
62
+ return sanitizeJsonSchema(jsonSchema);
63
+ }
64
+ /**
65
+ * Convert tools to OpenRouter API format
66
+ * Accepts readonly arrays for better type compatibility
67
+ */
68
+ export function convertToolsToAPIFormat(tools) {
69
+ return tools.map((tool) => ({
70
+ type: 'function',
71
+ name: tool.function.name,
72
+ description: tool.function.description || null,
73
+ strict: null,
74
+ parameters: convertZodToJsonSchema(tool.function.inputSchema),
75
+ }));
76
+ }
77
+ /**
78
+ * Validate tool input against Zod schema
79
+ * @throws ZodError if validation fails
80
+ */
81
+ export function validateToolInput(schema, args) {
82
+ return z4.parse(schema, args);
83
+ }
84
+ /**
85
+ * Validate tool output against Zod schema
86
+ * @throws ZodError if validation fails
87
+ */
88
+ export function validateToolOutput(schema, result) {
89
+ return z4.parse(schema, result);
90
+ }
91
+ /**
92
+ * Try to validate a value against a Zod schema without throwing
93
+ * @returns true if validation succeeds, false otherwise
94
+ */
95
+ function tryValidate(schema, value) {
96
+ const result = z4.safeParse(schema, value);
97
+ return result.success;
98
+ }
99
+ /**
100
+ * Parse tool call arguments from JSON string.
101
+ * Treats empty/whitespace-only strings as an empty object — some providers
102
+ * return `arguments: ""` for tools that take no parameters.
103
+ */
104
+ export function parseToolCallArguments(argumentsString) {
105
+ const trimmed = argumentsString.trim();
106
+ if (!trimmed) {
107
+ return {};
108
+ }
109
+ try {
110
+ return JSON.parse(trimmed);
111
+ }
112
+ catch (error) {
113
+ throw new Error(`Failed to parse tool call arguments: ${error instanceof Error ? error.message : String(error)}`);
114
+ }
115
+ }
116
+ /**
117
+ * Build a ToolExecuteContext for a tool from a TurnContext and optional context store
118
+ */
119
+ function buildExecuteCtx(tool, turnContext, contextStore, sharedSchema) {
120
+ return buildToolExecuteContext(turnContext, contextStore, tool.function.name, tool.function.contextSchema, sharedSchema);
121
+ }
122
+ /**
123
+ * Execute a regular (non-generator) tool
124
+ */
125
+ export async function executeRegularTool(tool, toolCall, context, contextStore, sharedSchema) {
126
+ if (!isRegularExecuteTool(tool)) {
127
+ throw new Error(`Tool "${toolCall.name}" is not a regular execute tool or has no execute function`);
128
+ }
129
+ try {
130
+ const validatedInput = validateToolInput(tool.function.inputSchema, toolCall.arguments);
131
+ const executeContext = buildExecuteCtx(tool, context, contextStore, sharedSchema);
132
+ // Execute tool with context
133
+ const result = await Promise.resolve(tool.function.execute(validatedInput, executeContext));
134
+ // Validate output if schema is provided
135
+ if (tool.function.outputSchema) {
136
+ const validatedOutput = validateToolOutput(tool.function.outputSchema, result);
137
+ return {
138
+ toolCallId: toolCall.id,
139
+ toolName: toolCall.name,
140
+ result: validatedOutput,
141
+ };
142
+ }
143
+ return {
144
+ toolCallId: toolCall.id,
145
+ toolName: toolCall.name,
146
+ result,
147
+ };
148
+ }
149
+ catch (error) {
150
+ return {
151
+ toolCallId: toolCall.id,
152
+ toolName: toolCall.name,
153
+ result: null,
154
+ error: error instanceof Error ? error : new Error(String(error)),
155
+ };
156
+ }
157
+ }
158
+ /**
159
+ * Execute a generator tool and collect preliminary and final results
160
+ * - Intermediate yields are validated against eventSchema (preliminary events)
161
+ * - Last yield is validated against outputSchema (final result sent to model)
162
+ * - Generator must emit at least one value
163
+ */
164
+ export async function executeGeneratorTool(tool, toolCall, context, onPreliminaryResult, contextStore, sharedSchema) {
165
+ if (!isGeneratorTool(tool)) {
166
+ throw new Error(`Tool "${toolCall.name}" is not a generator tool`);
167
+ }
168
+ try {
169
+ const validatedInput = validateToolInput(tool.function.inputSchema, toolCall.arguments);
170
+ const executeContext = buildExecuteCtx(tool, context, contextStore, sharedSchema);
171
+ const preliminaryResults = [];
172
+ let finalResult;
173
+ let hasFinalResult = false;
174
+ let lastEmittedValue;
175
+ let hasEmittedValue = false;
176
+ const iterator = tool.function.execute(validatedInput, executeContext);
177
+ let iterResult = await iterator.next();
178
+ while (!iterResult.done) {
179
+ const event = iterResult.value;
180
+ lastEmittedValue = event;
181
+ hasEmittedValue = true;
182
+ const matchesOutputSchema = tryValidate(tool.function.outputSchema, event);
183
+ const matchesEventSchema = tryValidate(tool.function.eventSchema, event);
184
+ if (matchesOutputSchema && !matchesEventSchema && !hasFinalResult) {
185
+ finalResult = validateToolOutput(tool.function.outputSchema, event);
186
+ hasFinalResult = true;
187
+ }
188
+ else {
189
+ const validatedPreliminary = validateToolOutput(tool.function.eventSchema, event);
190
+ preliminaryResults.push(validatedPreliminary);
191
+ if (onPreliminaryResult) {
192
+ onPreliminaryResult(toolCall.id, validatedPreliminary);
193
+ }
194
+ }
195
+ iterResult = await iterator.next();
196
+ }
197
+ if (iterResult.value !== undefined) {
198
+ finalResult = validateToolOutput(tool.function.outputSchema, iterResult.value);
199
+ hasFinalResult = true;
200
+ }
201
+ if (!hasFinalResult) {
202
+ if (!hasEmittedValue) {
203
+ throw new Error(`Generator tool "${toolCall.name}" completed without emitting any values or returning a result`);
204
+ }
205
+ finalResult = validateToolOutput(tool.function.outputSchema, lastEmittedValue);
206
+ }
207
+ return {
208
+ toolCallId: toolCall.id,
209
+ toolName: toolCall.name,
210
+ result: finalResult,
211
+ preliminaryResults,
212
+ };
213
+ }
214
+ catch (error) {
215
+ return {
216
+ toolCallId: toolCall.id,
217
+ toolName: toolCall.name,
218
+ result: null,
219
+ error: error instanceof Error ? error : new Error(String(error)),
220
+ };
221
+ }
222
+ }
223
+ /**
224
+ * Execute a tool call
225
+ * Automatically detects if it's a regular or generator tool
226
+ */
227
+ export async function executeTool(tool, toolCall, context, onPreliminaryResult, contextStore, sharedSchema) {
228
+ if (!hasExecuteFunction(tool)) {
229
+ throw new Error(`Tool "${toolCall.name}" has no execute function. Use manual tool execution.`);
230
+ }
231
+ if (isGeneratorTool(tool)) {
232
+ return executeGeneratorTool(tool, toolCall, context, onPreliminaryResult, contextStore, sharedSchema);
233
+ }
234
+ return executeRegularTool(tool, toolCall, context, contextStore, sharedSchema);
235
+ }
236
+ /**
237
+ * Find a tool by name in the tools array
238
+ */
239
+ export function findToolByName(tools, name) {
240
+ return tools.find((tool) => tool.function.name === name);
241
+ }
242
+ /**
243
+ * Format tool execution result as a string for sending to the model
244
+ */
245
+ export function formatToolResultForModel(result) {
246
+ if (result.error) {
247
+ return JSON.stringify({
248
+ error: result.error.message,
249
+ toolName: result.toolName,
250
+ });
251
+ }
252
+ return JSON.stringify(result.result);
253
+ }
254
+ /**
255
+ * Create a user-friendly error message for tool execution errors
256
+ */
257
+ export function formatToolExecutionError(error, toolCall) {
258
+ if (error instanceof ZodError) {
259
+ const issues = error.issues.map((issue) => ({
260
+ path: issue.path.join('.'),
261
+ message: issue.message,
262
+ }));
263
+ return `Tool "${toolCall.name}" validation error:\n${JSON.stringify(issues, null, 2)}`;
264
+ }
265
+ return `Tool "${toolCall.name}" execution error: ${error.message}`;
266
+ }
267
+ //# sourceMappingURL=tool-executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-executor.js","sourceRoot":"","sources":["../../src/lib/tool-executor.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7B,OAAO,EAAE,uBAAuB,EAAyB,MAAM,mBAAmB,CAAC;AACnF,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAE5F,qCAAqC;AACrC,MAAM,CAAC,MAAM,QAAQ,GAAG,EAAE,CAAC,QAAQ,CAAC;AAEpC;;GAEG;AACH,SAAS,eAAe,CAAC,KAAc;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAaD,MAAM,UAAU,kBAAkB,CAAC,GAAY;IAC7C,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC5C,OAAO,GAAG,CAAC;IACb,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,E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AC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;AAC3D,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,wBAAwB,CAAC,MAAiC;IACxE,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;QACjB,OAAO,IAAI,CAAC,SAAS,CAAC;YACpB,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,OAAO;YAC3B,QAAQ,EAAE,MAAM,CAAC,QAAQ;SAC1B,CAAC,CAAC;IACL,CAAC;IAED,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,wBAAwB,CAAC,KAAY,EAAE,QAA8B;IACnF,IAAI,KAAK,YAAY,QAAQ,EAAE,CAAC;QAC9B,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YAC1C,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;YAC1B,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CAAC,CAAC,CAAC;QAEJ,OAAO,SAAS,QAAQ,CAAC,IAAI,wBAAwB,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;IACzF,CAAC;IAED,OAAO,SAAS,QAAQ,CAAC,IAAI,sBAAsB,KAAK,CAAC,OAAO,EAAE,CAAC;AACrE,CAAC"}
@@ -0,0 +1,50 @@
1
+ import type * as models from '@openrouter/sdk/models';
2
+ import type { APITool, Tool, ToolExecutionResult } from './tool-types.js';
3
+ /**
4
+ * Options for tool execution
5
+ */
6
+ export interface ToolExecutionOptions {
7
+ onPreliminaryResult?: (toolCallId: string, result: unknown) => void;
8
+ }
9
+ /**
10
+ * Result of the tool execution loop
11
+ */
12
+ export interface ToolOrchestrationResult {
13
+ finalResponse: models.OpenResponsesResult;
14
+ allResponses: models.OpenResponsesResult[];
15
+ toolExecutionResults: ToolExecutionResult<Tool>[];
16
+ conversationInput: models.InputsUnion;
17
+ }
18
+ /**
19
+ * Execute tool calls and manage multi-turn conversations
20
+ * This orchestrates the loop of: request -> tool calls -> execute -> send results -> repeat
21
+ *
22
+ * @param sendRequest - Function to send a request and get a response
23
+ * @param initialInput - Starting input for the conversation
24
+ * @param initialRequest - Full initial request with all parameters
25
+ * @param tools - Enhanced tools with Zod schemas and execute functions
26
+ * @param apiTools - Converted tools in API format (JSON Schema)
27
+ * @param options - Execution options
28
+ * @returns Result containing final response and all execution data
29
+ */
30
+ export declare function executeToolLoop(sendRequest: (input: models.InputsUnion, tools: APITool[]) => Promise<models.OpenResponsesResult>, initialInput: models.InputsUnion, initialRequest: models.ResponsesRequest, tools: Tool[], apiTools: APITool[], options?: ToolExecutionOptions): Promise<ToolOrchestrationResult>;
31
+ /**
32
+ * Convert tool execution results to a map for easy lookup
33
+ */
34
+ export declare function toolResultsToMap(results: ToolExecutionResult<Tool>[]): Map<string, {
35
+ result: unknown;
36
+ preliminaryResults?: unknown[];
37
+ }>;
38
+ /**
39
+ * Build a summary of tool executions for debugging/logging
40
+ */
41
+ export declare function summarizeToolExecutions(results: ToolExecutionResult<Tool>[]): string;
42
+ /**
43
+ * Check if any tool executions had errors
44
+ */
45
+ export declare function hasToolExecutionErrors(results: ToolExecutionResult<Tool>[]): boolean;
46
+ /**
47
+ * Get all tool execution errors
48
+ */
49
+ export declare function getToolExecutionErrors(results: ToolExecutionResult<Tool>[]): Error[];
50
+ //# sourceMappingURL=tool-orchestrator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-orchestrator.d.ts","sourceRoot":"","sources":["../../src/lib/tool-orchestrator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,MAAM,wBAAwB,CAAC;AACtD,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,m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