@eum-agent/llm-protocol-openai 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1147 -157
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,5 +1,449 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import OpenAI, { APIConnectionError, APIError } from "openai";
|
|
3
|
+
//#region src/logo.ts
|
|
4
|
+
/** Official OpenAI mark reused from the supplier extension's vendored SVG. */
|
|
5
|
+
const protocolLogo = "data:image/svg+xml,%3Csvg%20fill%3D%22currentColor%22%20fill-rule%3D%22evenodd%22%20height%3D%2224%22%20style%3D%22flex%3Anone%3Bline-height%3A1%22%20viewBox%3D%220%200%2024%2024%22%20width%3D%2224%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Ctitle%3EOpenAI%3C%2Ftitle%3E%3Cpath%20d%3D%22M9.205%208.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357%201.356-.523%202.117-.523%202.854%200%204.662%202.212%204.662%204.566%200%20.167%200%20.357-.024.547l-4.71-2.759a.797.797%200%2000-.856%200l-5.97%203.473zm10.609%208.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473%201.95-1.118a.433.433%200%2001.476%200l4.543%202.617c1.309.76%202.189%202.378%202.189%203.948%200%201.808-1.07%203.473-2.76%204.163zM7.802%2012.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545%201.95-4.472%204.591-4.472%201%200%201.927.333%202.712.928L8.23%205.067c-.285.166-.428.404-.428.737v6.898zM12%2015.128l-2.795-1.57v-3.33L12%208.658l2.795%201.57v3.33L12%2015.128zm1.796%207.23c-1%200-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974%201.142c.167.095.238.238.238.428v5.233c0%202.545-1.974%204.472-4.614%204.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482%204.482%200%20014.21%206.327v5.423c0%20.333.143.571.428.738l5.947%203.449-1.95%201.118a.432.432%200%2001-.476%200zm-.262%203.9c-2.688%200-4.662-2.021-4.662-4.519%200-.19.024-.38.047-.57l4.686%202.71c.286.167.571.167.856%200l5.97-3.448v2.26c0%20.19-.07.333-.237.428l-4.543%202.616c-.619.357-1.356.523-2.117.523zm5.899%202.83a5.947%205.947%200%20005.827-4.756C22.287%2018.339%2024%2015.84%2024%2013.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498%200-3.401-2.759-5.947-5.946-5.947-.642%200-1.26.095-1.88.31A5.962%205.962%200%200010.205%200a5.947%205.947%200%2000-5.827%204.757C1.713%205.447%200%207.945%200%2010.49c0%201.666.713%203.283%201.998%204.448-.119.5-.19%201-.19%201.499%200%203.401%202.759%205.946%205.946%205.946.642%200%201.26-.095%201.88-.309a5.96%205.96%200%20004.162%201.713z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E";
|
|
6
|
+
//#endregion
|
|
7
|
+
//#region src/protocol/probe.ts
|
|
8
|
+
async function readBody(response, maxBytes) {
|
|
9
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new Error("invalid response budget");
|
|
10
|
+
const declared = response.headers.get("content-length");
|
|
11
|
+
if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
|
|
12
|
+
await response.body?.cancel();
|
|
13
|
+
throw new Error("read-limit: provider response exceeds its member budget");
|
|
14
|
+
}
|
|
15
|
+
if (!response.body) return {
|
|
16
|
+
text: "",
|
|
17
|
+
bytes: 0
|
|
18
|
+
};
|
|
19
|
+
const reader = response.body.getReader();
|
|
20
|
+
const decoder = new TextDecoder();
|
|
21
|
+
let bytes = 0, text = "";
|
|
22
|
+
try {
|
|
23
|
+
for (;;) {
|
|
24
|
+
const next = await reader.read();
|
|
25
|
+
if (next.done) break;
|
|
26
|
+
bytes += next.value.byteLength;
|
|
27
|
+
if (bytes > maxBytes) {
|
|
28
|
+
await reader.cancel();
|
|
29
|
+
throw new Error("read-limit: provider response exceeds its member budget");
|
|
30
|
+
}
|
|
31
|
+
text += decoder.decode(next.value, { stream: true });
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
text: text + decoder.decode(),
|
|
35
|
+
bytes
|
|
36
|
+
};
|
|
37
|
+
} finally {
|
|
38
|
+
reader.releaseLock();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function baseUrlOf(probe) {
|
|
42
|
+
const configured = probe.config.baseUrl;
|
|
43
|
+
return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
|
|
44
|
+
}
|
|
45
|
+
async function refuse(response, maxBytes = 8388608) {
|
|
46
|
+
const body = (await readBody(response, maxBytes)).text;
|
|
47
|
+
throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
|
|
48
|
+
}
|
|
49
|
+
function headers(probe) {
|
|
50
|
+
return {
|
|
51
|
+
...probe.options.allowUnauthenticated === true && !probe.secrets.apiKey ? {} : { authorization: `Bearer ${probe.secrets.apiKey ?? ""}` },
|
|
52
|
+
"content-type": "application/json"
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function record(value) {
|
|
56
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
57
|
+
}
|
|
58
|
+
function count(value) {
|
|
59
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
|
|
60
|
+
}
|
|
61
|
+
function strings(value, allowEmpty = false) {
|
|
62
|
+
return Array.isArray(value) && value.every((one) => typeof one === "string") && (allowEmpty || value.length > 0) ? value : void 0;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* One listed model as an offer. The family agrees on `id` alone, so every
|
|
66
|
+
* other field is read wherever an endpoint puts it: `context_window` or
|
|
67
|
+
* `context_length`, `max_output_tokens` or `max_output_length`,
|
|
68
|
+
* `input_modalities` or the `supports_*_in` flags, `output_modalities`,
|
|
69
|
+
* `supports_reasoning` or `reasoning` in `supported_features` (which also
|
|
70
|
+
* says `tools`), `temperature` in `supported_sampling_parameters`, and an
|
|
71
|
+
* `effort` object with its levels and default. A default the levels do not
|
|
72
|
+
* list is dropped. A valid feature or sampling list, including an empty one,
|
|
73
|
+
* answers for what it leaves out. Missing or malformed lists remain unknown.
|
|
74
|
+
*/
|
|
75
|
+
function offerOf(row, id) {
|
|
76
|
+
const contextWindow = count(row.context_window) ?? count(row.context_length);
|
|
77
|
+
const maxOutput = count(row.max_output_tokens) ?? count(row.max_output_length);
|
|
78
|
+
const features = strings(row.supported_features, true);
|
|
79
|
+
const sampling = strings(row.supported_sampling_parameters, true);
|
|
80
|
+
const reasoning = typeof row.supports_reasoning === "boolean" ? row.supports_reasoning : features?.includes("reasoning");
|
|
81
|
+
const effort = record(row.effort);
|
|
82
|
+
const efforts = strings(effort?.supported_levels);
|
|
83
|
+
const defaultEffort = typeof effort?.default_level === "string" && efforts?.includes(effort.default_level) ? effort.default_level : void 0;
|
|
84
|
+
const flagged = typeof row.supports_image_in === "boolean" || typeof row.supports_video_in === "boolean" ? [
|
|
85
|
+
"text",
|
|
86
|
+
...row.supports_image_in === true ? ["image"] : [],
|
|
87
|
+
...row.supports_video_in === true ? ["video"] : []
|
|
88
|
+
] : void 0;
|
|
89
|
+
const input = strings(row.input_modalities) ?? flagged;
|
|
90
|
+
const output = strings(row.output_modalities);
|
|
91
|
+
return {
|
|
92
|
+
model: id,
|
|
93
|
+
...typeof row.name === "string" && row.name !== "" ? { name: row.name } : {},
|
|
94
|
+
...contextWindow === void 0 ? {} : { contextWindow },
|
|
95
|
+
...maxOutput === void 0 ? {} : { maxOutput },
|
|
96
|
+
...reasoning === void 0 ? {} : { reasoning },
|
|
97
|
+
...features === void 0 ? {} : { toolCall: features.includes("tools") },
|
|
98
|
+
...sampling === void 0 ? {} : { temperature: sampling.includes("temperature") },
|
|
99
|
+
...input === void 0 ? {} : { input },
|
|
100
|
+
...output === void 0 ? {} : { output },
|
|
101
|
+
...efforts === void 0 ? {} : { efforts },
|
|
102
|
+
...defaultEffort === void 0 ? {} : { defaultEffort }
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const probeOpenAI = {
|
|
106
|
+
async listModels(probe, fetcher = globalThis.fetch) {
|
|
107
|
+
const response = await fetcher(`${baseUrlOf(probe)}/models`, {
|
|
108
|
+
method: "GET",
|
|
109
|
+
headers: headers(probe),
|
|
110
|
+
signal: probe.signal
|
|
111
|
+
});
|
|
112
|
+
if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
|
|
113
|
+
return (JSON.parse((await readBody(response, probe.maxResponseBytes ?? 8388608)).text).data ?? []).flatMap((row) => typeof row.id === "string" ? [offerOf(row, row.id)] : []);
|
|
114
|
+
},
|
|
115
|
+
async testConnection(probe, fetcher = globalThis.fetch, protocol = "chat-completions") {
|
|
116
|
+
if (probe.model !== void 0) {
|
|
117
|
+
const response = await fetcher(`${baseUrlOf(probe)}/${protocol === "responses" ? "responses" : "chat/completions"}`, {
|
|
118
|
+
method: "POST",
|
|
119
|
+
headers: headers(probe),
|
|
120
|
+
body: JSON.stringify(protocol === "responses" ? {
|
|
121
|
+
model: probe.model,
|
|
122
|
+
input: [{
|
|
123
|
+
role: "user",
|
|
124
|
+
content: "ping"
|
|
125
|
+
}],
|
|
126
|
+
max_output_tokens: 16,
|
|
127
|
+
store: false
|
|
128
|
+
} : {
|
|
129
|
+
model: probe.model,
|
|
130
|
+
max_tokens: 1,
|
|
131
|
+
messages: [{
|
|
132
|
+
role: "user",
|
|
133
|
+
content: "ping"
|
|
134
|
+
}]
|
|
135
|
+
}),
|
|
136
|
+
signal: probe.signal
|
|
137
|
+
});
|
|
138
|
+
if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
|
|
139
|
+
await readBody(response, probe.maxResponseBytes ?? 8388608);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
await probeOpenAI.listModels(probe, fetcher);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region src/support.ts
|
|
147
|
+
/** Normalizes official facts without requiring an installed Chat capability. */
|
|
148
|
+
function normalizeOffers(input) {
|
|
149
|
+
return Object.fromEntries(input.offers.map((offer) => [offer.model, {
|
|
150
|
+
id: offer.model,
|
|
151
|
+
...offer.name === void 0 ? {} : { name: offer.name },
|
|
152
|
+
...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
|
|
153
|
+
...offer.efforts?.length ? { reasoning_options: [{
|
|
154
|
+
type: "effort",
|
|
155
|
+
values: [...offer.efforts]
|
|
156
|
+
}] } : {},
|
|
157
|
+
...offer.temperature === void 0 ? {} : { temperature: offer.temperature },
|
|
158
|
+
...offer.toolCall === void 0 ? {} : { tool_call: offer.toolCall },
|
|
159
|
+
...offer.input === void 0 ? {} : { attachment: offer.input.some((one) => one !== "text") },
|
|
160
|
+
...offer.input === void 0 && offer.output === void 0 ? {} : { modalities: {
|
|
161
|
+
...offer.input === void 0 ? {} : { input: [...offer.input] },
|
|
162
|
+
...offer.output === void 0 ? {} : { output: [...offer.output] }
|
|
163
|
+
} },
|
|
164
|
+
...!offer.contextWindow && !offer.maxOutput ? {} : { limit: {
|
|
165
|
+
...offer.contextWindow && offer.contextWindow > 0 ? { context: offer.contextWindow } : {},
|
|
166
|
+
...offer.maxOutput && offer.maxOutput > 0 ? { output: offer.maxOutput } : {}
|
|
167
|
+
} },
|
|
168
|
+
...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
|
|
169
|
+
}]));
|
|
170
|
+
}
|
|
171
|
+
/** The owner-qualified accessor is read per operation; withdrawal never exposes an old service. */
|
|
172
|
+
function lazySupport(read) {
|
|
173
|
+
return new Proxy({}, { get(_target, key) {
|
|
174
|
+
if (key === "normalizeListing") return normalizeOffers;
|
|
175
|
+
const service = read();
|
|
176
|
+
if (!service) throw new Error("Chat model support is unavailable");
|
|
177
|
+
const value = Reflect.get(service, key);
|
|
178
|
+
return typeof value === "function" ? value.bind(service) : value;
|
|
179
|
+
} });
|
|
180
|
+
}
|
|
181
|
+
//#endregion
|
|
182
|
+
//#region src/images/port.ts
|
|
183
|
+
/** Strict settings accepted by the current GPT image API and compatible image endpoints. */
|
|
184
|
+
const imageParamsSchema = z.strictObject({
|
|
185
|
+
size: z.enum([
|
|
186
|
+
"auto",
|
|
187
|
+
"256x256",
|
|
188
|
+
"512x512",
|
|
189
|
+
"1024x1024",
|
|
190
|
+
"1536x1024",
|
|
191
|
+
"1024x1536",
|
|
192
|
+
"1792x1024",
|
|
193
|
+
"1024x1792"
|
|
194
|
+
]).optional(),
|
|
195
|
+
quality: z.enum([
|
|
196
|
+
"auto",
|
|
197
|
+
"low",
|
|
198
|
+
"medium",
|
|
199
|
+
"high",
|
|
200
|
+
"xhigh",
|
|
201
|
+
"max",
|
|
202
|
+
"standard",
|
|
203
|
+
"hd"
|
|
204
|
+
]).optional(),
|
|
205
|
+
background: z.enum([
|
|
206
|
+
"auto",
|
|
207
|
+
"transparent",
|
|
208
|
+
"opaque"
|
|
209
|
+
]).optional(),
|
|
210
|
+
outputFormat: z.enum([
|
|
211
|
+
"png",
|
|
212
|
+
"jpeg",
|
|
213
|
+
"webp"
|
|
214
|
+
]).optional(),
|
|
215
|
+
n: z.number().int().min(1).max(8).optional()
|
|
216
|
+
});
|
|
217
|
+
/** Narrows official GPT image settings while keeping explicit custom model profiles usable. */
|
|
218
|
+
function imageParamsFor(model) {
|
|
219
|
+
if (!isGptImage(model)) return imageParamsSchema;
|
|
220
|
+
return imageParamsSchema.extend({
|
|
221
|
+
size: z.enum([
|
|
222
|
+
"auto",
|
|
223
|
+
"1024x1024",
|
|
224
|
+
"1536x1024",
|
|
225
|
+
"1024x1536"
|
|
226
|
+
]).optional(),
|
|
227
|
+
quality: model.startsWith("gpt-image-2.5-") ? z.enum([
|
|
228
|
+
"auto",
|
|
229
|
+
"low",
|
|
230
|
+
"medium",
|
|
231
|
+
"high",
|
|
232
|
+
"xhigh",
|
|
233
|
+
"max"
|
|
234
|
+
]).optional() : z.enum([
|
|
235
|
+
"auto",
|
|
236
|
+
"low",
|
|
237
|
+
"medium",
|
|
238
|
+
"high"
|
|
239
|
+
]).optional()
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
function isGptImage(model) {
|
|
243
|
+
return model.startsWith("gpt-image") || model === "chatgpt-image-latest";
|
|
244
|
+
}
|
|
245
|
+
function fail(code, resultState, message) {
|
|
246
|
+
throw Object.assign(new Error(message), {
|
|
247
|
+
name: "GenerationFailure",
|
|
248
|
+
code,
|
|
249
|
+
resultState
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
/** Checks large inline payloads without a repeated regexp group that can exhaust the VM stack. */
|
|
253
|
+
function validBase64(value) {
|
|
254
|
+
if (value.length % 4 !== 0) return false;
|
|
255
|
+
const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
|
|
256
|
+
return !/[^A-Za-z0-9+/]/.test(value.slice(0, value.length - padding));
|
|
257
|
+
}
|
|
258
|
+
async function readResponse(response, signal) {
|
|
259
|
+
const limit = 402653184;
|
|
260
|
+
const length = response.headers.get("content-length");
|
|
261
|
+
if (length !== null && /^\d+$/.test(length) && Number(length) > limit) {
|
|
262
|
+
await response.body?.cancel().catch(() => {});
|
|
263
|
+
fail("too-large", "not-delivered", "The image response exceeds its byte budget");
|
|
264
|
+
}
|
|
265
|
+
if (!response.body) fail("invalid-output", "not-delivered", "The image response is empty");
|
|
266
|
+
const reader = response.body.getReader();
|
|
267
|
+
const chunks = [];
|
|
268
|
+
let bytes = 0;
|
|
269
|
+
try {
|
|
270
|
+
for (;;) {
|
|
271
|
+
signal.throwIfAborted();
|
|
272
|
+
const next = await reader.read();
|
|
273
|
+
if (next.done) break;
|
|
274
|
+
bytes += next.value.byteLength;
|
|
275
|
+
if (bytes > limit) {
|
|
276
|
+
await reader.cancel().catch(() => {});
|
|
277
|
+
fail("too-large", "not-delivered", "The image response exceeds its byte budget");
|
|
278
|
+
}
|
|
279
|
+
chunks.push(next.value);
|
|
280
|
+
}
|
|
281
|
+
} finally {
|
|
282
|
+
reader.releaseLock();
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
286
|
+
} catch {
|
|
287
|
+
fail("invalid-output", "not-delivered", "The image service returned invalid JSON");
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/** Creates an image port using the host's routed fetch; credentials remain local to the call. */
|
|
291
|
+
function createOpenAIImagePort(call, fetcher) {
|
|
292
|
+
return { async generate(request, signal) {
|
|
293
|
+
signal.throwIfAborted();
|
|
294
|
+
if (!call.secrets.apiKey) fail("credential-unavailable", "not-submitted", "An API key is required");
|
|
295
|
+
const params = imageParamsFor(call.model).safeParse(request.params);
|
|
296
|
+
if (!params.success) fail("invalid-params", "not-submitted", "Unsupported image parameters");
|
|
297
|
+
if (!["create", "edit"].includes(request.operation) || request.outputKind !== "image") fail("unsupported", "not-submitted", "Unsupported image operation");
|
|
298
|
+
if (request.operation === "create" && request.inputs.length) fail("invalid-input", "not-submitted", "Image creation does not accept references");
|
|
299
|
+
if (request.operation === "edit" && (request.inputs.length < 1 || request.inputs.length > 16)) fail("invalid-input", "not-submitted", "Image editing needs between one and sixteen references");
|
|
300
|
+
const { outputFormat, ...settings } = params.data;
|
|
301
|
+
const payload = {
|
|
302
|
+
model: call.model,
|
|
303
|
+
prompt: request.prompt,
|
|
304
|
+
...settings,
|
|
305
|
+
...outputFormat ? { output_format: outputFormat } : {},
|
|
306
|
+
...!isGptImage(call.model) ? { response_format: "b64_json" } : {}
|
|
307
|
+
};
|
|
308
|
+
let body = JSON.stringify(payload);
|
|
309
|
+
if (request.operation === "edit") {
|
|
310
|
+
const form = new FormData();
|
|
311
|
+
for (const [key, value] of Object.entries(payload)) form.set(key, String(value));
|
|
312
|
+
let total = 0;
|
|
313
|
+
for (const [index, input] of request.inputs.entries()) {
|
|
314
|
+
if (![
|
|
315
|
+
"image/png",
|
|
316
|
+
"image/jpeg",
|
|
317
|
+
"image/webp"
|
|
318
|
+
].includes(input.mediaType)) fail("invalid-input", "not-submitted", "Unsupported image reference media type");
|
|
319
|
+
const chunks = [];
|
|
320
|
+
let size = 0;
|
|
321
|
+
for await (const chunk of input.read(signal)) {
|
|
322
|
+
signal.throwIfAborted();
|
|
323
|
+
size += chunk.byteLength;
|
|
324
|
+
total += chunk.byteLength;
|
|
325
|
+
if (size > input.size || total > 52428800) fail("too-large", "not-submitted", "Image references exceed the request budget");
|
|
326
|
+
chunks.push(chunk);
|
|
327
|
+
}
|
|
328
|
+
if (size !== input.size) fail("invalid-input", "not-submitted", "The image reference changed size");
|
|
329
|
+
form.append("image[]", new Blob([Buffer.concat(chunks)], { type: input.mediaType }), `reference-${index}.` + input.mediaType.slice(6));
|
|
330
|
+
}
|
|
331
|
+
body = form;
|
|
332
|
+
}
|
|
333
|
+
const url = new URL(`${String(call.config.baseUrl ?? "").replace(/\/+$/, "")}/images/${request.operation === "edit" ? "edits" : "generations"}`);
|
|
334
|
+
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) fail("invalid-params", "not-submitted", "Invalid image API address");
|
|
335
|
+
let response;
|
|
336
|
+
try {
|
|
337
|
+
response = await fetcher(url.href, {
|
|
338
|
+
method: "POST",
|
|
339
|
+
redirect: "error",
|
|
340
|
+
signal,
|
|
341
|
+
headers: {
|
|
342
|
+
authorization: `Bearer ${call.secrets.apiKey}`,
|
|
343
|
+
...typeof body === "string" ? { "content-type": "application/json" } : {}
|
|
344
|
+
},
|
|
345
|
+
body
|
|
346
|
+
});
|
|
347
|
+
} catch {
|
|
348
|
+
fail(signal.aborted ? "cancelled" : "network", "unknown", "The image submission result is unknown");
|
|
349
|
+
}
|
|
350
|
+
if (!response.ok) {
|
|
351
|
+
await response.body?.cancel().catch(() => {});
|
|
352
|
+
fail(response.status === 401 ? "credential-unavailable" : response.status === 403 ? "forbidden" : response.status === 429 ? "quota" : "provider", "not-delivered", `Image generation failed with HTTP ${response.status}`);
|
|
353
|
+
}
|
|
354
|
+
try {
|
|
355
|
+
const raw = await readResponse(response, signal);
|
|
356
|
+
const envelope = z.record(z.string(), z.unknown()).safeParse(raw);
|
|
357
|
+
if (!envelope.success) fail("invalid-output", "not-delivered", "The image response is not a JSON object");
|
|
358
|
+
if (envelope.data.error !== void 0 && envelope.data.error !== null) fail("provider", "not-delivered", "The image service returned an error in a successful HTTP response");
|
|
359
|
+
if (!Array.isArray(envelope.data.data)) fail("invalid-output", "not-delivered", "The image response is missing its image data array");
|
|
360
|
+
if (!envelope.data.data.length) fail("invalid-output", "not-delivered", "The image response contains no images");
|
|
361
|
+
const result = z.array(z.object({
|
|
362
|
+
b64_json: z.string().optional(),
|
|
363
|
+
url: z.string().optional()
|
|
364
|
+
})).max(8).safeParse(envelope.data.data);
|
|
365
|
+
if (!result.success) fail("invalid-output", "not-delivered", "The image response contains unsupported image entries");
|
|
366
|
+
let outputBytes = 0;
|
|
367
|
+
return { assets: result.data.map((item) => {
|
|
368
|
+
if (item.b64_json === void 0) {
|
|
369
|
+
if (item.url) fail("invalid-output", "not-delivered", "The image service returned a URL instead of the requested inline image bytes; URL delivery is not configured for this connection");
|
|
370
|
+
fail("invalid-output", "not-delivered", "The image response is missing its inline image bytes");
|
|
371
|
+
}
|
|
372
|
+
if (!item.b64_json.length) fail("invalid-output", "not-delivered", "The image response contains empty inline image bytes");
|
|
373
|
+
if (!validBase64(item.b64_json)) fail("invalid-output", "not-delivered", "Invalid image encoding");
|
|
374
|
+
const bytes = Buffer.from(item.b64_json, "base64");
|
|
375
|
+
outputBytes += bytes.byteLength;
|
|
376
|
+
if (outputBytes > 268435456) fail("too-large", "not-delivered", "Image outputs exceed their byte budget");
|
|
377
|
+
if (!bytes.length) fail("invalid-output", "not-delivered", "The image is empty");
|
|
378
|
+
return {
|
|
379
|
+
mediaType: outputFormat === "jpeg" ? "image/jpeg" : outputFormat === "webp" ? "image/webp" : "image/png",
|
|
380
|
+
body: (async function* () {
|
|
381
|
+
yield bytes;
|
|
382
|
+
})()
|
|
383
|
+
};
|
|
384
|
+
}) };
|
|
385
|
+
} catch (error) {
|
|
386
|
+
if (error?.name === "GenerationFailure") throw error;
|
|
387
|
+
fail(signal.aborted ? "cancelled" : "invalid-output", "not-delivered", "The image response could not be read completely");
|
|
388
|
+
}
|
|
389
|
+
} };
|
|
390
|
+
}
|
|
391
|
+
//#endregion
|
|
392
|
+
//#region src/images/protocol.ts
|
|
393
|
+
/** Registers explicit image execution profiles for saved generation and editing bindings. */
|
|
394
|
+
function imagesProtocolType(support, fetcher) {
|
|
395
|
+
return {
|
|
396
|
+
type: "openai-images",
|
|
397
|
+
label: "OpenAI Images API",
|
|
398
|
+
logo: protocolLogo,
|
|
399
|
+
fields: [{
|
|
400
|
+
key: "baseUrl",
|
|
401
|
+
kind: "url",
|
|
402
|
+
label: "Base URL",
|
|
403
|
+
required: true
|
|
404
|
+
}],
|
|
405
|
+
userConfigurable: true,
|
|
406
|
+
optionsSchema: z.strictObject({}),
|
|
407
|
+
adapters: { image: {
|
|
408
|
+
models: (input) => input.configuredModels.filter((row) => row.execution?.protocolId === "openai-images" && row.execution.profile === "openai-image-v1").map((row) => ({
|
|
409
|
+
id: row.id,
|
|
410
|
+
label: row.id,
|
|
411
|
+
outputKinds: ["image"],
|
|
412
|
+
operations: [{
|
|
413
|
+
id: "create",
|
|
414
|
+
inputKinds: [],
|
|
415
|
+
minInputs: 0,
|
|
416
|
+
maxInputs: 0,
|
|
417
|
+
paramsSchema: imageParamsFor(row.id)
|
|
418
|
+
}, {
|
|
419
|
+
id: "edit",
|
|
420
|
+
inputKinds: ["image"],
|
|
421
|
+
minInputs: 1,
|
|
422
|
+
maxInputs: 16,
|
|
423
|
+
paramsSchema: imageParamsFor(row.id)
|
|
424
|
+
}]
|
|
425
|
+
})),
|
|
426
|
+
createPort: (call) => createOpenAIImagePort(call, fetcher)
|
|
427
|
+
} },
|
|
428
|
+
executionCandidates: () => [{
|
|
429
|
+
profile: "openai-image-v1",
|
|
430
|
+
label: "OpenAI Images generation and editing",
|
|
431
|
+
chat: false,
|
|
432
|
+
generation: ["image"]
|
|
433
|
+
}],
|
|
434
|
+
validateExecution(input) {
|
|
435
|
+
if (input.requested.protocolId !== "openai-images" || input.requested.profile !== "openai-image-v1" || input.requested.sourceIdentity !== void 0) throw new Error("Unsupported image execution profile");
|
|
436
|
+
return {
|
|
437
|
+
protocolId: "openai-images",
|
|
438
|
+
profile: "openai-image-v1"
|
|
439
|
+
};
|
|
440
|
+
},
|
|
441
|
+
normalizeListing: (input) => normalizeOffers(input),
|
|
442
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, fetcher) }),
|
|
443
|
+
testConnection: (probe) => probeOpenAI.listModels(probe, fetcher).then(() => {})
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
//#endregion
|
|
3
447
|
//#region src/protocol/facts.ts
|
|
4
448
|
/** Parameter ranges and request limits for this provider wire. */
|
|
5
449
|
const facts = {
|
|
@@ -135,7 +579,7 @@ function userContent(message, index, plan) {
|
|
|
135
579
|
* results handed back follow it in one user message, each after the id of
|
|
136
580
|
* the call it came from; an image standing in as a line of text stays in
|
|
137
581
|
* its call's own tool message. */
|
|
138
|
-
function toChatMessages(message, index, plan,
|
|
582
|
+
function toChatMessages(message, index, plan, options) {
|
|
139
583
|
const toolResults = message.content.map((part, partIndex) => ({
|
|
140
584
|
part,
|
|
141
585
|
partIndex
|
|
@@ -176,7 +620,7 @@ function toChatMessages(message, index, plan, reasoningReplay) {
|
|
|
176
620
|
return [{
|
|
177
621
|
role: "assistant",
|
|
178
622
|
content,
|
|
179
|
-
...reasoningReplay === "reasoning-content" && message.outputTruncation?.incompleteThinking !== true ? { reasoning_content: message.content.filter((part) => part.type === "thinking").map((part) => part.text).join("") } : {},
|
|
623
|
+
...options.reasoningReplay === "reasoning-content" && message.content.filter((part) => part.type === "thinking").every((part) => part.signature === void 0 && part.issuer !== void 0 && part.issuer === options.endpoint && part.originModel === options.model) && message.outputTruncation?.incompleteThinking !== true ? { reasoning_content: message.content.filter((part) => part.type === "thinking").map((part) => part.text).join("") } : {},
|
|
180
624
|
...toolCalls === void 0 ? {} : { tool_calls: toolCalls }
|
|
181
625
|
}];
|
|
182
626
|
}
|
|
@@ -211,8 +655,8 @@ function volatileMessages(volatile) {
|
|
|
211
655
|
}
|
|
212
656
|
/** A reply's recorded notes go just before it — where the request that
|
|
213
657
|
* produced it carried them — so every request extends the previous one. */
|
|
214
|
-
function withNotes(message, index, plan,
|
|
215
|
-
return [...message.role === "assistant" ? volatileMessages(message.volatile) : [], ...toChatMessages(message, index, plan,
|
|
658
|
+
function withNotes(message, index, plan, options) {
|
|
659
|
+
return [...message.role === "assistant" ? volatileMessages(message.volatile) : [], ...toChatMessages(message, index, plan, options)];
|
|
216
660
|
}
|
|
217
661
|
function toToolParam(tool) {
|
|
218
662
|
return {
|
|
@@ -244,7 +688,7 @@ function toOpenAIRequest(request, options) {
|
|
|
244
688
|
stream_options: { include_usage: true },
|
|
245
689
|
messages: [
|
|
246
690
|
...systemMessage,
|
|
247
|
-
...request.messages.flatMap((message, index) => withNotes(message, index, plan, options
|
|
691
|
+
...request.messages.flatMap((message, index) => withNotes(message, index, plan, options)),
|
|
248
692
|
...volatileMessages(request.volatile)
|
|
249
693
|
],
|
|
250
694
|
...tools.length === 0 ? {} : { tools },
|
|
@@ -295,7 +739,7 @@ function parseToolInput(argumentsJson) {
|
|
|
295
739
|
* unknown reasons and replies without text or usable tool calls fail without retry.
|
|
296
740
|
* A stream with neither usage nor a terminal reason retains interruption semantics.
|
|
297
741
|
*/
|
|
298
|
-
async function* mapOpenAIStream(chunks, support) {
|
|
742
|
+
async function* mapOpenAIStream(chunks, support, originModel) {
|
|
299
743
|
const textParts = [];
|
|
300
744
|
const thinkingParts = [];
|
|
301
745
|
const toolCalls = /* @__PURE__ */ new Map();
|
|
@@ -397,7 +841,8 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
397
841
|
const thinkingText = thinkingParts.join("");
|
|
398
842
|
if (thinkingText.length > 0) content.push({
|
|
399
843
|
type: "thinking",
|
|
400
|
-
text: thinkingText
|
|
844
|
+
text: thinkingText,
|
|
845
|
+
...originModel === void 0 ? {} : { originModel }
|
|
401
846
|
});
|
|
402
847
|
const text = refusalText ?? textParts.join("");
|
|
403
848
|
if (text.length > 0) content.push({
|
|
@@ -475,7 +920,8 @@ function openaiOptions(plan) {
|
|
|
475
920
|
function createOpenAIModelPort(options) {
|
|
476
921
|
function clientForAttempt(reportProgress) {
|
|
477
922
|
return options.client ?? new OpenAI({
|
|
478
|
-
apiKey: options.apiKey ?? "",
|
|
923
|
+
apiKey: options.allowUnauthenticated && !options.apiKey ? "not-used" : options.apiKey ?? "",
|
|
924
|
+
...options.allowUnauthenticated && !options.apiKey ? { defaultHeaders: { Authorization: null } } : {},
|
|
479
925
|
fetch: async (...args) => options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress),
|
|
480
926
|
baseURL: options.baseURL ?? "",
|
|
481
927
|
maxRetries: 0
|
|
@@ -592,7 +1038,7 @@ function createOpenAIModelPort(options) {
|
|
|
592
1038
|
yield chunk;
|
|
593
1039
|
}
|
|
594
1040
|
})();
|
|
595
|
-
for await (const chunk of mapOpenAIStream(observed, options.support)) {
|
|
1041
|
+
for await (const chunk of mapOpenAIStream(observed, options.support, options.model)) {
|
|
596
1042
|
if (chunk.kind === "final") outcome = "ok";
|
|
597
1043
|
yield chunk;
|
|
598
1044
|
}
|
|
@@ -627,149 +1073,21 @@ function createOpenAIModelPort(options) {
|
|
|
627
1073
|
};
|
|
628
1074
|
}
|
|
629
1075
|
//#endregion
|
|
630
|
-
//#region src/protocol
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
};
|
|
642
|
-
const reader = response.body.getReader();
|
|
643
|
-
const decoder = new TextDecoder();
|
|
644
|
-
let bytes = 0, text = "";
|
|
645
|
-
try {
|
|
646
|
-
for (;;) {
|
|
647
|
-
const next = await reader.read();
|
|
648
|
-
if (next.done) break;
|
|
649
|
-
bytes += next.value.byteLength;
|
|
650
|
-
if (bytes > maxBytes) {
|
|
651
|
-
await reader.cancel();
|
|
652
|
-
throw new Error("read-limit: provider response exceeds its member budget");
|
|
653
|
-
}
|
|
654
|
-
text += decoder.decode(next.value, { stream: true });
|
|
655
|
-
}
|
|
656
|
-
return {
|
|
657
|
-
text: text + decoder.decode(),
|
|
658
|
-
bytes
|
|
659
|
-
};
|
|
660
|
-
} finally {
|
|
661
|
-
reader.releaseLock();
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
function baseUrlOf(probe) {
|
|
665
|
-
const configured = probe.config.baseUrl;
|
|
666
|
-
return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
|
|
667
|
-
}
|
|
668
|
-
async function refuse(response, maxBytes = 8388608) {
|
|
669
|
-
const body = (await readBody(response, maxBytes)).text;
|
|
670
|
-
throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
|
|
671
|
-
}
|
|
672
|
-
function headers(probe) {
|
|
673
|
-
return {
|
|
674
|
-
authorization: `Bearer ${probe.secrets.apiKey ?? ""}`,
|
|
675
|
-
"content-type": "application/json"
|
|
676
|
-
};
|
|
677
|
-
}
|
|
678
|
-
function record(value) {
|
|
679
|
-
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
680
|
-
}
|
|
681
|
-
function count(value) {
|
|
682
|
-
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
|
|
683
|
-
}
|
|
684
|
-
function strings(value, allowEmpty = false) {
|
|
685
|
-
return Array.isArray(value) && value.every((one) => typeof one === "string") && (allowEmpty || value.length > 0) ? value : void 0;
|
|
686
|
-
}
|
|
687
|
-
/**
|
|
688
|
-
* One listed model as an offer. The family agrees on `id` alone, so every
|
|
689
|
-
* other field is read wherever an endpoint puts it: `context_window` or
|
|
690
|
-
* `context_length`, `max_output_tokens` or `max_output_length`,
|
|
691
|
-
* `input_modalities` or the `supports_*_in` flags, `output_modalities`,
|
|
692
|
-
* `supports_reasoning` or `reasoning` in `supported_features` (which also
|
|
693
|
-
* says `tools`), `temperature` in `supported_sampling_parameters`, and an
|
|
694
|
-
* `effort` object with its levels and default. A default the levels do not
|
|
695
|
-
* list is dropped. A valid feature or sampling list, including an empty one,
|
|
696
|
-
* answers for what it leaves out. Missing or malformed lists remain unknown.
|
|
697
|
-
*/
|
|
698
|
-
function offerOf(row, id) {
|
|
699
|
-
const contextWindow = count(row.context_window) ?? count(row.context_length);
|
|
700
|
-
const maxOutput = count(row.max_output_tokens) ?? count(row.max_output_length);
|
|
701
|
-
const features = strings(row.supported_features, true);
|
|
702
|
-
const sampling = strings(row.supported_sampling_parameters, true);
|
|
703
|
-
const reasoning = typeof row.supports_reasoning === "boolean" ? row.supports_reasoning : features?.includes("reasoning");
|
|
704
|
-
const effort = record(row.effort);
|
|
705
|
-
const efforts = strings(effort?.supported_levels);
|
|
706
|
-
const defaultEffort = typeof effort?.default_level === "string" && efforts?.includes(effort.default_level) ? effort.default_level : void 0;
|
|
707
|
-
const flagged = typeof row.supports_image_in === "boolean" || typeof row.supports_video_in === "boolean" ? [
|
|
708
|
-
"text",
|
|
709
|
-
...row.supports_image_in === true ? ["image"] : [],
|
|
710
|
-
...row.supports_video_in === true ? ["video"] : []
|
|
711
|
-
] : void 0;
|
|
712
|
-
const input = strings(row.input_modalities) ?? flagged;
|
|
713
|
-
const output = strings(row.output_modalities);
|
|
714
|
-
return {
|
|
715
|
-
model: id,
|
|
716
|
-
...typeof row.name === "string" && row.name !== "" ? { name: row.name } : {},
|
|
717
|
-
...contextWindow === void 0 ? {} : { contextWindow },
|
|
718
|
-
...maxOutput === void 0 ? {} : { maxOutput },
|
|
719
|
-
...reasoning === void 0 ? {} : { reasoning },
|
|
720
|
-
...features === void 0 ? {} : { toolCall: features.includes("tools") },
|
|
721
|
-
...sampling === void 0 ? {} : { temperature: sampling.includes("temperature") },
|
|
722
|
-
...input === void 0 ? {} : { input },
|
|
723
|
-
...output === void 0 ? {} : { output },
|
|
724
|
-
...efforts === void 0 ? {} : { efforts },
|
|
725
|
-
...defaultEffort === void 0 ? {} : { defaultEffort }
|
|
726
|
-
};
|
|
727
|
-
}
|
|
728
|
-
const probeOpenAI = {
|
|
729
|
-
async listModels(probe, fetcher = globalThis.fetch) {
|
|
730
|
-
const response = await fetcher(`${baseUrlOf(probe)}/models`, {
|
|
731
|
-
method: "GET",
|
|
732
|
-
headers: headers(probe),
|
|
733
|
-
signal: probe.signal
|
|
734
|
-
});
|
|
735
|
-
if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
|
|
736
|
-
return (JSON.parse((await readBody(response, probe.maxResponseBytes ?? 8388608)).text).data ?? []).flatMap((row) => typeof row.id === "string" ? [offerOf(row, row.id)] : []);
|
|
737
|
-
},
|
|
738
|
-
async testConnection(probe, fetcher = globalThis.fetch) {
|
|
739
|
-
if (probe.model !== void 0) {
|
|
740
|
-
const response = await fetcher(`${baseUrlOf(probe)}/chat/completions`, {
|
|
741
|
-
method: "POST",
|
|
742
|
-
headers: headers(probe),
|
|
743
|
-
body: JSON.stringify({
|
|
744
|
-
model: probe.model,
|
|
745
|
-
max_tokens: 1,
|
|
746
|
-
messages: [{
|
|
747
|
-
role: "user",
|
|
748
|
-
content: "ping"
|
|
749
|
-
}]
|
|
750
|
-
}),
|
|
751
|
-
signal: probe.signal
|
|
752
|
-
});
|
|
753
|
-
if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
|
|
754
|
-
return;
|
|
755
|
-
}
|
|
756
|
-
await probeOpenAI.listModels(probe, fetcher);
|
|
757
|
-
}
|
|
758
|
-
};
|
|
759
|
-
//#endregion
|
|
760
|
-
//#region src/protocol.ts
|
|
761
|
-
/** Validated supplier options; no supplier identity is interpreted by this protocol. */
|
|
762
|
-
const OpenAIProtocolOptions = z.strictObject({
|
|
763
|
-
reasoningReplay: z.enum(["omit", "reasoning-content"]).optional(),
|
|
764
|
-
thinkingField: z.boolean().optional(),
|
|
765
|
-
outputLimitField: z.enum(["max_tokens", "max_completion_tokens"]).optional(),
|
|
766
|
-
promptCacheKey: z.boolean().optional()
|
|
767
|
-
});
|
|
768
|
-
/** Registers concrete Chat Completions request mapping, streaming and probes. */
|
|
769
|
-
function openaiProtocolType(support, fetch) {
|
|
1076
|
+
//#region src/protocol.ts
|
|
1077
|
+
/** Validated supplier options; no supplier identity is interpreted by this protocol. */
|
|
1078
|
+
const OpenAIProtocolOptions = z.strictObject({
|
|
1079
|
+
allowUnauthenticated: z.boolean().optional(),
|
|
1080
|
+
reasoningReplay: z.enum(["omit", "reasoning-content"]).optional(),
|
|
1081
|
+
thinkingField: z.boolean().optional(),
|
|
1082
|
+
outputLimitField: z.enum(["max_tokens", "max_completion_tokens"]).optional(),
|
|
1083
|
+
promptCacheKey: z.boolean().optional()
|
|
1084
|
+
});
|
|
1085
|
+
/** Registers concrete Chat Completions request mapping, streaming and probes. */
|
|
1086
|
+
function openaiProtocolType(support, fetch) {
|
|
770
1087
|
return {
|
|
771
1088
|
type: "openai",
|
|
772
|
-
label: "OpenAI Chat Completions",
|
|
1089
|
+
label: "OpenAI Chat Completions API",
|
|
1090
|
+
logo: protocolLogo,
|
|
773
1091
|
fields: [{
|
|
774
1092
|
key: "baseUrl",
|
|
775
1093
|
kind: "url",
|
|
@@ -780,7 +1098,7 @@ function openaiProtocolType(support, fetch) {
|
|
|
780
1098
|
optionsSchema: OpenAIProtocolOptions,
|
|
781
1099
|
facts,
|
|
782
1100
|
prepareParams: (input) => support.prepareParams(input, facts),
|
|
783
|
-
chat: {
|
|
1101
|
+
adapters: { chat: {
|
|
784
1102
|
fileKinds: ["image"],
|
|
785
1103
|
supportsModel: () => true,
|
|
786
1104
|
createPort(call) {
|
|
@@ -810,23 +1128,695 @@ function openaiProtocolType(support, fetch) {
|
|
|
810
1128
|
})
|
|
811
1129
|
});
|
|
812
1130
|
}
|
|
813
|
-
},
|
|
814
|
-
normalizeListing: (input) =>
|
|
815
|
-
listModels: (probe) => probeOpenAI.listModels(probe, fetch),
|
|
1131
|
+
} },
|
|
1132
|
+
normalizeListing: (input) => normalizeOffers(input),
|
|
1133
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, fetch) }),
|
|
816
1134
|
testConnection: (probe) => probeOpenAI.testConnection(probe, fetch)
|
|
817
1135
|
};
|
|
818
1136
|
}
|
|
819
1137
|
//#endregion
|
|
1138
|
+
//#region src/responses/request.ts
|
|
1139
|
+
function replayable(message, options) {
|
|
1140
|
+
if (options.reasoningReplay === "omit" || message.outputTruncation?.incompleteThinking || !message.content.some((part) => part.type === "text" && part.text !== "" || part.type === "tool-use")) return false;
|
|
1141
|
+
return message.content.filter((part) => part.type === "thinking").every((part) => (options.reasoningReplay === "reasoning-content" || part.signature !== void 0) && part.issuer === options.endpoint && part.originModel === options.model);
|
|
1142
|
+
}
|
|
1143
|
+
/** Counts retained reasoning usage only for assistant state that is actually replayed. */
|
|
1144
|
+
function responsesHiddenInputTokens(request, options) {
|
|
1145
|
+
return request.messages.reduce((total, message) => {
|
|
1146
|
+
if (options.reasoningReplay === "reasoning-content" || message.role !== "assistant" || !replayable(message, options)) return total;
|
|
1147
|
+
return total + Math.max(0, ...message.content.map((part) => part.type === "thinking" ? part.outputTokens ?? 0 : 0));
|
|
1148
|
+
}, 0);
|
|
1149
|
+
}
|
|
1150
|
+
/** A planned file as content parts: the label and the image, or the line in its place. */
|
|
1151
|
+
function fileParts(planned) {
|
|
1152
|
+
const label = {
|
|
1153
|
+
type: "input_text",
|
|
1154
|
+
text: planned.label
|
|
1155
|
+
};
|
|
1156
|
+
if (planned.fate !== "send") return [label];
|
|
1157
|
+
return [label, {
|
|
1158
|
+
type: "input_image",
|
|
1159
|
+
image_url: `data:${planned.mediaType};base64,${planned.data ?? ""}`
|
|
1160
|
+
}];
|
|
1161
|
+
}
|
|
1162
|
+
/** A result without files keeps its plain string; one with files is an array. */
|
|
1163
|
+
function outputOf(part, plan, at) {
|
|
1164
|
+
const files = part.files ?? [];
|
|
1165
|
+
if (files.length === 0) return part.content;
|
|
1166
|
+
return [...part.content === "" ? [] : [{
|
|
1167
|
+
type: "input_text",
|
|
1168
|
+
text: part.content
|
|
1169
|
+
}], ...files.flatMap((_, index) => fileParts(plan.at(at.message, at.part, index)))];
|
|
1170
|
+
}
|
|
1171
|
+
function userItems(message, index, plan) {
|
|
1172
|
+
const items = [];
|
|
1173
|
+
let text = "";
|
|
1174
|
+
let content = [];
|
|
1175
|
+
const flushText = () => {
|
|
1176
|
+
if (text.length > 0) content.push({
|
|
1177
|
+
type: "input_text",
|
|
1178
|
+
text
|
|
1179
|
+
});
|
|
1180
|
+
text = "";
|
|
1181
|
+
};
|
|
1182
|
+
const flush = () => {
|
|
1183
|
+
flushText();
|
|
1184
|
+
if (content.length > 0) items.push({
|
|
1185
|
+
type: "message",
|
|
1186
|
+
role: "user",
|
|
1187
|
+
content
|
|
1188
|
+
});
|
|
1189
|
+
content = [];
|
|
1190
|
+
};
|
|
1191
|
+
message.content.forEach((part, partIndex) => {
|
|
1192
|
+
if (part.type === "text") text += part.text;
|
|
1193
|
+
else if (part.type === "file") {
|
|
1194
|
+
flushText();
|
|
1195
|
+
content.push(...fileParts(plan.at(index, partIndex)));
|
|
1196
|
+
} else if (part.type === "tool-result") {
|
|
1197
|
+
flush();
|
|
1198
|
+
items.push({
|
|
1199
|
+
type: "function_call_output",
|
|
1200
|
+
call_id: part.toolUseId,
|
|
1201
|
+
output: outputOf(part, plan, {
|
|
1202
|
+
message: index,
|
|
1203
|
+
part: partIndex
|
|
1204
|
+
})
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
});
|
|
1208
|
+
flush();
|
|
1209
|
+
return items;
|
|
1210
|
+
}
|
|
1211
|
+
function assistantItems(message, options) {
|
|
1212
|
+
const sendThinking = replayable(message, options);
|
|
1213
|
+
const items = [];
|
|
1214
|
+
for (const part of message.content) if (part.type === "thinking") {
|
|
1215
|
+
if (!sendThinking) continue;
|
|
1216
|
+
if (options.reasoningReplay === "reasoning-content") {
|
|
1217
|
+
items.push({
|
|
1218
|
+
type: "reasoning",
|
|
1219
|
+
content: [{
|
|
1220
|
+
type: "reasoning_text",
|
|
1221
|
+
text: part.text
|
|
1222
|
+
}]
|
|
1223
|
+
});
|
|
1224
|
+
continue;
|
|
1225
|
+
}
|
|
1226
|
+
items.push({
|
|
1227
|
+
type: "reasoning",
|
|
1228
|
+
summary: part.text === "" ? [] : [{
|
|
1229
|
+
type: "summary_text",
|
|
1230
|
+
text: part.text
|
|
1231
|
+
}],
|
|
1232
|
+
encrypted_content: part.signature
|
|
1233
|
+
});
|
|
1234
|
+
} else if (part.type === "text") {
|
|
1235
|
+
if (part.text === "") continue;
|
|
1236
|
+
items.push({
|
|
1237
|
+
type: "message",
|
|
1238
|
+
role: "assistant",
|
|
1239
|
+
content: [{
|
|
1240
|
+
type: "output_text",
|
|
1241
|
+
text: part.text
|
|
1242
|
+
}]
|
|
1243
|
+
});
|
|
1244
|
+
} else if (part.type === "tool-use") items.push({
|
|
1245
|
+
type: "function_call",
|
|
1246
|
+
call_id: part.id,
|
|
1247
|
+
name: part.name,
|
|
1248
|
+
arguments: JSON.stringify(part.input ?? {})
|
|
1249
|
+
});
|
|
1250
|
+
return items;
|
|
1251
|
+
}
|
|
1252
|
+
/** The one user item a set of notes renders as, or nothing. */
|
|
1253
|
+
function noteItems(notes) {
|
|
1254
|
+
const text = (notes ?? []).map((note) => note.text).join("\n\n");
|
|
1255
|
+
return text === "" ? [] : [{
|
|
1256
|
+
type: "message",
|
|
1257
|
+
role: "user",
|
|
1258
|
+
content: [{
|
|
1259
|
+
type: "input_text",
|
|
1260
|
+
text
|
|
1261
|
+
}]
|
|
1262
|
+
}];
|
|
1263
|
+
}
|
|
1264
|
+
function toolOf(tool) {
|
|
1265
|
+
return {
|
|
1266
|
+
type: "function",
|
|
1267
|
+
name: tool.name,
|
|
1268
|
+
description: tool.description,
|
|
1269
|
+
parameters: tool.inputSchema,
|
|
1270
|
+
strict: false
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
/** Renders stateless history using only the endpoint-declared reasoning representation. */
|
|
1274
|
+
function toResponsesBody(request, options, plan) {
|
|
1275
|
+
const input = [];
|
|
1276
|
+
const updates = new Map(options.effortUpdates?.map((update) => [update.beforeUserMessageId, update.effort]));
|
|
1277
|
+
request.messages.forEach((message, index) => {
|
|
1278
|
+
const effort = updates.get(message.id);
|
|
1279
|
+
if (effort !== void 0) input.push({
|
|
1280
|
+
type: "configuration_update",
|
|
1281
|
+
reasoning: { effort }
|
|
1282
|
+
});
|
|
1283
|
+
if (message.role === "user") input.push(...userItems(message, index, plan));
|
|
1284
|
+
else input.push(...noteItems(message.volatile), ...assistantItems(message, options));
|
|
1285
|
+
});
|
|
1286
|
+
input.push(...noteItems(request.volatile));
|
|
1287
|
+
const instructions = (request.system ?? []).join("\n\n");
|
|
1288
|
+
const tools = (request.tools ?? []).map(toolOf);
|
|
1289
|
+
return {
|
|
1290
|
+
model: options.model,
|
|
1291
|
+
...instructions === "" ? {} : { instructions },
|
|
1292
|
+
input,
|
|
1293
|
+
...tools.length === 0 ? {} : {
|
|
1294
|
+
tools,
|
|
1295
|
+
tool_choice: request.toolChoice === "none" ? "none" : "auto"
|
|
1296
|
+
},
|
|
1297
|
+
...options.effort === void 0 && options.reasoningSummary === false ? {} : { reasoning: {
|
|
1298
|
+
...options.effort === void 0 ? {} : { effort: options.effort },
|
|
1299
|
+
...options.reasoningSummary === false ? {} : { summary: "auto" }
|
|
1300
|
+
} },
|
|
1301
|
+
...options.encryptedReasoningInclude !== false && (options.reasoningReplay === void 0 || options.reasoningReplay === "encrypted") ? { include: ["reasoning.encrypted_content"] } : {},
|
|
1302
|
+
store: false,
|
|
1303
|
+
stream: true
|
|
1304
|
+
};
|
|
1305
|
+
}
|
|
1306
|
+
//#endregion
|
|
1307
|
+
//#region src/responses/codec.ts
|
|
1308
|
+
/** Shared Responses rendering for registered transports. */
|
|
1309
|
+
const responsesCodec = {
|
|
1310
|
+
render: toResponsesBody,
|
|
1311
|
+
hiddenInputTokens: responsesHiddenInputTokens
|
|
1312
|
+
};
|
|
1313
|
+
//#endregion
|
|
1314
|
+
//#region src/responses/options.ts
|
|
1315
|
+
/** Explicit wire capabilities; no supplier identity or URL is interpreted. */
|
|
1316
|
+
const ResponsesProtocolOptions = z.strictObject({
|
|
1317
|
+
allowUnauthenticated: z.boolean().optional(),
|
|
1318
|
+
reasoningReplay: z.enum([
|
|
1319
|
+
"encrypted",
|
|
1320
|
+
"reasoning-content",
|
|
1321
|
+
"omit"
|
|
1322
|
+
]).optional(),
|
|
1323
|
+
reasoningSummary: z.boolean().optional(),
|
|
1324
|
+
/** Wire effort enabling an active thinking toggle when no effort was selected. */
|
|
1325
|
+
thinkingOnEffort: z.enum([
|
|
1326
|
+
"minimal",
|
|
1327
|
+
"low",
|
|
1328
|
+
"medium",
|
|
1329
|
+
"high",
|
|
1330
|
+
"xhigh",
|
|
1331
|
+
"max"
|
|
1332
|
+
]).optional(),
|
|
1333
|
+
encryptedReasoningInclude: z.boolean().optional(),
|
|
1334
|
+
effortCache: z.boolean().optional(),
|
|
1335
|
+
promptCacheKey: z.boolean().optional(),
|
|
1336
|
+
/** False removes callable tools when the caller explicitly prohibits tool use. */
|
|
1337
|
+
toolChoiceNone: z.boolean().optional()
|
|
1338
|
+
});
|
|
1339
|
+
//#endregion
|
|
1340
|
+
//#region src/responses/stream.ts
|
|
1341
|
+
/** Locally recognized stream failures, mapped to host diagnostics by the port. */
|
|
1342
|
+
var ResponsesStreamError = class extends Error {
|
|
1343
|
+
retryable;
|
|
1344
|
+
failureCode;
|
|
1345
|
+
constructor(message, options) {
|
|
1346
|
+
super(message);
|
|
1347
|
+
this.retryable = options.retryable;
|
|
1348
|
+
this.failureCode = options.failureCode ?? "response-invalid";
|
|
1349
|
+
}
|
|
1350
|
+
};
|
|
1351
|
+
function toFailedError(failure) {
|
|
1352
|
+
return new ResponsesStreamError("Responses stream failed", {
|
|
1353
|
+
retryable: [
|
|
1354
|
+
"rate_limit_exceeded",
|
|
1355
|
+
"server_error",
|
|
1356
|
+
"overloaded_error"
|
|
1357
|
+
].includes(String(failure.code)),
|
|
1358
|
+
failureCode: failure.code === "context_length_exceeded" ? "context-limit-exceeded" : failure.code === "insufficient_quota" ? "quota-exceeded" : "provider-error"
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
const str = (value) => typeof value === "string" ? value : "";
|
|
1362
|
+
const num = (value) => typeof value === "number" && value >= 0 ? value : 0;
|
|
1363
|
+
function partsOf(item, model) {
|
|
1364
|
+
if (item.type === "reasoning") {
|
|
1365
|
+
const summary = Array.isArray(item.summary) ? item.summary : [];
|
|
1366
|
+
const plain = Array.isArray(item.content) ? item.content : [];
|
|
1367
|
+
const text = (plain.length > 0 ? plain : summary).map((one) => str(one.text)).join("\n\n");
|
|
1368
|
+
const encrypted = str(item.encrypted_content);
|
|
1369
|
+
return [{
|
|
1370
|
+
type: "thinking",
|
|
1371
|
+
text,
|
|
1372
|
+
originModel: model,
|
|
1373
|
+
...encrypted === "" ? {} : { signature: encrypted }
|
|
1374
|
+
}];
|
|
1375
|
+
}
|
|
1376
|
+
if (item.type === "message") {
|
|
1377
|
+
const text = (Array.isArray(item.content) ? item.content : []).map((one) => {
|
|
1378
|
+
const part = one;
|
|
1379
|
+
return part.type === "output_text" ? str(part.text) : part.type === "refusal" ? str(part.refusal) : "";
|
|
1380
|
+
}).join("");
|
|
1381
|
+
return text === "" ? [] : [{
|
|
1382
|
+
type: "text",
|
|
1383
|
+
text
|
|
1384
|
+
}];
|
|
1385
|
+
}
|
|
1386
|
+
if (item.type === "function_call") {
|
|
1387
|
+
const id = str(item.call_id);
|
|
1388
|
+
const name = str(item.name);
|
|
1389
|
+
if (id.trim() === "" || name.trim() === "") throw new ResponsesStreamError("invalid model function_call: missing call_id or name", { retryable: false });
|
|
1390
|
+
if (item.status !== void 0 && item.status !== "completed") throw new ResponsesStreamError("invalid model function_call: call is not complete", { retryable: false });
|
|
1391
|
+
let input;
|
|
1392
|
+
try {
|
|
1393
|
+
input = JSON.parse(str(item.arguments));
|
|
1394
|
+
} catch {
|
|
1395
|
+
throw new ResponsesStreamError("invalid model function_call: arguments are not complete JSON", { retryable: false });
|
|
1396
|
+
}
|
|
1397
|
+
return [{
|
|
1398
|
+
type: "tool-use",
|
|
1399
|
+
id,
|
|
1400
|
+
name,
|
|
1401
|
+
input
|
|
1402
|
+
}];
|
|
1403
|
+
}
|
|
1404
|
+
return [];
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* Forwards deltas immediately and assembles terminal output from completed items.
|
|
1408
|
+
* Completed unusable replies and malformed tool calls fail without retry; refusals remain visible.
|
|
1409
|
+
*/
|
|
1410
|
+
async function* mapResponsesStream(events, options) {
|
|
1411
|
+
const items = [];
|
|
1412
|
+
const callIds = /* @__PURE__ */ new Map();
|
|
1413
|
+
const pendingCalls = /* @__PURE__ */ new Map();
|
|
1414
|
+
let openThinking = "";
|
|
1415
|
+
let refused = false;
|
|
1416
|
+
let open = "";
|
|
1417
|
+
for await (const event of events) switch (event.type) {
|
|
1418
|
+
case "response.output_text.delta":
|
|
1419
|
+
case "response.refusal.delta": {
|
|
1420
|
+
if (event.type === "response.refusal.delta") refused = true;
|
|
1421
|
+
const text = str(event.delta);
|
|
1422
|
+
if (text === "") break;
|
|
1423
|
+
yield {
|
|
1424
|
+
kind: "text-delta",
|
|
1425
|
+
text
|
|
1426
|
+
};
|
|
1427
|
+
open += text;
|
|
1428
|
+
break;
|
|
1429
|
+
}
|
|
1430
|
+
case "response.reasoning_text.delta":
|
|
1431
|
+
case "response.reasoning_summary_text.delta": {
|
|
1432
|
+
const text = str(event.delta);
|
|
1433
|
+
if (text !== "") {
|
|
1434
|
+
openThinking += text;
|
|
1435
|
+
yield {
|
|
1436
|
+
kind: "thinking-delta",
|
|
1437
|
+
text
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
break;
|
|
1441
|
+
}
|
|
1442
|
+
case "response.output_item.added": {
|
|
1443
|
+
const item = event.item;
|
|
1444
|
+
if (item?.type === "function_call") {
|
|
1445
|
+
const callId = str(item.call_id);
|
|
1446
|
+
callIds.set(str(item.id), callId);
|
|
1447
|
+
pendingCalls.set(str(item.id), {
|
|
1448
|
+
id: callId,
|
|
1449
|
+
...str(item.name) === "" ? {} : { name: str(item.name) }
|
|
1450
|
+
});
|
|
1451
|
+
yield {
|
|
1452
|
+
kind: "tool-call-delta",
|
|
1453
|
+
id: callId,
|
|
1454
|
+
name: str(item.name),
|
|
1455
|
+
inputDelta: ""
|
|
1456
|
+
};
|
|
1457
|
+
}
|
|
1458
|
+
break;
|
|
1459
|
+
}
|
|
1460
|
+
case "response.function_call_arguments.delta": {
|
|
1461
|
+
const callId = callIds.get(str(event.item_id));
|
|
1462
|
+
if (callId !== void 0) yield {
|
|
1463
|
+
kind: "tool-call-delta",
|
|
1464
|
+
id: callId,
|
|
1465
|
+
inputDelta: str(event.delta)
|
|
1466
|
+
};
|
|
1467
|
+
break;
|
|
1468
|
+
}
|
|
1469
|
+
case "response.output_item.done": {
|
|
1470
|
+
const item = event.item;
|
|
1471
|
+
if (item !== void 0) items.push(item);
|
|
1472
|
+
if (item?.type === "function_call") {
|
|
1473
|
+
pendingCalls.delete(str(item.id));
|
|
1474
|
+
for (const [key, call] of pendingCalls) if (call.id === str(item.call_id)) pendingCalls.delete(key);
|
|
1475
|
+
}
|
|
1476
|
+
if (item?.type === "reasoning") openThinking = "";
|
|
1477
|
+
if (item?.type === "message" && Array.isArray(item.content)) refused ||= item.content.some((part) => part.type === "refusal");
|
|
1478
|
+
if (item?.type === "message") open = "";
|
|
1479
|
+
break;
|
|
1480
|
+
}
|
|
1481
|
+
case "response.completed":
|
|
1482
|
+
case "response.incomplete": {
|
|
1483
|
+
const response = event.response ?? {};
|
|
1484
|
+
const terminalItems = Array.isArray(response.output) ? response.output : items;
|
|
1485
|
+
const incompleteThinking = terminalItems.some((item) => item.type === "reasoning" && item.status === "incomplete") || openThinking !== "" && !terminalItems.some((item) => item.type === "reasoning" && item.status === "completed");
|
|
1486
|
+
refused ||= terminalItems.some((item) => item.type === "message" && Array.isArray(item.content) && item.content.some((part) => part.type === "refusal"));
|
|
1487
|
+
const usage = response.usage ?? {};
|
|
1488
|
+
const details = usage.input_tokens_details ?? {};
|
|
1489
|
+
const cache = {
|
|
1490
|
+
...typeof details.cached_tokens === "number" && details.cached_tokens >= 0 ? { cacheReadTokens: details.cached_tokens } : {},
|
|
1491
|
+
...typeof details.cache_write_tokens === "number" && details.cache_write_tokens >= 0 ? { cacheWriteTokens: details.cache_write_tokens } : {}
|
|
1492
|
+
};
|
|
1493
|
+
const truncated = event.type === "response.incomplete" && response.incomplete_details?.reason === "max_output_tokens";
|
|
1494
|
+
if (event.type === "response.incomplete" && !truncated && !refused) throw new ResponsesStreamError(`incomplete model reply (${event.type})`, { retryable: false });
|
|
1495
|
+
const incompleteToolCalls = new Map([...pendingCalls.values()].map((call) => [call.id, call]));
|
|
1496
|
+
const content = terminalItems.flatMap((item) => {
|
|
1497
|
+
try {
|
|
1498
|
+
const parts = partsOf(item, options.model);
|
|
1499
|
+
if (item.type === "function_call") incompleteToolCalls.delete(str(item.call_id));
|
|
1500
|
+
return parts;
|
|
1501
|
+
} catch (error) {
|
|
1502
|
+
if (!truncated || item.type !== "function_call" || str(item.call_id) === "") throw error;
|
|
1503
|
+
incompleteToolCalls.set(str(item.call_id), {
|
|
1504
|
+
id: str(item.call_id),
|
|
1505
|
+
...str(item.name) === "" ? {} : { name: str(item.name) }
|
|
1506
|
+
});
|
|
1507
|
+
return [];
|
|
1508
|
+
}
|
|
1509
|
+
});
|
|
1510
|
+
if (truncated && open !== "" && !terminalItems.some((item) => item.type === "message")) content.push({
|
|
1511
|
+
type: "text",
|
|
1512
|
+
text: open
|
|
1513
|
+
});
|
|
1514
|
+
if (truncated && openThinking !== "" && !terminalItems.some((item) => item.type === "reasoning")) content.unshift({
|
|
1515
|
+
type: "thinking",
|
|
1516
|
+
text: openThinking
|
|
1517
|
+
});
|
|
1518
|
+
if (!truncated && !refused && !content.some((part) => part.type === "text" || part.type === "tool-use")) throw new ResponsesStreamError(`incomplete model reply (${event.type})`, {
|
|
1519
|
+
retryable: false,
|
|
1520
|
+
failureCode: "response-empty"
|
|
1521
|
+
});
|
|
1522
|
+
const finishReason = refused ? "refusal" : truncated ? "max-tokens" : content.some((part) => part.type === "tool-use") ? "tool-calls" : "stop";
|
|
1523
|
+
yield {
|
|
1524
|
+
kind: "final",
|
|
1525
|
+
finishReason,
|
|
1526
|
+
...finishReason === "max-tokens" ? { outputTruncation: {
|
|
1527
|
+
incompleteToolCalls: [...incompleteToolCalls.values()],
|
|
1528
|
+
...incompleteThinking ? { incompleteThinking: true } : {}
|
|
1529
|
+
} } : {},
|
|
1530
|
+
usage: {
|
|
1531
|
+
inputTokens: num(usage.input_tokens),
|
|
1532
|
+
outputTokens: num(usage.output_tokens),
|
|
1533
|
+
...cache
|
|
1534
|
+
},
|
|
1535
|
+
message: {
|
|
1536
|
+
role: "assistant",
|
|
1537
|
+
content
|
|
1538
|
+
}
|
|
1539
|
+
};
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
case "response.failed":
|
|
1543
|
+
case "error": throw toFailedError(event.response?.error ?? event.error ?? event);
|
|
1544
|
+
}
|
|
1545
|
+
throw new ResponsesStreamError("model stream interrupted", {
|
|
1546
|
+
retryable: true,
|
|
1547
|
+
failureCode: "stream-interrupted"
|
|
1548
|
+
});
|
|
1549
|
+
}
|
|
1550
|
+
//#endregion
|
|
1551
|
+
//#region src/responses/port.ts
|
|
1552
|
+
/** Creates a stateless public Responses port with host-owned retry and inspection. */
|
|
1553
|
+
function createResponsesPort(call, support, fetch, capability) {
|
|
1554
|
+
const options = ResponsesProtocolOptions.parse(call.options);
|
|
1555
|
+
function build(request, inspection = false) {
|
|
1556
|
+
const entry = support.catalogue(call.providerId, call.model);
|
|
1557
|
+
const endpoint = support.endpoint(call.providerId);
|
|
1558
|
+
const params = support.resolveParams({
|
|
1559
|
+
facts,
|
|
1560
|
+
entry,
|
|
1561
|
+
endpoint,
|
|
1562
|
+
model: call.model,
|
|
1563
|
+
stored: request.params ?? {}
|
|
1564
|
+
});
|
|
1565
|
+
const extra = support.extraParams(request.params ?? {});
|
|
1566
|
+
for (const key of [
|
|
1567
|
+
"input",
|
|
1568
|
+
"instructions",
|
|
1569
|
+
"store",
|
|
1570
|
+
"include",
|
|
1571
|
+
"previous_response_id",
|
|
1572
|
+
"conversation"
|
|
1573
|
+
]) if (key in extra) throw new Error(`invalid-params: reserved field ${key}`);
|
|
1574
|
+
const replay = support.planEffortCache({
|
|
1575
|
+
request,
|
|
1576
|
+
inspection,
|
|
1577
|
+
effort: params.effort,
|
|
1578
|
+
capability: capability(request),
|
|
1579
|
+
bindingFingerprint: support.inspectionFingerprint({
|
|
1580
|
+
connectionFingerprint: call.connectionFingerprint,
|
|
1581
|
+
providerId: call.providerId,
|
|
1582
|
+
model: call.model,
|
|
1583
|
+
config: call.config,
|
|
1584
|
+
options: call.options,
|
|
1585
|
+
system: request.system,
|
|
1586
|
+
tools: request.tools,
|
|
1587
|
+
thinking: params.thinking,
|
|
1588
|
+
extra
|
|
1589
|
+
})
|
|
1590
|
+
});
|
|
1591
|
+
const media = support.mediaContextOf({
|
|
1592
|
+
entry,
|
|
1593
|
+
endpoint,
|
|
1594
|
+
facts,
|
|
1595
|
+
stored: request.params ?? {},
|
|
1596
|
+
fileKinds: ["image"]
|
|
1597
|
+
});
|
|
1598
|
+
const mediaPlan = support.planMedia(request, media);
|
|
1599
|
+
const settings = {
|
|
1600
|
+
model: call.model,
|
|
1601
|
+
endpoint: call.providerId,
|
|
1602
|
+
effort: params.thinking === false ? "none" : replay.baseEffort ?? (params.thinking === true ? options.thinkingOnEffort : void 0),
|
|
1603
|
+
reasoningReplay: options.reasoningReplay,
|
|
1604
|
+
reasoningSummary: options.reasoningSummary,
|
|
1605
|
+
encryptedReasoningInclude: options.encryptedReasoningInclude,
|
|
1606
|
+
effortUpdates: replay.updates
|
|
1607
|
+
};
|
|
1608
|
+
let maxTokens = params.maxTokens;
|
|
1609
|
+
if (request.purpose === "summary") {
|
|
1610
|
+
if (!Number.isSafeInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0) throw new Error("summaryMaxTokens must be a positive integer");
|
|
1611
|
+
maxTokens = Math.min(maxTokens ?? Infinity, Number(request.summaryMaxTokens));
|
|
1612
|
+
}
|
|
1613
|
+
return {
|
|
1614
|
+
body: {
|
|
1615
|
+
...toResponsesBody(options.toolChoiceNone === false && request.toolChoice === "none" ? {
|
|
1616
|
+
...request,
|
|
1617
|
+
tools: []
|
|
1618
|
+
} : request, settings, mediaPlan),
|
|
1619
|
+
...maxTokens === void 0 ? {} : { max_output_tokens: maxTokens },
|
|
1620
|
+
...params.temperature === void 0 ? {} : { temperature: params.temperature },
|
|
1621
|
+
...request.cacheKey && options.promptCacheKey !== false ? { prompt_cache_key: request.cacheKey } : {},
|
|
1622
|
+
...request.purpose === "summary" ? {} : extra
|
|
1623
|
+
},
|
|
1624
|
+
replay,
|
|
1625
|
+
entry,
|
|
1626
|
+
mediaPlan,
|
|
1627
|
+
settings,
|
|
1628
|
+
maxTokens
|
|
1629
|
+
};
|
|
1630
|
+
}
|
|
1631
|
+
return {
|
|
1632
|
+
inspect(request) {
|
|
1633
|
+
const { body, replay, entry, mediaPlan, settings, maxTokens } = build(request, true);
|
|
1634
|
+
return support.inspect({
|
|
1635
|
+
body,
|
|
1636
|
+
request,
|
|
1637
|
+
textTokens: support.measureText(support.requestText("responses", body)),
|
|
1638
|
+
tokenizer: "o200k_base-protocol-text-v2",
|
|
1639
|
+
capacity: entry?.limit,
|
|
1640
|
+
outputReserve: maxTokens ?? entry?.limit?.output ?? 0,
|
|
1641
|
+
outputReserveSource: maxTokens === void 0 ? "capacity" : "enforced",
|
|
1642
|
+
hiddenInputTokens: responsesHiddenInputTokens(request, settings),
|
|
1643
|
+
mediaTokens: mediaPlan.tokens,
|
|
1644
|
+
fingerprint: {
|
|
1645
|
+
protocol: "openai-responses",
|
|
1646
|
+
model: call.model,
|
|
1647
|
+
config: call.config,
|
|
1648
|
+
params: request.params,
|
|
1649
|
+
capacity: entry?.limit,
|
|
1650
|
+
updates: replay.updates
|
|
1651
|
+
}
|
|
1652
|
+
});
|
|
1653
|
+
},
|
|
1654
|
+
stream(request, signal, observer) {
|
|
1655
|
+
signal.throwIfAborted();
|
|
1656
|
+
const { body, replay } = build(request);
|
|
1657
|
+
return support.withChatAttempts({
|
|
1658
|
+
signal,
|
|
1659
|
+
async *attempt(attemptSignal, reportProgress, attempt) {
|
|
1660
|
+
const observe = (event) => {
|
|
1661
|
+
try {
|
|
1662
|
+
observer?.observe?.(event);
|
|
1663
|
+
} catch {}
|
|
1664
|
+
};
|
|
1665
|
+
const attemptCount = attempt + 1;
|
|
1666
|
+
let outcome = "unknown";
|
|
1667
|
+
let firstResponseFinished = false;
|
|
1668
|
+
let attemptFinished = false;
|
|
1669
|
+
observe({
|
|
1670
|
+
stage: "attempt",
|
|
1671
|
+
phase: "start",
|
|
1672
|
+
attempt: attemptCount
|
|
1673
|
+
});
|
|
1674
|
+
observe({
|
|
1675
|
+
stage: "first-response",
|
|
1676
|
+
phase: "start",
|
|
1677
|
+
attempt: attemptCount
|
|
1678
|
+
});
|
|
1679
|
+
let abortStream;
|
|
1680
|
+
try {
|
|
1681
|
+
const stream = await new OpenAI({
|
|
1682
|
+
apiKey: options.allowUnauthenticated && !call.secrets.apiKey ? "not-used" : call.secrets.apiKey ?? "",
|
|
1683
|
+
...options.allowUnauthenticated && !call.secrets.apiKey ? { defaultHeaders: { Authorization: null } } : {},
|
|
1684
|
+
baseURL: String(call.config.baseUrl),
|
|
1685
|
+
maxRetries: 0,
|
|
1686
|
+
fetch: async (...args) => support.observeResponseProgress(await fetch(...args), reportProgress)
|
|
1687
|
+
}).responses.create(body, { signal: attemptSignal });
|
|
1688
|
+
abortStream = () => stream.controller.abort();
|
|
1689
|
+
firstResponseFinished = true;
|
|
1690
|
+
observe({
|
|
1691
|
+
stage: "first-response",
|
|
1692
|
+
phase: "end",
|
|
1693
|
+
attempt: attemptCount,
|
|
1694
|
+
outcome: "ok"
|
|
1695
|
+
});
|
|
1696
|
+
try {
|
|
1697
|
+
observer?.dispatched({ attempt });
|
|
1698
|
+
} catch {}
|
|
1699
|
+
const observed = (async function* () {
|
|
1700
|
+
for await (const event of stream) {
|
|
1701
|
+
reportProgress();
|
|
1702
|
+
yield event;
|
|
1703
|
+
}
|
|
1704
|
+
})();
|
|
1705
|
+
for await (const chunk of mapResponsesStream(observed, { model: call.model })) {
|
|
1706
|
+
attemptSignal.throwIfAborted();
|
|
1707
|
+
if (chunk.kind === "final") {
|
|
1708
|
+
outcome = "ok";
|
|
1709
|
+
attemptFinished = true;
|
|
1710
|
+
observe({
|
|
1711
|
+
stage: "attempt",
|
|
1712
|
+
phase: "end",
|
|
1713
|
+
attempt: attemptCount,
|
|
1714
|
+
outcome
|
|
1715
|
+
});
|
|
1716
|
+
}
|
|
1717
|
+
yield chunk.kind === "final" && replay.replayData !== void 0 ? {
|
|
1718
|
+
...chunk,
|
|
1719
|
+
replayData: replay.replayData
|
|
1720
|
+
} : chunk;
|
|
1721
|
+
}
|
|
1722
|
+
} catch (error) {
|
|
1723
|
+
outcome = attemptSignal.aborted ? "cancelled" : "error";
|
|
1724
|
+
throw error;
|
|
1725
|
+
} finally {
|
|
1726
|
+
if (attemptSignal.aborted && !attemptFinished) outcome = "cancelled";
|
|
1727
|
+
abortStream?.();
|
|
1728
|
+
if (!firstResponseFinished) observe({
|
|
1729
|
+
stage: "first-response",
|
|
1730
|
+
phase: "end",
|
|
1731
|
+
attempt: attemptCount,
|
|
1732
|
+
outcome
|
|
1733
|
+
});
|
|
1734
|
+
if (!attemptFinished) observe({
|
|
1735
|
+
stage: "attempt",
|
|
1736
|
+
phase: "end",
|
|
1737
|
+
attempt: attemptCount,
|
|
1738
|
+
outcome
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
},
|
|
1742
|
+
classify(error) {
|
|
1743
|
+
const failure = error instanceof ResponsesStreamError ? support.failures.create({
|
|
1744
|
+
code: error.failureCode,
|
|
1745
|
+
stage: "stream",
|
|
1746
|
+
source: "protocol",
|
|
1747
|
+
category: error.retryable ? "network" : "protocol",
|
|
1748
|
+
retryable: error.retryable
|
|
1749
|
+
}) : toModelFailure(error, support.failures);
|
|
1750
|
+
return {
|
|
1751
|
+
error: failure,
|
|
1752
|
+
retryable: failure.retryable === true,
|
|
1753
|
+
retryAfterMs: retryAfterMs(error)
|
|
1754
|
+
};
|
|
1755
|
+
}
|
|
1756
|
+
});
|
|
1757
|
+
}
|
|
1758
|
+
};
|
|
1759
|
+
}
|
|
1760
|
+
//#endregion
|
|
1761
|
+
//#region src/responses/protocol.ts
|
|
1762
|
+
function capability(input) {
|
|
1763
|
+
if (ResponsesProtocolOptions.parse(input.options ?? {}).effortCache === false) return {
|
|
1764
|
+
status: "unsupported",
|
|
1765
|
+
reason: "configuration-updates-unavailable"
|
|
1766
|
+
};
|
|
1767
|
+
if (input.params.thinking === false || input.params.effort === "none") return {
|
|
1768
|
+
status: "unsupported",
|
|
1769
|
+
reason: "reasoning-required"
|
|
1770
|
+
};
|
|
1771
|
+
return { status: "supported" };
|
|
1772
|
+
}
|
|
1773
|
+
/** Registers the HTTP Responses API independently from Chat Completions. */
|
|
1774
|
+
function responsesProtocolType(support, fetch) {
|
|
1775
|
+
return {
|
|
1776
|
+
type: "openai-responses",
|
|
1777
|
+
label: "OpenAI Responses API",
|
|
1778
|
+
userConfigurable: true,
|
|
1779
|
+
logo: protocolLogo,
|
|
1780
|
+
fields: [{
|
|
1781
|
+
key: "baseUrl",
|
|
1782
|
+
kind: "url",
|
|
1783
|
+
label: "Base URL",
|
|
1784
|
+
required: true
|
|
1785
|
+
}],
|
|
1786
|
+
optionsSchema: ResponsesProtocolOptions,
|
|
1787
|
+
facts,
|
|
1788
|
+
effortCacheCapability: capability,
|
|
1789
|
+
prepareParams: (input) => support.prepareParams(input, facts),
|
|
1790
|
+
adapters: { chat: {
|
|
1791
|
+
fileKinds: ["image"],
|
|
1792
|
+
supportsModel: () => true,
|
|
1793
|
+
createPort: (call) => createResponsesPort(call, support, fetch, (request) => capability({
|
|
1794
|
+
...call,
|
|
1795
|
+
params: request.params ?? {},
|
|
1796
|
+
explicitKeys: []
|
|
1797
|
+
}))
|
|
1798
|
+
} },
|
|
1799
|
+
normalizeListing: (input) => normalizeOffers(input),
|
|
1800
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, fetch) }),
|
|
1801
|
+
testConnection: (probe) => probeOpenAI.testConnection(probe, fetch, "responses")
|
|
1802
|
+
};
|
|
1803
|
+
}
|
|
1804
|
+
//#endregion
|
|
820
1805
|
//#region src/index.ts
|
|
821
1806
|
/** Protocol extensions contribute no tools. */
|
|
822
1807
|
const TOOL_NAMES = [];
|
|
823
1808
|
const plugin = {
|
|
824
1809
|
name: "@eum-agent/llm-protocol-openai",
|
|
825
|
-
requires: ["
|
|
1810
|
+
requires: ["network"],
|
|
1811
|
+
optionalServices: ["model-support"],
|
|
1812
|
+
provides: ["openai-responses-codec"],
|
|
826
1813
|
apply(ctx) {
|
|
827
|
-
const support = ctx.services.
|
|
1814
|
+
const support = lazySupport(() => ctx.services.find("model-support"));
|
|
828
1815
|
const network = ctx.services.get("network");
|
|
829
|
-
ctx.
|
|
1816
|
+
ctx.services.provide("openai-responses-codec", responsesCodec);
|
|
1817
|
+
ctx.modelProtocols.register(openaiProtocolType(support, network.fetch));
|
|
1818
|
+
ctx.modelProtocols.register(responsesProtocolType(support, network.fetch));
|
|
1819
|
+
ctx.modelProtocols.register(imagesProtocolType(support, network.fetch));
|
|
830
1820
|
}
|
|
831
1821
|
};
|
|
832
1822
|
//#endregion
|