@openrouter/sdk 1.5.56 → 1.5.57

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 (103) hide show
  1. package/esm/lib/config.d.ts +2 -2
  2. package/esm/lib/config.js +2 -2
  3. package/esm/models/additionaltoolsitem.d.ts +5 -4
  4. package/esm/models/additionaltoolsitem.js +3 -0
  5. package/esm/models/alignmentresponsesrejected.d.ts +4 -1
  6. package/esm/models/alignmentresponsesrejected.js +6 -0
  7. package/esm/models/byokproviderslug.d.ts +1 -0
  8. package/esm/models/byokproviderslug.js +1 -0
  9. package/esm/models/createworkspacerequest.d.ts +1 -0
  10. package/esm/models/createworkspacerequest.js +1 -0
  11. package/esm/models/decisionschoicequestion.d.ts +4 -4
  12. package/esm/models/decisionschoicequestion.js +1 -5
  13. package/esm/models/decisionsnoulquestion.d.ts +12 -12
  14. package/esm/models/decisionsnoulquestion.js +3 -7
  15. package/esm/models/decisionsscorequestion.d.ts +4 -4
  16. package/esm/models/decisionsscorequestion.js +1 -5
  17. package/esm/models/imagegenerationproviderpreferences.d.ts +6 -0
  18. package/esm/models/imagegenerationproviderpreferences.js +1 -0
  19. package/esm/models/imagegenerationrequest.d.ts +1 -1
  20. package/esm/models/index.d.ts +6 -0
  21. package/esm/models/index.js +6 -0
  22. package/esm/models/mcpapprovalrequestitem.d.ts +7 -0
  23. package/esm/models/mcpapprovalrequestitem.js +19 -1
  24. package/esm/models/mcpcallitem.d.ts +17 -1
  25. package/esm/models/mcpcallitem.js +18 -0
  26. package/esm/models/mcpservertool.d.ts +78 -69
  27. package/esm/models/mcpservertool.js +135 -105
  28. package/esm/models/mcpservertoolopenrouter.d.ts +28 -0
  29. package/esm/models/mcpservertoolopenrouter.js +20 -0
  30. package/esm/models/mcpservertoolparameters.d.ts +152 -0
  31. package/esm/models/mcpservertoolparameters.js +134 -0
  32. package/esm/models/openairesponsestoolchoiceunion.d.ts +3 -2
  33. package/esm/models/openairesponsestoolchoiceunion.js +3 -0
  34. package/esm/models/operations/listbyokkeys.d.ts +1 -0
  35. package/esm/models/operations/listbyokkeys.js +1 -0
  36. package/esm/models/outputitemmcpapprovalrequest.d.ts +14 -0
  37. package/esm/models/outputitemmcpapprovalrequest.js +23 -0
  38. package/esm/models/outputitemmcpcall.d.ts +74 -0
  39. package/esm/models/outputitemmcpcall.js +94 -0
  40. package/esm/models/outputitemmcplisttools.d.ts +25 -0
  41. package/esm/models/outputitemmcplisttools.js +37 -0
  42. package/esm/models/outputitems.d.ts +3 -0
  43. package/esm/models/outputitems.js +2 -0
  44. package/esm/models/providername.d.ts +1 -0
  45. package/esm/models/providername.js +1 -0
  46. package/esm/models/provideroptions.d.ts +6 -0
  47. package/esm/models/provideroptions.js +1 -0
  48. package/esm/models/providerresponse.d.ts +1 -0
  49. package/esm/models/providerresponse.js +1 -0
  50. package/esm/models/responsesrequest.d.ts +9 -0
  51. package/esm/models/responsesrequest.js +3 -0
  52. package/esm/models/toolchoicemcp.d.ts +33 -0
  53. package/esm/models/toolchoicemcp.js +42 -0
  54. package/esm/models/toolsearchoutputitem.d.ts +5 -4
  55. package/esm/models/toolsearchoutputitem.js +3 -0
  56. package/esm/models/updateworkspacerequest.d.ts +1 -0
  57. package/esm/models/updateworkspacerequest.js +1 -0
  58. package/esm/models/videogenerationrequest.d.ts +6 -0
  59. package/esm/models/videogenerationrequest.js +1 -0
  60. package/esm/sdk/sdk.d.ts +0 -9
  61. package/esm/sdk/sdk.js +1 -7
  62. package/jsr.json +1 -1
  63. package/package.json +7 -7
  64. package/esm/funcs/call-model.d.ts +0 -67
  65. package/esm/funcs/call-model.js +0 -98
  66. package/esm/lib/anthropic-compat.d.ts +0 -51
  67. package/esm/lib/anthropic-compat.js +0 -222
  68. package/esm/lib/async-params.d.ts +0 -107
  69. package/esm/lib/async-params.js +0 -88
  70. package/esm/lib/chat-compat.d.ts +0 -47
  71. package/esm/lib/chat-compat.js +0 -111
  72. package/esm/lib/claude-constants.d.ts +0 -22
  73. package/esm/lib/claude-constants.js +0 -20
  74. package/esm/lib/claude-type-guards.d.ts +0 -10
  75. package/esm/lib/claude-type-guards.js +0 -70
  76. package/esm/lib/conversation-state.d.ts +0 -63
  77. package/esm/lib/conversation-state.js +0 -210
  78. package/esm/lib/model-result.d.ts +0 -373
  79. package/esm/lib/model-result.js +0 -1414
  80. package/esm/lib/next-turn-params.d.ts +0 -30
  81. package/esm/lib/next-turn-params.js +0 -135
  82. package/esm/lib/reusable-stream.d.ts +0 -39
  83. package/esm/lib/reusable-stream.js +0 -192
  84. package/esm/lib/stop-conditions.d.ts +0 -80
  85. package/esm/lib/stop-conditions.js +0 -104
  86. package/esm/lib/stream-transformers.d.ts +0 -118
  87. package/esm/lib/stream-transformers.js +0 -852
  88. package/esm/lib/stream-type-guards.d.ts +0 -49
  89. package/esm/lib/stream-type-guards.js +0 -85
  90. package/esm/lib/tool-context.d.ts +0 -68
  91. package/esm/lib/tool-context.js +0 -175
  92. package/esm/lib/tool-event-broadcaster.d.ts +0 -44
  93. package/esm/lib/tool-event-broadcaster.js +0 -146
  94. package/esm/lib/tool-executor.d.ts +0 -74
  95. package/esm/lib/tool-executor.js +0 -267
  96. package/esm/lib/tool-orchestrator.d.ts +0 -52
  97. package/esm/lib/tool-orchestrator.js +0 -180
  98. package/esm/lib/tool-types.d.ts +0 -573
  99. package/esm/lib/tool-types.js +0 -80
  100. package/esm/lib/tool.d.ts +0 -108
  101. package/esm/lib/tool.js +0 -74
  102. package/esm/lib/turn-context.d.ts +0 -52
  103. package/esm/lib/turn-context.js +0 -59
@@ -1,49 +0,0 @@
1
- import type { FileCitation } from '../models/filecitation.js';
2
- import type { FilePath } from '../models/filepath.js';
3
- import type { FunctionCallArgsDeltaEvent } from '../models/functioncallargsdeltaevent.js';
4
- import type { FunctionCallArgsDoneEvent } from '../models/functioncallargsdoneevent.js';
5
- import type { OpenAIResponsesRefusalContent } from '../models/openairesponsesrefusalcontent.js';
6
- import type { OutputFileSearchCallItem } from '../models/outputfilesearchcallitem.js';
7
- import type { OutputFunctionCallItem } from '../models/outputfunctioncallitem.js';
8
- import type { OutputImageGenerationCallItem } from '../models/outputimagegenerationcallitem.js';
9
- import type { OutputMessage } from '../models/outputmessage.js';
10
- import type { OutputReasoningItem } from '../models/outputreasoningitem.js';
11
- import type { OutputWebSearchCallItem } from '../models/outputwebsearchcallitem.js';
12
- import type { ReasoningDeltaEvent } from '../models/reasoningdeltaevent.js';
13
- import type { ResponseOutputText } from '../models/responseoutputtext.js';
14
- import type { StreamEvents } from '../models/streamevents.js';
15
- import type { StreamEventsResponseCompleted } from '../models/streameventsresponsecompleted.js';
16
- import type { StreamEventsResponseFailed } from '../models/streameventsresponsefailed.js';
17
- import type { StreamEventsResponseIncomplete } from '../models/streameventsresponseincomplete.js';
18
- import type { StreamEventsResponseOutputItemAdded } from '../models/streameventsresponseoutputitemadded.js';
19
- import type { StreamEventsResponseOutputItemDone } from '../models/streameventsresponseoutputitemdone.js';
20
- import type { TextDeltaEvent } from '../models/textdeltaevent.js';
21
- import type { URLCitation } from '../models/urlcitation.js';
22
- /**
23
- * Type guards for OpenResponses stream events
24
- * These enable proper TypeScript narrowing without type casts
25
- */
26
- export declare function isOutputTextDeltaEvent(event: StreamEvents): event is TextDeltaEvent;
27
- export declare function isReasoningDeltaEvent(event: StreamEvents): event is ReasoningDeltaEvent;
28
- export declare function isFunctionCallArgumentsDeltaEvent(event: StreamEvents): event is FunctionCallArgsDeltaEvent;
29
- export declare function isOutputItemAddedEvent(event: StreamEvents): event is StreamEventsResponseOutputItemAdded;
30
- export declare function isOutputItemDoneEvent(event: StreamEvents): event is StreamEventsResponseOutputItemDone;
31
- export declare function isResponseCompletedEvent(event: StreamEvents): event is StreamEventsResponseCompleted;
32
- export declare function isResponseFailedEvent(event: StreamEvents): event is StreamEventsResponseFailed;
33
- export declare function isResponseIncompleteEvent(event: StreamEvents): event is StreamEventsResponseIncomplete;
34
- export declare function isFunctionCallArgumentsDoneEvent(event: StreamEvents): event is FunctionCallArgsDoneEvent;
35
- export declare function isOutputMessage(item: unknown): item is OutputMessage;
36
- export declare function isFunctionCallItem(item: unknown): item is OutputFunctionCallItem;
37
- export declare function isReasoningOutputItem(item: unknown): item is OutputReasoningItem;
38
- export declare function isWebSearchCallOutputItem(item: unknown): item is OutputWebSearchCallItem;
39
- export declare function isFileSearchCallOutputItem(item: unknown): item is OutputFileSearchCallItem;
40
- export declare function isImageGenerationCallOutputItem(item: unknown): item is OutputImageGenerationCallItem;
41
- export declare function isOutputTextPart(part: unknown): part is ResponseOutputText;
42
- export declare function isRefusalPart(part: unknown): part is OpenAIResponsesRefusalContent;
43
- export declare function isFileCitationAnnotation(annotation: unknown): annotation is FileCitation;
44
- export declare function isURLCitationAnnotation(annotation: unknown): annotation is URLCitation;
45
- export declare function isFilePathAnnotation(annotation: unknown): annotation is FilePath;
46
- export declare function hasTypeProperty(item: unknown): item is {
47
- type: string;
48
- };
49
- //# sourceMappingURL=stream-type-guards.d.ts.map
@@ -1,85 +0,0 @@
1
- /**
2
- * Type guards for OpenResponses stream events
3
- * These enable proper TypeScript narrowing without type casts
4
- */
5
- // Stream event type guards
6
- export function isOutputTextDeltaEvent(event) {
7
- return 'type' in event && event.type === 'response.output_text.delta';
8
- }
9
- export function isReasoningDeltaEvent(event) {
10
- return 'type' in event && event.type === 'response.reasoning_text.delta';
11
- }
12
- export function isFunctionCallArgumentsDeltaEvent(event) {
13
- return 'type' in event && event.type === 'response.function_call_arguments.delta';
14
- }
15
- export function isOutputItemAddedEvent(event) {
16
- return 'type' in event && event.type === 'response.output_item.added';
17
- }
18
- export function isOutputItemDoneEvent(event) {
19
- return 'type' in event && event.type === 'response.output_item.done';
20
- }
21
- export function isResponseCompletedEvent(event) {
22
- return 'type' in event && event.type === 'response.completed';
23
- }
24
- export function isResponseFailedEvent(event) {
25
- return 'type' in event && event.type === 'response.failed';
26
- }
27
- export function isResponseIncompleteEvent(event) {
28
- return 'type' in event && event.type === 'response.incomplete';
29
- }
30
- export function isFunctionCallArgumentsDoneEvent(event) {
31
- return 'type' in event && event.type === 'response.function_call_arguments.done';
32
- }
33
- // Output item type guards
34
- export function isOutputMessage(item) {
35
- return typeof item === 'object' && item !== null && 'type' in item && item.type === 'message';
36
- }
37
- export function isFunctionCallItem(item) {
38
- return (typeof item === 'object' && item !== null && 'type' in item && item.type === 'function_call');
39
- }
40
- export function isReasoningOutputItem(item) {
41
- return typeof item === 'object' && item !== null && 'type' in item && item.type === 'reasoning';
42
- }
43
- export function isWebSearchCallOutputItem(item) {
44
- return (typeof item === 'object' && item !== null && 'type' in item && item.type === 'web_search_call');
45
- }
46
- export function isFileSearchCallOutputItem(item) {
47
- return (typeof item === 'object' && item !== null && 'type' in item && item.type === 'file_search_call');
48
- }
49
- export function isImageGenerationCallOutputItem(item) {
50
- return (typeof item === 'object' &&
51
- item !== null &&
52
- 'type' in item &&
53
- item.type === 'image_generation_call');
54
- }
55
- // Content part type guards
56
- export function isOutputTextPart(part) {
57
- return typeof part === 'object' && part !== null && 'type' in part && part.type === 'output_text';
58
- }
59
- export function isRefusalPart(part) {
60
- return typeof part === 'object' && part !== null && 'type' in part && part.type === 'refusal';
61
- }
62
- // Annotation type guards for Claude conversion
63
- export function isFileCitationAnnotation(annotation) {
64
- return (typeof annotation === 'object' &&
65
- annotation !== null &&
66
- 'type' in annotation &&
67
- annotation.type === 'file_citation');
68
- }
69
- export function isURLCitationAnnotation(annotation) {
70
- return (typeof annotation === 'object' &&
71
- annotation !== null &&
72
- 'type' in annotation &&
73
- annotation.type === 'url_citation');
74
- }
75
- export function isFilePathAnnotation(annotation) {
76
- return (typeof annotation === 'object' &&
77
- annotation !== null &&
78
- 'type' in annotation &&
79
- annotation.type === 'file_path');
80
- }
81
- // Helper to check if output has a type property
82
- export function hasTypeProperty(item) {
83
- return (typeof item === 'object' && item !== null && 'type' in item && typeof item.type === 'string');
84
- }
85
- //# sourceMappingURL=stream-type-guards.js.map
@@ -1,68 +0,0 @@
1
- import type { $ZodObject, $ZodShape } from 'zod/v4/core';
2
- import type { ToolExecuteContext, TurnContext } from './tool-types.js';
3
- /**
4
- * Listener function called when context values change
5
- * Receives a shallow copy of the full context store
6
- */
7
- type ContextChangeListener = (snapshot: Record<string, Record<string, unknown>>) => void;
8
- /**
9
- * Context input can be a static value, a sync function, or an async function
10
- */
11
- export type ContextInput<T extends Record<string, Record<string, unknown>>> = T | ((turn: TurnContext) => T) | ((turn: TurnContext) => Promise<T>);
12
- /**
13
- * Mutable context store shared across all tool executions within a callModel invocation.
14
- * Stores context keyed by tool name: `{ get_weather: { apiKey: '...' }, db_query: { dbUrl: '...' } }`.
15
- * Notifies listeners on changes.
16
- */
17
- export declare class ToolContextStore {
18
- private store;
19
- private listeners;
20
- constructor(initialValues?: Record<string, Record<string, unknown>>);
21
- /** Subscribe to context changes. Returns an unsubscribe function. */
22
- subscribe(listener: ContextChangeListener): () => void;
23
- /** Get a deep-shallow copy of the full context (all tools) */
24
- getSnapshot(): Record<string, Record<string, unknown>>;
25
- /** Get a shallow copy of context for a specific tool */
26
- getToolContext(toolName: string): Record<string, unknown>;
27
- /** Set context for a specific tool and notify listeners */
28
- setToolContext(toolName: string, values: Record<string, unknown>): void;
29
- /** Merge partial values into a specific tool's context and notify listeners */
30
- mergeToolContext(toolName: string, partial: Record<string, unknown>): void;
31
- private notifyListeners;
32
- }
33
- /**
34
- * Build a flat ToolExecuteContext for a specific tool.
35
- * Returns a merged object with TurnContext fields, a `local` getter
36
- * (reads from the store on each access), `shared` getter, and mutation methods.
37
- *
38
- * The `local` and `shared` getters are live — calling `setContext()` or
39
- * `setSharedContext()` and then reading the property reflects updated values immediately.
40
- *
41
- * @param turnContext - The current turn context
42
- * @param store - The shared context store (keyed by tool name)
43
- * @param toolName - The tool's name
44
- * @param schema - The tool's contextSchema (for validation)
45
- * @param sharedSchema - The shared contextSchema (for validation)
46
- * @returns A flat ToolExecuteContext
47
- */
48
- export declare function buildToolExecuteContext<TName extends string, TContext extends Record<string, unknown>, TShared extends Record<string, unknown> = Record<string, unknown>>(turnContext: TurnContext, store: ToolContextStore | undefined, toolName: TName, schema: $ZodObject<$ZodShape> | undefined, sharedSchema?: $ZodObject<$ZodShape> | undefined): ToolExecuteContext<TName, TContext, TShared>;
49
- /**
50
- * Resolve a context input (static value, sync function, or async function) to a plain object.
51
- *
52
- * @param contextInput - The context value or function from callModel
53
- * @param turnContext - The current turn context for function resolution
54
- * @returns The resolved context object (keyed by tool name)
55
- */
56
- export declare function resolveContext<T extends Record<string, Record<string, unknown>>>(contextInput: ContextInput<T> | undefined, turnContext: TurnContext): Promise<T>;
57
- /**
58
- * Extract and validate context values for a specific tool from the context store.
59
- * Returns a shallow copy so the caller cannot mutate the store directly.
60
- *
61
- * @param store - The shared context store (keyed by tool name)
62
- * @param toolName - The tool's name
63
- * @param schema - The tool's contextSchema
64
- * @returns A shallow copy of the validated context values for this tool
65
- */
66
- export declare function extractToolContext(store: ToolContextStore, toolName: string, schema: $ZodObject<$ZodShape> | undefined): Record<string, unknown>;
67
- export {};
68
- //# sourceMappingURL=tool-context.d.ts.map
@@ -1,175 +0,0 @@
1
- import * as z4 from 'zod/v4';
2
- import { SHARED_CONTEXT_KEY } from './tool-types.js';
3
- //#endregion
4
- //#region ToolContextStore
5
- /**
6
- * Mutable context store shared across all tool executions within a callModel invocation.
7
- * Stores context keyed by tool name: `{ get_weather: { apiKey: '...' }, db_query: { dbUrl: '...' } }`.
8
- * Notifies listeners on changes.
9
- */
10
- export class ToolContextStore {
11
- constructor(initialValues = {}) {
12
- this.listeners = new Set();
13
- this.store = {};
14
- for (const [key, value] of Object.entries(initialValues)) {
15
- this.store[key] = { ...value };
16
- }
17
- }
18
- /** Subscribe to context changes. Returns an unsubscribe function. */
19
- subscribe(listener) {
20
- this.listeners.add(listener);
21
- return () => {
22
- this.listeners.delete(listener);
23
- };
24
- }
25
- /** Get a deep-shallow copy of the full context (all tools) */
26
- getSnapshot() {
27
- const snapshot = {};
28
- for (const [key, value] of Object.entries(this.store)) {
29
- snapshot[key] = { ...value };
30
- }
31
- return snapshot;
32
- }
33
- /** Get a shallow copy of context for a specific tool */
34
- getToolContext(toolName) {
35
- const data = this.store[toolName];
36
- if (!data) {
37
- return {};
38
- }
39
- return { ...data };
40
- }
41
- /** Set context for a specific tool and notify listeners */
42
- setToolContext(toolName, values) {
43
- this.store[toolName] = { ...values };
44
- this.notifyListeners();
45
- }
46
- /** Merge partial values into a specific tool's context and notify listeners */
47
- mergeToolContext(toolName, partial) {
48
- const existing = this.store[toolName] ?? {};
49
- this.store[toolName] = { ...existing, ...partial };
50
- this.notifyListeners();
51
- }
52
- notifyListeners() {
53
- const snapshot = {};
54
- for (const [key, value] of Object.entries(this.store)) {
55
- snapshot[key] = { ...value };
56
- }
57
- for (const listener of this.listeners) {
58
- listener(snapshot);
59
- }
60
- }
61
- }
62
- //#endregion
63
- //#region buildToolExecuteContext
64
- /**
65
- * Validate a partial update against a schema's shape, filtering to known keys
66
- * and validating each key individually. Returns the filtered partial.
67
- */
68
- function validatePartialAgainstSchema(partial, schema) {
69
- const schemaKeys = Object.keys(schema._zod.def.shape);
70
- const filteredPartial = {};
71
- for (const [key, value] of Object.entries(partial)) {
72
- if (schemaKeys.includes(key)) {
73
- filteredPartial[key] = value;
74
- }
75
- }
76
- const shape = schema._zod.def.shape;
77
- for (const [key, value] of Object.entries(filteredPartial)) {
78
- const keySchema = shape[key];
79
- if (keySchema) {
80
- z4.parse(keySchema, value);
81
- }
82
- }
83
- return filteredPartial;
84
- }
85
- /**
86
- * Build a flat ToolExecuteContext for a specific tool.
87
- * Returns a merged object with TurnContext fields, a `local` getter
88
- * (reads from the store on each access), `shared` getter, and mutation methods.
89
- *
90
- * The `local` and `shared` getters are live — calling `setContext()` or
91
- * `setSharedContext()` and then reading the property reflects updated values immediately.
92
- *
93
- * @param turnContext - The current turn context
94
- * @param store - The shared context store (keyed by tool name)
95
- * @param toolName - The tool's name
96
- * @param schema - The tool's contextSchema (for validation)
97
- * @param sharedSchema - The shared contextSchema (for validation)
98
- * @returns A flat ToolExecuteContext
99
- */
100
- export function buildToolExecuteContext(turnContext, store, toolName, schema, sharedSchema) {
101
- // Validate initial context eagerly (throws on bad data)
102
- if (store && schema) {
103
- extractToolContext(store, toolName, schema);
104
- }
105
- if (store && sharedSchema) {
106
- extractToolContext(store, SHARED_CONTEXT_KEY, sharedSchema);
107
- }
108
- const ctx = {
109
- ...turnContext,
110
- get local() {
111
- const data = store ? store.getToolContext(toolName) : {};
112
- return Object.freeze(data);
113
- },
114
- setContext(partial) {
115
- if (!store || !schema) {
116
- return;
117
- }
118
- const filteredPartial = validatePartialAgainstSchema(partial, schema);
119
- store.mergeToolContext(toolName, filteredPartial);
120
- },
121
- get shared() {
122
- const data = store ? store.getToolContext(SHARED_CONTEXT_KEY) : {};
123
- return Object.freeze(data);
124
- },
125
- setSharedContext(partial) {
126
- if (!store || !sharedSchema) {
127
- return;
128
- }
129
- const filteredPartial = validatePartialAgainstSchema(partial, sharedSchema);
130
- store.mergeToolContext(SHARED_CONTEXT_KEY, filteredPartial);
131
- },
132
- };
133
- return ctx;
134
- }
135
- //#endregion
136
- //#region resolveContext
137
- /**
138
- * Resolve a context input (static value, sync function, or async function) to a plain object.
139
- *
140
- * @param contextInput - The context value or function from callModel
141
- * @param turnContext - The current turn context for function resolution
142
- * @returns The resolved context object (keyed by tool name)
143
- */
144
- export async function resolveContext(contextInput, turnContext) {
145
- if (contextInput === undefined) {
146
- return {};
147
- }
148
- if (typeof contextInput === 'function') {
149
- return Promise.resolve(contextInput(turnContext));
150
- }
151
- return contextInput;
152
- }
153
- //#endregion
154
- //#region extractToolContext
155
- /**
156
- * Extract and validate context values for a specific tool from the context store.
157
- * Returns a shallow copy so the caller cannot mutate the store directly.
158
- *
159
- * @param store - The shared context store (keyed by tool name)
160
- * @param toolName - The tool's name
161
- * @param schema - The tool's contextSchema
162
- * @returns A shallow copy of the validated context values for this tool
163
- */
164
- export function extractToolContext(store, toolName, schema) {
165
- if (!schema) {
166
- return {};
167
- }
168
- const toolData = store.getToolContext(toolName);
169
- // Validate the extracted values against the schema
170
- z4.parse(schema, toolData);
171
- // getToolContext already returns a shallow copy
172
- return toolData;
173
- }
174
- //#endregion
175
- //# sourceMappingURL=tool-context.js.map
@@ -1,44 +0,0 @@
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 declare class ToolEventBroadcaster<T> {
12
- private buffer;
13
- private consumers;
14
- private nextConsumerId;
15
- private isComplete;
16
- private completionError;
17
- /**
18
- * Push a new event to all consumers.
19
- * Events are buffered so late-joining consumers can catch up.
20
- */
21
- push(event: T): void;
22
- /**
23
- * Mark the broadcaster as complete - no more events will be pushed.
24
- * Optionally pass an error to signal failure to all consumers.
25
- * Cleans up buffer and consumers after completion.
26
- */
27
- complete(error?: Error): void;
28
- /**
29
- * Clean up resources after all consumers have finished.
30
- * Called automatically after complete(), but can be called manually.
31
- */
32
- private cleanup;
33
- /**
34
- * Create a new consumer that can independently iterate over events.
35
- * Consumers can join at any time and will receive events from position 0.
36
- * Multiple consumers can be created and will all receive the same events.
37
- */
38
- createConsumer(): AsyncIterableIterator<T>;
39
- /**
40
- * Notify all waiting consumers that new data is available or stream completed
41
- */
42
- private notifyWaitingConsumers;
43
- }
44
- //# sourceMappingURL=tool-event-broadcaster.d.ts.map
@@ -1,146 +0,0 @@
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 { done: true, value: undefined };
72
- }
73
- if (consumer.cancelled) {
74
- return { done: true, value: undefined };
75
- }
76
- // Return buffered event if available
77
- if (consumer.position < self.buffer.length) {
78
- const value = self.buffer[consumer.position];
79
- consumer.position++;
80
- return { done: false, value };
81
- }
82
- // If complete and caught up, we're done
83
- if (self.isComplete) {
84
- self.consumers.delete(consumerId);
85
- self.cleanup();
86
- if (self.completionError) {
87
- throw self.completionError;
88
- }
89
- return { done: true, value: undefined };
90
- }
91
- // Set up waiting promise FIRST to avoid race condition
92
- const waitPromise = new Promise((resolve, reject) => {
93
- consumer.waitingPromise = { resolve, reject };
94
- // Immediately check if we should resolve after setting up promise
95
- if (self.isComplete ||
96
- self.completionError ||
97
- consumer.position < self.buffer.length) {
98
- resolve();
99
- }
100
- });
101
- await waitPromise;
102
- consumer.waitingPromise = null;
103
- // Recursively try again after waking up
104
- return this.next();
105
- },
106
- async return() {
107
- const consumer = self.consumers.get(consumerId);
108
- if (consumer) {
109
- consumer.cancelled = true;
110
- self.consumers.delete(consumerId);
111
- self.cleanup();
112
- }
113
- return { done: true, value: undefined };
114
- },
115
- async throw(e) {
116
- const consumer = self.consumers.get(consumerId);
117
- if (consumer) {
118
- consumer.cancelled = true;
119
- self.consumers.delete(consumerId);
120
- self.cleanup();
121
- }
122
- throw e;
123
- },
124
- [Symbol.asyncIterator]() {
125
- return this;
126
- },
127
- };
128
- }
129
- /**
130
- * Notify all waiting consumers that new data is available or stream completed
131
- */
132
- notifyWaitingConsumers() {
133
- for (const consumer of this.consumers.values()) {
134
- if (consumer.waitingPromise) {
135
- if (this.completionError) {
136
- consumer.waitingPromise.reject(this.completionError);
137
- }
138
- else {
139
- consumer.waitingPromise.resolve();
140
- }
141
- consumer.waitingPromise = null;
142
- }
143
- }
144
- }
145
- }
146
- //# sourceMappingURL=tool-event-broadcaster.js.map
@@ -1,74 +0,0 @@
1
- import type { $ZodType } from 'zod/v4/core';
2
- import type { $ZodObject, $ZodShape } from 'zod/v4/core';
3
- import type { APITool, ParsedToolCall, Tool, ToolExecutionResult, TurnContext } from './tool-types.js';
4
- import * as z4 from 'zod/v4';
5
- import { type ToolContextStore } from './tool-context.js';
6
- export declare const ZodError: z4.z.core.$constructor<z4.ZodError<unknown>, z4.z.core.$ZodIssue[]>;
7
- /**
8
- * Recursively remove keys prefixed with ~ from an object.
9
- * These are metadata properties (like ~standard from Standard Schema)
10
- * that should not be sent to downstream providers.
11
- * @see https://github.com/OpenRouterTeam/typescript-sdk/issues/131
12
- *
13
- * When given a Record<string, unknown>, returns Record<string, unknown>.
14
- * When given unknown, returns unknown (preserves primitives, null, etc).
15
- */
16
- export declare function sanitizeJsonSchema(obj: Record<string, unknown>): Record<string, unknown>;
17
- export declare function sanitizeJsonSchema(obj: unknown): unknown;
18
- /**
19
- * Convert a Zod schema to JSON Schema using Zod v4's toJSONSchema function.
20
- * Accepts ZodType from the main zod package for user compatibility.
21
- * The resulting schema is sanitized to remove metadata properties (like ~standard)
22
- * that would cause 400 errors with downstream providers.
23
- */
24
- export declare function convertZodToJsonSchema(zodSchema: $ZodType): Record<string, unknown>;
25
- /**
26
- * Convert tools to OpenRouter API format
27
- * Accepts readonly arrays for better type compatibility
28
- */
29
- export declare function convertToolsToAPIFormat(tools: readonly Tool[]): APITool[];
30
- /**
31
- * Validate tool input against Zod schema
32
- * @throws ZodError if validation fails
33
- */
34
- export declare function validateToolInput<T>(schema: $ZodType<T>, args: unknown): T;
35
- /**
36
- * Validate tool output against Zod schema
37
- * @throws ZodError if validation fails
38
- */
39
- export declare function validateToolOutput<T>(schema: $ZodType<T>, result: unknown): T;
40
- /**
41
- * Parse tool call arguments from JSON string.
42
- * Treats empty/whitespace-only strings as an empty object — some providers
43
- * return `arguments: ""` for tools that take no parameters.
44
- */
45
- export declare function parseToolCallArguments(argumentsString: string): unknown;
46
- /**
47
- * Execute a regular (non-generator) tool
48
- */
49
- export declare function executeRegularTool(tool: Tool, toolCall: ParsedToolCall<Tool>, context: TurnContext, contextStore?: ToolContextStore, sharedSchema?: $ZodObject<$ZodShape>): Promise<ToolExecutionResult<Tool>>;
50
- /**
51
- * Execute a generator tool and collect preliminary and final results
52
- * - Intermediate yields are validated against eventSchema (preliminary events)
53
- * - Last yield is validated against outputSchema (final result sent to model)
54
- * - Generator must emit at least one value
55
- */
56
- 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>>;
57
- /**
58
- * Execute a tool call
59
- * Automatically detects if it's a regular or generator tool
60
- */
61
- 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>>;
62
- /**
63
- * Find a tool by name in the tools array
64
- */
65
- export declare function findToolByName(tools: Tool[], name: string): Tool | undefined;
66
- /**
67
- * Format tool execution result as a string for sending to the model
68
- */
69
- export declare function formatToolResultForModel(result: ToolExecutionResult<Tool>): string;
70
- /**
71
- * Create a user-friendly error message for tool execution errors
72
- */
73
- export declare function formatToolExecutionError(error: Error, toolCall: ParsedToolCall<Tool>): string;
74
- //# sourceMappingURL=tool-executor.d.ts.map