@yaks/openai 0.0.0-stage → 0.2.36

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 (78) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +389 -2
  3. package/_dist/batches.d.ts +77 -0
  4. package/_dist/batches.d.ts.map +1 -0
  5. package/_dist/credential.d.ts +13 -0
  6. package/_dist/credential.d.ts.map +1 -0
  7. package/_dist/images.d.ts +15 -0
  8. package/_dist/images.d.ts.map +1 -0
  9. package/_dist/list.d.ts +8 -0
  10. package/_dist/list.d.ts.map +1 -0
  11. package/_dist/media.d.ts +11 -0
  12. package/_dist/media.d.ts.map +1 -0
  13. package/_dist/mod.d.ts +30 -0
  14. package/_dist/mod.d.ts.map +1 -0
  15. package/_dist/project-keys.d.ts +4 -0
  16. package/_dist/project-keys.d.ts.map +1 -0
  17. package/_dist/provider.d.ts +48 -0
  18. package/_dist/provider.d.ts.map +1 -0
  19. package/_dist/responses.d.ts +51 -0
  20. package/_dist/responses.d.ts.map +1 -0
  21. package/_dist/transport.d.ts +121 -0
  22. package/_dist/transport.d.ts.map +1 -0
  23. package/_dist/vocab.d.ts +10 -0
  24. package/_dist/vocab.d.ts.map +1 -0
  25. package/batches.js +145 -0
  26. package/batches.js.map +1 -0
  27. package/batches.ts +194 -0
  28. package/credential.js +30 -0
  29. package/credential.js.map +1 -0
  30. package/credential.ts +40 -0
  31. package/deno.json +1 -0
  32. package/generations.js +288 -0
  33. package/generations.js.map +1 -0
  34. package/generations.ts +365 -0
  35. package/images.js +37 -0
  36. package/images.js.map +1 -0
  37. package/images.ts +63 -0
  38. package/info.js +55 -0
  39. package/info.js.map +1 -0
  40. package/info.ts +59 -0
  41. package/limits.js +50 -0
  42. package/limits.js.map +1 -0
  43. package/limits.ts +48 -0
  44. package/list.js +88 -0
  45. package/list.js.map +1 -0
  46. package/list.ts +127 -0
  47. package/mark.js +29 -0
  48. package/mark.js.map +1 -0
  49. package/mark.ts +50 -0
  50. package/media.js +60 -0
  51. package/media.js.map +1 -0
  52. package/media.ts +94 -0
  53. package/mod.js +28 -0
  54. package/mod.js.map +1 -0
  55. package/mod.ts +64 -0
  56. package/native.js +176 -0
  57. package/native.js.map +1 -0
  58. package/native.ts +221 -0
  59. package/package.json +36 -4
  60. package/project-keys.js +32 -0
  61. package/project-keys.js.map +1 -0
  62. package/project-keys.ts +43 -0
  63. package/provider.js +190 -0
  64. package/provider.js.map +1 -0
  65. package/provider.ts +292 -0
  66. package/reads.js +167 -0
  67. package/reads.js.map +1 -0
  68. package/reads.ts +169 -0
  69. package/responses.js +612 -0
  70. package/responses.js.map +1 -0
  71. package/responses.ts +706 -0
  72. package/transport.js +646 -0
  73. package/transport.js.map +1 -0
  74. package/transport.ts +972 -0
  75. package/vocab.js +23 -0
  76. package/vocab.js.map +1 -0
  77. package/vocab.json +25 -0
  78. package/vocab.ts +29 -0
package/responses.ts ADDED
@@ -0,0 +1,706 @@
1
+ import { type Hold, type Scope, sharing, sleep } from '@yaks/fp'
2
+ import { listing } from './list.js'
3
+ import { described } from './info.js'
4
+ import { reads } from './reads.js'
5
+ import { generatedImages, type Images } from './images.js'
6
+ import { dataUrl } from './media.js'
7
+ // Provider-neutral model items in and out; transport.ts alone owns the HTTP
8
+ // calls to the Responses API.
9
+ import {
10
+ acknowledged,
11
+ began,
12
+ cacheExpiry,
13
+ type Item,
14
+ type Listed,
15
+ type Mark,
16
+ type MediaReceipt,
17
+ type MediaReceipts,
18
+ type Model,
19
+ ModelError,
20
+ receivedMedia,
21
+ recoveredMedia,
22
+ type Reply,
23
+ type Request,
24
+ submitted,
25
+ UNANCHORED,
26
+ type Usage,
27
+ } from '@yaks/model'
28
+ import type { Credential } from './credential.ts'
29
+ import { openaiDoc, responseAnchor } from './vocab.js'
30
+ import { marking } from './mark.js'
31
+ import { planLimits } from './limits.js'
32
+ import {
33
+ request,
34
+ ResponseError,
35
+ type ResponseOptions,
36
+ type ResponseRequest,
37
+ type RunOptions,
38
+ transport,
39
+ type TransportCredential,
40
+ } from './transport.js'
41
+
42
+ export { openaiDoc }
43
+
44
+ export let OPENAI_COMP = 'openai'
45
+
46
+ /** How the model is reached. */
47
+ export type Options = Omit<ResponseOptions, 'credentials'> & RunOptions & {
48
+ credential: () => Credential | Promise<Credential>
49
+ /** Provider component used for acknowledgements, marks and private receipts. */
50
+ provider?: string
51
+ /** Retry a rejected credential once with a fresh bearer. */
52
+ refresh?: (stale: TransportCredential) => Credential | Promise<Credential>
53
+ /** Configure native image storage and offer the tool on every ask. */
54
+ images?: Images
55
+ /** Private provider results retained before artifact conversion or delivery. */
56
+ receipts?: MediaReceipts
57
+ /** Offer provider-hosted web search, page opening, and find-in-page. */
58
+ web?: boolean
59
+ /** Let an acknowledged generation finish after its stream disconnects. */
60
+ background?: boolean
61
+ /** The account whose ChatGPT plan the Codex backend's limit readings are
62
+ * of (@yaks/model `accountEid`). */
63
+ account?: string
64
+ /** who may share a read under way (@yaks/model `Lent.scope`) */
65
+ scope?: Scope
66
+ /** keeps a cancel sent after its request alive (@yaks/model `Lent.hold`) */
67
+ hold?: Hold
68
+ /** How long the endpoint keeps a cached prefix, in seconds: each reply's
69
+ * mark records the request's start plus this as its `cache_expires_at`.
70
+ * Unknown where absent. */
71
+ retention?: number | 'openai-default'
72
+ }
73
+
74
+ type Frame = Record<string, unknown>
75
+
76
+ let record = (value: unknown): value is Frame =>
77
+ value != null && typeof value == 'object' && !Array.isArray(value)
78
+
79
+ let str = (value: unknown, fallback = '') =>
80
+ typeof value == 'string' ? value : fallback
81
+
82
+ // The neutral items in the API's four shapes.
83
+ let shape: Record<Item['kind'], (item: Item) => unknown> = {
84
+ image: (i) => {
85
+ let image = i as Extract<Item, { kind: 'image' }>
86
+ return {
87
+ role: 'user',
88
+ content: [
89
+ { type: 'input_text', text: image.label },
90
+ { type: 'input_image', image_url: dataUrl(image) },
91
+ ],
92
+ }
93
+ },
94
+ document: (i) => {
95
+ let doc = i as Extract<Item, { kind: 'document' }>
96
+ return {
97
+ role: 'user',
98
+ content: [
99
+ { type: 'input_text', text: doc.label },
100
+ {
101
+ type: 'input_file',
102
+ filename: doc.filename ?? doc.label,
103
+ file_data: dataUrl(doc),
104
+ },
105
+ ],
106
+ }
107
+ },
108
+ instruction: (i) => ({
109
+ role: 'developer',
110
+ content: [{ type: 'input_text', text: (i as { text: string }).text }],
111
+ }),
112
+ user: (i) => ({
113
+ role: 'user',
114
+ content: [{ type: 'input_text', text: (i as { text: string }).text }],
115
+ }),
116
+ assistant: (i) => ({
117
+ type: 'message',
118
+ role: 'assistant',
119
+ content: [{ type: 'output_text', text: (i as { text: string }).text }],
120
+ }),
121
+ call: (i) => {
122
+ let c = i as { id: string; name: string; args: string }
123
+ return {
124
+ type: 'function_call',
125
+ call_id: c.id,
126
+ name: c.name,
127
+ arguments: c.args,
128
+ }
129
+ },
130
+ result: (i) => {
131
+ let r = i as { id: string; output: string }
132
+ return { type: 'function_call_output', call_id: r.id, output: r.output }
133
+ },
134
+ }
135
+
136
+ /** A request's items as Responses input items. */
137
+ export let input = (items: Item[]): unknown[] =>
138
+ items.map((i) => shape[i.kind](i))
139
+
140
+ // Object insertion order from a graph or MCP server is not schema meaning.
141
+ // Arrays keep their order (tuple schemas and alternatives may depend on it).
142
+ let canonical = (value: unknown): unknown =>
143
+ Array.isArray(value)
144
+ ? value.map(canonical)
145
+ : record(value)
146
+ ? Object.fromEntries(
147
+ Object.keys(value).sort().map((key) => [key, canonical(value[key])]),
148
+ )
149
+ : value
150
+
151
+ let toolOrder = (a: Frame, b: Frame): number => {
152
+ let x = String(a.type) + ':' + String(a.name ?? '')
153
+ let y = String(b.type) + ':' + String(b.name ?? '')
154
+ return x < y ? -1 : x > y ? 1 : 0
155
+ }
156
+
157
+ // Hosted web search, held to `sites` where a request names them (@yaks/model
158
+ // `Request.sites`): it then reads only those domains.
159
+ let searching = (sites?: string[]) =>
160
+ sites ? { type: 'web_search', filters: { allowed_domains: sites } } : {
161
+ type: 'web_search',
162
+ }
163
+
164
+ // The models that reason, by name: the o-series, GPT-5 and after, and
165
+ // Codex. The API's list says nothing of it, and refuses a `reasoning`
166
+ // setting to a model that doesn't.
167
+ let REASONS = /^(?:o\d|gpt-(?:[5-9]|\d{2,})|codex)/
168
+
169
+ /** Whether `model` reasons, so a request asks what it thought: a summary of
170
+ * its reasoning, which a person reads beside the reply (@yaks/model
171
+ * `Reply.thought`). */
172
+ export let reasons = (model: string): boolean => REASONS.test(model)
173
+
174
+ // Models with explicit Responses API cache breakpoints.
175
+ let explicitCache = (model: string): boolean =>
176
+ /^gpt-(?:5\.[6-9]|[6-9])(?:[.-]|$)/.test(model)
177
+
178
+ // A request with a cache prefix sends its instructions as the conversation's
179
+ // first items, the shared part ending at a breakpoint, and the tools only
180
+ // some requests have (`scoped`) after them, so every conversation of an
181
+ // application reads one cached prefix. An anchored request continues a
182
+ // conversation the API holds, instructions and declared tools included: it
183
+ // sends only what followed, declaring the scoped tools the anchor's request
184
+ // was not sent (`Request.held`). The caller anchors only while the
185
+ // instructions are unchanged.
186
+ let prompt = (req: Request, scoped: Frame[]) => {
187
+ let prefix = req.cachePrefix
188
+ let explicit = explicitCache(req.model)
189
+ let cache = explicit
190
+ ? { prompt_cache_options: { mode: 'implicit', ttl: '30m' } }
191
+ : {}
192
+ if (prefix && req.instructions && req.anchor) {
193
+ let held = new Set(req.held)
194
+ let added = scoped.filter((t) => !held.has(String(t.name)))
195
+ return {
196
+ input: [
197
+ ...added.length ? [declaring(added)] : [],
198
+ ...input([...req.items, ...req.turnContext ?? []]),
199
+ ],
200
+ ...cache,
201
+ }
202
+ }
203
+ if (!prefix || !req.instructions) {
204
+ return {
205
+ ...req.instructions ? { instructions: req.instructions } : {},
206
+ input: input([...req.items, ...req.turnContext ?? []]),
207
+ }
208
+ }
209
+ let shared = req.instructions.slice(0, prefix.length)
210
+ let local = req.instructions.slice(prefix.length)
211
+ return {
212
+ input: [
213
+ {
214
+ role: 'developer',
215
+ content: [{
216
+ type: 'input_text',
217
+ text: shared,
218
+ ...explicit
219
+ ? {
220
+ prompt_cache_breakpoint: {
221
+ mode: 'explicit',
222
+ ...prefix.retention >= 43_200 ? { ttl: '12h' } : {},
223
+ },
224
+ }
225
+ : {},
226
+ }],
227
+ },
228
+ ...local ? input([{ kind: 'instruction', text: local }]) : [],
229
+ ...scoped.length ? [declaring(scoped)] : [],
230
+ ...input([...req.items, ...req.turnContext ?? []]),
231
+ ],
232
+ ...cache,
233
+ }
234
+ }
235
+
236
+ // Tools declared in the conversation, after the cached prefix rather than in
237
+ // the request's own list ahead of it.
238
+ let declaring = (tools: Frame[]) => ({
239
+ type: 'additional_tools',
240
+ role: 'developer',
241
+ tools,
242
+ })
243
+
244
+ /** The whole request body. */
245
+ export let body = (
246
+ req: Request,
247
+ store = false,
248
+ images?: Images,
249
+ web = false,
250
+ ): ResponseRequest => {
251
+ let tools = [
252
+ ...req.tools.map((t) => ({ type: 'function', strict: false, ...t })),
253
+ ...images ? [{ ...images.tool, type: 'image_generation' }] : [],
254
+ ...web ? [searching(req.sites)] : [],
255
+ ].sort(toolOrder)
256
+ let inline = req.cachePrefix?.tools && req.instructions &&
257
+ /^gpt-6(?:[.-]|$)/.test(req.model) && !req.sites
258
+ let shared = new Set(req.cachePrefix?.tools)
259
+ let scoped = (t: Frame) =>
260
+ inline && t.type == 'function' && !shared.has(String(t.name))
261
+ return request({
262
+ model: req.model,
263
+ ...prompt(req, tools.filter(scoped).map((t) => canonical(t) as Frame)),
264
+ tools: tools.filter((t) => !scoped(t)).map(canonical),
265
+ ...req.cachePrefix || req.conversation
266
+ ? { prompt_cache_key: req.cachePrefix?.key ?? req.conversation }
267
+ : {},
268
+ ...req.effort || reasons(req.model)
269
+ ? {
270
+ reasoning: {
271
+ ...req.effort ? { effort: req.effort } : {},
272
+ summary: 'auto',
273
+ },
274
+ }
275
+ : {},
276
+ ...req.tokens ? { max_output_tokens: req.tokens } : {},
277
+ ...req.anchor ? { previous_response_id: req.anchor } : {},
278
+ }, store)
279
+ }
280
+
281
+ /** Keep provider citations as clickable Markdown in the stored final text:
282
+ * each page cited that the text does not link yet, once, by its title or else
283
+ * its host. */
284
+ let citedText = (part: Frame): string => {
285
+ let text = str(part.text ?? part.refusal)
286
+ let annotations = Array.isArray(part.annotations) ? part.annotations : []
287
+ let links = annotations.filter((a): a is Frame =>
288
+ record(a) && a.type == 'url_citation' && typeof a.url == 'string'
289
+ )
290
+ for (let a of links) {
291
+ let url = URL.parse(String(a.url))
292
+ if (url?.protocol != 'https:' && url?.protocol != 'http:') continue
293
+ // The model often links its source inline itself, where the citation's
294
+ // offsets point; then the text has it already.
295
+ if (text.includes(String(a.url)) || text.includes(url.href)) continue
296
+ let title = str(a.title).replace(/[\[\]\\\r\n]/g, ' ').trim() ||
297
+ url.hostname
298
+ text += ` [${title}](<${url.href.replaceAll('>', '%3E')}>)`
299
+ }
300
+ return text
301
+ }
302
+
303
+ /** What a reply's reasoning items summarized, a paragraph a part, or
304
+ * nothing where it summarized none. */
305
+ export let thought = (done: Frame[]): string | undefined =>
306
+ done.filter((item) => item.type == 'reasoning').flatMap((item) =>
307
+ Array.isArray(item.summary) ? item.summary : []
308
+ ).map((part) => record(part) ? str(part.text).trim() : '').filter(Boolean)
309
+ .join('\n\n') || undefined
310
+
311
+ /** Completed output items as neutral items; reasoning ({@link thought}) and
312
+ * anything else the API adds are not part of the conversation and are
313
+ * dropped. */
314
+ export let items = (done: Frame[]): Item[] => {
315
+ let out: Item[] = []
316
+ for (let item of done) {
317
+ if (item.type == 'message') {
318
+ let parts = Array.isArray(item.content) ? item.content : []
319
+ let text = parts.map((p: unknown) => record(p) ? citedText(p) : '')
320
+ .join('')
321
+ out.push({
322
+ kind: 'assistant',
323
+ text,
324
+ ...item.id ? { id: str(item.id) } : {},
325
+ })
326
+ } else if (item.type == 'function_call') {
327
+ out.push({
328
+ kind: 'call',
329
+ id: str(item.call_id),
330
+ name: str(item.name),
331
+ args: str(item.arguments, '{}'),
332
+ })
333
+ }
334
+ }
335
+ return out
336
+ }
337
+
338
+ /**
339
+ * A {@link Model} over the Responses API.
340
+ *
341
+ * ```ts
342
+ * import { responses } from '@yaks/openai'
343
+ *
344
+ * let model = responses({
345
+ * credential: () => ({ token: 'key', base: 'https://api.openai.com/v1' }),
346
+ * })
347
+ * ```
348
+ *
349
+ * A refusal the API named (a 4xx, a failed response), a missing credential, and
350
+ * a connection that was never established are all {@link ModelError}s; the
351
+ * server records those as errors and carries on. Anything else thrown is a bug.
352
+ *
353
+ * The model writes `openai{response_id}` on every reply it returns, and returns
354
+ * that id as an anchor only when `store` is on: the Codex backend stores
355
+ * nothing, so through it a caller replays the conversation and the id is only a
356
+ * record, not something to continue from.
357
+ */
358
+ export let responses = (opts: Options): Model => {
359
+ let list = async () =>
360
+ listing(await opts.credential(), opts.fetch, opts.refresh, opts.headers)
361
+ let known = new Map<string, Listed | undefined>()
362
+ let info = (name: string) =>
363
+ sharing(known, name, async () => {
364
+ let model = (await list()).find((m) => m.name == name)
365
+ return model ? described(model, opts.fetch) : undefined
366
+ }, { scope: opts.scope })
367
+ let client = transport({
368
+ ...opts,
369
+ shape: (request) => request,
370
+ credentials: { get: opts.credential, refresh: opts.refresh },
371
+ })
372
+ return Object.assign(ask(opts, client), {
373
+ reads,
374
+ lateResults: true as const,
375
+ list,
376
+ info,
377
+ // Only OpenAI's own API, which keeps replies, counts input.
378
+ ...opts.store
379
+ ? { count: (req: Request) => client.count(wired(opts, req), req.signal) }
380
+ : {},
381
+ vocab: openaiDoc,
382
+ mark: marking(opts.provider ?? OPENAI_COMP, opts.retention),
383
+ anchor: (comps: Record<string, unknown>) =>
384
+ opts.store
385
+ ? responseAnchor(comps, opts.provider ?? OPENAI_COMP)
386
+ : undefined,
387
+ recover: (call: string) =>
388
+ recoveredMedia(
389
+ call,
390
+ opts.receipts,
391
+ (receipt) => delivered(receipt, opts),
392
+ ),
393
+ ...opts.background ? { retrieve: retrieving(opts, client) } : {},
394
+ })
395
+ }
396
+
397
+ let cancelling = (
398
+ opts: Options,
399
+ client: ReturnType<typeof transport>,
400
+ id: string,
401
+ ) => opts.hold ? opts.hold(client.cancel(id)) : client.cancel(id)
402
+
403
+ let retrieving =
404
+ (opts: Options, client: ReturnType<typeof transport>) =>
405
+ async (mark: Mark, signal?: AbortSignal): Promise<Reply | undefined> => {
406
+ let id = str(mark[opts.provider ?? OPENAI_COMP]?.response_id)
407
+ if (!id) return
408
+ try {
409
+ while (true) {
410
+ let response = await client.get(id, signal)
411
+ if (!response) return
412
+ if (response.id != id || typeof response.model != 'string') {
413
+ throw new ModelError(
414
+ 'response_receipt',
415
+ 'Invalid background response',
416
+ )
417
+ }
418
+ if (response.status == 'queued' || response.status == 'in_progress') {
419
+ await sleep(2000, signal, opts.clock)
420
+ continue
421
+ }
422
+ let cut = response.status == 'incomplete' &&
423
+ record(response.incomplete_details) &&
424
+ response.incomplete_details.reason == 'max_output_tokens'
425
+ if (response.status != 'completed' && !cut) return
426
+ let reply = await delivery(
427
+ response,
428
+ responseItems(response),
429
+ opts.images,
430
+ )
431
+ return cut ? { ...reply, cut: true } : reply
432
+ }
433
+ } finally {
434
+ if (signal?.aborted) await cancelling(opts, client, id)
435
+ }
436
+ }
437
+
438
+ // The request as it is sent.
439
+ let wired = (opts: Options, req: Request, background = false) => {
440
+ let prepared = body(req, opts.store, opts.images, opts.web ?? true)
441
+ if (background) prepared.background = true
442
+ return (opts.shape?.(prepared) ?? prepared) as ResponseRequest
443
+ }
444
+
445
+ let ask =
446
+ (opts: Options, client: ReturnType<typeof transport>) =>
447
+ async (req: Request): Promise<Reply> => {
448
+ if (req.questions) {
449
+ throw new ModelError(
450
+ 'questions',
451
+ 'The Responses API answers no typed questions',
452
+ )
453
+ }
454
+ let responseId = ''
455
+ let background = !!opts.background && !!req.onAck
456
+ let signal = req.signal && opts.signal
457
+ ? AbortSignal.any([req.signal, opts.signal])
458
+ : req.signal ?? opts.signal
459
+ try {
460
+ // The endpoint decides support, including OAuth and custom deployments.
461
+ // Never retry without the tool based on an ambiguous provider error.
462
+ let started = Date.now()
463
+ let selected = opts.images
464
+ const textIndexes = new Map<string, number>()
465
+ let wire = wired(opts, req, background)
466
+ let output: Frame[] = []
467
+ let receipt: MediaReceipt | undefined
468
+ let checkpointed = false
469
+ let out = await client.run(
470
+ wire,
471
+ {
472
+ submit: req.onSubmit || opts.submit
473
+ ? async (request) => {
474
+ wire = request
475
+ await opts.submit?.(request)
476
+ await submitted(req)
477
+ }
478
+ : undefined,
479
+ signal,
480
+ noRetry: () => checkpointed || !!req.onText && textIndexes.size > 0,
481
+ conversation: req.conversation,
482
+ ...req.stallTimeout == null
483
+ ? {}
484
+ : { stallMs: Math.max(0, req.stallTimeout) * 1000 },
485
+ // Image payloads must never escape through diagnostic/event subscribers.
486
+ event: async (event) => {
487
+ let response = record(event.response) ? event.response : undefined
488
+ let id = str(response?.id ?? event.response_id)
489
+ if (id && !responseId) {
490
+ responseId = id
491
+ checkpointed ||= !!req.onAck
492
+ await acknowledged(req, {
493
+ [opts.provider ?? OPENAI_COMP]: { response_id: id },
494
+ })
495
+ }
496
+ if (event.type == 'response.output_item.added') began(req)
497
+ if (
498
+ event.type == 'response.output_item.done' && record(event.item)
499
+ ) {
500
+ output.push(event.item)
501
+ }
502
+ let terminal = event.type == 'response.completed'
503
+ let complete = terminal && response?.status == 'completed' &&
504
+ typeof response.model == 'string'
505
+ let partial =
506
+ event.type == 'response.image_generation_call.partial_image' ||
507
+ (event.type == 'response.output_item.done' &&
508
+ record(event.item) &&
509
+ event.item.type == 'image_generation_call')
510
+ if ((terminal || partial) && responseId) {
511
+ let { cost } = tokenUsage(response?.usage)
512
+ receipt = {
513
+ provider: opts.provider ?? OPENAI_COMP,
514
+ call: req.call ?? responseId,
515
+ id: responseId,
516
+ model: str(response?.model, req.model),
517
+ input: wire,
518
+ response: {
519
+ api: 'responses',
520
+ response: response ?? { id: responseId },
521
+ items: output.length
522
+ ? [...output]
523
+ : Array.isArray(response?.output)
524
+ ? response.output
525
+ : [],
526
+ ...partial ? { event } : {},
527
+ },
528
+ complete,
529
+ ...cost !== undefined ? { cost, costReported: true } : {},
530
+ }
531
+ checkpointed ||= !!opts.receipts || !!req.onReceipt ||
532
+ !!req.onMedia
533
+ await receivedMedia(req, receipt, opts.receipts)
534
+ }
535
+ if (
536
+ (event.type == 'response.output_text.delta' ||
537
+ event.type == 'response.refusal.delta') &&
538
+ typeof event.delta == 'string'
539
+ ) {
540
+ const key = String(event.item_id ?? event.output_index)
541
+ if (!textIndexes.has(key)) textIndexes.set(key, textIndexes.size)
542
+ req.onText?.({
543
+ index: textIndexes.get(key)!,
544
+ id: key,
545
+ text: event.delta,
546
+ })
547
+ }
548
+ await opts.event?.(imageSafe(event))
549
+ },
550
+ },
551
+ )
552
+ let reply = await delivery(
553
+ out.response,
554
+ out.items.length ? out.items : responseItems(out.response),
555
+ selected,
556
+ )
557
+ if (receipt) await opts.receipts?.save({ ...receipt, reply })
558
+ let limits = planLimits(out.limits, opts.account)
559
+ return {
560
+ ...reply,
561
+ ...req.cachePrefix && explicitCache(req.model) &&
562
+ reply.cacheExpiresAt === undefined
563
+ ? { cacheExpiresAt: new Date(started + 1_800_000).toISOString() }
564
+ : {},
565
+ ...out.cut ? { cut: true } : {},
566
+ ...limits.length ? { limits } : {},
567
+ }
568
+ } catch (error) {
569
+ // A reply the API no longer keeps (past its retention, or deleted) is
570
+ // no defect: asked again with the whole conversation, it passes.
571
+ if (req.anchor && unanchored(error)) {
572
+ throw new ModelError(UNANCHORED, (error as Error).message)
573
+ }
574
+ // Invalid request history is a caller defect, not an operational refusal.
575
+ // Keep the transport exception (including provider details) healable.
576
+ if (
577
+ !(error instanceof ResponseError) ||
578
+ error.code == 'invalid_request_error'
579
+ ) throw error
580
+ let { body, limits } = error
581
+ let headers = limits && Object.keys(limits).length ? limits : undefined
582
+ let read = planLimits(limits ?? {}, opts.account)
583
+ let { usage } = tokenUsage(error.usage)
584
+ throw Object.assign(
585
+ new ModelError(
586
+ error.code ?? error.kind,
587
+ error.message,
588
+ error.retry,
589
+ body || headers ? { body, headers } : undefined,
590
+ ),
591
+ read.length ? { limits: read } : {},
592
+ usage ? { usage } : {},
593
+ )
594
+ } finally {
595
+ if (background && responseId && signal?.aborted) {
596
+ await cancelling(opts, client, responseId)
597
+ }
598
+ }
599
+ }
600
+
601
+ // The API's refusal of a `previous_response_id` it does not hold.
602
+ let unanchored = (error: unknown) =>
603
+ error instanceof ResponseError && error.status != null &&
604
+ error.status < 500 &&
605
+ (error.code == 'previous_response_not_found' ||
606
+ /previous[ _]response/i.test(`${error.message} ${error.body ?? ''}`))
607
+
608
+ let delivered = (receipt: MediaReceipt, opts: Options): Promise<Reply> => {
609
+ let data = receipt.response
610
+ if (
611
+ !record(data) || data.api != 'responses' || !record(data.response) ||
612
+ data.response.status != 'completed' ||
613
+ typeof data.response.model != 'string' ||
614
+ data.response.id != receipt.id ||
615
+ !Array.isArray(data.items) || !data.items.every(record)
616
+ ) {
617
+ throw new ModelError('media_receipt', 'Invalid Responses receipt')
618
+ }
619
+ return delivery(data.response, data.items, opts.images)
620
+ }
621
+
622
+ let responseItems = (response: Frame): Frame[] =>
623
+ Array.isArray(response.output) ? response.output.filter(record) : []
624
+
625
+ let delivery = async (
626
+ response: Frame,
627
+ output: Frame[],
628
+ images?: Images,
629
+ ): Promise<Reply> => {
630
+ let artifacts = await generatedImages(output, images)
631
+ let thinking = thought(output)
632
+ return {
633
+ id: str(response.id),
634
+ model: str(response.model),
635
+ ...thinking ? { thought: thinking } : {},
636
+ ...response.cache_expires_at !== undefined
637
+ ? { cacheExpiresAt: cacheExpiry(response.cache_expires_at) ?? null }
638
+ : {},
639
+ items: items(output),
640
+ ...artifacts.length ? { artifacts } : {},
641
+ ...searched(tokenUsage(response.usage), output),
642
+ }
643
+ }
644
+
645
+ // What a reply's usage says with the hosted searches it ran, each billed at
646
+ // the model's `web_search` (@yaks/model `Usage.web_searches`): OpenAI counts
647
+ // them only as items of its output.
648
+ let searched = (
649
+ reply: Pick<Reply, 'usage' | 'cost'>,
650
+ output: Frame[],
651
+ ): Pick<Reply, 'usage' | 'cost'> => {
652
+ let n = output.filter((o) =>
653
+ o.type == 'web_search_call' &&
654
+ (!record(o.action) || o.action.type == 'search')
655
+ ).length
656
+ return n ? { ...reply, usage: { ...reply.usage, web_searches: n } } : reply
657
+ }
658
+
659
+ /** Preserve absence: an unreported cache count is not a cache miss. A
660
+ * provider that reports what the request cost in dollars (OpenRouter's
661
+ * `usage.cost`) answers it as the reply's `cost`; OpenAI reports none. */
662
+ export let tokenUsage = (raw: unknown): Pick<Reply, 'usage' | 'cost'> => {
663
+ if (!raw || typeof raw != 'object') return {}
664
+ let u = raw as Record<string, unknown>
665
+ let detail = (key: string, field: string) => {
666
+ let value = u[key]
667
+ return value && typeof value == 'object'
668
+ ? (value as Record<string, unknown>)[field]
669
+ : undefined
670
+ }
671
+ let writes = detail('input_tokens_details', 'cache_write_tokens_details')
672
+ let usage = Object.fromEntries(
673
+ Object.entries({
674
+ input_tokens: u.input_tokens,
675
+ output_tokens: u.output_tokens,
676
+ total_tokens: u.total_tokens,
677
+ cached_tokens: detail('input_tokens_details', 'cached_tokens'),
678
+ cache_write_tokens: detail('input_tokens_details', 'cache_write_tokens'),
679
+ cache_write_12h_tokens: record(writes)
680
+ ? writes.ttl_12h_tokens
681
+ : undefined,
682
+ reasoning_tokens: detail('output_tokens_details', 'reasoning_tokens'),
683
+ }).filter(([, n]) =>
684
+ typeof n == 'number' && Number.isSafeInteger(n) && n >= 0
685
+ ),
686
+ ) as Usage
687
+ let cost = u.cost
688
+ return {
689
+ ...Object.keys(usage).length ? { usage } : {},
690
+ ...typeof cost == 'number' && Number.isFinite(cost) && cost >= 0
691
+ ? { cost }
692
+ : {},
693
+ }
694
+ }
695
+
696
+ /** Remove binary result fields from event observers, including nested response output. */
697
+ let imageSafe = <T>(value: T): T => {
698
+ if (Array.isArray(value)) return value.map(imageSafe) as T
699
+ if (!record(value)) return value
700
+ let image = value.type == 'image_generation_call'
701
+ return Object.fromEntries(
702
+ Object.entries(value).filter(([key]) =>
703
+ key != 'partial_image_b64' && !(image && key == 'result')
704
+ ).map(([key, item]) => [key, imageSafe(item)]),
705
+ ) as T
706
+ }