@eum-agent/llm-protocol-openai 1.0.0 → 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 +1316 -196
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,11 +1,453 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { countTokens } from "gpt-tokenizer/encoding/o200k_base";
|
|
3
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
|
|
4
447
|
//#region src/protocol/facts.ts
|
|
5
448
|
/** Parameter ranges and request limits for this provider wire. */
|
|
6
449
|
const facts = {
|
|
7
|
-
|
|
8
|
-
maxTokensFallback: 8192,
|
|
450
|
+
outputLimit: { support: "optional" },
|
|
9
451
|
temperature: {
|
|
10
452
|
min: 0,
|
|
11
453
|
max: 2,
|
|
@@ -21,32 +463,10 @@ const facts = {
|
|
|
21
463
|
//#endregion
|
|
22
464
|
//#region src/protocol/errors.ts
|
|
23
465
|
/**
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* redact against the endpoint's credentials and show.
|
|
466
|
+
* SDK exceptions have two consumers: explicit probes retain provider text for
|
|
467
|
+
* their credential-redaction boundary, while Agent calls accept only fixed
|
|
468
|
+
* templates and allowlisted facts through the host factory.
|
|
28
469
|
*/
|
|
29
|
-
/** Thrown by `stream()` once retries are exhausted (or the failure was
|
|
30
|
-
* never retryable) — mirrors the anthropic member's `ModelCallError`; the
|
|
31
|
-
* two packages share no code, only the shape of the port error they both
|
|
32
|
-
* produce. */
|
|
33
|
-
var ModelCallError = class extends Error {
|
|
34
|
-
status;
|
|
35
|
-
retryable;
|
|
36
|
-
/** The endpoint's own error body, unredacted. The runtime's guard removes
|
|
37
|
-
* every credential of the endpoint from it before it reaches a reason. */
|
|
38
|
-
providerText;
|
|
39
|
-
/** What the status alone says the refusal is (`failureKindOf`). */
|
|
40
|
-
kind;
|
|
41
|
-
constructor(message, options) {
|
|
42
|
-
super(message);
|
|
43
|
-
this.name = "ModelCallError";
|
|
44
|
-
this.status = options.status;
|
|
45
|
-
this.retryable = options.retryable;
|
|
46
|
-
this.providerText = options.providerText;
|
|
47
|
-
this.kind = options.status === 413 ? "request-too-large" : void 0;
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
470
|
/** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
|
|
51
471
|
* every other status is not. */
|
|
52
472
|
function isRetryableStatus(status) {
|
|
@@ -57,27 +477,46 @@ function retryAfterMs(error) {
|
|
|
57
477
|
const header = error.headers?.get("retry-after");
|
|
58
478
|
if (!header) return void 0;
|
|
59
479
|
const seconds = Number(header);
|
|
60
|
-
if (!Number.isFinite(seconds)) return void 0;
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
function toPortError(error) {
|
|
64
|
-
if (error instanceof APIError) {
|
|
65
|
-
const status = error.status;
|
|
66
|
-
const retryable = error instanceof APIConnectionError || isRetryableStatus(status);
|
|
67
|
-
const type = error.type;
|
|
68
|
-
return new ModelCallError(`OpenAI-compatible API error (status ${status ?? "unknown"}${type ? `, type ${type}` : ""})`, {
|
|
69
|
-
status,
|
|
70
|
-
retryable,
|
|
71
|
-
providerText: providerTextOf(error)
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
return new ModelCallError(`OpenAI-compatible call failed: ${error instanceof Error ? error.message : String(error)}`, { retryable: false });
|
|
480
|
+
if (!Number.isFinite(seconds) || seconds < 0) return void 0;
|
|
481
|
+
const milliseconds = seconds * 1e3;
|
|
482
|
+
return Number.isFinite(milliseconds) ? milliseconds : void 0;
|
|
75
483
|
}
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
484
|
+
/** Maps verified SDK classes and factory identities to bounded Agent failure candidates. */
|
|
485
|
+
function toModelFailure(error, failures) {
|
|
486
|
+
if (failures.owns(error)) return error;
|
|
487
|
+
if (!(error instanceof APIError)) return failures.create({
|
|
488
|
+
code: "unknown",
|
|
489
|
+
stage: "unknown",
|
|
490
|
+
category: "unknown",
|
|
491
|
+
source: "unknown",
|
|
492
|
+
retryable: false
|
|
493
|
+
});
|
|
494
|
+
const rawCode = error.code ?? error.type;
|
|
495
|
+
const providerCode = typeof rawCode === "string" && (/* @__PURE__ */ new Set([
|
|
496
|
+
"usage_not_included",
|
|
497
|
+
"usage_limit_reached",
|
|
498
|
+
"insufficient_quota",
|
|
499
|
+
"context_length_exceeded",
|
|
500
|
+
"rate_limit_exceeded",
|
|
501
|
+
"overloaded_error",
|
|
502
|
+
"api_error",
|
|
503
|
+
"rate_limit_error",
|
|
504
|
+
"cyber_policy",
|
|
505
|
+
"invalid_prompt",
|
|
506
|
+
"bio_policy",
|
|
507
|
+
"misalignment_policy_violation"
|
|
508
|
+
])).has(rawCode) ? rawCode : void 0;
|
|
509
|
+
const connection = error instanceof APIConnectionError;
|
|
510
|
+
const status = Number.isInteger(error.status) && Number(error.status) >= 100 && Number(error.status) <= 599 ? error.status : void 0;
|
|
511
|
+
return failures.create({
|
|
512
|
+
code: connection ? "stream-interrupted" : status === 413 ? "request-too-large" : status === void 0 ? "provider-error" : "http-error",
|
|
513
|
+
stage: connection ? "transport" : status === 413 ? "request" : status === void 0 ? "stream" : "transport",
|
|
514
|
+
category: connection ? "network" : status === 413 ? "request-too-large" : "provider",
|
|
515
|
+
source: connection ? "transport" : "protocol",
|
|
516
|
+
...status === void 0 ? {} : { status },
|
|
517
|
+
retryable: connection || isRetryableStatus(status),
|
|
518
|
+
...providerCode === void 0 ? {} : { providerCode }
|
|
519
|
+
});
|
|
81
520
|
}
|
|
82
521
|
//#endregion
|
|
83
522
|
//#region src/protocol/request.ts
|
|
@@ -133,13 +572,14 @@ function userContent(message, index, plan) {
|
|
|
133
572
|
}
|
|
134
573
|
/** One kernel message becomes zero or more wire messages: a `user`
|
|
135
574
|
* message's `tool-result` parts each become their own `role: 'tool'`
|
|
136
|
-
* message
|
|
575
|
+
* message. Assistant replies without text or tool calls are omitted after
|
|
576
|
+
* reasoning is stripped; the endpoint requires at least one of those fields.
|
|
137
577
|
*
|
|
138
578
|
* A `role: 'tool'` message holds text alone, so the images a batch of
|
|
139
579
|
* results handed back follow it in one user message, each after the id of
|
|
140
580
|
* the call it came from; an image standing in as a line of text stays in
|
|
141
581
|
* its call's own tool message. */
|
|
142
|
-
function toChatMessages(message, index, plan) {
|
|
582
|
+
function toChatMessages(message, index, plan, options) {
|
|
143
583
|
const toolResults = message.content.map((part, partIndex) => ({
|
|
144
584
|
part,
|
|
145
585
|
partIndex
|
|
@@ -173,11 +613,17 @@ function toChatMessages(message, index, plan) {
|
|
|
173
613
|
}, ...images]
|
|
174
614
|
}];
|
|
175
615
|
}
|
|
176
|
-
if (message.role === "assistant")
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
616
|
+
if (message.role === "assistant") {
|
|
617
|
+
const content = textOf(message.content);
|
|
618
|
+
const toolCalls = toolCallsOf(message.content);
|
|
619
|
+
if (content === null && toolCalls === void 0) return [];
|
|
620
|
+
return [{
|
|
621
|
+
role: "assistant",
|
|
622
|
+
content,
|
|
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("") } : {},
|
|
624
|
+
...toolCalls === void 0 ? {} : { tool_calls: toolCalls }
|
|
625
|
+
}];
|
|
626
|
+
}
|
|
181
627
|
return [{
|
|
182
628
|
role: "user",
|
|
183
629
|
content: userContent(message, index, plan)
|
|
@@ -209,8 +655,8 @@ function volatileMessages(volatile) {
|
|
|
209
655
|
}
|
|
210
656
|
/** A reply's recorded notes go just before it — where the request that
|
|
211
657
|
* produced it carried them — so every request extends the previous one. */
|
|
212
|
-
function withNotes(message, index, plan) {
|
|
213
|
-
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)];
|
|
214
660
|
}
|
|
215
661
|
function toToolParam(tool) {
|
|
216
662
|
return {
|
|
@@ -222,6 +668,7 @@ function toToolParam(tool) {
|
|
|
222
668
|
}
|
|
223
669
|
};
|
|
224
670
|
}
|
|
671
|
+
/** Renders provider history without empty assistant messages; rejects invalid summary budgets. */
|
|
225
672
|
function toOpenAIRequest(request, options) {
|
|
226
673
|
const summary = request.purpose === "summary";
|
|
227
674
|
if (summary && (!Number.isInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0)) throw new Error("summaryMaxTokens must be a positive integer for a summary request");
|
|
@@ -241,7 +688,7 @@ function toOpenAIRequest(request, options) {
|
|
|
241
688
|
stream_options: { include_usage: true },
|
|
242
689
|
messages: [
|
|
243
690
|
...systemMessage,
|
|
244
|
-
...request.messages.flatMap((message, index) => withNotes(message, index, plan)),
|
|
691
|
+
...request.messages.flatMap((message, index) => withNotes(message, index, plan, options)),
|
|
245
692
|
...volatileMessages(request.volatile)
|
|
246
693
|
],
|
|
247
694
|
...tools.length === 0 ? {} : { tools },
|
|
@@ -260,12 +707,19 @@ function cacheOf(usage) {
|
|
|
260
707
|
const read = usage.prompt_tokens_details?.cached_tokens ?? usage.prompt_cache_hit_tokens;
|
|
261
708
|
return typeof read === "number" && read >= 0 ? { cacheReadTokens: read } : {};
|
|
262
709
|
}
|
|
263
|
-
function toFinishReason(reason) {
|
|
710
|
+
function toFinishReason(reason, support) {
|
|
264
711
|
switch (reason) {
|
|
265
712
|
case "tool_calls": return "tool-calls";
|
|
266
713
|
case "length": return "max-tokens";
|
|
267
714
|
case "content_filter": return "refusal";
|
|
268
|
-
|
|
715
|
+
case "stop": return "stop";
|
|
716
|
+
default: throw support.failures.create({
|
|
717
|
+
code: reason === null ? "finish-reason-missing" : "finish-reason-unsupported",
|
|
718
|
+
stage: "response-validation",
|
|
719
|
+
category: "protocol",
|
|
720
|
+
source: "protocol",
|
|
721
|
+
retryable: false
|
|
722
|
+
});
|
|
269
723
|
}
|
|
270
724
|
}
|
|
271
725
|
/** The accumulated arguments as JSON, or `undefined` when they will not
|
|
@@ -281,17 +735,11 @@ function parseToolInput(argumentsJson) {
|
|
|
281
735
|
}
|
|
282
736
|
}
|
|
283
737
|
/**
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
287
|
-
* assistant message with no content — which reads as a model that had nothing
|
|
288
|
-
* to say and ends the turn as an ordinary completion. This sentence is the
|
|
289
|
-
* adapter's own, not the endpoint's, and it goes where both the person and the
|
|
290
|
-
* next turn read it. The `anthropic` member carries the same one for the same
|
|
291
|
-
* reason.
|
|
738
|
+
* Streams provider deltas and one validated final reply. Missing terminal reasons,
|
|
739
|
+
* unknown reasons and replies without text or usable tool calls fail without retry.
|
|
740
|
+
* A stream with neither usage nor a terminal reason retains interruption semantics.
|
|
292
741
|
*/
|
|
293
|
-
|
|
294
|
-
async function* mapOpenAIStream(chunks, support) {
|
|
742
|
+
async function* mapOpenAIStream(chunks, support, originModel) {
|
|
295
743
|
const textParts = [];
|
|
296
744
|
const thinkingParts = [];
|
|
297
745
|
const toolCalls = /* @__PURE__ */ new Map();
|
|
@@ -299,9 +747,11 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
299
747
|
let inputTokens = 0;
|
|
300
748
|
let outputTokens = 0;
|
|
301
749
|
let finishReason = "stop";
|
|
750
|
+
let rawFinishReason = null;
|
|
302
751
|
let cache = {};
|
|
303
752
|
let ended = false;
|
|
304
753
|
let refusalText;
|
|
754
|
+
let thinkingOpen = false;
|
|
305
755
|
for await (const chunk of chunks) {
|
|
306
756
|
if (chunk.usage) {
|
|
307
757
|
inputTokens = chunk.usage.prompt_tokens;
|
|
@@ -314,6 +764,7 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
314
764
|
const delta = choice.delta;
|
|
315
765
|
const reasoningContent = delta.reasoning_content || (typeof delta.reasoning === "string" ? delta.reasoning : void 0);
|
|
316
766
|
if (reasoningContent) {
|
|
767
|
+
thinkingOpen = true;
|
|
317
768
|
thinkingParts.push(reasoningContent);
|
|
318
769
|
yield {
|
|
319
770
|
kind: "thinking-delta",
|
|
@@ -321,6 +772,7 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
321
772
|
};
|
|
322
773
|
}
|
|
323
774
|
if (choice.delta.content) {
|
|
775
|
+
thinkingOpen = false;
|
|
324
776
|
textParts.push(choice.delta.content);
|
|
325
777
|
yield {
|
|
326
778
|
kind: "text-delta",
|
|
@@ -329,9 +781,16 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
329
781
|
}
|
|
330
782
|
if (choice.delta.refusal) refusalText = (refusalText ?? "") + choice.delta.refusal;
|
|
331
783
|
for (const delta of choice.delta.tool_calls ?? []) {
|
|
784
|
+
thinkingOpen = false;
|
|
332
785
|
let state = toolCalls.get(delta.index);
|
|
333
786
|
if (!state) {
|
|
334
|
-
if (!delta.id || !delta.function?.name) throw
|
|
787
|
+
if (!delta.id || !delta.function?.name) throw support.failures.create({
|
|
788
|
+
code: "response-invalid",
|
|
789
|
+
stage: "response-validation",
|
|
790
|
+
category: "protocol",
|
|
791
|
+
source: "protocol",
|
|
792
|
+
retryable: false
|
|
793
|
+
});
|
|
335
794
|
state = {
|
|
336
795
|
id: delta.id,
|
|
337
796
|
name: delta.function.name,
|
|
@@ -365,29 +824,49 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
365
824
|
};
|
|
366
825
|
}
|
|
367
826
|
if (choice.finish_reason) {
|
|
368
|
-
|
|
827
|
+
rawFinishReason = choice.finish_reason;
|
|
828
|
+
finishReason = toFinishReason(choice.finish_reason, support);
|
|
369
829
|
ended = true;
|
|
370
830
|
}
|
|
371
831
|
}
|
|
372
832
|
if (!ended) throw support.interruptedFailure();
|
|
833
|
+
if (rawFinishReason === null) throw support.failures.create({
|
|
834
|
+
code: "finish-reason-missing",
|
|
835
|
+
stage: "response-validation",
|
|
836
|
+
category: "protocol",
|
|
837
|
+
source: "protocol",
|
|
838
|
+
retryable: false
|
|
839
|
+
});
|
|
373
840
|
const content = [];
|
|
374
841
|
const thinkingText = thinkingParts.join("");
|
|
375
842
|
if (thinkingText.length > 0) content.push({
|
|
376
843
|
type: "thinking",
|
|
377
|
-
text: thinkingText
|
|
844
|
+
text: thinkingText,
|
|
845
|
+
...originModel === void 0 ? {} : { originModel }
|
|
378
846
|
});
|
|
379
847
|
const text = refusalText ?? textParts.join("");
|
|
380
848
|
if (text.length > 0) content.push({
|
|
381
849
|
type: "text",
|
|
382
850
|
text
|
|
383
851
|
});
|
|
384
|
-
|
|
852
|
+
const incompleteToolCalls = [];
|
|
385
853
|
for (const index of toolCallOrder) {
|
|
386
854
|
const call = toolCalls.get(index);
|
|
387
855
|
if (!call) continue;
|
|
388
|
-
const input = parseToolInput(call.arguments);
|
|
856
|
+
const input = finishReason === "max-tokens" && call.arguments.trim() === "" ? void 0 : parseToolInput(call.arguments);
|
|
389
857
|
if (input === void 0) {
|
|
390
|
-
|
|
858
|
+
if (finishReason !== "max-tokens") throw support.failures.create({
|
|
859
|
+
code: "response-invalid",
|
|
860
|
+
stage: "response-validation",
|
|
861
|
+
category: "protocol",
|
|
862
|
+
source: "protocol",
|
|
863
|
+
retryable: false,
|
|
864
|
+
finishReason
|
|
865
|
+
});
|
|
866
|
+
incompleteToolCalls.push({
|
|
867
|
+
id: call.id,
|
|
868
|
+
name: call.name
|
|
869
|
+
});
|
|
391
870
|
continue;
|
|
392
871
|
}
|
|
393
872
|
content.push({
|
|
@@ -397,13 +876,21 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
397
876
|
input
|
|
398
877
|
});
|
|
399
878
|
}
|
|
400
|
-
if (content.
|
|
401
|
-
|
|
402
|
-
|
|
879
|
+
if (finishReason !== "refusal" && finishReason !== "max-tokens" && !content.some((part) => part.type === "text" || part.type === "tool-use")) throw support.failures.create({
|
|
880
|
+
code: "response-empty",
|
|
881
|
+
stage: "response-validation",
|
|
882
|
+
category: "protocol",
|
|
883
|
+
source: "protocol",
|
|
884
|
+
retryable: false,
|
|
885
|
+
finishReason
|
|
403
886
|
});
|
|
404
887
|
yield {
|
|
405
888
|
kind: "final",
|
|
406
889
|
finishReason,
|
|
890
|
+
...finishReason === "max-tokens" ? { outputTruncation: {
|
|
891
|
+
incompleteToolCalls,
|
|
892
|
+
...thinkingOpen ? { incompleteThinking: true } : {}
|
|
893
|
+
} } : {},
|
|
407
894
|
usage: {
|
|
408
895
|
inputTokens,
|
|
409
896
|
outputTokens,
|
|
@@ -433,7 +920,8 @@ function openaiOptions(plan) {
|
|
|
433
920
|
function createOpenAIModelPort(options) {
|
|
434
921
|
function clientForAttempt(reportProgress) {
|
|
435
922
|
return options.client ?? new OpenAI({
|
|
436
|
-
apiKey: options.apiKey ?? "",
|
|
923
|
+
apiKey: options.allowUnauthenticated && !options.apiKey ? "not-used" : options.apiKey ?? "",
|
|
924
|
+
...options.allowUnauthenticated && !options.apiKey ? { defaultHeaders: { Authorization: null } } : {},
|
|
437
925
|
fetch: async (...args) => options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress),
|
|
438
926
|
baseURL: options.baseURL ?? "",
|
|
439
927
|
maxRetries: 0
|
|
@@ -476,8 +964,8 @@ function createOpenAIModelPort(options) {
|
|
|
476
964
|
const outputReserve = enforced ? Math.max(...explicitOutputLimits) : capacity?.output ?? Math.max(0, ...explicitOutputLimits);
|
|
477
965
|
return options.support.inspect({
|
|
478
966
|
body: params,
|
|
479
|
-
textTokens:
|
|
480
|
-
tokenizer: "o200k_base-
|
|
967
|
+
textTokens: options.support.measureText(options.support.requestText("chat-completions", params)),
|
|
968
|
+
tokenizer: "o200k_base-protocol-text-v2",
|
|
481
969
|
request,
|
|
482
970
|
capacity,
|
|
483
971
|
outputReserve,
|
|
@@ -502,27 +990,81 @@ function createOpenAIModelPort(options) {
|
|
|
502
990
|
}
|
|
503
991
|
});
|
|
504
992
|
},
|
|
505
|
-
stream(request, signal) {
|
|
993
|
+
stream(request, signal, observer) {
|
|
994
|
+
signal.throwIfAborted();
|
|
506
995
|
const { params } = build(request);
|
|
507
996
|
return options.support.withChatAttempts({
|
|
508
997
|
signal,
|
|
509
998
|
...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
|
|
510
999
|
...options.sleep === void 0 ? {} : { sleep: options.sleep },
|
|
511
1000
|
...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
|
|
512
|
-
async *attempt(attemptSignal, reportProgress) {
|
|
513
|
-
const
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
1001
|
+
async *attempt(attemptSignal, reportProgress, attempt) {
|
|
1002
|
+
const observe = (event) => {
|
|
1003
|
+
try {
|
|
1004
|
+
observer?.observe?.(event);
|
|
1005
|
+
} catch {}
|
|
1006
|
+
};
|
|
1007
|
+
const attemptCount = attempt + 1;
|
|
1008
|
+
let outcome = "unknown";
|
|
1009
|
+
let firstResponseFinished = false;
|
|
1010
|
+
observe({
|
|
1011
|
+
stage: "attempt",
|
|
1012
|
+
phase: "start",
|
|
1013
|
+
attempt: attemptCount
|
|
1014
|
+
});
|
|
1015
|
+
observe({
|
|
1016
|
+
stage: "first-response",
|
|
1017
|
+
phase: "start",
|
|
1018
|
+
attempt: attemptCount
|
|
1019
|
+
});
|
|
1020
|
+
try {
|
|
1021
|
+
attemptSignal.throwIfAborted();
|
|
1022
|
+
const chunks = await clientForAttempt(reportProgress).chat.completions.create(params, { signal: attemptSignal });
|
|
1023
|
+
firstResponseFinished = true;
|
|
1024
|
+
observe({
|
|
1025
|
+
stage: "first-response",
|
|
1026
|
+
phase: "end",
|
|
1027
|
+
attempt: attemptCount,
|
|
1028
|
+
outcome: "ok"
|
|
1029
|
+
});
|
|
1030
|
+
attemptSignal.throwIfAborted();
|
|
1031
|
+
try {
|
|
1032
|
+
observer?.dispatched({ attempt });
|
|
1033
|
+
} catch {}
|
|
1034
|
+
attemptSignal.throwIfAborted();
|
|
1035
|
+
const observed = (async function* () {
|
|
1036
|
+
for await (const chunk of chunks) {
|
|
1037
|
+
reportProgress();
|
|
1038
|
+
yield chunk;
|
|
1039
|
+
}
|
|
1040
|
+
})();
|
|
1041
|
+
for await (const chunk of mapOpenAIStream(observed, options.support, options.model)) {
|
|
1042
|
+
if (chunk.kind === "final") outcome = "ok";
|
|
517
1043
|
yield chunk;
|
|
518
1044
|
}
|
|
519
|
-
}
|
|
1045
|
+
} catch (error) {
|
|
1046
|
+
outcome = attemptSignal.aborted ? "cancelled" : "error";
|
|
1047
|
+
throw error;
|
|
1048
|
+
} finally {
|
|
1049
|
+
if (!firstResponseFinished) observe({
|
|
1050
|
+
stage: "first-response",
|
|
1051
|
+
phase: "end",
|
|
1052
|
+
attempt: attemptCount,
|
|
1053
|
+
outcome
|
|
1054
|
+
});
|
|
1055
|
+
observe({
|
|
1056
|
+
stage: "attempt",
|
|
1057
|
+
phase: "end",
|
|
1058
|
+
attempt: attemptCount,
|
|
1059
|
+
outcome
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
520
1062
|
},
|
|
521
1063
|
classify(error) {
|
|
522
|
-
const portError =
|
|
1064
|
+
const portError = toModelFailure(error, options.support.failures);
|
|
523
1065
|
return {
|
|
524
1066
|
error: portError,
|
|
525
|
-
retryable: portError.retryable,
|
|
1067
|
+
retryable: portError.retryable === true,
|
|
526
1068
|
retryAfterMs: retryAfterMs(error)
|
|
527
1069
|
};
|
|
528
1070
|
}
|
|
@@ -531,106 +1073,11 @@ function createOpenAIModelPort(options) {
|
|
|
531
1073
|
};
|
|
532
1074
|
}
|
|
533
1075
|
//#endregion
|
|
534
|
-
//#region src/protocol/probe.ts
|
|
535
|
-
function baseUrlOf(probe) {
|
|
536
|
-
const configured = probe.config.baseUrl;
|
|
537
|
-
return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
|
|
538
|
-
}
|
|
539
|
-
async function refuse(response) {
|
|
540
|
-
const body = await response.text().catch(() => "");
|
|
541
|
-
throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
|
|
542
|
-
}
|
|
543
|
-
function headers(probe) {
|
|
544
|
-
return {
|
|
545
|
-
authorization: `Bearer ${probe.secrets.apiKey ?? ""}`,
|
|
546
|
-
"content-type": "application/json"
|
|
547
|
-
};
|
|
548
|
-
}
|
|
549
|
-
function record(value) {
|
|
550
|
-
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
551
|
-
}
|
|
552
|
-
function count(value) {
|
|
553
|
-
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
|
|
554
|
-
}
|
|
555
|
-
function strings(value, allowEmpty = false) {
|
|
556
|
-
return Array.isArray(value) && value.every((one) => typeof one === "string") && (allowEmpty || value.length > 0) ? value : void 0;
|
|
557
|
-
}
|
|
558
|
-
/**
|
|
559
|
-
* One listed model as an offer. The family agrees on `id` alone, so every
|
|
560
|
-
* other field is read wherever an endpoint puts it: `context_window` or
|
|
561
|
-
* `context_length`, `max_output_tokens` or `max_output_length`,
|
|
562
|
-
* `input_modalities` or the `supports_*_in` flags, `output_modalities`,
|
|
563
|
-
* `supports_reasoning` or `reasoning` in `supported_features` (which also
|
|
564
|
-
* says `tools`), `temperature` in `supported_sampling_parameters`, and an
|
|
565
|
-
* `effort` object with its levels and default. A default the levels do not
|
|
566
|
-
* list is dropped. A valid feature or sampling list, including an empty one,
|
|
567
|
-
* answers for what it leaves out. Missing or malformed lists remain unknown.
|
|
568
|
-
*/
|
|
569
|
-
function offerOf(row, id) {
|
|
570
|
-
const contextWindow = count(row.context_window) ?? count(row.context_length);
|
|
571
|
-
const maxOutput = count(row.max_output_tokens) ?? count(row.max_output_length);
|
|
572
|
-
const features = strings(row.supported_features, true);
|
|
573
|
-
const sampling = strings(row.supported_sampling_parameters, true);
|
|
574
|
-
const reasoning = typeof row.supports_reasoning === "boolean" ? row.supports_reasoning : features?.includes("reasoning");
|
|
575
|
-
const effort = record(row.effort);
|
|
576
|
-
const efforts = strings(effort?.supported_levels);
|
|
577
|
-
const defaultEffort = typeof effort?.default_level === "string" && efforts?.includes(effort.default_level) ? effort.default_level : void 0;
|
|
578
|
-
const flagged = typeof row.supports_image_in === "boolean" || typeof row.supports_video_in === "boolean" ? [
|
|
579
|
-
"text",
|
|
580
|
-
...row.supports_image_in === true ? ["image"] : [],
|
|
581
|
-
...row.supports_video_in === true ? ["video"] : []
|
|
582
|
-
] : void 0;
|
|
583
|
-
const input = strings(row.input_modalities) ?? flagged;
|
|
584
|
-
const output = strings(row.output_modalities);
|
|
585
|
-
return {
|
|
586
|
-
model: id,
|
|
587
|
-
...typeof row.name === "string" && row.name !== "" ? { name: row.name } : {},
|
|
588
|
-
...contextWindow === void 0 ? {} : { contextWindow },
|
|
589
|
-
...maxOutput === void 0 ? {} : { maxOutput },
|
|
590
|
-
...reasoning === void 0 ? {} : { reasoning },
|
|
591
|
-
...features === void 0 ? {} : { toolCall: features.includes("tools") },
|
|
592
|
-
...sampling === void 0 ? {} : { temperature: sampling.includes("temperature") },
|
|
593
|
-
...input === void 0 ? {} : { input },
|
|
594
|
-
...output === void 0 ? {} : { output },
|
|
595
|
-
...efforts === void 0 ? {} : { efforts },
|
|
596
|
-
...defaultEffort === void 0 ? {} : { defaultEffort }
|
|
597
|
-
};
|
|
598
|
-
}
|
|
599
|
-
const probeOpenAI = {
|
|
600
|
-
async listModels(probe, fetcher = globalThis.fetch) {
|
|
601
|
-
const response = await fetcher(`${baseUrlOf(probe)}/models`, {
|
|
602
|
-
method: "GET",
|
|
603
|
-
headers: headers(probe),
|
|
604
|
-
signal: probe.signal
|
|
605
|
-
});
|
|
606
|
-
if (!response.ok) await refuse(response);
|
|
607
|
-
return ((await response.json()).data ?? []).flatMap((row) => typeof row.id === "string" ? [offerOf(row, row.id)] : []);
|
|
608
|
-
},
|
|
609
|
-
async testConnection(probe, fetcher = globalThis.fetch) {
|
|
610
|
-
if (probe.model !== void 0) {
|
|
611
|
-
const response = await fetcher(`${baseUrlOf(probe)}/chat/completions`, {
|
|
612
|
-
method: "POST",
|
|
613
|
-
headers: headers(probe),
|
|
614
|
-
body: JSON.stringify({
|
|
615
|
-
model: probe.model,
|
|
616
|
-
max_tokens: 1,
|
|
617
|
-
messages: [{
|
|
618
|
-
role: "user",
|
|
619
|
-
content: "ping"
|
|
620
|
-
}]
|
|
621
|
-
}),
|
|
622
|
-
signal: probe.signal
|
|
623
|
-
});
|
|
624
|
-
if (!response.ok) await refuse(response);
|
|
625
|
-
return;
|
|
626
|
-
}
|
|
627
|
-
await probeOpenAI.listModels(probe, fetcher);
|
|
628
|
-
}
|
|
629
|
-
};
|
|
630
|
-
//#endregion
|
|
631
1076
|
//#region src/protocol.ts
|
|
632
1077
|
/** Validated supplier options; no supplier identity is interpreted by this protocol. */
|
|
633
1078
|
const OpenAIProtocolOptions = z.strictObject({
|
|
1079
|
+
allowUnauthenticated: z.boolean().optional(),
|
|
1080
|
+
reasoningReplay: z.enum(["omit", "reasoning-content"]).optional(),
|
|
634
1081
|
thinkingField: z.boolean().optional(),
|
|
635
1082
|
outputLimitField: z.enum(["max_tokens", "max_completion_tokens"]).optional(),
|
|
636
1083
|
promptCacheKey: z.boolean().optional()
|
|
@@ -639,7 +1086,8 @@ const OpenAIProtocolOptions = z.strictObject({
|
|
|
639
1086
|
function openaiProtocolType(support, fetch) {
|
|
640
1087
|
return {
|
|
641
1088
|
type: "openai",
|
|
642
|
-
label: "OpenAI Chat Completions",
|
|
1089
|
+
label: "OpenAI Chat Completions API",
|
|
1090
|
+
logo: protocolLogo,
|
|
643
1091
|
fields: [{
|
|
644
1092
|
key: "baseUrl",
|
|
645
1093
|
kind: "url",
|
|
@@ -650,7 +1098,7 @@ function openaiProtocolType(support, fetch) {
|
|
|
650
1098
|
optionsSchema: OpenAIProtocolOptions,
|
|
651
1099
|
facts,
|
|
652
1100
|
prepareParams: (input) => support.prepareParams(input, facts),
|
|
653
|
-
chat: {
|
|
1101
|
+
adapters: { chat: {
|
|
654
1102
|
fileKinds: ["image"],
|
|
655
1103
|
supportsModel: () => true,
|
|
656
1104
|
createPort(call) {
|
|
@@ -680,23 +1128,695 @@ function openaiProtocolType(support, fetch) {
|
|
|
680
1128
|
})
|
|
681
1129
|
});
|
|
682
1130
|
}
|
|
683
|
-
},
|
|
684
|
-
normalizeListing: (input) =>
|
|
685
|
-
listModels: (probe) => probeOpenAI.listModels(probe, fetch),
|
|
1131
|
+
} },
|
|
1132
|
+
normalizeListing: (input) => normalizeOffers(input),
|
|
1133
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, fetch) }),
|
|
686
1134
|
testConnection: (probe) => probeOpenAI.testConnection(probe, fetch)
|
|
687
1135
|
};
|
|
688
1136
|
}
|
|
689
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
|
|
690
1805
|
//#region src/index.ts
|
|
691
1806
|
/** Protocol extensions contribute no tools. */
|
|
692
1807
|
const TOOL_NAMES = [];
|
|
693
1808
|
const plugin = {
|
|
694
1809
|
name: "@eum-agent/llm-protocol-openai",
|
|
695
|
-
requires: ["
|
|
1810
|
+
requires: ["network"],
|
|
1811
|
+
optionalServices: ["model-support"],
|
|
1812
|
+
provides: ["openai-responses-codec"],
|
|
696
1813
|
apply(ctx) {
|
|
697
|
-
const support = ctx.services.
|
|
1814
|
+
const support = lazySupport(() => ctx.services.find("model-support"));
|
|
698
1815
|
const network = ctx.services.get("network");
|
|
699
|
-
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));
|
|
700
1820
|
}
|
|
701
1821
|
};
|
|
702
1822
|
//#endregion
|