@eum-agent/llm-protocol-openai 1.1.0 → 1.2.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 +1397 -443
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,11 +1,22 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import
|
|
3
|
-
//#region src/
|
|
4
|
-
|
|
5
|
-
const
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
//#region src/connection-fetch.ts
|
|
4
|
+
function withConnectionHeaders(fetch, headers) {
|
|
5
|
+
const configured = Object.entries(headers ?? {});
|
|
6
|
+
if (configured.length === 0) return fetch;
|
|
7
|
+
return (input, init) => {
|
|
8
|
+
const merged = new Headers(input instanceof Request ? input.headers : void 0);
|
|
9
|
+
for (const [name, value] of new Headers(init?.headers)) merged.set(name, value);
|
|
10
|
+
for (const [name, value] of configured) merged.set(name, value);
|
|
11
|
+
return fetch(input, {
|
|
12
|
+
...init,
|
|
13
|
+
headers: merged
|
|
14
|
+
});
|
|
15
|
+
};
|
|
16
|
+
}
|
|
6
17
|
//#endregion
|
|
7
18
|
//#region src/protocol/probe.ts
|
|
8
|
-
async function readBody(response, maxBytes) {
|
|
19
|
+
async function readBody$1(response, maxBytes) {
|
|
9
20
|
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new Error("invalid response budget");
|
|
10
21
|
const declared = response.headers.get("content-length");
|
|
11
22
|
if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
|
|
@@ -43,7 +54,7 @@ function baseUrlOf(probe) {
|
|
|
43
54
|
return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
|
|
44
55
|
}
|
|
45
56
|
async function refuse(response, maxBytes = 8388608) {
|
|
46
|
-
const body = (await readBody(response, maxBytes)).text;
|
|
57
|
+
const body = (await readBody$1(response, maxBytes)).text;
|
|
47
58
|
throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
|
|
48
59
|
}
|
|
49
60
|
function headers(probe) {
|
|
@@ -52,7 +63,7 @@ function headers(probe) {
|
|
|
52
63
|
"content-type": "application/json"
|
|
53
64
|
};
|
|
54
65
|
}
|
|
55
|
-
function record(value) {
|
|
66
|
+
function record$1(value) {
|
|
56
67
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
57
68
|
}
|
|
58
69
|
function count(value) {
|
|
@@ -61,33 +72,52 @@ function count(value) {
|
|
|
61
72
|
function strings(value, allowEmpty = false) {
|
|
62
73
|
return Array.isArray(value) && value.every((one) => typeof one === "string") && (allowEmpty || value.length > 0) ? value : void 0;
|
|
63
74
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
+
const EFFORT_SHAPES = [
|
|
76
|
+
{
|
|
77
|
+
at: (row) => record$1(row.effort),
|
|
78
|
+
levels: "supported_levels",
|
|
79
|
+
fallback: "default_level"
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
at: (row) => record$1(row.reasoning_efforts),
|
|
83
|
+
levels: "valid_efforts",
|
|
84
|
+
fallback: "default_effort"
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
at: (row) => record$1(record$1(row.reasoning)?.effort),
|
|
88
|
+
levels: "valid",
|
|
89
|
+
fallback: "default"
|
|
90
|
+
}
|
|
91
|
+
];
|
|
92
|
+
function effortsOf(row) {
|
|
93
|
+
for (const shape of EFFORT_SHAPES) {
|
|
94
|
+
const object = shape.at(row);
|
|
95
|
+
const efforts = strings(object?.[shape.levels]);
|
|
96
|
+
if (efforts === void 0) continue;
|
|
97
|
+
const fallback = object?.[shape.fallback];
|
|
98
|
+
return typeof fallback === "string" && efforts.includes(fallback) ? {
|
|
99
|
+
efforts,
|
|
100
|
+
defaultEffort: fallback
|
|
101
|
+
} : { efforts };
|
|
102
|
+
}
|
|
103
|
+
return {};
|
|
104
|
+
}
|
|
75
105
|
function offerOf(row, id) {
|
|
76
|
-
const
|
|
106
|
+
const limit = record$1(row.limit);
|
|
107
|
+
const modalities = record$1(row.modalities);
|
|
108
|
+
const contextWindow = count(row.context_window) ?? count(row.context_length) ?? count(limit?.context);
|
|
77
109
|
const maxOutput = count(row.max_output_tokens) ?? count(row.max_output_length);
|
|
78
110
|
const features = strings(row.supported_features, true);
|
|
79
111
|
const sampling = strings(row.supported_sampling_parameters, true);
|
|
80
112
|
const reasoning = typeof row.supports_reasoning === "boolean" ? row.supports_reasoning : features?.includes("reasoning");
|
|
81
|
-
const
|
|
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;
|
|
113
|
+
const { efforts, defaultEffort } = effortsOf(row);
|
|
84
114
|
const flagged = typeof row.supports_image_in === "boolean" || typeof row.supports_video_in === "boolean" ? [
|
|
85
115
|
"text",
|
|
86
116
|
...row.supports_image_in === true ? ["image"] : [],
|
|
87
117
|
...row.supports_video_in === true ? ["video"] : []
|
|
88
118
|
] : void 0;
|
|
89
|
-
const input = strings(row.input_modalities) ?? flagged;
|
|
90
|
-
const output = strings(row.output_modalities);
|
|
119
|
+
const input = strings(row.input_modalities) ?? flagged ?? strings(modalities?.input);
|
|
120
|
+
const output = strings(row.output_modalities) ?? strings(modalities?.output);
|
|
91
121
|
return {
|
|
92
122
|
model: id,
|
|
93
123
|
...typeof row.name === "string" && row.name !== "" ? { name: row.name } : {},
|
|
@@ -110,45 +140,558 @@ const probeOpenAI = {
|
|
|
110
140
|
signal: probe.signal
|
|
111
141
|
});
|
|
112
142
|
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)] : []);
|
|
143
|
+
return (JSON.parse((await readBody$1(response, probe.maxResponseBytes ?? 8388608)).text).data ?? []).flatMap((row) => typeof row.id === "string" ? [offerOf(row, row.id)] : []);
|
|
114
144
|
},
|
|
115
145
|
async testConnection(probe, fetcher = globalThis.fetch, protocol = "chat-completions") {
|
|
116
146
|
if (probe.model !== void 0) {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
147
|
+
probe.signal.throwIfAborted();
|
|
148
|
+
const attempt = probe.accountingDispatch?.attempt(0);
|
|
149
|
+
let succeeded = false;
|
|
150
|
+
let submitted = false;
|
|
151
|
+
try {
|
|
152
|
+
const response = await fetcher(`${baseUrlOf(probe)}/${protocol === "responses" ? "responses" : "chat/completions"}`, {
|
|
153
|
+
method: "POST",
|
|
154
|
+
headers: headers(probe),
|
|
155
|
+
body: JSON.stringify(protocol === "responses" ? {
|
|
156
|
+
model: probe.model,
|
|
157
|
+
input: [{
|
|
158
|
+
role: "user",
|
|
159
|
+
content: "ping"
|
|
160
|
+
}],
|
|
161
|
+
max_output_tokens: 16,
|
|
162
|
+
store: false
|
|
163
|
+
} : {
|
|
164
|
+
model: probe.model,
|
|
165
|
+
max_tokens: 1,
|
|
166
|
+
messages: [{
|
|
167
|
+
role: "user",
|
|
168
|
+
content: "ping"
|
|
169
|
+
}]
|
|
170
|
+
}),
|
|
171
|
+
signal: probe.signal
|
|
172
|
+
});
|
|
173
|
+
submitted = true;
|
|
174
|
+
const received = await readBody$1(response, probe.maxResponseBytes ?? 8388608);
|
|
175
|
+
if (attempt && received.text) try {
|
|
176
|
+
const usage = record$1(record$1(JSON.parse(received.text))?.usage);
|
|
177
|
+
if (usage) {
|
|
178
|
+
const field = (value) => typeof value === "number" ? value : void 0;
|
|
179
|
+
const details = record$1(usage.prompt_tokens_details ?? usage.input_tokens_details);
|
|
180
|
+
attempt.report({
|
|
181
|
+
sequence: 1,
|
|
182
|
+
inputTokens: field(usage.prompt_tokens ?? usage.input_tokens),
|
|
183
|
+
outputTokens: field(usage.completion_tokens ?? usage.output_tokens),
|
|
184
|
+
totalTokens: field(usage.total_tokens),
|
|
185
|
+
cacheReadTokens: field(details?.cached_tokens ?? usage.prompt_cache_hit_tokens)
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
} catch {}
|
|
189
|
+
if (!response.ok) throw Object.assign(new Error(received.text || response.statusText), { status: response.status });
|
|
190
|
+
succeeded = true;
|
|
191
|
+
return;
|
|
192
|
+
} finally {
|
|
193
|
+
attempt?.end({
|
|
194
|
+
outcome: succeeded ? "success" : probe.signal.aborted ? "cancelled" : "failed",
|
|
195
|
+
submission: submitted ? "submitted" : "unknown"
|
|
196
|
+
});
|
|
197
|
+
}
|
|
141
198
|
}
|
|
142
199
|
await probeOpenAI.listModels(probe, fetcher);
|
|
143
200
|
}
|
|
144
201
|
};
|
|
145
202
|
//#endregion
|
|
203
|
+
//#region src/decisions/body.ts
|
|
204
|
+
var ResponseBodyLimitError = class extends Error {};
|
|
205
|
+
async function cancelBody(response) {
|
|
206
|
+
try {
|
|
207
|
+
await response.body?.cancel();
|
|
208
|
+
} catch {}
|
|
209
|
+
}
|
|
210
|
+
async function readBody(response, maxBytes, signal) {
|
|
211
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
|
|
212
|
+
await cancelBody(response);
|
|
213
|
+
throw new ResponseBodyLimitError("Invalid response byte budget.");
|
|
214
|
+
}
|
|
215
|
+
const declared = response.headers.get("content-length");
|
|
216
|
+
if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
|
|
217
|
+
await cancelBody(response);
|
|
218
|
+
throw new ResponseBodyLimitError("Response exceeds its byte budget.");
|
|
219
|
+
}
|
|
220
|
+
if (!response.body) {
|
|
221
|
+
signal.throwIfAborted();
|
|
222
|
+
return "";
|
|
223
|
+
}
|
|
224
|
+
const reader = response.body.getReader();
|
|
225
|
+
const decoder = new TextDecoder();
|
|
226
|
+
let bytes = 0;
|
|
227
|
+
let text = "";
|
|
228
|
+
let cancellation;
|
|
229
|
+
const abort = () => {
|
|
230
|
+
cancellation ??= reader.cancel().catch(() => {});
|
|
231
|
+
};
|
|
232
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
233
|
+
try {
|
|
234
|
+
if (signal.aborted) abort();
|
|
235
|
+
for (;;) {
|
|
236
|
+
signal.throwIfAborted();
|
|
237
|
+
const next = await reader.read();
|
|
238
|
+
signal.throwIfAborted();
|
|
239
|
+
if (next.done) return text + decoder.decode();
|
|
240
|
+
bytes += next.value.byteLength;
|
|
241
|
+
if (bytes > maxBytes) throw new ResponseBodyLimitError("Response exceeds its byte budget.");
|
|
242
|
+
text += decoder.decode(next.value, { stream: true });
|
|
243
|
+
}
|
|
244
|
+
} catch (error) {
|
|
245
|
+
await (cancellation ?? reader.cancel().catch(() => {}));
|
|
246
|
+
throw error;
|
|
247
|
+
} finally {
|
|
248
|
+
signal.removeEventListener("abort", abort);
|
|
249
|
+
reader.releaseLock();
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
//#endregion
|
|
253
|
+
//#region src/decisions/failure.ts
|
|
254
|
+
function openAIDecisionsFailure(code, message, retryable = false) {
|
|
255
|
+
const error = new Error(message);
|
|
256
|
+
error.name = "DecisionFailure";
|
|
257
|
+
Object.assign(error, {
|
|
258
|
+
code,
|
|
259
|
+
retryable
|
|
260
|
+
});
|
|
261
|
+
return error;
|
|
262
|
+
}
|
|
263
|
+
function openAIDecisionsStatusFailure(status) {
|
|
264
|
+
if (status === 401 || status === 403) return openAIDecisionsFailure("credential-unavailable", "The connection credential was rejected.");
|
|
265
|
+
if (status === 429) return openAIDecisionsFailure("quota", "The decision service rate or quota limit was reached.", true);
|
|
266
|
+
if (status === 408 || status === 504) return openAIDecisionsFailure("timeout", "The decision service did not answer in time.", true);
|
|
267
|
+
return openAIDecisionsFailure("provider", "The decision service request failed.");
|
|
268
|
+
}
|
|
269
|
+
//#endregion
|
|
270
|
+
//#region src/decisions/request.ts
|
|
271
|
+
function questionOf(name, question) {
|
|
272
|
+
if (question.type === "noul") return {
|
|
273
|
+
name,
|
|
274
|
+
type: "predicate",
|
|
275
|
+
instructions: question.criteria ? `${question.instructions}\n\nOutcome criteria:\n${JSON.stringify(question.criteria)}` : question.instructions
|
|
276
|
+
};
|
|
277
|
+
if (question.type === "choice") return {
|
|
278
|
+
name,
|
|
279
|
+
type: "choice",
|
|
280
|
+
instructions: question.instructions,
|
|
281
|
+
choices: Object.entries(question.criteria).map(([value, description]) => ({
|
|
282
|
+
value,
|
|
283
|
+
...description === null ? {} : { description }
|
|
284
|
+
}))
|
|
285
|
+
};
|
|
286
|
+
return {
|
|
287
|
+
name,
|
|
288
|
+
type: "score",
|
|
289
|
+
instructions: question.instructions,
|
|
290
|
+
levels: question.criteria.map((label) => ({ label }))
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
function buildOpenAIDecisionsRequest(request, model) {
|
|
294
|
+
const content = [{
|
|
295
|
+
type: "input_text",
|
|
296
|
+
text: typeof request.state === "string" ? request.state : JSON.stringify(request.state)
|
|
297
|
+
}];
|
|
298
|
+
for (const image of request.images) {
|
|
299
|
+
content.push({
|
|
300
|
+
type: "input_text",
|
|
301
|
+
text: `[image: ${image.label}]`
|
|
302
|
+
});
|
|
303
|
+
content.push({
|
|
304
|
+
type: "input_image",
|
|
305
|
+
image_url: `data:${image.mediaType};base64,${Buffer.from(image.bytes).toString("base64")}`
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
model,
|
|
310
|
+
input: [{
|
|
311
|
+
role: "user",
|
|
312
|
+
content
|
|
313
|
+
}],
|
|
314
|
+
questions: Object.entries(request.questions).map(([name, question]) => questionOf(name, question))
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/decisions/response.ts
|
|
319
|
+
const INVALID = "The decision service returned an unusable answer.";
|
|
320
|
+
function invalid$1() {
|
|
321
|
+
return openAIDecisionsFailure("invalid-response", INVALID);
|
|
322
|
+
}
|
|
323
|
+
function probability(value) {
|
|
324
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) throw invalid$1();
|
|
325
|
+
return value;
|
|
326
|
+
}
|
|
327
|
+
function distribution(value, question) {
|
|
328
|
+
const keys = Object.keys(question.criteria);
|
|
329
|
+
if (!Array.isArray(value) || value.length !== keys.length) throw invalid$1();
|
|
330
|
+
const result = Object.create(null);
|
|
331
|
+
for (const entry of value) {
|
|
332
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw invalid$1();
|
|
333
|
+
const raw = entry;
|
|
334
|
+
if (question.type === "choice" ? typeof raw.value !== "string" : typeof raw.value !== "number" || !Number.isInteger(raw.value)) throw invalid$1();
|
|
335
|
+
const key = String(raw.value);
|
|
336
|
+
if (!keys.includes(key) || Object.hasOwn(result, key)) throw invalid$1();
|
|
337
|
+
if (question.type === "score" && raw.label !== question.criteria[Number(key)]) throw invalid$1();
|
|
338
|
+
result[key] = probability(raw.probability);
|
|
339
|
+
}
|
|
340
|
+
return result;
|
|
341
|
+
}
|
|
342
|
+
function answerOf(raw, question) {
|
|
343
|
+
if (raw.type !== (question.type === "noul" ? "predicate" : question.type)) throw invalid$1();
|
|
344
|
+
if (question.type === "noul") return {
|
|
345
|
+
type: "noul",
|
|
346
|
+
probability: probability(raw.probability)
|
|
347
|
+
};
|
|
348
|
+
const keys = Object.keys(question.criteria);
|
|
349
|
+
const probabilities = distribution(raw.probabilities, question);
|
|
350
|
+
const confidence = raw.confidence === void 0 ? {} : { confidence: probability(raw.confidence) };
|
|
351
|
+
if (question.type === "choice") {
|
|
352
|
+
if (typeof raw.choice !== "string" || !keys.includes(raw.choice)) throw invalid$1();
|
|
353
|
+
return {
|
|
354
|
+
type: "choice",
|
|
355
|
+
choice: raw.choice,
|
|
356
|
+
probabilities,
|
|
357
|
+
...confidence
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
const score = raw.score;
|
|
361
|
+
if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || score > keys.length - 1) throw invalid$1();
|
|
362
|
+
const expected = question.criteria.reduce((total, _level, index) => total + index * probabilities[String(index)], 0);
|
|
363
|
+
if (Math.abs(expected - score) > 1e-6) throw invalid$1();
|
|
364
|
+
return {
|
|
365
|
+
type: "score",
|
|
366
|
+
score,
|
|
367
|
+
probabilities,
|
|
368
|
+
...confidence
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
function normalizeOpenAIDecisionsResponse(payload, request) {
|
|
372
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) throw invalid$1();
|
|
373
|
+
const envelope = payload;
|
|
374
|
+
const list = envelope.answers;
|
|
375
|
+
if (!Array.isArray(list)) throw invalid$1();
|
|
376
|
+
const ids = Object.keys(request.questions);
|
|
377
|
+
if (list.length !== ids.length) throw invalid$1();
|
|
378
|
+
const normalized = Object.create(null);
|
|
379
|
+
for (const item of list) {
|
|
380
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) throw invalid$1();
|
|
381
|
+
const raw = item;
|
|
382
|
+
const name = raw.name;
|
|
383
|
+
if (typeof name !== "string" || !Object.hasOwn(request.questions, name)) throw invalid$1();
|
|
384
|
+
if (Object.hasOwn(normalized, name)) throw invalid$1();
|
|
385
|
+
normalized[name] = answerOf(raw, request.questions[name]);
|
|
386
|
+
}
|
|
387
|
+
const usage = envelope.usage;
|
|
388
|
+
if (usage === void 0) return { answers: normalized };
|
|
389
|
+
if (!usage || typeof usage !== "object") throw invalid$1();
|
|
390
|
+
const inputTokens = usage.input_tokens;
|
|
391
|
+
if (inputTokens === void 0) return { answers: normalized };
|
|
392
|
+
if (typeof inputTokens !== "number" || !Number.isInteger(inputTokens) || inputTokens < 0) throw invalid$1();
|
|
393
|
+
return {
|
|
394
|
+
answers: normalized,
|
|
395
|
+
usage: { inputTokens }
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
//#endregion
|
|
399
|
+
//#region src/decisions/protocol.ts
|
|
400
|
+
const TIMEOUT_MS$1 = 6e4;
|
|
401
|
+
const RESPONSE_LIMIT$1 = 8388608;
|
|
402
|
+
const options$1 = z.strictObject({ timeoutMs: z.number().int().min(1e3).max(3e5).optional() });
|
|
403
|
+
function decisionsProtocolType(networkFetch) {
|
|
404
|
+
return {
|
|
405
|
+
type: "openai-decisions",
|
|
406
|
+
label: "OpenAI Decisions API",
|
|
407
|
+
fields: [{
|
|
408
|
+
key: "baseUrl",
|
|
409
|
+
kind: "url",
|
|
410
|
+
label: "Base URL",
|
|
411
|
+
required: true
|
|
412
|
+
}],
|
|
413
|
+
userConfigurable: true,
|
|
414
|
+
optionsSchema: options$1,
|
|
415
|
+
adapters: { decision: {
|
|
416
|
+
limits: () => ({
|
|
417
|
+
images: true,
|
|
418
|
+
maxQuestions: 32,
|
|
419
|
+
maxChoiceOptions: 20,
|
|
420
|
+
maxScoreLevels: 10
|
|
421
|
+
}),
|
|
422
|
+
async evaluate({ request, signal, call }) {
|
|
423
|
+
if (signal.aborted) throw openAIDecisionsFailure("cancelled", "The decision request was cancelled.");
|
|
424
|
+
const timeoutMs = options$1.parse(call.options).timeoutMs ?? TIMEOUT_MS$1;
|
|
425
|
+
const baseUrl = typeof call.config.baseUrl === "string" ? call.config.baseUrl : "";
|
|
426
|
+
if (!baseUrl) throw openAIDecisionsFailure("unavailable", "The connection has no address.");
|
|
427
|
+
const apiKey = call.secrets.apiKey;
|
|
428
|
+
if (!apiKey) throw openAIDecisionsFailure("credential-unavailable", "The connection credential is missing.");
|
|
429
|
+
const body = buildOpenAIDecisionsRequest(request, call.model);
|
|
430
|
+
const deadline = AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
|
|
431
|
+
const accounting = call.accountingDispatch?.attempt(0);
|
|
432
|
+
let outcome = "failed";
|
|
433
|
+
let submission = "unknown";
|
|
434
|
+
try {
|
|
435
|
+
let response;
|
|
436
|
+
try {
|
|
437
|
+
response = await withConnectionHeaders(networkFetch, call.headers)(`${baseUrl.replace(/\/+$/, "")}/decisions`, {
|
|
438
|
+
method: "POST",
|
|
439
|
+
headers: {
|
|
440
|
+
"Content-Type": "application/json",
|
|
441
|
+
Authorization: `Bearer ${apiKey}`
|
|
442
|
+
},
|
|
443
|
+
body: JSON.stringify(body),
|
|
444
|
+
signal: deadline
|
|
445
|
+
});
|
|
446
|
+
} catch {
|
|
447
|
+
if (signal.aborted) throw openAIDecisionsFailure("cancelled", "The decision request was cancelled.");
|
|
448
|
+
if (deadline.aborted) throw openAIDecisionsFailure("timeout", "The decision service timed out.", true);
|
|
449
|
+
throw openAIDecisionsFailure("network", "The decision service could not be reached.", true);
|
|
450
|
+
}
|
|
451
|
+
submission = "submitted";
|
|
452
|
+
if (!response.ok) {
|
|
453
|
+
await cancelBody(response);
|
|
454
|
+
throw openAIDecisionsStatusFailure(response.status);
|
|
455
|
+
}
|
|
456
|
+
let text;
|
|
457
|
+
try {
|
|
458
|
+
text = await readBody(response, RESPONSE_LIMIT$1, deadline);
|
|
459
|
+
} catch (error) {
|
|
460
|
+
if (error instanceof ResponseBodyLimitError) throw openAIDecisionsFailure("invalid-response", "The decision service response was too large.");
|
|
461
|
+
if (signal.aborted) throw openAIDecisionsFailure("cancelled", "The decision request was cancelled.");
|
|
462
|
+
if (deadline.aborted) throw openAIDecisionsFailure("timeout", "The decision service timed out.", true);
|
|
463
|
+
throw openAIDecisionsFailure("network", "The decision response could not be read.");
|
|
464
|
+
}
|
|
465
|
+
let payload;
|
|
466
|
+
try {
|
|
467
|
+
payload = JSON.parse(text);
|
|
468
|
+
} catch {
|
|
469
|
+
throw openAIDecisionsFailure("invalid-response", "The decision service response was not JSON.");
|
|
470
|
+
}
|
|
471
|
+
const usage = payload && typeof payload === "object" ? payload.usage : void 0;
|
|
472
|
+
if (typeof usage?.input_tokens === "number") accounting?.report({
|
|
473
|
+
sequence: 1,
|
|
474
|
+
inputTokens: usage.input_tokens
|
|
475
|
+
});
|
|
476
|
+
const result = normalizeOpenAIDecisionsResponse(payload, request);
|
|
477
|
+
outcome = "success";
|
|
478
|
+
return result;
|
|
479
|
+
} finally {
|
|
480
|
+
accounting?.end({
|
|
481
|
+
outcome: signal.aborted ? "cancelled" : outcome,
|
|
482
|
+
submission
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
} },
|
|
487
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, withConnectionHeaders(networkFetch, probe.headers)) }),
|
|
488
|
+
testConnection: (probe) => probeOpenAI.listModels(probe, withConnectionHeaders(networkFetch, probe.headers)).then(() => {})
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
//#endregion
|
|
492
|
+
//#region src/embeddings/failure.ts
|
|
493
|
+
function openAIEmbeddingsFailure(code, message, retryable = false) {
|
|
494
|
+
const error = new Error(message);
|
|
495
|
+
error.name = "EmbeddingFailure";
|
|
496
|
+
return Object.assign(error, {
|
|
497
|
+
code,
|
|
498
|
+
retryable
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
function openAIEmbeddingsStatusFailure(status) {
|
|
502
|
+
if (status === 401 || status === 403) return openAIEmbeddingsFailure("credential-unavailable", "The connection credential was rejected.");
|
|
503
|
+
if (status === 429) return openAIEmbeddingsFailure("quota", "The embedding service rate or quota limit was reached.", true);
|
|
504
|
+
if (status === 408 || status === 504) return openAIEmbeddingsFailure("timeout", "The embedding service did not answer in time.", true);
|
|
505
|
+
return openAIEmbeddingsFailure("provider", "The embedding service request failed.");
|
|
506
|
+
}
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region src/embeddings/models.ts
|
|
509
|
+
const shared = {
|
|
510
|
+
inputKinds: ["text"],
|
|
511
|
+
maxInputs: 2048,
|
|
512
|
+
maxInputTokens: 8192,
|
|
513
|
+
maxBatchInputTokens: 3e5,
|
|
514
|
+
purposeAware: false,
|
|
515
|
+
normalized: true
|
|
516
|
+
};
|
|
517
|
+
const openAIEmbeddingModels = {
|
|
518
|
+
"text-embedding-3-small": {
|
|
519
|
+
...shared,
|
|
520
|
+
dimensions: {
|
|
521
|
+
default: 1536,
|
|
522
|
+
range: {
|
|
523
|
+
min: 1,
|
|
524
|
+
max: 1536
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
},
|
|
528
|
+
"text-embedding-3-large": {
|
|
529
|
+
...shared,
|
|
530
|
+
dimensions: {
|
|
531
|
+
default: 3072,
|
|
532
|
+
range: {
|
|
533
|
+
min: 1,
|
|
534
|
+
max: 3072
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
function openAIEmbeddingLimits(model) {
|
|
540
|
+
return Object.hasOwn(openAIEmbeddingModels, model) ? openAIEmbeddingModels[model] : void 0;
|
|
541
|
+
}
|
|
542
|
+
//#endregion
|
|
543
|
+
//#region src/embeddings/request.ts
|
|
544
|
+
function buildOpenAIEmbeddingsRequest(request, model, params) {
|
|
545
|
+
return {
|
|
546
|
+
model,
|
|
547
|
+
input: request.inputs.map((one) => one.text),
|
|
548
|
+
encoding_format: "float",
|
|
549
|
+
...typeof params.dimensions === "number" ? { dimensions: params.dimensions } : {}
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
//#endregion
|
|
553
|
+
//#region src/embeddings/response.ts
|
|
554
|
+
function invalid() {
|
|
555
|
+
return openAIEmbeddingsFailure("invalid-response", "The embedding service returned an unusable response.");
|
|
556
|
+
}
|
|
557
|
+
function record(value) {
|
|
558
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid();
|
|
559
|
+
return value;
|
|
560
|
+
}
|
|
561
|
+
function normalizeOpenAIEmbeddingsResponse(payload, inputCount) {
|
|
562
|
+
const envelope = record(payload);
|
|
563
|
+
const data = envelope.data;
|
|
564
|
+
if (!Array.isArray(data) || data.length !== inputCount) throw invalid();
|
|
565
|
+
const vectors = new Array(inputCount);
|
|
566
|
+
for (const item of data) {
|
|
567
|
+
const raw = record(item);
|
|
568
|
+
const index = raw.index;
|
|
569
|
+
if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= inputCount || vectors[index] !== void 0) throw invalid();
|
|
570
|
+
const values = raw.embedding;
|
|
571
|
+
if (!Array.isArray(values) || !values.every((one) => typeof one === "number")) throw invalid();
|
|
572
|
+
vectors[index] = Float32Array.from(values);
|
|
573
|
+
}
|
|
574
|
+
const usage = envelope.usage;
|
|
575
|
+
if (usage === void 0) return { vectors };
|
|
576
|
+
const inputTokens = record(usage).prompt_tokens;
|
|
577
|
+
if (inputTokens === void 0) return { vectors };
|
|
578
|
+
if (typeof inputTokens !== "number" || !Number.isInteger(inputTokens) || inputTokens < 0) throw invalid();
|
|
579
|
+
return {
|
|
580
|
+
vectors,
|
|
581
|
+
usage: { inputTokens }
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
//#endregion
|
|
585
|
+
//#region src/embeddings/protocol.ts
|
|
586
|
+
const TIMEOUT_MS = 6e4;
|
|
587
|
+
const RESPONSE_LIMIT = 67108864;
|
|
588
|
+
const options = z.strictObject({ timeoutMs: z.number().int().min(1e3).max(3e5).optional() });
|
|
589
|
+
function cancelled() {
|
|
590
|
+
return openAIEmbeddingsFailure("cancelled", "The embedding request was cancelled.");
|
|
591
|
+
}
|
|
592
|
+
function timedOut() {
|
|
593
|
+
return openAIEmbeddingsFailure("timeout", "The embedding service timed out.", true);
|
|
594
|
+
}
|
|
595
|
+
function embeddingsProtocolType(networkFetch) {
|
|
596
|
+
return {
|
|
597
|
+
type: "openai-embeddings",
|
|
598
|
+
label: "OpenAI Embeddings API",
|
|
599
|
+
fields: [{
|
|
600
|
+
key: "baseUrl",
|
|
601
|
+
kind: "url",
|
|
602
|
+
label: "Base URL",
|
|
603
|
+
required: true
|
|
604
|
+
}],
|
|
605
|
+
userConfigurable: true,
|
|
606
|
+
optionsSchema: options,
|
|
607
|
+
adapters: { embedding: {
|
|
608
|
+
limits({ ref }) {
|
|
609
|
+
const limits = openAIEmbeddingLimits(ref.model);
|
|
610
|
+
if (!limits) throw openAIEmbeddingsFailure("unsupported", "The embedding model is not supported.");
|
|
611
|
+
return limits;
|
|
612
|
+
},
|
|
613
|
+
async embed({ request, params, signal, call }) {
|
|
614
|
+
if (signal.aborted) throw cancelled();
|
|
615
|
+
const timeoutMs = options.parse(call.options).timeoutMs ?? TIMEOUT_MS;
|
|
616
|
+
const baseUrl = typeof call.config.baseUrl === "string" ? call.config.baseUrl : "";
|
|
617
|
+
if (!baseUrl) throw openAIEmbeddingsFailure("unavailable", "The connection has no address.");
|
|
618
|
+
const apiKey = call.secrets.apiKey;
|
|
619
|
+
if (!apiKey) throw openAIEmbeddingsFailure("credential-unavailable", "The connection credential is missing.");
|
|
620
|
+
const body = buildOpenAIEmbeddingsRequest(request, call.model, params);
|
|
621
|
+
const deadline = AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
|
|
622
|
+
const accounting = call.accountingDispatch?.attempt(0);
|
|
623
|
+
let outcome = "failed";
|
|
624
|
+
let submission = "unknown";
|
|
625
|
+
try {
|
|
626
|
+
let response;
|
|
627
|
+
try {
|
|
628
|
+
response = await withConnectionHeaders(networkFetch, call.headers)(`${baseUrl.replace(/\/+$/, "")}/embeddings`, {
|
|
629
|
+
method: "POST",
|
|
630
|
+
headers: {
|
|
631
|
+
"Content-Type": "application/json",
|
|
632
|
+
Authorization: `Bearer ${apiKey}`
|
|
633
|
+
},
|
|
634
|
+
body: JSON.stringify(body),
|
|
635
|
+
signal: deadline
|
|
636
|
+
});
|
|
637
|
+
} catch {
|
|
638
|
+
if (signal.aborted) throw cancelled();
|
|
639
|
+
if (deadline.aborted) throw timedOut();
|
|
640
|
+
throw openAIEmbeddingsFailure("network", "The embedding service could not be reached.", true);
|
|
641
|
+
}
|
|
642
|
+
submission = "submitted";
|
|
643
|
+
if (!response.ok) {
|
|
644
|
+
await cancelBody(response);
|
|
645
|
+
throw openAIEmbeddingsStatusFailure(response.status);
|
|
646
|
+
}
|
|
647
|
+
let text;
|
|
648
|
+
try {
|
|
649
|
+
text = await readBody(response, RESPONSE_LIMIT, deadline);
|
|
650
|
+
} catch (error) {
|
|
651
|
+
if (error instanceof ResponseBodyLimitError) throw openAIEmbeddingsFailure("invalid-response", "The embedding service response was too large.");
|
|
652
|
+
if (signal.aborted) throw cancelled();
|
|
653
|
+
if (deadline.aborted) throw timedOut();
|
|
654
|
+
throw openAIEmbeddingsFailure("network", "The embedding response could not be read.");
|
|
655
|
+
}
|
|
656
|
+
let payload;
|
|
657
|
+
try {
|
|
658
|
+
payload = JSON.parse(text);
|
|
659
|
+
} catch {
|
|
660
|
+
throw openAIEmbeddingsFailure("invalid-response", "The embedding service response was not JSON.");
|
|
661
|
+
}
|
|
662
|
+
const tokens = payload && typeof payload === "object" ? payload.usage?.prompt_tokens : void 0;
|
|
663
|
+
if (typeof tokens === "number" && Number.isInteger(tokens) && tokens >= 0) accounting?.report({
|
|
664
|
+
sequence: 1,
|
|
665
|
+
inputTokens: tokens
|
|
666
|
+
});
|
|
667
|
+
const result = normalizeOpenAIEmbeddingsResponse(payload, request.inputs.length);
|
|
668
|
+
outcome = "success";
|
|
669
|
+
return result;
|
|
670
|
+
} finally {
|
|
671
|
+
accounting?.end({
|
|
672
|
+
outcome: signal.aborted ? "cancelled" : outcome,
|
|
673
|
+
submission
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
} },
|
|
678
|
+
listModels: async (probe) => ({ offers: (await probeOpenAI.listModels(probe, withConnectionHeaders(networkFetch, probe.headers))).filter((offer) => openAIEmbeddingLimits(offer.model) !== void 0) }),
|
|
679
|
+
testConnection: (probe) => probeOpenAI.listModels(probe, withConnectionHeaders(networkFetch, probe.headers)).then(() => {})
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
//#endregion
|
|
683
|
+
//#region src/logo.ts
|
|
684
|
+
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";
|
|
685
|
+
//#endregion
|
|
146
686
|
//#region src/support.ts
|
|
147
|
-
|
|
687
|
+
function inputLimit(offer) {
|
|
688
|
+
return Number.isSafeInteger(offer.inputLimit) && Number(offer.inputLimit) > 0 ? offer.inputLimit : void 0;
|
|
689
|
+
}
|
|
148
690
|
function normalizeOffers(input) {
|
|
149
691
|
return Object.fromEntries(input.offers.map((offer) => [offer.model, {
|
|
150
692
|
id: offer.model,
|
|
151
693
|
...offer.name === void 0 ? {} : { name: offer.name },
|
|
694
|
+
...offer.chat === void 0 ? {} : { chat: offer.chat },
|
|
152
695
|
...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
|
|
153
696
|
...offer.efforts?.length ? { reasoning_options: [{
|
|
154
697
|
type: "effort",
|
|
@@ -161,14 +704,14 @@ function normalizeOffers(input) {
|
|
|
161
704
|
...offer.input === void 0 ? {} : { input: [...offer.input] },
|
|
162
705
|
...offer.output === void 0 ? {} : { output: [...offer.output] }
|
|
163
706
|
} },
|
|
164
|
-
...!offer.contextWindow && !offer.maxOutput ? {} : { limit: {
|
|
707
|
+
...!offer.contextWindow && inputLimit(offer) === void 0 && !offer.maxOutput ? {} : { limit: {
|
|
165
708
|
...offer.contextWindow && offer.contextWindow > 0 ? { context: offer.contextWindow } : {},
|
|
709
|
+
...inputLimit(offer) === void 0 ? {} : { input: inputLimit(offer) },
|
|
166
710
|
...offer.maxOutput && offer.maxOutput > 0 ? { output: offer.maxOutput } : {}
|
|
167
711
|
} },
|
|
168
712
|
...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
|
|
169
713
|
}]));
|
|
170
714
|
}
|
|
171
|
-
/** The owner-qualified accessor is read per operation; withdrawal never exposes an old service. */
|
|
172
715
|
function lazySupport(read) {
|
|
173
716
|
return new Proxy({}, { get(_target, key) {
|
|
174
717
|
if (key === "normalizeListing") return normalizeOffers;
|
|
@@ -180,7 +723,22 @@ function lazySupport(read) {
|
|
|
180
723
|
}
|
|
181
724
|
//#endregion
|
|
182
725
|
//#region src/images/port.ts
|
|
183
|
-
|
|
726
|
+
const text = (en, zh) => ({
|
|
727
|
+
"en-US": en,
|
|
728
|
+
"zh-CN": zh
|
|
729
|
+
});
|
|
730
|
+
const auto = text("Auto", "\u81ea\u52a8");
|
|
731
|
+
const qualityPresentation = { options: {
|
|
732
|
+
auto,
|
|
733
|
+
low: text("Low", "\u4f4e"),
|
|
734
|
+
medium: text("Medium", "\u4e2d"),
|
|
735
|
+
high: text("High", "\u9ad8"),
|
|
736
|
+
xhigh: text("Very high", "\u5f88\u9ad8"),
|
|
737
|
+
max: text("Maximum", "\u6700\u9ad8"),
|
|
738
|
+
standard: text("Standard", "\u6807\u51c6"),
|
|
739
|
+
hd: text("HD", "\u9ad8\u6e05")
|
|
740
|
+
} };
|
|
741
|
+
const sizePresentation = { options: { auto } };
|
|
184
742
|
const imageParamsSchema = z.strictObject({
|
|
185
743
|
size: z.enum([
|
|
186
744
|
"auto",
|
|
@@ -191,7 +749,7 @@ const imageParamsSchema = z.strictObject({
|
|
|
191
749
|
"1024x1536",
|
|
192
750
|
"1792x1024",
|
|
193
751
|
"1024x1792"
|
|
194
|
-
]).optional(),
|
|
752
|
+
]).optional().meta({ presentation: sizePresentation }),
|
|
195
753
|
quality: z.enum([
|
|
196
754
|
"auto",
|
|
197
755
|
"low",
|
|
@@ -201,12 +759,16 @@ const imageParamsSchema = z.strictObject({
|
|
|
201
759
|
"max",
|
|
202
760
|
"standard",
|
|
203
761
|
"hd"
|
|
204
|
-
]).optional(),
|
|
762
|
+
]).optional().meta({ presentation: qualityPresentation }),
|
|
205
763
|
background: z.enum([
|
|
206
764
|
"auto",
|
|
207
765
|
"transparent",
|
|
208
766
|
"opaque"
|
|
209
|
-
]).optional()
|
|
767
|
+
]).optional().meta({ presentation: { options: {
|
|
768
|
+
auto,
|
|
769
|
+
transparent: text("Transparent", "\u900f\u660e"),
|
|
770
|
+
opaque: text("Opaque", "\u4e0d\u900f\u660e")
|
|
771
|
+
} } }),
|
|
210
772
|
outputFormat: z.enum([
|
|
211
773
|
"png",
|
|
212
774
|
"jpeg",
|
|
@@ -214,7 +776,6 @@ const imageParamsSchema = z.strictObject({
|
|
|
214
776
|
]).optional(),
|
|
215
777
|
n: z.number().int().min(1).max(8).optional()
|
|
216
778
|
});
|
|
217
|
-
/** Narrows official GPT image settings while keeping explicit custom model profiles usable. */
|
|
218
779
|
function imageParamsFor(model) {
|
|
219
780
|
if (!isGptImage(model)) return imageParamsSchema;
|
|
220
781
|
return imageParamsSchema.extend({
|
|
@@ -223,20 +784,20 @@ function imageParamsFor(model) {
|
|
|
223
784
|
"1024x1024",
|
|
224
785
|
"1536x1024",
|
|
225
786
|
"1024x1536"
|
|
226
|
-
]).optional(),
|
|
227
|
-
quality: model.startsWith("gpt-image-2.5-") ? z.enum([
|
|
787
|
+
]).optional().meta({ presentation: sizePresentation }),
|
|
788
|
+
quality: (model.startsWith("gpt-image-2.5-") ? z.enum([
|
|
228
789
|
"auto",
|
|
229
790
|
"low",
|
|
230
791
|
"medium",
|
|
231
792
|
"high",
|
|
232
793
|
"xhigh",
|
|
233
794
|
"max"
|
|
234
|
-
])
|
|
795
|
+
]) : z.enum([
|
|
235
796
|
"auto",
|
|
236
797
|
"low",
|
|
237
798
|
"medium",
|
|
238
799
|
"high"
|
|
239
|
-
]).optional()
|
|
800
|
+
])).optional().meta({ presentation: qualityPresentation })
|
|
240
801
|
});
|
|
241
802
|
}
|
|
242
803
|
function isGptImage(model) {
|
|
@@ -249,7 +810,6 @@ function fail(code, resultState, message) {
|
|
|
249
810
|
resultState
|
|
250
811
|
});
|
|
251
812
|
}
|
|
252
|
-
/** Checks large inline payloads without a repeated regexp group that can exhaust the VM stack. */
|
|
253
813
|
function validBase64(value) {
|
|
254
814
|
if (value.length % 4 !== 0) return false;
|
|
255
815
|
const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
|
|
@@ -287,7 +847,6 @@ async function readResponse(response, signal) {
|
|
|
287
847
|
fail("invalid-output", "not-delivered", "The image service returned invalid JSON");
|
|
288
848
|
}
|
|
289
849
|
}
|
|
290
|
-
/** Creates an image port using the host's routed fetch; credentials remain local to the call. */
|
|
291
850
|
function createOpenAIImagePort(call, fetcher) {
|
|
292
851
|
return { async generate(request, signal) {
|
|
293
852
|
signal.throwIfAborted();
|
|
@@ -332,65 +891,90 @@ function createOpenAIImagePort(call, fetcher) {
|
|
|
332
891
|
}
|
|
333
892
|
const url = new URL(`${String(call.config.baseUrl ?? "").replace(/\/+$/, "")}/images/${request.operation === "edit" ? "edits" : "generations"}`);
|
|
334
893
|
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) fail("invalid-params", "not-submitted", "Invalid image API address");
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
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
|
-
}
|
|
894
|
+
const accounting = call.accountingDispatch?.attempt(0);
|
|
895
|
+
let outcome = "failed";
|
|
896
|
+
let submission = "unknown";
|
|
354
897
|
try {
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
898
|
+
let response;
|
|
899
|
+
try {
|
|
900
|
+
response = await fetcher(url.href, {
|
|
901
|
+
method: "POST",
|
|
902
|
+
redirect: "error",
|
|
903
|
+
signal,
|
|
904
|
+
headers: {
|
|
905
|
+
authorization: `Bearer ${call.secrets.apiKey}`,
|
|
906
|
+
...typeof body === "string" ? { "content-type": "application/json" } : {}
|
|
907
|
+
},
|
|
908
|
+
body
|
|
909
|
+
});
|
|
910
|
+
} catch {
|
|
911
|
+
fail(signal.aborted ? "cancelled" : "network", "unknown", "The image submission result is unknown");
|
|
912
|
+
}
|
|
913
|
+
submission = "submitted";
|
|
914
|
+
if (!response.ok) {
|
|
915
|
+
await response.body?.cancel().catch(() => {});
|
|
916
|
+
fail(response.status === 401 ? "credential-unavailable" : response.status === 403 ? "forbidden" : response.status === 429 ? "quota" : "provider", "not-delivered", `Image generation failed with HTTP ${response.status}`);
|
|
917
|
+
}
|
|
918
|
+
try {
|
|
919
|
+
const raw = await readResponse(response, signal);
|
|
920
|
+
const envelope = z.record(z.string(), z.unknown()).safeParse(raw);
|
|
921
|
+
if (!envelope.success) fail("invalid-output", "not-delivered", "The image response is not a JSON object");
|
|
922
|
+
const usage = envelope.data.usage && typeof envelope.data.usage === "object" ? envelope.data.usage : void 0;
|
|
923
|
+
const reportedUsage = usage ? {
|
|
924
|
+
...typeof usage.input_tokens === "number" ? { inputTokens: usage.input_tokens } : {},
|
|
925
|
+
...typeof usage.output_tokens === "number" ? { outputTokens: usage.output_tokens } : {},
|
|
926
|
+
...typeof usage.total_tokens === "number" ? { totalTokens: usage.total_tokens } : {}
|
|
927
|
+
} : void 0;
|
|
928
|
+
if (reportedUsage) accounting?.report({
|
|
929
|
+
sequence: 1,
|
|
930
|
+
...reportedUsage
|
|
931
|
+
});
|
|
932
|
+
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");
|
|
933
|
+
if (!Array.isArray(envelope.data.data)) fail("invalid-output", "not-delivered", "The image response is missing its image data array");
|
|
934
|
+
if (!envelope.data.data.length) fail("invalid-output", "not-delivered", "The image response contains no images");
|
|
935
|
+
const result = z.array(z.object({
|
|
936
|
+
b64_json: z.string().optional(),
|
|
937
|
+
url: z.string().optional()
|
|
938
|
+
})).max(8).safeParse(envelope.data.data);
|
|
939
|
+
if (!result.success) fail("invalid-output", "not-delivered", "The image response contains unsupported image entries");
|
|
940
|
+
let outputBytes = 0;
|
|
941
|
+
const assets = result.data.map((item) => {
|
|
942
|
+
if (item.b64_json === void 0) {
|
|
943
|
+
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");
|
|
944
|
+
fail("invalid-output", "not-delivered", "The image response is missing its inline image bytes");
|
|
945
|
+
}
|
|
946
|
+
if (!item.b64_json.length) fail("invalid-output", "not-delivered", "The image response contains empty inline image bytes");
|
|
947
|
+
if (!validBase64(item.b64_json)) fail("invalid-output", "not-delivered", "Invalid image encoding");
|
|
948
|
+
const bytes = Buffer.from(item.b64_json, "base64");
|
|
949
|
+
outputBytes += bytes.byteLength;
|
|
950
|
+
if (outputBytes > 268435456) fail("too-large", "not-delivered", "Image outputs exceed their byte budget");
|
|
951
|
+
if (!bytes.length) fail("invalid-output", "not-delivered", "The image is empty");
|
|
952
|
+
return {
|
|
953
|
+
mediaType: outputFormat === "jpeg" ? "image/jpeg" : outputFormat === "webp" ? "image/webp" : "image/png",
|
|
954
|
+
body: (async function* () {
|
|
955
|
+
yield bytes;
|
|
956
|
+
})()
|
|
957
|
+
};
|
|
958
|
+
});
|
|
959
|
+
outcome = "success";
|
|
378
960
|
return {
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
yield bytes;
|
|
382
|
-
})()
|
|
961
|
+
assets,
|
|
962
|
+
...reportedUsage ? { usage: reportedUsage } : {}
|
|
383
963
|
};
|
|
384
|
-
})
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
964
|
+
} catch (error) {
|
|
965
|
+
if (error?.name === "GenerationFailure") throw error;
|
|
966
|
+
fail(signal.aborted ? "cancelled" : "invalid-output", "not-delivered", "The image response could not be read completely");
|
|
967
|
+
}
|
|
968
|
+
} finally {
|
|
969
|
+
accounting?.end({
|
|
970
|
+
outcome: signal.aborted ? "cancelled" : outcome,
|
|
971
|
+
submission
|
|
972
|
+
});
|
|
388
973
|
}
|
|
389
974
|
} };
|
|
390
975
|
}
|
|
391
976
|
//#endregion
|
|
392
977
|
//#region src/images/protocol.ts
|
|
393
|
-
/** Registers explicit image execution profiles for saved generation and editing bindings. */
|
|
394
978
|
function imagesProtocolType(support, fetcher) {
|
|
395
979
|
return {
|
|
396
980
|
type: "openai-images",
|
|
@@ -423,7 +1007,7 @@ function imagesProtocolType(support, fetcher) {
|
|
|
423
1007
|
paramsSchema: imageParamsFor(row.id)
|
|
424
1008
|
}]
|
|
425
1009
|
})),
|
|
426
|
-
createPort: (call) => createOpenAIImagePort(call, fetcher)
|
|
1010
|
+
createPort: (call) => createOpenAIImagePort(call, withConnectionHeaders(fetcher, call.headers))
|
|
427
1011
|
} },
|
|
428
1012
|
executionCandidates: () => [{
|
|
429
1013
|
profile: "openai-image-v1",
|
|
@@ -439,13 +1023,12 @@ function imagesProtocolType(support, fetcher) {
|
|
|
439
1023
|
};
|
|
440
1024
|
},
|
|
441
1025
|
normalizeListing: (input) => normalizeOffers(input),
|
|
442
|
-
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, fetcher) }),
|
|
443
|
-
testConnection: (probe) => probeOpenAI.listModels(probe, fetcher).then(() => {})
|
|
1026
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, withConnectionHeaders(fetcher, probe.headers)) }),
|
|
1027
|
+
testConnection: (probe) => probeOpenAI.listModels(probe, withConnectionHeaders(fetcher, probe.headers)).then(() => {})
|
|
444
1028
|
};
|
|
445
1029
|
}
|
|
446
1030
|
//#endregion
|
|
447
1031
|
//#region src/protocol/facts.ts
|
|
448
|
-
/** Parameter ranges and request limits for this provider wire. */
|
|
449
1032
|
const facts = {
|
|
450
1033
|
outputLimit: { support: "optional" },
|
|
451
1034
|
temperature: {
|
|
@@ -461,19 +1044,32 @@ const facts = {
|
|
|
461
1044
|
}
|
|
462
1045
|
};
|
|
463
1046
|
//#endregion
|
|
1047
|
+
//#region src/protocol/sdk.ts
|
|
1048
|
+
let loaded;
|
|
1049
|
+
let loading;
|
|
1050
|
+
function loadOpenAISdk() {
|
|
1051
|
+
loading ??= import("openai").then((sdk) => {
|
|
1052
|
+
loaded = sdk;
|
|
1053
|
+
return sdk;
|
|
1054
|
+
}, (error) => {
|
|
1055
|
+
loading = void 0;
|
|
1056
|
+
throw error;
|
|
1057
|
+
});
|
|
1058
|
+
return loading;
|
|
1059
|
+
}
|
|
1060
|
+
function isOpenAIApiError(error) {
|
|
1061
|
+
return loaded !== void 0 && error instanceof loaded.APIError;
|
|
1062
|
+
}
|
|
1063
|
+
function isOpenAIConnectionError(error) {
|
|
1064
|
+
return loaded !== void 0 && error instanceof loaded.APIConnectionError;
|
|
1065
|
+
}
|
|
1066
|
+
//#endregion
|
|
464
1067
|
//#region src/protocol/errors.ts
|
|
465
|
-
/**
|
|
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.
|
|
469
|
-
*/
|
|
470
|
-
/** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
|
|
471
|
-
* every other status is not. */
|
|
472
1068
|
function isRetryableStatus(status) {
|
|
473
1069
|
return status === 408 || status === 409 || status === 429 || status !== void 0 && status >= 500;
|
|
474
1070
|
}
|
|
475
1071
|
function retryAfterMs(error) {
|
|
476
|
-
if (!(error
|
|
1072
|
+
if (!isOpenAIApiError(error)) return void 0;
|
|
477
1073
|
const header = error.headers?.get("retry-after");
|
|
478
1074
|
if (!header) return void 0;
|
|
479
1075
|
const seconds = Number(header);
|
|
@@ -481,16 +1077,20 @@ function retryAfterMs(error) {
|
|
|
481
1077
|
const milliseconds = seconds * 1e3;
|
|
482
1078
|
return Number.isFinite(milliseconds) ? milliseconds : void 0;
|
|
483
1079
|
}
|
|
484
|
-
|
|
485
|
-
|
|
1080
|
+
function exceedsContextWindow(error) {
|
|
1081
|
+
if (error.code === "context_length_exceeded") return true;
|
|
1082
|
+
const message = error.error?.message;
|
|
1083
|
+
return error.status === 400 && typeof message === "string" && /maximum context length/i.test(message);
|
|
1084
|
+
}
|
|
1085
|
+
function toModelFailure(error, failures, transportFailure) {
|
|
486
1086
|
if (failures.owns(error)) return error;
|
|
487
|
-
if (!(error
|
|
1087
|
+
if (!isOpenAIApiError(error)) return transportFailure?.(error) ?? failures.create({
|
|
488
1088
|
code: "unknown",
|
|
489
1089
|
stage: "unknown",
|
|
490
1090
|
category: "unknown",
|
|
491
1091
|
source: "unknown",
|
|
492
1092
|
retryable: false
|
|
493
|
-
});
|
|
1093
|
+
}, { cause: error });
|
|
494
1094
|
const rawCode = error.code ?? error.type;
|
|
495
1095
|
const providerCode = typeof rawCode === "string" && (/* @__PURE__ */ new Set([
|
|
496
1096
|
"usage_not_included",
|
|
@@ -506,8 +1106,24 @@ function toModelFailure(error, failures) {
|
|
|
506
1106
|
"bio_policy",
|
|
507
1107
|
"misalignment_policy_violation"
|
|
508
1108
|
])).has(rawCode) ? rawCode : void 0;
|
|
509
|
-
const connection = error
|
|
1109
|
+
const connection = isOpenAIConnectionError(error);
|
|
510
1110
|
const status = Number.isInteger(error.status) && Number(error.status) >= 100 && Number(error.status) <= 599 ? error.status : void 0;
|
|
1111
|
+
const details = {
|
|
1112
|
+
...status === void 0 ? {} : { status },
|
|
1113
|
+
...typeof error.requestID === "string" ? { providerRequestId: error.requestID } : {}
|
|
1114
|
+
};
|
|
1115
|
+
if (exceedsContextWindow(error)) return failures.create({
|
|
1116
|
+
code: "context-window-exceeded",
|
|
1117
|
+
stage: "request",
|
|
1118
|
+
category: "request-too-large",
|
|
1119
|
+
source: "protocol",
|
|
1120
|
+
...status === void 0 ? {} : { status },
|
|
1121
|
+
retryable: false,
|
|
1122
|
+
...providerCode === void 0 ? {} : { providerCode }
|
|
1123
|
+
}, {
|
|
1124
|
+
cause: error,
|
|
1125
|
+
details
|
|
1126
|
+
});
|
|
511
1127
|
return failures.create({
|
|
512
1128
|
code: connection ? "stream-interrupted" : status === 413 ? "request-too-large" : status === void 0 ? "provider-error" : "http-error",
|
|
513
1129
|
stage: connection ? "transport" : status === 413 ? "request" : status === void 0 ? "stream" : "transport",
|
|
@@ -516,6 +1132,9 @@ function toModelFailure(error, failures) {
|
|
|
516
1132
|
...status === void 0 ? {} : { status },
|
|
517
1133
|
retryable: connection || isRetryableStatus(status),
|
|
518
1134
|
...providerCode === void 0 ? {} : { providerCode }
|
|
1135
|
+
}, {
|
|
1136
|
+
cause: error,
|
|
1137
|
+
details
|
|
519
1138
|
});
|
|
520
1139
|
}
|
|
521
1140
|
//#endregion
|
|
@@ -541,9 +1160,6 @@ function imagePart(planned) {
|
|
|
541
1160
|
image_url: { url: `data:${planned.mediaType};base64,${planned.data ?? ""}` }
|
|
542
1161
|
};
|
|
543
1162
|
}
|
|
544
|
-
/** A user message's parts in order: text, and each file as its label and
|
|
545
|
-
* image, or as the line standing in for it. A message whose parts are all
|
|
546
|
-
* text stays the one string it always was. */
|
|
547
1163
|
function userContent(message, index, plan) {
|
|
548
1164
|
if (!message.content.some((part) => part.type === "file")) return textOf(message.content) ?? "";
|
|
549
1165
|
const parts = [];
|
|
@@ -570,15 +1186,6 @@ function userContent(message, index, plan) {
|
|
|
570
1186
|
flush();
|
|
571
1187
|
return parts.every((part) => part.type === "text") ? parts.map((part) => part.text).join("\n") : parts;
|
|
572
1188
|
}
|
|
573
|
-
/** One kernel message becomes zero or more wire messages: a `user`
|
|
574
|
-
* message's `tool-result` parts each become their own `role: 'tool'`
|
|
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.
|
|
577
|
-
*
|
|
578
|
-
* A `role: 'tool'` message holds text alone, so the images a batch of
|
|
579
|
-
* results handed back follow it in one user message, each after the id of
|
|
580
|
-
* the call it came from; an image standing in as a line of text stays in
|
|
581
|
-
* its call's own tool message. */
|
|
582
1189
|
function toChatMessages(message, index, plan, options) {
|
|
583
1190
|
const toolResults = message.content.map((part, partIndex) => ({
|
|
584
1191
|
part,
|
|
@@ -620,7 +1227,7 @@ function toChatMessages(message, index, plan, options) {
|
|
|
620
1227
|
return [{
|
|
621
1228
|
role: "assistant",
|
|
622
1229
|
content,
|
|
623
|
-
...
|
|
1230
|
+
...openaiThinkingIsSendable(message, options) ? { reasoning_content: message.content.filter((part) => part.type === "thinking").map((part) => part.text).join("") } : {},
|
|
624
1231
|
...toolCalls === void 0 ? {} : { tool_calls: toolCalls }
|
|
625
1232
|
}];
|
|
626
1233
|
}
|
|
@@ -629,23 +1236,6 @@ function toChatMessages(message, index, plan, options) {
|
|
|
629
1236
|
content: userContent(message, index, plan)
|
|
630
1237
|
}];
|
|
631
1238
|
}
|
|
632
|
-
/**
|
|
633
|
-
* The volatile slot's contributions, as one standalone message to put after
|
|
634
|
-
* everything `toChatMessages` produced.
|
|
635
|
-
*
|
|
636
|
-
* **Appended unconditionally, without looking at what the last message is.**
|
|
637
|
-
* `toChatMessages` turns a user message carrying `tool-result` parts into
|
|
638
|
-
* `role: 'tool'` messages and drops its text parts, so writing the text into
|
|
639
|
-
* the last message — the anthropic member's shape — would lose it silently on
|
|
640
|
-
* the most common path there is: the step right after a tool call, which is
|
|
641
|
-
* when a volatile contribution first reaches the model. One message of its
|
|
642
|
-
* own has no such branch, and it puts the invariant in the code rather than
|
|
643
|
-
* in a reviewer's head.
|
|
644
|
-
*
|
|
645
|
-
* Nothing is added when there is nothing to add — an absent slot, an empty
|
|
646
|
-
* one, and one whose contributions are all empty leave the request the
|
|
647
|
-
* caller would have got anyway.
|
|
648
|
-
*/
|
|
649
1239
|
function volatileMessages(volatile) {
|
|
650
1240
|
const content = (volatile ?? []).map((note) => note.text).join("\n\n");
|
|
651
1241
|
return content.length > 0 ? [{
|
|
@@ -653,8 +1243,6 @@ function volatileMessages(volatile) {
|
|
|
653
1243
|
content
|
|
654
1244
|
}] : [];
|
|
655
1245
|
}
|
|
656
|
-
/** A reply's recorded notes go just before it — where the request that
|
|
657
|
-
* produced it carried them — so every request extends the previous one. */
|
|
658
1246
|
function withNotes(message, index, plan, options) {
|
|
659
1247
|
return [...message.role === "assistant" ? volatileMessages(message.volatile) : [], ...toChatMessages(message, index, plan, options)];
|
|
660
1248
|
}
|
|
@@ -668,16 +1256,17 @@ function toToolParam(tool) {
|
|
|
668
1256
|
}
|
|
669
1257
|
};
|
|
670
1258
|
}
|
|
671
|
-
|
|
672
|
-
|
|
1259
|
+
function openaiThinkingIsSendable(message, options) {
|
|
1260
|
+
return message.role === "assistant" && (textOf(message.content) !== null || toolCallsOf(message.content) !== void 0) && 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;
|
|
1261
|
+
}
|
|
1262
|
+
function toOpenAIRequest(request, options, plan = options.support.planMedia(request, options.media ?? {
|
|
1263
|
+
acceptsImages: true,
|
|
1264
|
+
limits: void 0
|
|
1265
|
+
})) {
|
|
673
1266
|
const summary = request.purpose === "summary";
|
|
674
1267
|
if (summary && (!Number.isInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0)) throw new Error("summaryMaxTokens must be a positive integer for a summary request");
|
|
675
1268
|
const tools = request.tools && request.tools.length > 0 ? request.tools.map(toToolParam) : [];
|
|
676
1269
|
const maxTokens = summary ? Math.min(request.summaryMaxTokens, Number.isInteger(options.maxTokens) && Number(options.maxTokens) > 0 ? options.maxTokens : request.summaryMaxTokens) : options.maxTokens;
|
|
677
|
-
const plan = options.support.planMedia(request, options.media ?? {
|
|
678
|
-
acceptsImages: true,
|
|
679
|
-
limits: void 0
|
|
680
|
-
});
|
|
681
1270
|
const systemMessage = request.system ? [{
|
|
682
1271
|
role: "system",
|
|
683
1272
|
content: request.system.join("\n\n")
|
|
@@ -698,14 +1287,16 @@ function toOpenAIRequest(request, options) {
|
|
|
698
1287
|
...options.temperature === void 0 ? {} : { temperature: options.temperature },
|
|
699
1288
|
...maxTokens === void 0 ? {} : { [options.outputLimitField ?? "max_tokens"]: maxTokens },
|
|
700
1289
|
...options.promptCacheKey === true && request.cacheKey !== void 0 ? { prompt_cache_key: request.cacheKey } : {},
|
|
701
|
-
...summary ? {} : options.extra
|
|
1290
|
+
...summary && request.summaryShape !== "continuation" ? {} : options.extra,
|
|
1291
|
+
...summary && maxTokens !== void 0 ? { [options.outputLimitField ?? "max_tokens"]: maxTokens } : {},
|
|
1292
|
+
...summary && request.toolChoice === "none" && tools.length > 0 ? { tool_choice: "none" } : {}
|
|
702
1293
|
};
|
|
703
1294
|
}
|
|
704
1295
|
//#endregion
|
|
705
1296
|
//#region src/protocol/stream.ts
|
|
706
1297
|
function cacheOf(usage) {
|
|
707
1298
|
const read = usage.prompt_tokens_details?.cached_tokens ?? usage.prompt_cache_hit_tokens;
|
|
708
|
-
return
|
|
1299
|
+
return Number.isSafeInteger(read) && Number(read) >= 0 ? { cacheReadTokens: read } : {};
|
|
709
1300
|
}
|
|
710
1301
|
function toFinishReason(reason, support) {
|
|
711
1302
|
switch (reason) {
|
|
@@ -719,13 +1310,9 @@ function toFinishReason(reason, support) {
|
|
|
719
1310
|
category: "protocol",
|
|
720
1311
|
source: "protocol",
|
|
721
1312
|
retryable: false
|
|
722
|
-
});
|
|
1313
|
+
}, reason === null ? void 0 : { details: { finishReason: String(reason) } });
|
|
723
1314
|
}
|
|
724
1315
|
}
|
|
725
|
-
/** The accumulated arguments as JSON, or `undefined` when they will not
|
|
726
|
-
* parse — which is what a tool call the endpoint cut off at its output cap
|
|
727
|
-
* looks like. `JSON.parse` never produces `undefined` itself, so it is free
|
|
728
|
-
* to stand for "no usable input here". */
|
|
729
1316
|
function parseToolInput(argumentsJson) {
|
|
730
1317
|
if (argumentsJson.length === 0) return {};
|
|
731
1318
|
try {
|
|
@@ -734,16 +1321,13 @@ function parseToolInput(argumentsJson) {
|
|
|
734
1321
|
return;
|
|
735
1322
|
}
|
|
736
1323
|
}
|
|
737
|
-
|
|
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.
|
|
741
|
-
*/
|
|
742
|
-
async function* mapOpenAIStream(chunks, support, originModel) {
|
|
1324
|
+
async function* mapOpenAIStream(chunks, support, originModel, usageReporter) {
|
|
743
1325
|
const textParts = [];
|
|
744
1326
|
const thinkingParts = [];
|
|
745
1327
|
const toolCalls = /* @__PURE__ */ new Map();
|
|
746
1328
|
const toolCallOrder = [];
|
|
1329
|
+
let usageSequence = 0;
|
|
1330
|
+
let inputTokensReported = false;
|
|
747
1331
|
let inputTokens = 0;
|
|
748
1332
|
let outputTokens = 0;
|
|
749
1333
|
let finishReason = "stop";
|
|
@@ -754,9 +1338,22 @@ async function* mapOpenAIStream(chunks, support, originModel) {
|
|
|
754
1338
|
let thinkingOpen = false;
|
|
755
1339
|
for await (const chunk of chunks) {
|
|
756
1340
|
if (chunk.usage) {
|
|
757
|
-
|
|
758
|
-
|
|
1341
|
+
inputTokensReported = Number.isSafeInteger(chunk.usage.prompt_tokens) && chunk.usage.prompt_tokens >= 0;
|
|
1342
|
+
inputTokens = inputTokensReported ? chunk.usage.prompt_tokens : 0;
|
|
1343
|
+
outputTokens = Number.isSafeInteger(chunk.usage.completion_tokens) && chunk.usage.completion_tokens >= 0 ? chunk.usage.completion_tokens : 0;
|
|
759
1344
|
cache = cacheOf(chunk.usage);
|
|
1345
|
+
const cached = chunk.usage.prompt_tokens_details?.cached_tokens ?? chunk.usage.prompt_cache_hit_tokens;
|
|
1346
|
+
if (cached !== void 0 && cached !== null && (!Number.isSafeInteger(cached) || cached < 0 || cached > inputTokens)) {
|
|
1347
|
+
inputTokensReported = false;
|
|
1348
|
+
cache = {};
|
|
1349
|
+
}
|
|
1350
|
+
usageReporter?.report({
|
|
1351
|
+
sequence: ++usageSequence,
|
|
1352
|
+
...typeof chunk.usage.prompt_tokens === "number" ? { inputTokens: chunk.usage.prompt_tokens } : {},
|
|
1353
|
+
...typeof chunk.usage.completion_tokens === "number" ? { outputTokens: chunk.usage.completion_tokens } : {},
|
|
1354
|
+
...typeof chunk.usage.total_tokens === "number" ? { totalTokens: chunk.usage.total_tokens } : {},
|
|
1355
|
+
...cache
|
|
1356
|
+
});
|
|
760
1357
|
ended = true;
|
|
761
1358
|
}
|
|
762
1359
|
const choice = chunk.choices[0];
|
|
@@ -850,20 +1447,17 @@ async function* mapOpenAIStream(chunks, support, originModel) {
|
|
|
850
1447
|
text
|
|
851
1448
|
});
|
|
852
1449
|
const incompleteToolCalls = [];
|
|
1450
|
+
const droppedToolCalls = [];
|
|
853
1451
|
for (const index of toolCallOrder) {
|
|
854
1452
|
const call = toolCalls.get(index);
|
|
855
1453
|
if (!call) continue;
|
|
856
1454
|
const input = finishReason === "max-tokens" && call.arguments.trim() === "" ? void 0 : parseToolInput(call.arguments);
|
|
857
1455
|
if (input === void 0) {
|
|
858
|
-
if (finishReason
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
category: "protocol",
|
|
862
|
-
source: "protocol",
|
|
863
|
-
retryable: false,
|
|
864
|
-
finishReason
|
|
1456
|
+
if (finishReason === "max-tokens") incompleteToolCalls.push({
|
|
1457
|
+
id: call.id,
|
|
1458
|
+
name: call.name
|
|
865
1459
|
});
|
|
866
|
-
|
|
1460
|
+
else droppedToolCalls.push({
|
|
867
1461
|
id: call.id,
|
|
868
1462
|
name: call.name
|
|
869
1463
|
});
|
|
@@ -876,7 +1470,7 @@ async function* mapOpenAIStream(chunks, support, originModel) {
|
|
|
876
1470
|
input
|
|
877
1471
|
});
|
|
878
1472
|
}
|
|
879
|
-
if (finishReason !== "refusal" && finishReason !== "max-tokens" && !content.some((part) => part.type === "text" || part.type === "tool-use")) throw support.failures.create({
|
|
1473
|
+
if (finishReason !== "refusal" && finishReason !== "max-tokens" && droppedToolCalls.length === 0 && !content.some((part) => part.type === "text" || part.type === "tool-use")) throw support.failures.create({
|
|
880
1474
|
code: "response-empty",
|
|
881
1475
|
stage: "response-validation",
|
|
882
1476
|
category: "protocol",
|
|
@@ -891,10 +1485,12 @@ async function* mapOpenAIStream(chunks, support, originModel) {
|
|
|
891
1485
|
incompleteToolCalls,
|
|
892
1486
|
...thinkingOpen ? { incompleteThinking: true } : {}
|
|
893
1487
|
} } : {},
|
|
1488
|
+
...droppedToolCalls.length > 0 ? { droppedToolCalls } : {},
|
|
894
1489
|
usage: {
|
|
895
1490
|
inputTokens,
|
|
896
1491
|
outputTokens,
|
|
897
|
-
...cache
|
|
1492
|
+
...cache,
|
|
1493
|
+
...inputTokensReported ? {} : { inputTokensReported: false }
|
|
898
1494
|
},
|
|
899
1495
|
...finishReason === "refusal" ? { refusalCategory: "content_filter" } : {},
|
|
900
1496
|
message: {
|
|
@@ -905,9 +1501,6 @@ async function* mapOpenAIStream(chunks, support, originModel) {
|
|
|
905
1501
|
}
|
|
906
1502
|
//#endregion
|
|
907
1503
|
//#region src/protocol/port.ts
|
|
908
|
-
/** The neutral plan in this family's spelling: on and off go out as the
|
|
909
|
-
* endpoint's `thinking` field where it has one, else as `effort: 'none'`,
|
|
910
|
-
* which `params.ts` already put in the plan. */
|
|
911
1504
|
function openaiOptions(plan) {
|
|
912
1505
|
return {
|
|
913
1506
|
...plan.effort === void 0 ? {} : { reasoningEffort: plan.effort },
|
|
@@ -916,19 +1509,23 @@ function openaiOptions(plan) {
|
|
|
916
1509
|
...plan.maxTokens === void 0 ? {} : { maxTokens: plan.maxTokens }
|
|
917
1510
|
};
|
|
918
1511
|
}
|
|
919
|
-
/** Creates an OpenAI-compatible port with inspection and partial-stream retry protection. */
|
|
920
1512
|
function createOpenAIModelPort(options) {
|
|
921
|
-
function clientForAttempt(reportProgress) {
|
|
1513
|
+
async function clientForAttempt(reportProgress, dispatched) {
|
|
1514
|
+
const { default: OpenAI } = await loadOpenAISdk();
|
|
922
1515
|
return options.client ?? new OpenAI({
|
|
923
1516
|
apiKey: options.allowUnauthenticated && !options.apiKey ? "not-used" : options.apiKey ?? "",
|
|
924
1517
|
...options.allowUnauthenticated && !options.apiKey ? { defaultHeaders: { Authorization: null } } : {},
|
|
925
|
-
fetch: async (...args) =>
|
|
1518
|
+
fetch: async (...args) => {
|
|
1519
|
+
const pending = (options.fetch ?? globalThis.fetch)(...args);
|
|
1520
|
+
dispatched();
|
|
1521
|
+
return options.support.observeResponseProgress(await pending, reportProgress);
|
|
1522
|
+
},
|
|
926
1523
|
baseURL: options.baseURL ?? "",
|
|
927
1524
|
maxRetries: 0
|
|
928
1525
|
});
|
|
929
1526
|
}
|
|
930
1527
|
function build(request) {
|
|
931
|
-
const capacity = options.catalogue?.()?.limit;
|
|
1528
|
+
const capacity = options.support.freezePayload(options.catalogue?.()?.limit ?? {});
|
|
932
1529
|
const outputLimit = Number.isInteger(capacity?.output) && Number(capacity?.output) > 0 ? Number(capacity?.output) : void 0;
|
|
933
1530
|
const effectiveRequest = request.purpose === "summary" && outputLimit !== void 0 ? {
|
|
934
1531
|
...request,
|
|
@@ -948,57 +1545,150 @@ function createOpenAIModelPort(options) {
|
|
|
948
1545
|
...options.support.extraParams(request.params ?? {})
|
|
949
1546
|
}
|
|
950
1547
|
};
|
|
1548
|
+
const mediaPlan = options.support.planMedia(effectiveRequest, requestOptions.media ?? {
|
|
1549
|
+
acceptsImages: true,
|
|
1550
|
+
limits: void 0
|
|
1551
|
+
});
|
|
1552
|
+
const params = options.support.freezePayload(toOpenAIRequest(effectiveRequest, requestOptions, mediaPlan));
|
|
1553
|
+
const settings = options.support.freezePayload({
|
|
1554
|
+
reasoningEffort: requestOptions.reasoningEffort,
|
|
1555
|
+
temperature: requestOptions.temperature,
|
|
1556
|
+
maxTokens: params.max_tokens,
|
|
1557
|
+
extra: request.purpose === "summary" && request.summaryShape !== "continuation" ? void 0 : requestOptions.extra
|
|
1558
|
+
});
|
|
1559
|
+
const replacements = /* @__PURE__ */ new Map();
|
|
1560
|
+
let mediaIndex = 0;
|
|
1561
|
+
for (const message of params.messages) {
|
|
1562
|
+
if (!Array.isArray(message.content)) continue;
|
|
1563
|
+
for (const part of message.content) {
|
|
1564
|
+
if (part.type !== "image_url") continue;
|
|
1565
|
+
const planned = mediaPlan.sent[mediaIndex++];
|
|
1566
|
+
if (!planned || part.image_url.url !== `data:${planned.mediaType};base64,${planned.data ?? ""}`) throw new Error("prepared_media_selection_mismatch");
|
|
1567
|
+
const data = planned.data ?? "";
|
|
1568
|
+
const hash = createHash("sha256");
|
|
1569
|
+
for (let offset = 0; offset < data.length; offset += 65536) hash.update(data.slice(offset, offset + 65536), "base64");
|
|
1570
|
+
replacements.set(part.image_url, {
|
|
1571
|
+
kind: "media",
|
|
1572
|
+
value: JSON.stringify({
|
|
1573
|
+
sha256: hash.digest("hex"),
|
|
1574
|
+
byteLength: Buffer.byteLength(data, "base64"),
|
|
1575
|
+
variantId: planned.variantId,
|
|
1576
|
+
mediaType: planned.mediaType,
|
|
1577
|
+
width: planned.width,
|
|
1578
|
+
height: planned.height,
|
|
1579
|
+
detail: part.image_url.detail ?? "auto"
|
|
1580
|
+
})
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
if (mediaIndex !== mediaPlan.sent.length) throw new Error("prepared_media_selection_mismatch");
|
|
951
1585
|
return {
|
|
952
|
-
params
|
|
953
|
-
|
|
954
|
-
|
|
1586
|
+
params,
|
|
1587
|
+
capacity,
|
|
1588
|
+
mediaPlan,
|
|
1589
|
+
replacements,
|
|
1590
|
+
replaySelections: options.support.prepareReplaySelections(effectiveRequest, ({ message, part }) => {
|
|
1591
|
+
const selected = part && openaiThinkingIsSendable(message, requestOptions);
|
|
1592
|
+
return {
|
|
1593
|
+
mode: "reasoning-content",
|
|
1594
|
+
textIncluded: !!selected,
|
|
1595
|
+
...selected ? { selectedText: part.text } : { reason: "not-applicable" },
|
|
1596
|
+
group: message.id
|
|
1597
|
+
};
|
|
1598
|
+
}),
|
|
1599
|
+
request: {
|
|
1600
|
+
...request,
|
|
1601
|
+
params: options.support.freezePayload(request.params ?? {})
|
|
1602
|
+
},
|
|
1603
|
+
fingerprint: options.support.freezePayload({
|
|
1604
|
+
rendering: "openai-chat-completions-v3",
|
|
1605
|
+
endpoint: options.endpoint ?? options.baseURL,
|
|
1606
|
+
model: params.model,
|
|
1607
|
+
purpose: request.purpose,
|
|
1608
|
+
settings
|
|
1609
|
+
})
|
|
955
1610
|
};
|
|
956
1611
|
}
|
|
957
|
-
return {
|
|
958
|
-
|
|
959
|
-
|
|
1612
|
+
return options.support.createPreparedPort({
|
|
1613
|
+
prepare: build,
|
|
1614
|
+
semantics(payload) {
|
|
1615
|
+
return {
|
|
1616
|
+
replaySelections: payload.replaySelections,
|
|
1617
|
+
mediaSelections: () => options.support.mediaSelections(payload.mediaPlan),
|
|
1618
|
+
toolDefinitions: payload.params.tools ?? Object.freeze([]),
|
|
1619
|
+
parameters: Object.freeze(Object.fromEntries(Object.entries(payload.params).filter(([key]) => ![
|
|
1620
|
+
"model",
|
|
1621
|
+
"messages",
|
|
1622
|
+
"tools",
|
|
1623
|
+
"stream",
|
|
1624
|
+
"stream_options",
|
|
1625
|
+
"prompt_cache_key"
|
|
1626
|
+
].includes(key)))),
|
|
1627
|
+
format: "request-semantic-v1",
|
|
1628
|
+
protocolId: "openai",
|
|
1629
|
+
adapterVersion: "1",
|
|
1630
|
+
rendererVersion: "openai-chat-completions-v3",
|
|
1631
|
+
frames: () => options.support.semanticFrames(payload.params, {
|
|
1632
|
+
omitRoot: [
|
|
1633
|
+
"stream",
|
|
1634
|
+
"stream_options",
|
|
1635
|
+
"prompt_cache_key"
|
|
1636
|
+
],
|
|
1637
|
+
replacements: payload.replacements
|
|
1638
|
+
})
|
|
1639
|
+
};
|
|
1640
|
+
},
|
|
1641
|
+
async inspect(payload, signal) {
|
|
1642
|
+
signal.throwIfAborted();
|
|
1643
|
+
const started = options.support.performance?.now();
|
|
1644
|
+
const { params, request, capacity, mediaPlan, fingerprint } = payload;
|
|
960
1645
|
const bodyMaxTokens = params.max_tokens;
|
|
961
1646
|
const bodyMaxCompletionTokens = params.max_completion_tokens;
|
|
962
1647
|
const explicitOutputLimits = [bodyMaxTokens, bodyMaxCompletionTokens].filter((value) => Number.isInteger(value) && Number(value) > 0).map(Number);
|
|
963
1648
|
const enforced = Number.isInteger(bodyMaxCompletionTokens) && Number(bodyMaxCompletionTokens) > 0;
|
|
964
1649
|
const outputReserve = enforced ? Math.max(...explicitOutputLimits) : capacity?.output ?? Math.max(0, ...explicitOutputLimits);
|
|
965
|
-
|
|
1650
|
+
options.support.performance?.observe({
|
|
1651
|
+
stage: "model.project",
|
|
1652
|
+
measurementPurpose: "request",
|
|
1653
|
+
durationMs: options.support.performance.now() - started,
|
|
1654
|
+
count: 1
|
|
1655
|
+
});
|
|
1656
|
+
const text = options.support.requestText("chat-completions", params);
|
|
1657
|
+
const inspection = options.support.inspect({
|
|
966
1658
|
body: params,
|
|
967
|
-
textTokens:
|
|
968
|
-
|
|
1659
|
+
textTokens: 0,
|
|
1660
|
+
textBytes: Buffer.byteLength(text),
|
|
1661
|
+
tokenizer: "utf8-bytes-quarter-v1",
|
|
969
1662
|
request,
|
|
970
1663
|
capacity,
|
|
971
1664
|
outputReserve,
|
|
972
1665
|
outputReserveSource: enforced ? "enforced" : "capacity",
|
|
973
|
-
mediaTokens:
|
|
974
|
-
|
|
975
|
-
limits: void 0
|
|
976
|
-
}).tokens,
|
|
977
|
-
fingerprint: {
|
|
978
|
-
rendering: "openai-chat-completions-v3",
|
|
979
|
-
endpoint: options.endpoint ?? options.baseURL,
|
|
980
|
-
model: params.model,
|
|
981
|
-
purpose: request.purpose,
|
|
982
|
-
contextWindow: request.params?.contextWindow,
|
|
983
|
-
capacity,
|
|
984
|
-
settings: {
|
|
985
|
-
reasoningEffort: requestOptions.reasoningEffort,
|
|
986
|
-
temperature: requestOptions.temperature,
|
|
987
|
-
maxTokens: bodyMaxTokens,
|
|
988
|
-
extra: request.purpose === "summary" ? void 0 : requestOptions.extra
|
|
989
|
-
}
|
|
990
|
-
}
|
|
1666
|
+
mediaTokens: mediaPlan.tokens,
|
|
1667
|
+
fingerprint
|
|
991
1668
|
});
|
|
1669
|
+
const textTokens = await options.support.measureText(text, signal);
|
|
1670
|
+
signal.throwIfAborted();
|
|
1671
|
+
return {
|
|
1672
|
+
...inspection,
|
|
1673
|
+
inputTokens: inspection.inputTokens + textTokens
|
|
1674
|
+
};
|
|
992
1675
|
},
|
|
993
|
-
stream(
|
|
1676
|
+
stream(payload, signal, observer, scope) {
|
|
994
1677
|
signal.throwIfAborted();
|
|
995
|
-
const { params } =
|
|
1678
|
+
const { params } = payload;
|
|
996
1679
|
return options.support.withChatAttempts({
|
|
1680
|
+
retainCleanup: scope.retainCleanup,
|
|
1681
|
+
beforeAttempt: (_signal, ordinal) => observer?.beforeAttempt?.(ordinal),
|
|
1682
|
+
accountingDispatch: options.accountingDispatch,
|
|
1683
|
+
effective: {
|
|
1684
|
+
outputLimit: params.max_completion_tokens ?? params.max_tokens,
|
|
1685
|
+
effort: params.reasoning_effort
|
|
1686
|
+
},
|
|
997
1687
|
signal,
|
|
998
1688
|
...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
|
|
999
1689
|
...options.sleep === void 0 ? {} : { sleep: options.sleep },
|
|
1000
1690
|
...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
|
|
1001
|
-
async *attempt(attemptSignal, reportProgress, attempt) {
|
|
1691
|
+
async *attempt(attemptSignal, reportProgress, attempt, usageReporter) {
|
|
1002
1692
|
const observe = (event) => {
|
|
1003
1693
|
try {
|
|
1004
1694
|
observer?.observe?.(event);
|
|
@@ -1006,7 +1696,37 @@ function createOpenAIModelPort(options) {
|
|
|
1006
1696
|
};
|
|
1007
1697
|
const attemptCount = attempt + 1;
|
|
1008
1698
|
let outcome = "unknown";
|
|
1699
|
+
let timeout;
|
|
1009
1700
|
let firstResponseFinished = false;
|
|
1701
|
+
let dispatchObserved = false;
|
|
1702
|
+
const markDispatched = () => {
|
|
1703
|
+
if (dispatchObserved) return;
|
|
1704
|
+
dispatchObserved = true;
|
|
1705
|
+
try {
|
|
1706
|
+
observer?.dispatched({
|
|
1707
|
+
attempt,
|
|
1708
|
+
presentation: {
|
|
1709
|
+
schema: "chat.dispatch-settings.v1",
|
|
1710
|
+
data: {
|
|
1711
|
+
model: {
|
|
1712
|
+
availability: "resolved",
|
|
1713
|
+
value: params.model,
|
|
1714
|
+
origin: "protocol"
|
|
1715
|
+
},
|
|
1716
|
+
effort: params.reasoning_effort ? {
|
|
1717
|
+
availability: "resolved",
|
|
1718
|
+
value: params.reasoning_effort,
|
|
1719
|
+
origin: "protocol"
|
|
1720
|
+
} : {
|
|
1721
|
+
availability: "resolved",
|
|
1722
|
+
value: "default",
|
|
1723
|
+
origin: "protocol"
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
});
|
|
1728
|
+
} catch {}
|
|
1729
|
+
};
|
|
1010
1730
|
observe({
|
|
1011
1731
|
stage: "attempt",
|
|
1012
1732
|
phase: "start",
|
|
@@ -1017,9 +1737,15 @@ function createOpenAIModelPort(options) {
|
|
|
1017
1737
|
phase: "start",
|
|
1018
1738
|
attempt: attemptCount
|
|
1019
1739
|
});
|
|
1740
|
+
let sdkIterator;
|
|
1020
1741
|
try {
|
|
1742
|
+
const client = await clientForAttempt(reportProgress, markDispatched);
|
|
1021
1743
|
attemptSignal.throwIfAborted();
|
|
1022
|
-
const
|
|
1744
|
+
const pending = client.chat.completions.create(params, { signal: attemptSignal });
|
|
1745
|
+
if (options.client) markDispatched();
|
|
1746
|
+
const chunks = await pending;
|
|
1747
|
+
if (options.client) reportProgress();
|
|
1748
|
+
sdkIterator = chunks[Symbol.asyncIterator]();
|
|
1023
1749
|
firstResponseFinished = true;
|
|
1024
1750
|
observe({
|
|
1025
1751
|
stage: "first-response",
|
|
@@ -1028,40 +1754,51 @@ function createOpenAIModelPort(options) {
|
|
|
1028
1754
|
outcome: "ok"
|
|
1029
1755
|
});
|
|
1030
1756
|
attemptSignal.throwIfAborted();
|
|
1031
|
-
|
|
1032
|
-
observer?.dispatched({ attempt });
|
|
1033
|
-
} catch {}
|
|
1034
|
-
attemptSignal.throwIfAborted();
|
|
1757
|
+
const iterator = sdkIterator;
|
|
1035
1758
|
const observed = (async function* () {
|
|
1036
|
-
for
|
|
1759
|
+
for (;;) {
|
|
1760
|
+
const result = await iterator.next();
|
|
1761
|
+
if (result.done) return;
|
|
1037
1762
|
reportProgress();
|
|
1038
|
-
yield
|
|
1763
|
+
yield result.value;
|
|
1039
1764
|
}
|
|
1040
1765
|
})();
|
|
1041
|
-
for await (const chunk of mapOpenAIStream(observed, options.support, options.model)) {
|
|
1766
|
+
for await (const chunk of mapOpenAIStream(observed, options.support, options.model, usageReporter)) {
|
|
1042
1767
|
if (chunk.kind === "final") outcome = "ok";
|
|
1043
1768
|
yield chunk;
|
|
1044
1769
|
}
|
|
1045
1770
|
} catch (error) {
|
|
1046
|
-
|
|
1771
|
+
const reason = attemptSignal.aborted ? options.support.failures.verified(attemptSignal.reason) : void 0;
|
|
1772
|
+
if (reason?.code === "stream-idle-timeout") {
|
|
1773
|
+
outcome = "timeout";
|
|
1774
|
+
timeout = reason;
|
|
1775
|
+
} else outcome = attemptSignal.aborted ? "cancelled" : "error";
|
|
1047
1776
|
throw error;
|
|
1048
1777
|
} finally {
|
|
1049
|
-
if (
|
|
1050
|
-
|
|
1778
|
+
if (sdkIterator) {
|
|
1779
|
+
const iterator = sdkIterator;
|
|
1780
|
+
scope.retainCleanup(async () => {
|
|
1781
|
+
await iterator.return?.();
|
|
1782
|
+
}).catch(() => {});
|
|
1783
|
+
}
|
|
1784
|
+
const end = {
|
|
1051
1785
|
phase: "end",
|
|
1052
1786
|
attempt: attemptCount,
|
|
1053
|
-
outcome
|
|
1787
|
+
outcome,
|
|
1788
|
+
...timeout ? { failure: timeout } : {}
|
|
1789
|
+
};
|
|
1790
|
+
if (!firstResponseFinished) observe({
|
|
1791
|
+
stage: "first-response",
|
|
1792
|
+
...end
|
|
1054
1793
|
});
|
|
1055
1794
|
observe({
|
|
1056
1795
|
stage: "attempt",
|
|
1057
|
-
|
|
1058
|
-
attempt: attemptCount,
|
|
1059
|
-
outcome
|
|
1796
|
+
...end
|
|
1060
1797
|
});
|
|
1061
1798
|
}
|
|
1062
1799
|
},
|
|
1063
1800
|
classify(error) {
|
|
1064
|
-
const portError = toModelFailure(error, options.support.failures);
|
|
1801
|
+
const portError = toModelFailure(error, options.support.failures, options.support.transportFailure);
|
|
1065
1802
|
return {
|
|
1066
1803
|
error: portError,
|
|
1067
1804
|
retryable: portError.retryable === true,
|
|
@@ -1070,11 +1807,10 @@ function createOpenAIModelPort(options) {
|
|
|
1070
1807
|
}
|
|
1071
1808
|
});
|
|
1072
1809
|
}
|
|
1073
|
-
};
|
|
1810
|
+
});
|
|
1074
1811
|
}
|
|
1075
1812
|
//#endregion
|
|
1076
1813
|
//#region src/protocol.ts
|
|
1077
|
-
/** Validated supplier options; no supplier identity is interpreted by this protocol. */
|
|
1078
1814
|
const OpenAIProtocolOptions = z.strictObject({
|
|
1079
1815
|
allowUnauthenticated: z.boolean().optional(),
|
|
1080
1816
|
reasoningReplay: z.enum(["omit", "reasoning-content"]).optional(),
|
|
@@ -1082,7 +1818,6 @@ const OpenAIProtocolOptions = z.strictObject({
|
|
|
1082
1818
|
outputLimitField: z.enum(["max_tokens", "max_completion_tokens"]).optional(),
|
|
1083
1819
|
promptCacheKey: z.boolean().optional()
|
|
1084
1820
|
});
|
|
1085
|
-
/** Registers concrete Chat Completions request mapping, streaming and probes. */
|
|
1086
1821
|
function openaiProtocolType(support, fetch) {
|
|
1087
1822
|
return {
|
|
1088
1823
|
type: "openai",
|
|
@@ -1104,8 +1839,9 @@ function openaiProtocolType(support, fetch) {
|
|
|
1104
1839
|
createPort(call) {
|
|
1105
1840
|
const options = OpenAIProtocolOptions.parse(call.options);
|
|
1106
1841
|
return createOpenAIModelPort({
|
|
1842
|
+
accountingDispatch: call.accountingDispatch,
|
|
1107
1843
|
support,
|
|
1108
|
-
fetch,
|
|
1844
|
+
fetch: withConnectionHeaders(fetch, call.headers),
|
|
1109
1845
|
model: call.model,
|
|
1110
1846
|
endpoint: call.providerId,
|
|
1111
1847
|
apiKey: call.secrets.apiKey ?? "",
|
|
@@ -1130,9 +1866,54 @@ function openaiProtocolType(support, fetch) {
|
|
|
1130
1866
|
}
|
|
1131
1867
|
} },
|
|
1132
1868
|
normalizeListing: (input) => normalizeOffers(input),
|
|
1133
|
-
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, fetch) }),
|
|
1134
|
-
testConnection: (probe) => probeOpenAI.testConnection(probe, fetch)
|
|
1869
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, withConnectionHeaders(fetch, probe.headers)) }),
|
|
1870
|
+
testConnection: (probe) => probeOpenAI.testConnection(probe, withConnectionHeaders(fetch, probe.headers))
|
|
1871
|
+
};
|
|
1872
|
+
}
|
|
1873
|
+
//#endregion
|
|
1874
|
+
//#region src/responses/semantics.ts
|
|
1875
|
+
function responsesSemanticFields(body, mediaPlan) {
|
|
1876
|
+
const fields = /* @__PURE__ */ new Map();
|
|
1877
|
+
for (const item of body.input) if (item.type === "reasoning" && typeof item.encrypted_content === "string") fields.set(item, /* @__PURE__ */ new Map([["encrypted_content", {
|
|
1878
|
+
kind: "replay",
|
|
1879
|
+
value: JSON.stringify({
|
|
1880
|
+
sha256: createHash("sha256").update(item.encrypted_content).digest("hex"),
|
|
1881
|
+
byteLength: Buffer.byteLength(item.encrypted_content),
|
|
1882
|
+
mode: "responses-encrypted",
|
|
1883
|
+
model: body.model
|
|
1884
|
+
})
|
|
1885
|
+
}]]));
|
|
1886
|
+
let mediaIndex = 0;
|
|
1887
|
+
const mediaFields = (input) => {
|
|
1888
|
+
if (Array.isArray(input)) {
|
|
1889
|
+
for (const item of input) mediaFields(item);
|
|
1890
|
+
return;
|
|
1891
|
+
}
|
|
1892
|
+
if (input === null || typeof input !== "object") return;
|
|
1893
|
+
const item = input;
|
|
1894
|
+
if (item.type === "input_image") {
|
|
1895
|
+
const planned = mediaPlan.sent[mediaIndex++];
|
|
1896
|
+
if (!planned || item.image_url !== `data:${planned.mediaType};base64,${planned.data ?? ""}`) throw new Error("prepared_media_selection_mismatch");
|
|
1897
|
+
const data = planned.data ?? "";
|
|
1898
|
+
const hash = createHash("sha256");
|
|
1899
|
+
for (let offset = 0; offset < data.length; offset += 65536) hash.update(data.slice(offset, offset + 65536), "base64");
|
|
1900
|
+
fields.set(item, /* @__PURE__ */ new Map([["image_url", {
|
|
1901
|
+
kind: "media",
|
|
1902
|
+
value: JSON.stringify({
|
|
1903
|
+
sha256: hash.digest("hex"),
|
|
1904
|
+
byteLength: Buffer.byteLength(data, "base64"),
|
|
1905
|
+
variantId: planned.variantId,
|
|
1906
|
+
mediaType: planned.mediaType,
|
|
1907
|
+
width: planned.width,
|
|
1908
|
+
height: planned.height
|
|
1909
|
+
})
|
|
1910
|
+
}]]));
|
|
1911
|
+
}
|
|
1912
|
+
for (const key of ["content", "output"]) if (Array.isArray(item[key])) mediaFields(item[key]);
|
|
1135
1913
|
};
|
|
1914
|
+
mediaFields(body.input);
|
|
1915
|
+
if (mediaIndex !== mediaPlan.sent.length) throw new Error("prepared_media_selection_mismatch");
|
|
1916
|
+
return fields;
|
|
1136
1917
|
}
|
|
1137
1918
|
//#endregion
|
|
1138
1919
|
//#region src/responses/request.ts
|
|
@@ -1140,14 +1921,22 @@ function replayable(message, options) {
|
|
|
1140
1921
|
if (options.reasoningReplay === "omit" || message.outputTruncation?.incompleteThinking || !message.content.some((part) => part.type === "text" && part.text !== "" || part.type === "tool-use")) return false;
|
|
1141
1922
|
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
1923
|
}
|
|
1143
|
-
|
|
1924
|
+
function responsesReplayChoice(message, part, options) {
|
|
1925
|
+
const selected = message.role === "assistant" && replayable(message, options);
|
|
1926
|
+
const plain = options.reasoningReplay === "reasoning-content";
|
|
1927
|
+
return {
|
|
1928
|
+
mode: plain ? "reasoning-content" : "encrypted",
|
|
1929
|
+
textIncluded: selected && part.text !== "",
|
|
1930
|
+
...selected ? { selectedText: plain ? part.text : part.signature } : { reason: "not-applicable" },
|
|
1931
|
+
group: message.id
|
|
1932
|
+
};
|
|
1933
|
+
}
|
|
1144
1934
|
function responsesHiddenInputTokens(request, options) {
|
|
1145
1935
|
return request.messages.reduce((total, message) => {
|
|
1146
1936
|
if (options.reasoningReplay === "reasoning-content" || message.role !== "assistant" || !replayable(message, options)) return total;
|
|
1147
1937
|
return total + Math.max(0, ...message.content.map((part) => part.type === "thinking" ? part.outputTokens ?? 0 : 0));
|
|
1148
1938
|
}, 0);
|
|
1149
1939
|
}
|
|
1150
|
-
/** A planned file as content parts: the label and the image, or the line in its place. */
|
|
1151
1940
|
function fileParts(planned) {
|
|
1152
1941
|
const label = {
|
|
1153
1942
|
type: "input_text",
|
|
@@ -1159,7 +1948,6 @@ function fileParts(planned) {
|
|
|
1159
1948
|
image_url: `data:${planned.mediaType};base64,${planned.data ?? ""}`
|
|
1160
1949
|
}];
|
|
1161
1950
|
}
|
|
1162
|
-
/** A result without files keeps its plain string; one with files is an array. */
|
|
1163
1951
|
function outputOf(part, plan, at) {
|
|
1164
1952
|
const files = part.files ?? [];
|
|
1165
1953
|
if (files.length === 0) return part.content;
|
|
@@ -1249,7 +2037,6 @@ function assistantItems(message, options) {
|
|
|
1249
2037
|
});
|
|
1250
2038
|
return items;
|
|
1251
2039
|
}
|
|
1252
|
-
/** The one user item a set of notes renders as, or nothing. */
|
|
1253
2040
|
function noteItems(notes) {
|
|
1254
2041
|
const text = (notes ?? []).map((note) => note.text).join("\n\n");
|
|
1255
2042
|
return text === "" ? [] : [{
|
|
@@ -1270,7 +2057,6 @@ function toolOf(tool) {
|
|
|
1270
2057
|
strict: false
|
|
1271
2058
|
};
|
|
1272
2059
|
}
|
|
1273
|
-
/** Renders stateless history using only the endpoint-declared reasoning representation. */
|
|
1274
2060
|
function toResponsesBody(request, options, plan) {
|
|
1275
2061
|
const input = [];
|
|
1276
2062
|
const updates = new Map(options.effortUpdates?.map((update) => [update.beforeUserMessageId, update.effort]));
|
|
@@ -1305,14 +2091,14 @@ function toResponsesBody(request, options, plan) {
|
|
|
1305
2091
|
}
|
|
1306
2092
|
//#endregion
|
|
1307
2093
|
//#region src/responses/codec.ts
|
|
1308
|
-
/** Shared Responses rendering for registered transports. */
|
|
1309
2094
|
const responsesCodec = {
|
|
1310
2095
|
render: toResponsesBody,
|
|
2096
|
+
replayChoice: responsesReplayChoice,
|
|
2097
|
+
semanticFields: responsesSemanticFields,
|
|
1311
2098
|
hiddenInputTokens: responsesHiddenInputTokens
|
|
1312
2099
|
};
|
|
1313
2100
|
//#endregion
|
|
1314
2101
|
//#region src/responses/options.ts
|
|
1315
|
-
/** Explicit wire capabilities; no supplier identity or URL is interpreted. */
|
|
1316
2102
|
const ResponsesProtocolOptions = z.strictObject({
|
|
1317
2103
|
allowUnauthenticated: z.boolean().optional(),
|
|
1318
2104
|
reasoningReplay: z.enum([
|
|
@@ -1321,7 +2107,6 @@ const ResponsesProtocolOptions = z.strictObject({
|
|
|
1321
2107
|
"omit"
|
|
1322
2108
|
]).optional(),
|
|
1323
2109
|
reasoningSummary: z.boolean().optional(),
|
|
1324
|
-
/** Wire effort enabling an active thinking toggle when no effort was selected. */
|
|
1325
2110
|
thinkingOnEffort: z.enum([
|
|
1326
2111
|
"minimal",
|
|
1327
2112
|
"low",
|
|
@@ -1333,12 +2118,10 @@ const ResponsesProtocolOptions = z.strictObject({
|
|
|
1333
2118
|
encryptedReasoningInclude: z.boolean().optional(),
|
|
1334
2119
|
effortCache: z.boolean().optional(),
|
|
1335
2120
|
promptCacheKey: z.boolean().optional(),
|
|
1336
|
-
/** False removes callable tools when the caller explicitly prohibits tool use. */
|
|
1337
2121
|
toolChoiceNone: z.boolean().optional()
|
|
1338
2122
|
});
|
|
1339
2123
|
//#endregion
|
|
1340
2124
|
//#region src/responses/stream.ts
|
|
1341
|
-
/** Locally recognized stream failures, mapped to host diagnostics by the port. */
|
|
1342
2125
|
var ResponsesStreamError = class extends Error {
|
|
1343
2126
|
retryable;
|
|
1344
2127
|
failureCode;
|
|
@@ -1355,11 +2138,28 @@ function toFailedError(failure) {
|
|
|
1355
2138
|
"server_error",
|
|
1356
2139
|
"overloaded_error"
|
|
1357
2140
|
].includes(String(failure.code)),
|
|
1358
|
-
failureCode: failure.code === "context_length_exceeded" ? "context-
|
|
2141
|
+
failureCode: failure.code === "context_length_exceeded" ? "context-window-exceeded" : failure.code === "insufficient_quota" ? "quota-exceeded" : "provider-error"
|
|
1359
2142
|
});
|
|
1360
2143
|
}
|
|
1361
2144
|
const str = (value) => typeof value === "string" ? value : "";
|
|
1362
|
-
const
|
|
2145
|
+
const validCount = (value) => Number.isSafeInteger(value) && Number(value) >= 0;
|
|
2146
|
+
const num = (value) => validCount(value) ? value : 0;
|
|
2147
|
+
function unparseableCall(item) {
|
|
2148
|
+
if (item.type !== "function_call") return void 0;
|
|
2149
|
+
const id = str(item.call_id);
|
|
2150
|
+
const name = str(item.name);
|
|
2151
|
+
if (id.trim() === "" || name.trim() === "") return void 0;
|
|
2152
|
+
if (item.status !== void 0 && item.status !== "completed") return void 0;
|
|
2153
|
+
try {
|
|
2154
|
+
JSON.parse(str(item.arguments));
|
|
2155
|
+
return;
|
|
2156
|
+
} catch {
|
|
2157
|
+
return {
|
|
2158
|
+
id,
|
|
2159
|
+
name
|
|
2160
|
+
};
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
1363
2163
|
function partsOf(item, model) {
|
|
1364
2164
|
if (item.type === "reasoning") {
|
|
1365
2165
|
const summary = Array.isArray(item.summary) ? item.summary : [];
|
|
@@ -1403,144 +2203,169 @@ function partsOf(item, model) {
|
|
|
1403
2203
|
}
|
|
1404
2204
|
return [];
|
|
1405
2205
|
}
|
|
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
2206
|
async function* mapResponsesStream(events, options) {
|
|
2207
|
+
let usageSequence = 0;
|
|
2208
|
+
let reported = {};
|
|
1411
2209
|
const items = [];
|
|
1412
2210
|
const callIds = /* @__PURE__ */ new Map();
|
|
1413
2211
|
const pendingCalls = /* @__PURE__ */ new Map();
|
|
1414
2212
|
let openThinking = "";
|
|
1415
2213
|
let refused = false;
|
|
1416
2214
|
let open = "";
|
|
1417
|
-
for await (const event of events)
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
const
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
2215
|
+
for await (const event of events) {
|
|
2216
|
+
const response = event.response;
|
|
2217
|
+
if (response?.usage && typeof response.usage === "object") {
|
|
2218
|
+
const usage = response.usage;
|
|
2219
|
+
const details = usage.input_tokens_details ?? {};
|
|
2220
|
+
reported = {
|
|
2221
|
+
...reported,
|
|
2222
|
+
...typeof usage.input_tokens === "number" ? { inputTokens: usage.input_tokens } : {},
|
|
2223
|
+
...typeof usage.output_tokens === "number" ? { outputTokens: usage.output_tokens } : {},
|
|
2224
|
+
...typeof usage.total_tokens === "number" ? { totalTokens: usage.total_tokens } : {},
|
|
2225
|
+
...typeof details.cached_tokens === "number" ? { cacheReadTokens: details.cached_tokens } : {},
|
|
2226
|
+
...typeof details.cache_write_tokens === "number" ? { cacheWriteTokens: details.cache_write_tokens } : {}
|
|
1426
2227
|
};
|
|
1427
|
-
|
|
1428
|
-
|
|
2228
|
+
options.usageReporter?.report({
|
|
2229
|
+
sequence: ++usageSequence,
|
|
2230
|
+
...reported
|
|
2231
|
+
});
|
|
1429
2232
|
}
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
2233
|
+
switch (event.type) {
|
|
2234
|
+
case "response.output_text.delta":
|
|
2235
|
+
case "response.refusal.delta": {
|
|
2236
|
+
if (event.type === "response.refusal.delta") refused = true;
|
|
2237
|
+
const text = str(event.delta);
|
|
2238
|
+
if (text === "") break;
|
|
1435
2239
|
yield {
|
|
1436
|
-
kind: "
|
|
2240
|
+
kind: "text-delta",
|
|
1437
2241
|
text
|
|
1438
2242
|
};
|
|
2243
|
+
open += text;
|
|
2244
|
+
break;
|
|
1439
2245
|
}
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
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);
|
|
2246
|
+
case "response.reasoning_text.delta":
|
|
2247
|
+
case "response.reasoning_summary_text.delta": {
|
|
2248
|
+
const text = str(event.delta);
|
|
2249
|
+
if (text !== "") {
|
|
2250
|
+
openThinking += text;
|
|
2251
|
+
yield {
|
|
2252
|
+
kind: "thinking-delta",
|
|
2253
|
+
text
|
|
2254
|
+
};
|
|
2255
|
+
}
|
|
2256
|
+
break;
|
|
1475
2257
|
}
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
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),
|
|
2258
|
+
case "response.output_item.added": {
|
|
2259
|
+
const item = event.item;
|
|
2260
|
+
if (item?.type === "function_call") {
|
|
2261
|
+
const callId = str(item.call_id);
|
|
2262
|
+
callIds.set(str(item.id), callId);
|
|
2263
|
+
pendingCalls.set(str(item.id), {
|
|
2264
|
+
id: callId,
|
|
1505
2265
|
...str(item.name) === "" ? {} : { name: str(item.name) }
|
|
1506
2266
|
});
|
|
1507
|
-
|
|
2267
|
+
yield {
|
|
2268
|
+
kind: "tool-call-delta",
|
|
2269
|
+
id: callId,
|
|
2270
|
+
name: str(item.name),
|
|
2271
|
+
inputDelta: ""
|
|
2272
|
+
};
|
|
1508
2273
|
}
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
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
|
|
2274
|
+
break;
|
|
2275
|
+
}
|
|
2276
|
+
case "response.function_call_arguments.delta": {
|
|
2277
|
+
const callId = callIds.get(str(event.item_id));
|
|
2278
|
+
if (callId !== void 0) yield {
|
|
2279
|
+
kind: "tool-call-delta",
|
|
2280
|
+
id: callId,
|
|
2281
|
+
inputDelta: str(event.delta)
|
|
2282
|
+
};
|
|
2283
|
+
break;
|
|
2284
|
+
}
|
|
2285
|
+
case "response.output_item.done": {
|
|
2286
|
+
const item = event.item;
|
|
2287
|
+
if (item !== void 0) items.push(item);
|
|
2288
|
+
if (item?.type === "function_call") {
|
|
2289
|
+
pendingCalls.delete(str(item.id));
|
|
2290
|
+
for (const [key, call] of pendingCalls) if (call.id === str(item.call_id)) pendingCalls.delete(key);
|
|
1538
2291
|
}
|
|
1539
|
-
|
|
1540
|
-
|
|
2292
|
+
if (item?.type === "reasoning") openThinking = "";
|
|
2293
|
+
if (item?.type === "message" && Array.isArray(item.content)) refused ||= item.content.some((part) => part.type === "refusal");
|
|
2294
|
+
if (item?.type === "message") open = "";
|
|
2295
|
+
break;
|
|
2296
|
+
}
|
|
2297
|
+
case "response.completed":
|
|
2298
|
+
case "response.incomplete": {
|
|
2299
|
+
const response = event.response ?? {};
|
|
2300
|
+
const terminalItems = Array.isArray(response.output) ? response.output : items;
|
|
2301
|
+
const incompleteThinking = terminalItems.some((item) => item.type === "reasoning" && item.status === "incomplete") || openThinking !== "" && !terminalItems.some((item) => item.type === "reasoning" && item.status === "completed");
|
|
2302
|
+
refused ||= terminalItems.some((item) => item.type === "message" && Array.isArray(item.content) && item.content.some((part) => part.type === "refusal"));
|
|
2303
|
+
const usage = response.usage ?? {};
|
|
2304
|
+
const details = usage.input_tokens_details ?? {};
|
|
2305
|
+
const cache = {
|
|
2306
|
+
...validCount(details.cached_tokens) && details.cached_tokens <= num(usage.input_tokens) ? { cacheReadTokens: details.cached_tokens } : {},
|
|
2307
|
+
...validCount(details.cache_write_tokens) && details.cache_write_tokens <= num(usage.input_tokens) ? { cacheWriteTokens: details.cache_write_tokens } : {}
|
|
2308
|
+
};
|
|
2309
|
+
const truncated = event.type === "response.incomplete" && response.incomplete_details?.reason === "max_output_tokens";
|
|
2310
|
+
if (event.type === "response.incomplete" && !truncated && !refused) throw new ResponsesStreamError(`incomplete model reply (${event.type})`, { retryable: false });
|
|
2311
|
+
const incompleteToolCalls = new Map([...pendingCalls.values()].map((call) => [call.id, call]));
|
|
2312
|
+
const droppedToolCalls = [];
|
|
2313
|
+
const content = terminalItems.flatMap((item) => {
|
|
2314
|
+
const unparseable = unparseableCall(item);
|
|
2315
|
+
if (unparseable && !truncated) {
|
|
2316
|
+
droppedToolCalls.push(unparseable);
|
|
2317
|
+
return [];
|
|
2318
|
+
}
|
|
2319
|
+
try {
|
|
2320
|
+
const parts = partsOf(item, options.model);
|
|
2321
|
+
if (item.type === "function_call") incompleteToolCalls.delete(str(item.call_id));
|
|
2322
|
+
return parts;
|
|
2323
|
+
} catch (error) {
|
|
2324
|
+
if (!truncated || item.type !== "function_call" || str(item.call_id) === "") throw error;
|
|
2325
|
+
incompleteToolCalls.set(str(item.call_id), {
|
|
2326
|
+
id: str(item.call_id),
|
|
2327
|
+
...str(item.name) === "" ? {} : { name: str(item.name) }
|
|
2328
|
+
});
|
|
2329
|
+
return [];
|
|
2330
|
+
}
|
|
2331
|
+
});
|
|
2332
|
+
if (truncated && open !== "" && !terminalItems.some((item) => item.type === "message")) content.push({
|
|
2333
|
+
type: "text",
|
|
2334
|
+
text: open
|
|
2335
|
+
});
|
|
2336
|
+
if (truncated && openThinking !== "" && !terminalItems.some((item) => item.type === "reasoning")) content.unshift({
|
|
2337
|
+
type: "thinking",
|
|
2338
|
+
text: openThinking
|
|
2339
|
+
});
|
|
2340
|
+
if (!truncated && !refused && droppedToolCalls.length === 0 && !content.some((part) => part.type === "text" || part.type === "tool-use")) throw new ResponsesStreamError(`incomplete model reply (${event.type})`, {
|
|
2341
|
+
retryable: false,
|
|
2342
|
+
failureCode: "response-empty"
|
|
2343
|
+
});
|
|
2344
|
+
const finishReason = refused ? "refusal" : truncated ? "max-tokens" : droppedToolCalls.length > 0 || content.some((part) => part.type === "tool-use") ? "tool-calls" : "stop";
|
|
2345
|
+
yield {
|
|
2346
|
+
kind: "final",
|
|
2347
|
+
finishReason,
|
|
2348
|
+
...droppedToolCalls.length > 0 ? { droppedToolCalls } : {},
|
|
2349
|
+
...finishReason === "max-tokens" ? { outputTruncation: {
|
|
2350
|
+
incompleteToolCalls: [...incompleteToolCalls.values()],
|
|
2351
|
+
...incompleteThinking ? { incompleteThinking: true } : {}
|
|
2352
|
+
} } : {},
|
|
2353
|
+
usage: {
|
|
2354
|
+
inputTokens: num(usage.input_tokens),
|
|
2355
|
+
...validCount(usage.input_tokens) && (details.cached_tokens == null || validCount(details.cached_tokens) && details.cached_tokens <= usage.input_tokens) && (details.cache_write_tokens == null || validCount(details.cache_write_tokens) && details.cache_write_tokens <= usage.input_tokens) ? {} : { inputTokensReported: false },
|
|
2356
|
+
outputTokens: num(usage.output_tokens),
|
|
2357
|
+
...cache
|
|
2358
|
+
},
|
|
2359
|
+
message: {
|
|
2360
|
+
role: "assistant",
|
|
2361
|
+
content
|
|
2362
|
+
}
|
|
2363
|
+
};
|
|
2364
|
+
return;
|
|
2365
|
+
}
|
|
2366
|
+
case "response.failed":
|
|
2367
|
+
case "error": throw toFailedError(event.response?.error ?? event.error ?? event);
|
|
1541
2368
|
}
|
|
1542
|
-
case "response.failed":
|
|
1543
|
-
case "error": throw toFailedError(event.response?.error ?? event.error ?? event);
|
|
1544
2369
|
}
|
|
1545
2370
|
throw new ResponsesStreamError("model stream interrupted", {
|
|
1546
2371
|
retryable: true,
|
|
@@ -1549,10 +2374,9 @@ async function* mapResponsesStream(events, options) {
|
|
|
1549
2374
|
}
|
|
1550
2375
|
//#endregion
|
|
1551
2376
|
//#region src/responses/port.ts
|
|
1552
|
-
/** Creates a stateless public Responses port with host-owned retry and inspection. */
|
|
1553
2377
|
function createResponsesPort(call, support, fetch, capability) {
|
|
1554
2378
|
const options = ResponsesProtocolOptions.parse(call.options);
|
|
1555
|
-
function build(request
|
|
2379
|
+
function build(request) {
|
|
1556
2380
|
const entry = support.catalogue(call.providerId, call.model);
|
|
1557
2381
|
const endpoint = support.endpoint(call.providerId);
|
|
1558
2382
|
const params = support.resolveParams({
|
|
@@ -1573,7 +2397,7 @@ function createResponsesPort(call, support, fetch, capability) {
|
|
|
1573
2397
|
]) if (key in extra) throw new Error(`invalid-params: reserved field ${key}`);
|
|
1574
2398
|
const replay = support.planEffortCache({
|
|
1575
2399
|
request,
|
|
1576
|
-
inspection,
|
|
2400
|
+
inspection: false,
|
|
1577
2401
|
effort: params.effort,
|
|
1578
2402
|
capability: capability(request),
|
|
1579
2403
|
bindingFingerprint: support.inspectionFingerprint({
|
|
@@ -1596,13 +2420,14 @@ function createResponsesPort(call, support, fetch, capability) {
|
|
|
1596
2420
|
fileKinds: ["image"]
|
|
1597
2421
|
});
|
|
1598
2422
|
const mediaPlan = support.planMedia(request, media);
|
|
2423
|
+
const reasons = entry?.reasoning !== false;
|
|
1599
2424
|
const settings = {
|
|
1600
2425
|
model: call.model,
|
|
1601
2426
|
endpoint: call.providerId,
|
|
1602
2427
|
effort: params.thinking === false ? "none" : replay.baseEffort ?? (params.thinking === true ? options.thinkingOnEffort : void 0),
|
|
1603
2428
|
reasoningReplay: options.reasoningReplay,
|
|
1604
|
-
reasoningSummary: options.reasoningSummary,
|
|
1605
|
-
encryptedReasoningInclude: options.encryptedReasoningInclude,
|
|
2429
|
+
reasoningSummary: reasons ? options.reasoningSummary : false,
|
|
2430
|
+
encryptedReasoningInclude: reasons ? options.encryptedReasoningInclude : false,
|
|
1606
2431
|
effortUpdates: replay.updates
|
|
1607
2432
|
};
|
|
1608
2433
|
let maxTokens = params.maxTokens;
|
|
@@ -1610,53 +2435,132 @@ function createResponsesPort(call, support, fetch, capability) {
|
|
|
1610
2435
|
if (!Number.isSafeInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0) throw new Error("summaryMaxTokens must be a positive integer");
|
|
1611
2436
|
maxTokens = Math.min(maxTokens ?? Infinity, Number(request.summaryMaxTokens));
|
|
1612
2437
|
}
|
|
2438
|
+
const toolsWithheld = options.toolChoiceNone === false && request.toolChoice === "none" && (request.tools?.length ?? 0) > 0;
|
|
2439
|
+
const continuation = request.purpose === "summary" && request.summaryShape === "continuation";
|
|
2440
|
+
const rendered = toResponsesBody(toolsWithheld ? {
|
|
2441
|
+
...request,
|
|
2442
|
+
tools: []
|
|
2443
|
+
} : request, settings, mediaPlan);
|
|
2444
|
+
const body = support.freezePayload({
|
|
2445
|
+
...rendered,
|
|
2446
|
+
...maxTokens === void 0 ? {} : { max_output_tokens: maxTokens },
|
|
2447
|
+
...params.temperature === void 0 ? {} : { temperature: params.temperature },
|
|
2448
|
+
...request.cacheKey && options.promptCacheKey !== false ? { prompt_cache_key: request.cacheKey } : {},
|
|
2449
|
+
...request.purpose === "summary" && !continuation ? {} : extra,
|
|
2450
|
+
...continuation && maxTokens !== void 0 ? { max_output_tokens: maxTokens } : {},
|
|
2451
|
+
...continuation && "tool_choice" in rendered ? { tool_choice: rendered.tool_choice } : {}
|
|
2452
|
+
});
|
|
2453
|
+
const fields = responsesSemanticFields(body, mediaPlan);
|
|
2454
|
+
const receipts = new Map(replay.replaySources?.map((source) => [source.messageId, JSON.stringify(source.contribution)]));
|
|
1613
2455
|
return {
|
|
1614
|
-
body
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
},
|
|
1624
|
-
replay,
|
|
1625
|
-
entry,
|
|
2456
|
+
body,
|
|
2457
|
+
replaySelections: support.prepareReplaySelections(request, ({ message, part }) => part ? responsesReplayChoice(message, part, settings) : {
|
|
2458
|
+
mode: "effort-cache",
|
|
2459
|
+
textIncluded: false,
|
|
2460
|
+
selectedText: receipts.get(message.id),
|
|
2461
|
+
reason: "not-applicable"
|
|
2462
|
+
}),
|
|
2463
|
+
replay: support.freezePayload(replay),
|
|
2464
|
+
capacity: support.freezePayload(entry?.limit ?? {}),
|
|
1626
2465
|
mediaPlan,
|
|
1627
|
-
|
|
1628
|
-
|
|
2466
|
+
maxTokens,
|
|
2467
|
+
toolsWithheld,
|
|
2468
|
+
fields,
|
|
2469
|
+
hiddenInputTokens: responsesHiddenInputTokens(request, settings),
|
|
2470
|
+
request: {
|
|
2471
|
+
...request,
|
|
2472
|
+
params: support.freezePayload(request.params ?? {})
|
|
2473
|
+
},
|
|
2474
|
+
connection: {
|
|
2475
|
+
baseURL: String(call.config.baseUrl),
|
|
2476
|
+
apiKey: call.secrets.apiKey,
|
|
2477
|
+
model: call.model
|
|
2478
|
+
},
|
|
2479
|
+
fingerprint: support.freezePayload({
|
|
2480
|
+
protocol: "openai-responses",
|
|
2481
|
+
model: call.model,
|
|
2482
|
+
config: call.config,
|
|
2483
|
+
params: request.params,
|
|
2484
|
+
updates: replay.updates
|
|
2485
|
+
})
|
|
1629
2486
|
};
|
|
1630
2487
|
}
|
|
1631
|
-
return {
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
return
|
|
2488
|
+
return support.createPreparedPort({
|
|
2489
|
+
prepare: build,
|
|
2490
|
+
semantics(payload) {
|
|
2491
|
+
return {
|
|
2492
|
+
replaySelections: payload.replaySelections,
|
|
2493
|
+
mediaSelections: () => support.mediaSelections(payload.mediaPlan),
|
|
2494
|
+
toolDefinitions: payload.body.tools ?? Object.freeze([]),
|
|
2495
|
+
parameters: Object.freeze(Object.fromEntries(Object.entries(payload.body).filter(([key]) => ![
|
|
2496
|
+
"model",
|
|
2497
|
+
"input",
|
|
2498
|
+
"instructions",
|
|
2499
|
+
"tools",
|
|
2500
|
+
"stream",
|
|
2501
|
+
"store",
|
|
2502
|
+
"prompt_cache_key"
|
|
2503
|
+
].includes(key)))),
|
|
2504
|
+
format: "request-semantic-v1",
|
|
2505
|
+
protocolId: "openai-responses",
|
|
2506
|
+
adapterVersion: "1",
|
|
2507
|
+
rendererVersion: "responses-v1",
|
|
2508
|
+
frames: () => support.semanticFrames(payload.body, {
|
|
2509
|
+
omitRoot: [
|
|
2510
|
+
"stream",
|
|
2511
|
+
"store",
|
|
2512
|
+
"prompt_cache_key"
|
|
2513
|
+
],
|
|
2514
|
+
fields: payload.fields
|
|
2515
|
+
})
|
|
2516
|
+
};
|
|
2517
|
+
},
|
|
2518
|
+
async inspect(payload, signal) {
|
|
2519
|
+
signal.throwIfAborted();
|
|
2520
|
+
const started = support.performance?.now();
|
|
2521
|
+
const { body, request, capacity, mediaPlan, maxTokens, hiddenInputTokens, fingerprint, toolsWithheld } = payload;
|
|
2522
|
+
support.performance?.observe({
|
|
2523
|
+
stage: "model.project",
|
|
2524
|
+
measurementPurpose: "request",
|
|
2525
|
+
durationMs: support.performance.now() - started,
|
|
2526
|
+
count: 1
|
|
2527
|
+
});
|
|
2528
|
+
const text = support.requestText("responses", body);
|
|
2529
|
+
const inspection = support.inspect({
|
|
1635
2530
|
body,
|
|
1636
2531
|
request,
|
|
1637
|
-
textTokens:
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
2532
|
+
textTokens: 0,
|
|
2533
|
+
textBytes: Buffer.byteLength(text),
|
|
2534
|
+
tokenizer: "utf8-bytes-quarter-v1",
|
|
2535
|
+
capacity,
|
|
2536
|
+
outputReserve: maxTokens ?? capacity.output ?? 0,
|
|
1641
2537
|
outputReserveSource: maxTokens === void 0 ? "capacity" : "enforced",
|
|
1642
|
-
hiddenInputTokens
|
|
2538
|
+
hiddenInputTokens,
|
|
1643
2539
|
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
|
-
}
|
|
2540
|
+
fingerprint
|
|
1652
2541
|
});
|
|
2542
|
+
const textTokens = await support.measureText(text, signal);
|
|
2543
|
+
signal.throwIfAborted();
|
|
2544
|
+
return {
|
|
2545
|
+
...inspection,
|
|
2546
|
+
inputTokens: inspection.inputTokens + textTokens,
|
|
2547
|
+
...toolsWithheld ? { toolsWithheld: true } : {}
|
|
2548
|
+
};
|
|
1653
2549
|
},
|
|
1654
|
-
stream(
|
|
2550
|
+
stream(payload, signal, observer, scope) {
|
|
1655
2551
|
signal.throwIfAborted();
|
|
1656
|
-
const { body, replay } =
|
|
2552
|
+
const { body, replay, connection } = payload;
|
|
2553
|
+
const dispatchEffort = body.reasoning?.effort === "none" ? "none" : replay.effectiveEffort ?? body.reasoning?.effort;
|
|
1657
2554
|
return support.withChatAttempts({
|
|
2555
|
+
retainCleanup: scope.retainCleanup,
|
|
2556
|
+
beforeAttempt: (_signal, ordinal) => observer?.beforeAttempt?.(ordinal),
|
|
2557
|
+
accountingDispatch: call.accountingDispatch,
|
|
2558
|
+
effective: {
|
|
2559
|
+
outputLimit: body.max_output_tokens,
|
|
2560
|
+
effort: body.reasoning?.effort
|
|
2561
|
+
},
|
|
1658
2562
|
signal,
|
|
1659
|
-
async *attempt(attemptSignal, reportProgress, attempt) {
|
|
2563
|
+
async *attempt(attemptSignal, reportProgress, attempt, usageReporter) {
|
|
1660
2564
|
const observe = (event) => {
|
|
1661
2565
|
try {
|
|
1662
2566
|
observer?.observe?.(event);
|
|
@@ -1664,8 +2568,44 @@ function createResponsesPort(call, support, fetch, capability) {
|
|
|
1664
2568
|
};
|
|
1665
2569
|
const attemptCount = attempt + 1;
|
|
1666
2570
|
let outcome = "unknown";
|
|
2571
|
+
let timeout;
|
|
2572
|
+
const abortedOutcome = () => {
|
|
2573
|
+
const reason = support.failures.verified(attemptSignal.reason);
|
|
2574
|
+
if (reason?.code !== "stream-idle-timeout") return "cancelled";
|
|
2575
|
+
timeout = reason;
|
|
2576
|
+
return "timeout";
|
|
2577
|
+
};
|
|
1667
2578
|
let firstResponseFinished = false;
|
|
1668
2579
|
let attemptFinished = false;
|
|
2580
|
+
let dispatchObserved = false;
|
|
2581
|
+
const markDispatched = () => {
|
|
2582
|
+
if (dispatchObserved) return;
|
|
2583
|
+
dispatchObserved = true;
|
|
2584
|
+
try {
|
|
2585
|
+
observer?.dispatched({
|
|
2586
|
+
attempt,
|
|
2587
|
+
presentation: {
|
|
2588
|
+
schema: "chat.dispatch-settings.v1",
|
|
2589
|
+
data: {
|
|
2590
|
+
model: {
|
|
2591
|
+
availability: "resolved",
|
|
2592
|
+
value: body.model,
|
|
2593
|
+
origin: "protocol"
|
|
2594
|
+
},
|
|
2595
|
+
effort: dispatchEffort ? {
|
|
2596
|
+
availability: "resolved",
|
|
2597
|
+
value: dispatchEffort,
|
|
2598
|
+
origin: "protocol"
|
|
2599
|
+
} : {
|
|
2600
|
+
availability: "resolved",
|
|
2601
|
+
value: "default",
|
|
2602
|
+
origin: "protocol"
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
});
|
|
2607
|
+
} catch {}
|
|
2608
|
+
};
|
|
1669
2609
|
observe({
|
|
1670
2610
|
stage: "attempt",
|
|
1671
2611
|
phase: "start",
|
|
@@ -1678,12 +2618,18 @@ function createResponsesPort(call, support, fetch, capability) {
|
|
|
1678
2618
|
});
|
|
1679
2619
|
let abortStream;
|
|
1680
2620
|
try {
|
|
2621
|
+
const { default: OpenAI } = await loadOpenAISdk();
|
|
2622
|
+
attemptSignal.throwIfAborted();
|
|
1681
2623
|
const stream = await new OpenAI({
|
|
1682
|
-
apiKey: options.allowUnauthenticated && !
|
|
1683
|
-
...options.allowUnauthenticated && !
|
|
1684
|
-
baseURL:
|
|
2624
|
+
apiKey: options.allowUnauthenticated && !connection.apiKey ? "not-used" : connection.apiKey ?? "",
|
|
2625
|
+
...options.allowUnauthenticated && !connection.apiKey ? { defaultHeaders: { Authorization: null } } : {},
|
|
2626
|
+
baseURL: connection.baseURL,
|
|
1685
2627
|
maxRetries: 0,
|
|
1686
|
-
fetch: async (...args) =>
|
|
2628
|
+
fetch: async (...args) => {
|
|
2629
|
+
const pending = fetch(...args);
|
|
2630
|
+
markDispatched();
|
|
2631
|
+
return support.observeResponseProgress(await pending, reportProgress);
|
|
2632
|
+
}
|
|
1687
2633
|
}).responses.create(body, { signal: attemptSignal });
|
|
1688
2634
|
abortStream = () => stream.controller.abort();
|
|
1689
2635
|
firstResponseFinished = true;
|
|
@@ -1693,16 +2639,16 @@ function createResponsesPort(call, support, fetch, capability) {
|
|
|
1693
2639
|
attempt: attemptCount,
|
|
1694
2640
|
outcome: "ok"
|
|
1695
2641
|
});
|
|
1696
|
-
try {
|
|
1697
|
-
observer?.dispatched({ attempt });
|
|
1698
|
-
} catch {}
|
|
1699
2642
|
const observed = (async function* () {
|
|
1700
2643
|
for await (const event of stream) {
|
|
1701
2644
|
reportProgress();
|
|
1702
2645
|
yield event;
|
|
1703
2646
|
}
|
|
1704
2647
|
})();
|
|
1705
|
-
for await (const chunk of mapResponsesStream(observed, {
|
|
2648
|
+
for await (const chunk of mapResponsesStream(observed, {
|
|
2649
|
+
model: connection.model,
|
|
2650
|
+
usageReporter
|
|
2651
|
+
})) {
|
|
1706
2652
|
attemptSignal.throwIfAborted();
|
|
1707
2653
|
if (chunk.kind === "final") {
|
|
1708
2654
|
outcome = "ok";
|
|
@@ -1720,33 +2666,41 @@ function createResponsesPort(call, support, fetch, capability) {
|
|
|
1720
2666
|
} : chunk;
|
|
1721
2667
|
}
|
|
1722
2668
|
} catch (error) {
|
|
1723
|
-
outcome = attemptSignal.aborted ?
|
|
2669
|
+
outcome = attemptSignal.aborted ? abortedOutcome() : "error";
|
|
1724
2670
|
throw error;
|
|
1725
2671
|
} finally {
|
|
1726
|
-
if (attemptSignal.aborted && !attemptFinished) outcome =
|
|
2672
|
+
if (attemptSignal.aborted && !attemptFinished) outcome = abortedOutcome();
|
|
1727
2673
|
abortStream?.();
|
|
1728
2674
|
if (!firstResponseFinished) observe({
|
|
1729
2675
|
stage: "first-response",
|
|
1730
2676
|
phase: "end",
|
|
1731
2677
|
attempt: attemptCount,
|
|
1732
|
-
outcome
|
|
2678
|
+
outcome,
|
|
2679
|
+
...timeout ? { failure: timeout } : {}
|
|
1733
2680
|
});
|
|
1734
2681
|
if (!attemptFinished) observe({
|
|
1735
2682
|
stage: "attempt",
|
|
1736
2683
|
phase: "end",
|
|
1737
2684
|
attempt: attemptCount,
|
|
1738
|
-
outcome
|
|
2685
|
+
outcome,
|
|
2686
|
+
...timeout ? { failure: timeout } : {}
|
|
1739
2687
|
});
|
|
1740
2688
|
}
|
|
1741
2689
|
},
|
|
1742
2690
|
classify(error) {
|
|
1743
|
-
const failure = error instanceof ResponsesStreamError ? support.failures.create({
|
|
2691
|
+
const failure = error instanceof ResponsesStreamError ? error.failureCode === "context-window-exceeded" ? support.failures.create({
|
|
2692
|
+
code: error.failureCode,
|
|
2693
|
+
stage: "request",
|
|
2694
|
+
source: "protocol",
|
|
2695
|
+
category: "request-too-large",
|
|
2696
|
+
retryable: false
|
|
2697
|
+
}) : support.failures.create({
|
|
1744
2698
|
code: error.failureCode,
|
|
1745
2699
|
stage: "stream",
|
|
1746
2700
|
source: "protocol",
|
|
1747
2701
|
category: error.retryable ? "network" : "protocol",
|
|
1748
2702
|
retryable: error.retryable
|
|
1749
|
-
}) : toModelFailure(error, support.failures);
|
|
2703
|
+
}) : toModelFailure(error, support.failures, support.transportFailure);
|
|
1750
2704
|
return {
|
|
1751
2705
|
error: failure,
|
|
1752
2706
|
retryable: failure.retryable === true,
|
|
@@ -1755,7 +2709,7 @@ function createResponsesPort(call, support, fetch, capability) {
|
|
|
1755
2709
|
}
|
|
1756
2710
|
});
|
|
1757
2711
|
}
|
|
1758
|
-
};
|
|
2712
|
+
});
|
|
1759
2713
|
}
|
|
1760
2714
|
//#endregion
|
|
1761
2715
|
//#region src/responses/protocol.ts
|
|
@@ -1770,7 +2724,6 @@ function capability(input) {
|
|
|
1770
2724
|
};
|
|
1771
2725
|
return { status: "supported" };
|
|
1772
2726
|
}
|
|
1773
|
-
/** Registers the HTTP Responses API independently from Chat Completions. */
|
|
1774
2727
|
function responsesProtocolType(support, fetch) {
|
|
1775
2728
|
return {
|
|
1776
2729
|
type: "openai-responses",
|
|
@@ -1790,20 +2743,19 @@ function responsesProtocolType(support, fetch) {
|
|
|
1790
2743
|
adapters: { chat: {
|
|
1791
2744
|
fileKinds: ["image"],
|
|
1792
2745
|
supportsModel: () => true,
|
|
1793
|
-
createPort: (call) => createResponsesPort(call, support, fetch, (request) => capability({
|
|
2746
|
+
createPort: (call) => createResponsesPort(call, support, withConnectionHeaders(fetch, call.headers), (request) => capability({
|
|
1794
2747
|
...call,
|
|
1795
2748
|
params: request.params ?? {},
|
|
1796
2749
|
explicitKeys: []
|
|
1797
2750
|
}))
|
|
1798
2751
|
} },
|
|
1799
2752
|
normalizeListing: (input) => normalizeOffers(input),
|
|
1800
|
-
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, fetch) }),
|
|
1801
|
-
testConnection: (probe) => probeOpenAI.testConnection(probe, fetch, "responses")
|
|
2753
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, withConnectionHeaders(fetch, probe.headers)) }),
|
|
2754
|
+
testConnection: (probe) => probeOpenAI.testConnection(probe, withConnectionHeaders(fetch, probe.headers), "responses")
|
|
1802
2755
|
};
|
|
1803
2756
|
}
|
|
1804
2757
|
//#endregion
|
|
1805
2758
|
//#region src/index.ts
|
|
1806
|
-
/** Protocol extensions contribute no tools. */
|
|
1807
2759
|
const TOOL_NAMES = [];
|
|
1808
2760
|
const plugin = {
|
|
1809
2761
|
name: "@eum-agent/llm-protocol-openai",
|
|
@@ -1817,6 +2769,8 @@ const plugin = {
|
|
|
1817
2769
|
ctx.modelProtocols.register(openaiProtocolType(support, network.fetch));
|
|
1818
2770
|
ctx.modelProtocols.register(responsesProtocolType(support, network.fetch));
|
|
1819
2771
|
ctx.modelProtocols.register(imagesProtocolType(support, network.fetch));
|
|
2772
|
+
ctx.modelProtocols.register(decisionsProtocolType(network.fetch));
|
|
2773
|
+
ctx.modelProtocols.register(embeddingsProtocolType(network.fetch));
|
|
1820
2774
|
}
|
|
1821
2775
|
};
|
|
1822
2776
|
//#endregion
|