@agentic-kit/openai 1.2.0 → 1.2.2

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 (4) hide show
  1. package/esm/index.js +6 -176
  2. package/index.d.ts +1 -180
  3. package/index.js +29 -199
  4. package/package.json +9 -3
package/esm/index.js CHANGED
@@ -1,81 +1,8 @@
1
+ import { calculateUsageCost, clone, createAssistantMessage, DefaultAssistantMessageEventStream, normalizeBaseUrl, parsePartialJson, } from '@agentic-kit/protocol';
1
2
  // Use the runtime's native fetch. Node 18.17+ (engine requirement),
2
3
  // browsers, Bun, and Deno all provide it with a Web ReadableStream body —
3
4
  // which is what SSE parsing here requires.
4
5
  const fetch = globalThis.fetch.bind(globalThis);
5
- class EventStream {
6
- isTerminal;
7
- extractResult;
8
- queue = [];
9
- waiting = [];
10
- done = false;
11
- finalResultPromise;
12
- resolveFinalResult;
13
- constructor(isTerminal, extractResult) {
14
- this.isTerminal = isTerminal;
15
- this.extractResult = extractResult;
16
- this.finalResultPromise = new Promise((resolve) => {
17
- this.resolveFinalResult = resolve;
18
- });
19
- }
20
- push(event) {
21
- if (this.done) {
22
- return;
23
- }
24
- if (this.isTerminal(event)) {
25
- this.done = true;
26
- this.resolveFinalResult(this.extractResult(event));
27
- }
28
- const waiter = this.waiting.shift();
29
- if (waiter) {
30
- waiter({ value: event, done: false });
31
- return;
32
- }
33
- this.queue.push(event);
34
- }
35
- end(result) {
36
- this.done = true;
37
- if (result !== undefined) {
38
- this.resolveFinalResult(result);
39
- }
40
- while (this.waiting.length > 0) {
41
- this.waiting.shift()({ value: undefined, done: true });
42
- }
43
- }
44
- async *[Symbol.asyncIterator]() {
45
- while (true) {
46
- if (this.queue.length > 0) {
47
- yield this.queue.shift();
48
- continue;
49
- }
50
- if (this.done) {
51
- return;
52
- }
53
- const next = await new Promise((resolve) => {
54
- this.waiting.push(resolve);
55
- });
56
- if (next.done) {
57
- return;
58
- }
59
- yield next.value;
60
- }
61
- }
62
- result() {
63
- return this.finalResultPromise;
64
- }
65
- }
66
- class DefaultAssistantMessageEventStream extends EventStream {
67
- constructor() {
68
- super((event) => event.type === 'done' || event.type === 'error', (event) => {
69
- if (event.type === 'done') {
70
- return event.message;
71
- }
72
- if (event.type === 'error') {
73
- return event.error;
74
- }
75
- throw new Error('Unexpected terminal event');
76
- });
77
- }
78
- }
79
6
  export const OPENAI_COMPATIBLE_MODELS = [
80
7
  {
81
8
  id: 'gpt-5.4',
@@ -184,8 +111,8 @@ export class OpenAIAdapter {
184
111
  return {
185
112
  ...builtIn,
186
113
  baseUrl: this.baseUrl,
187
- headers: { ...(builtIn.headers ?? {}), ...(this.defaultHeaders ?? {}), ...(overrides?.headers ?? {}) },
188
- compat: { ...(builtIn.compat ?? {}), ...(this.compat ?? {}), ...(overrides?.compat ?? {}) },
114
+ headers: { ...(this.defaultHeaders ?? {}), ...(builtIn.headers ?? {}), ...(overrides?.headers ?? {}) },
115
+ compat: { ...(this.compat ?? {}), ...(builtIn.compat ?? {}), ...(overrides?.compat ?? {}) },
189
116
  ...overrides,
190
117
  };
191
118
  }
@@ -493,41 +420,15 @@ function toOpenAIMessage(message, compat) {
493
420
  ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
494
421
  };
495
422
  }
496
- function createAssistantMessage(model) {
497
- return {
498
- role: 'assistant',
499
- api: model.api,
500
- provider: model.provider,
501
- model: model.id,
502
- content: [],
503
- usage: {
504
- input: 0,
505
- output: 0,
506
- cacheRead: 0,
507
- cacheWrite: 0,
508
- totalTokens: 0,
509
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
510
- },
511
- stopReason: 'stop',
512
- timestamp: Date.now(),
513
- };
514
- }
515
- function calculateUsageCost(model, usage) {
516
- usage.cost.input = ((model.cost?.input ?? 0) / 1_000_000) * usage.input;
517
- usage.cost.output = ((model.cost?.output ?? 0) / 1_000_000) * usage.output;
518
- usage.cost.cacheRead = ((model.cost?.cacheRead ?? 0) / 1_000_000) * usage.cacheRead;
519
- usage.cost.cacheWrite = ((model.cost?.cacheWrite ?? 0) / 1_000_000) * usage.cacheWrite;
520
- usage.cost.total =
521
- usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
522
- }
523
423
  function applyUsage(usage, model, payload) {
524
424
  const cachedTokens = payload.prompt_tokens_details?.cached_tokens ?? 0;
525
425
  const reasoningTokens = payload.completion_tokens_details?.reasoning_tokens ?? 0;
526
426
  usage.input = (payload.prompt_tokens ?? 0) - cachedTokens;
527
- usage.output = (payload.completion_tokens ?? 0) + reasoningTokens;
427
+ usage.output = payload.completion_tokens ?? 0;
428
+ usage.reasoning = reasoningTokens;
528
429
  usage.cacheRead = cachedTokens;
529
430
  usage.cacheWrite = 0;
530
- usage.totalTokens = payload.total_tokens ?? usage.input + usage.output + usage.cacheRead;
431
+ usage.totalTokens = payload.total_tokens ?? usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
531
432
  calculateUsageCost(model, usage);
532
433
  }
533
434
  function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinkingIndex) {
@@ -563,77 +464,6 @@ function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinking
563
464
  });
564
465
  }
565
466
  }
566
- function normalizeBaseUrl(baseUrl) {
567
- const trimmed = baseUrl.replace(/\/+$/, '');
568
- if (/\/v\d+$/.test(trimmed)) {
569
- return trimmed;
570
- }
571
- return `${trimmed}/v1`;
572
- }
573
- function parsePartialJson(raw) {
574
- const trimmed = raw.trim();
575
- if (!trimmed) {
576
- return {};
577
- }
578
- try {
579
- return JSON.parse(trimmed);
580
- }
581
- catch {
582
- // continue
583
- }
584
- const completed = completePartialJson(trimmed);
585
- if (!completed) {
586
- return {};
587
- }
588
- try {
589
- return JSON.parse(completed);
590
- }
591
- catch {
592
- return {};
593
- }
594
- }
595
- function completePartialJson(input) {
596
- let output = input;
597
- let inString = false;
598
- let escaping = false;
599
- const stack = [];
600
- for (const char of input) {
601
- if (escaping) {
602
- escaping = false;
603
- continue;
604
- }
605
- if (char === '\\') {
606
- escaping = true;
607
- continue;
608
- }
609
- if (char === '"') {
610
- inString = !inString;
611
- continue;
612
- }
613
- if (inString) {
614
- continue;
615
- }
616
- if (char === '{') {
617
- stack.push('}');
618
- }
619
- else if (char === '[') {
620
- stack.push(']');
621
- }
622
- else if (char === '}' || char === ']') {
623
- stack.pop();
624
- }
625
- }
626
- if (inString) {
627
- output += '"';
628
- }
629
- while (stack.length > 0) {
630
- output += stack.pop();
631
- }
632
- return output;
633
- }
634
- function clone(value) {
635
- return JSON.parse(JSON.stringify(value));
636
- }
637
467
  function firstNonEmpty(...values) {
638
468
  return values.find((value) => typeof value === 'string' && value.length > 0);
639
469
  }
package/index.d.ts CHANGED
@@ -1,183 +1,4 @@
1
- type JsonPrimitive = string | number | boolean | null;
2
- type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
3
- interface JsonObject {
4
- [key: string]: JsonValue | undefined;
5
- }
6
- interface JsonSchema {
7
- additionalProperties?: boolean | JsonSchema;
8
- description?: string;
9
- enum?: JsonValue[];
10
- items?: JsonSchema | JsonSchema[];
11
- properties?: Record<string, JsonSchema>;
12
- required?: string[];
13
- type?: string | string[];
14
- }
15
- interface OpenAICompatibleCompat {
16
- maxTokensField?: 'max_completion_tokens' | 'max_tokens';
17
- reasoningFormat?: 'none' | 'openai';
18
- supportsReasoningEffort?: boolean;
19
- supportsStrictToolSchema?: boolean;
20
- supportsUsageInStreaming?: boolean;
21
- toolCallIdFormat?: 'passthrough' | 'safe64' | 'mistral9';
22
- requiresToolResultName?: boolean;
23
- }
24
- interface ModelDescriptor {
25
- id: string;
26
- name: string;
27
- api: string;
28
- provider: string;
29
- baseUrl: string;
30
- input: Array<'text' | 'image'>;
31
- reasoning: boolean;
32
- tools?: boolean;
33
- contextWindow?: number;
34
- maxOutputTokens?: number;
35
- cost?: {
36
- input?: number;
37
- output?: number;
38
- cacheRead?: number;
39
- cacheWrite?: number;
40
- };
41
- headers?: Record<string, string>;
42
- compat?: OpenAICompatibleCompat;
43
- }
44
- interface TextContent {
45
- type: 'text';
46
- text: string;
47
- }
48
- interface ImageContent {
49
- type: 'image';
50
- data: string;
51
- mimeType: string;
52
- }
53
- interface ThinkingContent {
54
- type: 'thinking';
55
- thinking: string;
56
- signature?: string;
57
- }
58
- interface ToolCallContent {
59
- type: 'toolCall';
60
- id: string;
61
- name: string;
62
- arguments: Record<string, JsonValue | undefined>;
63
- rawArguments?: string;
64
- }
65
- type Message = {
66
- role: 'user';
67
- content: string | Array<TextContent | ImageContent>;
68
- timestamp: number;
69
- } | {
70
- role: 'assistant';
71
- content: Array<TextContent | ThinkingContent | ToolCallContent>;
72
- api: string;
73
- provider: string;
74
- model: string;
75
- usage: Usage;
76
- stopReason: 'stop' | 'length' | 'toolUse' | 'error' | 'aborted';
77
- errorMessage?: string;
78
- timestamp: number;
79
- } | {
80
- role: 'toolResult';
81
- toolCallId: string;
82
- toolName: string;
83
- content: Array<TextContent | ImageContent>;
84
- isError: boolean;
85
- details?: unknown;
86
- timestamp: number;
87
- };
88
- interface ToolDefinition {
89
- name: string;
90
- description: string;
91
- parameters: JsonSchema;
92
- }
93
- interface Context {
94
- systemPrompt?: string;
95
- messages: Message[];
96
- tools?: ToolDefinition[];
97
- }
98
- interface StreamOptions {
99
- apiKey?: string;
100
- headers?: Record<string, string>;
101
- maxTokens?: number;
102
- onPayload?: (payload: unknown) => void;
103
- reasoning?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
104
- signal?: AbortSignal;
105
- temperature?: number;
106
- }
107
- interface Usage {
108
- input: number;
109
- output: number;
110
- cacheRead: number;
111
- cacheWrite: number;
112
- totalTokens: number;
113
- cost: {
114
- input: number;
115
- output: number;
116
- cacheRead: number;
117
- cacheWrite: number;
118
- total: number;
119
- };
120
- }
121
- type AssistantMessage = Extract<Message, {
122
- role: 'assistant';
123
- }>;
124
- type AssistantMessageEvent = {
125
- type: 'start';
126
- partial: AssistantMessage;
127
- } | {
128
- type: 'text_start';
129
- contentIndex: number;
130
- partial: AssistantMessage;
131
- } | {
132
- type: 'text_delta';
133
- contentIndex: number;
134
- delta: string;
135
- partial: AssistantMessage;
136
- } | {
137
- type: 'text_end';
138
- contentIndex: number;
139
- content: string;
140
- partial: AssistantMessage;
141
- } | {
142
- type: 'thinking_start';
143
- contentIndex: number;
144
- partial: AssistantMessage;
145
- } | {
146
- type: 'thinking_delta';
147
- contentIndex: number;
148
- delta: string;
149
- partial: AssistantMessage;
150
- } | {
151
- type: 'thinking_end';
152
- contentIndex: number;
153
- content: string;
154
- partial: AssistantMessage;
155
- } | {
156
- type: 'toolcall_start';
157
- contentIndex: number;
158
- partial: AssistantMessage;
159
- } | {
160
- type: 'toolcall_delta';
161
- contentIndex: number;
162
- delta: string;
163
- partial: AssistantMessage;
164
- } | {
165
- type: 'toolcall_end';
166
- contentIndex: number;
167
- toolCall: ToolCallContent;
168
- partial: AssistantMessage;
169
- } | {
170
- type: 'done';
171
- reason: 'stop' | 'length' | 'toolUse';
172
- message: AssistantMessage;
173
- } | {
174
- type: 'error';
175
- reason: 'error' | 'aborted';
176
- error: AssistantMessage;
177
- };
178
- interface AssistantMessageEventStream extends AsyncIterable<AssistantMessageEvent> {
179
- result(): Promise<AssistantMessage>;
180
- }
1
+ import { type AssistantMessageEventStream, type Context, type ModelDescriptor, type OpenAICompatibleCompat, type StreamOptions } from '@agentic-kit/protocol';
181
2
  interface OpenAIModelDefinition extends ModelDescriptor {
182
3
  }
183
4
  export interface OpenAIOptions {
package/index.js CHANGED
@@ -1,84 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OpenAIAdapter = exports.OPENAI_COMPATIBLE_MODELS = void 0;
4
+ const protocol_1 = require("@agentic-kit/protocol");
4
5
  // Use the runtime's native fetch. Node 18.17+ (engine requirement),
5
6
  // browsers, Bun, and Deno all provide it with a Web ReadableStream body —
6
7
  // which is what SSE parsing here requires.
7
8
  const fetch = globalThis.fetch.bind(globalThis);
8
- class EventStream {
9
- isTerminal;
10
- extractResult;
11
- queue = [];
12
- waiting = [];
13
- done = false;
14
- finalResultPromise;
15
- resolveFinalResult;
16
- constructor(isTerminal, extractResult) {
17
- this.isTerminal = isTerminal;
18
- this.extractResult = extractResult;
19
- this.finalResultPromise = new Promise((resolve) => {
20
- this.resolveFinalResult = resolve;
21
- });
22
- }
23
- push(event) {
24
- if (this.done) {
25
- return;
26
- }
27
- if (this.isTerminal(event)) {
28
- this.done = true;
29
- this.resolveFinalResult(this.extractResult(event));
30
- }
31
- const waiter = this.waiting.shift();
32
- if (waiter) {
33
- waiter({ value: event, done: false });
34
- return;
35
- }
36
- this.queue.push(event);
37
- }
38
- end(result) {
39
- this.done = true;
40
- if (result !== undefined) {
41
- this.resolveFinalResult(result);
42
- }
43
- while (this.waiting.length > 0) {
44
- this.waiting.shift()({ value: undefined, done: true });
45
- }
46
- }
47
- async *[Symbol.asyncIterator]() {
48
- while (true) {
49
- if (this.queue.length > 0) {
50
- yield this.queue.shift();
51
- continue;
52
- }
53
- if (this.done) {
54
- return;
55
- }
56
- const next = await new Promise((resolve) => {
57
- this.waiting.push(resolve);
58
- });
59
- if (next.done) {
60
- return;
61
- }
62
- yield next.value;
63
- }
64
- }
65
- result() {
66
- return this.finalResultPromise;
67
- }
68
- }
69
- class DefaultAssistantMessageEventStream extends EventStream {
70
- constructor() {
71
- super((event) => event.type === 'done' || event.type === 'error', (event) => {
72
- if (event.type === 'done') {
73
- return event.message;
74
- }
75
- if (event.type === 'error') {
76
- return event.error;
77
- }
78
- throw new Error('Unexpected terminal event');
79
- });
80
- }
81
- }
82
9
  exports.OPENAI_COMPATIBLE_MODELS = [
83
10
  {
84
11
  id: 'gpt-5.4',
@@ -161,7 +88,7 @@ class OpenAIAdapter {
161
88
  constructor(options) {
162
89
  const normalized = typeof options === 'string' ? { apiKey: options } : options ?? {};
163
90
  this.apiKey = normalized.apiKey;
164
- this.baseUrl = normalizeBaseUrl(normalized.baseUrl ?? 'https://api.openai.com/v1');
91
+ this.baseUrl = (0, protocol_1.normalizeBaseUrl)(normalized.baseUrl ?? 'https://api.openai.com/v1');
165
92
  this.provider = normalized.provider ?? 'openai';
166
93
  this.name = this.provider;
167
94
  this.defaultHeaders = normalized.headers;
@@ -187,8 +114,8 @@ class OpenAIAdapter {
187
114
  return {
188
115
  ...builtIn,
189
116
  baseUrl: this.baseUrl,
190
- headers: { ...(builtIn.headers ?? {}), ...(this.defaultHeaders ?? {}), ...(overrides?.headers ?? {}) },
191
- compat: { ...(builtIn.compat ?? {}), ...(this.compat ?? {}), ...(overrides?.compat ?? {}) },
117
+ headers: { ...(this.defaultHeaders ?? {}), ...(builtIn.headers ?? {}), ...(overrides?.headers ?? {}) },
118
+ compat: { ...(this.compat ?? {}), ...(builtIn.compat ?? {}), ...(overrides?.compat ?? {}) },
192
119
  ...overrides,
193
120
  };
194
121
  }
@@ -227,8 +154,8 @@ class OpenAIAdapter {
227
154
  }
228
155
  }
229
156
  stream(model, context, options) {
230
- const stream = new DefaultAssistantMessageEventStream();
231
- const output = createAssistantMessage(model);
157
+ const stream = new protocol_1.DefaultAssistantMessageEventStream();
158
+ const output = (0, protocol_1.createAssistantMessage)(model);
232
159
  void (async () => {
233
160
  let textIndex;
234
161
  let thinkingIndex;
@@ -250,7 +177,7 @@ class OpenAIAdapter {
250
177
  const text = await response.text().catch(() => '');
251
178
  throw new Error(`OpenAI error ${response.status}: ${text}`);
252
179
  }
253
- stream.push({ type: 'start', partial: clone(output) });
180
+ stream.push({ type: 'start', partial: (0, protocol_1.clone)(output) });
254
181
  const reader = response.body?.getReader();
255
182
  if (!reader) {
256
183
  throw new Error('No response body');
@@ -276,8 +203,8 @@ class OpenAIAdapter {
276
203
  }
277
204
  if (payload === '[DONE]') {
278
205
  emitFinalBlockEvents(stream, output, toolIndexMap, textIndex, thinkingIndex);
279
- calculateUsageCost(model, output.usage);
280
- stream.push({ type: 'done', reason: doneReason, message: clone(output) });
206
+ (0, protocol_1.calculateUsageCost)(model, output.usage);
207
+ stream.push({ type: 'done', reason: doneReason, message: (0, protocol_1.clone)(output) });
281
208
  stream.end(output);
282
209
  return;
283
210
  }
@@ -305,7 +232,7 @@ class OpenAIAdapter {
305
232
  stream.push({
306
233
  type: 'thinking_start',
307
234
  contentIndex: thinkingIndex,
308
- partial: clone(output),
235
+ partial: (0, protocol_1.clone)(output),
309
236
  });
310
237
  }
311
238
  const block = output.content[thinkingIndex];
@@ -314,7 +241,7 @@ class OpenAIAdapter {
314
241
  type: 'thinking_delta',
315
242
  contentIndex: thinkingIndex,
316
243
  delta: reasoningDelta,
317
- partial: clone(output),
244
+ partial: (0, protocol_1.clone)(output),
318
245
  });
319
246
  }
320
247
  if (typeof delta.content === 'string' && delta.content.length > 0) {
@@ -323,7 +250,7 @@ class OpenAIAdapter {
323
250
  stream.push({
324
251
  type: 'text_start',
325
252
  contentIndex: textIndex,
326
- partial: clone(output),
253
+ partial: (0, protocol_1.clone)(output),
327
254
  });
328
255
  }
329
256
  const block = output.content[textIndex];
@@ -332,7 +259,7 @@ class OpenAIAdapter {
332
259
  type: 'text_delta',
333
260
  contentIndex: textIndex,
334
261
  delta: delta.content,
335
- partial: clone(output),
262
+ partial: (0, protocol_1.clone)(output),
336
263
  });
337
264
  }
338
265
  for (const toolDelta of delta.tool_calls ?? []) {
@@ -351,7 +278,7 @@ class OpenAIAdapter {
351
278
  stream.push({
352
279
  type: 'toolcall_start',
353
280
  contentIndex,
354
- partial: clone(output),
281
+ partial: (0, protocol_1.clone)(output),
355
282
  });
356
283
  }
357
284
  const block = output.content[contentIndex];
@@ -363,31 +290,31 @@ class OpenAIAdapter {
363
290
  }
364
291
  if (toolDelta.function?.arguments) {
365
292
  block.rawArguments = `${block.rawArguments ?? ''}${toolDelta.function.arguments}`;
366
- block.arguments = parsePartialJson(block.rawArguments);
293
+ block.arguments = (0, protocol_1.parsePartialJson)(block.rawArguments);
367
294
  stream.push({
368
295
  type: 'toolcall_delta',
369
296
  contentIndex,
370
297
  delta: toolDelta.function.arguments,
371
- partial: clone(output),
298
+ partial: (0, protocol_1.clone)(output),
372
299
  });
373
300
  }
374
301
  }
375
302
  }
376
303
  }
377
304
  emitFinalBlockEvents(stream, output, toolIndexMap, textIndex, thinkingIndex);
378
- calculateUsageCost(model, output.usage);
379
- stream.push({ type: 'done', reason: doneReason, message: clone(output) });
305
+ (0, protocol_1.calculateUsageCost)(model, output.usage);
306
+ stream.push({ type: 'done', reason: doneReason, message: (0, protocol_1.clone)(output) });
380
307
  stream.end(output);
381
308
  }
382
309
  catch (error) {
383
310
  emitFinalBlockEvents(stream, output, toolIndexMap, textIndex, thinkingIndex);
384
311
  output.stopReason = options?.signal?.aborted ? 'aborted' : 'error';
385
312
  output.errorMessage = error instanceof Error ? error.message : String(error);
386
- calculateUsageCost(model, output.usage);
313
+ (0, protocol_1.calculateUsageCost)(model, output.usage);
387
314
  stream.push({
388
315
  type: 'error',
389
316
  reason: output.stopReason === 'aborted' ? 'aborted' : 'error',
390
- error: clone(output),
317
+ error: (0, protocol_1.clone)(output),
391
318
  });
392
319
  stream.end(output);
393
320
  }
@@ -497,42 +424,16 @@ function toOpenAIMessage(message, compat) {
497
424
  ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
498
425
  };
499
426
  }
500
- function createAssistantMessage(model) {
501
- return {
502
- role: 'assistant',
503
- api: model.api,
504
- provider: model.provider,
505
- model: model.id,
506
- content: [],
507
- usage: {
508
- input: 0,
509
- output: 0,
510
- cacheRead: 0,
511
- cacheWrite: 0,
512
- totalTokens: 0,
513
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
514
- },
515
- stopReason: 'stop',
516
- timestamp: Date.now(),
517
- };
518
- }
519
- function calculateUsageCost(model, usage) {
520
- usage.cost.input = ((model.cost?.input ?? 0) / 1_000_000) * usage.input;
521
- usage.cost.output = ((model.cost?.output ?? 0) / 1_000_000) * usage.output;
522
- usage.cost.cacheRead = ((model.cost?.cacheRead ?? 0) / 1_000_000) * usage.cacheRead;
523
- usage.cost.cacheWrite = ((model.cost?.cacheWrite ?? 0) / 1_000_000) * usage.cacheWrite;
524
- usage.cost.total =
525
- usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
526
- }
527
427
  function applyUsage(usage, model, payload) {
528
428
  const cachedTokens = payload.prompt_tokens_details?.cached_tokens ?? 0;
529
429
  const reasoningTokens = payload.completion_tokens_details?.reasoning_tokens ?? 0;
530
430
  usage.input = (payload.prompt_tokens ?? 0) - cachedTokens;
531
- usage.output = (payload.completion_tokens ?? 0) + reasoningTokens;
431
+ usage.output = payload.completion_tokens ?? 0;
432
+ usage.reasoning = reasoningTokens;
532
433
  usage.cacheRead = cachedTokens;
533
434
  usage.cacheWrite = 0;
534
- usage.totalTokens = payload.total_tokens ?? usage.input + usage.output + usage.cacheRead;
535
- calculateUsageCost(model, usage);
435
+ usage.totalTokens = payload.total_tokens ?? usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
436
+ (0, protocol_1.calculateUsageCost)(model, usage);
536
437
  }
537
438
  function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinkingIndex) {
538
439
  const textBlock = textIndex !== undefined ? message.content[textIndex] : undefined;
@@ -541,7 +442,7 @@ function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinking
541
442
  type: 'text_end',
542
443
  contentIndex: textIndex,
543
444
  content: textBlock.text,
544
- partial: clone(message),
445
+ partial: (0, protocol_1.clone)(message),
545
446
  });
546
447
  }
547
448
  const thinkingBlock = thinkingIndex !== undefined ? message.content[thinkingIndex] : undefined;
@@ -550,7 +451,7 @@ function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinking
550
451
  type: 'thinking_end',
551
452
  contentIndex: thinkingIndex,
552
453
  content: thinkingBlock.thinking,
553
- partial: clone(message),
454
+ partial: (0, protocol_1.clone)(message),
554
455
  });
555
456
  }
556
457
  for (const contentIndex of toolIndexMap.values()) {
@@ -558,86 +459,15 @@ function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinking
558
459
  if (!toolCall) {
559
460
  continue;
560
461
  }
561
- toolCall.arguments = parsePartialJson(toolCall.rawArguments ?? '');
462
+ toolCall.arguments = (0, protocol_1.parsePartialJson)(toolCall.rawArguments ?? '');
562
463
  stream.push({
563
464
  type: 'toolcall_end',
564
465
  contentIndex,
565
- toolCall: clone(toolCall),
566
- partial: clone(message),
466
+ toolCall: (0, protocol_1.clone)(toolCall),
467
+ partial: (0, protocol_1.clone)(message),
567
468
  });
568
469
  }
569
470
  }
570
- function normalizeBaseUrl(baseUrl) {
571
- const trimmed = baseUrl.replace(/\/+$/, '');
572
- if (/\/v\d+$/.test(trimmed)) {
573
- return trimmed;
574
- }
575
- return `${trimmed}/v1`;
576
- }
577
- function parsePartialJson(raw) {
578
- const trimmed = raw.trim();
579
- if (!trimmed) {
580
- return {};
581
- }
582
- try {
583
- return JSON.parse(trimmed);
584
- }
585
- catch {
586
- // continue
587
- }
588
- const completed = completePartialJson(trimmed);
589
- if (!completed) {
590
- return {};
591
- }
592
- try {
593
- return JSON.parse(completed);
594
- }
595
- catch {
596
- return {};
597
- }
598
- }
599
- function completePartialJson(input) {
600
- let output = input;
601
- let inString = false;
602
- let escaping = false;
603
- const stack = [];
604
- for (const char of input) {
605
- if (escaping) {
606
- escaping = false;
607
- continue;
608
- }
609
- if (char === '\\') {
610
- escaping = true;
611
- continue;
612
- }
613
- if (char === '"') {
614
- inString = !inString;
615
- continue;
616
- }
617
- if (inString) {
618
- continue;
619
- }
620
- if (char === '{') {
621
- stack.push('}');
622
- }
623
- else if (char === '[') {
624
- stack.push(']');
625
- }
626
- else if (char === '}' || char === ']') {
627
- stack.pop();
628
- }
629
- }
630
- if (inString) {
631
- output += '"';
632
- }
633
- while (stack.length > 0) {
634
- output += stack.pop();
635
- }
636
- return output;
637
- }
638
- function clone(value) {
639
- return JSON.parse(JSON.stringify(value));
640
- }
641
471
  function firstNonEmpty(...values) {
642
472
  return values.find((value) => typeof value === 'string' && value.length > 0);
643
473
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentic-kit/openai",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "author": "Dan Lynch <pyramation@gmail.com>",
5
5
  "description": "OpenAI (and OpenAI-compatible) adapter for agentic-kit",
6
6
  "main": "index.js",
@@ -34,8 +34,14 @@
34
34
  "build:dev": "makage build --dev",
35
35
  "lint": "eslint . --fix",
36
36
  "test": "jest",
37
- "test:watch": "jest --watch"
37
+ "test:watch": "jest --watch",
38
+ "test:live": "node ./scripts/run-live-tests.js smoke",
39
+ "test:live:smoke": "node ./scripts/run-live-tests.js smoke",
40
+ "test:live:extended": "node ./scripts/run-live-tests.js extended"
41
+ },
42
+ "dependencies": {
43
+ "@agentic-kit/protocol": "1.1.0"
38
44
  },
39
45
  "keywords": [],
40
- "gitHead": "d4f3f660be621267efe12671c22db202ccdb3f0b"
46
+ "gitHead": "fbf34d1146e8543664d904f75e5b3440f2b1d2a4"
41
47
  }