@a-dray/aglib 0.6.7 → 0.7.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.
@@ -0,0 +1,217 @@
1
+ import { textOf } from "../../content.js";
2
+ /**
3
+ * What a vendor-loop harness shares: an agent process that owns its own
4
+ * context and model calls, running *our* tools and nothing of its own.
5
+ *
6
+ * Two facts hold for every such adapter and are why this file exists rather
7
+ * than two copies of it. The vendor's conversation lives in the vendor's own
8
+ * session store, so continuing it means naming that session; and our log has
9
+ * to say what happened in a shape a native model could take over from, because
10
+ * an owner who switches an instance from a subscription to an API key expects
11
+ * the conversation to carry on.
12
+ */
13
+ /**
14
+ * The vendor session a run continues, recorded on the run's final assistant
15
+ * entry. `fingerprint` names what the session was opened with that cannot be
16
+ * changed on resume — a vendor that fixes the tool list at session start is
17
+ * resumed only while the list is the same.
18
+ */
19
+ export function sessionState(provider, session, fingerprint) {
20
+ return { provider, items: [{ session, ...(fingerprint ? { fingerprint } : {}) }] };
21
+ }
22
+ /** A stable name for a tool list, by what the model is shown of it. */
23
+ export function toolFingerprint(context) {
24
+ const text = JSON.stringify((context.tools?.list() ?? []).map((tool) => [tool.name, tool.description, tool.parameters]));
25
+ let hash = 2166136261;
26
+ for (let index = 0; index < text.length; index += 1)
27
+ hash = Math.imul(hash ^ text.charCodeAt(index), 16777619) >>> 0;
28
+ return hash.toString(16);
29
+ }
30
+ /**
31
+ * Where this activation starts: the vendor session to resume, and the words to
32
+ * open it with.
33
+ *
34
+ * A session is resumed only when the latest assistant entry in the log was
35
+ * written by this provider and names it. Any later assistant entry means
36
+ * another model spoke since, so the vendor's copy is missing part of the
37
+ * conversation and resuming it would answer from a past that is not the log's.
38
+ * Then the session starts fresh, opened with the conversation so far rendered
39
+ * as text: the vendor cannot be handed our messages as its own, and a summary
40
+ * of them is the honest substitute. `fresh` asks for that start whatever the
41
+ * log says, for a session the log names and the vendor no longer has; a
42
+ * `fingerprint` that differs from the recorded one asks for it too.
43
+ */
44
+ export function opening(context, provider, options = {}) {
45
+ const entries = context.entries();
46
+ const last = entries.findLast((entry) => entry.type === "assistant");
47
+ const state = !options.fresh && last?.type === "assistant" && last.providerState?.provider === provider ? last.providerState.items[0] : undefined;
48
+ const fields = state && typeof state === "object" && !Array.isArray(state) ? state : {};
49
+ const session = typeof fields["session"] === "string" && fields["fingerprint"] === options.fingerprint ? fields["session"] : undefined;
50
+ const turn = context.context?.turn ? [`<turn-context>\n${context.context.turn}\n</turn-context>`] : [];
51
+ if (session) {
52
+ const since = entries.filter((entry) => (entry.type === "run.started" || entry.type === "hook.input") && entry.seq > last.seq);
53
+ return { resume: session, prompt: join([...turn, ...since.map((entry) => entry.input)]) };
54
+ }
55
+ const current = entries.filter((entry) => entry.type === "run.started" && entry.runId === context.runId);
56
+ const before = earlier(context.history(), current.length);
57
+ const transcript = before.length ? [`<conversation-so-far>\n${transcriptText(before)}\n</conversation-so-far>`] : [];
58
+ return { prompt: join([...transcript, ...turn, ...current.map((entry) => entry.input)]) };
59
+ }
60
+ /** Inputs folded into this run by `drain` that the vendor has not been shown yet. */
61
+ export function arrivals(context, shown) {
62
+ return context.entries()
63
+ .filter((entry) => entry.type === "run.started" && entry.runId === context.runId && !shown.has(entry.seq))
64
+ .map((entry) => { shown.add(entry.seq); return entry.input; });
65
+ }
66
+ /** Seqs of this run's inputs that `opening` already put in the prompt. */
67
+ export function openingInputs(context) {
68
+ return new Set(context.entries().filter((entry) => entry.type === "run.started" && entry.runId === context.runId).map((entry) => entry.seq));
69
+ }
70
+ /**
71
+ * The conversation before this run, as the model was shown it: the projection
72
+ * minus its system messages (the vendor gets ours as its own instructions) and
73
+ * minus the inputs this run is about to send.
74
+ */
75
+ function earlier(messages, current) {
76
+ const body = messages.filter((message) => message.role !== "system");
77
+ let drop = current;
78
+ const out = [...body];
79
+ while (drop > 0 && out.length && out[out.length - 1].role === "user") {
80
+ out.pop();
81
+ drop -= 1;
82
+ }
83
+ return out;
84
+ }
85
+ const RESULT_CHARS = 4_000;
86
+ /** A readable transcript. Tool output is cut, because the next turns can read again what matters. */
87
+ export function transcriptText(messages) {
88
+ return messages.map((message) => {
89
+ if (message.role === "user")
90
+ return `[user]\n${described(message.content)}`;
91
+ if (message.role === "assistant") {
92
+ const calls = (message.calls ?? []).map((call) => `→ ${call.name}(${call.arguments})`);
93
+ return [`[assistant]`, textOf(message.content), ...calls].filter(Boolean).join("\n");
94
+ }
95
+ if (message.role === "tool") {
96
+ const text = described(message.content);
97
+ return `[tool result${message.isError ? ", error" : ""}]\n${text.length > RESULT_CHARS ? `${text.slice(0, RESULT_CHARS)}…` : text}`;
98
+ }
99
+ return "";
100
+ }).filter(Boolean).join("\n\n");
101
+ }
102
+ /** Text, with media named rather than dropped silently. */
103
+ export function described(content) {
104
+ if (typeof content === "string")
105
+ return content;
106
+ return content.map((part) => {
107
+ if (part.type === "text")
108
+ return part.text;
109
+ if (part.type === "image")
110
+ return `[image ${part.mediaType}]`;
111
+ if (part.type === "file")
112
+ return `[file ${part.name ?? ""} ${part.mediaType}]`.replace(" ", " ");
113
+ return "";
114
+ }).filter(Boolean).join("\n");
115
+ }
116
+ function join(parts) {
117
+ const out = [];
118
+ for (const part of parts) {
119
+ if (typeof part === "string") {
120
+ if (part)
121
+ out.push({ type: "text", text: part });
122
+ }
123
+ else
124
+ out.push(...part);
125
+ }
126
+ return out.every((part) => part.type === "text") ? out.map((part) => part.text).join("\n\n") : out;
127
+ }
128
+ /**
129
+ * Runs our tools for a vendor's loop, one call at a time, through the log.
130
+ *
131
+ * Each call is committed the way the native loop commits one — the assistant
132
+ * turn that asked for it with the text said before it, then `tool.started`,
133
+ * then `tool.finished` with the call's deliveries — so the log projects to a
134
+ * conversation any model can continue. Calls are serialised: a vendor may run
135
+ * several at once, and interleaving their entries would leave an assistant turn
136
+ * whose calls are answered out of order.
137
+ */
138
+ export function createToolRunner(context) {
139
+ let said = "";
140
+ let tail = Promise.resolve();
141
+ let usage;
142
+ return {
143
+ /** A block of text the vendor said, since the last call or the start. */
144
+ say(text) { if (text)
145
+ said = said ? `${said}\n\n${text}` : text; },
146
+ /** Usage to carry on the next committed assistant entry. */
147
+ spent(next) { usage = addUsage(usage, next); },
148
+ /**
149
+ * A call the vendor made through one of its own account connectors, which
150
+ * ran in the vendor's cloud rather than through our executor. It is
151
+ * recorded as a note — what was said before it, then the call and what it
152
+ * returned — not as a tool call, because a model that takes the session
153
+ * over has no such tool, and a provider may refuse a history that calls a
154
+ * tool the request does not declare.
155
+ */
156
+ note(call) {
157
+ const record = `[connector ${call.name}] ${JSON.stringify(call.arguments ?? {})}\n${call.isError ? "failed: " : "→ "}${call.result.length > RESULT_CHARS ? `${call.result.slice(0, RESULT_CHARS)}…` : call.result}`;
158
+ const next = tail.then(async () => {
159
+ const text = said;
160
+ said = "";
161
+ await context.commit([{ type: "assistant", runId: context.runId, content: text ? `${text}\n\n${record}` : record }]);
162
+ });
163
+ tail = next.catch(() => undefined);
164
+ return next;
165
+ },
166
+ run(call) {
167
+ const next = tail.then(() => runOne(call));
168
+ tail = next.catch(() => undefined);
169
+ return next;
170
+ },
171
+ /** The final assistant entry: what was said after the last call, and where the vendor's session is. */
172
+ async finish(providerState, generation) {
173
+ await tail;
174
+ const text = said;
175
+ said = "";
176
+ const spentHere = usage;
177
+ usage = undefined;
178
+ await context.commit([{
179
+ type: "assistant", runId: context.runId, content: text,
180
+ ...(spentHere ? { usage: spentHere } : {}), providerState,
181
+ generation: { ...generation, endedAt: new Date().toISOString(), ...(context.context?.turn ? { turn: context.context.turn } : {}) },
182
+ }]);
183
+ return text;
184
+ },
185
+ };
186
+ async function runOne(call) {
187
+ const text = said;
188
+ said = "";
189
+ const spentHere = usage;
190
+ usage = undefined;
191
+ await context.commit([
192
+ { type: "assistant", runId: context.runId, content: text, calls: [call], ...(spentHere ? { usage: spentHere } : {}) },
193
+ { type: "tool.started", runId: context.runId, callId: call.callId },
194
+ ]);
195
+ let completion;
196
+ if (context.tools) {
197
+ for await (const done of context.tools.execute({ calls: [call], signal: context.signal })) {
198
+ completion = done;
199
+ break;
200
+ }
201
+ }
202
+ const result = completion?.result ?? { content: context.tools ? "Tool use cancelled" : `No tool named '${call.name}' is available.`, isError: true };
203
+ await context.commit([{ type: "tool.finished", runId: context.runId, callId: call.callId, result }], completion?.deliveries ?? []);
204
+ return result;
205
+ }
206
+ }
207
+ export function addUsage(a, b) {
208
+ if (!a)
209
+ return { ...b };
210
+ const out = { ...a };
211
+ for (const key of ["inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens", "costUsd"]) {
212
+ if (b[key] !== undefined)
213
+ out[key] = (out[key] ?? 0) + b[key];
214
+ }
215
+ return out;
216
+ }
217
+ //# sourceMappingURL=vendor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vendor.js","sourceRoot":"","sources":["../../../src/harness/adapters/vendor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAK1C;;;;;;;;;;GAUG;AAEH;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,QAAgB,EAAE,OAAe,EAAE,WAAoB;IAClF,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAgB,EAAE,CAAC;AACpG,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,eAAe,CAAC,OAAuB;IACrD,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACzH,IAAI,IAAI,GAAG,UAAU,CAAC;I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AAC;AACH,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,CAAoB,EAAE,CAAQ;IACrD,IAAI,CAAC,CAAC;QAAE,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;IACxB,MAAM,GAAG,GAAU,EAAE,GAAG,CAAC,EAAE,CAAC;IAC5B,KAAK,MAAM,GAAG,IAAI,CAAC,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,SAAS,CAAU,EAAE,CAAC;QAC7G,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,SAAS;YAAE,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChE,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import type { HarnessContext } from \"../harness.js\";\nimport type { Content, ContentPart } from \"../../content.js\";\nimport { textOf } from \"../../content.js\";\nimport type { Delivery, Entry, Stored, ToolCall, ToolResult, Usage } from \"../../session/entry.js\";\nimport type { Message } from \"../../session/messages.js\";\nimport type { JsonValue } from \"../../json.js\";\n\n/**\n * What a vendor-loop harness shares: an agent process that owns its own\n * context and model calls, running *our* tools and nothing of its own.\n *\n * Two facts hold for every such adapter and are why this file exists rather\n * than two copies of it. The vendor's conversation lives in the vendor's own\n * session store, so continuing it means naming that session; and our log has\n * to say what happened in a shape a native model could take over from, because\n * an owner who switches an instance from a subscription to an API key expects\n * the conversation to carry on.\n */\n\n/**\n * The vendor session a run continues, recorded on the run's final assistant\n * entry. `fingerprint` names what the session was opened with that cannot be\n * changed on resume — a vendor that fixes the tool list at session start is\n * resumed only while the list is the same.\n */\nexport function sessionState(provider: string, session: string, fingerprint?: string) {\n return { provider, items: [{ session, ...(fingerprint ? { fingerprint } : {}) }] as JsonValue[] };\n}\n\n/** A stable name for a tool list, by what the model is shown of it. */\nexport function toolFingerprint(context: HarnessContext): string {\n const text = JSON.stringify((context.tools?.list() ?? []).map((tool) => [tool.name, tool.description, tool.parameters]));\n let hash = 2166136261;\n for (let index = 0; index < text.length; index += 1) hash = Math.imul(hash ^ text.charCodeAt(index), 16777619) >>> 0;\n return hash.toString(16);\n}\n\n/**\n * Where this activation starts: the vendor session to resume, and the words to\n * open it with.\n *\n * A session is resumed only when the latest assistant entry in the log was\n * written by this provider and names it. Any later assistant entry means\n * another model spoke since, so the vendor's copy is missing part of the\n * conversation and resuming it would answer from a past that is not the log's.\n * Then the session starts fresh, opened with the conversation so far rendered\n * as text: the vendor cannot be handed our messages as its own, and a summary\n * of them is the honest substitute. `fresh` asks for that start whatever the\n * log says, for a session the log names and the vendor no longer has; a\n * `fingerprint` that differs from the recorded one asks for it too.\n */\nexport function opening(context: HarnessContext, provider: string, options: { fresh?: boolean; fingerprint?: string } = {}): { resume?: string; prompt: Content } {\n const entries = context.entries();\n const last = entries.findLast((entry) => entry.type === \"assistant\");\n const state = !options.fresh && last?.type === \"assistant\" && last.providerState?.provider === provider ? last.providerState.items[0] : undefined;\n const fields = state && typeof state === \"object\" && !Array.isArray(state) ? state as { readonly [key: string]: JsonValue } : {};\n const session = typeof fields[\"session\"] === \"string\" && fields[\"fingerprint\"] === options.fingerprint ? fields[\"session\"] : undefined;\n const turn = context.context?.turn ? [`<turn-context>\\n${context.context.turn}\\n</turn-context>`] : [];\n if (session) {\n const since = entries.filter((entry): entry is Stored<Extract<Entry, { type: \"run.started\" | \"hook.input\" }>> =>\n (entry.type === \"run.started\" || entry.type === \"hook.input\") && entry.seq > last!.seq);\n return { resume: session, prompt: join([...turn, ...since.map((entry) => entry.input)]) };\n }\n const current = entries.filter((entry) => entry.type === \"run.started\" && entry.runId === context.runId);\n const before = earlier(context.history(), current.length);\n const transcript = before.length ? [`<conversation-so-far>\\n${transcriptText(before)}\\n</conversation-so-far>`] : [];\n return { prompt: join([...transcript, ...turn, ...current.map((entry) => (entry as Extract<Entry, { type: \"run.started\" }>).input)]) };\n}\n\n/** Inputs folded into this run by `drain` that the vendor has not been shown yet. */\nexport function arrivals(context: HarnessContext, shown: Set<number>): Content[] {\n return context.entries()\n .filter((entry) => entry.type === \"run.started\" && entry.runId === context.runId && !shown.has(entry.seq))\n .map((entry) => { shown.add(entry.seq); return (entry as Extract<Entry, { type: \"run.started\" }>).input; });\n}\n\n/** Seqs of this run's inputs that `opening` already put in the prompt. */\nexport function openingInputs(context: HarnessContext): Set<number> {\n return new Set(context.entries().filter((entry) => entry.type === \"run.started\" && entry.runId === context.runId).map((entry) => entry.seq));\n}\n\n/**\n * The conversation before this run, as the model was shown it: the projection\n * minus its system messages (the vendor gets ours as its own instructions) and\n * minus the inputs this run is about to send.\n */\nfunction earlier(messages: readonly Message[], current: number): Message[] {\n const body = messages.filter((message) => message.role !== \"system\");\n let drop = current;\n const out = [...body];\n while (drop > 0 && out.length && out[out.length - 1]!.role === \"user\") { out.pop(); drop -= 1; }\n return out;\n}\n\nconst RESULT_CHARS = 4_000;\n\n/** A readable transcript. Tool output is cut, because the next turns can read again what matters. */\nexport function transcriptText(messages: readonly Message[]): string {\n return messages.map((message) => {\n if (message.role === \"user\") return `[user]\\n${described(message.content)}`;\n if (message.role === \"assistant\") {\n const calls = (message.calls ?? []).map((call) => `→ ${call.name}(${call.arguments})`);\n return [`[assistant]`, textOf(message.content), ...calls].filter(Boolean).join(\"\\n\");\n }\n if (message.role === \"tool\") {\n const text = described(message.content);\n return `[tool result${message.isError ? \", error\" : \"\"}]\\n${text.length > RESULT_CHARS ? `${text.slice(0, RESULT_CHARS)}…` : text}`;\n }\n return \"\";\n }).filter(Boolean).join(\"\\n\\n\");\n}\n\n/** Text, with media named rather than dropped silently. */\nexport function described(content: Content): string {\n if (typeof content === \"string\") return content;\n return content.map((part) => {\n if (part.type === \"text\") return part.text;\n if (part.type === \"image\") return `[image ${part.mediaType}]`;\n if (part.type === \"file\") return `[file ${part.name ?? \"\"} ${part.mediaType}]`.replace(\" \", \" \");\n return \"\";\n }).filter(Boolean).join(\"\\n\");\n}\n\nfunction join(parts: readonly Content[]): Content {\n const out: ContentPart[] = [];\n for (const part of parts) {\n if (typeof part === \"string\") { if (part) out.push({ type: \"text\", text: part }); }\n else out.push(...part);\n }\n return out.every((part) => part.type === \"text\") ? out.map((part) => (part as { text: string }).text).join(\"\\n\\n\") : out;\n}\n\n/**\n * Runs our tools for a vendor's loop, one call at a time, through the log.\n *\n * Each call is committed the way the native loop commits one — the assistant\n * turn that asked for it with the text said before it, then `tool.started`,\n * then `tool.finished` with the call's deliveries — so the log projects to a\n * conversation any model can continue. Calls are serialised: a vendor may run\n * several at once, and interleaving their entries would leave an assistant turn\n * whose calls are answered out of order.\n */\nexport function createToolRunner(context: HarnessContext) {\n let said = \"\";\n let tail: Promise<unknown> = Promise.resolve();\n let usage: Usage | undefined;\n return {\n /** A block of text the vendor said, since the last call or the start. */\n say(text: string) { if (text) said = said ? `${said}\\n\\n${text}` : text; },\n /** Usage to carry on the next committed assistant entry. */\n spent(next: Usage) { usage = addUsage(usage, next); },\n /**\n * A call the vendor made through one of its own account connectors, which\n * ran in the vendor's cloud rather than through our executor. It is\n * recorded as a note — what was said before it, then the call and what it\n * returned — not as a tool call, because a model that takes the session\n * over has no such tool, and a provider may refuse a history that calls a\n * tool the request does not declare.\n */\n note(call: { name: string; arguments: unknown; result: string; isError?: boolean }) {\n const record = `[connector ${call.name}] ${JSON.stringify(call.arguments ?? {})}\\n${call.isError ? \"failed: \" : \"→ \"}${call.result.length > RESULT_CHARS ? `${call.result.slice(0, RESULT_CHARS)}…` : call.result}`;\n const next = tail.then(async () => {\n const text = said;\n said = \"\";\n await context.commit([{ type: \"assistant\", runId: context.runId, content: text ? `${text}\\n\\n${record}` : record }]);\n });\n tail = next.catch(() => undefined);\n return next;\n },\n run(call: ToolCall): Promise<ToolResult> {\n const next = tail.then(() => runOne(call));\n tail = next.catch(() => undefined);\n return next;\n },\n /** The final assistant entry: what was said after the last call, and where the vendor's session is. */\n async finish(providerState: { provider: string; items: JsonValue[] }, generation: { id: string; model?: string; startedAt: string }) {\n await tail;\n const text = said;\n said = \"\";\n const spentHere = usage;\n usage = undefined;\n await context.commit([{\n type: \"assistant\", runId: context.runId, content: text,\n ...(spentHere ? { usage: spentHere } : {}), providerState,\n generation: { ...generation, endedAt: new Date().toISOString(), ...(context.context?.turn ? { turn: context.context.turn } : {}) },\n }]);\n return text;\n },\n };\n\n async function runOne(call: ToolCall): Promise<ToolResult> {\n const text = said;\n said = \"\";\n const spentHere = usage;\n usage = undefined;\n await context.commit([\n { type: \"assistant\", runId: context.runId, content: text, calls: [call], ...(spentHere ? { usage: spentHere } : {}) },\n { type: \"tool.started\", runId: context.runId, callId: call.callId },\n ]);\n let completion: { result: ToolResult; deliveries: readonly Delivery[] } | undefined;\n if (context.tools) {\n for await (const done of context.tools.execute({ calls: [call], signal: context.signal })) { completion = done; break; }\n }\n const result = completion?.result ?? { content: context.tools ? \"Tool use cancelled\" : `No tool named '${call.name}' is available.`, isError: true };\n await context.commit([{ type: \"tool.finished\", runId: context.runId, callId: call.callId, result }], completion?.deliveries ?? []);\n return result;\n }\n}\n\nexport function addUsage(a: Usage | undefined, b: Usage): Usage {\n if (!a) return { ...b };\n const out: Usage = { ...a };\n for (const key of [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\", \"costUsd\"] as const) {\n if (b[key] !== undefined) out[key] = (out[key] ?? 0) + b[key];\n }\n return out;\n}\n"]}
@@ -234,9 +234,9 @@ function encodeConversation(messages, provider, marked) {
234
234
  mark(encoded);
235
235
  out.push(encoded);
236
236
  if (message.role === "tool" && typeof message.content !== "string") {
237
- const media = message.content.filter((part) => part.type === "image");
237
+ const media = message.content.filter((part) => part.type === "image" || part.type === "file");
238
238
  if (media.length)
239
- images.push({ type: "text", text: `Images from tool call ${message.callId}:` }, ...media);
239
+ images.push({ type: "text", text: `Attachments from tool call ${message.callId}:` }, ...media);
240
240
  }
241
241
  });
242
242
  flush();
@@ -294,7 +294,11 @@ function encodeContent(content) {
294
294
  const url = part.source.kind === "url" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;
295
295
  parts.push({ type: "image_url", image_url: { url } });
296
296
  }
297
- // Files and opaque blocks have no place on this wire. Dropping them beats
297
+ if (part.type === "file") {
298
+ const file_data = part.source.kind === "url" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;
299
+ parts.push({ type: "file", file: { filename: part.name ?? "attachment", file_data } });
300
+ }
301
+ // Opaque blocks have no place on this wire. Dropping them beats
298
302
  // stringifying them into something the model would read as prose.
299
303
  }
300
304
  const only = parts.length === 1 ? parts[0] : undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/openai-compatible/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAqB,MAAM,gBAAgB,CAAC;AA2C3E;;;GAGG;AACH,MAAM,UAAU,2BAA2B,CAAC,OAAgC;IAC1E,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE,EAAE,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IACzG,MAAM,QAAQ,GAAG,qBAAqB,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;IAC5E,MAAM,OAAO,GAAG,OAAO,CAAC,eAAe,KAAK,eAAe,CAAC;IAC5D,OAAO;QACL,EAAE,EAAE,qBAAqB,OAAO,CAAC,KAAK,EAAE;QAExC,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAqB;YACnC,IAAI,QAAkB,CAAC;YACvB,IAAI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AC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { isWaitStatus, retrying, type RetryOptions } from \"../../retry.js\";\n\nexport interface OpenAiCompatibleOptions {\n apiKey: string;\n baseUrl: string;\n model: string;\n headers?: Readonly<Record<string, string>>;\n /**\n * How this endpoint spells reasoning effort. OpenAI takes `reasoning_effort`;\n * OpenRouter takes `reasoning: { effort }` and forwards it to whoever is\n * serving the model. Sending both is not compatibility — OpenAI rejects the\n * request outright — so the dialect is declared rather than guessed.\n */\n effortParameter?: \"reasoning_effort\" | \"reasoning\" | \"none\";\n /**\n * How this endpoint spells a cache breakpoint, where it has one. Most models\n * on this wire cache a repeated prefix by themselves and have no field for\n * it — plain OpenAI rejects one it does not know — so the default sends none.\n * OpenRouter takes Anthropic's `cache_control` on a text part and forwards\n * it to the models that cache nothing without one.\n */\n cacheBreakpoint?: \"cache_control\" | \"none\";\n /**\n * The conversation this model is serving, sent as `prompt_cache_key` on every\n * request. A provider that caches a prefix per backend routes requests that\n * share a key to the backend holding it; without one a growing conversation\n * lands on a different backend each turn and reads almost none of it back.\n * Meta's Muse Spark behind OpenRouter is the case measured: 3% of a\n * conversation's prefix read from cache without it, 91% with it. Set only\n * where the endpoint takes the field — plain OpenAI chat completions does\n * not — so the default sends none.\n */\n promptCacheKey?: string;\n /**\n * A refusal this endpoint means as a wait, beyond the statuses every HTTP\n * wire means so. Retried before the first delta like those, and reported as\n * a rate limit when the retries run out.\n */\n isWait?: RetryOptions[\"isWait\"];\n /** Injectable for tests; defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * The OpenAI chat-completions wire, which almost every provider now speaks —\n * OpenRouter, Together, Groq, vLLM, Ollama. One adapter, one base URL.\n */\nexport function createOpenAiCompatibleModel(options: OpenAiCompatibleOptions): Model {\n const call = retrying(options.fetch ?? fetch, { ...(options.isWait ? { isWait: options.isWait } : {}) });\n const provider = `openai-compatible:${options.baseUrl.replace(/\\/+$/, \"\")}`;\n const marking = options.cacheBreakpoint === \"cache_control\";\n return {\n id: `openai-compatible:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n let response: Response;\n try {\n response = await call(`${options.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${options.apiKey}`,\n ...options.headers,\n },\n body: JSON.stringify({\n model: options.model,\n messages: encodeConversation(request.messages, provider, marking ? breakpoints(request) : new Set()),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.maxOutputTokens !== undefined ? { max_tokens: request.maxOutputTokens } : {}),\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...encodeEffort(request.effort, options.effortParameter ?? \"reasoning_effort\"),\n ...(options.promptCacheKey ? { prompt_cache_key: options.promptCacheKey } : {}),\n stream: true,\n stream_options: { include_usage: true },\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n if (!response.ok) return err(await httpError(response, options.isWait));\n if (!response.body) return err({ code: \"provider\", message: \"No response body\", retryable: true });\n\n const text: string[] = [];\n const calls = new Map<number, { callId: string; name: string; arguments: string }>();\n let finish: ModelResponse[\"finishReason\"] = \"stop\";\n let usage: Usage = {};\n let model: string | undefined;\n const reasoningDetails: JsonValue[] = [];\n let sawReasoningDetails = false;\n const reasoning: string[] = [];\n const reasoningContent: string[] = [];\n\n // A stream that dies mid-body — cancelled, dropped, truncated — must come\n // back as a typed failure like any other. Without this the generator throws,\n // `run.result` rejects instead of resolving `cancelled`, no `run.finished`\n // is ever committed, and the activation stays open until its claim expires.\n try {\n for await (const event of sseLines(response.body)) {\n if (event === \"[DONE]\") break;\n let frame: ChatFrame;\n try { frame = JSON.parse(event) as ChatFrame; } catch { continue; }\n model ??= frame.model;\n if (frame.usage) usage = decodeUsage(frame.usage);\n\n const choice = frame.choices?.[0];\n if (!choice) continue;\n if (choice.finish_reason) finish = decodeFinish(choice.finish_reason);\n\n const content = choice.delta?.content;\n if (content) { text.push(content); yield { type: \"text.delta\", text: content }; }\n\n const reasoningDelta = choice.delta?.reasoning;\n const reasoningContentDelta = choice.delta?.reasoning_content;\n if (reasoningDelta !== undefined) reasoning.push(reasoningDelta);\n if (reasoningContentDelta !== undefined) reasoningContent.push(reasoningContentDelta);\n const visibleReasoning = reasoningDelta ?? reasoningContentDelta;\n if (visibleReasoning) yield { type: \"reasoning.delta\", text: visibleReasoning };\n if (choice.delta?.reasoning_details !== undefined) {\n sawReasoningDetails = true;\n appendReasoningDetails(reasoningDetails, choice.delta.reasoning_details);\n }\n\n for (const fragment of choice.delta?.tool_calls ?? []) {\n // Providers stream tool arguments in fragments, keyed by position;\n // only the first fragment carries the id and the name.\n const existing = calls.get(fragment.index) ?? {\n callId: fragment.id ?? `call_${fragment.index}`,\n name: fragment.function?.name ?? \"\",\n arguments: \"\",\n };\n if (fragment.id) existing.callId = fragment.id;\n if (fragment.function?.name) existing.name = fragment.function.name;\n if (fragment.function?.arguments) {\n existing.arguments += fragment.function.arguments;\n yield { type: \"tool-call.delta\", callId: existing.callId, arguments: fragment.function.arguments };\n }\n calls.set(fragment.index, existing);\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n const collected: ToolCall[] = [...calls.values()]\n .map((call) => ({ callId: call.callId, name: call.name, arguments: call.arguments || \"{}\" }));\n\n const state = reasoningState(reasoningDetails, sawReasoningDetails, reasoning, reasoningContent);\n return ok({\n message: { content: text.join(\"\"), ...(collected.length ? { calls: collected } : {}) },\n finishReason: collected.length && finish === \"stop\" ? \"tool-calls\" : finish,\n usage,\n ...(model ? { model } : {}),\n ...(state.length ? { providerState: { provider, items: state } } : {}),\n });\n },\n };\n}\n\n/**\n * OpenRouter is this wire with a fixed base URL, attribution headers, and two\n * facts of its own.\n *\n * It caches Claude only when asked. Every other model it serves reads a\n * repeated prefix from cache on its own; a Claude request without a\n * `cache_control` mark is read in full every turn, at full price. The mark\n * goes on the models that need it and on no other: whether the providers that\n * cache by themselves ignore a mark is not something its documentation says,\n * and a strict one could refuse the request.\n *\n * It answers 402 for two different things. One is an account with no credit,\n * which is a refusal. The other is the account's credit being reserved by its\n * own other requests still in flight, which clears when they finish — the\n * commonest failure an agent serving several sessions at once will see, and a\n * wait. The body's structured `error.metadata.reason` tells them apart.\n */\nexport function createOpenRouterModel(input: {\n apiKey: string; model: string; appUrl?: string; appName?: string; promptCacheKey?: string; fetch?: typeof fetch;\n}): Model {\n return createOpenAiCompatibleModel({\n apiKey: input.apiKey,\n baseUrl: \"https://openrouter.ai/api/v1\",\n model: input.model,\n effortParameter: \"reasoning\",\n cacheBreakpoint: /^~?anthropic\\//.test(input.model) ? \"cache_control\" : \"none\",\n isWait: inFlightBudgetExhausted,\n ...(input.promptCacheKey ? { promptCacheKey: input.promptCacheKey } : {}),\n headers: {\n ...(input.appUrl ? { \"http-referer\": input.appUrl } : {}),\n ...(input.appName ? { \"x-title\": input.appName } : {}),\n },\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n\nasync function inFlightBudgetExhausted(response: Response): Promise<boolean> {\n if (response.status !== 402) return false;\n const body = await response.clone().json().catch(() => undefined) as\n { error?: { metadata?: { reason?: unknown } } } | undefined;\n return body?.error?.metadata?.reason === \"in_flight_budget_exhausted\";\n}\n\nfunction encodeEffort(\n effort: ModelRequest[\"effort\"],\n parameter: \"reasoning_effort\" | \"reasoning\" | \"none\",\n): Record<string, unknown> {\n if (!effort || parameter === \"none\") return {};\n return parameter === \"reasoning\" ? { reasoning: { effort } } : { reasoning_effort: effort };\n}\n\n/**\n * Which messages carry a breakpoint: the same three places the Anthropic\n * adapter marks, for the same reasons it gives.\n *\n * The prefix ends where the caller says. When that is at or past the leading\n * run of system messages, the first and the last of them are marked — the last\n * makes a conversation's own prefix reusable across its turns, the first makes\n * the standing instructions every conversation shares reusable across\n * conversations. A boundary past the system run marks the message it ends on\n * as well. Three at most, inside a budget of four.\n */\nfunction breakpoints(request: ModelRequest): ReadonlySet<number> {\n const boundary = request.cacheAfter;\n if (boundary === undefined) return new Set();\n const lead = leadingSystem(request.messages);\n const marked = new Set<number>();\n if (lead > 0 && boundary >= lead) marked.add(0).add(lead - 1);\n if (boundary > lead && boundary <= request.messages.length) marked.add(boundary - 1);\n return marked;\n}\n\n/** How far the leading run of system messages reaches: the standing instructions and the run's context. */\nfunction leadingSystem(messages: readonly Message[]): number {\n let lead = 0;\n while (lead < messages.length && messages[lead]!.role === \"system\") lead += 1;\n return lead;\n}\n\nfunction encodeConversation(\n messages: readonly Message[], provider: string, marked: ReadonlySet<number>,\n): Record<string, unknown>[] {\n const out: Record<string, unknown>[] = [];\n let images: ContentPart[] = [];\n const flush = () => {\n if (images.length) out.push({ role: \"user\", content: encodeContent(images) });\n images = [];\n };\n const lead = leadingSystem(messages);\n messages.forEach((message, index) => {\n // The wire accepts only text in tool replies. Keep every reply in a parallel\n // batch adjacent before supplying its images as associated user content.\n if (message.role !== \"tool\") flush();\n const encoded = encodeMessage(message, provider);\n // A system message past the leading run is the turn's context, which the\n // projection places after the cache boundary so that the prefix before it\n // can be read back. This wire sends it as `user`, its text unchanged.\n // OpenRouter folds every `system` message into Gemini's one\n // `systemInstruction`, and Gemini's implicit cache treats that instruction\n // as immutable, so a request that ends in a `system` message reads nothing\n // from cache — 0 tokens of a 15,138-token prefix, whether repeated byte for\n // byte or with one line changed — where the same line as a trailing `user`\n // message reads 12,189. DeepSeek does the same, 0 against 15,104; GLM reads\n // 11,520 either way. In production that was Gemini 3.8 Flash falling from\n // a nine-tenths daily cache share to none, at full input price every turn.\n if (message.role === \"system\" && index >= lead) encoded[\"role\"] = \"user\";\n if (marked.has(index)) mark(encoded);\n out.push(encoded);\n if (message.role === \"tool\" && typeof message.content !== \"string\") {\n const media = message.content.filter((part) => part.type === \"image\");\n if (media.length) images.push({ type: \"text\", text: `Images from tool call ${message.callId}:` }, ...media);\n }\n });\n flush();\n return out;\n}\n\n/**\n * A breakpoint lands on a text part, so a bare string becomes one part to\n * carry it. A message with no text — an assistant turn that only called tools,\n * a user turn that is only an image — has nowhere to put one and gets none.\n */\nfunction mark(encoded: Record<string, unknown>): void {\n const content = encoded[\"content\"];\n if (typeof content === \"string\") {\n if (content) encoded[\"content\"] = [{ type: \"text\", text: content, cache_control: { type: \"ephemeral\" } }];\n return;\n }\n if (!Array.isArray(content)) return;\n const last = content.findLast((part: Record<string, unknown>) => part[\"type\"] === \"text\") as\n Record<string, unknown> | undefined;\n if (last) last[\"cache_control\"] = { type: \"ephemeral\" };\n}\n\nfunction encodeMessage(message: Message, provider: string): Record<string, unknown> {\n if (message.role === \"tool\") {\n return { role: \"tool\", tool_call_id: message.callId, content: textOf(message.content) };\n }\n if (message.role === \"assistant\") {\n return {\n role: \"assistant\",\n content: textOf(message.content) || null,\n ...decodeReasoningState(message, provider),\n ...(message.calls?.length\n ? {\n tool_calls: message.calls.map((call) => ({\n id: call.callId, type: \"function\",\n function: { name: call.name, arguments: call.arguments },\n })),\n }\n : {}),\n };\n }\n return { role: message.role, content: encodeContent(message.content) };\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown {\n if (typeof content === \"string\") return content;\n const parts: Record<string, unknown>[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") { parts.push({ type: \"text\", text: part.text }); continue; }\n if (part.type === \"image\") {\n const url = part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;\n parts.push({ type: \"image_url\", image_url: { url } });\n }\n // Files and opaque blocks have no place on this wire. Dropping them beats\n // stringifying them into something the model would read as prose.\n }\n const only = parts.length === 1 ? parts[0] : undefined;\n return only?.type === \"text\" ? only.text : parts;\n}\n\nfunction reasoningState(\n details: readonly JsonValue[],\n sawDetails: boolean,\n reasoning: readonly string[],\n reasoningContent: readonly string[],\n): JsonValue[] {\n const state: Record<string, JsonValue> = {};\n if (sawDetails) state[\"reasoning_details\"] = details;\n if (!sawDetails && reasoning.length) state[\"reasoning\"] = reasoning.join(\"\");\n if (!sawDetails && reasoningContent.length) state[\"reasoning_content\"] = reasoningContent.join(\"\");\n return Object.keys(state).length ? [state] : [];\n}\n\nfunction decodeReasoningState(message: Extract<Message, { role: \"assistant\" }>, provider: string) {\n if (message.providerState?.provider !== provider) return {};\n const state: Record<string, JsonValue> = {};\n for (const item of message.providerState.items) {\n const value = record(item);\n const details = value?.[\"reasoning_details\"];\n if (Array.isArray(details)) state[\"reasoning_details\"] = details;\n for (const field of [\"reasoning\", \"reasoning_content\"] as const) {\n if (typeof value?.[field] === \"string\") state[field] = value[field];\n }\n }\n return state;\n}\n\n/** Rebuild the complete blocks OpenRouter's chat stream fragments by type. */\nfunction appendReasoningDetails(target: JsonValue[], incoming: readonly JsonValue[]): void {\n for (const raw of incoming) {\n const detail = record(raw);\n if (!detail) {\n target.push(clone(raw));\n continue;\n }\n const field = detail?.[\"type\"] === \"reasoning.text\" ? \"text\"\n : detail?.[\"type\"] === \"reasoning.summary\" ? \"summary\"\n : undefined;\n const previous = record(target.at(-1));\n if (!field || !previous || previous[\"type\"] !== detail[\"type\"] || !compatible(previous, detail, field)) {\n target.push(clone(raw));\n continue;\n }\n\n const merged: Record<string, JsonValue> = { ...previous };\n for (const [key, value] of Object.entries(detail)) {\n if (key === field) continue;\n if (value !== null || merged[key] === undefined) merged[key] = value;\n }\n merged[field] = `${typeof previous[field] === \"string\" ? previous[field] : \"\"}${\n typeof detail[field] === \"string\" ? detail[field] : \"\"\n }`;\n target[target.length - 1] = merged;\n }\n}\n\nfunction compatible(\n left: Readonly<Record<string, JsonValue>>,\n right: Readonly<Record<string, JsonValue>>,\n payload: string,\n): boolean {\n const keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n for (const key of keys) {\n if (key === payload) continue;\n const a = left[key];\n const b = right[key];\n if (a === undefined || a === null || b === undefined || b === null) continue;\n if (JSON.stringify(a) !== JSON.stringify(b)) return false;\n }\n return true;\n}\n\nconst record = (value: JsonValue | undefined): Readonly<Record<string, JsonValue>> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Readonly<Record<string, JsonValue>>\n : undefined;\n\nconst clone = (value: JsonValue): JsonValue => JSON.parse(JSON.stringify(value)) as JsonValue;\n\nconst encodeTool = (tool: ToolSpec) => ({\n type: \"function\",\n function: { name: tool.name, description: tool.description, parameters: tool.parameters, strict: false },\n});\n\nconst decodeFinish = (reason: string): ModelResponse[\"finishReason\"] =>\n reason === \"tool_calls\" ? \"tool-calls\"\n : reason === \"length\" ? \"length\"\n : reason === \"content_filter\" ? \"refusal\"\n : \"stop\";\n\nconst decodeUsage = (usage: ChatUsage): Usage => ({\n // Carried, not computed. A router picks an upstream provider per request and\n // adds its own margin, so what it charged is a thing only it can say — and\n // the frame carrying it is the one this adapter already reads.\n ...(typeof usage.cost === \"number\" ? { costUsd: usage.cost } : {}),\n // `prompt_tokens` is the whole prompt, and both `cached_tokens` and\n // `cache_write_tokens` are counted inside it. `Usage` keeps the three input\n // counts disjoint, so the cached parts come out here rather than every\n // caller having to know which wire produced the number it is holding.\n ...(usage.prompt_tokens !== undefined\n ? {\n inputTokens: Math.max(\n usage.prompt_tokens\n - (usage.prompt_tokens_details?.cached_tokens ?? 0)\n - (usage.prompt_tokens_details?.cache_write_tokens ?? 0),\n 0,\n ),\n }\n : {}),\n ...(usage.completion_tokens !== undefined ? { outputTokens: usage.completion_tokens } : {}),\n ...(usage.prompt_tokens_details?.cached_tokens !== undefined\n ? { cacheReadTokens: usage.prompt_tokens_details.cached_tokens } : {}),\n ...(usage.prompt_tokens_details?.cache_write_tokens !== undefined\n ? { cacheWriteTokens: usage.prompt_tokens_details.cache_write_tokens } : {}),\n});\n\n/**\n * A refusal, or a wait the retries did not outlast. The second keeps a\n * retryable code: the provider never said the request was wrong, and a caller\n * with the time to try again later is told so.\n */\nasync function httpError(response: Response, isWait: RetryOptions[\"isWait\"]): Promise<ModelError> {\n const wait = isWaitStatus(response.status) || (await isWait?.(response) ?? false);\n const body = await response.text().catch(() => \"\");\n const code: ModelError[\"code\"] =\n response.status === 401 || response.status === 403 ? \"auth\"\n : response.status === 400 && /context|token/i.test(body) ? \"context-length\"\n : wait && (response.status === 429 || response.status === 402) ? \"rate-limit\"\n : wait ? \"provider\"\n : \"failed\";\n const said = errorBody(body);\n const errorType = said?.[\"type\"];\n const errorCode = said?.[\"code\"];\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: wait,\n status: response.status,\n ...(typeof errorType === \"string\" ? { errorType } : {}),\n ...(typeof errorCode === \"string\" ? { errorCode } : {}),\n };\n}\n\n/** The `error` object of a refusal's JSON body, when it has one; read whole, not the cut the message keeps. */\nfunction errorBody(body: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try { parsed = JSON.parse(body); } catch { return undefined; }\n const error = parsed !== null && typeof parsed === \"object\" ? (parsed as { error?: unknown }).error : undefined;\n return error !== null && typeof error === \"object\" && !Array.isArray(error) ? error as Record<string, unknown> : undefined;\n}\n\nfunction transportError(error: unknown, signal?: AbortSignal): ModelError {\n if (signal?.aborted) return { code: \"cancelled\", message: \"Generation cancelled\", retryable: false };\n return { code: \"provider\", message: error instanceof Error ? error.message : String(error), retryable: true };\n}\n\n/** Server-sent events, reassembled across chunk boundaries. */\nasync function* sseLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line.startsWith(\"data:\")) yield line.slice(5).trim();\n newline = buffer.indexOf(\"\\n\");\n }\n }\n}\n\ninterface ChatUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n /**\n * `cache_write_tokens` is OpenRouter's, reported when the model it routed to\n * wrote the marked prefix; plain OpenAI sends only `cached_tokens`.\n */\n prompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n /**\n * What this generation was charged. OpenRouter sets it on every response and\n * calls it credits, whose base currency is US dollars; plain OpenAI and the\n * self-hosted endpoints on this wire do not send it at all, so it is absent\n * rather than zero there.\n */\n cost?: number;\n}\ninterface ChatFrame {\n model?: string;\n usage?: ChatUsage;\n choices?: readonly {\n finish_reason?: string | null;\n delta?: {\n content?: string;\n reasoning?: string;\n reasoning_content?: string;\n reasoning_details?: readonly JsonValue[];\n tool_calls?: readonly { index: number; id?: string; function?: { name?: string; arguments?: string } }[];\n };\n }[];\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/model/adapters/openai-compatible/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAqB,MAAM,gBAAgB,CAAC;AA2C3E;;;GAGG;AACH,MAAM,UAAU,2BAA2B,CAAC,OAAgC;IAC1E,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE,EAAE,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CA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sB,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IACrG,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAChH,CAAC;AAED,+DAA+D;AAC/D,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAgC;IACvD,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,IAA4C,EAAE,CAAC;QACvE,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnC,OAAO,OAAO,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;YACnC,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContentPart, Message, Model, ModelDelta, ModelError, ModelRequest, ModelResponse, ToolCall, ToolSpec, Usage,\n} from \"../../model.js\";\nimport { err, ok, type Result } from \"../../../result.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { isWaitStatus, retrying, type RetryOptions } from \"../../retry.js\";\n\nexport interface OpenAiCompatibleOptions {\n apiKey: string;\n baseUrl: string;\n model: string;\n headers?: Readonly<Record<string, string>>;\n /**\n * How this endpoint spells reasoning effort. OpenAI takes `reasoning_effort`;\n * OpenRouter takes `reasoning: { effort }` and forwards it to whoever is\n * serving the model. Sending both is not compatibility — OpenAI rejects the\n * request outright — so the dialect is declared rather than guessed.\n */\n effortParameter?: \"reasoning_effort\" | \"reasoning\" | \"none\";\n /**\n * How this endpoint spells a cache breakpoint, where it has one. Most models\n * on this wire cache a repeated prefix by themselves and have no field for\n * it — plain OpenAI rejects one it does not know — so the default sends none.\n * OpenRouter takes Anthropic's `cache_control` on a text part and forwards\n * it to the models that cache nothing without one.\n */\n cacheBreakpoint?: \"cache_control\" | \"none\";\n /**\n * The conversation this model is serving, sent as `prompt_cache_key` on every\n * request. A provider that caches a prefix per backend routes requests that\n * share a key to the backend holding it; without one a growing conversation\n * lands on a different backend each turn and reads almost none of it back.\n * Meta's Muse Spark behind OpenRouter is the case measured: 3% of a\n * conversation's prefix read from cache without it, 91% with it. Set only\n * where the endpoint takes the field — plain OpenAI chat completions does\n * not — so the default sends none.\n */\n promptCacheKey?: string;\n /**\n * A refusal this endpoint means as a wait, beyond the statuses every HTTP\n * wire means so. Retried before the first delta like those, and reported as\n * a rate limit when the retries run out.\n */\n isWait?: RetryOptions[\"isWait\"];\n /** Injectable for tests; defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * The OpenAI chat-completions wire, which almost every provider now speaks —\n * OpenRouter, Together, Groq, vLLM, Ollama. One adapter, one base URL.\n */\nexport function createOpenAiCompatibleModel(options: OpenAiCompatibleOptions): Model {\n const call = retrying(options.fetch ?? fetch, { ...(options.isWait ? { isWait: options.isWait } : {}) });\n const provider = `openai-compatible:${options.baseUrl.replace(/\\/+$/, \"\")}`;\n const marking = options.cacheBreakpoint === \"cache_control\";\n return {\n id: `openai-compatible:${options.model}`,\n\n async *generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>> {\n let response: Response;\n try {\n response = await call(`${options.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${options.apiKey}`,\n ...options.headers,\n },\n body: JSON.stringify({\n model: options.model,\n messages: encodeConversation(request.messages, provider, marking ? breakpoints(request) : new Set()),\n ...(request.tools?.length ? { tools: request.tools.map(encodeTool) } : {}),\n ...(request.maxOutputTokens !== undefined ? { max_tokens: request.maxOutputTokens } : {}),\n ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),\n ...encodeEffort(request.effort, options.effortParameter ?? \"reasoning_effort\"),\n ...(options.promptCacheKey ? { prompt_cache_key: options.promptCacheKey } : {}),\n stream: true,\n stream_options: { include_usage: true },\n }),\n ...(request.signal ? { signal: request.signal } : {}),\n });\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n if (!response.ok) return err(await httpError(response, options.isWait));\n if (!response.body) return err({ code: \"provider\", message: \"No response body\", retryable: true });\n\n const text: string[] = [];\n const calls = new Map<number, { callId: string; name: string; arguments: string }>();\n let finish: ModelResponse[\"finishReason\"] = \"stop\";\n let usage: Usage = {};\n let model: string | undefined;\n const reasoningDetails: JsonValue[] = [];\n let sawReasoningDetails = false;\n const reasoning: string[] = [];\n const reasoningContent: string[] = [];\n\n // A stream that dies mid-body — cancelled, dropped, truncated — must come\n // back as a typed failure like any other. Without this the generator throws,\n // `run.result` rejects instead of resolving `cancelled`, no `run.finished`\n // is ever committed, and the activation stays open until its claim expires.\n try {\n for await (const event of sseLines(response.body)) {\n if (event === \"[DONE]\") break;\n let frame: ChatFrame;\n try { frame = JSON.parse(event) as ChatFrame; } catch { continue; }\n model ??= frame.model;\n if (frame.usage) usage = decodeUsage(frame.usage);\n\n const choice = frame.choices?.[0];\n if (!choice) continue;\n if (choice.finish_reason) finish = decodeFinish(choice.finish_reason);\n\n const content = choice.delta?.content;\n if (content) { text.push(content); yield { type: \"text.delta\", text: content }; }\n\n const reasoningDelta = choice.delta?.reasoning;\n const reasoningContentDelta = choice.delta?.reasoning_content;\n if (reasoningDelta !== undefined) reasoning.push(reasoningDelta);\n if (reasoningContentDelta !== undefined) reasoningContent.push(reasoningContentDelta);\n const visibleReasoning = reasoningDelta ?? reasoningContentDelta;\n if (visibleReasoning) yield { type: \"reasoning.delta\", text: visibleReasoning };\n if (choice.delta?.reasoning_details !== undefined) {\n sawReasoningDetails = true;\n appendReasoningDetails(reasoningDetails, choice.delta.reasoning_details);\n }\n\n for (const fragment of choice.delta?.tool_calls ?? []) {\n // Providers stream tool arguments in fragments, keyed by position;\n // only the first fragment carries the id and the name.\n const existing = calls.get(fragment.index) ?? {\n callId: fragment.id ?? `call_${fragment.index}`,\n name: fragment.function?.name ?? \"\",\n arguments: \"\",\n };\n if (fragment.id) existing.callId = fragment.id;\n if (fragment.function?.name) existing.name = fragment.function.name;\n if (fragment.function?.arguments) {\n existing.arguments += fragment.function.arguments;\n yield { type: \"tool-call.delta\", callId: existing.callId, arguments: fragment.function.arguments };\n }\n calls.set(fragment.index, existing);\n }\n }\n } catch (error) {\n return err(transportError(error, request.signal));\n }\n\n const collected: ToolCall[] = [...calls.values()]\n .map((call) => ({ callId: call.callId, name: call.name, arguments: call.arguments || \"{}\" }));\n\n const state = reasoningState(reasoningDetails, sawReasoningDetails, reasoning, reasoningContent);\n return ok({\n message: { content: text.join(\"\"), ...(collected.length ? { calls: collected } : {}) },\n finishReason: collected.length && finish === \"stop\" ? \"tool-calls\" : finish,\n usage,\n ...(model ? { model } : {}),\n ...(state.length ? { providerState: { provider, items: state } } : {}),\n });\n },\n };\n}\n\n/**\n * OpenRouter is this wire with a fixed base URL, attribution headers, and two\n * facts of its own.\n *\n * It caches Claude only when asked. Every other model it serves reads a\n * repeated prefix from cache on its own; a Claude request without a\n * `cache_control` mark is read in full every turn, at full price. The mark\n * goes on the models that need it and on no other: whether the providers that\n * cache by themselves ignore a mark is not something its documentation says,\n * and a strict one could refuse the request.\n *\n * It answers 402 for two different things. One is an account with no credit,\n * which is a refusal. The other is the account's credit being reserved by its\n * own other requests still in flight, which clears when they finish — the\n * commonest failure an agent serving several sessions at once will see, and a\n * wait. The body's structured `error.metadata.reason` tells them apart.\n */\nexport function createOpenRouterModel(input: {\n apiKey: string; model: string; appUrl?: string; appName?: string; promptCacheKey?: string; fetch?: typeof fetch;\n}): Model {\n return createOpenAiCompatibleModel({\n apiKey: input.apiKey,\n baseUrl: \"https://openrouter.ai/api/v1\",\n model: input.model,\n effortParameter: \"reasoning\",\n cacheBreakpoint: /^~?anthropic\\//.test(input.model) ? \"cache_control\" : \"none\",\n isWait: inFlightBudgetExhausted,\n ...(input.promptCacheKey ? { promptCacheKey: input.promptCacheKey } : {}),\n headers: {\n ...(input.appUrl ? { \"http-referer\": input.appUrl } : {}),\n ...(input.appName ? { \"x-title\": input.appName } : {}),\n },\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n\nasync function inFlightBudgetExhausted(response: Response): Promise<boolean> {\n if (response.status !== 402) return false;\n const body = await response.clone().json().catch(() => undefined) as\n { error?: { metadata?: { reason?: unknown } } } | undefined;\n return body?.error?.metadata?.reason === \"in_flight_budget_exhausted\";\n}\n\nfunction encodeEffort(\n effort: ModelRequest[\"effort\"],\n parameter: \"reasoning_effort\" | \"reasoning\" | \"none\",\n): Record<string, unknown> {\n if (!effort || parameter === \"none\") return {};\n return parameter === \"reasoning\" ? { reasoning: { effort } } : { reasoning_effort: effort };\n}\n\n/**\n * Which messages carry a breakpoint: the same three places the Anthropic\n * adapter marks, for the same reasons it gives.\n *\n * The prefix ends where the caller says. When that is at or past the leading\n * run of system messages, the first and the last of them are marked — the last\n * makes a conversation's own prefix reusable across its turns, the first makes\n * the standing instructions every conversation shares reusable across\n * conversations. A boundary past the system run marks the message it ends on\n * as well. Three at most, inside a budget of four.\n */\nfunction breakpoints(request: ModelRequest): ReadonlySet<number> {\n const boundary = request.cacheAfter;\n if (boundary === undefined) return new Set();\n const lead = leadingSystem(request.messages);\n const marked = new Set<number>();\n if (lead > 0 && boundary >= lead) marked.add(0).add(lead - 1);\n if (boundary > lead && boundary <= request.messages.length) marked.add(boundary - 1);\n return marked;\n}\n\n/** How far the leading run of system messages reaches: the standing instructions and the run's context. */\nfunction leadingSystem(messages: readonly Message[]): number {\n let lead = 0;\n while (lead < messages.length && messages[lead]!.role === \"system\") lead += 1;\n return lead;\n}\n\nfunction encodeConversation(\n messages: readonly Message[], provider: string, marked: ReadonlySet<number>,\n): Record<string, unknown>[] {\n const out: Record<string, unknown>[] = [];\n let images: ContentPart[] = [];\n const flush = () => {\n if (images.length) out.push({ role: \"user\", content: encodeContent(images) });\n images = [];\n };\n const lead = leadingSystem(messages);\n messages.forEach((message, index) => {\n // The wire accepts only text in tool replies. Keep every reply in a parallel\n // batch adjacent before supplying its images as associated user content.\n if (message.role !== \"tool\") flush();\n const encoded = encodeMessage(message, provider);\n // A system message past the leading run is the turn's context, which the\n // projection places after the cache boundary so that the prefix before it\n // can be read back. This wire sends it as `user`, its text unchanged.\n // OpenRouter folds every `system` message into Gemini's one\n // `systemInstruction`, and Gemini's implicit cache treats that instruction\n // as immutable, so a request that ends in a `system` message reads nothing\n // from cache — 0 tokens of a 15,138-token prefix, whether repeated byte for\n // byte or with one line changed — where the same line as a trailing `user`\n // message reads 12,189. DeepSeek does the same, 0 against 15,104; GLM reads\n // 11,520 either way. In production that was Gemini 3.8 Flash falling from\n // a nine-tenths daily cache share to none, at full input price every turn.\n if (message.role === \"system\" && index >= lead) encoded[\"role\"] = \"user\";\n if (marked.has(index)) mark(encoded);\n out.push(encoded);\n if (message.role === \"tool\" && typeof message.content !== \"string\") {\n const media = message.content.filter((part) => part.type === \"image\" || part.type === \"file\");\n if (media.length) images.push({ type: \"text\", text: `Attachments from tool call ${message.callId}:` }, ...media);\n }\n });\n flush();\n return out;\n}\n\n/**\n * A breakpoint lands on a text part, so a bare string becomes one part to\n * carry it. A message with no text — an assistant turn that only called tools,\n * a user turn that is only an image — has nowhere to put one and gets none.\n */\nfunction mark(encoded: Record<string, unknown>): void {\n const content = encoded[\"content\"];\n if (typeof content === \"string\") {\n if (content) encoded[\"content\"] = [{ type: \"text\", text: content, cache_control: { type: \"ephemeral\" } }];\n return;\n }\n if (!Array.isArray(content)) return;\n const last = content.findLast((part: Record<string, unknown>) => part[\"type\"] === \"text\") as\n Record<string, unknown> | undefined;\n if (last) last[\"cache_control\"] = { type: \"ephemeral\" };\n}\n\nfunction encodeMessage(message: Message, provider: string): Record<string, unknown> {\n if (message.role === \"tool\") {\n return { role: \"tool\", tool_call_id: message.callId, content: textOf(message.content) };\n }\n if (message.role === \"assistant\") {\n return {\n role: \"assistant\",\n content: textOf(message.content) || null,\n ...decodeReasoningState(message, provider),\n ...(message.calls?.length\n ? {\n tool_calls: message.calls.map((call) => ({\n id: call.callId, type: \"function\",\n function: { name: call.name, arguments: call.arguments },\n })),\n }\n : {}),\n };\n }\n return { role: message.role, content: encodeContent(message.content) };\n}\n\nfunction encodeContent(content: Message[\"content\"]): unknown {\n if (typeof content === \"string\") return content;\n const parts: Record<string, unknown>[] = [];\n for (const part of content as readonly ContentPart[]) {\n if (part.type === \"text\") { parts.push({ type: \"text\", text: part.text }); continue; }\n if (part.type === \"image\") {\n const url = part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;\n parts.push({ type: \"image_url\", image_url: { url } });\n }\n if (part.type === \"file\") {\n const file_data = part.source.kind === \"url\" ? part.source.url : `data:${part.mediaType};base64,${part.source.data}`;\n parts.push({ type: \"file\", file: { filename: part.name ?? \"attachment\", file_data } });\n }\n // Opaque blocks have no place on this wire. Dropping them beats\n // stringifying them into something the model would read as prose.\n }\n const only = parts.length === 1 ? parts[0] : undefined;\n return only?.type === \"text\" ? only.text : parts;\n}\n\nfunction reasoningState(\n details: readonly JsonValue[],\n sawDetails: boolean,\n reasoning: readonly string[],\n reasoningContent: readonly string[],\n): JsonValue[] {\n const state: Record<string, JsonValue> = {};\n if (sawDetails) state[\"reasoning_details\"] = details;\n if (!sawDetails && reasoning.length) state[\"reasoning\"] = reasoning.join(\"\");\n if (!sawDetails && reasoningContent.length) state[\"reasoning_content\"] = reasoningContent.join(\"\");\n return Object.keys(state).length ? [state] : [];\n}\n\nfunction decodeReasoningState(message: Extract<Message, { role: \"assistant\" }>, provider: string) {\n if (message.providerState?.provider !== provider) return {};\n const state: Record<string, JsonValue> = {};\n for (const item of message.providerState.items) {\n const value = record(item);\n const details = value?.[\"reasoning_details\"];\n if (Array.isArray(details)) state[\"reasoning_details\"] = details;\n for (const field of [\"reasoning\", \"reasoning_content\"] as const) {\n if (typeof value?.[field] === \"string\") state[field] = value[field];\n }\n }\n return state;\n}\n\n/** Rebuild the complete blocks OpenRouter's chat stream fragments by type. */\nfunction appendReasoningDetails(target: JsonValue[], incoming: readonly JsonValue[]): void {\n for (const raw of incoming) {\n const detail = record(raw);\n if (!detail) {\n target.push(clone(raw));\n continue;\n }\n const field = detail?.[\"type\"] === \"reasoning.text\" ? \"text\"\n : detail?.[\"type\"] === \"reasoning.summary\" ? \"summary\"\n : undefined;\n const previous = record(target.at(-1));\n if (!field || !previous || previous[\"type\"] !== detail[\"type\"] || !compatible(previous, detail, field)) {\n target.push(clone(raw));\n continue;\n }\n\n const merged: Record<string, JsonValue> = { ...previous };\n for (const [key, value] of Object.entries(detail)) {\n if (key === field) continue;\n if (value !== null || merged[key] === undefined) merged[key] = value;\n }\n merged[field] = `${typeof previous[field] === \"string\" ? previous[field] : \"\"}${\n typeof detail[field] === \"string\" ? detail[field] : \"\"\n }`;\n target[target.length - 1] = merged;\n }\n}\n\nfunction compatible(\n left: Readonly<Record<string, JsonValue>>,\n right: Readonly<Record<string, JsonValue>>,\n payload: string,\n): boolean {\n const keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n for (const key of keys) {\n if (key === payload) continue;\n const a = left[key];\n const b = right[key];\n if (a === undefined || a === null || b === undefined || b === null) continue;\n if (JSON.stringify(a) !== JSON.stringify(b)) return false;\n }\n return true;\n}\n\nconst record = (value: JsonValue | undefined): Readonly<Record<string, JsonValue>> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Readonly<Record<string, JsonValue>>\n : undefined;\n\nconst clone = (value: JsonValue): JsonValue => JSON.parse(JSON.stringify(value)) as JsonValue;\n\nconst encodeTool = (tool: ToolSpec) => ({\n type: \"function\",\n function: { name: tool.name, description: tool.description, parameters: tool.parameters, strict: false },\n});\n\nconst decodeFinish = (reason: string): ModelResponse[\"finishReason\"] =>\n reason === \"tool_calls\" ? \"tool-calls\"\n : reason === \"length\" ? \"length\"\n : reason === \"content_filter\" ? \"refusal\"\n : \"stop\";\n\nconst decodeUsage = (usage: ChatUsage): Usage => ({\n // Carried, not computed. A router picks an upstream provider per request and\n // adds its own margin, so what it charged is a thing only it can say — and\n // the frame carrying it is the one this adapter already reads.\n ...(typeof usage.cost === \"number\" ? { costUsd: usage.cost } : {}),\n // `prompt_tokens` is the whole prompt, and both `cached_tokens` and\n // `cache_write_tokens` are counted inside it. `Usage` keeps the three input\n // counts disjoint, so the cached parts come out here rather than every\n // caller having to know which wire produced the number it is holding.\n ...(usage.prompt_tokens !== undefined\n ? {\n inputTokens: Math.max(\n usage.prompt_tokens\n - (usage.prompt_tokens_details?.cached_tokens ?? 0)\n - (usage.prompt_tokens_details?.cache_write_tokens ?? 0),\n 0,\n ),\n }\n : {}),\n ...(usage.completion_tokens !== undefined ? { outputTokens: usage.completion_tokens } : {}),\n ...(usage.prompt_tokens_details?.cached_tokens !== undefined\n ? { cacheReadTokens: usage.prompt_tokens_details.cached_tokens } : {}),\n ...(usage.prompt_tokens_details?.cache_write_tokens !== undefined\n ? { cacheWriteTokens: usage.prompt_tokens_details.cache_write_tokens } : {}),\n});\n\n/**\n * A refusal, or a wait the retries did not outlast. The second keeps a\n * retryable code: the provider never said the request was wrong, and a caller\n * with the time to try again later is told so.\n */\nasync function httpError(response: Response, isWait: RetryOptions[\"isWait\"]): Promise<ModelError> {\n const wait = isWaitStatus(response.status) || (await isWait?.(response) ?? false);\n const body = await response.text().catch(() => \"\");\n const code: ModelError[\"code\"] =\n response.status === 401 || response.status === 403 ? \"auth\"\n : response.status === 400 && /context|token/i.test(body) ? \"context-length\"\n : wait && (response.status === 429 || response.status === 402) ? \"rate-limit\"\n : wait ? \"provider\"\n : \"failed\";\n const said = errorBody(body);\n const errorType = said?.[\"type\"];\n const errorCode = said?.[\"code\"];\n return {\n code,\n message: `${response.status} ${response.statusText}${body ? `: ${body.slice(0, 400)}` : \"\"}`,\n retryable: wait,\n status: response.status,\n ...(typeof errorType === \"string\" ? { errorType } : {}),\n ...(typeof errorCode === \"string\" ? { errorCode } : {}),\n };\n}\n\n/** The `error` object of a refusal's JSON body, when it has one; read whole, not the cut the message keeps. */\nfunction errorBody(body: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try { parsed = JSON.parse(body); } catch { return undefined; }\n const error = parsed !== null && typeof parsed === \"object\" ? (parsed as { error?: unknown }).error : undefined;\n return error !== null && typeof error === \"object\" && !Array.isArray(error) ? error as Record<string, unknown> : undefined;\n}\n\nfunction transportError(error: unknown, signal?: AbortSignal): ModelError {\n if (signal?.aborted) return { code: \"cancelled\", message: \"Generation cancelled\", retryable: false };\n return { code: \"provider\", message: error instanceof Error ? error.message : String(error), retryable: true };\n}\n\n/** Server-sent events, reassembled across chunk boundaries. */\nasync function* sseLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line.startsWith(\"data:\")) yield line.slice(5).trim();\n newline = buffer.indexOf(\"\\n\");\n }\n }\n}\n\ninterface ChatUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n /**\n * `cache_write_tokens` is OpenRouter's, reported when the model it routed to\n * wrote the marked prefix; plain OpenAI sends only `cached_tokens`.\n */\n prompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };\n /**\n * What this generation was charged. OpenRouter sets it on every response and\n * calls it credits, whose base currency is US dollars; plain OpenAI and the\n * self-hosted endpoints on this wire do not send it at all, so it is absent\n * rather than zero there.\n */\n cost?: number;\n}\ninterface ChatFrame {\n model?: string;\n usage?: ChatUsage;\n choices?: readonly {\n finish_reason?: string | null;\n delta?: {\n content?: string;\n reasoning?: string;\n reasoning_content?: string;\n reasoning_details?: readonly JsonValue[];\n tool_calls?: readonly { index: number; id?: string; function?: { name?: string; arguments?: string } }[];\n };\n }[];\n}\n"]}
@@ -15,6 +15,8 @@ export interface OpenAiResponsesConnection {
15
15
  export interface OpenAiResponsesOptions {
16
16
  apiKey: string;
17
17
  model: string;
18
+ /** OpenAI's processing tier for this model's requests; absent leaves it to the project's default. */
19
+ serviceTier?: "auto" | "default" | "flex" | "fast" | "priority" | "ultrafast";
18
20
  baseURL?: string;
19
21
  headers?: Readonly<Record<string, string>>;
20
22
  /** Declare function tools with OpenAI's asynchronous execution extension. */
@@ -221,7 +221,7 @@ export function createOpenAiResponsesModel(options) {
221
221
  id: `${provider}:${options.model}`,
222
222
  ...(options.asyncTools ? { asyncTools: true } : {}),
223
223
  generate(request) {
224
- return generation(lane, options.model, request, options.steering === true);
224
+ return generation(lane, options.model, request, options.steering === true, options.serviceTier);
225
225
  },
226
226
  close() {
227
227
  for (const openHub of [...hubs])
@@ -230,7 +230,7 @@ export function createOpenAiResponsesModel(options) {
230
230
  },
231
231
  };
232
232
  }
233
- function generation(connect, configuredModel, request, steering) {
233
+ function generation(connect, configuredModel, request, steering, serviceTier) {
234
234
  let connection;
235
235
  let activeResponseId;
236
236
  let ended = false;
@@ -267,7 +267,7 @@ function generation(connect, configuredModel, request, steering) {
267
267
  let refused = false;
268
268
  let terminal = false;
269
269
  try {
270
- connection.send(encodeRequest(configuredModel, request));
270
+ connection.send(encodeRequest(configuredModel, request, serviceTier));
271
271
  for await (const envelope of connection) {
272
272
  if (envelope.type === "error") {
273
273
  rejectSteers(steers, providerError(envelope.error));
@@ -515,10 +515,11 @@ function rejectSteers(steers, error) {
515
515
  for (const steer of steers)
516
516
  steer.reject(error);
517
517
  }
518
- function encodeRequest(model, request) {
518
+ function encodeRequest(model, request, serviceTier) {
519
519
  return {
520
520
  type: "response.create",
521
521
  model,
522
+ ...(serviceTier ? { service_tier: serviceTier } : {}),
522
523
  store: false,
523
524
  include: ["reasoning.encrypted_content"],
524
525
  input: encodeMessages(request.messages),