@eum-agent/llm-protocol-openai 0.0.0-stage → 1.0.1

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.
Files changed (3) hide show
  1. package/dist/index.js +833 -0
  2. package/package.json +42 -3
  3. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,833 @@
1
+ import { z } from "zod";
2
+ import OpenAI, { APIConnectionError, APIError } from "openai";
3
+ //#region src/protocol/facts.ts
4
+ /** Parameter ranges and request limits for this provider wire. */
5
+ const facts = {
6
+ outputLimit: { support: "optional" },
7
+ temperature: {
8
+ min: 0,
9
+ max: 2,
10
+ step: .05,
11
+ default: 1
12
+ },
13
+ thinkingSwitch: false,
14
+ limits: {
15
+ requestBytes: 20971520,
16
+ images: 50
17
+ }
18
+ };
19
+ //#endregion
20
+ //#region src/protocol/errors.ts
21
+ /**
22
+ * SDK exceptions have two consumers: explicit probes retain provider text for
23
+ * their credential-redaction boundary, while Agent calls accept only fixed
24
+ * templates and allowlisted facts through the host factory.
25
+ */
26
+ /** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
27
+ * every other status is not. */
28
+ function isRetryableStatus(status) {
29
+ return status === 408 || status === 409 || status === 429 || status !== void 0 && status >= 500;
30
+ }
31
+ function retryAfterMs(error) {
32
+ if (!(error instanceof APIError)) return void 0;
33
+ const header = error.headers?.get("retry-after");
34
+ if (!header) return void 0;
35
+ const seconds = Number(header);
36
+ if (!Number.isFinite(seconds) || seconds < 0) return void 0;
37
+ const milliseconds = seconds * 1e3;
38
+ return Number.isFinite(milliseconds) ? milliseconds : void 0;
39
+ }
40
+ /** Maps verified SDK classes and factory identities to bounded Agent failure candidates. */
41
+ function toModelFailure(error, failures) {
42
+ if (failures.owns(error)) return error;
43
+ if (!(error instanceof APIError)) return failures.create({
44
+ code: "unknown",
45
+ stage: "unknown",
46
+ category: "unknown",
47
+ source: "unknown",
48
+ retryable: false
49
+ });
50
+ const rawCode = error.code ?? error.type;
51
+ const providerCode = typeof rawCode === "string" && (/* @__PURE__ */ new Set([
52
+ "usage_not_included",
53
+ "usage_limit_reached",
54
+ "insufficient_quota",
55
+ "context_length_exceeded",
56
+ "rate_limit_exceeded",
57
+ "overloaded_error",
58
+ "api_error",
59
+ "rate_limit_error",
60
+ "cyber_policy",
61
+ "invalid_prompt",
62
+ "bio_policy",
63
+ "misalignment_policy_violation"
64
+ ])).has(rawCode) ? rawCode : void 0;
65
+ const connection = error instanceof APIConnectionError;
66
+ const status = Number.isInteger(error.status) && Number(error.status) >= 100 && Number(error.status) <= 599 ? error.status : void 0;
67
+ return failures.create({
68
+ code: connection ? "stream-interrupted" : status === 413 ? "request-too-large" : status === void 0 ? "provider-error" : "http-error",
69
+ stage: connection ? "transport" : status === 413 ? "request" : status === void 0 ? "stream" : "transport",
70
+ category: connection ? "network" : status === 413 ? "request-too-large" : "provider",
71
+ source: connection ? "transport" : "protocol",
72
+ ...status === void 0 ? {} : { status },
73
+ retryable: connection || isRetryableStatus(status),
74
+ ...providerCode === void 0 ? {} : { providerCode }
75
+ });
76
+ }
77
+ //#endregion
78
+ //#region src/protocol/request.ts
79
+ function textOf(parts) {
80
+ const text = parts.filter((part) => part.type === "text").map((part) => part.text).join("");
81
+ return text.length > 0 ? text : null;
82
+ }
83
+ function toolCallsOf(parts) {
84
+ const calls = parts.filter((part) => part.type === "tool-use").map((part) => ({
85
+ id: part.id,
86
+ type: "function",
87
+ function: {
88
+ name: part.name,
89
+ arguments: JSON.stringify(part.input ?? {})
90
+ }
91
+ }));
92
+ return calls.length > 0 ? calls : void 0;
93
+ }
94
+ function imagePart(planned) {
95
+ return {
96
+ type: "image_url",
97
+ image_url: { url: `data:${planned.mediaType};base64,${planned.data ?? ""}` }
98
+ };
99
+ }
100
+ /** A user message's parts in order: text, and each file as its label and
101
+ * image, or as the line standing in for it. A message whose parts are all
102
+ * text stays the one string it always was. */
103
+ function userContent(message, index, plan) {
104
+ if (!message.content.some((part) => part.type === "file")) return textOf(message.content) ?? "";
105
+ const parts = [];
106
+ let text = "";
107
+ const flush = () => {
108
+ if (text.length > 0) parts.push({
109
+ type: "text",
110
+ text
111
+ });
112
+ text = "";
113
+ };
114
+ message.content.forEach((part, partIndex) => {
115
+ if (part.type === "text") text += part.text;
116
+ else if (part.type === "file") {
117
+ const planned = plan.at(index, partIndex);
118
+ flush();
119
+ parts.push({
120
+ type: "text",
121
+ text: planned.label
122
+ });
123
+ if (planned.fate === "send") parts.push(imagePart(planned));
124
+ }
125
+ });
126
+ flush();
127
+ return parts.every((part) => part.type === "text") ? parts.map((part) => part.text).join("\n") : parts;
128
+ }
129
+ /** One kernel message becomes zero or more wire messages: a `user`
130
+ * message's `tool-result` parts each become their own `role: 'tool'`
131
+ * message. Assistant replies without text or tool calls are omitted after
132
+ * reasoning is stripped; the endpoint requires at least one of those fields.
133
+ *
134
+ * A `role: 'tool'` message holds text alone, so the images a batch of
135
+ * results handed back follow it in one user message, each after the id of
136
+ * the call it came from; an image standing in as a line of text stays in
137
+ * its call's own tool message. */
138
+ function toChatMessages(message, index, plan, reasoningReplay) {
139
+ const toolResults = message.content.map((part, partIndex) => ({
140
+ part,
141
+ partIndex
142
+ })).filter((entry) => entry.part.type === "tool-result");
143
+ if (message.role === "user" && toolResults.length > 0) {
144
+ const images = [];
145
+ const tools = toolResults.map(({ part, partIndex }) => {
146
+ const lines = [part.content];
147
+ (part.files ?? []).forEach((_, fileIndex) => {
148
+ const planned = plan.at(index, partIndex, fileIndex);
149
+ if (planned.fate !== "send") {
150
+ lines.push(planned.label);
151
+ return;
152
+ }
153
+ images.push({
154
+ type: "text",
155
+ text: `${part.toolUseId} ${planned.label}`
156
+ }, imagePart(planned));
157
+ });
158
+ return {
159
+ role: "tool",
160
+ content: lines.filter((line) => line !== "").join("\n"),
161
+ tool_call_id: part.toolUseId
162
+ };
163
+ });
164
+ return images.length === 0 ? tools : [...tools, {
165
+ role: "user",
166
+ content: [{
167
+ type: "text",
168
+ text: "Images returned by tool calls:"
169
+ }, ...images]
170
+ }];
171
+ }
172
+ if (message.role === "assistant") {
173
+ const content = textOf(message.content);
174
+ const toolCalls = toolCallsOf(message.content);
175
+ if (content === null && toolCalls === void 0) return [];
176
+ return [{
177
+ role: "assistant",
178
+ content,
179
+ ...reasoningReplay === "reasoning-content" && message.outputTruncation?.incompleteThinking !== true ? { reasoning_content: message.content.filter((part) => part.type === "thinking").map((part) => part.text).join("") } : {},
180
+ ...toolCalls === void 0 ? {} : { tool_calls: toolCalls }
181
+ }];
182
+ }
183
+ return [{
184
+ role: "user",
185
+ content: userContent(message, index, plan)
186
+ }];
187
+ }
188
+ /**
189
+ * The volatile slot's contributions, as one standalone message to put after
190
+ * everything `toChatMessages` produced.
191
+ *
192
+ * **Appended unconditionally, without looking at what the last message is.**
193
+ * `toChatMessages` turns a user message carrying `tool-result` parts into
194
+ * `role: 'tool'` messages and drops its text parts, so writing the text into
195
+ * the last message — the anthropic member's shape — would lose it silently on
196
+ * the most common path there is: the step right after a tool call, which is
197
+ * when a volatile contribution first reaches the model. One message of its
198
+ * own has no such branch, and it puts the invariant in the code rather than
199
+ * in a reviewer's head.
200
+ *
201
+ * Nothing is added when there is nothing to add — an absent slot, an empty
202
+ * one, and one whose contributions are all empty leave the request the
203
+ * caller would have got anyway.
204
+ */
205
+ function volatileMessages(volatile) {
206
+ const content = (volatile ?? []).map((note) => note.text).join("\n\n");
207
+ return content.length > 0 ? [{
208
+ role: "user",
209
+ content
210
+ }] : [];
211
+ }
212
+ /** A reply's recorded notes go just before it — where the request that
213
+ * produced it carried them — so every request extends the previous one. */
214
+ function withNotes(message, index, plan, reasoningReplay) {
215
+ return [...message.role === "assistant" ? volatileMessages(message.volatile) : [], ...toChatMessages(message, index, plan, reasoningReplay)];
216
+ }
217
+ function toToolParam(tool) {
218
+ return {
219
+ type: "function",
220
+ function: {
221
+ name: tool.name,
222
+ description: tool.description,
223
+ parameters: tool.inputSchema
224
+ }
225
+ };
226
+ }
227
+ /** Renders provider history without empty assistant messages; rejects invalid summary budgets. */
228
+ function toOpenAIRequest(request, options) {
229
+ const summary = request.purpose === "summary";
230
+ if (summary && (!Number.isInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0)) throw new Error("summaryMaxTokens must be a positive integer for a summary request");
231
+ const tools = request.tools && request.tools.length > 0 ? request.tools.map(toToolParam) : [];
232
+ const maxTokens = summary ? Math.min(request.summaryMaxTokens, Number.isInteger(options.maxTokens) && Number(options.maxTokens) > 0 ? options.maxTokens : request.summaryMaxTokens) : options.maxTokens;
233
+ const plan = options.support.planMedia(request, options.media ?? {
234
+ acceptsImages: true,
235
+ limits: void 0
236
+ });
237
+ const systemMessage = request.system ? [{
238
+ role: "system",
239
+ content: request.system.join("\n\n")
240
+ }] : [];
241
+ return {
242
+ model: options.model,
243
+ stream: true,
244
+ stream_options: { include_usage: true },
245
+ messages: [
246
+ ...systemMessage,
247
+ ...request.messages.flatMap((message, index) => withNotes(message, index, plan, options.reasoningReplay)),
248
+ ...volatileMessages(request.volatile)
249
+ ],
250
+ ...tools.length === 0 ? {} : { tools },
251
+ ...request.toolChoice === "none" && tools.length > 0 ? { tool_choice: "none" } : {},
252
+ ...options.reasoningEffort === void 0 ? {} : { reasoning_effort: options.reasoningEffort },
253
+ ...options.thinkingField === true && options.thinking !== void 0 ? { thinking: { type: options.thinking ? "enabled" : "disabled" } } : {},
254
+ ...options.temperature === void 0 ? {} : { temperature: options.temperature },
255
+ ...maxTokens === void 0 ? {} : { [options.outputLimitField ?? "max_tokens"]: maxTokens },
256
+ ...options.promptCacheKey === true && request.cacheKey !== void 0 ? { prompt_cache_key: request.cacheKey } : {},
257
+ ...summary ? {} : options.extra
258
+ };
259
+ }
260
+ //#endregion
261
+ //#region src/protocol/stream.ts
262
+ function cacheOf(usage) {
263
+ const read = usage.prompt_tokens_details?.cached_tokens ?? usage.prompt_cache_hit_tokens;
264
+ return typeof read === "number" && read >= 0 ? { cacheReadTokens: read } : {};
265
+ }
266
+ function toFinishReason(reason, support) {
267
+ switch (reason) {
268
+ case "tool_calls": return "tool-calls";
269
+ case "length": return "max-tokens";
270
+ case "content_filter": return "refusal";
271
+ case "stop": return "stop";
272
+ default: throw support.failures.create({
273
+ code: reason === null ? "finish-reason-missing" : "finish-reason-unsupported",
274
+ stage: "response-validation",
275
+ category: "protocol",
276
+ source: "protocol",
277
+ retryable: false
278
+ });
279
+ }
280
+ }
281
+ /** The accumulated arguments as JSON, or `undefined` when they will not
282
+ * parse — which is what a tool call the endpoint cut off at its output cap
283
+ * looks like. `JSON.parse` never produces `undefined` itself, so it is free
284
+ * to stand for "no usable input here". */
285
+ function parseToolInput(argumentsJson) {
286
+ if (argumentsJson.length === 0) return {};
287
+ try {
288
+ return JSON.parse(argumentsJson);
289
+ } catch {
290
+ return;
291
+ }
292
+ }
293
+ /**
294
+ * Streams provider deltas and one validated final reply. Missing terminal reasons,
295
+ * unknown reasons and replies without text or usable tool calls fail without retry.
296
+ * A stream with neither usage nor a terminal reason retains interruption semantics.
297
+ */
298
+ async function* mapOpenAIStream(chunks, support) {
299
+ const textParts = [];
300
+ const thinkingParts = [];
301
+ const toolCalls = /* @__PURE__ */ new Map();
302
+ const toolCallOrder = [];
303
+ let inputTokens = 0;
304
+ let outputTokens = 0;
305
+ let finishReason = "stop";
306
+ let rawFinishReason = null;
307
+ let cache = {};
308
+ let ended = false;
309
+ let refusalText;
310
+ let thinkingOpen = false;
311
+ for await (const chunk of chunks) {
312
+ if (chunk.usage) {
313
+ inputTokens = chunk.usage.prompt_tokens;
314
+ outputTokens = chunk.usage.completion_tokens;
315
+ cache = cacheOf(chunk.usage);
316
+ ended = true;
317
+ }
318
+ const choice = chunk.choices[0];
319
+ if (!choice) continue;
320
+ const delta = choice.delta;
321
+ const reasoningContent = delta.reasoning_content || (typeof delta.reasoning === "string" ? delta.reasoning : void 0);
322
+ if (reasoningContent) {
323
+ thinkingOpen = true;
324
+ thinkingParts.push(reasoningContent);
325
+ yield {
326
+ kind: "thinking-delta",
327
+ text: reasoningContent
328
+ };
329
+ }
330
+ if (choice.delta.content) {
331
+ thinkingOpen = false;
332
+ textParts.push(choice.delta.content);
333
+ yield {
334
+ kind: "text-delta",
335
+ text: choice.delta.content
336
+ };
337
+ }
338
+ if (choice.delta.refusal) refusalText = (refusalText ?? "") + choice.delta.refusal;
339
+ for (const delta of choice.delta.tool_calls ?? []) {
340
+ thinkingOpen = false;
341
+ let state = toolCalls.get(delta.index);
342
+ if (!state) {
343
+ if (!delta.id || !delta.function?.name) throw support.failures.create({
344
+ code: "response-invalid",
345
+ stage: "response-validation",
346
+ category: "protocol",
347
+ source: "protocol",
348
+ retryable: false
349
+ });
350
+ state = {
351
+ id: delta.id,
352
+ name: delta.function.name,
353
+ arguments: ""
354
+ };
355
+ toolCalls.set(delta.index, state);
356
+ toolCallOrder.push(delta.index);
357
+ yield {
358
+ kind: "tool-call-delta",
359
+ id: state.id,
360
+ name: state.name,
361
+ inputDelta: ""
362
+ };
363
+ if (delta.function.arguments) {
364
+ state.arguments += delta.function.arguments;
365
+ yield {
366
+ kind: "tool-call-delta",
367
+ id: state.id,
368
+ inputDelta: delta.function.arguments
369
+ };
370
+ }
371
+ continue;
372
+ }
373
+ const argumentsDelta = delta.function?.arguments ?? "";
374
+ if (argumentsDelta.length === 0) continue;
375
+ state.arguments += argumentsDelta;
376
+ yield {
377
+ kind: "tool-call-delta",
378
+ id: state.id,
379
+ inputDelta: argumentsDelta
380
+ };
381
+ }
382
+ if (choice.finish_reason) {
383
+ rawFinishReason = choice.finish_reason;
384
+ finishReason = toFinishReason(choice.finish_reason, support);
385
+ ended = true;
386
+ }
387
+ }
388
+ if (!ended) throw support.interruptedFailure();
389
+ if (rawFinishReason === null) throw support.failures.create({
390
+ code: "finish-reason-missing",
391
+ stage: "response-validation",
392
+ category: "protocol",
393
+ source: "protocol",
394
+ retryable: false
395
+ });
396
+ const content = [];
397
+ const thinkingText = thinkingParts.join("");
398
+ if (thinkingText.length > 0) content.push({
399
+ type: "thinking",
400
+ text: thinkingText
401
+ });
402
+ const text = refusalText ?? textParts.join("");
403
+ if (text.length > 0) content.push({
404
+ type: "text",
405
+ text
406
+ });
407
+ const incompleteToolCalls = [];
408
+ for (const index of toolCallOrder) {
409
+ const call = toolCalls.get(index);
410
+ if (!call) continue;
411
+ const input = finishReason === "max-tokens" && call.arguments.trim() === "" ? void 0 : parseToolInput(call.arguments);
412
+ if (input === void 0) {
413
+ if (finishReason !== "max-tokens") throw support.failures.create({
414
+ code: "response-invalid",
415
+ stage: "response-validation",
416
+ category: "protocol",
417
+ source: "protocol",
418
+ retryable: false,
419
+ finishReason
420
+ });
421
+ incompleteToolCalls.push({
422
+ id: call.id,
423
+ name: call.name
424
+ });
425
+ continue;
426
+ }
427
+ content.push({
428
+ type: "tool-use",
429
+ id: call.id,
430
+ name: call.name,
431
+ input
432
+ });
433
+ }
434
+ if (finishReason !== "refusal" && finishReason !== "max-tokens" && !content.some((part) => part.type === "text" || part.type === "tool-use")) throw support.failures.create({
435
+ code: "response-empty",
436
+ stage: "response-validation",
437
+ category: "protocol",
438
+ source: "protocol",
439
+ retryable: false,
440
+ finishReason
441
+ });
442
+ yield {
443
+ kind: "final",
444
+ finishReason,
445
+ ...finishReason === "max-tokens" ? { outputTruncation: {
446
+ incompleteToolCalls,
447
+ ...thinkingOpen ? { incompleteThinking: true } : {}
448
+ } } : {},
449
+ usage: {
450
+ inputTokens,
451
+ outputTokens,
452
+ ...cache
453
+ },
454
+ ...finishReason === "refusal" ? { refusalCategory: "content_filter" } : {},
455
+ message: {
456
+ role: "assistant",
457
+ content
458
+ }
459
+ };
460
+ }
461
+ //#endregion
462
+ //#region src/protocol/port.ts
463
+ /** The neutral plan in this family's spelling: on and off go out as the
464
+ * endpoint's `thinking` field where it has one, else as `effort: 'none'`,
465
+ * which `params.ts` already put in the plan. */
466
+ function openaiOptions(plan) {
467
+ return {
468
+ ...plan.effort === void 0 ? {} : { reasoningEffort: plan.effort },
469
+ ...plan.thinking === void 0 ? {} : { thinking: plan.thinking },
470
+ ...plan.temperature === void 0 ? {} : { temperature: plan.temperature },
471
+ ...plan.maxTokens === void 0 ? {} : { maxTokens: plan.maxTokens }
472
+ };
473
+ }
474
+ /** Creates an OpenAI-compatible port with inspection and partial-stream retry protection. */
475
+ function createOpenAIModelPort(options) {
476
+ function clientForAttempt(reportProgress) {
477
+ return options.client ?? new OpenAI({
478
+ apiKey: options.apiKey ?? "",
479
+ fetch: async (...args) => options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress),
480
+ baseURL: options.baseURL ?? "",
481
+ maxRetries: 0
482
+ });
483
+ }
484
+ function build(request) {
485
+ const capacity = options.catalogue?.()?.limit;
486
+ const outputLimit = Number.isInteger(capacity?.output) && Number(capacity?.output) > 0 ? Number(capacity?.output) : void 0;
487
+ const effectiveRequest = request.purpose === "summary" && outputLimit !== void 0 ? {
488
+ ...request,
489
+ summaryMaxTokens: Math.min(request.summaryMaxTokens ?? 0, outputLimit)
490
+ } : request;
491
+ const { media: mediaOf, ...rest } = options;
492
+ const media = mediaOf?.(request.params ?? {});
493
+ const base = media === void 0 ? rest : {
494
+ ...rest,
495
+ media
496
+ };
497
+ const requestOptions = options.params === void 0 ? base : {
498
+ ...base,
499
+ ...openaiOptions(options.params(request.params ?? {})),
500
+ extra: {
501
+ ...options.extra,
502
+ ...options.support.extraParams(request.params ?? {})
503
+ }
504
+ };
505
+ return {
506
+ params: toOpenAIRequest(effectiveRequest, requestOptions),
507
+ requestOptions,
508
+ capacity
509
+ };
510
+ }
511
+ return {
512
+ inspect(request) {
513
+ const { params, requestOptions, capacity } = build(request);
514
+ const bodyMaxTokens = params.max_tokens;
515
+ const bodyMaxCompletionTokens = params.max_completion_tokens;
516
+ const explicitOutputLimits = [bodyMaxTokens, bodyMaxCompletionTokens].filter((value) => Number.isInteger(value) && Number(value) > 0).map(Number);
517
+ const enforced = Number.isInteger(bodyMaxCompletionTokens) && Number(bodyMaxCompletionTokens) > 0;
518
+ const outputReserve = enforced ? Math.max(...explicitOutputLimits) : capacity?.output ?? Math.max(0, ...explicitOutputLimits);
519
+ return options.support.inspect({
520
+ body: params,
521
+ textTokens: options.support.measureText(options.support.requestText("chat-completions", params)),
522
+ tokenizer: "o200k_base-protocol-text-v2",
523
+ request,
524
+ capacity,
525
+ outputReserve,
526
+ outputReserveSource: enforced ? "enforced" : "capacity",
527
+ mediaTokens: options.support.planMedia(request, requestOptions.media ?? {
528
+ acceptsImages: true,
529
+ limits: void 0
530
+ }).tokens,
531
+ fingerprint: {
532
+ rendering: "openai-chat-completions-v3",
533
+ endpoint: options.endpoint ?? options.baseURL,
534
+ model: params.model,
535
+ purpose: request.purpose,
536
+ contextWindow: request.params?.contextWindow,
537
+ capacity,
538
+ settings: {
539
+ reasoningEffort: requestOptions.reasoningEffort,
540
+ temperature: requestOptions.temperature,
541
+ maxTokens: bodyMaxTokens,
542
+ extra: request.purpose === "summary" ? void 0 : requestOptions.extra
543
+ }
544
+ }
545
+ });
546
+ },
547
+ stream(request, signal, observer) {
548
+ signal.throwIfAborted();
549
+ const { params } = build(request);
550
+ return options.support.withChatAttempts({
551
+ signal,
552
+ ...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
553
+ ...options.sleep === void 0 ? {} : { sleep: options.sleep },
554
+ ...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
555
+ async *attempt(attemptSignal, reportProgress, attempt) {
556
+ const observe = (event) => {
557
+ try {
558
+ observer?.observe?.(event);
559
+ } catch {}
560
+ };
561
+ const attemptCount = attempt + 1;
562
+ let outcome = "unknown";
563
+ let firstResponseFinished = false;
564
+ observe({
565
+ stage: "attempt",
566
+ phase: "start",
567
+ attempt: attemptCount
568
+ });
569
+ observe({
570
+ stage: "first-response",
571
+ phase: "start",
572
+ attempt: attemptCount
573
+ });
574
+ try {
575
+ attemptSignal.throwIfAborted();
576
+ const chunks = await clientForAttempt(reportProgress).chat.completions.create(params, { signal: attemptSignal });
577
+ firstResponseFinished = true;
578
+ observe({
579
+ stage: "first-response",
580
+ phase: "end",
581
+ attempt: attemptCount,
582
+ outcome: "ok"
583
+ });
584
+ attemptSignal.throwIfAborted();
585
+ try {
586
+ observer?.dispatched({ attempt });
587
+ } catch {}
588
+ attemptSignal.throwIfAborted();
589
+ const observed = (async function* () {
590
+ for await (const chunk of chunks) {
591
+ reportProgress();
592
+ yield chunk;
593
+ }
594
+ })();
595
+ for await (const chunk of mapOpenAIStream(observed, options.support)) {
596
+ if (chunk.kind === "final") outcome = "ok";
597
+ yield chunk;
598
+ }
599
+ } catch (error) {
600
+ outcome = attemptSignal.aborted ? "cancelled" : "error";
601
+ throw error;
602
+ } finally {
603
+ if (!firstResponseFinished) observe({
604
+ stage: "first-response",
605
+ phase: "end",
606
+ attempt: attemptCount,
607
+ outcome
608
+ });
609
+ observe({
610
+ stage: "attempt",
611
+ phase: "end",
612
+ attempt: attemptCount,
613
+ outcome
614
+ });
615
+ }
616
+ },
617
+ classify(error) {
618
+ const portError = toModelFailure(error, options.support.failures);
619
+ return {
620
+ error: portError,
621
+ retryable: portError.retryable === true,
622
+ retryAfterMs: retryAfterMs(error)
623
+ };
624
+ }
625
+ });
626
+ }
627
+ };
628
+ }
629
+ //#endregion
630
+ //#region src/protocol/probe.ts
631
+ async function readBody(response, maxBytes) {
632
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new Error("invalid response budget");
633
+ const declared = response.headers.get("content-length");
634
+ if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
635
+ await response.body?.cancel();
636
+ throw new Error("read-limit: provider response exceeds its member budget");
637
+ }
638
+ if (!response.body) return {
639
+ text: "",
640
+ bytes: 0
641
+ };
642
+ const reader = response.body.getReader();
643
+ const decoder = new TextDecoder();
644
+ let bytes = 0, text = "";
645
+ try {
646
+ for (;;) {
647
+ const next = await reader.read();
648
+ if (next.done) break;
649
+ bytes += next.value.byteLength;
650
+ if (bytes > maxBytes) {
651
+ await reader.cancel();
652
+ throw new Error("read-limit: provider response exceeds its member budget");
653
+ }
654
+ text += decoder.decode(next.value, { stream: true });
655
+ }
656
+ return {
657
+ text: text + decoder.decode(),
658
+ bytes
659
+ };
660
+ } finally {
661
+ reader.releaseLock();
662
+ }
663
+ }
664
+ function baseUrlOf(probe) {
665
+ const configured = probe.config.baseUrl;
666
+ return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
667
+ }
668
+ async function refuse(response, maxBytes = 8388608) {
669
+ const body = (await readBody(response, maxBytes)).text;
670
+ throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
671
+ }
672
+ function headers(probe) {
673
+ return {
674
+ authorization: `Bearer ${probe.secrets.apiKey ?? ""}`,
675
+ "content-type": "application/json"
676
+ };
677
+ }
678
+ function record(value) {
679
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
680
+ }
681
+ function count(value) {
682
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
683
+ }
684
+ function strings(value, allowEmpty = false) {
685
+ return Array.isArray(value) && value.every((one) => typeof one === "string") && (allowEmpty || value.length > 0) ? value : void 0;
686
+ }
687
+ /**
688
+ * One listed model as an offer. The family agrees on `id` alone, so every
689
+ * other field is read wherever an endpoint puts it: `context_window` or
690
+ * `context_length`, `max_output_tokens` or `max_output_length`,
691
+ * `input_modalities` or the `supports_*_in` flags, `output_modalities`,
692
+ * `supports_reasoning` or `reasoning` in `supported_features` (which also
693
+ * says `tools`), `temperature` in `supported_sampling_parameters`, and an
694
+ * `effort` object with its levels and default. A default the levels do not
695
+ * list is dropped. A valid feature or sampling list, including an empty one,
696
+ * answers for what it leaves out. Missing or malformed lists remain unknown.
697
+ */
698
+ function offerOf(row, id) {
699
+ const contextWindow = count(row.context_window) ?? count(row.context_length);
700
+ const maxOutput = count(row.max_output_tokens) ?? count(row.max_output_length);
701
+ const features = strings(row.supported_features, true);
702
+ const sampling = strings(row.supported_sampling_parameters, true);
703
+ const reasoning = typeof row.supports_reasoning === "boolean" ? row.supports_reasoning : features?.includes("reasoning");
704
+ const effort = record(row.effort);
705
+ const efforts = strings(effort?.supported_levels);
706
+ const defaultEffort = typeof effort?.default_level === "string" && efforts?.includes(effort.default_level) ? effort.default_level : void 0;
707
+ const flagged = typeof row.supports_image_in === "boolean" || typeof row.supports_video_in === "boolean" ? [
708
+ "text",
709
+ ...row.supports_image_in === true ? ["image"] : [],
710
+ ...row.supports_video_in === true ? ["video"] : []
711
+ ] : void 0;
712
+ const input = strings(row.input_modalities) ?? flagged;
713
+ const output = strings(row.output_modalities);
714
+ return {
715
+ model: id,
716
+ ...typeof row.name === "string" && row.name !== "" ? { name: row.name } : {},
717
+ ...contextWindow === void 0 ? {} : { contextWindow },
718
+ ...maxOutput === void 0 ? {} : { maxOutput },
719
+ ...reasoning === void 0 ? {} : { reasoning },
720
+ ...features === void 0 ? {} : { toolCall: features.includes("tools") },
721
+ ...sampling === void 0 ? {} : { temperature: sampling.includes("temperature") },
722
+ ...input === void 0 ? {} : { input },
723
+ ...output === void 0 ? {} : { output },
724
+ ...efforts === void 0 ? {} : { efforts },
725
+ ...defaultEffort === void 0 ? {} : { defaultEffort }
726
+ };
727
+ }
728
+ const probeOpenAI = {
729
+ async listModels(probe, fetcher = globalThis.fetch) {
730
+ const response = await fetcher(`${baseUrlOf(probe)}/models`, {
731
+ method: "GET",
732
+ headers: headers(probe),
733
+ signal: probe.signal
734
+ });
735
+ if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
736
+ return (JSON.parse((await readBody(response, probe.maxResponseBytes ?? 8388608)).text).data ?? []).flatMap((row) => typeof row.id === "string" ? [offerOf(row, row.id)] : []);
737
+ },
738
+ async testConnection(probe, fetcher = globalThis.fetch) {
739
+ if (probe.model !== void 0) {
740
+ const response = await fetcher(`${baseUrlOf(probe)}/chat/completions`, {
741
+ method: "POST",
742
+ headers: headers(probe),
743
+ body: JSON.stringify({
744
+ model: probe.model,
745
+ max_tokens: 1,
746
+ messages: [{
747
+ role: "user",
748
+ content: "ping"
749
+ }]
750
+ }),
751
+ signal: probe.signal
752
+ });
753
+ if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
754
+ return;
755
+ }
756
+ await probeOpenAI.listModels(probe, fetcher);
757
+ }
758
+ };
759
+ //#endregion
760
+ //#region src/protocol.ts
761
+ /** Validated supplier options; no supplier identity is interpreted by this protocol. */
762
+ const OpenAIProtocolOptions = z.strictObject({
763
+ reasoningReplay: z.enum(["omit", "reasoning-content"]).optional(),
764
+ thinkingField: z.boolean().optional(),
765
+ outputLimitField: z.enum(["max_tokens", "max_completion_tokens"]).optional(),
766
+ promptCacheKey: z.boolean().optional()
767
+ });
768
+ /** Registers concrete Chat Completions request mapping, streaming and probes. */
769
+ function openaiProtocolType(support, fetch) {
770
+ return {
771
+ type: "openai",
772
+ label: "OpenAI Chat Completions",
773
+ fields: [{
774
+ key: "baseUrl",
775
+ kind: "url",
776
+ label: "Base URL",
777
+ required: true
778
+ }],
779
+ userConfigurable: true,
780
+ optionsSchema: OpenAIProtocolOptions,
781
+ facts,
782
+ prepareParams: (input) => support.prepareParams(input, facts),
783
+ chat: {
784
+ fileKinds: ["image"],
785
+ supportsModel: () => true,
786
+ createPort(call) {
787
+ const options = OpenAIProtocolOptions.parse(call.options);
788
+ return createOpenAIModelPort({
789
+ support,
790
+ fetch,
791
+ model: call.model,
792
+ endpoint: call.providerId,
793
+ apiKey: call.secrets.apiKey ?? "",
794
+ baseURL: String(call.config.baseUrl ?? ""),
795
+ ...options,
796
+ catalogue: () => support.catalogue(call.providerId, call.model),
797
+ media: (stored) => support.mediaContextOf({
798
+ entry: support.catalogue(call.providerId, call.model),
799
+ stored,
800
+ facts,
801
+ endpoint: support.endpoint(call.providerId),
802
+ fileKinds: ["image"]
803
+ }),
804
+ params: (stored) => support.resolveParams({
805
+ entry: support.catalogue(call.providerId, call.model),
806
+ stored,
807
+ facts,
808
+ model: call.model,
809
+ endpoint: support.endpoint(call.providerId)
810
+ })
811
+ });
812
+ }
813
+ },
814
+ normalizeListing: (input) => support.normalizeListing(input),
815
+ listModels: (probe) => probeOpenAI.listModels(probe, fetch),
816
+ testConnection: (probe) => probeOpenAI.testConnection(probe, fetch)
817
+ };
818
+ }
819
+ //#endregion
820
+ //#region src/index.ts
821
+ /** Protocol extensions contribute no tools. */
822
+ const TOOL_NAMES = [];
823
+ const plugin = {
824
+ name: "@eum-agent/llm-protocol-openai",
825
+ requires: ["model-support", "network"],
826
+ apply(ctx) {
827
+ const support = ctx.services.get("model-support");
828
+ const network = ctx.services.get("network");
829
+ ctx.models.registerProtocol(openaiProtocolType(support, network.fetch));
830
+ }
831
+ };
832
+ //#endregion
833
+ export { TOOL_NAMES, plugin as default };
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@eum-agent/llm-protocol-openai",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "displayName": {
4
+ "en-US": "OpenAI Model Protocol",
5
+ "zh-CN": "模型协议 · OpenAI"
6
+ },
7
+ "version": "1.0.1",
8
+ "type": "module",
9
+ "description": "Public OpenAI model communication protocol",
10
+ "license": "MIT",
11
+ "exports": {
12
+ ".": {
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "devDependencies": {
20
+ "@eum-agent/plugin": "1.0.1"
21
+ },
22
+ "dependencies": {
23
+ "zod": "^4.4.3",
24
+ "openai": "^7.8.0",
25
+ "gpt-tokenizer": "4.0.0"
26
+ },
27
+ "yaoguang": {
28
+ "kind": "extension",
29
+ "dependencies": {
30
+ "@eum-agent/llm-management": "1.0.1"
31
+ },
32
+ "foundationDependencies": {
33
+ "@eum-agent/infra-local": "1.0.1"
34
+ },
35
+ "description": {
36
+ "en-US": "Public OpenAI model communication protocol",
37
+ "zh-CN": "OpenAI 公共模型协议"
38
+ }
39
+ },
40
+ "scripts": {
41
+ "build": "tsdown",
42
+ "test": "vitest run",
43
+ "typecheck": "tsc --noEmit"
44
+ }
6
45
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.