@myagentroam/agent 0.15.12 → 0.15.14
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/cli/subagent/index.js +0 -3
- package/dist/model/openai-responses.d.ts +11 -4
- package/dist/model/openai-responses.js +105 -40
- package/dist/model/responses-request.d.ts +16 -5
- package/dist/model/responses-request.js +87 -56
- package/dist/model/responses-session-cache.d.ts +2 -3
- package/dist/session/record-projection.js +3 -0
- package/package.json +1 -1
|
@@ -10,9 +10,6 @@ import { childResources } from './resources.js';
|
|
|
10
10
|
import { sharedSessionHistory } from './history.js';
|
|
11
11
|
const delegationPrompt = [
|
|
12
12
|
'# Delegation and coordination',
|
|
13
|
-
'Prefer handling focused or tightly coupled work locally.',
|
|
14
|
-
'Consider delegating a clearly separable subtask when parallel progress or context savings materially outweigh coordination overhead.',
|
|
15
|
-
'Avoid splitting work merely because agents are available.',
|
|
16
13
|
'A useful handoff includes an objective, necessary context, expected output, and a read-only boundary or non-overlapping write scope.',
|
|
17
14
|
'Prefer following up through the direct delegate; deeper Session inspection is usually useful only when a concrete issue needs independent verification.',
|
|
18
15
|
'While children run, prefer advancing meaningful, non-overlapping task work rather than duplicating delegated work. Waiting is generally useful once no meaningful local task work remains and a required result is needed to unblock or finish the task.',
|
|
@@ -1,13 +1,20 @@
|
|
|
1
|
+
import { type ResponsesRequestBody, type ResponsesToolPlaceholders } from './responses-request.js';
|
|
1
2
|
export { openAiInput } from './responses-request.js';
|
|
2
3
|
import { type AgentModelConfiguration, type ModelCredential, type ModelCredentialAcquireReason } from './configuration.js';
|
|
3
4
|
import WebSocket from 'ws';
|
|
4
5
|
import type { ModelAdapter, ModelAttemptDiagnostic, ModelEvent, ModelRequest, ModelTurnSession } from './contracts.js';
|
|
5
|
-
import { ResponsesSessionCache, type
|
|
6
|
-
interface
|
|
7
|
-
readonly inputItemCount: number;
|
|
8
|
-
readonly fullBody: ResponsesRequestBody;
|
|
6
|
+
import { ResponsesSessionCache, type ResponsesSessionState } from './responses-session-cache.js';
|
|
7
|
+
interface PreparedResponsesAttempt {
|
|
9
8
|
readonly body: ResponsesRequestBody;
|
|
9
|
+
readonly inputItemCount: number;
|
|
10
|
+
readonly toolPlans: ReadonlyMap<string, ResponsesToolPlaceholders | undefined>;
|
|
11
|
+
readonly deferredToolPlans: ReadonlyMap<string, ResponsesToolPlaceholders | undefined>;
|
|
12
|
+
}
|
|
13
|
+
interface PreparedResponsesRequest {
|
|
14
|
+
readonly first: PreparedResponsesAttempt;
|
|
15
|
+
readonly full: PreparedResponsesAttempt;
|
|
10
16
|
readonly continuation: boolean;
|
|
17
|
+
completed?: PreparedResponsesAttempt;
|
|
11
18
|
}
|
|
12
19
|
type ResponsesWebSocketDiagnostic = Pick<ModelAttemptDiagnostic, 'requestBytes' | 'imageCount' | 'imageBytes' | 'requestFrameCount' | 'sentFrameCount' | 'webSocketPhase' | 'webSocketCloseCode'>;
|
|
13
20
|
export declare class OpenAiResponsesAdapter implements ModelAdapter {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { responsesRequestBody } from './responses-request.js';
|
|
2
2
|
export { openAiInput } from './responses-request.js';
|
|
3
3
|
import { ResponsesTextProjection, hostedWebActionInput, hostedWebActionSummary, responseCitations, responseEventId, responseItem } from './responses-event-projection.js';
|
|
4
4
|
import { isRealUserMessage } from './input-images.js';
|
|
@@ -20,6 +20,47 @@ const WEBSOCKET_IDLE_TIMEOUT_MS = 180_000;
|
|
|
20
20
|
const WEBSOCKET_SEND_FRAME_BYTES = 1024 * 1024;
|
|
21
21
|
const OPENAI_RESPONSES_EARLY_EOF_REASON = 'OPENAI_RESPONSES_EARLY_EOF';
|
|
22
22
|
const X_CODEX_TURN_STATE = 'x-codex-turn-state';
|
|
23
|
+
/** Follow only positions recorded by the Strict projection, without mutating the response. */
|
|
24
|
+
function responsesToolArguments(value, plan) {
|
|
25
|
+
if (!plan)
|
|
26
|
+
return value;
|
|
27
|
+
const pending = [];
|
|
28
|
+
const copy = (node, fields) => {
|
|
29
|
+
if (!fields || node === null || typeof node !== 'object')
|
|
30
|
+
return node;
|
|
31
|
+
if (Array.isArray(node)) {
|
|
32
|
+
if (!fields.items)
|
|
33
|
+
return node;
|
|
34
|
+
const array = node.slice();
|
|
35
|
+
pending.push([array, fields]);
|
|
36
|
+
return array;
|
|
37
|
+
}
|
|
38
|
+
if (!fields.properties)
|
|
39
|
+
return node;
|
|
40
|
+
const object = { ...node };
|
|
41
|
+
pending.push([object, fields]);
|
|
42
|
+
return object;
|
|
43
|
+
};
|
|
44
|
+
const result = copy(value, plan);
|
|
45
|
+
while (pending.length > 0) {
|
|
46
|
+
const [node, fields] = pending.pop();
|
|
47
|
+
if (Array.isArray(node)) {
|
|
48
|
+
for (let i = 0; i < node.length; i++)
|
|
49
|
+
node[i] = copy(node[i], fields.items);
|
|
50
|
+
}
|
|
51
|
+
else if (fields.properties) {
|
|
52
|
+
for (const [key, child] of fields.properties) {
|
|
53
|
+
if (!Object.hasOwn(node, key))
|
|
54
|
+
continue;
|
|
55
|
+
if (node[key] === null && child.omitNull)
|
|
56
|
+
delete node[key];
|
|
57
|
+
else
|
|
58
|
+
node[key] = copy(node[key], child);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
23
64
|
export class OpenAiResponsesAdapter {
|
|
24
65
|
#cache = new ResponsesSessionCache();
|
|
25
66
|
#configuration;
|
|
@@ -54,7 +95,6 @@ export class OpenAiResponsesAdapter {
|
|
|
54
95
|
}
|
|
55
96
|
async *startTurn(request, signal, turn, prepared) {
|
|
56
97
|
let useContinuation = prepared.continuation;
|
|
57
|
-
let requestBody = prepared.body;
|
|
58
98
|
let credentialReason = 'REQUEST';
|
|
59
99
|
let unauthorizedRetryUsed = false;
|
|
60
100
|
let invalidContinuationFallbackUsed = false;
|
|
@@ -67,8 +107,8 @@ export class OpenAiResponsesAdapter {
|
|
|
67
107
|
// Adapter retries and Runtime recovery share this counter, but not Provider Turn state.
|
|
68
108
|
turn.restartProviderTurn();
|
|
69
109
|
useContinuation = false;
|
|
70
|
-
requestBody = prepared.fullBody;
|
|
71
110
|
}
|
|
111
|
+
const attemptRequest = useContinuation ? prepared.first : prepared.full;
|
|
72
112
|
if (resetOutputTiming)
|
|
73
113
|
yield { type: 'output.reset' };
|
|
74
114
|
resetOutputTiming = false;
|
|
@@ -80,7 +120,7 @@ export class OpenAiResponsesAdapter {
|
|
|
80
120
|
const attemptTransport = this.configuration.responsesTransport?.transport === 'WEBSOCKET' ? 'WEBSOCKET' : 'HTTP';
|
|
81
121
|
const requestPrefixDiagnostic = request.onAttemptDiagnostic
|
|
82
122
|
? {
|
|
83
|
-
requestInputItems:
|
|
123
|
+
requestInputItems: attemptRequest.inputItemCount
|
|
84
124
|
}
|
|
85
125
|
: {};
|
|
86
126
|
const prelude = [];
|
|
@@ -98,7 +138,7 @@ export class OpenAiResponsesAdapter {
|
|
|
98
138
|
...requestPrefixDiagnostic
|
|
99
139
|
});
|
|
100
140
|
try {
|
|
101
|
-
for await (const event of observeModelRequestUsage(() => this.startAttempt(request, signal,
|
|
141
|
+
for await (const event of observeModelRequestUsage(() => this.startAttempt(request, signal, attemptRequest, useContinuation, credentialReason, turn), request, this.configuration, signal)) {
|
|
102
142
|
if (event.type.startsWith('output.')) {
|
|
103
143
|
resetOutputTiming = true;
|
|
104
144
|
yield event;
|
|
@@ -131,6 +171,7 @@ export class OpenAiResponsesAdapter {
|
|
|
131
171
|
...turn.connectionDiagnostic(),
|
|
132
172
|
durationMs: Math.max(0, Date.now() - attemptStartedAt)
|
|
133
173
|
});
|
|
174
|
+
prepared.completed = attemptRequest;
|
|
134
175
|
return;
|
|
135
176
|
}
|
|
136
177
|
catch (error) {
|
|
@@ -159,7 +200,6 @@ export class OpenAiResponsesAdapter {
|
|
|
159
200
|
isLocalContinuationReset(error)) {
|
|
160
201
|
invalidContinuationFallbackUsed = true;
|
|
161
202
|
useContinuation = false;
|
|
162
|
-
requestBody = prepared.fullBody;
|
|
163
203
|
turn.restartProviderTurn();
|
|
164
204
|
retryState.attempts = Math.max(0, retryState.attempts - 1);
|
|
165
205
|
credentialReason = 'RECONNECT';
|
|
@@ -181,7 +221,6 @@ export class OpenAiResponsesAdapter {
|
|
|
181
221
|
if (fallback?.action === 'resetContinuation') {
|
|
182
222
|
invalidContinuationFallbackUsed = true;
|
|
183
223
|
useContinuation = false;
|
|
184
|
-
requestBody = prepared.fullBody;
|
|
185
224
|
turn.restartProviderTurn();
|
|
186
225
|
credentialReason = 'RECONNECT';
|
|
187
226
|
await reportFailure(true, {
|
|
@@ -226,14 +265,14 @@ export class OpenAiResponsesAdapter {
|
|
|
226
265
|
? 'RECONNECT'
|
|
227
266
|
: 'REQUEST';
|
|
228
267
|
useContinuation = false;
|
|
229
|
-
requestBody = prepared.fullBody;
|
|
230
268
|
if (error instanceof AgentError && error.details?.transport === 'WEBSOCKET')
|
|
231
269
|
turn.invalidateWebSocket();
|
|
232
270
|
await waitForModelRetry(retryAfter, attempt, signal, delayMs);
|
|
233
271
|
}
|
|
234
272
|
}
|
|
235
273
|
}
|
|
236
|
-
async *startAttempt(request, signal,
|
|
274
|
+
async *startAttempt(request, signal, attempt, continuation, credentialReason, turn) {
|
|
275
|
+
const { body, toolPlans } = attempt;
|
|
237
276
|
let latestCredentialRevision;
|
|
238
277
|
let diagnosticSecrets = [];
|
|
239
278
|
const fetchResponse = async (requestBody) => {
|
|
@@ -396,7 +435,7 @@ export class OpenAiResponsesAdapter {
|
|
|
396
435
|
type: 'client_tool.call',
|
|
397
436
|
callId,
|
|
398
437
|
name: 'tool_search',
|
|
399
|
-
arguments: arguments_,
|
|
438
|
+
arguments: responsesToolArguments(arguments_, toolPlans.get('tool_search')),
|
|
400
439
|
...(argumentError ? { argumentError } : {})
|
|
401
440
|
}, modelStreamEventObservedAt(raw));
|
|
402
441
|
}
|
|
@@ -427,7 +466,7 @@ export class OpenAiResponsesAdapter {
|
|
|
427
466
|
type: 'client_tool.call',
|
|
428
467
|
callId,
|
|
429
468
|
name,
|
|
430
|
-
arguments:
|
|
469
|
+
arguments: responsesToolArguments(args, toolPlans.get(name)),
|
|
431
470
|
...(argumentError ? { argumentError } : {})
|
|
432
471
|
}, modelStreamEventObservedAt(raw));
|
|
433
472
|
}
|
|
@@ -696,18 +735,24 @@ class OpenAiResponsesTurnSession {
|
|
|
696
735
|
yield event;
|
|
697
736
|
}
|
|
698
737
|
responseId = this.#completedResponseId ?? responseId;
|
|
699
|
-
|
|
738
|
+
const attempt = prepared.completed;
|
|
739
|
+
if (attempt !== undefined &&
|
|
740
|
+
responsesContinuationEnabled(this.adapter.configuration) &&
|
|
700
741
|
completed &&
|
|
701
742
|
responseId !== undefined &&
|
|
702
743
|
(outputItems.length > 0 || !sawUnrepresentedOutput)) {
|
|
703
744
|
this.state.lastRequest =
|
|
704
745
|
this.adapter.configuration.responsesTransport?.transport === 'WEBSOCKET'
|
|
705
|
-
? { ...
|
|
706
|
-
: prepared.
|
|
746
|
+
? { ...attempt.body, input: [] }
|
|
747
|
+
: prepared.full.body;
|
|
707
748
|
this.state.lastMessageCount = request.messages.length + outputMessageCount;
|
|
708
|
-
this.state.lastInputItemCount =
|
|
749
|
+
this.state.lastInputItemCount = attempt.inputItemCount;
|
|
709
750
|
this.state.lastSystem = JSON.stringify([request.system, request.systemBlocks]);
|
|
710
|
-
this.state.lastResponse = {
|
|
751
|
+
this.state.lastResponse = {
|
|
752
|
+
responseId,
|
|
753
|
+
outputItems,
|
|
754
|
+
deferredToolPlans: attempt.deferredToolPlans
|
|
755
|
+
};
|
|
711
756
|
}
|
|
712
757
|
else
|
|
713
758
|
clearResponsesContinuation(this.state);
|
|
@@ -772,55 +817,57 @@ class OpenAiResponsesTurnSession {
|
|
|
772
817
|
clearResponsesContinuation(this.state);
|
|
773
818
|
}
|
|
774
819
|
// The continuation baseline must not share mutable schemas or items with callers.
|
|
775
|
-
const
|
|
820
|
+
const project = (input, messages, previousOutputItems = []) => {
|
|
821
|
+
const toolProjection = { direct: new Map(), deferred: new Map() };
|
|
822
|
+
const body = JSON.parse(JSON.stringify(responsesRequestBody(this.adapter.configuration, input, messages, previousOutputItems, toolProjection)));
|
|
823
|
+
return { body, toolProjection };
|
|
824
|
+
};
|
|
825
|
+
let fullProjection;
|
|
826
|
+
const fullRequest = () => (fullProjection ??= project(request, request.messages));
|
|
776
827
|
let full;
|
|
777
|
-
const
|
|
828
|
+
const fullAttempt = () => {
|
|
829
|
+
const { body, toolProjection } = fullRequest();
|
|
830
|
+
return (full ??= prepareResponsesAttempt(body, body.input.length, toolProjection));
|
|
831
|
+
};
|
|
778
832
|
if (responsesContinuationEnabled(this.adapter.configuration)) {
|
|
779
833
|
const websocket = this.adapter.configuration.responsesTransport?.transport === 'WEBSOCKET';
|
|
780
834
|
const suffixMessages = websocket && this.state.lastMessageCount !== undefined
|
|
781
835
|
? request.messages.slice(this.state.lastMessageCount)
|
|
782
836
|
: undefined;
|
|
783
|
-
const
|
|
837
|
+
const suffix = websocket &&
|
|
784
838
|
this.state.lastResponse !== undefined &&
|
|
785
839
|
suffixMessages !== undefined &&
|
|
786
840
|
this.state.lastRequest !== undefined &&
|
|
787
841
|
this.state.lastSystem === JSON.stringify([request.system, request.systemBlocks]) &&
|
|
788
842
|
// Top-level images attach to the last real user, which must be in this suffix.
|
|
789
843
|
(!request.images?.length || suffixMessages.some(isRealUserMessage))
|
|
790
|
-
?
|
|
844
|
+
? project({ ...request, system: '', systemBlocks: [] }, suffixMessages, this.state.lastResponse.outputItems)
|
|
791
845
|
: undefined;
|
|
792
846
|
const incremental = websocket
|
|
793
|
-
?
|
|
794
|
-
responsesContinuationPropertiesMatch(this.state.lastRequest,
|
|
795
|
-
?
|
|
847
|
+
? suffix !== undefined &&
|
|
848
|
+
responsesContinuationPropertiesMatch(this.state.lastRequest, suffix.body)
|
|
849
|
+
? suffix.body.input
|
|
796
850
|
: undefined
|
|
797
|
-
: incrementalResponsesInput(this.state,
|
|
851
|
+
: incrementalResponsesInput(this.state, fullRequest().body);
|
|
798
852
|
if (incremental !== undefined) {
|
|
799
|
-
const
|
|
853
|
+
const previous = this.state.lastResponse;
|
|
800
854
|
const inputItemCount = websocket
|
|
801
|
-
? (this.state.lastInputItemCount ?? 0) +
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
: fullBody().input.length;
|
|
855
|
+
? (this.state.lastInputItemCount ?? 0) + previous.outputItems.length + incremental.length
|
|
856
|
+
: fullRequest().body.input.length;
|
|
857
|
+
const { body, toolProjection } = suffix ?? fullRequest();
|
|
805
858
|
delete this.state.lastResponse;
|
|
806
859
|
return {
|
|
807
|
-
get
|
|
808
|
-
return
|
|
809
|
-
},
|
|
810
|
-
inputItemCount,
|
|
811
|
-
body: {
|
|
812
|
-
...(suffixBody ?? fullBody()),
|
|
813
|
-
input: incremental,
|
|
814
|
-
previous_response_id: responseId
|
|
860
|
+
get full() {
|
|
861
|
+
return fullAttempt();
|
|
815
862
|
},
|
|
863
|
+
first: prepareResponsesAttempt({ ...body, input: incremental, previous_response_id: previous.responseId }, inputItemCount, toolProjection, previous.deferredToolPlans),
|
|
816
864
|
continuation: true
|
|
817
865
|
};
|
|
818
866
|
}
|
|
819
867
|
}
|
|
820
868
|
return {
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
body: fullBody(),
|
|
869
|
+
full: fullAttempt(),
|
|
870
|
+
first: fullAttempt(),
|
|
824
871
|
continuation: false
|
|
825
872
|
};
|
|
826
873
|
}
|
|
@@ -967,6 +1014,24 @@ function incrementalResponsesInput(state, current) {
|
|
|
967
1014
|
return undefined;
|
|
968
1015
|
return current.input.slice(baseline.length);
|
|
969
1016
|
}
|
|
1017
|
+
/** Inherited plans describe the provider prefix; only the input actually sent can replace them. */
|
|
1018
|
+
function prepareResponsesAttempt(body, inputItemCount, projection, inherited) {
|
|
1019
|
+
const deferredToolPlans = new Map(inherited);
|
|
1020
|
+
for (const value of body.input) {
|
|
1021
|
+
const item = record(value);
|
|
1022
|
+
const callId = text(item.call_id);
|
|
1023
|
+
if (item.type !== 'tool_search_output' || callId === undefined)
|
|
1024
|
+
continue;
|
|
1025
|
+
for (const [name, plan] of projection.deferred.get(callId) ?? [])
|
|
1026
|
+
deferredToolPlans.set(name, plan);
|
|
1027
|
+
}
|
|
1028
|
+
return {
|
|
1029
|
+
body,
|
|
1030
|
+
inputItemCount,
|
|
1031
|
+
deferredToolPlans,
|
|
1032
|
+
toolPlans: new Map([...deferredToolPlans, ...projection.direct])
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
970
1035
|
function responsesContinuationPropertiesMatch(previous, current) {
|
|
971
1036
|
return (JSON.stringify({ ...previous, input: undefined, previous_response_id: undefined }) ===
|
|
972
1037
|
JSON.stringify({ ...current, input: undefined, previous_response_id: undefined }));
|
|
@@ -1,7 +1,18 @@
|
|
|
1
1
|
import { type AgentModelConfiguration } from './configuration.js';
|
|
2
2
|
import type { ModelRequest } from './contracts.js';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
export type ResponsesRequestBody = Readonly<Record<string, unknown>> & {
|
|
4
|
+
readonly input: readonly unknown[];
|
|
5
|
+
};
|
|
6
|
+
export interface ResponsesToolPlaceholders {
|
|
7
|
+
omitNull?: true;
|
|
8
|
+
properties?: Map<string, ResponsesToolPlaceholders>;
|
|
9
|
+
items?: ResponsesToolPlaceholders;
|
|
10
|
+
}
|
|
11
|
+
type ToolPlaceholders = Map<string, ResponsesToolPlaceholders | undefined>;
|
|
12
|
+
export interface ResponsesToolProjection {
|
|
13
|
+
direct: ToolPlaceholders;
|
|
14
|
+
deferred: Map<string, ToolPlaceholders>;
|
|
15
|
+
}
|
|
16
|
+
export declare function responsesRequestBody(configuration: AgentModelConfiguration, request: ModelRequest, messages: ModelRequest['messages'], previousOutputItems?: readonly Record<string, unknown>[], placeholders?: ResponsesToolProjection): ResponsesRequestBody;
|
|
17
|
+
export declare function openAiInput(messages: ModelRequest['messages'], images: ModelRequest['images'] | undefined, modelId: string, requireEncryptedReasoning: boolean, configurationUpdates?: boolean, nativeTools?: boolean, tools?: ModelRequest['tools'], previousOutputItems?: readonly Record<string, unknown>[], deferredPlaceholders?: ResponsesToolProjection['deferred']): Record<string, unknown>[];
|
|
18
|
+
export {};
|
|
@@ -7,7 +7,7 @@ import { record, text } from './sse.js';
|
|
|
7
7
|
import { resolveModelTextBlocks } from './text-blocks.js';
|
|
8
8
|
import { stableToolSchema } from './tool-schema.js';
|
|
9
9
|
import { jsonToolInput } from './tool-input.js';
|
|
10
|
-
export function responsesRequestBody(configuration, request, messages, previousOutputItems = []) {
|
|
10
|
+
export function responsesRequestBody(configuration, request, messages, previousOutputItems = [], placeholders) {
|
|
11
11
|
const systemBlocks = resolveModelTextBlocks(request.system, request.systemBlocks ?? []);
|
|
12
12
|
if ((request.systemBlocks !== undefined && systemBlocks.some((block) => block.cache)) ||
|
|
13
13
|
messages.some((message) => message.textBlocks !== undefined &&
|
|
@@ -21,9 +21,9 @@ export function responsesRequestBody(configuration, request, messages, previousO
|
|
|
21
21
|
type: 'tool_search',
|
|
22
22
|
execution: 'client',
|
|
23
23
|
description: tool.description,
|
|
24
|
-
parameters: stableToolSchema(
|
|
24
|
+
parameters: stableToolSchema(strictToolParameters(tool, placeholders?.direct))
|
|
25
25
|
}
|
|
26
|
-
: responsesFunctionTool(tool, configuration.responsesOptionalParameters?.nativeTools !== false));
|
|
26
|
+
: responsesFunctionTool(tool, configuration.responsesOptionalParameters?.nativeTools !== false, placeholders?.direct));
|
|
27
27
|
if (configuration.responsesToolNamespace && tools.length > 0) {
|
|
28
28
|
const native = tools.filter((tool) => record(tool).type === 'tool_search');
|
|
29
29
|
const nested = tools.filter((tool) => record(tool).type !== 'tool_search');
|
|
@@ -41,7 +41,7 @@ export function responsesRequestBody(configuration, request, messages, previousO
|
|
|
41
41
|
configuration.hostedWebSearch)
|
|
42
42
|
tools.push({ type: 'web_search' });
|
|
43
43
|
const toolChoice = request.toolChoice ?? 'auto';
|
|
44
|
-
const input = openAiInput(messages, request.images, configuration.id, true, usesResponsesConfigurationUpdates(configuration), configuration.responsesOptionalParameters?.nativeTools !== false, request.tools, previousOutputItems);
|
|
44
|
+
const input = openAiInput(messages, request.images, configuration.id, true, usesResponsesConfigurationUpdates(configuration), configuration.responsesOptionalParameters?.nativeTools !== false, request.tools, previousOutputItems, placeholders?.deferred);
|
|
45
45
|
const systemInput = responsesSystemInput(request, systemBlocks);
|
|
46
46
|
if (systemInput !== undefined)
|
|
47
47
|
input.unshift(systemInput);
|
|
@@ -106,7 +106,13 @@ function responsesSystemInput(request, blocks = resolveModelTextBlocks(request.s
|
|
|
106
106
|
content: blocks.map((block) => ({ type: 'input_text', text: block.text }))
|
|
107
107
|
};
|
|
108
108
|
}
|
|
109
|
-
function strictFunctionSchema(value, optional = false) {
|
|
109
|
+
function strictFunctionSchema(value, optional = false, placeholders) {
|
|
110
|
+
const projected = projectStrictFunctionSchema(value, optional, placeholders);
|
|
111
|
+
if (optional && placeholders && acceptsNull(value) === false && acceptsNull(projected) === true)
|
|
112
|
+
placeholders.omitNull = true;
|
|
113
|
+
return projected;
|
|
114
|
+
}
|
|
115
|
+
function projectStrictFunctionSchema(value, optional, placeholders) {
|
|
110
116
|
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
111
117
|
return value;
|
|
112
118
|
const schema = value;
|
|
@@ -115,30 +121,46 @@ function strictFunctionSchema(value, optional = false) {
|
|
|
115
121
|
supportedSchema.anyOf = schema.anyOf.map((branch) => strictFunctionSchema(branch));
|
|
116
122
|
if (optional && Array.isArray(schema.enum) && !schema.enum.includes(null))
|
|
117
123
|
supportedSchema.enum = [...schema.enum, null];
|
|
124
|
+
// Do not select a union branch or infer constraints from references.
|
|
125
|
+
const childPlans = placeholders &&
|
|
126
|
+
!hasUnresolvedNullConstraint(schema) &&
|
|
127
|
+
!['anyOf', 'const', 'enum'].some((key) => Object.hasOwn(schema, key))
|
|
128
|
+
? placeholders
|
|
129
|
+
: undefined;
|
|
118
130
|
if (schema.type === 'object') {
|
|
119
131
|
const properties = record(schema.properties);
|
|
120
132
|
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
|
|
121
133
|
return {
|
|
122
134
|
...supportedSchema,
|
|
123
135
|
...(optional ? { type: ['object', 'null'] } : {}),
|
|
124
|
-
properties: Object.fromEntries(Object.entries(properties).map(([name, property]) =>
|
|
125
|
-
|
|
126
|
-
strictFunctionSchema(property, !required.has(name))
|
|
127
|
-
|
|
136
|
+
properties: Object.fromEntries(Object.entries(properties).map(([name, property]) => {
|
|
137
|
+
const child = childPlans ? {} : undefined;
|
|
138
|
+
const projected = strictFunctionSchema(property, !required.has(name), child);
|
|
139
|
+
if (childPlans && child && hasPlaceholders(child))
|
|
140
|
+
(childPlans.properties ??= new Map()).set(name, child);
|
|
141
|
+
return [name, projected];
|
|
142
|
+
})),
|
|
128
143
|
required: Object.keys(properties),
|
|
129
144
|
additionalProperties: false
|
|
130
145
|
};
|
|
131
146
|
}
|
|
132
|
-
if (schema.type === 'array')
|
|
147
|
+
if (schema.type === 'array') {
|
|
148
|
+
const child = childPlans ? {} : undefined;
|
|
149
|
+
const items = schema.items === undefined ? undefined : strictFunctionSchema(schema.items, false, child);
|
|
150
|
+
if (childPlans && child && hasPlaceholders(child))
|
|
151
|
+
childPlans.items = child;
|
|
133
152
|
return {
|
|
134
153
|
...supportedSchema,
|
|
135
|
-
...(
|
|
154
|
+
...(items === undefined ? {} : { items }),
|
|
136
155
|
...(optional ? { type: ['array', 'null'] } : {})
|
|
137
156
|
};
|
|
157
|
+
}
|
|
138
158
|
if (!optional)
|
|
139
159
|
return supportedSchema;
|
|
140
160
|
if (typeof schema.type === 'string')
|
|
141
|
-
return
|
|
161
|
+
return schema.type === 'null'
|
|
162
|
+
? supportedSchema
|
|
163
|
+
: { ...supportedSchema, type: [schema.type, 'null'] };
|
|
142
164
|
if (Array.isArray(schema.type))
|
|
143
165
|
return {
|
|
144
166
|
...supportedSchema,
|
|
@@ -155,7 +177,30 @@ function strictFunctionSchema(value, optional = false) {
|
|
|
155
177
|
};
|
|
156
178
|
return { anyOf: [supportedSchema, { type: 'null' }] };
|
|
157
179
|
}
|
|
158
|
-
|
|
180
|
+
function hasPlaceholders(plan) {
|
|
181
|
+
return Boolean(plan.omitNull || plan.properties || plan.items);
|
|
182
|
+
}
|
|
183
|
+
function hasUnresolvedNullConstraint(schema) {
|
|
184
|
+
return ['$ref', '$dynamicRef', '$recursiveRef', 'oneOf', 'allOf', 'not', 'if', 'nullable'].some((key) => Object.hasOwn(schema, key));
|
|
185
|
+
}
|
|
186
|
+
/** Only classify null for the explicit forms used by the Strict projection. */
|
|
187
|
+
function acceptsNull(value) {
|
|
188
|
+
if (typeof value === 'boolean')
|
|
189
|
+
return value;
|
|
190
|
+
const schema = record(value);
|
|
191
|
+
if (hasUnresolvedNullConstraint(schema))
|
|
192
|
+
return undefined;
|
|
193
|
+
if ((typeof schema.type === 'string' && schema.type !== 'null') ||
|
|
194
|
+
(Array.isArray(schema.type) && !schema.type.includes('null')) ||
|
|
195
|
+
(Object.hasOwn(schema, 'const') && schema.const !== null) ||
|
|
196
|
+
(Array.isArray(schema.enum) && !schema.enum.includes(null)))
|
|
197
|
+
return false;
|
|
198
|
+
if (!Array.isArray(schema.anyOf))
|
|
199
|
+
return true;
|
|
200
|
+
const branches = schema.anyOf.map(acceptsNull);
|
|
201
|
+
return branches.includes(true) ? true : branches.includes(undefined) ? undefined : false;
|
|
202
|
+
}
|
|
203
|
+
export function openAiInput(messages, images, modelId, requireEncryptedReasoning, configurationUpdates = true, nativeTools = true, tools = [], previousOutputItems = [], deferredPlaceholders) {
|
|
159
204
|
const compatibleMessages = messages.filter((message) => message.role !== 'provider' ||
|
|
160
205
|
(message.provider === 'OPENAI_RESPONSES' &&
|
|
161
206
|
(message.providerModelId === undefined || message.providerModelId === modelId) &&
|
|
@@ -251,12 +296,12 @@ export function openAiInput(messages, images, modelId, requireEncryptedReasoning
|
|
|
251
296
|
searchDiagnostics.push(`Tool Search failed (call ID: ${message.callId}):\n${message.content}`);
|
|
252
297
|
message = { ...message, toolSearchTools: [] };
|
|
253
298
|
}
|
|
254
|
-
input.push(openAiInputItem(message, message === lastUser ? images : undefined, customCallIds, functionCallIds, nativeTools, tools));
|
|
299
|
+
input.push(openAiInputItem(message, message === lastUser ? images : undefined, customCallIds, functionCallIds, nativeTools, tools, deferredPlaceholders));
|
|
255
300
|
}
|
|
256
301
|
flushSearchDiagnostics();
|
|
257
302
|
return input;
|
|
258
303
|
}
|
|
259
|
-
function openAiInputItem(message, images, customCallIds = new Set(), functionCallIds = new Set(), nativeTools = true, tools = []) {
|
|
304
|
+
function openAiInputItem(message, images, customCallIds = new Set(), functionCallIds = new Set(), nativeTools = true, tools = [], deferredPlaceholders) {
|
|
260
305
|
const userImages = message.role === 'user' ? uniqueModelImages(message.images, images) : [];
|
|
261
306
|
if (message.role === 'provider') {
|
|
262
307
|
if (message.provider !== 'OPENAI_RESPONSES' || !message.item)
|
|
@@ -298,14 +343,19 @@ function openAiInputItem(message, images, customCallIds = new Set(), functionCal
|
|
|
298
343
|
if (message.role === 'tool' &&
|
|
299
344
|
nativeTools &&
|
|
300
345
|
message.toolSearchTools &&
|
|
301
|
-
!functionCallIds.has(message.callId ?? ''))
|
|
346
|
+
!functionCallIds.has(message.callId ?? '')) {
|
|
347
|
+
const placeholders = deferredPlaceholders ? new Map() : undefined;
|
|
348
|
+
const projectedTools = message.toolSearchTools.map((tool) => responsesFunctionTool(tool, true, placeholders));
|
|
349
|
+
if (placeholders && message.callId)
|
|
350
|
+
deferredPlaceholders?.set(message.callId, placeholders);
|
|
302
351
|
return {
|
|
303
352
|
type: 'tool_search_output',
|
|
304
353
|
call_id: message.callId,
|
|
305
354
|
status: 'completed',
|
|
306
355
|
execution: 'client',
|
|
307
|
-
tools:
|
|
356
|
+
tools: projectedTools
|
|
308
357
|
};
|
|
358
|
+
}
|
|
309
359
|
if (message.role === 'tool')
|
|
310
360
|
return {
|
|
311
361
|
type: customCallIds.has(message.callId ?? '')
|
|
@@ -368,46 +418,27 @@ function openAiInputItem(message, images, customCallIds = new Set(), functionCal
|
|
|
368
418
|
function contextualAuthority(message) {
|
|
369
419
|
return message.contextualBlock?.authority;
|
|
370
420
|
}
|
|
371
|
-
function
|
|
372
|
-
const
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
type: 'function',
|
|
377
|
-
name: tool.name,
|
|
378
|
-
description: tool.description,
|
|
379
|
-
parameters: stableToolSchema(strict ? strictFunctionSchema(stableToolSchema(tool.inputSchema)) : tool.inputSchema),
|
|
380
|
-
strict
|
|
381
|
-
};
|
|
421
|
+
function strictToolParameters(tool, placeholders) {
|
|
422
|
+
const plan = placeholders ? {} : undefined;
|
|
423
|
+
const parameters = strictFunctionSchema(stableToolSchema(tool.inputSchema), false, plan);
|
|
424
|
+
placeholders?.set(tool.name, plan && hasPlaceholders(plan) ? plan : undefined);
|
|
425
|
+
return parameters;
|
|
382
426
|
}
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
return
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
const properties = record(schema.properties);
|
|
399
|
-
return Object.fromEntries(args.filter(([key, argument]) => {
|
|
400
|
-
if (argument !== null || required.has(key) || !Object.hasOwn(properties, key))
|
|
401
|
-
return true;
|
|
402
|
-
const { type, enum: choices } = record(properties[key]);
|
|
403
|
-
if (Array.isArray(choices) && !choices.includes(null))
|
|
404
|
-
return false;
|
|
405
|
-
if (typeof type === 'string')
|
|
406
|
-
return type === 'null';
|
|
407
|
-
if (Array.isArray(type))
|
|
408
|
-
return type.includes('null');
|
|
409
|
-
return true;
|
|
410
|
-
}));
|
|
427
|
+
function responsesFunctionTool(tool, nativeTools, placeholders) {
|
|
428
|
+
if (tool.inputMode === 'freeform' && nativeTools) {
|
|
429
|
+
placeholders?.set(tool.name, undefined);
|
|
430
|
+
return { type: 'custom', name: tool.name, description: tool.description };
|
|
431
|
+
}
|
|
432
|
+
const strict = !hasOpenFunctionObject(tool.inputSchema);
|
|
433
|
+
if (!strict)
|
|
434
|
+
placeholders?.set(tool.name, undefined);
|
|
435
|
+
return {
|
|
436
|
+
type: 'function',
|
|
437
|
+
name: tool.name,
|
|
438
|
+
description: tool.description,
|
|
439
|
+
parameters: stableToolSchema(strict ? strictToolParameters(tool, placeholders) : tool.inputSchema),
|
|
440
|
+
strict
|
|
441
|
+
};
|
|
411
442
|
}
|
|
412
443
|
function hasOpenFunctionObject(value) {
|
|
413
444
|
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import WebSocket from 'ws';
|
|
2
|
-
|
|
3
|
-
readonly input: readonly unknown[];
|
|
4
|
-
};
|
|
2
|
+
import type { ResponsesRequestBody, ResponsesToolPlaceholders } from './responses-request.js';
|
|
5
3
|
export interface ResponsesSessionState {
|
|
6
4
|
socket?: WebSocket;
|
|
7
5
|
endpoint?: string;
|
|
@@ -16,6 +14,7 @@ export interface ResponsesSessionState {
|
|
|
16
14
|
lastResponse?: {
|
|
17
15
|
readonly responseId: string;
|
|
18
16
|
readonly outputItems: readonly Record<string, unknown>[];
|
|
17
|
+
readonly deferredToolPlans: ReadonlyMap<string, ResponsesToolPlaceholders | undefined>;
|
|
19
18
|
};
|
|
20
19
|
}
|
|
21
20
|
export declare function clearResponsesContinuation(state: ResponsesSessionState): void;
|
|
@@ -67,6 +67,9 @@ export function parseModelInputMetadata(value) {
|
|
|
67
67
|
...(typeof metadata.recordId === 'string' && metadata.recordId.length <= 128
|
|
68
68
|
? { recordId: metadata.recordId }
|
|
69
69
|
: {}),
|
|
70
|
+
...(typeof metadata.clientMessageId === 'string'
|
|
71
|
+
? { clientMessageId: metadata.clientMessageId }
|
|
72
|
+
: {}),
|
|
70
73
|
...(typeof metadata.extensionId === 'string' && metadata.extensionId.length <= 128
|
|
71
74
|
? { extensionId: metadata.extensionId }
|
|
72
75
|
: {}),
|