@openai/agents-core 0.3.6 → 0.3.8
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.
- package/dist/errors.d.ts +40 -0
- package/dist/errors.js +38 -1
- package/dist/errors.js.map +1 -1
- package/dist/errors.mjs +34 -0
- package/dist/errors.mjs.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +13 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -1
- package/dist/index.mjs.map +1 -1
- package/dist/metadata.js +2 -2
- package/dist/metadata.mjs +2 -2
- package/dist/result.d.ts +17 -0
- package/dist/result.js +71 -24
- package/dist/result.js.map +1 -1
- package/dist/result.mjs +69 -22
- package/dist/result.mjs.map +1 -1
- package/dist/run.d.ts +14 -47
- package/dist/run.js +421 -994
- package/dist/run.js.map +1 -1
- package/dist/run.mjs +405 -978
- package/dist/run.mjs.map +1 -1
- package/dist/runState.d.ts +1286 -172
- package/dist/runState.js +146 -16
- package/dist/runState.js.map +1 -1
- package/dist/runState.mjs +142 -12
- package/dist/runState.mjs.map +1 -1
- package/dist/runner/constants.d.ts +1 -0
- package/dist/runner/constants.js +6 -0
- package/dist/runner/constants.js.map +1 -0
- package/dist/runner/constants.mjs +3 -0
- package/dist/runner/constants.mjs.map +1 -0
- package/dist/runner/conversation.d.ts +85 -0
- package/dist/runner/conversation.js +275 -0
- package/dist/runner/conversation.js.map +1 -0
- package/dist/runner/conversation.mjs +269 -0
- package/dist/runner/conversation.mjs.map +1 -0
- package/dist/runner/guardrails.d.ts +23 -0
- package/dist/runner/guardrails.js +174 -0
- package/dist/runner/guardrails.js.map +1 -0
- package/dist/runner/guardrails.mjs +166 -0
- package/dist/runner/guardrails.mjs.map +1 -0
- package/dist/runner/items.d.ts +18 -0
- package/dist/runner/items.js +89 -0
- package/dist/runner/items.js.map +1 -0
- package/dist/runner/items.mjs +79 -0
- package/dist/runner/items.mjs.map +1 -0
- package/dist/runner/mcpApprovals.d.ts +25 -0
- package/dist/runner/mcpApprovals.js +66 -0
- package/dist/runner/mcpApprovals.js.map +1 -0
- package/dist/runner/mcpApprovals.mjs +63 -0
- package/dist/runner/mcpApprovals.mjs.map +1 -0
- package/dist/runner/modelOutputs.d.ts +10 -0
- package/dist/runner/modelOutputs.js +206 -0
- package/dist/runner/modelOutputs.js.map +1 -0
- package/dist/runner/modelOutputs.mjs +203 -0
- package/dist/runner/modelOutputs.mjs.map +1 -0
- package/dist/runner/modelPreparation.d.ts +8 -0
- package/dist/runner/modelPreparation.js +41 -0
- package/dist/runner/modelPreparation.js.map +1 -0
- package/dist/runner/modelPreparation.mjs +38 -0
- package/dist/runner/modelPreparation.mjs.map +1 -0
- package/dist/runner/modelSettings.d.ts +20 -0
- package/dist/runner/modelSettings.js +97 -0
- package/dist/runner/modelSettings.js.map +1 -0
- package/dist/runner/modelSettings.mjs +92 -0
- package/dist/runner/modelSettings.mjs.map +1 -0
- package/dist/runner/runLoop.d.ts +32 -0
- package/dist/runner/runLoop.js +62 -0
- package/dist/runner/runLoop.js.map +1 -0
- package/dist/runner/runLoop.mjs +57 -0
- package/dist/runner/runLoop.mjs.map +1 -0
- package/dist/runner/sessionPersistence.d.ts +26 -0
- package/dist/runner/sessionPersistence.js +441 -0
- package/dist/runner/sessionPersistence.js.map +1 -0
- package/dist/runner/sessionPersistence.mjs +431 -0
- package/dist/runner/sessionPersistence.mjs.map +1 -0
- package/dist/runner/steps.d.ts +48 -0
- package/dist/runner/steps.js +40 -0
- package/dist/runner/steps.js.map +1 -0
- package/dist/runner/steps.mjs +36 -0
- package/dist/runner/steps.mjs.map +1 -0
- package/dist/runner/streaming.d.ts +9 -0
- package/dist/runner/streaming.js +74 -0
- package/dist/runner/streaming.js.map +1 -0
- package/dist/runner/streaming.mjs +65 -0
- package/dist/runner/streaming.mjs.map +1 -0
- package/dist/runner/toolExecution.d.ts +15 -0
- package/dist/runner/toolExecution.js +997 -0
- package/dist/runner/toolExecution.js.map +1 -0
- package/dist/runner/toolExecution.mjs +984 -0
- package/dist/runner/toolExecution.mjs.map +1 -0
- package/dist/runner/toolUseTracker.d.ts +9 -0
- package/dist/runner/toolUseTracker.js +34 -0
- package/dist/runner/toolUseTracker.js.map +1 -0
- package/dist/runner/toolUseTracker.mjs +30 -0
- package/dist/runner/toolUseTracker.mjs.map +1 -0
- package/dist/runner/tracing.d.ts +23 -0
- package/dist/runner/tracing.js +45 -0
- package/dist/runner/tracing.js.map +1 -0
- package/dist/runner/tracing.mjs +41 -0
- package/dist/runner/tracing.mjs.map +1 -0
- package/dist/runner/turnPreparation.d.ts +30 -0
- package/dist/runner/turnPreparation.js +80 -0
- package/dist/runner/turnPreparation.js.map +1 -0
- package/dist/runner/turnPreparation.mjs +74 -0
- package/dist/runner/turnPreparation.mjs.map +1 -0
- package/dist/runner/turnResolution.d.ts +3 -0
- package/dist/runner/turnResolution.js +531 -0
- package/dist/runner/turnResolution.js.map +1 -0
- package/dist/runner/turnResolution.mjs +526 -0
- package/dist/runner/turnResolution.mjs.map +1 -0
- package/dist/runner/types.d.ts +66 -0
- package/dist/runner/types.js +3 -0
- package/dist/runner/types.js.map +1 -0
- package/dist/runner/types.mjs +2 -0
- package/dist/runner/types.mjs.map +1 -0
- package/dist/shims/mcp-server/node.js +76 -30
- package/dist/shims/mcp-server/node.js.map +1 -1
- package/dist/shims/mcp-server/node.mjs +76 -30
- package/dist/shims/mcp-server/node.mjs.map +1 -1
- package/dist/tool.d.ts +28 -2
- package/dist/tool.js +7 -1
- package/dist/tool.js.map +1 -1
- package/dist/tool.mjs +8 -2
- package/dist/tool.mjs.map +1 -1
- package/dist/toolGuardrail.d.ts +101 -0
- package/dist/toolGuardrail.js +58 -0
- package/dist/toolGuardrail.js.map +1 -0
- package/dist/toolGuardrail.mjs +51 -0
- package/dist/toolGuardrail.mjs.map +1 -0
- package/dist/tracing/config.d.ts +3 -0
- package/dist/tracing/config.js +3 -0
- package/dist/tracing/config.js.map +1 -0
- package/dist/tracing/config.mjs +2 -0
- package/dist/tracing/config.mjs.map +1 -0
- package/dist/tracing/context.d.ts +2 -0
- package/dist/tracing/context.js +95 -24
- package/dist/tracing/context.js.map +1 -1
- package/dist/tracing/context.mjs +95 -24
- package/dist/tracing/context.mjs.map +1 -1
- package/dist/tracing/createSpans.d.ts +11 -11
- package/dist/tracing/index.d.ts +2 -0
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/tracing/provider.js +54 -4
- package/dist/tracing/provider.js.map +1 -1
- package/dist/tracing/provider.mjs +54 -4
- package/dist/tracing/provider.mjs.map +1 -1
- package/dist/tracing/spans.d.ts +2 -0
- package/dist/tracing/spans.js +6 -0
- package/dist/tracing/spans.js.map +1 -1
- package/dist/tracing/spans.mjs +6 -0
- package/dist/tracing/spans.mjs.map +1 -1
- package/dist/tracing/traces.d.ts +11 -1
- package/dist/tracing/traces.js +15 -2
- package/dist/tracing/traces.js.map +1 -1
- package/dist/tracing/traces.mjs +15 -2
- package/dist/tracing/traces.mjs.map +1 -1
- package/dist/types/protocol.d.ts +11 -0
- package/dist/types/protocol.js +1 -0
- package/dist/types/protocol.js.map +1 -1
- package/dist/types/protocol.mjs +1 -0
- package/dist/types/protocol.mjs.map +1 -1
- package/dist/utils/binary.d.ts +6 -0
- package/dist/utils/binary.js +53 -0
- package/dist/utils/binary.js.map +1 -0
- package/dist/utils/binary.mjs +49 -0
- package/dist/utils/binary.mjs.map +1 -0
- package/dist/utils/toolGuardrails.d.ts +24 -0
- package/dist/utils/toolGuardrails.js +58 -0
- package/dist/utils/toolGuardrails.js.map +1 -0
- package/dist/utils/toolGuardrails.mjs +54 -0
- package/dist/utils/toolGuardrails.mjs.map +1 -0
- package/package.json +4 -3
- package/dist/runImplementation.d.ts +0 -161
- package/dist/runImplementation.js +0 -2054
- package/dist/runImplementation.js.map +0 -1
- package/dist/runImplementation.mjs +0 -2028
- package/dist/runImplementation.mjs.map +0 -1
|
@@ -1,2054 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.AgentToolUseTracker = exports.nextStepSchema = void 0;
|
|
7
|
-
exports.processModelResponse = processModelResponse;
|
|
8
|
-
exports.maybeResetToolChoice = maybeResetToolChoice;
|
|
9
|
-
exports.resolveInterruptedTurn = resolveInterruptedTurn;
|
|
10
|
-
exports.resolveTurnAfterModelResponse = resolveTurnAfterModelResponse;
|
|
11
|
-
exports.getToolCallOutputItem = getToolCallOutputItem;
|
|
12
|
-
exports.executeFunctionToolCalls = executeFunctionToolCalls;
|
|
13
|
-
exports.executeShellActions = executeShellActions;
|
|
14
|
-
exports.executeApplyPatchOperations = executeApplyPatchOperations;
|
|
15
|
-
exports.executeComputerActions = executeComputerActions;
|
|
16
|
-
exports.executeHandoffCalls = executeHandoffCalls;
|
|
17
|
-
exports.checkForFinalOutputFromTools = checkForFinalOutputFromTools;
|
|
18
|
-
exports.streamStepItemsToRunResult = streamStepItemsToRunResult;
|
|
19
|
-
exports.addStepToRunResult = addStepToRunResult;
|
|
20
|
-
exports.toInputItemList = toInputItemList;
|
|
21
|
-
exports.extractOutputItemsFromRunItems = extractOutputItemsFromRunItems;
|
|
22
|
-
exports.saveToSession = saveToSession;
|
|
23
|
-
exports.saveStreamInputToSession = saveStreamInputToSession;
|
|
24
|
-
exports.saveStreamResultToSession = saveStreamResultToSession;
|
|
25
|
-
exports.prepareInputItemsWithSession = prepareInputItemsWithSession;
|
|
26
|
-
const agent_1 = require("./agent.js");
|
|
27
|
-
const errors_1 = require("./errors.js");
|
|
28
|
-
const handoff_1 = require("./handoff.js");
|
|
29
|
-
const items_1 = require("./items.js");
|
|
30
|
-
const logger_1 = __importDefault(require("./logger.js"));
|
|
31
|
-
const tool_1 = require("./tool.js");
|
|
32
|
-
const messages_1 = require("./utils/messages.js");
|
|
33
|
-
const createSpans_1 = require("./tracing/createSpans.js");
|
|
34
|
-
const tools_1 = require("./utils/tools.js");
|
|
35
|
-
const base64_1 = require("./utils/base64.js");
|
|
36
|
-
const smartString_1 = require("./utils/smartString.js");
|
|
37
|
-
const safeExecute_1 = require("./utils/safeExecute.js");
|
|
38
|
-
const context_1 = require("./tracing/context.js");
|
|
39
|
-
const events_1 = require("./events.js");
|
|
40
|
-
const zod_1 = require("zod");
|
|
41
|
-
const utils_1 = require("./utils/index.js");
|
|
42
|
-
const session_1 = require("./memory/session.js");
|
|
43
|
-
const usage_1 = require("./usage.js");
|
|
44
|
-
function isApprovalItemLike(value) {
|
|
45
|
-
if (!value || typeof value !== 'object') {
|
|
46
|
-
return false;
|
|
47
|
-
}
|
|
48
|
-
if (!('rawItem' in value)) {
|
|
49
|
-
return false;
|
|
50
|
-
}
|
|
51
|
-
const rawItem = value.rawItem;
|
|
52
|
-
if (!rawItem || typeof rawItem !== 'object') {
|
|
53
|
-
return false;
|
|
54
|
-
}
|
|
55
|
-
const itemType = rawItem.type;
|
|
56
|
-
return itemType === 'function_call' || itemType === 'hosted_tool_call';
|
|
57
|
-
}
|
|
58
|
-
function getApprovalIdentity(approval) {
|
|
59
|
-
const rawItem = approval.rawItem;
|
|
60
|
-
if (!rawItem) {
|
|
61
|
-
return undefined;
|
|
62
|
-
}
|
|
63
|
-
if (rawItem.type === 'function_call' && rawItem.callId) {
|
|
64
|
-
return `function_call:${rawItem.callId}`;
|
|
65
|
-
}
|
|
66
|
-
if ('callId' in rawItem && rawItem.callId) {
|
|
67
|
-
return `${rawItem.type}:${rawItem.callId}`;
|
|
68
|
-
}
|
|
69
|
-
const id = 'id' in rawItem ? rawItem.id : undefined;
|
|
70
|
-
if (id) {
|
|
71
|
-
return `${rawItem.type}:${id}`;
|
|
72
|
-
}
|
|
73
|
-
const providerData = typeof rawItem.providerData === 'object' && rawItem.providerData
|
|
74
|
-
? rawItem.providerData
|
|
75
|
-
: undefined;
|
|
76
|
-
if (providerData?.id) {
|
|
77
|
-
return `${rawItem.type}:provider:${providerData.id}`;
|
|
78
|
-
}
|
|
79
|
-
const agentName = 'agent' in approval && approval.agent ? approval.agent.name : '';
|
|
80
|
-
try {
|
|
81
|
-
return `${agentName}:${rawItem.type}:${JSON.stringify(rawItem)}`;
|
|
82
|
-
}
|
|
83
|
-
catch {
|
|
84
|
-
return `${agentName}:${rawItem.type}`;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
function formatFinalOutputTypeError(error) {
|
|
88
|
-
// Surface structured output validation hints without echoing potentially large or sensitive payloads.
|
|
89
|
-
try {
|
|
90
|
-
if (error instanceof zod_1.z.ZodError) {
|
|
91
|
-
const issue = error.issues[0];
|
|
92
|
-
if (issue) {
|
|
93
|
-
const issuePathParts = Array.isArray(issue.path) ? issue.path : [];
|
|
94
|
-
const issuePath = issuePathParts.length > 0
|
|
95
|
-
? issuePathParts.map((part) => String(part)).join('.')
|
|
96
|
-
: '(root)';
|
|
97
|
-
const message = truncateForDeveloper(issue.message ?? '');
|
|
98
|
-
return `Invalid output type: final assistant output failed schema validation at "${issuePath}" (${message}).`;
|
|
99
|
-
}
|
|
100
|
-
return 'Invalid output type: final assistant output failed schema validation.';
|
|
101
|
-
}
|
|
102
|
-
if (error instanceof Error && error.message) {
|
|
103
|
-
return `Invalid output type: ${truncateForDeveloper(error.message)}`;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
catch {
|
|
107
|
-
// Swallow formatting errors so we can return a generic message below.
|
|
108
|
-
}
|
|
109
|
-
return 'Invalid output type: final assistant output did not match the expected schema.';
|
|
110
|
-
}
|
|
111
|
-
function truncateForDeveloper(message, maxLength = 160) {
|
|
112
|
-
const trimmed = message.trim();
|
|
113
|
-
if (!trimmed) {
|
|
114
|
-
return 'Schema validation failed.';
|
|
115
|
-
}
|
|
116
|
-
if (trimmed.length <= maxLength) {
|
|
117
|
-
return trimmed;
|
|
118
|
-
}
|
|
119
|
-
return `${trimmed.slice(0, maxLength - 3)}...`;
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* @internal
|
|
123
|
-
* Walks a raw model response and classifies each item so the runner can schedule follow-up work.
|
|
124
|
-
* Returns both the serializable RunItems (for history/streaming) and the actionable tool metadata.
|
|
125
|
-
*/
|
|
126
|
-
function processModelResponse(modelResponse, agent, tools, handoffs) {
|
|
127
|
-
const items = [];
|
|
128
|
-
const runHandoffs = [];
|
|
129
|
-
const runFunctions = [];
|
|
130
|
-
const runComputerActions = [];
|
|
131
|
-
const runShellActions = [];
|
|
132
|
-
const runApplyPatchActions = [];
|
|
133
|
-
const runMCPApprovalRequests = [];
|
|
134
|
-
const toolsUsed = [];
|
|
135
|
-
const handoffMap = new Map(handoffs.map((h) => [h.toolName, h]));
|
|
136
|
-
// Resolve tools upfront so we can look up the concrete handler in O(1) while iterating outputs.
|
|
137
|
-
const functionMap = new Map(tools.filter((t) => t.type === 'function').map((t) => [t.name, t]));
|
|
138
|
-
const computerTool = tools.find((t) => t.type === 'computer');
|
|
139
|
-
const shellTool = tools.find((t) => t.type === 'shell');
|
|
140
|
-
const applyPatchTool = tools.find((t) => t.type === 'apply_patch');
|
|
141
|
-
const mcpToolMap = new Map(tools
|
|
142
|
-
.filter((t) => t.type === 'hosted_tool' && t.providerData?.type === 'mcp')
|
|
143
|
-
.map((t) => t)
|
|
144
|
-
.map((t) => [t.providerData.server_label, t]));
|
|
145
|
-
for (const output of modelResponse.output) {
|
|
146
|
-
if (output.type === 'message') {
|
|
147
|
-
if (output.role === 'assistant') {
|
|
148
|
-
items.push(new items_1.RunMessageOutputItem(output, agent));
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
else if (output.type === 'hosted_tool_call') {
|
|
152
|
-
items.push(new items_1.RunToolCallItem(output, agent));
|
|
153
|
-
const toolName = output.name;
|
|
154
|
-
toolsUsed.push(toolName);
|
|
155
|
-
if (output.providerData?.type === 'mcp_approval_request' ||
|
|
156
|
-
output.name === 'mcp_approval_request') {
|
|
157
|
-
// Hosted remote MCP server's approval process
|
|
158
|
-
const providerData = output.providerData;
|
|
159
|
-
const mcpServerLabel = providerData.server_label;
|
|
160
|
-
const mcpServerTool = mcpToolMap.get(mcpServerLabel);
|
|
161
|
-
if (typeof mcpServerTool === 'undefined') {
|
|
162
|
-
const message = `MCP server (${mcpServerLabel}) not found in Agent (${agent.name})`;
|
|
163
|
-
(0, context_1.addErrorToCurrentSpan)({
|
|
164
|
-
message,
|
|
165
|
-
data: { mcp_server_label: mcpServerLabel },
|
|
166
|
-
});
|
|
167
|
-
throw new errors_1.ModelBehaviorError(message);
|
|
168
|
-
}
|
|
169
|
-
// Do this approval later:
|
|
170
|
-
// We support both onApproval callback (like the Python SDK does) and HITL patterns.
|
|
171
|
-
const approvalItem = new items_1.RunToolApprovalItem({
|
|
172
|
-
type: 'hosted_tool_call',
|
|
173
|
-
// We must use this name to align with the name sent from the servers
|
|
174
|
-
name: providerData.name,
|
|
175
|
-
id: providerData.id,
|
|
176
|
-
status: 'in_progress',
|
|
177
|
-
providerData,
|
|
178
|
-
}, agent);
|
|
179
|
-
runMCPApprovalRequests.push({
|
|
180
|
-
requestItem: approvalItem,
|
|
181
|
-
mcpTool: mcpServerTool,
|
|
182
|
-
});
|
|
183
|
-
if (!mcpServerTool.providerData.on_approval) {
|
|
184
|
-
// When onApproval function exists, it confirms the approval right after this.
|
|
185
|
-
// Thus, this approval item must be appended only for the next turn interruption patterns.
|
|
186
|
-
items.push(approvalItem);
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
else if (output.type === 'reasoning') {
|
|
191
|
-
items.push(new items_1.RunReasoningItem(output, agent));
|
|
192
|
-
}
|
|
193
|
-
else if (output.type === 'computer_call') {
|
|
194
|
-
items.push(new items_1.RunToolCallItem(output, agent));
|
|
195
|
-
toolsUsed.push('computer_use');
|
|
196
|
-
if (!computerTool) {
|
|
197
|
-
(0, context_1.addErrorToCurrentSpan)({
|
|
198
|
-
message: 'Model produced computer action without a computer tool.',
|
|
199
|
-
data: {
|
|
200
|
-
agent_name: agent.name,
|
|
201
|
-
},
|
|
202
|
-
});
|
|
203
|
-
throw new errors_1.ModelBehaviorError('Model produced computer action without a computer tool.');
|
|
204
|
-
}
|
|
205
|
-
runComputerActions.push({
|
|
206
|
-
toolCall: output,
|
|
207
|
-
computer: computerTool,
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
else if (output.type === 'shell_call') {
|
|
211
|
-
items.push(new items_1.RunToolCallItem(output, agent));
|
|
212
|
-
toolsUsed.push('shell');
|
|
213
|
-
if (!shellTool) {
|
|
214
|
-
(0, context_1.addErrorToCurrentSpan)({
|
|
215
|
-
message: 'Model produced shell action without a shell tool.',
|
|
216
|
-
data: {
|
|
217
|
-
agent_name: agent.name,
|
|
218
|
-
},
|
|
219
|
-
});
|
|
220
|
-
throw new errors_1.ModelBehaviorError('Model produced shell action without a shell tool.');
|
|
221
|
-
}
|
|
222
|
-
runShellActions.push({
|
|
223
|
-
toolCall: output,
|
|
224
|
-
shell: shellTool,
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
|
-
else if (output.type === 'apply_patch_call') {
|
|
228
|
-
items.push(new items_1.RunToolCallItem(output, agent));
|
|
229
|
-
toolsUsed.push('apply_patch');
|
|
230
|
-
if (!applyPatchTool) {
|
|
231
|
-
(0, context_1.addErrorToCurrentSpan)({
|
|
232
|
-
message: 'Model produced apply_patch action without an apply_patch tool.',
|
|
233
|
-
data: {
|
|
234
|
-
agent_name: agent.name,
|
|
235
|
-
},
|
|
236
|
-
});
|
|
237
|
-
throw new errors_1.ModelBehaviorError('Model produced apply_patch action without an apply_patch tool.');
|
|
238
|
-
}
|
|
239
|
-
runApplyPatchActions.push({
|
|
240
|
-
toolCall: output,
|
|
241
|
-
applyPatch: applyPatchTool,
|
|
242
|
-
});
|
|
243
|
-
}
|
|
244
|
-
if (output.type !== 'function_call') {
|
|
245
|
-
continue;
|
|
246
|
-
}
|
|
247
|
-
toolsUsed.push(output.name);
|
|
248
|
-
const handoff = handoffMap.get(output.name);
|
|
249
|
-
if (handoff) {
|
|
250
|
-
items.push(new items_1.RunHandoffCallItem(output, agent));
|
|
251
|
-
runHandoffs.push({
|
|
252
|
-
toolCall: output,
|
|
253
|
-
handoff: handoff,
|
|
254
|
-
});
|
|
255
|
-
}
|
|
256
|
-
else {
|
|
257
|
-
const functionTool = functionMap.get(output.name);
|
|
258
|
-
if (!functionTool) {
|
|
259
|
-
(0, context_1.addErrorToCurrentSpan)({
|
|
260
|
-
message: `Tool ${output.name} not found in agent ${agent.name}.`,
|
|
261
|
-
data: {
|
|
262
|
-
tool_name: output.name,
|
|
263
|
-
agent_name: agent.name,
|
|
264
|
-
},
|
|
265
|
-
});
|
|
266
|
-
throw new errors_1.ModelBehaviorError(`Tool ${output.name} not found in agent ${agent.name}.`);
|
|
267
|
-
}
|
|
268
|
-
items.push(new items_1.RunToolCallItem(output, agent));
|
|
269
|
-
runFunctions.push({
|
|
270
|
-
toolCall: output,
|
|
271
|
-
tool: functionTool,
|
|
272
|
-
});
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
return {
|
|
276
|
-
newItems: items,
|
|
277
|
-
handoffs: runHandoffs,
|
|
278
|
-
functions: runFunctions,
|
|
279
|
-
computerActions: runComputerActions,
|
|
280
|
-
shellActions: runShellActions,
|
|
281
|
-
applyPatchActions: runApplyPatchActions,
|
|
282
|
-
mcpApprovalRequests: runMCPApprovalRequests,
|
|
283
|
-
toolsUsed: toolsUsed,
|
|
284
|
-
hasToolsOrApprovalsToRun() {
|
|
285
|
-
return (runHandoffs.length > 0 ||
|
|
286
|
-
runFunctions.length > 0 ||
|
|
287
|
-
runMCPApprovalRequests.length > 0 ||
|
|
288
|
-
runComputerActions.length > 0 ||
|
|
289
|
-
runShellActions.length > 0 ||
|
|
290
|
-
runApplyPatchActions.length > 0);
|
|
291
|
-
},
|
|
292
|
-
};
|
|
293
|
-
}
|
|
294
|
-
exports.nextStepSchema = zod_1.z.discriminatedUnion('type', [
|
|
295
|
-
zod_1.z.object({
|
|
296
|
-
type: zod_1.z.literal('next_step_handoff'),
|
|
297
|
-
newAgent: zod_1.z.any(),
|
|
298
|
-
}),
|
|
299
|
-
zod_1.z.object({
|
|
300
|
-
type: zod_1.z.literal('next_step_final_output'),
|
|
301
|
-
output: zod_1.z.string(),
|
|
302
|
-
}),
|
|
303
|
-
zod_1.z.object({
|
|
304
|
-
type: zod_1.z.literal('next_step_run_again'),
|
|
305
|
-
}),
|
|
306
|
-
zod_1.z.object({
|
|
307
|
-
type: zod_1.z.literal('next_step_interruption'),
|
|
308
|
-
data: zod_1.z.record(zod_1.z.string(), zod_1.z.any()),
|
|
309
|
-
}),
|
|
310
|
-
]);
|
|
311
|
-
/**
|
|
312
|
-
* Internal convenience wrapper that groups the outcome of a single agent turn. It lets the caller
|
|
313
|
-
* update the RunState in one shot and decide which step to execute next.
|
|
314
|
-
*/
|
|
315
|
-
class SingleStepResult {
|
|
316
|
-
originalInput;
|
|
317
|
-
modelResponse;
|
|
318
|
-
preStepItems;
|
|
319
|
-
newStepItems;
|
|
320
|
-
nextStep;
|
|
321
|
-
constructor(
|
|
322
|
-
/**
|
|
323
|
-
* The input items (i.e., the items before run() was called). May be mutated by handoff input filters.
|
|
324
|
-
*/
|
|
325
|
-
originalInput,
|
|
326
|
-
/**
|
|
327
|
-
* The model response for the current step
|
|
328
|
-
*/
|
|
329
|
-
modelResponse,
|
|
330
|
-
/**
|
|
331
|
-
* The items before the current step was executed
|
|
332
|
-
*/
|
|
333
|
-
preStepItems,
|
|
334
|
-
/**
|
|
335
|
-
* The items after the current step was executed
|
|
336
|
-
*/
|
|
337
|
-
newStepItems,
|
|
338
|
-
/**
|
|
339
|
-
* The next step to execute
|
|
340
|
-
*/
|
|
341
|
-
nextStep) {
|
|
342
|
-
this.originalInput = originalInput;
|
|
343
|
-
this.modelResponse = modelResponse;
|
|
344
|
-
this.preStepItems = preStepItems;
|
|
345
|
-
this.newStepItems = newStepItems;
|
|
346
|
-
this.nextStep = nextStep;
|
|
347
|
-
}
|
|
348
|
-
/**
|
|
349
|
-
* The items generated during the agent run (i.e. everything generated after originalInput)
|
|
350
|
-
*/
|
|
351
|
-
get generatedItems() {
|
|
352
|
-
return this.preStepItems.concat(this.newStepItems);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
/**
|
|
356
|
-
* @internal
|
|
357
|
-
* Resets the tool choice when the agent is configured to prefer a fresh tool selection after
|
|
358
|
-
* any tool usage. This prevents the provider from reusing stale tool hints across turns.
|
|
359
|
-
*/
|
|
360
|
-
function maybeResetToolChoice(agent, toolUseTracker, modelSettings) {
|
|
361
|
-
if (agent.resetToolChoice && toolUseTracker.hasUsedTools(agent)) {
|
|
362
|
-
return { ...modelSettings, toolChoice: undefined };
|
|
363
|
-
}
|
|
364
|
-
return modelSettings;
|
|
365
|
-
}
|
|
366
|
-
/**
|
|
367
|
-
* @internal
|
|
368
|
-
* Continues a turn that was previously interrupted waiting for tool approval. Executes the now
|
|
369
|
-
* approved tools and returns the resulting step transition.
|
|
370
|
-
*/
|
|
371
|
-
async function resolveInterruptedTurn(agent, originalInput, originalPreStepItems, newResponse, processedResponse, runner, state) {
|
|
372
|
-
// call_ids for function tools
|
|
373
|
-
const functionCallIds = originalPreStepItems
|
|
374
|
-
.filter((item) => item instanceof items_1.RunToolApprovalItem &&
|
|
375
|
-
'callId' in item.rawItem &&
|
|
376
|
-
item.rawItem.type === 'function_call')
|
|
377
|
-
.map((item) => item.rawItem.callId);
|
|
378
|
-
// We already persisted the turn once when the approval interrupt was raised, so the
|
|
379
|
-
// counter reflects the approval items as "flushed". When we resume the same turn we need
|
|
380
|
-
// to rewind it so the eventual tool output for this call is still written to the session.
|
|
381
|
-
const pendingApprovalItems = state
|
|
382
|
-
.getInterruptions()
|
|
383
|
-
.filter(isApprovalItemLike);
|
|
384
|
-
if (pendingApprovalItems.length > 0) {
|
|
385
|
-
const pendingApprovalIdentities = new Set();
|
|
386
|
-
for (const approval of pendingApprovalItems) {
|
|
387
|
-
const identity = getApprovalIdentity(approval);
|
|
388
|
-
if (identity) {
|
|
389
|
-
pendingApprovalIdentities.add(identity);
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
if (pendingApprovalIdentities.size > 0) {
|
|
393
|
-
let rewindCount = 0;
|
|
394
|
-
for (let index = originalPreStepItems.length - 1; index >= 0; index--) {
|
|
395
|
-
const item = originalPreStepItems[index];
|
|
396
|
-
if (!(item instanceof items_1.RunToolApprovalItem)) {
|
|
397
|
-
continue;
|
|
398
|
-
}
|
|
399
|
-
const identity = getApprovalIdentity(item);
|
|
400
|
-
if (!identity) {
|
|
401
|
-
continue;
|
|
402
|
-
}
|
|
403
|
-
if (!pendingApprovalIdentities.has(identity)) {
|
|
404
|
-
continue;
|
|
405
|
-
}
|
|
406
|
-
rewindCount++;
|
|
407
|
-
pendingApprovalIdentities.delete(identity);
|
|
408
|
-
if (pendingApprovalIdentities.size === 0) {
|
|
409
|
-
break;
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
// Persisting the approval request already advanced the counter once, so undo the increment
|
|
413
|
-
// to make sure we write the final tool output back to the session when the turn resumes.
|
|
414
|
-
if (rewindCount > 0) {
|
|
415
|
-
state._currentTurnPersistedItemCount = Math.max(0, state._currentTurnPersistedItemCount - rewindCount);
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
// Run function tools that require approval after they get their approval results
|
|
420
|
-
const functionToolRuns = processedResponse.functions.filter((run) => {
|
|
421
|
-
return functionCallIds.includes(run.toolCall.callId);
|
|
422
|
-
});
|
|
423
|
-
const functionResults = await executeFunctionToolCalls(agent, functionToolRuns, runner, state);
|
|
424
|
-
// There is no built-in HITL approval surface for computer tools today, so every pending action
|
|
425
|
-
// is executed immediately when the turn resumes.
|
|
426
|
-
const computerResults = processedResponse.computerActions.length > 0
|
|
427
|
-
? await executeComputerActions(agent, processedResponse.computerActions, runner, state._context)
|
|
428
|
-
: [];
|
|
429
|
-
// When resuming we receive the original RunItem references; suppress duplicates so history and streaming do not double-emit the same items.
|
|
430
|
-
const originalPreStepItemSet = new Set(originalPreStepItems);
|
|
431
|
-
const newItems = [];
|
|
432
|
-
const newItemsSet = new Set();
|
|
433
|
-
const appendIfNew = (item) => {
|
|
434
|
-
if (originalPreStepItemSet.has(item) || newItemsSet.has(item)) {
|
|
435
|
-
return;
|
|
436
|
-
}
|
|
437
|
-
newItems.push(item);
|
|
438
|
-
newItemsSet.add(item);
|
|
439
|
-
};
|
|
440
|
-
for (const result of functionResults) {
|
|
441
|
-
appendIfNew(result.runItem);
|
|
442
|
-
}
|
|
443
|
-
for (const result of computerResults) {
|
|
444
|
-
appendIfNew(result);
|
|
445
|
-
}
|
|
446
|
-
// Run MCP tools that require approval after they get their approval results
|
|
447
|
-
const mcpApprovalRuns = processedResponse.mcpApprovalRequests.filter((run) => {
|
|
448
|
-
return (run.requestItem.type === 'tool_approval_item' &&
|
|
449
|
-
run.requestItem.rawItem.type === 'hosted_tool_call' &&
|
|
450
|
-
run.requestItem.rawItem.providerData?.type === 'mcp_approval_request');
|
|
451
|
-
});
|
|
452
|
-
// Hosted MCP approvals may still be waiting on a human decision when the turn resumes.
|
|
453
|
-
const pendingHostedMCPApprovals = new Set();
|
|
454
|
-
const pendingHostedMCPApprovalIds = new Set();
|
|
455
|
-
// Keep track of approvals we still need to surface next turn so HITL flows can resume cleanly.
|
|
456
|
-
for (const run of mcpApprovalRuns) {
|
|
457
|
-
// the approval_request_id "mcpr_123..."
|
|
458
|
-
const rawItem = run.requestItem.rawItem;
|
|
459
|
-
if (rawItem.type !== 'hosted_tool_call') {
|
|
460
|
-
continue;
|
|
461
|
-
}
|
|
462
|
-
const approvalRequestId = rawItem.id;
|
|
463
|
-
const approved = state._context.isToolApproved({
|
|
464
|
-
// Since this item name must be the same with the one sent from Responses API server
|
|
465
|
-
toolName: rawItem.name,
|
|
466
|
-
callId: approvalRequestId,
|
|
467
|
-
});
|
|
468
|
-
if (typeof approved !== 'undefined') {
|
|
469
|
-
const providerData = {
|
|
470
|
-
approve: approved,
|
|
471
|
-
approval_request_id: approvalRequestId,
|
|
472
|
-
reason: undefined,
|
|
473
|
-
};
|
|
474
|
-
// Tell Responses API server the approval result in the next turn
|
|
475
|
-
const responseItem = new items_1.RunToolCallItem({
|
|
476
|
-
type: 'hosted_tool_call',
|
|
477
|
-
name: 'mcp_approval_response',
|
|
478
|
-
providerData,
|
|
479
|
-
}, agent);
|
|
480
|
-
appendIfNew(responseItem);
|
|
481
|
-
}
|
|
482
|
-
else {
|
|
483
|
-
pendingHostedMCPApprovals.add(run.requestItem);
|
|
484
|
-
pendingHostedMCPApprovalIds.add(approvalRequestId);
|
|
485
|
-
functionResults.push({
|
|
486
|
-
type: 'hosted_mcp_tool_approval',
|
|
487
|
-
tool: run.mcpTool,
|
|
488
|
-
runItem: run.requestItem,
|
|
489
|
-
});
|
|
490
|
-
appendIfNew(run.requestItem);
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
// Server-managed conversations rely on preStepItems to re-surface pending approvals.
|
|
494
|
-
// Keep unresolved hosted MCP approvals in place so HITL flows still have something to approve next turn.
|
|
495
|
-
// Drop resolved approval placeholders so they are not replayed on the next turn, but keep
|
|
496
|
-
// pending approvals in place to signal the outstanding work to the UI and session store.
|
|
497
|
-
const preStepItems = originalPreStepItems.filter((item) => {
|
|
498
|
-
if (!(item instanceof items_1.RunToolApprovalItem)) {
|
|
499
|
-
return true;
|
|
500
|
-
}
|
|
501
|
-
if (item.rawItem.type === 'hosted_tool_call' &&
|
|
502
|
-
item.rawItem.providerData?.type === 'mcp_approval_request') {
|
|
503
|
-
if (pendingHostedMCPApprovals.has(item)) {
|
|
504
|
-
return true;
|
|
505
|
-
}
|
|
506
|
-
const approvalRequestId = item.rawItem.id;
|
|
507
|
-
if (approvalRequestId) {
|
|
508
|
-
return pendingHostedMCPApprovalIds.has(approvalRequestId);
|
|
509
|
-
}
|
|
510
|
-
return false;
|
|
511
|
-
}
|
|
512
|
-
return false;
|
|
513
|
-
});
|
|
514
|
-
const completedStep = await maybeCompleteTurnFromToolResults({
|
|
515
|
-
agent,
|
|
516
|
-
runner,
|
|
517
|
-
state,
|
|
518
|
-
functionResults,
|
|
519
|
-
originalInput,
|
|
520
|
-
newResponse,
|
|
521
|
-
preStepItems,
|
|
522
|
-
newItems,
|
|
523
|
-
});
|
|
524
|
-
if (completedStep) {
|
|
525
|
-
return completedStep;
|
|
526
|
-
}
|
|
527
|
-
// we only ran new tools and side effects. We need to run the rest of the agent
|
|
528
|
-
return new SingleStepResult(originalInput, newResponse, preStepItems, newItems, { type: 'next_step_run_again' });
|
|
529
|
-
}
|
|
530
|
-
/**
|
|
531
|
-
* @internal
|
|
532
|
-
* Executes every follow-up action the model requested (function tools, computer actions, MCP flows),
|
|
533
|
-
* appends their outputs to the run history, and determines the next step for the agent loop.
|
|
534
|
-
*/
|
|
535
|
-
async function resolveTurnAfterModelResponse(agent, originalInput, originalPreStepItems, newResponse, processedResponse, runner, state) {
|
|
536
|
-
// Reuse the same array reference so we can compare object identity when deciding whether to
|
|
537
|
-
// append new items, ensuring we never double-stream existing RunItems.
|
|
538
|
-
const preStepItems = originalPreStepItems;
|
|
539
|
-
const seenItems = new Set(originalPreStepItems);
|
|
540
|
-
const newItems = [];
|
|
541
|
-
const appendIfNew = (item) => {
|
|
542
|
-
if (seenItems.has(item)) {
|
|
543
|
-
return;
|
|
544
|
-
}
|
|
545
|
-
newItems.push(item);
|
|
546
|
-
seenItems.add(item);
|
|
547
|
-
};
|
|
548
|
-
for (const item of processedResponse.newItems) {
|
|
549
|
-
appendIfNew(item);
|
|
550
|
-
}
|
|
551
|
-
// Run function tools and computer actions in parallel; neither depends on the other's side effects.
|
|
552
|
-
const [functionResults, computerResults, shellResults, applyPatchResults] = await Promise.all([
|
|
553
|
-
executeFunctionToolCalls(agent, processedResponse.functions, runner, state),
|
|
554
|
-
executeComputerActions(agent, processedResponse.computerActions, runner, state._context),
|
|
555
|
-
executeShellActions(agent, processedResponse.shellActions, runner, state._context),
|
|
556
|
-
executeApplyPatchOperations(agent, processedResponse.applyPatchActions, runner, state._context),
|
|
557
|
-
]);
|
|
558
|
-
for (const result of functionResults) {
|
|
559
|
-
appendIfNew(result.runItem);
|
|
560
|
-
}
|
|
561
|
-
for (const item of computerResults) {
|
|
562
|
-
appendIfNew(item);
|
|
563
|
-
}
|
|
564
|
-
for (const item of shellResults) {
|
|
565
|
-
appendIfNew(item);
|
|
566
|
-
}
|
|
567
|
-
for (const item of applyPatchResults) {
|
|
568
|
-
appendIfNew(item);
|
|
569
|
-
}
|
|
570
|
-
// run hosted MCP approval requests
|
|
571
|
-
if (processedResponse.mcpApprovalRequests.length > 0) {
|
|
572
|
-
for (const approvalRequest of processedResponse.mcpApprovalRequests) {
|
|
573
|
-
const toolData = approvalRequest.mcpTool
|
|
574
|
-
.providerData;
|
|
575
|
-
const requestData = approvalRequest.requestItem.rawItem
|
|
576
|
-
.providerData;
|
|
577
|
-
if (toolData.on_approval) {
|
|
578
|
-
// synchronously handle the approval process here
|
|
579
|
-
const approvalResult = await toolData.on_approval(state._context, approvalRequest.requestItem);
|
|
580
|
-
const approvalResponseData = {
|
|
581
|
-
approve: approvalResult.approve,
|
|
582
|
-
approval_request_id: requestData.id,
|
|
583
|
-
reason: approvalResult.reason,
|
|
584
|
-
};
|
|
585
|
-
newItems.push(new items_1.RunToolCallItem({
|
|
586
|
-
type: 'hosted_tool_call',
|
|
587
|
-
name: 'mcp_approval_response',
|
|
588
|
-
providerData: approvalResponseData,
|
|
589
|
-
}, agent));
|
|
590
|
-
}
|
|
591
|
-
else {
|
|
592
|
-
// receive a user's approval on the next turn
|
|
593
|
-
newItems.push(approvalRequest.requestItem);
|
|
594
|
-
const approvalItem = {
|
|
595
|
-
type: 'hosted_mcp_tool_approval',
|
|
596
|
-
tool: approvalRequest.mcpTool,
|
|
597
|
-
runItem: new items_1.RunToolApprovalItem({
|
|
598
|
-
type: 'hosted_tool_call',
|
|
599
|
-
name: requestData.name,
|
|
600
|
-
id: requestData.id,
|
|
601
|
-
arguments: requestData.arguments,
|
|
602
|
-
status: 'in_progress',
|
|
603
|
-
providerData: requestData,
|
|
604
|
-
}, agent),
|
|
605
|
-
};
|
|
606
|
-
functionResults.push(approvalItem);
|
|
607
|
-
// newItems.push(approvalItem.runItem);
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
// process handoffs
|
|
612
|
-
if (processedResponse.handoffs.length > 0) {
|
|
613
|
-
return await executeHandoffCalls(agent, originalInput, preStepItems, newItems, newResponse, processedResponse.handoffs, runner, state._context);
|
|
614
|
-
}
|
|
615
|
-
const completedStep = await maybeCompleteTurnFromToolResults({
|
|
616
|
-
agent,
|
|
617
|
-
runner,
|
|
618
|
-
state,
|
|
619
|
-
functionResults,
|
|
620
|
-
originalInput,
|
|
621
|
-
newResponse,
|
|
622
|
-
preStepItems,
|
|
623
|
-
newItems,
|
|
624
|
-
});
|
|
625
|
-
if (completedStep) {
|
|
626
|
-
return completedStep;
|
|
627
|
-
}
|
|
628
|
-
// If the model issued any tool calls or handoffs in this turn,
|
|
629
|
-
// we must NOT treat any assistant message in the same turn as the final output.
|
|
630
|
-
// We should run the loop again so the model can see the tool results and respond.
|
|
631
|
-
const hadToolCallsOrActions = (processedResponse.functions?.length ?? 0) > 0 ||
|
|
632
|
-
(processedResponse.computerActions?.length ?? 0) > 0 ||
|
|
633
|
-
(processedResponse.shellActions?.length ?? 0) > 0 ||
|
|
634
|
-
(processedResponse.applyPatchActions?.length ?? 0) > 0 ||
|
|
635
|
-
(processedResponse.mcpApprovalRequests?.length ?? 0) > 0 ||
|
|
636
|
-
(processedResponse.handoffs?.length ?? 0) > 0;
|
|
637
|
-
if (hadToolCallsOrActions) {
|
|
638
|
-
return new SingleStepResult(originalInput, newResponse, preStepItems, newItems, { type: 'next_step_run_again' });
|
|
639
|
-
}
|
|
640
|
-
// No tool calls/actions in this turn; safe to consider a plain assistant message as final.
|
|
641
|
-
const messageItems = newItems.filter((item) => item instanceof items_1.RunMessageOutputItem);
|
|
642
|
-
// we will use the last content output as the final output
|
|
643
|
-
const potentialFinalOutput = messageItems.length > 0
|
|
644
|
-
? (0, messages_1.getLastTextFromOutputMessage)(messageItems[messageItems.length - 1].rawItem)
|
|
645
|
-
: undefined;
|
|
646
|
-
// if there is no output we just run again
|
|
647
|
-
if (typeof potentialFinalOutput === 'undefined') {
|
|
648
|
-
return new SingleStepResult(originalInput, newResponse, preStepItems, newItems, { type: 'next_step_run_again' });
|
|
649
|
-
}
|
|
650
|
-
// Keep looping if any tool output placeholders still require an approval follow-up.
|
|
651
|
-
const hasPendingToolsOrApprovals = functionResults.some((result) => result.runItem instanceof items_1.RunToolApprovalItem);
|
|
652
|
-
if (!hasPendingToolsOrApprovals) {
|
|
653
|
-
if (agent.outputType === 'text') {
|
|
654
|
-
return new SingleStepResult(originalInput, newResponse, preStepItems, newItems, {
|
|
655
|
-
type: 'next_step_final_output',
|
|
656
|
-
output: potentialFinalOutput,
|
|
657
|
-
});
|
|
658
|
-
}
|
|
659
|
-
if (agent.outputType !== 'text' && potentialFinalOutput) {
|
|
660
|
-
// Structured output schema => always leads to a final output if we have text.
|
|
661
|
-
const { parser } = (0, tools_1.getSchemaAndParserFromInputType)(agent.outputType, 'final_output');
|
|
662
|
-
const [error] = await (0, safeExecute_1.safeExecute)(() => parser(potentialFinalOutput));
|
|
663
|
-
if (error) {
|
|
664
|
-
const outputErrorMessage = formatFinalOutputTypeError(error);
|
|
665
|
-
(0, context_1.addErrorToCurrentSpan)({
|
|
666
|
-
message: outputErrorMessage,
|
|
667
|
-
data: {
|
|
668
|
-
error: String(error),
|
|
669
|
-
},
|
|
670
|
-
});
|
|
671
|
-
throw new errors_1.ModelBehaviorError(outputErrorMessage);
|
|
672
|
-
}
|
|
673
|
-
return new SingleStepResult(originalInput, newResponse, preStepItems, newItems, { type: 'next_step_final_output', output: potentialFinalOutput });
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
return new SingleStepResult(originalInput, newResponse, preStepItems, newItems, { type: 'next_step_run_again' });
|
|
677
|
-
}
|
|
678
|
-
// Consolidates the logic that determines whether tool results yielded a final answer,
|
|
679
|
-
// triggered an interruption, or require the agent loop to continue running.
|
|
680
|
-
async function maybeCompleteTurnFromToolResults({ agent, runner, state, functionResults, originalInput, newResponse, preStepItems, newItems, }) {
|
|
681
|
-
const toolOutcome = await checkForFinalOutputFromTools(agent, functionResults, state);
|
|
682
|
-
if (toolOutcome.isFinalOutput) {
|
|
683
|
-
runner.emit('agent_end', state._context, agent, toolOutcome.finalOutput);
|
|
684
|
-
agent.emit('agent_end', state._context, toolOutcome.finalOutput);
|
|
685
|
-
return new SingleStepResult(originalInput, newResponse, preStepItems, newItems, {
|
|
686
|
-
type: 'next_step_final_output',
|
|
687
|
-
output: toolOutcome.finalOutput,
|
|
688
|
-
});
|
|
689
|
-
}
|
|
690
|
-
if (toolOutcome.isInterrupted) {
|
|
691
|
-
return new SingleStepResult(originalInput, newResponse, preStepItems, newItems, {
|
|
692
|
-
type: 'next_step_interruption',
|
|
693
|
-
data: {
|
|
694
|
-
interruptions: toolOutcome.interruptions,
|
|
695
|
-
},
|
|
696
|
-
});
|
|
697
|
-
}
|
|
698
|
-
return null;
|
|
699
|
-
}
|
|
700
|
-
/**
|
|
701
|
-
* @internal
|
|
702
|
-
* Normalizes tool outputs once so downstream code works with fully structured protocol items.
|
|
703
|
-
* Doing this here keeps API surface stable even when providers add new shapes.
|
|
704
|
-
*/
|
|
705
|
-
function getToolCallOutputItem(toolCall, output) {
|
|
706
|
-
const maybeStructuredOutputs = normalizeStructuredToolOutputs(output);
|
|
707
|
-
if (maybeStructuredOutputs) {
|
|
708
|
-
const structuredItems = maybeStructuredOutputs.map(convertStructuredToolOutputToInputItem);
|
|
709
|
-
return {
|
|
710
|
-
type: 'function_call_result',
|
|
711
|
-
name: toolCall.name,
|
|
712
|
-
callId: toolCall.callId,
|
|
713
|
-
status: 'completed',
|
|
714
|
-
output: structuredItems,
|
|
715
|
-
};
|
|
716
|
-
}
|
|
717
|
-
return {
|
|
718
|
-
type: 'function_call_result',
|
|
719
|
-
name: toolCall.name,
|
|
720
|
-
callId: toolCall.callId,
|
|
721
|
-
status: 'completed',
|
|
722
|
-
output: {
|
|
723
|
-
type: 'text',
|
|
724
|
-
text: (0, smartString_1.toSmartString)(output),
|
|
725
|
-
},
|
|
726
|
-
};
|
|
727
|
-
}
|
|
728
|
-
function normalizeFileValue(value) {
|
|
729
|
-
const directFile = value.file;
|
|
730
|
-
if (typeof directFile === 'string' && directFile.length > 0) {
|
|
731
|
-
return directFile;
|
|
732
|
-
}
|
|
733
|
-
const normalizedObject = normalizeFileObjectCandidate(directFile);
|
|
734
|
-
if (normalizedObject) {
|
|
735
|
-
return normalizedObject;
|
|
736
|
-
}
|
|
737
|
-
const legacyValue = normalizeLegacyFileValue(value);
|
|
738
|
-
if (legacyValue) {
|
|
739
|
-
return legacyValue;
|
|
740
|
-
}
|
|
741
|
-
return null;
|
|
742
|
-
}
|
|
743
|
-
function normalizeFileObjectCandidate(value) {
|
|
744
|
-
if (!isRecord(value)) {
|
|
745
|
-
return null;
|
|
746
|
-
}
|
|
747
|
-
if ('data' in value && value.data !== undefined) {
|
|
748
|
-
const dataValue = value.data;
|
|
749
|
-
const hasStringData = typeof dataValue === 'string' && dataValue.length > 0;
|
|
750
|
-
const hasBinaryData = dataValue instanceof Uint8Array && dataValue.length > 0;
|
|
751
|
-
if (!hasStringData && !hasBinaryData) {
|
|
752
|
-
return null;
|
|
753
|
-
}
|
|
754
|
-
if (!isNonEmptyString(value.mediaType) ||
|
|
755
|
-
!isNonEmptyString(value.filename)) {
|
|
756
|
-
return null;
|
|
757
|
-
}
|
|
758
|
-
return {
|
|
759
|
-
data: typeof dataValue === 'string' ? dataValue : new Uint8Array(dataValue),
|
|
760
|
-
mediaType: value.mediaType,
|
|
761
|
-
filename: value.filename,
|
|
762
|
-
};
|
|
763
|
-
}
|
|
764
|
-
if (isNonEmptyString(value.url)) {
|
|
765
|
-
const result = { url: value.url };
|
|
766
|
-
if (isNonEmptyString(value.filename)) {
|
|
767
|
-
result.filename = value.filename;
|
|
768
|
-
}
|
|
769
|
-
return result;
|
|
770
|
-
}
|
|
771
|
-
const referencedId = (isNonEmptyString(value.id) && value.id) ||
|
|
772
|
-
(isNonEmptyString(value.fileId) && value.fileId);
|
|
773
|
-
if (referencedId) {
|
|
774
|
-
const result = { id: referencedId };
|
|
775
|
-
if (isNonEmptyString(value.filename)) {
|
|
776
|
-
result.filename = value.filename;
|
|
777
|
-
}
|
|
778
|
-
return result;
|
|
779
|
-
}
|
|
780
|
-
return null;
|
|
781
|
-
}
|
|
782
|
-
function normalizeLegacyFileValue(value) {
|
|
783
|
-
const filename = typeof value.filename === 'string' && value.filename.length > 0
|
|
784
|
-
? value.filename
|
|
785
|
-
: undefined;
|
|
786
|
-
const mediaType = typeof value.mediaType === 'string' && value.mediaType.length > 0
|
|
787
|
-
? value.mediaType
|
|
788
|
-
: undefined;
|
|
789
|
-
if (typeof value.fileData === 'string' && value.fileData.length > 0) {
|
|
790
|
-
if (!mediaType || !filename) {
|
|
791
|
-
return null;
|
|
792
|
-
}
|
|
793
|
-
return { data: value.fileData, mediaType, filename };
|
|
794
|
-
}
|
|
795
|
-
if (value.fileData instanceof Uint8Array && value.fileData.length > 0) {
|
|
796
|
-
if (!mediaType || !filename) {
|
|
797
|
-
return null;
|
|
798
|
-
}
|
|
799
|
-
return { data: new Uint8Array(value.fileData), mediaType, filename };
|
|
800
|
-
}
|
|
801
|
-
if (typeof value.fileUrl === 'string' && value.fileUrl.length > 0) {
|
|
802
|
-
const result = { url: value.fileUrl };
|
|
803
|
-
if (filename) {
|
|
804
|
-
result.filename = filename;
|
|
805
|
-
}
|
|
806
|
-
return result;
|
|
807
|
-
}
|
|
808
|
-
if (typeof value.fileId === 'string' && value.fileId.length > 0) {
|
|
809
|
-
const result = { id: value.fileId };
|
|
810
|
-
if (filename) {
|
|
811
|
-
result.filename = filename;
|
|
812
|
-
}
|
|
813
|
-
return result;
|
|
814
|
-
}
|
|
815
|
-
return null;
|
|
816
|
-
}
|
|
817
|
-
function isRecord(value) {
|
|
818
|
-
return typeof value === 'object' && value !== null;
|
|
819
|
-
}
|
|
820
|
-
function isNonEmptyString(value) {
|
|
821
|
-
return typeof value === 'string' && value.length > 0;
|
|
822
|
-
}
|
|
823
|
-
function toInlineImageString(data, mediaType) {
|
|
824
|
-
if (typeof data === 'string') {
|
|
825
|
-
if (mediaType && !data.startsWith('data:')) {
|
|
826
|
-
return asDataUrl(data, mediaType);
|
|
827
|
-
}
|
|
828
|
-
return data;
|
|
829
|
-
}
|
|
830
|
-
const base64 = (0, base64_1.encodeUint8ArrayToBase64)(data);
|
|
831
|
-
return asDataUrl(base64, mediaType);
|
|
832
|
-
}
|
|
833
|
-
function asDataUrl(base64, mediaType) {
|
|
834
|
-
return mediaType ? `data:${mediaType};base64,${base64}` : base64;
|
|
835
|
-
}
|
|
836
|
-
/**
|
|
837
|
-
* @internal
|
|
838
|
-
* Runs every function tool call requested by the model and returns their outputs alongside
|
|
839
|
-
* the `RunItem` instances that should be appended to history.
|
|
840
|
-
*/
|
|
841
|
-
async function executeFunctionToolCalls(agent, toolRuns, runner, state) {
|
|
842
|
-
async function runSingleTool(toolRun) {
|
|
843
|
-
let parsedArgs = toolRun.toolCall.arguments;
|
|
844
|
-
if (toolRun.tool.parameters) {
|
|
845
|
-
if ((0, utils_1.isZodObject)(toolRun.tool.parameters)) {
|
|
846
|
-
parsedArgs = toolRun.tool.parameters.parse(parsedArgs);
|
|
847
|
-
}
|
|
848
|
-
else {
|
|
849
|
-
parsedArgs = JSON.parse(parsedArgs);
|
|
850
|
-
}
|
|
851
|
-
}
|
|
852
|
-
// Some tools require a human or policy check before execution; defer until approval is recorded.
|
|
853
|
-
const needsApproval = await toolRun.tool.needsApproval(state._context, parsedArgs, toolRun.toolCall.callId);
|
|
854
|
-
if (needsApproval) {
|
|
855
|
-
const approval = state._context.isToolApproved({
|
|
856
|
-
toolName: toolRun.tool.name,
|
|
857
|
-
callId: toolRun.toolCall.callId,
|
|
858
|
-
});
|
|
859
|
-
if (approval === false) {
|
|
860
|
-
// rejected
|
|
861
|
-
return (0, createSpans_1.withFunctionSpan)(async (span) => {
|
|
862
|
-
const response = 'Tool execution was not approved.';
|
|
863
|
-
span.setError({
|
|
864
|
-
message: response,
|
|
865
|
-
data: {
|
|
866
|
-
tool_name: toolRun.tool.name,
|
|
867
|
-
error: `Tool execution for ${toolRun.toolCall.callId} was manually rejected by user.`,
|
|
868
|
-
},
|
|
869
|
-
});
|
|
870
|
-
span.spanData.output = response;
|
|
871
|
-
return {
|
|
872
|
-
type: 'function_output',
|
|
873
|
-
tool: toolRun.tool,
|
|
874
|
-
output: response,
|
|
875
|
-
runItem: new items_1.RunToolCallOutputItem(getToolCallOutputItem(toolRun.toolCall, response), agent, response),
|
|
876
|
-
};
|
|
877
|
-
}, {
|
|
878
|
-
data: {
|
|
879
|
-
name: toolRun.tool.name,
|
|
880
|
-
},
|
|
881
|
-
});
|
|
882
|
-
}
|
|
883
|
-
if (approval !== true) {
|
|
884
|
-
// this approval process needs to be done in the next turn
|
|
885
|
-
return {
|
|
886
|
-
type: 'function_approval',
|
|
887
|
-
tool: toolRun.tool,
|
|
888
|
-
runItem: new items_1.RunToolApprovalItem(toolRun.toolCall, agent),
|
|
889
|
-
};
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
return (0, createSpans_1.withFunctionSpan)(async (span) => {
|
|
893
|
-
if (runner.config.traceIncludeSensitiveData) {
|
|
894
|
-
span.spanData.input = toolRun.toolCall.arguments;
|
|
895
|
-
}
|
|
896
|
-
try {
|
|
897
|
-
runner.emit('agent_tool_start', state._context, agent, toolRun.tool, {
|
|
898
|
-
toolCall: toolRun.toolCall,
|
|
899
|
-
});
|
|
900
|
-
agent.emit('agent_tool_start', state._context, toolRun.tool, {
|
|
901
|
-
toolCall: toolRun.toolCall,
|
|
902
|
-
});
|
|
903
|
-
const toolOutput = await toolRun.tool.invoke(state._context, toolRun.toolCall.arguments, { toolCall: toolRun.toolCall });
|
|
904
|
-
// Use string data for tracing and event emitter
|
|
905
|
-
const stringResult = (0, smartString_1.toSmartString)(toolOutput);
|
|
906
|
-
runner.emit('agent_tool_end', state._context, agent, toolRun.tool, stringResult, { toolCall: toolRun.toolCall });
|
|
907
|
-
agent.emit('agent_tool_end', state._context, toolRun.tool, stringResult, { toolCall: toolRun.toolCall });
|
|
908
|
-
if (runner.config.traceIncludeSensitiveData) {
|
|
909
|
-
span.spanData.output = stringResult;
|
|
910
|
-
}
|
|
911
|
-
const functionResult = {
|
|
912
|
-
type: 'function_output',
|
|
913
|
-
tool: toolRun.tool,
|
|
914
|
-
output: toolOutput,
|
|
915
|
-
runItem: new items_1.RunToolCallOutputItem(getToolCallOutputItem(toolRun.toolCall, toolOutput), agent, toolOutput),
|
|
916
|
-
};
|
|
917
|
-
const nestedRunResult = (0, agent_1.consumeAgentToolRunResult)(toolRun.toolCall);
|
|
918
|
-
if (nestedRunResult) {
|
|
919
|
-
functionResult.agentRunResult = nestedRunResult;
|
|
920
|
-
const nestedInterruptions = nestedRunResult.interruptions;
|
|
921
|
-
if (nestedInterruptions.length > 0) {
|
|
922
|
-
functionResult.interruptions = nestedInterruptions;
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
return functionResult;
|
|
926
|
-
}
|
|
927
|
-
catch (error) {
|
|
928
|
-
span.setError({
|
|
929
|
-
message: 'Error running tool',
|
|
930
|
-
data: {
|
|
931
|
-
tool_name: toolRun.tool.name,
|
|
932
|
-
error: String(error),
|
|
933
|
-
},
|
|
934
|
-
});
|
|
935
|
-
// Emit agent_tool_end even on error to maintain consistent event lifecycle
|
|
936
|
-
const errorResult = String(error);
|
|
937
|
-
runner.emit('agent_tool_end', state._context, agent, toolRun.tool, errorResult, {
|
|
938
|
-
toolCall: toolRun.toolCall,
|
|
939
|
-
});
|
|
940
|
-
agent.emit('agent_tool_end', state._context, toolRun.tool, errorResult, {
|
|
941
|
-
toolCall: toolRun.toolCall,
|
|
942
|
-
});
|
|
943
|
-
throw error;
|
|
944
|
-
}
|
|
945
|
-
}, {
|
|
946
|
-
data: {
|
|
947
|
-
name: toolRun.tool.name,
|
|
948
|
-
},
|
|
949
|
-
});
|
|
950
|
-
}
|
|
951
|
-
try {
|
|
952
|
-
const results = await Promise.all(toolRuns.map(runSingleTool));
|
|
953
|
-
return results;
|
|
954
|
-
}
|
|
955
|
-
catch (e) {
|
|
956
|
-
throw new errors_1.ToolCallError(`Failed to run function tools: ${e}`, e, state);
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
/**
|
|
960
|
-
* @internal
|
|
961
|
-
*/
|
|
962
|
-
// Internal helper: dispatch a computer action and return a screenshot (sync/async)
|
|
963
|
-
async function _runComputerActionAndScreenshot(computer, toolCall) {
|
|
964
|
-
const action = toolCall.action;
|
|
965
|
-
let screenshot;
|
|
966
|
-
// Dispatch based on action type string (assume action.type exists)
|
|
967
|
-
switch (action.type) {
|
|
968
|
-
case 'click':
|
|
969
|
-
await computer.click(action.x, action.y, action.button);
|
|
970
|
-
break;
|
|
971
|
-
case 'double_click':
|
|
972
|
-
await computer.doubleClick(action.x, action.y);
|
|
973
|
-
break;
|
|
974
|
-
case 'drag':
|
|
975
|
-
await computer.drag(action.path.map((p) => [p.x, p.y]));
|
|
976
|
-
break;
|
|
977
|
-
case 'keypress':
|
|
978
|
-
await computer.keypress(action.keys);
|
|
979
|
-
break;
|
|
980
|
-
case 'move':
|
|
981
|
-
await computer.move(action.x, action.y);
|
|
982
|
-
break;
|
|
983
|
-
case 'screenshot':
|
|
984
|
-
screenshot = await computer.screenshot();
|
|
985
|
-
break;
|
|
986
|
-
case 'scroll':
|
|
987
|
-
await computer.scroll(action.x, action.y, action.scroll_x, action.scroll_y);
|
|
988
|
-
break;
|
|
989
|
-
case 'type':
|
|
990
|
-
await computer.type(action.text);
|
|
991
|
-
break;
|
|
992
|
-
case 'wait':
|
|
993
|
-
await computer.wait();
|
|
994
|
-
break;
|
|
995
|
-
default:
|
|
996
|
-
action; // ensures that we handle every action we know of
|
|
997
|
-
// Unknown action, just take screenshot
|
|
998
|
-
break;
|
|
999
|
-
}
|
|
1000
|
-
if (typeof screenshot !== 'undefined') {
|
|
1001
|
-
return screenshot;
|
|
1002
|
-
}
|
|
1003
|
-
// Always return screenshot as base64 string
|
|
1004
|
-
if (typeof computer.screenshot === 'function') {
|
|
1005
|
-
screenshot = await computer.screenshot();
|
|
1006
|
-
if (typeof screenshot !== 'undefined') {
|
|
1007
|
-
return screenshot;
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
throw new Error('Computer does not implement screenshot()');
|
|
1011
|
-
}
|
|
1012
|
-
function toErrorMessage(error) {
|
|
1013
|
-
if (error instanceof Error) {
|
|
1014
|
-
return error.message || error.toString();
|
|
1015
|
-
}
|
|
1016
|
-
try {
|
|
1017
|
-
return JSON.stringify(error);
|
|
1018
|
-
}
|
|
1019
|
-
catch {
|
|
1020
|
-
return String(error);
|
|
1021
|
-
}
|
|
1022
|
-
}
|
|
1023
|
-
async function executeShellActions(agent, actions, runner, runContext, customLogger = undefined) {
|
|
1024
|
-
const _logger = customLogger ?? logger_1.default;
|
|
1025
|
-
const results = [];
|
|
1026
|
-
for (const action of actions) {
|
|
1027
|
-
const shellTool = action.shell;
|
|
1028
|
-
const toolCall = action.toolCall;
|
|
1029
|
-
const approvalItem = new items_1.RunToolApprovalItem(toolCall, agent, shellTool.name);
|
|
1030
|
-
const requiresApproval = await shellTool.needsApproval(runContext, toolCall.action, toolCall.callId);
|
|
1031
|
-
if (requiresApproval) {
|
|
1032
|
-
if (shellTool.onApproval) {
|
|
1033
|
-
const decision = await shellTool.onApproval(runContext, approvalItem);
|
|
1034
|
-
if (decision.approve === true) {
|
|
1035
|
-
runContext.approveTool(approvalItem);
|
|
1036
|
-
}
|
|
1037
|
-
else if (decision.approve === false) {
|
|
1038
|
-
runContext.rejectTool(approvalItem);
|
|
1039
|
-
}
|
|
1040
|
-
}
|
|
1041
|
-
const approval = runContext.isToolApproved({
|
|
1042
|
-
toolName: shellTool.name,
|
|
1043
|
-
callId: toolCall.callId,
|
|
1044
|
-
});
|
|
1045
|
-
if (approval === false) {
|
|
1046
|
-
const response = 'Tool execution was not approved.';
|
|
1047
|
-
const rejectionOutput = {
|
|
1048
|
-
stdout: '',
|
|
1049
|
-
stderr: response,
|
|
1050
|
-
outcome: { type: 'exit', exitCode: null },
|
|
1051
|
-
};
|
|
1052
|
-
results.push(new items_1.RunToolCallOutputItem({
|
|
1053
|
-
type: 'shell_call_output',
|
|
1054
|
-
callId: toolCall.callId,
|
|
1055
|
-
output: [rejectionOutput],
|
|
1056
|
-
}, agent, response));
|
|
1057
|
-
continue;
|
|
1058
|
-
}
|
|
1059
|
-
if (approval !== true) {
|
|
1060
|
-
results.push(approvalItem);
|
|
1061
|
-
continue;
|
|
1062
|
-
}
|
|
1063
|
-
}
|
|
1064
|
-
runner.emit('agent_tool_start', runContext, agent, shellTool, {
|
|
1065
|
-
toolCall,
|
|
1066
|
-
});
|
|
1067
|
-
if (typeof agent.emit === 'function') {
|
|
1068
|
-
agent.emit('agent_tool_start', runContext, shellTool, { toolCall });
|
|
1069
|
-
}
|
|
1070
|
-
let shellOutputs;
|
|
1071
|
-
const providerMeta = {};
|
|
1072
|
-
let maxOutputLength;
|
|
1073
|
-
try {
|
|
1074
|
-
const shellResult = await shellTool.shell.run(toolCall.action);
|
|
1075
|
-
shellOutputs = shellResult.output ?? [];
|
|
1076
|
-
if (shellResult.providerData) {
|
|
1077
|
-
Object.assign(providerMeta, shellResult.providerData);
|
|
1078
|
-
}
|
|
1079
|
-
if (typeof shellResult.maxOutputLength === 'number') {
|
|
1080
|
-
maxOutputLength = shellResult.maxOutputLength;
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
catch (err) {
|
|
1084
|
-
const errorText = toErrorMessage(err);
|
|
1085
|
-
shellOutputs = [
|
|
1086
|
-
{
|
|
1087
|
-
stdout: '',
|
|
1088
|
-
stderr: errorText,
|
|
1089
|
-
outcome: { type: 'exit', exitCode: null },
|
|
1090
|
-
},
|
|
1091
|
-
];
|
|
1092
|
-
_logger.error('Failed to execute shell action:', err);
|
|
1093
|
-
}
|
|
1094
|
-
shellOutputs = shellOutputs ?? [];
|
|
1095
|
-
runner.emit('agent_tool_end', runContext, agent, shellTool, JSON.stringify(shellOutputs), {
|
|
1096
|
-
toolCall,
|
|
1097
|
-
});
|
|
1098
|
-
if (typeof agent.emit === 'function') {
|
|
1099
|
-
agent.emit('agent_tool_end', runContext, shellTool, JSON.stringify(shellOutputs), {
|
|
1100
|
-
toolCall,
|
|
1101
|
-
});
|
|
1102
|
-
}
|
|
1103
|
-
const rawItem = {
|
|
1104
|
-
type: 'shell_call_output',
|
|
1105
|
-
callId: toolCall.callId,
|
|
1106
|
-
output: shellOutputs ?? [],
|
|
1107
|
-
};
|
|
1108
|
-
if (typeof maxOutputLength === 'number') {
|
|
1109
|
-
rawItem.maxOutputLength = maxOutputLength;
|
|
1110
|
-
}
|
|
1111
|
-
if (Object.keys(providerMeta).length > 0) {
|
|
1112
|
-
rawItem.providerData = providerMeta;
|
|
1113
|
-
}
|
|
1114
|
-
results.push(new items_1.RunToolCallOutputItem(rawItem, agent, rawItem.output));
|
|
1115
|
-
}
|
|
1116
|
-
return results;
|
|
1117
|
-
}
|
|
1118
|
-
async function executeApplyPatchOperations(agent, actions, runner, runContext, customLogger = undefined) {
|
|
1119
|
-
const _logger = customLogger ?? logger_1.default;
|
|
1120
|
-
const results = [];
|
|
1121
|
-
for (const action of actions) {
|
|
1122
|
-
const applyPatchTool = action.applyPatch;
|
|
1123
|
-
const toolCall = action.toolCall;
|
|
1124
|
-
const approvalItem = new items_1.RunToolApprovalItem(toolCall, agent, applyPatchTool.name);
|
|
1125
|
-
const requiresApproval = await applyPatchTool.needsApproval(runContext, toolCall.operation, toolCall.callId);
|
|
1126
|
-
if (requiresApproval) {
|
|
1127
|
-
if (applyPatchTool.onApproval) {
|
|
1128
|
-
const decision = await applyPatchTool.onApproval(runContext, approvalItem);
|
|
1129
|
-
if (decision.approve === true) {
|
|
1130
|
-
runContext.approveTool(approvalItem);
|
|
1131
|
-
}
|
|
1132
|
-
else if (decision.approve === false) {
|
|
1133
|
-
runContext.rejectTool(approvalItem);
|
|
1134
|
-
}
|
|
1135
|
-
}
|
|
1136
|
-
const approval = runContext.isToolApproved({
|
|
1137
|
-
toolName: applyPatchTool.name,
|
|
1138
|
-
callId: toolCall.callId,
|
|
1139
|
-
});
|
|
1140
|
-
if (approval === false) {
|
|
1141
|
-
const response = 'Tool execution was not approved.';
|
|
1142
|
-
results.push(new items_1.RunToolCallOutputItem({
|
|
1143
|
-
type: 'apply_patch_call_output',
|
|
1144
|
-
callId: toolCall.callId,
|
|
1145
|
-
status: 'failed',
|
|
1146
|
-
output: response,
|
|
1147
|
-
}, agent, response));
|
|
1148
|
-
continue;
|
|
1149
|
-
}
|
|
1150
|
-
if (approval !== true) {
|
|
1151
|
-
results.push(approvalItem);
|
|
1152
|
-
continue;
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
runner.emit('agent_tool_start', runContext, agent, applyPatchTool, {
|
|
1156
|
-
toolCall,
|
|
1157
|
-
});
|
|
1158
|
-
if (typeof agent.emit === 'function') {
|
|
1159
|
-
agent.emit('agent_tool_start', runContext, applyPatchTool, {
|
|
1160
|
-
toolCall,
|
|
1161
|
-
});
|
|
1162
|
-
}
|
|
1163
|
-
let status = 'completed';
|
|
1164
|
-
let output = '';
|
|
1165
|
-
try {
|
|
1166
|
-
let result;
|
|
1167
|
-
switch (toolCall.operation.type) {
|
|
1168
|
-
case 'create_file':
|
|
1169
|
-
result = await applyPatchTool.editor.createFile(toolCall.operation);
|
|
1170
|
-
break;
|
|
1171
|
-
case 'update_file':
|
|
1172
|
-
result = await applyPatchTool.editor.updateFile(toolCall.operation);
|
|
1173
|
-
break;
|
|
1174
|
-
case 'delete_file':
|
|
1175
|
-
result = await applyPatchTool.editor.deleteFile(toolCall.operation);
|
|
1176
|
-
break;
|
|
1177
|
-
default:
|
|
1178
|
-
throw new Error('Unsupported apply_patch operation');
|
|
1179
|
-
}
|
|
1180
|
-
if (result && typeof result.status === 'string') {
|
|
1181
|
-
status = result.status;
|
|
1182
|
-
}
|
|
1183
|
-
if (result && typeof result.output === 'string') {
|
|
1184
|
-
output = result.output;
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
catch (err) {
|
|
1188
|
-
status = 'failed';
|
|
1189
|
-
output = toErrorMessage(err);
|
|
1190
|
-
_logger.error('Failed to execute apply_patch operation:', err);
|
|
1191
|
-
}
|
|
1192
|
-
runner.emit('agent_tool_end', runContext, agent, applyPatchTool, output, {
|
|
1193
|
-
toolCall,
|
|
1194
|
-
});
|
|
1195
|
-
if (typeof agent.emit === 'function') {
|
|
1196
|
-
agent.emit('agent_tool_end', runContext, applyPatchTool, output, {
|
|
1197
|
-
toolCall,
|
|
1198
|
-
});
|
|
1199
|
-
}
|
|
1200
|
-
const rawItem = {
|
|
1201
|
-
type: 'apply_patch_call_output',
|
|
1202
|
-
callId: toolCall.callId,
|
|
1203
|
-
status,
|
|
1204
|
-
};
|
|
1205
|
-
if (output) {
|
|
1206
|
-
rawItem.output = output;
|
|
1207
|
-
}
|
|
1208
|
-
results.push(new items_1.RunToolCallOutputItem(rawItem, agent, output));
|
|
1209
|
-
}
|
|
1210
|
-
return results;
|
|
1211
|
-
}
|
|
1212
|
-
/**
|
|
1213
|
-
* @internal
|
|
1214
|
-
* Executes any computer-use actions emitted by the model and returns the resulting items so the
|
|
1215
|
-
* run history reflects the computer session.
|
|
1216
|
-
*/
|
|
1217
|
-
async function executeComputerActions(agent, actions, runner, runContext, customLogger = undefined) {
|
|
1218
|
-
const _logger = customLogger ?? logger_1.default;
|
|
1219
|
-
const results = [];
|
|
1220
|
-
for (const action of actions) {
|
|
1221
|
-
const toolCall = action.toolCall;
|
|
1222
|
-
// Hooks: on_tool_start (global + agent)
|
|
1223
|
-
runner.emit('agent_tool_start', runContext, agent, action.computer, {
|
|
1224
|
-
toolCall,
|
|
1225
|
-
});
|
|
1226
|
-
if (typeof agent.emit === 'function') {
|
|
1227
|
-
agent.emit('agent_tool_start', runContext, action.computer, { toolCall });
|
|
1228
|
-
}
|
|
1229
|
-
// Run the action and get screenshot
|
|
1230
|
-
let output;
|
|
1231
|
-
try {
|
|
1232
|
-
const computer = await (0, tool_1.resolveComputer)({
|
|
1233
|
-
tool: action.computer,
|
|
1234
|
-
runContext,
|
|
1235
|
-
});
|
|
1236
|
-
output = await _runComputerActionAndScreenshot(computer, toolCall);
|
|
1237
|
-
}
|
|
1238
|
-
catch (err) {
|
|
1239
|
-
_logger.error('Failed to execute computer action:', err);
|
|
1240
|
-
output = '';
|
|
1241
|
-
}
|
|
1242
|
-
// Hooks: on_tool_end (global + agent)
|
|
1243
|
-
runner.emit('agent_tool_end', runContext, agent, action.computer, output, {
|
|
1244
|
-
toolCall,
|
|
1245
|
-
});
|
|
1246
|
-
if (typeof agent.emit === 'function') {
|
|
1247
|
-
agent.emit('agent_tool_end', runContext, action.computer, output, {
|
|
1248
|
-
toolCall,
|
|
1249
|
-
});
|
|
1250
|
-
}
|
|
1251
|
-
// Return the screenshot as a data URL when available; fall back to an empty string on failures.
|
|
1252
|
-
const imageUrl = output ? `data:image/png;base64,${output}` : '';
|
|
1253
|
-
const rawItem = {
|
|
1254
|
-
type: 'computer_call_result',
|
|
1255
|
-
callId: toolCall.callId,
|
|
1256
|
-
output: { type: 'computer_screenshot', data: imageUrl },
|
|
1257
|
-
};
|
|
1258
|
-
results.push(new items_1.RunToolCallOutputItem(rawItem, agent, imageUrl));
|
|
1259
|
-
}
|
|
1260
|
-
return results;
|
|
1261
|
-
}
|
|
1262
|
-
/**
|
|
1263
|
-
* @internal
|
|
1264
|
-
* Drives handoff calls by invoking the downstream agent and capturing any generated items so
|
|
1265
|
-
* the current agent can continue with the new context.
|
|
1266
|
-
*/
|
|
1267
|
-
async function executeHandoffCalls(agent, originalInput, preStepItems, newStepItems, newResponse, runHandoffs, runner, runContext) {
|
|
1268
|
-
newStepItems = [...newStepItems];
|
|
1269
|
-
if (runHandoffs.length === 0) {
|
|
1270
|
-
logger_1.default.warn('Incorrectly called executeHandoffCalls with no handoffs. This should not happen. Moving on.');
|
|
1271
|
-
return new SingleStepResult(originalInput, newResponse, preStepItems, newStepItems, { type: 'next_step_run_again' });
|
|
1272
|
-
}
|
|
1273
|
-
if (runHandoffs.length > 1) {
|
|
1274
|
-
// multiple handoffs. Ignoring all but the first one by adding reject responses for those
|
|
1275
|
-
const outputMessage = 'Multiple handoffs detected, ignoring this one.';
|
|
1276
|
-
for (let i = 1; i < runHandoffs.length; i++) {
|
|
1277
|
-
newStepItems.push(new items_1.RunToolCallOutputItem(getToolCallOutputItem(runHandoffs[i].toolCall, outputMessage), agent, outputMessage));
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
const actualHandoff = runHandoffs[0];
|
|
1281
|
-
return (0, createSpans_1.withHandoffSpan)(async (handoffSpan) => {
|
|
1282
|
-
const handoff = actualHandoff.handoff;
|
|
1283
|
-
const newAgent = await handoff.onInvokeHandoff(runContext, actualHandoff.toolCall.arguments);
|
|
1284
|
-
handoffSpan.spanData.to_agent = newAgent.name;
|
|
1285
|
-
if (runHandoffs.length > 1) {
|
|
1286
|
-
const requestedAgents = runHandoffs.map((h) => h.handoff.agentName);
|
|
1287
|
-
handoffSpan.setError({
|
|
1288
|
-
message: 'Multiple handoffs requested',
|
|
1289
|
-
data: {
|
|
1290
|
-
requested_agents: requestedAgents,
|
|
1291
|
-
},
|
|
1292
|
-
});
|
|
1293
|
-
}
|
|
1294
|
-
newStepItems.push(new items_1.RunHandoffOutputItem(getToolCallOutputItem(actualHandoff.toolCall, (0, handoff_1.getTransferMessage)(newAgent)), agent, newAgent));
|
|
1295
|
-
runner.emit('agent_handoff', runContext, agent, newAgent);
|
|
1296
|
-
agent.emit('agent_handoff', runContext, newAgent);
|
|
1297
|
-
const inputFilter = handoff.inputFilter ?? runner.config.handoffInputFilter;
|
|
1298
|
-
if (inputFilter) {
|
|
1299
|
-
logger_1.default.debug('Filtering inputs for handoff');
|
|
1300
|
-
if (typeof inputFilter !== 'function') {
|
|
1301
|
-
handoffSpan.setError({
|
|
1302
|
-
message: 'Invalid input filter',
|
|
1303
|
-
data: {
|
|
1304
|
-
details: 'not callable',
|
|
1305
|
-
},
|
|
1306
|
-
});
|
|
1307
|
-
}
|
|
1308
|
-
const handoffInputData = {
|
|
1309
|
-
inputHistory: Array.isArray(originalInput)
|
|
1310
|
-
? [...originalInput]
|
|
1311
|
-
: originalInput,
|
|
1312
|
-
preHandoffItems: [...preStepItems],
|
|
1313
|
-
newItems: [...newStepItems],
|
|
1314
|
-
runContext,
|
|
1315
|
-
};
|
|
1316
|
-
const filtered = inputFilter(handoffInputData);
|
|
1317
|
-
originalInput = filtered.inputHistory;
|
|
1318
|
-
preStepItems = filtered.preHandoffItems;
|
|
1319
|
-
newStepItems = filtered.newItems;
|
|
1320
|
-
}
|
|
1321
|
-
return new SingleStepResult(originalInput, newResponse, preStepItems, newStepItems, { type: 'next_step_handoff', newAgent });
|
|
1322
|
-
}, {
|
|
1323
|
-
data: {
|
|
1324
|
-
from_agent: agent.name,
|
|
1325
|
-
},
|
|
1326
|
-
});
|
|
1327
|
-
}
|
|
1328
|
-
const NOT_FINAL_OUTPUT = {
|
|
1329
|
-
isFinalOutput: false,
|
|
1330
|
-
isInterrupted: undefined,
|
|
1331
|
-
};
|
|
1332
|
-
/**
|
|
1333
|
-
* @internal
|
|
1334
|
-
* Determines whether tool executions produced a final agent output, triggered an interruption,
|
|
1335
|
-
* or whether the agent loop should continue collecting more responses.
|
|
1336
|
-
*/
|
|
1337
|
-
async function checkForFinalOutputFromTools(agent, toolResults, state) {
|
|
1338
|
-
if (toolResults.length === 0) {
|
|
1339
|
-
return NOT_FINAL_OUTPUT;
|
|
1340
|
-
}
|
|
1341
|
-
const interruptions = [];
|
|
1342
|
-
for (const result of toolResults) {
|
|
1343
|
-
if (result.runItem instanceof items_1.RunToolApprovalItem) {
|
|
1344
|
-
interruptions.push(result.runItem);
|
|
1345
|
-
}
|
|
1346
|
-
if (result.type === 'function_output') {
|
|
1347
|
-
if (Array.isArray(result.interruptions)) {
|
|
1348
|
-
interruptions.push(...result.interruptions);
|
|
1349
|
-
}
|
|
1350
|
-
else if (result.agentRunResult) {
|
|
1351
|
-
const nestedInterruptions = result.agentRunResult.interruptions;
|
|
1352
|
-
if (nestedInterruptions.length > 0) {
|
|
1353
|
-
interruptions.push(...nestedInterruptions);
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
if (interruptions.length > 0) {
|
|
1359
|
-
return {
|
|
1360
|
-
isFinalOutput: false,
|
|
1361
|
-
isInterrupted: true,
|
|
1362
|
-
interruptions,
|
|
1363
|
-
};
|
|
1364
|
-
}
|
|
1365
|
-
if (agent.toolUseBehavior === 'run_llm_again') {
|
|
1366
|
-
return NOT_FINAL_OUTPUT;
|
|
1367
|
-
}
|
|
1368
|
-
const firstToolResult = toolResults[0];
|
|
1369
|
-
if (agent.toolUseBehavior === 'stop_on_first_tool') {
|
|
1370
|
-
if (firstToolResult?.type === 'function_output') {
|
|
1371
|
-
const stringOutput = (0, smartString_1.toSmartString)(firstToolResult.output);
|
|
1372
|
-
return {
|
|
1373
|
-
isFinalOutput: true,
|
|
1374
|
-
isInterrupted: undefined,
|
|
1375
|
-
finalOutput: stringOutput,
|
|
1376
|
-
};
|
|
1377
|
-
}
|
|
1378
|
-
return NOT_FINAL_OUTPUT;
|
|
1379
|
-
}
|
|
1380
|
-
const toolUseBehavior = agent.toolUseBehavior;
|
|
1381
|
-
if (typeof toolUseBehavior === 'object') {
|
|
1382
|
-
const stoppingTool = toolResults.find((r) => toolUseBehavior.stopAtToolNames.includes(r.tool.name));
|
|
1383
|
-
if (stoppingTool?.type === 'function_output') {
|
|
1384
|
-
const stringOutput = (0, smartString_1.toSmartString)(stoppingTool.output);
|
|
1385
|
-
return {
|
|
1386
|
-
isFinalOutput: true,
|
|
1387
|
-
isInterrupted: undefined,
|
|
1388
|
-
finalOutput: stringOutput,
|
|
1389
|
-
};
|
|
1390
|
-
}
|
|
1391
|
-
return NOT_FINAL_OUTPUT;
|
|
1392
|
-
}
|
|
1393
|
-
if (typeof toolUseBehavior === 'function') {
|
|
1394
|
-
return toolUseBehavior(state._context, toolResults);
|
|
1395
|
-
}
|
|
1396
|
-
throw new errors_1.UserError(`Invalid toolUseBehavior: ${toolUseBehavior}`, state);
|
|
1397
|
-
}
|
|
1398
|
-
function getRunItemStreamEventName(item) {
|
|
1399
|
-
if (item instanceof items_1.RunMessageOutputItem) {
|
|
1400
|
-
return 'message_output_created';
|
|
1401
|
-
}
|
|
1402
|
-
if (item instanceof items_1.RunHandoffCallItem) {
|
|
1403
|
-
return 'handoff_requested';
|
|
1404
|
-
}
|
|
1405
|
-
if (item instanceof items_1.RunHandoffOutputItem) {
|
|
1406
|
-
return 'handoff_occurred';
|
|
1407
|
-
}
|
|
1408
|
-
if (item instanceof items_1.RunToolCallItem) {
|
|
1409
|
-
return 'tool_called';
|
|
1410
|
-
}
|
|
1411
|
-
if (item instanceof items_1.RunToolCallOutputItem) {
|
|
1412
|
-
return 'tool_output';
|
|
1413
|
-
}
|
|
1414
|
-
if (item instanceof items_1.RunReasoningItem) {
|
|
1415
|
-
return 'reasoning_item_created';
|
|
1416
|
-
}
|
|
1417
|
-
if (item instanceof items_1.RunToolApprovalItem) {
|
|
1418
|
-
return 'tool_approval_requested';
|
|
1419
|
-
}
|
|
1420
|
-
return undefined;
|
|
1421
|
-
}
|
|
1422
|
-
function enqueueRunItemStreamEvent(result, item) {
|
|
1423
|
-
const itemName = getRunItemStreamEventName(item);
|
|
1424
|
-
if (!itemName) {
|
|
1425
|
-
logger_1.default.warn('Unknown item type: ', item);
|
|
1426
|
-
return;
|
|
1427
|
-
}
|
|
1428
|
-
result._addItem(new events_1.RunItemStreamEvent(itemName, item));
|
|
1429
|
-
}
|
|
1430
|
-
function streamStepItemsToRunResult(result, items) {
|
|
1431
|
-
// Preserve the order in which items were generated by enqueueing each one
|
|
1432
|
-
// immediately on the streamed result.
|
|
1433
|
-
for (const item of items) {
|
|
1434
|
-
enqueueRunItemStreamEvent(result, item);
|
|
1435
|
-
}
|
|
1436
|
-
}
|
|
1437
|
-
function addStepToRunResult(result, step, options) {
|
|
1438
|
-
// skipItems contains run items that were already streamed so we avoid
|
|
1439
|
-
// enqueueing duplicate events for the same instance.
|
|
1440
|
-
const skippedItems = options?.skipItems;
|
|
1441
|
-
for (const item of step.newStepItems) {
|
|
1442
|
-
if (skippedItems?.has(item)) {
|
|
1443
|
-
continue;
|
|
1444
|
-
}
|
|
1445
|
-
enqueueRunItemStreamEvent(result, item);
|
|
1446
|
-
}
|
|
1447
|
-
}
|
|
1448
|
-
class AgentToolUseTracker {
|
|
1449
|
-
#agentToTools = new Map();
|
|
1450
|
-
addToolUse(agent, toolNames) {
|
|
1451
|
-
this.#agentToTools.set(agent, toolNames);
|
|
1452
|
-
}
|
|
1453
|
-
hasUsedTools(agent) {
|
|
1454
|
-
return this.#agentToTools.has(agent);
|
|
1455
|
-
}
|
|
1456
|
-
toJSON() {
|
|
1457
|
-
return Object.fromEntries(Array.from(this.#agentToTools.entries()).map(([agent, toolNames]) => {
|
|
1458
|
-
return [agent.name, toolNames];
|
|
1459
|
-
}));
|
|
1460
|
-
}
|
|
1461
|
-
}
|
|
1462
|
-
exports.AgentToolUseTracker = AgentToolUseTracker;
|
|
1463
|
-
/**
|
|
1464
|
-
* @internal
|
|
1465
|
-
* Convert a user-provided input into a list of input items.
|
|
1466
|
-
*/
|
|
1467
|
-
function toInputItemList(input) {
|
|
1468
|
-
if (typeof input === 'string') {
|
|
1469
|
-
return [
|
|
1470
|
-
{
|
|
1471
|
-
type: 'message',
|
|
1472
|
-
role: 'user',
|
|
1473
|
-
content: input,
|
|
1474
|
-
},
|
|
1475
|
-
];
|
|
1476
|
-
}
|
|
1477
|
-
return [...input];
|
|
1478
|
-
}
|
|
1479
|
-
/**
|
|
1480
|
-
* @internal
|
|
1481
|
-
* Extract model output items from run items, excluding tool approval items.
|
|
1482
|
-
*/
|
|
1483
|
-
function extractOutputItemsFromRunItems(items) {
|
|
1484
|
-
return items
|
|
1485
|
-
.filter((item) => item.type !== 'tool_approval_item')
|
|
1486
|
-
.map((item) => item.rawItem);
|
|
1487
|
-
}
|
|
1488
|
-
function normalizeItemsForSessionPersistence(items) {
|
|
1489
|
-
// Persisted sessions must avoid raw binary so we convert every item into a JSON-safe shape before writing to storage.
|
|
1490
|
-
return items.map((item) => sanitizeValueForSession(stripTransientCallIds(item)));
|
|
1491
|
-
}
|
|
1492
|
-
function sanitizeValueForSession(value, context = {}) {
|
|
1493
|
-
if (value === null || value === undefined) {
|
|
1494
|
-
return value;
|
|
1495
|
-
}
|
|
1496
|
-
// Convert supported binary payloads into ArrayBuffer views before serialization.
|
|
1497
|
-
const binary = toUint8ArrayIfBinary(value);
|
|
1498
|
-
if (binary) {
|
|
1499
|
-
return toDataUrlFromBytes(binary, context.mediaType);
|
|
1500
|
-
}
|
|
1501
|
-
if (Array.isArray(value)) {
|
|
1502
|
-
return value.map((entry) => sanitizeValueForSession(entry, context));
|
|
1503
|
-
}
|
|
1504
|
-
if (!isPlainObject(value)) {
|
|
1505
|
-
return value;
|
|
1506
|
-
}
|
|
1507
|
-
const record = value;
|
|
1508
|
-
const result = {};
|
|
1509
|
-
const mediaType = typeof record.mediaType === 'string' && record.mediaType.length > 0
|
|
1510
|
-
? record.mediaType
|
|
1511
|
-
: context.mediaType;
|
|
1512
|
-
for (const [key, entry] of Object.entries(record)) {
|
|
1513
|
-
// Propagate explicit media type only when walking into binary payload containers.
|
|
1514
|
-
const nextContext = key === 'data' || key === 'fileData' ? { mediaType } : context;
|
|
1515
|
-
result[key] = sanitizeValueForSession(entry, nextContext);
|
|
1516
|
-
}
|
|
1517
|
-
return result;
|
|
1518
|
-
}
|
|
1519
|
-
function toUint8ArrayIfBinary(value) {
|
|
1520
|
-
// Normalize the diverse binary containers we may receive into a shared Uint8Array view.
|
|
1521
|
-
if (value instanceof ArrayBuffer) {
|
|
1522
|
-
return new Uint8Array(value);
|
|
1523
|
-
}
|
|
1524
|
-
if ((0, smartString_1.isArrayBufferView)(value)) {
|
|
1525
|
-
const view = value;
|
|
1526
|
-
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
|
1527
|
-
}
|
|
1528
|
-
if ((0, smartString_1.isNodeBuffer)(value)) {
|
|
1529
|
-
const view = value;
|
|
1530
|
-
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
|
1531
|
-
}
|
|
1532
|
-
if ((0, smartString_1.isSerializedBufferSnapshot)(value)) {
|
|
1533
|
-
const snapshot = value;
|
|
1534
|
-
return Uint8Array.from(snapshot.data);
|
|
1535
|
-
}
|
|
1536
|
-
return undefined;
|
|
1537
|
-
}
|
|
1538
|
-
function toDataUrlFromBytes(bytes, mediaType) {
|
|
1539
|
-
// Convert binary payloads into a durable data URL so session files remain self-contained.
|
|
1540
|
-
const base64 = (0, base64_1.encodeUint8ArrayToBase64)(bytes);
|
|
1541
|
-
// Note that OpenAI Responses API never accepts application/octet-stream as a media type,
|
|
1542
|
-
// so we fall back to text/plain; that said, tools are supposed to return a valid media type when this utility is used.
|
|
1543
|
-
const type = mediaType && !mediaType.startsWith('data:') ? mediaType : 'text/plain';
|
|
1544
|
-
return `data:${type};base64,${base64}`;
|
|
1545
|
-
}
|
|
1546
|
-
function isPlainObject(value) {
|
|
1547
|
-
if (typeof value !== 'object' || value === null) {
|
|
1548
|
-
return false;
|
|
1549
|
-
}
|
|
1550
|
-
const proto = Object.getPrototypeOf(value);
|
|
1551
|
-
return proto === Object.prototype || proto === null;
|
|
1552
|
-
}
|
|
1553
|
-
function stripTransientCallIds(value) {
|
|
1554
|
-
if (value === null || value === undefined) {
|
|
1555
|
-
return value;
|
|
1556
|
-
}
|
|
1557
|
-
if (Array.isArray(value)) {
|
|
1558
|
-
return value.map((entry) => stripTransientCallIds(entry));
|
|
1559
|
-
}
|
|
1560
|
-
if (!isPlainObject(value)) {
|
|
1561
|
-
return value;
|
|
1562
|
-
}
|
|
1563
|
-
const record = value;
|
|
1564
|
-
const result = {};
|
|
1565
|
-
const isProtocolItem = typeof record.type === 'string' && record.type.length > 0;
|
|
1566
|
-
const shouldStripId = isProtocolItem && shouldStripIdForType(record.type);
|
|
1567
|
-
for (const [key, entry] of Object.entries(record)) {
|
|
1568
|
-
if (shouldStripId && key === 'id') {
|
|
1569
|
-
continue;
|
|
1570
|
-
}
|
|
1571
|
-
result[key] = stripTransientCallIds(entry);
|
|
1572
|
-
}
|
|
1573
|
-
return result;
|
|
1574
|
-
}
|
|
1575
|
-
function shouldStripIdForType(type) {
|
|
1576
|
-
switch (type) {
|
|
1577
|
-
case 'function_call':
|
|
1578
|
-
case 'function_call_result':
|
|
1579
|
-
return true;
|
|
1580
|
-
default:
|
|
1581
|
-
return false;
|
|
1582
|
-
}
|
|
1583
|
-
}
|
|
1584
|
-
async function runCompactionOnSession(session, responseId, state) {
|
|
1585
|
-
if (!(0, session_1.isOpenAIResponsesCompactionAwareSession)(session)) {
|
|
1586
|
-
return;
|
|
1587
|
-
}
|
|
1588
|
-
// Called after a completed turn is persisted so compaction can consider the latest stored state.
|
|
1589
|
-
const compactionResult = await session.runCompaction(typeof responseId === 'undefined' ? undefined : { responseId });
|
|
1590
|
-
if (!compactionResult) {
|
|
1591
|
-
return;
|
|
1592
|
-
}
|
|
1593
|
-
const usage = compactionResult.usage;
|
|
1594
|
-
state._context.usage.add(new usage_1.Usage({
|
|
1595
|
-
requests: 1,
|
|
1596
|
-
inputTokens: usage.inputTokens,
|
|
1597
|
-
outputTokens: usage.outputTokens,
|
|
1598
|
-
totalTokens: usage.totalTokens,
|
|
1599
|
-
inputTokensDetails: usage.inputTokensDetails,
|
|
1600
|
-
outputTokensDetails: usage.outputTokensDetails,
|
|
1601
|
-
requestUsageEntries: [usage],
|
|
1602
|
-
}));
|
|
1603
|
-
}
|
|
1604
|
-
/**
|
|
1605
|
-
* @internal
|
|
1606
|
-
* Persist full turn (input + outputs) for non-streaming runs.
|
|
1607
|
-
*/
|
|
1608
|
-
// Persists the combination of user inputs (possibly filtered) and model outputs for a completed turn.
|
|
1609
|
-
async function saveToSession(session, sessionInputItems, result) {
|
|
1610
|
-
if (!session) {
|
|
1611
|
-
return;
|
|
1612
|
-
}
|
|
1613
|
-
const inputItems = sessionInputItems ?? [];
|
|
1614
|
-
const state = result.state;
|
|
1615
|
-
const alreadyPersisted = state._currentTurnPersistedItemCount ?? 0;
|
|
1616
|
-
// Persist only the portion of _generatedItems that has not yet been stored for this turn.
|
|
1617
|
-
const newRunItems = result.newItems.slice(alreadyPersisted);
|
|
1618
|
-
if (process.env.OPENAI_AGENTS__DEBUG_SAVE_SESSION) {
|
|
1619
|
-
console.debug('saveToSession:newRunItems', newRunItems.map((item) => item.type));
|
|
1620
|
-
}
|
|
1621
|
-
const outputItems = extractOutputItemsFromRunItems(newRunItems);
|
|
1622
|
-
const itemsToSave = [...inputItems, ...outputItems];
|
|
1623
|
-
if (itemsToSave.length === 0) {
|
|
1624
|
-
state._currentTurnPersistedItemCount =
|
|
1625
|
-
alreadyPersisted + newRunItems.length;
|
|
1626
|
-
await runCompactionOnSession(session, result.lastResponseId, state);
|
|
1627
|
-
return;
|
|
1628
|
-
}
|
|
1629
|
-
const sanitizedItems = normalizeItemsForSessionPersistence(itemsToSave);
|
|
1630
|
-
await session.addItems(sanitizedItems);
|
|
1631
|
-
await runCompactionOnSession(session, result.lastResponseId, state);
|
|
1632
|
-
state._currentTurnPersistedItemCount = alreadyPersisted + newRunItems.length;
|
|
1633
|
-
}
|
|
1634
|
-
/**
|
|
1635
|
-
* @internal
|
|
1636
|
-
* Persist only the user input for streaming runs at start.
|
|
1637
|
-
*/
|
|
1638
|
-
// For streaming runs we persist user input as soon as it is sent so reconnections can resume.
|
|
1639
|
-
async function saveStreamInputToSession(session, sessionInputItems) {
|
|
1640
|
-
if (!session) {
|
|
1641
|
-
return;
|
|
1642
|
-
}
|
|
1643
|
-
if (!sessionInputItems || sessionInputItems.length === 0) {
|
|
1644
|
-
return;
|
|
1645
|
-
}
|
|
1646
|
-
const sanitizedInput = normalizeItemsForSessionPersistence(sessionInputItems);
|
|
1647
|
-
await session.addItems(sanitizedInput);
|
|
1648
|
-
}
|
|
1649
|
-
/**
|
|
1650
|
-
* @internal
|
|
1651
|
-
* Persist only the model outputs for streaming runs at the end of a turn.
|
|
1652
|
-
*/
|
|
1653
|
-
// Complements saveStreamInputToSession by recording the streaming outputs at the end of the turn.
|
|
1654
|
-
async function saveStreamResultToSession(session, result) {
|
|
1655
|
-
if (!session) {
|
|
1656
|
-
return;
|
|
1657
|
-
}
|
|
1658
|
-
const state = result.state;
|
|
1659
|
-
const alreadyPersisted = state._currentTurnPersistedItemCount ?? 0;
|
|
1660
|
-
const newRunItems = result.newItems.slice(alreadyPersisted);
|
|
1661
|
-
const itemsToSave = extractOutputItemsFromRunItems(newRunItems);
|
|
1662
|
-
if (itemsToSave.length === 0) {
|
|
1663
|
-
state._currentTurnPersistedItemCount =
|
|
1664
|
-
alreadyPersisted + newRunItems.length;
|
|
1665
|
-
await runCompactionOnSession(session, result.lastResponseId, state);
|
|
1666
|
-
return;
|
|
1667
|
-
}
|
|
1668
|
-
const sanitizedItems = normalizeItemsForSessionPersistence(itemsToSave);
|
|
1669
|
-
await session.addItems(sanitizedItems);
|
|
1670
|
-
await runCompactionOnSession(session, result.lastResponseId, state);
|
|
1671
|
-
state._currentTurnPersistedItemCount = alreadyPersisted + newRunItems.length;
|
|
1672
|
-
}
|
|
1673
|
-
async function prepareInputItemsWithSession(input, session, sessionInputCallback, options) {
|
|
1674
|
-
if (!session) {
|
|
1675
|
-
return {
|
|
1676
|
-
preparedInput: input,
|
|
1677
|
-
sessionItems: undefined,
|
|
1678
|
-
};
|
|
1679
|
-
}
|
|
1680
|
-
const includeHistoryInPreparedInput = options?.includeHistoryInPreparedInput ?? true;
|
|
1681
|
-
const preserveDroppedNewItems = options?.preserveDroppedNewItems ?? false;
|
|
1682
|
-
const history = await session.getItems();
|
|
1683
|
-
const newInputItems = Array.isArray(input)
|
|
1684
|
-
? [...input]
|
|
1685
|
-
: toInputItemList(input);
|
|
1686
|
-
if (!sessionInputCallback) {
|
|
1687
|
-
return {
|
|
1688
|
-
preparedInput: includeHistoryInPreparedInput
|
|
1689
|
-
? [...history, ...newInputItems]
|
|
1690
|
-
: newInputItems,
|
|
1691
|
-
sessionItems: newInputItems,
|
|
1692
|
-
};
|
|
1693
|
-
}
|
|
1694
|
-
// Capture snapshots before invoking the callback so we can reason about the original state even
|
|
1695
|
-
// if the callback mutates the history array in-place.
|
|
1696
|
-
const historySnapshot = history.slice();
|
|
1697
|
-
const newInputSnapshot = newInputItems.slice();
|
|
1698
|
-
// Delegate history reconciliation to the user-supplied callback. It must return a concrete list
|
|
1699
|
-
// to keep downstream model requests well-typed.
|
|
1700
|
-
const combined = await sessionInputCallback(history, newInputItems);
|
|
1701
|
-
if (!Array.isArray(combined)) {
|
|
1702
|
-
throw new errors_1.UserError('Session input callback must return an array of AgentInputItem objects.');
|
|
1703
|
-
}
|
|
1704
|
-
const historyCounts = buildItemFrequencyMap(historySnapshot);
|
|
1705
|
-
const newInputCounts = buildItemFrequencyMap(newInputSnapshot);
|
|
1706
|
-
const historyRefs = buildItemReferenceMap(historySnapshot);
|
|
1707
|
-
const newInputRefs = buildItemReferenceMap(newInputSnapshot);
|
|
1708
|
-
const appended = [];
|
|
1709
|
-
for (const item of combined) {
|
|
1710
|
-
const key = sessionItemKey(item);
|
|
1711
|
-
if (consumeReference(newInputRefs, key, item)) {
|
|
1712
|
-
decrementCount(newInputCounts, key);
|
|
1713
|
-
appended.push(item);
|
|
1714
|
-
continue;
|
|
1715
|
-
}
|
|
1716
|
-
// Prioritize exact history matches before payload-based counts so callbacks that surface
|
|
1717
|
-
// history ahead of identical new inputs keep previously persisted items out of the new queue.
|
|
1718
|
-
if (consumeReference(historyRefs, key, item)) {
|
|
1719
|
-
decrementCount(historyCounts, key);
|
|
1720
|
-
continue;
|
|
1721
|
-
}
|
|
1722
|
-
const historyRemaining = historyCounts.get(key) ?? 0;
|
|
1723
|
-
if (historyRemaining > 0) {
|
|
1724
|
-
historyCounts.set(key, historyRemaining - 1);
|
|
1725
|
-
continue;
|
|
1726
|
-
}
|
|
1727
|
-
const newRemaining = newInputCounts.get(key) ?? 0;
|
|
1728
|
-
if (newRemaining > 0) {
|
|
1729
|
-
newInputCounts.set(key, newRemaining - 1);
|
|
1730
|
-
appended.push(item);
|
|
1731
|
-
continue;
|
|
1732
|
-
}
|
|
1733
|
-
appended.push(item);
|
|
1734
|
-
}
|
|
1735
|
-
// Preserve redacted inputs for model delivery when requested (e.g. server-managed histories).
|
|
1736
|
-
const preparedItems = includeHistoryInPreparedInput
|
|
1737
|
-
? combined
|
|
1738
|
-
: appended.length > 0
|
|
1739
|
-
? appended
|
|
1740
|
-
: preserveDroppedNewItems
|
|
1741
|
-
? newInputSnapshot
|
|
1742
|
-
: [];
|
|
1743
|
-
return {
|
|
1744
|
-
preparedInput: preparedItems,
|
|
1745
|
-
// Respect callbacks that intentionally drop the latest inputs (e.g. to redact sensitive
|
|
1746
|
-
// values) by persisting only the items they kept in the combined array.
|
|
1747
|
-
sessionItems: appended,
|
|
1748
|
-
};
|
|
1749
|
-
}
|
|
1750
|
-
/**
|
|
1751
|
-
* Accepts whatever the tool returned and attempts to coerce it into the structured protocol
|
|
1752
|
-
* shapes we expose to downstream model adapters (input_text/input_image/input_file). Tools are
|
|
1753
|
-
* allowed to return either a single structured object or an array of them; anything else falls
|
|
1754
|
-
* back to the legacy string pipeline.
|
|
1755
|
-
*/
|
|
1756
|
-
function normalizeStructuredToolOutputs(output) {
|
|
1757
|
-
if (Array.isArray(output)) {
|
|
1758
|
-
const structured = [];
|
|
1759
|
-
for (const item of output) {
|
|
1760
|
-
const normalized = normalizeStructuredToolOutput(item);
|
|
1761
|
-
if (!normalized) {
|
|
1762
|
-
return null;
|
|
1763
|
-
}
|
|
1764
|
-
structured.push(normalized);
|
|
1765
|
-
}
|
|
1766
|
-
return structured;
|
|
1767
|
-
}
|
|
1768
|
-
const normalized = normalizeStructuredToolOutput(output);
|
|
1769
|
-
return normalized ? [normalized] : null;
|
|
1770
|
-
}
|
|
1771
|
-
/**
|
|
1772
|
-
* Best-effort normalization of a single tool output item. If the object already matches the
|
|
1773
|
-
* protocol shape we simply cast it; otherwise we copy the recognised fields into the canonical
|
|
1774
|
-
* structure. Returning null lets the caller know we should revert to plain-string handling.
|
|
1775
|
-
*/
|
|
1776
|
-
function normalizeStructuredToolOutput(value) {
|
|
1777
|
-
if (!isRecord(value)) {
|
|
1778
|
-
return null;
|
|
1779
|
-
}
|
|
1780
|
-
const type = value.type;
|
|
1781
|
-
if (type === 'text' && typeof value.text === 'string') {
|
|
1782
|
-
const output = { type: 'text', text: value.text };
|
|
1783
|
-
if (isRecord(value.providerData)) {
|
|
1784
|
-
output.providerData = value.providerData;
|
|
1785
|
-
}
|
|
1786
|
-
return output;
|
|
1787
|
-
}
|
|
1788
|
-
if (type === 'image') {
|
|
1789
|
-
const output = { type: 'image' };
|
|
1790
|
-
let imageString;
|
|
1791
|
-
let imageFileId;
|
|
1792
|
-
const fallbackImageMediaType = isNonEmptyString(value.mediaType)
|
|
1793
|
-
? value.mediaType
|
|
1794
|
-
: undefined;
|
|
1795
|
-
const imageField = value.image;
|
|
1796
|
-
if (typeof imageField === 'string' && imageField.length > 0) {
|
|
1797
|
-
imageString = imageField;
|
|
1798
|
-
}
|
|
1799
|
-
else if (isRecord(imageField)) {
|
|
1800
|
-
const imageObj = imageField;
|
|
1801
|
-
const inlineMediaType = isNonEmptyString(imageObj.mediaType)
|
|
1802
|
-
? imageObj.mediaType
|
|
1803
|
-
: fallbackImageMediaType;
|
|
1804
|
-
if (isNonEmptyString(imageObj.url)) {
|
|
1805
|
-
imageString = imageObj.url;
|
|
1806
|
-
}
|
|
1807
|
-
else if (isNonEmptyString(imageObj.data)) {
|
|
1808
|
-
imageString = toInlineImageString(imageObj.data, inlineMediaType);
|
|
1809
|
-
}
|
|
1810
|
-
else if (imageObj.data instanceof Uint8Array &&
|
|
1811
|
-
imageObj.data.length > 0) {
|
|
1812
|
-
imageString = toInlineImageString(imageObj.data, inlineMediaType);
|
|
1813
|
-
}
|
|
1814
|
-
if (!imageString) {
|
|
1815
|
-
const candidateId = (isNonEmptyString(imageObj.fileId) && imageObj.fileId) ||
|
|
1816
|
-
(isNonEmptyString(imageObj.id) && imageObj.id) ||
|
|
1817
|
-
undefined;
|
|
1818
|
-
if (candidateId) {
|
|
1819
|
-
imageFileId = candidateId;
|
|
1820
|
-
}
|
|
1821
|
-
}
|
|
1822
|
-
}
|
|
1823
|
-
if (!imageString &&
|
|
1824
|
-
typeof value.imageUrl === 'string' &&
|
|
1825
|
-
value.imageUrl.length > 0) {
|
|
1826
|
-
imageString = value.imageUrl;
|
|
1827
|
-
}
|
|
1828
|
-
if (!imageFileId &&
|
|
1829
|
-
typeof value.fileId === 'string' &&
|
|
1830
|
-
value.fileId.length > 0) {
|
|
1831
|
-
imageFileId = value.fileId;
|
|
1832
|
-
}
|
|
1833
|
-
if (!imageString &&
|
|
1834
|
-
typeof value.data === 'string' &&
|
|
1835
|
-
value.data.length > 0) {
|
|
1836
|
-
imageString = fallbackImageMediaType
|
|
1837
|
-
? toInlineImageString(value.data, fallbackImageMediaType)
|
|
1838
|
-
: value.data;
|
|
1839
|
-
}
|
|
1840
|
-
else if (!imageString &&
|
|
1841
|
-
value.data instanceof Uint8Array &&
|
|
1842
|
-
value.data.length > 0) {
|
|
1843
|
-
imageString = toInlineImageString(value.data, fallbackImageMediaType);
|
|
1844
|
-
}
|
|
1845
|
-
if (typeof value.detail === 'string' && value.detail.length > 0) {
|
|
1846
|
-
output.detail = value.detail;
|
|
1847
|
-
}
|
|
1848
|
-
if (imageString) {
|
|
1849
|
-
output.image = imageString;
|
|
1850
|
-
}
|
|
1851
|
-
else if (imageFileId) {
|
|
1852
|
-
output.image = { fileId: imageFileId };
|
|
1853
|
-
}
|
|
1854
|
-
else {
|
|
1855
|
-
return null;
|
|
1856
|
-
}
|
|
1857
|
-
if (isRecord(value.providerData)) {
|
|
1858
|
-
output.providerData = value.providerData;
|
|
1859
|
-
}
|
|
1860
|
-
return output;
|
|
1861
|
-
}
|
|
1862
|
-
if (type === 'file') {
|
|
1863
|
-
const fileValue = normalizeFileValue(value);
|
|
1864
|
-
if (!fileValue) {
|
|
1865
|
-
return null;
|
|
1866
|
-
}
|
|
1867
|
-
const output = { type: 'file', file: fileValue };
|
|
1868
|
-
if (isRecord(value.providerData)) {
|
|
1869
|
-
output.providerData = value.providerData;
|
|
1870
|
-
}
|
|
1871
|
-
return output;
|
|
1872
|
-
}
|
|
1873
|
-
return null;
|
|
1874
|
-
}
|
|
1875
|
-
/**
|
|
1876
|
-
* Translates the normalized tool output into the protocol `input_*` items. This is the last hop
|
|
1877
|
-
* before we hand the data to model-specific adapters, so we generate the exact schema expected by
|
|
1878
|
-
* the protocol definitions.
|
|
1879
|
-
*/
|
|
1880
|
-
function convertStructuredToolOutputToInputItem(output) {
|
|
1881
|
-
if (output.type === 'text') {
|
|
1882
|
-
const result = {
|
|
1883
|
-
type: 'input_text',
|
|
1884
|
-
text: output.text,
|
|
1885
|
-
};
|
|
1886
|
-
if (output.providerData) {
|
|
1887
|
-
result.providerData = output.providerData;
|
|
1888
|
-
}
|
|
1889
|
-
return result;
|
|
1890
|
-
}
|
|
1891
|
-
if (output.type === 'image') {
|
|
1892
|
-
const result = { type: 'input_image' };
|
|
1893
|
-
if (typeof output.detail === 'string' && output.detail.length > 0) {
|
|
1894
|
-
result.detail = output.detail;
|
|
1895
|
-
}
|
|
1896
|
-
if (typeof output.image === 'string' && output.image.length > 0) {
|
|
1897
|
-
result.image = output.image;
|
|
1898
|
-
}
|
|
1899
|
-
else if (isRecord(output.image)) {
|
|
1900
|
-
const imageObj = output.image;
|
|
1901
|
-
const inlineMediaType = isNonEmptyString(imageObj.mediaType)
|
|
1902
|
-
? imageObj.mediaType
|
|
1903
|
-
: undefined;
|
|
1904
|
-
if (isNonEmptyString(imageObj.url)) {
|
|
1905
|
-
result.image = imageObj.url;
|
|
1906
|
-
}
|
|
1907
|
-
else if (isNonEmptyString(imageObj.data)) {
|
|
1908
|
-
result.image =
|
|
1909
|
-
inlineMediaType && !imageObj.data.startsWith('data:')
|
|
1910
|
-
? asDataUrl(imageObj.data, inlineMediaType)
|
|
1911
|
-
: imageObj.data;
|
|
1912
|
-
}
|
|
1913
|
-
else if (imageObj.data instanceof Uint8Array &&
|
|
1914
|
-
imageObj.data.length > 0) {
|
|
1915
|
-
const base64 = (0, base64_1.encodeUint8ArrayToBase64)(imageObj.data);
|
|
1916
|
-
result.image = asDataUrl(base64, inlineMediaType);
|
|
1917
|
-
}
|
|
1918
|
-
else {
|
|
1919
|
-
const referencedId = (isNonEmptyString(imageObj.fileId) && imageObj.fileId) ||
|
|
1920
|
-
(isNonEmptyString(imageObj.id) && imageObj.id) ||
|
|
1921
|
-
undefined;
|
|
1922
|
-
if (referencedId) {
|
|
1923
|
-
result.image = { id: referencedId };
|
|
1924
|
-
}
|
|
1925
|
-
}
|
|
1926
|
-
}
|
|
1927
|
-
if (output.providerData) {
|
|
1928
|
-
result.providerData = output.providerData;
|
|
1929
|
-
}
|
|
1930
|
-
return result;
|
|
1931
|
-
}
|
|
1932
|
-
if (output.type === 'file') {
|
|
1933
|
-
const result = { type: 'input_file' };
|
|
1934
|
-
const fileValue = output.file;
|
|
1935
|
-
if (typeof fileValue === 'string') {
|
|
1936
|
-
result.file = fileValue;
|
|
1937
|
-
}
|
|
1938
|
-
else if (fileValue && typeof fileValue === 'object') {
|
|
1939
|
-
const record = fileValue;
|
|
1940
|
-
if ('data' in record && record.data) {
|
|
1941
|
-
const mediaType = record.mediaType ?? 'text/plain';
|
|
1942
|
-
if (typeof record.data === 'string') {
|
|
1943
|
-
result.file = asDataUrl(record.data, mediaType);
|
|
1944
|
-
}
|
|
1945
|
-
else {
|
|
1946
|
-
const base64 = (0, base64_1.encodeUint8ArrayToBase64)(record.data);
|
|
1947
|
-
result.file = asDataUrl(base64, mediaType);
|
|
1948
|
-
}
|
|
1949
|
-
}
|
|
1950
|
-
else if (typeof record.url === 'string' && record.url.length > 0) {
|
|
1951
|
-
result.file = { url: record.url };
|
|
1952
|
-
}
|
|
1953
|
-
else {
|
|
1954
|
-
const referencedId = (typeof record.id === 'string' &&
|
|
1955
|
-
record.id.length > 0 &&
|
|
1956
|
-
record.id) ||
|
|
1957
|
-
(typeof record.fileId === 'string' && record.fileId.length > 0
|
|
1958
|
-
? record.fileId
|
|
1959
|
-
: undefined);
|
|
1960
|
-
if (referencedId) {
|
|
1961
|
-
result.file = { id: referencedId };
|
|
1962
|
-
}
|
|
1963
|
-
}
|
|
1964
|
-
if (typeof record.filename === 'string' && record.filename.length > 0) {
|
|
1965
|
-
result.filename = record.filename;
|
|
1966
|
-
}
|
|
1967
|
-
}
|
|
1968
|
-
if (output.providerData) {
|
|
1969
|
-
result.providerData = output.providerData;
|
|
1970
|
-
}
|
|
1971
|
-
return result;
|
|
1972
|
-
}
|
|
1973
|
-
const exhaustiveCheck = output;
|
|
1974
|
-
return exhaustiveCheck;
|
|
1975
|
-
}
|
|
1976
|
-
function buildItemFrequencyMap(items) {
|
|
1977
|
-
const counts = new Map();
|
|
1978
|
-
for (const item of items) {
|
|
1979
|
-
const key = sessionItemKey(item);
|
|
1980
|
-
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
1981
|
-
}
|
|
1982
|
-
return counts;
|
|
1983
|
-
}
|
|
1984
|
-
function buildItemReferenceMap(items) {
|
|
1985
|
-
const refs = new Map();
|
|
1986
|
-
for (const item of items) {
|
|
1987
|
-
const key = sessionItemKey(item);
|
|
1988
|
-
const list = refs.get(key);
|
|
1989
|
-
if (list) {
|
|
1990
|
-
list.push(item);
|
|
1991
|
-
}
|
|
1992
|
-
else {
|
|
1993
|
-
refs.set(key, [item]);
|
|
1994
|
-
}
|
|
1995
|
-
}
|
|
1996
|
-
return refs;
|
|
1997
|
-
}
|
|
1998
|
-
function consumeReference(refs, key, target) {
|
|
1999
|
-
const candidates = refs.get(key);
|
|
2000
|
-
if (!candidates || candidates.length === 0) {
|
|
2001
|
-
return false;
|
|
2002
|
-
}
|
|
2003
|
-
const index = candidates.findIndex((candidate) => candidate === target);
|
|
2004
|
-
if (index === -1) {
|
|
2005
|
-
return false;
|
|
2006
|
-
}
|
|
2007
|
-
candidates.splice(index, 1);
|
|
2008
|
-
if (candidates.length === 0) {
|
|
2009
|
-
refs.delete(key);
|
|
2010
|
-
}
|
|
2011
|
-
return true;
|
|
2012
|
-
}
|
|
2013
|
-
function decrementCount(map, key) {
|
|
2014
|
-
const remaining = (map.get(key) ?? 0) - 1;
|
|
2015
|
-
if (remaining <= 0) {
|
|
2016
|
-
map.delete(key);
|
|
2017
|
-
}
|
|
2018
|
-
else {
|
|
2019
|
-
map.set(key, remaining);
|
|
2020
|
-
}
|
|
2021
|
-
}
|
|
2022
|
-
function sessionItemKey(item) {
|
|
2023
|
-
return JSON.stringify(item, sessionSerializationReplacer);
|
|
2024
|
-
}
|
|
2025
|
-
function sessionSerializationReplacer(_key, value) {
|
|
2026
|
-
if (value instanceof ArrayBuffer) {
|
|
2027
|
-
return {
|
|
2028
|
-
__type: 'ArrayBuffer',
|
|
2029
|
-
data: (0, base64_1.encodeUint8ArrayToBase64)(new Uint8Array(value)),
|
|
2030
|
-
};
|
|
2031
|
-
}
|
|
2032
|
-
if ((0, smartString_1.isArrayBufferView)(value)) {
|
|
2033
|
-
const view = value;
|
|
2034
|
-
return {
|
|
2035
|
-
__type: view.constructor.name,
|
|
2036
|
-
data: (0, base64_1.encodeUint8ArrayToBase64)(new Uint8Array(view.buffer, view.byteOffset, view.byteLength)),
|
|
2037
|
-
};
|
|
2038
|
-
}
|
|
2039
|
-
if ((0, smartString_1.isNodeBuffer)(value)) {
|
|
2040
|
-
const view = value;
|
|
2041
|
-
return {
|
|
2042
|
-
__type: 'Buffer',
|
|
2043
|
-
data: (0, base64_1.encodeUint8ArrayToBase64)(new Uint8Array(view.buffer, view.byteOffset, view.byteLength)),
|
|
2044
|
-
};
|
|
2045
|
-
}
|
|
2046
|
-
if ((0, smartString_1.isSerializedBufferSnapshot)(value)) {
|
|
2047
|
-
return {
|
|
2048
|
-
__type: 'Buffer',
|
|
2049
|
-
data: (0, base64_1.encodeUint8ArrayToBase64)(Uint8Array.from(value.data)),
|
|
2050
|
-
};
|
|
2051
|
-
}
|
|
2052
|
-
return value;
|
|
2053
|
-
}
|
|
2054
|
-
//# sourceMappingURL=runImplementation.js.map
|