@openrouter/sdk 1.5.55 → 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 (104) 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 +51 -4
  20. package/esm/models/imagegenerationrequest.js +32 -1
  21. package/esm/models/index.d.ts +6 -0
  22. package/esm/models/index.js +6 -0
  23. package/esm/models/mcpapprovalrequestitem.d.ts +7 -0
  24. package/esm/models/mcpapprovalrequestitem.js +19 -1
  25. package/esm/models/mcpcallitem.d.ts +17 -1
  26. package/esm/models/mcpcallitem.js +18 -0
  27. package/esm/models/mcpservertool.d.ts +78 -69
  28. package/esm/models/mcpservertool.js +135 -105
  29. package/esm/models/mcpservertoolopenrouter.d.ts +28 -0
  30. package/esm/models/mcpservertoolopenrouter.js +20 -0
  31. package/esm/models/mcpservertoolparameters.d.ts +152 -0
  32. package/esm/models/mcpservertoolparameters.js +134 -0
  33. package/esm/models/openairesponsestoolchoiceunion.d.ts +3 -2
  34. package/esm/models/openairesponsestoolchoiceunion.js +3 -0
  35. package/esm/models/operations/listbyokkeys.d.ts +1 -0
  36. package/esm/models/operations/listbyokkeys.js +1 -0
  37. package/esm/models/outputitemmcpapprovalrequest.d.ts +14 -0
  38. package/esm/models/outputitemmcpapprovalrequest.js +23 -0
  39. package/esm/models/outputitemmcpcall.d.ts +74 -0
  40. package/esm/models/outputitemmcpcall.js +94 -0
  41. package/esm/models/outputitemmcplisttools.d.ts +25 -0
  42. package/esm/models/outputitemmcplisttools.js +37 -0
  43. package/esm/models/outputitems.d.ts +3 -0
  44. package/esm/models/outputitems.js +2 -0
  45. package/esm/models/providername.d.ts +1 -0
  46. package/esm/models/providername.js +1 -0
  47. package/esm/models/provideroptions.d.ts +6 -0
  48. package/esm/models/provideroptions.js +1 -0
  49. package/esm/models/providerresponse.d.ts +1 -0
  50. package/esm/models/providerresponse.js +1 -0
  51. package/esm/models/responsesrequest.d.ts +9 -0
  52. package/esm/models/responsesrequest.js +3 -0
  53. package/esm/models/toolchoicemcp.d.ts +33 -0
  54. package/esm/models/toolchoicemcp.js +42 -0
  55. package/esm/models/toolsearchoutputitem.d.ts +5 -4
  56. package/esm/models/toolsearchoutputitem.js +3 -0
  57. package/esm/models/updateworkspacerequest.d.ts +1 -0
  58. package/esm/models/updateworkspacerequest.js +1 -0
  59. package/esm/models/videogenerationrequest.d.ts +6 -0
  60. package/esm/models/videogenerationrequest.js +1 -0
  61. package/esm/sdk/sdk.d.ts +0 -9
  62. package/esm/sdk/sdk.js +1 -7
  63. package/jsr.json +1 -1
  64. package/package.json +5 -5
  65. package/esm/funcs/call-model.d.ts +0 -67
  66. package/esm/funcs/call-model.js +0 -98
  67. package/esm/lib/anthropic-compat.d.ts +0 -51
  68. package/esm/lib/anthropic-compat.js +0 -222
  69. package/esm/lib/async-params.d.ts +0 -107
  70. package/esm/lib/async-params.js +0 -88
  71. package/esm/lib/chat-compat.d.ts +0 -47
  72. package/esm/lib/chat-compat.js +0 -111
  73. package/esm/lib/claude-constants.d.ts +0 -22
  74. package/esm/lib/claude-constants.js +0 -20
  75. package/esm/lib/claude-type-guards.d.ts +0 -10
  76. package/esm/lib/claude-type-guards.js +0 -70
  77. package/esm/lib/conversation-state.d.ts +0 -63
  78. package/esm/lib/conversation-state.js +0 -210
  79. package/esm/lib/model-result.d.ts +0 -373
  80. package/esm/lib/model-result.js +0 -1414
  81. package/esm/lib/next-turn-params.d.ts +0 -30
  82. package/esm/lib/next-turn-params.js +0 -135
  83. package/esm/lib/reusable-stream.d.ts +0 -39
  84. package/esm/lib/reusable-stream.js +0 -192
  85. package/esm/lib/stop-conditions.d.ts +0 -80
  86. package/esm/lib/stop-conditions.js +0 -104
  87. package/esm/lib/stream-transformers.d.ts +0 -118
  88. package/esm/lib/stream-transformers.js +0 -852
  89. package/esm/lib/stream-type-guards.d.ts +0 -49
  90. package/esm/lib/stream-type-guards.js +0 -85
  91. package/esm/lib/tool-context.d.ts +0 -68
  92. package/esm/lib/tool-context.js +0 -175
  93. package/esm/lib/tool-event-broadcaster.d.ts +0 -44
  94. package/esm/lib/tool-event-broadcaster.js +0 -146
  95. package/esm/lib/tool-executor.d.ts +0 -74
  96. package/esm/lib/tool-executor.js +0 -267
  97. package/esm/lib/tool-orchestrator.d.ts +0 -52
  98. package/esm/lib/tool-orchestrator.js +0 -180
  99. package/esm/lib/tool-types.d.ts +0 -573
  100. package/esm/lib/tool-types.js +0 -80
  101. package/esm/lib/tool.d.ts +0 -108
  102. package/esm/lib/tool.js +0 -74
  103. package/esm/lib/turn-context.d.ts +0 -52
  104. package/esm/lib/turn-context.js +0 -59
@@ -1,1414 +0,0 @@
1
- import { ToolEventBroadcaster } from './tool-event-broadcaster.js';
2
- import { ToolContextStore, resolveContext } from './tool-context.js';
3
- import { responsesSend } from '../funcs/responsesSend.js';
4
- import { hasAsyncFunctions, resolveAsyncFunctions, } from './async-params.js';
5
- import { appendToMessages, createInitialState, createRejectedResult, createUnsentResult, extractTextFromResponse as extractTextFromResponseState, partitionToolCalls, unsentResultsToAPIFormat, updateState, } from './conversation-state.js';
6
- import { ReusableReadableStream } from './reusable-stream.js';
7
- import { buildItemsStream, buildResponsesMessageStream, buildToolCallStream, consumeStreamForCompletion, extractReasoningDeltas, extractResponsesMessageFromResponse, extractTextDeltas, extractTextFromResponse, extractToolCallsFromResponse, extractToolDeltas, itemsStreamHandlers, streamTerminationEvents, } from './stream-transformers.js';
8
- import { executeTool } from './tool-executor.js';
9
- import { executeNextTurnParamsFunctions, applyNextTurnParamsToRequest } from './next-turn-params.js';
10
- import { hasExecuteFunction, isToolCallOutputEvent } from './tool-types.js';
11
- import { isStopConditionMet, stepCountIs } from './stop-conditions.js';
12
- import { isFunctionCallItem, isResponseCompletedEvent, isResponseFailedEvent, isResponseIncompleteEvent, isOutputTextDeltaEvent, isReasoningDeltaEvent, hasTypeProperty, } from './stream-type-guards.js';
13
- /**
14
- * Default maximum number of tool execution steps if no stopWhen is specified.
15
- * This prevents infinite loops in tool execution.
16
- */
17
- const DEFAULT_MAX_STEPS = 5;
18
- /**
19
- * Type guard for stream event with toReadableStream method
20
- * Checks constructor name, prototype, and method availability
21
- */
22
- function isEventStream(value) {
23
- if (value === null || typeof value !== 'object') {
24
- return false;
25
- }
26
- // Check constructor name for EventStream
27
- const constructorName = Object.getPrototypeOf(value)?.constructor?.name;
28
- if (constructorName === 'EventStream') {
29
- return true;
30
- }
31
- // Fallback: check for toReadableStream method (may be on prototype)
32
- const maybeStream = value;
33
- return typeof maybeStream.toReadableStream === 'function';
34
- }
35
- /**
36
- * A wrapper around a streaming response that provides multiple consumption patterns.
37
- *
38
- * Allows consuming the response in multiple ways:
39
- * - `await result.getText()` - Get just the text
40
- * - `await result.getResponse()` - Get the full response object
41
- * - `for await (const delta of result.getTextStream())` - Stream text deltas
42
- * - `for await (const msg of result.getNewMessagesStream())` - Stream cumulative message snapshots
43
- * - `for await (const event of result.getFullResponsesStream())` - Stream all response events
44
- *
45
- * For message format conversion, use the helper functions:
46
- * - `toChatMessage(response)` for OpenAI chat format
47
- * - `toClaudeMessage(response)` for Anthropic Claude format
48
- *
49
- * All consumption patterns can be used concurrently thanks to the underlying
50
- * ReusableReadableStream implementation.
51
- *
52
- * @template TTools - The tools array type to enable typed tool calls and results
53
- * @template TShared - The shape of the shared context (inferred from sharedContextSchema)
54
- */
55
- export class ModelResult {
56
- constructor(options) {
57
- this.reusableStream = null;
58
- this.textPromise = null;
59
- this.initPromise = null;
60
- this.toolExecutionPromise = null;
61
- this.finalResponse = null;
62
- this.toolEventBroadcaster = null;
63
- this.allToolExecutionRounds = [];
64
- // Track resolved request after async function resolution
65
- this.resolvedRequest = null;
66
- // State management for multi-turn conversations
67
- this.stateAccessor = null;
68
- this.currentState = null;
69
- this.requireApprovalFn = null;
70
- this.approvedToolCalls = [];
71
- this.rejectedToolCalls = [];
72
- this.isResumingFromApproval = false;
73
- // Unified turn broadcaster for multi-turn streaming
74
- this.turnBroadcaster = null;
75
- this.initialStreamPipeStarted = false;
76
- this.initialPipePromise = null;
77
- // Context store for typed tool context (persists across turns)
78
- this.contextStore = null;
79
- this.options = options;
80
- // Runtime validation: approval decisions require state
81
- const hasApprovalDecisions = (options.approveToolCalls && options.approveToolCalls.length > 0) ||
82
- (options.rejectToolCalls && options.rejectToolCalls.length > 0);
83
- if (hasApprovalDecisions && !options.state) {
84
- throw new Error('approveToolCalls and rejectToolCalls require a state accessor. ' +
85
- 'Provide a StateAccessor via the "state" parameter to persist approval decisions.');
86
- }
87
- // Initialize state management
88
- this.stateAccessor = options.state ?? null;
89
- this.requireApprovalFn = options.requireApproval ?? null;
90
- this.approvedToolCalls = options.approveToolCalls ?? [];
91
- this.rejectedToolCalls = options.rejectToolCalls ?? [];
92
- }
93
- /**
94
- * Get or create the unified turn broadcaster (lazy initialization).
95
- * Broadcasts all API stream events, tool events, and turn delimiters across turns.
96
- */
97
- ensureTurnBroadcaster() {
98
- if (!this.turnBroadcaster) {
99
- this.turnBroadcaster = new ToolEventBroadcaster();
100
- }
101
- return this.turnBroadcaster;
102
- }
103
- /**
104
- * Start piping the initial stream into the turn broadcaster.
105
- * Idempotent — only starts once even if called multiple times.
106
- * Wraps the initial stream events with turn.start(0) / turn.end(0) delimiters.
107
- */
108
- startInitialStreamPipe() {
109
- if (this.initialStreamPipeStarted)
110
- return;
111
- this.initialStreamPipeStarted = true;
112
- const broadcaster = this.ensureTurnBroadcaster();
113
- if (!this.reusableStream) {
114
- return;
115
- }
116
- const stream = this.reusableStream;
117
- this.initialPipePromise = (async () => {
118
- broadcaster.push({
119
- type: 'turn.start',
120
- turnNumber: 0,
121
- timestamp: Date.now(),
122
- });
123
- const consumer = stream.createConsumer();
124
- for await (const event of consumer) {
125
- broadcaster.push(event);
126
- }
127
- broadcaster.push({
128
- type: 'turn.end',
129
- turnNumber: 0,
130
- timestamp: Date.now(),
131
- });
132
- })().catch((error) => {
133
- broadcaster.complete(error instanceof Error ? error : new Error(String(error)));
134
- });
135
- }
136
- /**
137
- * Pipe a follow-up stream into the turn broadcaster and capture the completed response.
138
- * Emits turn.start / turn.end delimiters around the stream events.
139
- */
140
- async pipeAndConsumeStream(stream, turnNumber) {
141
- const broadcaster = this.turnBroadcaster;
142
- broadcaster.push({
143
- type: 'turn.start',
144
- turnNumber,
145
- timestamp: Date.now(),
146
- });
147
- const consumer = stream.createConsumer();
148
- let completedResponse = null;
149
- for await (const event of consumer) {
150
- broadcaster.push(event);
151
- if (isResponseCompletedEvent(event)) {
152
- completedResponse = event.response;
153
- }
154
- if (isResponseFailedEvent(event)) {
155
- const errorMsg = 'message' in event ? String(event.message) : 'Response failed';
156
- throw new Error(errorMsg);
157
- }
158
- if (isResponseIncompleteEvent(event)) {
159
- completedResponse = event.response;
160
- }
161
- }
162
- broadcaster.push({
163
- type: 'turn.end',
164
- turnNumber,
165
- timestamp: Date.now(),
166
- });
167
- if (!completedResponse) {
168
- throw new Error('Follow-up stream ended without a completed response');
169
- }
170
- return completedResponse;
171
- }
172
- /**
173
- * Push a tool result event to both the legacy tool event broadcaster
174
- * and the unified turn broadcaster.
175
- */
176
- broadcastToolResult(toolCallId, result, preliminaryResults) {
177
- this.toolEventBroadcaster?.push({
178
- type: 'tool_result',
179
- toolCallId,
180
- result,
181
- ...(preliminaryResults?.length && { preliminaryResults }),
182
- });
183
- this.turnBroadcaster?.push({
184
- type: 'tool.result',
185
- toolCallId,
186
- result,
187
- timestamp: Date.now(),
188
- ...(preliminaryResults?.length && { preliminaryResults }),
189
- });
190
- }
191
- /**
192
- * Push a preliminary result event to both the legacy tool event broadcaster
193
- * and the unified turn broadcaster.
194
- */
195
- broadcastPreliminaryResult(toolCallId, result) {
196
- this.toolEventBroadcaster?.push({
197
- type: 'preliminary_result',
198
- toolCallId,
199
- result,
200
- });
201
- this.turnBroadcaster?.push({
202
- type: 'tool.preliminary_result',
203
- toolCallId,
204
- result,
205
- timestamp: Date.now(),
206
- });
207
- }
208
- /**
209
- * Set up the turn broadcaster with tool execution and return the consumer.
210
- * Used by stream methods that need to iterate over all turns.
211
- */
212
- startTurnBroadcasterExecution() {
213
- const broadcaster = this.ensureTurnBroadcaster();
214
- this.startInitialStreamPipe();
215
- const consumer = broadcaster.createConsumer();
216
- const executionPromise = this.executeToolsIfNeeded().finally(async () => {
217
- // Wait for the initial stream pipe to finish pushing all events
218
- // (including turn.end) before marking the broadcaster as complete.
219
- // Without this, turn.end can be silently dropped if the pipe hasn't
220
- // finished when executeToolsIfNeeded completes.
221
- if (this.initialPipePromise) {
222
- await this.initialPipePromise;
223
- }
224
- broadcaster.complete();
225
- });
226
- return { consumer, executionPromise };
227
- }
228
- /**
229
- * Type guard to check if a value is a non-streaming response
230
- * Only requires 'output' field and absence of 'toReadableStream' method
231
- */
232
- isNonStreamingResponse(value) {
233
- return (value !== null &&
234
- typeof value === 'object' &&
235
- 'output' in value &&
236
- !('toReadableStream' in value));
237
- }
238
- // =========================================================================
239
- // Extracted Helper Methods for executeToolsIfNeeded
240
- // =========================================================================
241
- /**
242
- * Get initial response from stream or cached final response.
243
- * Consumes the stream to completion if needed to extract the response.
244
- *
245
- * @returns The complete non-streaming response
246
- * @throws Error if neither stream nor response has been initialized
247
- */
248
- async getInitialResponse() {
249
- if (this.finalResponse) {
250
- return this.finalResponse;
251
- }
252
- if (this.reusableStream) {
253
- return consumeStreamForCompletion(this.reusableStream);
254
- }
255
- throw new Error('Neither stream nor response initialized');
256
- }
257
- /**
258
- * Save response output to state.
259
- * Appends the response output to the message history and records the response ID.
260
- *
261
- * @param response - The API response to save
262
- */
263
- async saveResponseToState(response) {
264
- if (!this.stateAccessor || !this.currentState)
265
- return;
266
- const outputItems = Array.isArray(response.output)
267
- ? response.output
268
- : [response.output];
269
- await this.saveStateSafely({
270
- messages: appendToMessages(this.currentState.messages, outputItems),
271
- previousResponseId: response.id,
272
- });
273
- }
274
- /**
275
- * Mark state as complete.
276
- * Sets the conversation status to 'complete' indicating no further tool execution is needed.
277
- */
278
- async markStateComplete() {
279
- await this.saveStateSafely({ status: 'complete' });
280
- }
281
- /**
282
- * Save tool results to state.
283
- * Appends tool execution results to the message history for multi-turn context.
284
- *
285
- * @param toolResults - The tool execution results to save
286
- */
287
- async saveToolResultsToState(toolResults) {
288
- if (!this.currentState)
289
- return;
290
- await this.saveStateSafely({
291
- messages: appendToMessages(this.currentState.messages, toolResults),
292
- });
293
- }
294
- /**
295
- * Check if execution should be interrupted by external signal.
296
- * Polls the state accessor for interruption flags set by external processes.
297
- *
298
- * @param currentResponse - The current response to save as partial state
299
- * @returns True if interrupted and caller should exit, false to continue
300
- */
301
- async checkForInterruption(currentResponse) {
302
- if (!this.stateAccessor)
303
- return false;
304
- const freshState = await this.stateAccessor.load();
305
- if (!freshState?.interruptedBy)
306
- return false;
307
- // Save partial state
308
- if (this.currentState) {
309
- const currentToolCalls = extractToolCallsFromResponse(currentResponse);
310
- await this.saveStateSafely({
311
- status: 'interrupted',
312
- partialResponse: {
313
- text: extractTextFromResponseState(currentResponse),
314
- toolCalls: currentToolCalls,
315
- },
316
- });
317
- }
318
- this.finalResponse = currentResponse;
319
- return true;
320
- }
321
- /**
322
- * Check if stop conditions are met.
323
- * Returns true if execution should stop.
324
- *
325
- * @remarks
326
- * Default: stepCountIs(DEFAULT_MAX_STEPS) if no stopWhen is specified.
327
- * This evaluates stop conditions against the complete step history.
328
- */
329
- async shouldStopExecution() {
330
- const stopWhen = this.options.stopWhen ?? stepCountIs(DEFAULT_MAX_STEPS);
331
- const stopConditions = Array.isArray(stopWhen)
332
- ? stopWhen
333
- : [stopWhen];
334
- return isStopConditionMet({
335
- stopConditions,
336
- steps: this.allToolExecutionRounds.map((round) => ({
337
- stepType: 'continue',
338
- text: extractTextFromResponse(round.response),
339
- toolCalls: round.toolCalls,
340
- toolResults: round.toolResults.map((tr) => ({
341
- toolCallId: tr.callId,
342
- toolName: round.toolCalls.find((tc) => tc.id === tr.callId)?.name ?? '',
343
- result: typeof tr.output === 'string' ? JSON.parse(tr.output) : tr.output,
344
- })),
345
- response: round.response,
346
- usage: round.response.usage,
347
- finishReason: undefined,
348
- })),
349
- });
350
- }
351
- /**
352
- * Check if any tool calls have execute functions.
353
- * Used to determine if automatic tool execution should be attempted.
354
- *
355
- * @param toolCalls - The tool calls to check
356
- * @returns True if at least one tool call has an executable function
357
- */
358
- hasExecutableToolCalls(toolCalls) {
359
- return toolCalls.some((toolCall) => {
360
- const tool = this.options.tools?.find((t) => t.function.name === toolCall.name);
361
- return tool && hasExecuteFunction(tool);
362
- });
363
- }
364
- /**
365
- * Execute tools that can auto-execute (don't require approval) in parallel.
366
- *
367
- * @param toolCalls - The tool calls to execute
368
- * @param turnContext - The current turn context
369
- * @returns Array of unsent tool results for later submission
370
- */
371
- async executeAutoApproveTools(toolCalls, turnContext) {
372
- const toolCallPromises = toolCalls.map(async (tc) => {
373
- const tool = this.options.tools?.find(t => t.function.name === tc.name);
374
- if (!tool || !hasExecuteFunction(tool)) {
375
- return null;
376
- }
377
- const result = await executeTool(tool, tc, turnContext, undefined, this.contextStore ?? undefined, this.options.sharedContextSchema);
378
- if (result.error) {
379
- return createRejectedResult(tc.id, String(tc.name), result.error.message);
380
- }
381
- return createUnsentResult(tc.id, String(tc.name), result.result);
382
- });
383
- const settledResults = await Promise.allSettled(toolCallPromises);
384
- const results = [];
385
- for (let i = 0; i < settledResults.length; i++) {
386
- const settled = settledResults[i];
387
- const tc = toolCalls[i];
388
- if (!settled || !tc)
389
- continue;
390
- if (settled.status === 'rejected') {
391
- const errorMessage = settled.reason instanceof Error
392
- ? settled.reason.message
393
- : String(settled.reason);
394
- results.push(createRejectedResult(tc.id, String(tc.name), errorMessage));
395
- continue;
396
- }
397
- if (settled.value) {
398
- results.push(settled.value);
399
- }
400
- }
401
- return results;
402
- }
403
- /**
404
- * Check for tools requiring approval and handle accordingly.
405
- * Partitions tool calls into those needing approval and those that can auto-execute.
406
- *
407
- * @param toolCalls - The tool calls to check
408
- * @param currentRound - The current execution round (1-indexed)
409
- * @param currentResponse - The current response to save if pausing
410
- * @returns True if execution should pause for approval, false to continue
411
- * @throws Error if approval is required but no state accessor is configured
412
- */
413
- async handleApprovalCheck(toolCalls, currentRound, currentResponse) {
414
- if (!this.options.tools)
415
- return false;
416
- const turnContext = {
417
- numberOfTurns: currentRound,
418
- // context is handled via contextStore, not on TurnContext
419
- };
420
- const { requiresApproval: needsApproval, autoExecute } = await partitionToolCalls(toolCalls, this.options.tools, turnContext, this.requireApprovalFn ?? undefined);
421
- if (needsApproval.length === 0)
422
- return false;
423
- // Validate: approval requires state accessor
424
- if (!this.stateAccessor) {
425
- const toolNames = needsApproval.map(tc => tc.name).join(', ');
426
- throw new Error(`Tool(s) require approval but no state accessor is configured: ${toolNames}. ` +
427
- 'Provide a StateAccessor via the "state" parameter to enable approval workflows.');
428
- }
429
- // Execute auto-approve tools
430
- const unsentResults = await this.executeAutoApproveTools(autoExecute, turnContext);
431
- // Save state with pending approvals
432
- const stateUpdates = {
433
- pendingToolCalls: needsApproval,
434
- status: 'awaiting_approval',
435
- };
436
- if (unsentResults.length > 0) {
437
- stateUpdates.unsentToolResults = unsentResults;
438
- }
439
- await this.saveStateSafely(stateUpdates);
440
- this.finalResponse = currentResponse;
441
- return true; // Pause for approval
442
- }
443
- /**
444
- * Execute all tools in a single round in parallel.
445
- * Emits tool.result events after tool execution completes.
446
- *
447
- * @param toolCalls - The tool calls to execute
448
- * @param turnContext - The current turn context
449
- * @returns Array of function call outputs formatted for the API
450
- */
451
- async executeToolRound(toolCalls, turnContext) {
452
- const toolCallPromises = toolCalls.map(async (toolCall) => {
453
- const tool = this.options.tools?.find((t) => t.function.name === toolCall.name);
454
- if (!tool || !hasExecuteFunction(tool)) {
455
- return null;
456
- }
457
- // Check if arguments failed to parse (remained as string instead of object)
458
- const args = toolCall.arguments;
459
- if (typeof args === 'string') {
460
- const rawArgs = args;
461
- const errorMessage = `Failed to parse tool call arguments for "${toolCall.name}": The model provided invalid JSON. ` +
462
- `Raw arguments received: "${rawArgs}". ` +
463
- `Please provide valid JSON arguments for this tool call.`;
464
- this.broadcastToolResult(toolCall.id, { error: errorMessage });
465
- return {
466
- type: 'parse_error',
467
- toolCall,
468
- output: {
469
- type: 'function_call_output',
470
- id: `output_${toolCall.id}`,
471
- callId: toolCall.id,
472
- output: JSON.stringify({ error: errorMessage }),
473
- },
474
- };
475
- }
476
- const preliminaryResultsForCall = [];
477
- const hasBroadcaster = this.toolEventBroadcaster || this.turnBroadcaster;
478
- const onPreliminaryResult = hasBroadcaster
479
- ? (callId, resultValue) => {
480
- const typedResult = resultValue;
481
- preliminaryResultsForCall.push(typedResult);
482
- this.broadcastPreliminaryResult(callId, typedResult);
483
- }
484
- : undefined;
485
- const result = await executeTool(tool, toolCall, turnContext, onPreliminaryResult, this.contextStore ?? undefined, this.options.sharedContextSchema);
486
- return {
487
- type: 'execution',
488
- toolCall,
489
- tool,
490
- result,
491
- preliminaryResultsForCall,
492
- };
493
- });
494
- const settledResults = await Promise.allSettled(toolCallPromises);
495
- const toolResults = [];
496
- for (let i = 0; i < settledResults.length; i++) {
497
- const settled = settledResults[i];
498
- const originalToolCall = toolCalls[i];
499
- if (!settled || !originalToolCall)
500
- continue;
501
- if (settled.status === 'rejected') {
502
- const errorMessage = settled.reason instanceof Error
503
- ? settled.reason.message
504
- : String(settled.reason);
505
- this.broadcastToolResult(originalToolCall.id, { error: errorMessage });
506
- const rejectedOutput = {
507
- type: 'function_call_output',
508
- id: `output_${originalToolCall.id}`,
509
- callId: originalToolCall.id,
510
- output: JSON.stringify({ error: errorMessage }),
511
- };
512
- toolResults.push(rejectedOutput);
513
- this.turnBroadcaster?.push({
514
- type: 'tool.call_output',
515
- output: rejectedOutput,
516
- timestamp: Date.now(),
517
- });
518
- continue;
519
- }
520
- const value = settled.value;
521
- if (!value)
522
- continue;
523
- if (value.type === 'parse_error') {
524
- toolResults.push(value.output);
525
- this.turnBroadcaster?.push({
526
- type: 'tool.call_output',
527
- output: value.output,
528
- timestamp: Date.now(),
529
- });
530
- continue;
531
- }
532
- const toolResult = (value.result.error
533
- ? { error: value.result.error.message }
534
- : value.result.result);
535
- this.broadcastToolResult(value.toolCall.id, toolResult, value.preliminaryResultsForCall.length > 0 ? value.preliminaryResultsForCall : undefined);
536
- const executedOutput = {
537
- type: 'function_call_output',
538
- id: `output_${value.toolCall.id}`,
539
- callId: value.toolCall.id,
540
- output: value.result.error
541
- ? JSON.stringify({ error: value.result.error.message })
542
- : JSON.stringify(value.result.result),
543
- };
544
- toolResults.push(executedOutput);
545
- this.turnBroadcaster?.push({
546
- type: 'tool.call_output',
547
- output: executedOutput,
548
- timestamp: Date.now(),
549
- });
550
- }
551
- return toolResults;
552
- }
553
- /**
554
- * Resolve async functions for the current turn.
555
- * Updates the resolved request with turn-specific parameter values.
556
- *
557
- * @param turnContext - The turn context for parameter resolution
558
- */
559
- async resolveAsyncFunctionsForTurn(turnContext) {
560
- if (hasAsyncFunctions(this.options.request)) {
561
- const resolved = await resolveAsyncFunctions(this.options.request, turnContext);
562
- // Preserve accumulated input from previous turns
563
- const preservedInput = this.resolvedRequest?.input;
564
- const preservedStream = this.resolvedRequest?.stream;
565
- this.resolvedRequest = {
566
- ...resolved,
567
- stream: preservedStream ?? true,
568
- ...(preservedInput !== undefined && { input: preservedInput }),
569
- };
570
- }
571
- }
572
- /**
573
- * Apply nextTurnParams from executed tools.
574
- * Allows tools to modify request parameters for subsequent turns.
575
- *
576
- * @param toolCalls - The tool calls that were just executed
577
- */
578
- async applyNextTurnParams(toolCalls) {
579
- if (!this.options.tools || toolCalls.length === 0 || !this.resolvedRequest) {
580
- return;
581
- }
582
- const computedParams = await executeNextTurnParamsFunctions(toolCalls, this.options.tools, this.resolvedRequest);
583
- if (Object.keys(computedParams).length > 0) {
584
- this.resolvedRequest = applyNextTurnParamsToRequest(this.resolvedRequest, computedParams);
585
- }
586
- }
587
- /**
588
- * Make a follow-up API request with tool results.
589
- * Uses streaming and pipes events through the turn broadcaster when available.
590
- */
591
- async makeFollowupRequest(currentResponse, toolResults, turnNumber) {
592
- const originalInput = this.resolvedRequest?.input;
593
- const normalizedOriginalInput = Array.isArray(originalInput)
594
- ? originalInput
595
- : originalInput
596
- ? [{ role: 'user', content: originalInput }]
597
- : [];
598
- const newInput = [
599
- ...normalizedOriginalInput,
600
- ...(Array.isArray(currentResponse.output)
601
- ? currentResponse.output
602
- : [currentResponse.output]),
603
- ...toolResults,
604
- ];
605
- if (!this.resolvedRequest) {
606
- throw new Error('Request not initialized');
607
- }
608
- // Update resolvedRequest.input with accumulated conversation for next turn
609
- this.resolvedRequest = {
610
- ...this.resolvedRequest,
611
- input: newInput,
612
- };
613
- const newRequest = {
614
- ...this.resolvedRequest,
615
- stream: true,
616
- };
617
- const newResult = await responsesSend(this.options.client, { responsesRequest: newRequest }, this.options.options);
618
- if (!newResult.ok) {
619
- throw newResult.error;
620
- }
621
- // Handle streaming or non-streaming response
622
- const value = newResult.value;
623
- if (isEventStream(value)) {
624
- const followUpStream = new ReusableReadableStream(value);
625
- if (this.turnBroadcaster) {
626
- return this.pipeAndConsumeStream(followUpStream, turnNumber);
627
- }
628
- return consumeStreamForCompletion(followUpStream);
629
- }
630
- else if (this.isNonStreamingResponse(value)) {
631
- return value;
632
- }
633
- else {
634
- throw new Error('Unexpected response type from API');
635
- }
636
- }
637
- /**
638
- * Validate the final response has required fields.
639
- *
640
- * @param response - The response to validate
641
- * @throws Error if response is missing required fields or has invalid output
642
- */
643
- validateFinalResponse(response) {
644
- if (!response?.id || !response?.output) {
645
- throw new Error('Invalid final response: missing required fields');
646
- }
647
- if (!Array.isArray(response.output) || response.output.length === 0) {
648
- throw new Error('Invalid final response: empty or invalid output');
649
- }
650
- }
651
- /**
652
- * Resolve async functions in the request for a given turn context.
653
- * Extracts non-function fields and resolves any async parameter functions.
654
- *
655
- * @param context - The turn context for parameter resolution
656
- * @returns The resolved request without async functions
657
- */
658
- async resolveRequestForContext(context) {
659
- if (hasAsyncFunctions(this.options.request)) {
660
- return resolveAsyncFunctions(this.options.request, context);
661
- }
662
- // Already resolved, extract non-function fields
663
- // Filter out stopWhen and state-related fields that aren't part of the API request
664
- const { stopWhen: _, state: _s, requireApproval: _r, approveToolCalls: _a, rejectToolCalls: _rj, context: _c, ...rest } = this.options.request;
665
- return rest;
666
- }
667
- /**
668
- * Safely persist state with error handling.
669
- * Wraps state save operations to ensure failures are properly reported.
670
- *
671
- * @param updates - Optional partial state updates to apply before saving
672
- * @throws Error if state persistence fails
673
- */
674
- async saveStateSafely(updates) {
675
- if (!this.stateAccessor || !this.currentState)
676
- return;
677
- if (updates) {
678
- this.currentState = updateState(this.currentState, updates);
679
- }
680
- try {
681
- await this.stateAccessor.save(this.currentState);
682
- }
683
- catch (error) {
684
- const message = error instanceof Error ? error.message : String(error);
685
- throw new Error(`Failed to persist conversation state: ${message}`);
686
- }
687
- }
688
- /**
689
- * Remove optional properties from state when they should be cleared.
690
- * Uses delete to properly remove optional properties rather than setting undefined.
691
- *
692
- * @param props - Array of property names to remove from current state
693
- */
694
- clearOptionalStateProperties(props) {
695
- if (!this.currentState)
696
- return;
697
- for (const prop of props) {
698
- delete this.currentState[prop];
699
- }
700
- }
701
- // =========================================================================
702
- // Core Methods
703
- // =========================================================================
704
- /**
705
- * Initialize the stream if not already started
706
- * This is idempotent - multiple calls will return the same promise
707
- */
708
- initStream() {
709
- if (this.initPromise) {
710
- return this.initPromise;
711
- }
712
- this.initPromise = (async () => {
713
- // Load or create state if accessor provided
714
- if (this.stateAccessor) {
715
- const loadedState = await this.stateAccessor.load();
716
- if (loadedState) {
717
- this.currentState = loadedState;
718
- // Check if we're resuming from awaiting_approval with decisions
719
- if (loadedState.status === 'awaiting_approval' &&
720
- (this.approvedToolCalls.length > 0 || this.rejectedToolCalls.length > 0)) {
721
- // Initialize context store before resuming so tools have access
722
- if (this.options.context !== undefined) {
723
- const approvalContext = { numberOfTurns: 0 };
724
- const resolvedCtx = await resolveContext(this.options.context, approvalContext);
725
- this.contextStore = new ToolContextStore(resolvedCtx);
726
- }
727
- this.isResumingFromApproval = true;
728
- await this.processApprovalDecisions();
729
- return; // Skip normal initialization, we're resuming
730
- }
731
- // Check for interruption flag and handle
732
- if (loadedState.interruptedBy) {
733
- // Clear interruption flag and continue from saved state
734
- this.currentState = updateState(loadedState, { status: 'in_progress' });
735
- this.clearOptionalStateProperties(['interruptedBy']);
736
- await this.saveStateSafely();
737
- }
738
- }
739
- else {
740
- this.currentState = createInitialState();
741
- }
742
- // Update status to in_progress
743
- await this.saveStateSafely({ status: 'in_progress' });
744
- }
745
- // Resolve async functions before initial request
746
- // Build initial turn context (turn 0 for initial request)
747
- const initialContext = { numberOfTurns: 0 };
748
- // Initialize context store from the context option
749
- if (this.options.context !== undefined) {
750
- const resolvedCtx = await resolveContext(this.options.context, initialContext);
751
- this.contextStore = new ToolContextStore(resolvedCtx);
752
- }
753
- // Resolve any async functions first
754
- let baseRequest = await this.resolveRequestForContext(initialContext);
755
- // If we have state with existing messages, use those as input
756
- if (this.currentState && this.currentState.messages &&
757
- Array.isArray(this.currentState.messages) && this.currentState.messages.length > 0) {
758
- // Append new input to existing messages
759
- const newInput = baseRequest.input;
760
- if (newInput) {
761
- const inputArray = Array.isArray(newInput) ? newInput : [newInput];
762
- baseRequest = {
763
- ...baseRequest,
764
- input: appendToMessages(this.currentState.messages, inputArray),
765
- };
766
- }
767
- else {
768
- baseRequest = {
769
- ...baseRequest,
770
- input: this.currentState.messages,
771
- };
772
- }
773
- }
774
- // Store resolved request with stream mode
775
- this.resolvedRequest = {
776
- ...baseRequest,
777
- stream: true,
778
- };
779
- // Force stream mode for initial request
780
- const request = this.resolvedRequest;
781
- // Make the API request
782
- const apiResult = await responsesSend(this.options.client, { responsesRequest: request }, this.options.options);
783
- if (!apiResult.ok) {
784
- throw apiResult.error;
785
- }
786
- // Handle both streaming and non-streaming responses
787
- // The API may return a non-streaming response even when stream: true is requested
788
- if (isEventStream(apiResult.value)) {
789
- this.reusableStream = new ReusableReadableStream(apiResult.value);
790
- }
791
- else if (this.isNonStreamingResponse(apiResult.value)) {
792
- // API returned a complete response directly - use it as the final response
793
- this.finalResponse = apiResult.value;
794
- }
795
- else {
796
- throw new Error('Unexpected response type from API');
797
- }
798
- })();
799
- return this.initPromise;
800
- }
801
- /**
802
- * Process approval/rejection decisions and resume execution
803
- */
804
- async processApprovalDecisions() {
805
- if (!this.currentState || !this.stateAccessor) {
806
- throw new Error('Cannot process approval decisions without state');
807
- }
808
- const pendingCalls = this.currentState.pendingToolCalls ?? [];
809
- const unsentResults = [...(this.currentState.unsentToolResults ?? [])];
810
- // Build turn context - numberOfTurns represents the current turn (1-indexed after initial)
811
- const turnContext = {
812
- numberOfTurns: this.allToolExecutionRounds.length + 1,
813
- // context is handled via contextStore, not on TurnContext
814
- };
815
- // Process approvals - execute the approved tools
816
- for (const callId of this.approvedToolCalls) {
817
- const toolCall = pendingCalls.find(tc => tc.id === callId);
818
- if (!toolCall)
819
- continue;
820
- const tool = this.options.tools?.find(t => t.function.name === toolCall.name);
821
- if (!tool || !hasExecuteFunction(tool)) {
822
- // Can't execute, create error result
823
- unsentResults.push(createRejectedResult(callId, String(toolCall.name), 'Tool not found or not executable'));
824
- continue;
825
- }
826
- const result = await executeTool(tool, toolCall, turnContext, undefined, this.contextStore ?? undefined, this.options.sharedContextSchema);
827
- if (result.error) {
828
- unsentResults.push(createRejectedResult(callId, String(toolCall.name), result.error.message));
829
- }
830
- else {
831
- unsentResults.push(createUnsentResult(callId, String(toolCall.name), result.result));
832
- }
833
- }
834
- // Process rejections
835
- for (const callId of this.rejectedToolCalls) {
836
- const toolCall = pendingCalls.find(tc => tc.id === callId);
837
- if (!toolCall)
838
- continue;
839
- unsentResults.push(createRejectedResult(callId, String(toolCall.name), 'Rejected by user'));
840
- }
841
- // Remove processed calls from pending
842
- const processedIds = new Set([...this.approvedToolCalls, ...this.rejectedToolCalls]);
843
- const remainingPending = pendingCalls.filter(tc => !processedIds.has(tc.id));
844
- // Update state - conditionally include optional properties only if they have values
845
- const stateUpdates = {
846
- status: remainingPending.length > 0 ? 'awaiting_approval' : 'in_progress',
847
- };
848
- if (remainingPending.length > 0) {
849
- stateUpdates.pendingToolCalls = remainingPending;
850
- }
851
- if (unsentResults.length > 0) {
852
- stateUpdates.unsentToolResults = unsentResults;
853
- }
854
- await this.saveStateSafely(stateUpdates);
855
- // Clear optional properties if they should be empty
856
- const propsToClear = [];
857
- if (remainingPending.length === 0)
858
- propsToClear.push('pendingToolCalls');
859
- if (unsentResults.length === 0)
860
- propsToClear.push('unsentToolResults');
861
- if (propsToClear.length > 0) {
862
- this.clearOptionalStateProperties(propsToClear);
863
- await this.saveStateSafely();
864
- }
865
- // If we still have pending approvals, stop here
866
- if (remainingPending.length > 0) {
867
- return;
868
- }
869
- // Otherwise, continue with tool execution using unsent results
870
- await this.continueWithUnsentResults();
871
- }
872
- /**
873
- * Continue execution with unsent tool results
874
- */
875
- async continueWithUnsentResults() {
876
- if (!this.currentState || !this.stateAccessor)
877
- return;
878
- const unsentResults = this.currentState.unsentToolResults ?? [];
879
- if (unsentResults.length === 0)
880
- return;
881
- // Convert to API format
882
- const toolOutputs = unsentResultsToAPIFormat(unsentResults);
883
- // Build new input with tool results
884
- const currentMessages = this.currentState.messages;
885
- const newInput = appendToMessages(currentMessages, toolOutputs);
886
- // Clear unsent results from state
887
- this.currentState = updateState(this.currentState, {
888
- messages: newInput,
889
- });
890
- this.clearOptionalStateProperties(['unsentToolResults']);
891
- await this.saveStateSafely();
892
- // Build request with the updated input
893
- // numberOfTurns represents the current turn number (1-indexed after initial)
894
- const turnContext = {
895
- numberOfTurns: this.allToolExecutionRounds.length + 1,
896
- };
897
- const baseRequest = await this.resolveRequestForContext(turnContext);
898
- // Create request with the accumulated messages
899
- const request = {
900
- ...baseRequest,
901
- input: newInput,
902
- stream: true,
903
- };
904
- this.resolvedRequest = request;
905
- // Make the API request
906
- const apiResult = await responsesSend(this.options.client, { responsesRequest: request }, this.options.options);
907
- if (!apiResult.ok) {
908
- throw apiResult.error;
909
- }
910
- // Handle both streaming and non-streaming responses
911
- if (isEventStream(apiResult.value)) {
912
- this.reusableStream = new ReusableReadableStream(apiResult.value);
913
- }
914
- else if (this.isNonStreamingResponse(apiResult.value)) {
915
- this.finalResponse = apiResult.value;
916
- }
917
- else {
918
- throw new Error('Unexpected response type from API');
919
- }
920
- }
921
- /**
922
- * Execute tools automatically if they are provided and have execute functions
923
- * This is idempotent - multiple calls will return the same promise
924
- */
925
- async executeToolsIfNeeded() {
926
- if (this.toolExecutionPromise) {
927
- return this.toolExecutionPromise;
928
- }
929
- this.toolExecutionPromise = (async () => {
930
- await this.initStream();
931
- // If resuming from approval and still pending, don't continue
932
- if (this.isResumingFromApproval && this.currentState?.status === 'awaiting_approval') {
933
- return;
934
- }
935
- // Get initial response
936
- let currentResponse = await this.getInitialResponse();
937
- // Save initial response to state
938
- await this.saveResponseToState(currentResponse);
939
- // Check if tools should be executed
940
- const hasToolCalls = currentResponse.output.some((item) => hasTypeProperty(item) && item.type === 'function_call');
941
- if (!this.options.tools?.length || !hasToolCalls) {
942
- this.finalResponse = currentResponse;
943
- await this.markStateComplete();
944
- return;
945
- }
946
- // Extract and check tool calls
947
- const toolCalls = extractToolCallsFromResponse(currentResponse);
948
- // Check for approval requirements
949
- if (await this.handleApprovalCheck(toolCalls, 0, currentResponse)) {
950
- return; // Paused for approval
951
- }
952
- if (!this.hasExecutableToolCalls(toolCalls)) {
953
- this.finalResponse = currentResponse;
954
- await this.markStateComplete();
955
- return;
956
- }
957
- // Main execution loop
958
- let currentRound = 0;
959
- while (true) {
960
- // Check for external interruption
961
- if (await this.checkForInterruption(currentResponse)) {
962
- return;
963
- }
964
- // Check stop conditions
965
- if (await this.shouldStopExecution()) {
966
- break;
967
- }
968
- const currentToolCalls = extractToolCallsFromResponse(currentResponse);
969
- if (currentToolCalls.length === 0) {
970
- break;
971
- }
972
- // Check for approval requirements
973
- if (await this.handleApprovalCheck(currentToolCalls, currentRound + 1, currentResponse)) {
974
- return;
975
- }
976
- if (!this.hasExecutableToolCalls(currentToolCalls)) {
977
- break;
978
- }
979
- // Build turn context
980
- const turnNumber = currentRound + 1;
981
- const turnContext = { numberOfTurns: turnNumber };
982
- await this.options.onTurnStart?.(turnContext);
983
- // Resolve async functions for this turn
984
- await this.resolveAsyncFunctionsForTurn(turnContext);
985
- // Execute tools
986
- const toolResults = await this.executeToolRound(currentToolCalls, turnContext);
987
- // Track execution round
988
- this.allToolExecutionRounds.push({
989
- round: currentRound,
990
- toolCalls: currentToolCalls,
991
- response: currentResponse,
992
- toolResults,
993
- });
994
- // Save tool results to state
995
- await this.saveToolResultsToState(toolResults);
996
- // Apply nextTurnParams
997
- await this.applyNextTurnParams(currentToolCalls);
998
- currentResponse = await this.makeFollowupRequest(currentResponse, toolResults, turnNumber);
999
- await this.options.onTurnEnd?.(turnContext, currentResponse);
1000
- // Save new response to state
1001
- await this.saveResponseToState(currentResponse);
1002
- currentRound++;
1003
- }
1004
- // Validate and finalize
1005
- this.validateFinalResponse(currentResponse);
1006
- this.finalResponse = currentResponse;
1007
- await this.markStateComplete();
1008
- })();
1009
- return this.toolExecutionPromise;
1010
- }
1011
- /**
1012
- * Internal helper to get the text after tool execution
1013
- */
1014
- async getTextInternal() {
1015
- await this.executeToolsIfNeeded();
1016
- if (!this.finalResponse) {
1017
- throw new Error('Response not available');
1018
- }
1019
- return extractTextFromResponse(this.finalResponse);
1020
- }
1021
- /**
1022
- * Get just the text content from the response.
1023
- * This will consume the stream until completion, execute any tools, and extract the text.
1024
- */
1025
- getText() {
1026
- if (this.textPromise) {
1027
- return this.textPromise;
1028
- }
1029
- this.textPromise = this.getTextInternal();
1030
- return this.textPromise;
1031
- }
1032
- /**
1033
- * Get the complete response object including usage information.
1034
- * This will consume the stream until completion and execute any tools.
1035
- * Returns the full OpenResponsesResult with usage data (inputTokens, outputTokens, cachedTokens, etc.)
1036
- */
1037
- async getResponse() {
1038
- await this.executeToolsIfNeeded();
1039
- if (!this.finalResponse) {
1040
- throw new Error('Response not available');
1041
- }
1042
- return this.finalResponse;
1043
- }
1044
- /**
1045
- * Stream all response events as they arrive across all turns.
1046
- * Multiple consumers can iterate over this stream concurrently.
1047
- * Includes API events, tool events, and turn.start/turn.end delimiters.
1048
- */
1049
- getFullResponsesStream() {
1050
- return async function* () {
1051
- await this.initStream();
1052
- if (!this.reusableStream && !this.finalResponse) {
1053
- throw new Error('Stream not initialized');
1054
- }
1055
- if (!this.options.tools?.length) {
1056
- if (this.reusableStream) {
1057
- const consumer = this.reusableStream.createConsumer();
1058
- for await (const event of consumer) {
1059
- yield event;
1060
- }
1061
- }
1062
- return;
1063
- }
1064
- const { consumer, executionPromise } = this.startTurnBroadcasterExecution();
1065
- for await (const event of consumer) {
1066
- yield event;
1067
- }
1068
- await executionPromise;
1069
- }.call(this);
1070
- }
1071
- /**
1072
- * Stream only text deltas as they arrive from all turns.
1073
- * This filters the full event stream to only yield text content,
1074
- * including text from follow-up responses in multi-turn tool loops.
1075
- */
1076
- getTextStream() {
1077
- return async function* () {
1078
- await this.initStream();
1079
- if (!this.reusableStream && !this.finalResponse) {
1080
- throw new Error('Stream not initialized');
1081
- }
1082
- if (!this.options.tools?.length) {
1083
- if (this.reusableStream) {
1084
- yield* extractTextDeltas(this.reusableStream);
1085
- }
1086
- return;
1087
- }
1088
- const { consumer, executionPromise } = this.startTurnBroadcasterExecution();
1089
- for await (const event of consumer) {
1090
- if (isOutputTextDeltaEvent(event)) {
1091
- yield event.delta;
1092
- }
1093
- }
1094
- await executionPromise;
1095
- }.call(this);
1096
- }
1097
- /**
1098
- * Stream all output items cumulatively as they arrive.
1099
- * Items are emitted with the same ID but progressively updated content as streaming progresses.
1100
- * Also yields tool results (function_call_output) after tool execution completes.
1101
- *
1102
- * Item types include:
1103
- * - message: Assistant text responses (emitted cumulatively as text streams)
1104
- * - function_call: Tool calls (emitted cumulatively as arguments stream)
1105
- * - reasoning: Model reasoning (emitted cumulatively as thinking streams)
1106
- * - web_search_call: Web search operations
1107
- * - file_search_call: File search operations
1108
- * - image_generation_call: Image generation operations
1109
- * - function_call_output: Results from executed tools
1110
- */
1111
- getItemsStream() {
1112
- return async function* () {
1113
- await this.initStream();
1114
- if (!this.reusableStream && !this.finalResponse) {
1115
- throw new Error('Stream not initialized');
1116
- }
1117
- // No tools — stream single turn directly (no broadcaster needed)
1118
- if (!this.options.tools?.length) {
1119
- if (this.reusableStream) {
1120
- yield* buildItemsStream(this.reusableStream);
1121
- }
1122
- return;
1123
- }
1124
- // Use turnBroadcaster (same pattern as getTextStream/getFullResponsesStream).
1125
- // executeToolsIfNeeded() drives tool execution in the background while we
1126
- // passively consume events from the broadcaster in real-time.
1127
- const { consumer, executionPromise } = this.startTurnBroadcasterExecution();
1128
- const itemsInProgress = new Map();
1129
- for await (const event of consumer) {
1130
- // Tool call outputs → yield directly as function_call_output items
1131
- if (isToolCallOutputEvent(event)) {
1132
- yield event.output;
1133
- continue;
1134
- }
1135
- // Stream termination → reset items map for next turn
1136
- if ('type' in event && streamTerminationEvents.has(event.type)) {
1137
- itemsInProgress.clear();
1138
- }
1139
- // API stream events → dispatch through item handlers
1140
- // Cast is necessary: TypeScript cannot narrow a union via Record key lookup,
1141
- // but `event.type in itemsStreamHandlers` guarantees the event is an
1142
- // StreamEvents whose type matches a handler key.
1143
- if ('type' in event && event.type in itemsStreamHandlers) {
1144
- const handler = itemsStreamHandlers[event.type];
1145
- if (handler) {
1146
- const result = handler(event, itemsInProgress);
1147
- if (result) {
1148
- yield result;
1149
- }
1150
- }
1151
- }
1152
- }
1153
- await executionPromise;
1154
- }.call(this);
1155
- }
1156
- /**
1157
- * @deprecated Use `getItemsStream()` instead. This method only streams messages,
1158
- * while `getItemsStream()` streams all output item types (messages, function_calls,
1159
- * reasoning, etc.) with cumulative updates.
1160
- *
1161
- * Stream cumulative message snapshots as content is added in responses format.
1162
- * Each iteration yields an updated version of the message with new content.
1163
- * Also yields function_call items and FunctionCallOutputItem after tool execution completes.
1164
- * Returns OutputMessage, OutputFunctionCallItem, or FunctionCallOutputItem
1165
- * compatible with OpenAI Responses API format.
1166
- */
1167
- getNewMessagesStream() {
1168
- return async function* () {
1169
- await this.initStream();
1170
- if (!this.reusableStream && !this.finalResponse) {
1171
- throw new Error('Stream not initialized');
1172
- }
1173
- // First yield messages from the stream in responses format
1174
- if (this.reusableStream) {
1175
- yield* buildResponsesMessageStream(this.reusableStream);
1176
- }
1177
- // Execute tools if needed
1178
- await this.executeToolsIfNeeded();
1179
- // Yield function calls and their outputs for each executed tool
1180
- for (const round of this.allToolExecutionRounds) {
1181
- // First yield the function_call items from the response that triggered tool execution
1182
- for (const item of round.response.output) {
1183
- if (isFunctionCallItem(item)) {
1184
- yield item;
1185
- }
1186
- }
1187
- // Then yield the function_call_output results
1188
- for (const toolResult of round.toolResults) {
1189
- yield toolResult;
1190
- }
1191
- }
1192
- // If tools were executed, yield the final message (if there is one)
1193
- if (this.finalResponse && this.allToolExecutionRounds.length > 0) {
1194
- // Check if the final response contains a message
1195
- const hasMessage = this.finalResponse.output.some((item) => hasTypeProperty(item) && item.type === 'message');
1196
- if (hasMessage) {
1197
- yield extractResponsesMessageFromResponse(this.finalResponse);
1198
- }
1199
- }
1200
- }.call(this);
1201
- }
1202
- /**
1203
- * Stream only reasoning deltas as they arrive from all turns.
1204
- * This filters the full event stream to only yield reasoning content,
1205
- * including reasoning from follow-up responses in multi-turn tool loops.
1206
- */
1207
- getReasoningStream() {
1208
- return async function* () {
1209
- await this.initStream();
1210
- if (!this.reusableStream && !this.finalResponse) {
1211
- throw new Error('Stream not initialized');
1212
- }
1213
- if (!this.options.tools?.length) {
1214
- if (this.reusableStream) {
1215
- yield* extractReasoningDeltas(this.reusableStream);
1216
- }
1217
- return;
1218
- }
1219
- const { consumer, executionPromise } = this.startTurnBroadcasterExecution();
1220
- for await (const event of consumer) {
1221
- if (isReasoningDeltaEvent(event)) {
1222
- yield event.delta;
1223
- }
1224
- }
1225
- await executionPromise;
1226
- }.call(this);
1227
- }
1228
- /**
1229
- * Stream tool call argument deltas and preliminary results from all turns.
1230
- * Preliminary results are streamed in REAL-TIME as generator tools yield.
1231
- * - Tool call argument deltas as { type: "delta", content: string }
1232
- * - Preliminary results as { type: "preliminary_result", toolCallId, result }
1233
- */
1234
- getToolStream() {
1235
- return async function* () {
1236
- await this.initStream();
1237
- if (!this.reusableStream && !this.finalResponse) {
1238
- throw new Error('Stream not initialized');
1239
- }
1240
- if (!this.options.tools?.length) {
1241
- if (this.reusableStream) {
1242
- for await (const delta of extractToolDeltas(this.reusableStream)) {
1243
- yield { type: 'delta', content: delta };
1244
- }
1245
- }
1246
- return;
1247
- }
1248
- const { consumer, executionPromise } = this.startTurnBroadcasterExecution();
1249
- for await (const event of consumer) {
1250
- if (event.type === 'response.function_call_arguments.delta') {
1251
- yield { type: 'delta', content: event.delta };
1252
- continue;
1253
- }
1254
- if (event.type === 'tool.preliminary_result') {
1255
- yield {
1256
- type: 'preliminary_result',
1257
- toolCallId: event.toolCallId,
1258
- result: event.result,
1259
- };
1260
- }
1261
- }
1262
- await executionPromise;
1263
- }.call(this);
1264
- }
1265
- /**
1266
- * Get all tool calls from the completed response (before auto-execution).
1267
- * Note: If tools have execute functions, they will be automatically executed
1268
- * and this will return the tool calls from the initial response.
1269
- * Returns structured tool calls with parsed arguments.
1270
- */
1271
- async getToolCalls() {
1272
- await this.initStream();
1273
- // Handle non-streaming response case - use finalResponse directly
1274
- if (this.finalResponse) {
1275
- return extractToolCallsFromResponse(this.finalResponse);
1276
- }
1277
- if (!this.reusableStream) {
1278
- throw new Error('Stream not initialized');
1279
- }
1280
- const completedResponse = await consumeStreamForCompletion(this.reusableStream);
1281
- return extractToolCallsFromResponse(completedResponse);
1282
- }
1283
- /**
1284
- * Stream structured tool call objects as they're completed.
1285
- * Each iteration yields a complete tool call with parsed arguments.
1286
- */
1287
- getToolCallsStream() {
1288
- return async function* () {
1289
- await this.initStream();
1290
- if (!this.reusableStream && !this.finalResponse) {
1291
- throw new Error('Stream not initialized');
1292
- }
1293
- if (this.reusableStream) {
1294
- yield* buildToolCallStream(this.reusableStream);
1295
- }
1296
- }.call(this);
1297
- }
1298
- /**
1299
- * Returns an async iterable that emits a full context snapshot every time
1300
- * any tool calls ctx.update(). Can be consumed concurrently with getText(),
1301
- * getToolStream(), etc.
1302
- *
1303
- * @example
1304
- * ```typescript
1305
- * for await (const snapshot of result.getContextUpdates()) {
1306
- * console.log('Context changed:', snapshot);
1307
- * }
1308
- * ```
1309
- */
1310
- async *getContextUpdates() {
1311
- // Ensure stream is initialized (which creates the context store)
1312
- await this.initStream();
1313
- if (!this.contextStore) {
1314
- return;
1315
- }
1316
- const store = this.contextStore;
1317
- const queue = [];
1318
- let resolve = null;
1319
- let done = false;
1320
- const unsubscribe = store.subscribe((snapshot) => {
1321
- queue.push(snapshot);
1322
- if (resolve) {
1323
- resolve();
1324
- resolve = null;
1325
- }
1326
- });
1327
- // Signal completion when tool execution finishes
1328
- this.executeToolsIfNeeded().then(() => {
1329
- done = true;
1330
- if (resolve) {
1331
- resolve();
1332
- resolve = null;
1333
- }
1334
- }, () => {
1335
- done = true;
1336
- if (resolve) {
1337
- resolve();
1338
- resolve = null;
1339
- }
1340
- });
1341
- try {
1342
- while (!done) {
1343
- if (queue.length > 0) {
1344
- yield queue.shift();
1345
- }
1346
- else {
1347
- // Wait for next update or completion
1348
- await new Promise((r) => { resolve = r; });
1349
- }
1350
- }
1351
- // Drain any remaining queued snapshots
1352
- while (queue.length > 0) {
1353
- yield queue.shift();
1354
- }
1355
- }
1356
- finally {
1357
- unsubscribe();
1358
- }
1359
- }
1360
- /**
1361
- * Cancel the underlying stream and all consumers
1362
- */
1363
- async cancel() {
1364
- if (this.reusableStream) {
1365
- await this.reusableStream.cancel();
1366
- }
1367
- }
1368
- // =========================================================================
1369
- // Multi-Turn Conversation State Methods
1370
- // =========================================================================
1371
- /**
1372
- * Check if the conversation requires human approval to continue.
1373
- * Returns true if there are pending tool calls awaiting approval.
1374
- */
1375
- async requiresApproval() {
1376
- await this.initStream();
1377
- // If we have pending tool calls in state, approval is required
1378
- if (this.currentState?.status === 'awaiting_approval') {
1379
- return true;
1380
- }
1381
- // Also check if pendingToolCalls is populated
1382
- return (this.currentState?.pendingToolCalls?.length ?? 0) > 0;
1383
- }
1384
- /**
1385
- * Get the pending tool calls that require approval.
1386
- * Returns empty array if no approvals needed.
1387
- */
1388
- async getPendingToolCalls() {
1389
- await this.initStream();
1390
- // Try to trigger tool execution to populate pending calls
1391
- if (!this.isResumingFromApproval) {
1392
- await this.executeToolsIfNeeded();
1393
- }
1394
- return (this.currentState?.pendingToolCalls ?? []);
1395
- }
1396
- /**
1397
- * Get the current conversation state.
1398
- * Useful for inspection, debugging, or custom persistence.
1399
- * Note: This returns the raw ConversationState for inspection only.
1400
- * To resume a conversation, use the StateAccessor pattern.
1401
- */
1402
- async getState() {
1403
- await this.initStream();
1404
- // Ensure tool execution has been attempted (to populate final state)
1405
- if (!this.isResumingFromApproval) {
1406
- await this.executeToolsIfNeeded();
1407
- }
1408
- if (!this.currentState) {
1409
- throw new Error('State not initialized. Make sure a StateAccessor was provided to callModel.');
1410
- }
1411
- return this.currentState;
1412
- }
1413
- }
1414
- //# sourceMappingURL=model-result.js.map