@visual-z/xeno 0.1.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.
Files changed (180) hide show
  1. package/README.md +498 -0
  2. package/docs/install.md +130 -0
  3. package/package.json +43 -0
  4. package/src/apps/approve.ts +49 -0
  5. package/src/apps/cli.ts +37 -0
  6. package/src/apps/commands.ts +226 -0
  7. package/src/apps/completions.ts +28 -0
  8. package/src/apps/input.ts +297 -0
  9. package/src/apps/render.ts +207 -0
  10. package/src/apps/shell.ts +2353 -0
  11. package/src/apps/startup.ts +1302 -0
  12. package/src/core/benchmark.ts +195 -0
  13. package/src/core/boundary.ts +174 -0
  14. package/src/core/churn.ts +59 -0
  15. package/src/core/completion-review.ts +66 -0
  16. package/src/core/context-policy.ts +60 -0
  17. package/src/core/context-window.ts +54 -0
  18. package/src/core/continuation.ts +114 -0
  19. package/src/core/cycle.ts +17 -0
  20. package/src/core/data-query.ts +201 -0
  21. package/src/core/deadline.ts +39 -0
  22. package/src/core/derive.ts +489 -0
  23. package/src/core/edit-plan.ts +200 -0
  24. package/src/core/environment.ts +29 -0
  25. package/src/core/event-validation.ts +99 -0
  26. package/src/core/events.ts +486 -0
  27. package/src/core/evidence-links.ts +71 -0
  28. package/src/core/evidence.ts +89 -0
  29. package/src/core/execution.ts +12 -0
  30. package/src/core/exhaustive.ts +18 -0
  31. package/src/core/experiment.ts +40 -0
  32. package/src/core/export.ts +169 -0
  33. package/src/core/file-references.ts +35 -0
  34. package/src/core/frontmatter.ts +213 -0
  35. package/src/core/handoff.ts +397 -0
  36. package/src/core/harness-comparison.ts +90 -0
  37. package/src/core/history-query.ts +103 -0
  38. package/src/core/history.ts +100 -0
  39. package/src/core/json-event.ts +135 -0
  40. package/src/core/json-pointer.ts +46 -0
  41. package/src/core/keymap.ts +241 -0
  42. package/src/core/observation-view.ts +87 -0
  43. package/src/core/outcome.ts +45 -0
  44. package/src/core/overflow.ts +59 -0
  45. package/src/core/permissions.ts +182 -0
  46. package/src/core/policy-evaluation.ts +55 -0
  47. package/src/core/progress.ts +101 -0
  48. package/src/core/project.ts +372 -0
  49. package/src/core/prompts.ts +83 -0
  50. package/src/core/queue.ts +60 -0
  51. package/src/core/read-bounds.ts +15 -0
  52. package/src/core/recall-analysis.ts +90 -0
  53. package/src/core/recall-trial.ts +153 -0
  54. package/src/core/response-recovery.ts +46 -0
  55. package/src/core/scheduling.ts +8 -0
  56. package/src/core/settings.ts +174 -0
  57. package/src/core/skills.ts +121 -0
  58. package/src/core/stall.ts +48 -0
  59. package/src/core/text-normalize.ts +81 -0
  60. package/src/core/theme.ts +179 -0
  61. package/src/core/tokens.ts +149 -0
  62. package/src/core/tool-contract.ts +102 -0
  63. package/src/core/tool-input.ts +38 -0
  64. package/src/core/transcript.ts +60 -0
  65. package/src/core/window-trial.ts +65 -0
  66. package/src/core/work-state.ts +103 -0
  67. package/src/core/yaml.ts +282 -0
  68. package/src/index.ts +10 -0
  69. package/src/runtime/auth.ts +255 -0
  70. package/src/runtime/benchmark.ts +187 -0
  71. package/src/runtime/catalog.ts +365 -0
  72. package/src/runtime/evidence-notes.ts +33 -0
  73. package/src/runtime/exec-sessions.ts +214 -0
  74. package/src/runtime/execution-control.ts +39 -0
  75. package/src/runtime/harness-comparison.ts +356 -0
  76. package/src/runtime/history-tools.ts +108 -0
  77. package/src/runtime/loop.ts +1983 -0
  78. package/src/runtime/model.ts +614 -0
  79. package/src/runtime/models-fetch.ts +155 -0
  80. package/src/runtime/oauth-device.ts +86 -0
  81. package/src/runtime/oauth.ts +759 -0
  82. package/src/runtime/openai-responses.ts +286 -0
  83. package/src/runtime/openai.ts +675 -0
  84. package/src/runtime/provider.ts +498 -0
  85. package/src/runtime/recall-trial.ts +226 -0
  86. package/src/runtime/resume.ts +66 -0
  87. package/src/runtime/retry.ts +297 -0
  88. package/src/runtime/tools.ts +1193 -0
  89. package/src/runtime/usage.ts +225 -0
  90. package/src/runtime/window-trial.ts +140 -0
  91. package/src/runtime/working-notes.ts +30 -0
  92. package/src/store/atomic.ts +31 -0
  93. package/src/store/auth-store.ts +50 -0
  94. package/src/store/blobs.ts +142 -0
  95. package/src/store/command.ts +75 -0
  96. package/src/store/config.ts +69 -0
  97. package/src/store/context-files.ts +356 -0
  98. package/src/store/file-index.ts +81 -0
  99. package/src/store/git-branch.ts +35 -0
  100. package/src/store/history-search.ts +19 -0
  101. package/src/store/log.ts +642 -0
  102. package/src/store/models.ts +41 -0
  103. package/src/store/observations.ts +181 -0
  104. package/src/store/query-source.ts +44 -0
  105. package/src/store/recovery.ts +39 -0
  106. package/src/store/replay.ts +63 -0
  107. package/src/store/resources.ts +361 -0
  108. package/src/store/restore.ts +302 -0
  109. package/src/store/search.ts +644 -0
  110. package/src/store/serial.ts +13 -0
  111. package/src/store/sessions.ts +463 -0
  112. package/src/store/trust.ts +69 -0
  113. package/src/store/workspace.ts +256 -0
  114. package/src/store/worktree.ts +233 -0
  115. package/src/tui/ansi.ts +67 -0
  116. package/src/tui/autocomplete.ts +29 -0
  117. package/src/tui/complete.ts +87 -0
  118. package/src/tui/diff.ts +160 -0
  119. package/src/tui/editor.ts +893 -0
  120. package/src/tui/exhaustive.ts +14 -0
  121. package/src/tui/fuzzy.ts +75 -0
  122. package/src/tui/host.ts +223 -0
  123. package/src/tui/input.ts +69 -0
  124. package/src/tui/keys.ts +378 -0
  125. package/src/tui/markdown.ts +17 -0
  126. package/src/tui/render.ts +153 -0
  127. package/src/tui/select.ts +240 -0
  128. package/src/tui/settings.ts +40 -0
  129. package/src/tui/statusline.ts +162 -0
  130. package/src/tui/style.ts +205 -0
  131. package/src/tui/terminal.ts +30 -0
  132. package/src/tui/text.ts +52 -0
  133. package/src/tui/toolview.ts +386 -0
  134. package/src/tui/transcript.ts +71 -0
  135. package/src/tui/tree.ts +405 -0
  136. package/src/tui/width.ts +567 -0
  137. package/src/vendor/pi-tui/LICENSE.upstream +21 -0
  138. package/src/vendor/pi-tui/VENDOR.md +23 -0
  139. package/src/vendor/pi-tui/alt-screen-search.ts +327 -0
  140. package/src/vendor/pi-tui/autocomplete.ts +835 -0
  141. package/src/vendor/pi-tui/components/alt-screen-flash.ts +51 -0
  142. package/src/vendor/pi-tui/components/box.ts +167 -0
  143. package/src/vendor/pi-tui/components/cancellable-loader.ts +40 -0
  144. package/src/vendor/pi-tui/components/editor.ts +2470 -0
  145. package/src/vendor/pi-tui/components/h-stack.ts +44 -0
  146. package/src/vendor/pi-tui/components/image.ts +127 -0
  147. package/src/vendor/pi-tui/components/input.ts +494 -0
  148. package/src/vendor/pi-tui/components/loader.ts +101 -0
  149. package/src/vendor/pi-tui/components/markdown.ts +1015 -0
  150. package/src/vendor/pi-tui/components/mouse-region.ts +33 -0
  151. package/src/vendor/pi-tui/components/scroll-view.ts +224 -0
  152. package/src/vendor/pi-tui/components/select-list.ts +273 -0
  153. package/src/vendor/pi-tui/components/settings-list.ts +328 -0
  154. package/src/vendor/pi-tui/components/spacer.ts +28 -0
  155. package/src/vendor/pi-tui/components/stack.ts +154 -0
  156. package/src/vendor/pi-tui/components/text.ts +107 -0
  157. package/src/vendor/pi-tui/components/truncated-text.ts +65 -0
  158. package/src/vendor/pi-tui/components/v-stack.ts +33 -0
  159. package/src/vendor/pi-tui/editor-component.ts +74 -0
  160. package/src/vendor/pi-tui/fuzzy.ts +138 -0
  161. package/src/vendor/pi-tui/index.ts +156 -0
  162. package/src/vendor/pi-tui/keybindings.ts +320 -0
  163. package/src/vendor/pi-tui/keys.ts +1401 -0
  164. package/src/vendor/pi-tui/kill-ring.ts +46 -0
  165. package/src/vendor/pi-tui/latex.ts +1506 -0
  166. package/src/vendor/pi-tui/layout-node.ts +51 -0
  167. package/src/vendor/pi-tui/layout.ts +449 -0
  168. package/src/vendor/pi-tui/native-modifiers.ts +13 -0
  169. package/src/vendor/pi-tui/native-module-path.ts +31 -0
  170. package/src/vendor/pi-tui/native-platform.ts +63 -0
  171. package/src/vendor/pi-tui/stdin-buffer.ts +444 -0
  172. package/src/vendor/pi-tui/terminal-colors.ts +73 -0
  173. package/src/vendor/pi-tui/terminal-image.ts +696 -0
  174. package/src/vendor/pi-tui/terminal.ts +547 -0
  175. package/src/vendor/pi-tui/tui-alt-screen.ts +1742 -0
  176. package/src/vendor/pi-tui/tui-main-screen.ts +655 -0
  177. package/src/vendor/pi-tui/tui.ts +1456 -0
  178. package/src/vendor/pi-tui/undo-stack.ts +28 -0
  179. package/src/vendor/pi-tui/utils.ts +1345 -0
  180. package/src/vendor/pi-tui/word-navigation.ts +117 -0
@@ -0,0 +1,675 @@
1
+ /**
2
+ * The OpenAI Chat Completions adapter.
3
+ *
4
+ * "OpenAI-compatible" names a family of dialects rather than a protocol. The
5
+ * differences are small, undocumented in aggregate, and each one is a 400 or a
6
+ * silently wrong number: which field caps the output, whether the system
7
+ * prompt may use the `developer` role, where reasoning lives on the way out
8
+ * and on the way back, which usage field carries a cache hit. So the accent is
9
+ * carried as data on the model (`Compat`) and this file only reads it. The
10
+ * alternative -- branching on the provider's name -- ends as a chain of `||`
11
+ * that nobody can safely extend, which is where every adapter that started
12
+ * that way has arrived.
13
+ *
14
+ * Two of the three functions here are pure. `buildRequest` turns the core's
15
+ * provider-neutral messages into a request body and `parseResponse` turns a
16
+ * response body back into a turn; only `OpenAICompletionsProvider.send` is
17
+ * allowed to touch the network. That split is what lets the expensive mistakes
18
+ * -- a missing field that costs a 400, a cache hit counted as fresh input --
19
+ * be caught offline, without a key.
20
+ */
21
+
22
+ import type { Message, ContentBlock, FrozenPrefix } from "../core/project.ts";
23
+ import type { AssistantBlock } from "../core/events.ts";
24
+ import { assertNever } from "../core/exhaustive.ts";
25
+ import type { Provider, ProviderConfig, Turn, ToolSchema, OnDelta } from "./provider.ts";
26
+ import { DEFAULT_COMPAT, type Compat, type Effort, type ModelSpec } from "./model.ts";
27
+ import { withRetry, DEFAULT_RETRY, type RetryPolicy } from "./retry.ts";
28
+
29
+ /** One message as Chat Completions wants it. */
30
+ export interface WireMessage {
31
+ role: "system" | "developer" | "user" | "assistant" | "tool";
32
+ content?: string | null;
33
+ reasoning_content?: string;
34
+ /** OpenRouter's structured reasoning, replayed as received. */
35
+ reasoning_details?: unknown;
36
+ tool_calls?: ({
37
+ id: string;
38
+ type: "function";
39
+ function: { name: string; arguments: string };
40
+ } & Record<string, unknown>)[];
41
+ tool_call_id?: string;
42
+ }
43
+
44
+ export interface WireRequest {
45
+ model: string;
46
+ messages: WireMessage[];
47
+ max_tokens?: number;
48
+ max_completion_tokens?: number;
49
+ tools?: unknown[];
50
+ thinking?: { type: "enabled" | "disabled" };
51
+ reasoning_effort?: string;
52
+ }
53
+
54
+ /**
55
+ * The shape this adapter puts in a thinking block's opaque `raw`.
56
+ *
57
+ * `raw` is the core's escape hatch for "whatever this provider needs to see
58
+ * again, unchanged" -- the Anthropic adapter parks a signed block there. Here
59
+ * it is the reasoning text, because that is what has to go back on the wire.
60
+ * Each adapter recognises only its own, which is exactly why the field is
61
+ * typed `unknown` in the core.
62
+ */
63
+ interface ReasoningRaw {
64
+ reasoning_content: string;
65
+ /** OpenRouter: structured, sometimes encrypted, reasoning it wants back verbatim. */
66
+ reasoning_details?: unknown;
67
+ }
68
+
69
+ function reasoningDetailsOf(raw: unknown): unknown {
70
+ if (typeof raw !== "object" || raw === null) return undefined;
71
+ return (raw as Partial<ReasoningRaw>).reasoning_details;
72
+ }
73
+
74
+ /**
75
+ * A tool call's fields beyond the ones this adapter reads.
76
+ *
77
+ * Gemini's OpenAI-compatible endpoint puts a thought signature under
78
+ * `extra_content` and rejects the next request if it is not echoed back.
79
+ * Rather than learn each provider's extension, keep whatever else arrived and
80
+ * send it back unchanged -- the same contract as a thinking block's raw.
81
+ */
82
+ function extraFields(call: Record<string, unknown>): Record<string, unknown> | undefined {
83
+ const extra: Record<string, unknown> = {};
84
+ for (const [key, value] of Object.entries(call)) {
85
+ if (key !== "id" && key !== "type" && key !== "function" && key !== "index") extra[key] = value;
86
+ }
87
+ return Object.keys(extra).length > 0 ? extra : undefined;
88
+ }
89
+
90
+ function reasoningOf(raw: unknown): string | null {
91
+ if (typeof raw !== "object" || raw === null) return null;
92
+ const value = (raw as Partial<ReasoningRaw>).reasoning_content;
93
+ return typeof value === "string" ? value : null;
94
+ }
95
+
96
+ /**
97
+ * Chat Completions takes the whole tool list flat under `function`, where the
98
+ * Anthropic shape nests the schema under `input_schema`. `strict` is omitted
99
+ * rather than set false: providers in this family reject unknown fields, and
100
+ * the ones that support strict mode are not the ones we talk to.
101
+ */
102
+ function toWireTools(tools: readonly unknown[]): unknown[] {
103
+ return tools.map((t) => {
104
+ const tool = t as ToolSchema;
105
+ return {
106
+ type: "function",
107
+ function: {
108
+ name: tool.name,
109
+ description: tool.description,
110
+ parameters: tool.input_schema,
111
+ },
112
+ };
113
+ });
114
+ }
115
+
116
+ /**
117
+ * Flattens one assistant turn's blocks into the single string + tool_calls
118
+ * pair this API expects.
119
+ *
120
+ * The content must be a plain string and not an array of `{type:"text"}`
121
+ * blocks. The array form is legal OpenAI but some models in this family mirror
122
+ * the structure literally into their own output, producing nested
123
+ * `[{'type':'text','text':'[{...}]'}]` that then poisons every later turn.
124
+ */
125
+ function assistantMessage(content: readonly ContentBlock[], compat: Compat, reasoning: boolean): WireMessage {
126
+ const text: string[] = [];
127
+ const thinking: string[] = [];
128
+ const details: unknown[] = [];
129
+ const toolCalls: NonNullable<WireMessage["tool_calls"]> = [];
130
+
131
+ for (const b of content) {
132
+ switch (b.type) {
133
+ case "text":
134
+ text.push(b.text);
135
+ break;
136
+ case "thinking": {
137
+ const r = reasoningOf(b.raw);
138
+ if (r !== null && r.length > 0) thinking.push(r);
139
+ const d = reasoningDetailsOf(b.raw);
140
+ if (Array.isArray(d)) details.push(...d);
141
+ else if (d !== undefined) details.push(d);
142
+ break;
143
+ }
144
+ case "tool_use":
145
+ toolCalls.push({
146
+ ...(typeof b.wire === "object" && b.wire !== null ? b.wire as Record<string, unknown> : {}),
147
+ id: b.id,
148
+ type: "function",
149
+ function: { name: b.name, arguments: JSON.stringify(b.input) },
150
+ });
151
+ break;
152
+ case "tool_result":
153
+ // A tool_result inside an assistant turn is not a shape the projection
154
+ // produces. Ignored rather than thrown: the request stays valid, and
155
+ // the pairing checks that would catch it live in the core.
156
+ break;
157
+ default:
158
+ return assertNever(b, "assistantMessage");
159
+ }
160
+ }
161
+
162
+ const message: WireMessage = { role: "assistant" };
163
+ if (text.length > 0) message.content = text.join("");
164
+ if (toolCalls.length > 0) message.tool_calls = toolCalls;
165
+
166
+ // The documented rule, and the reason this adapter exists in this shape:
167
+ // once `tools` is in the request, DeepSeek requires reasoning_content on
168
+ // EVERY assistant message in the history -- including turns that did no
169
+ // thinking and made no tool call -- and returns 400 without it. An empty
170
+ // string is the documented stand-in, not a guess.
171
+ if (compat.requiresReasoningContentOnAssistantMessages && reasoning) {
172
+ message.reasoning_content = thinking.join("\n");
173
+ } else if (thinking.length > 0) {
174
+ message.reasoning_content = thinking.join("\n");
175
+ }
176
+ if (details.length > 0) message.reasoning_details = details;
177
+
178
+ return message;
179
+ }
180
+
181
+ /**
182
+ * Turns one projected user message into wire messages.
183
+ *
184
+ * The projection deliberately batches every tool result for a turn into a
185
+ * single user message, because splitting them teaches the model to stop
186
+ * issuing parallel calls. This API wants the opposite: one `tool` message per
187
+ * result, keyed by call id. So the split happens here, at the wire boundary,
188
+ * and the projection's property is left intact.
189
+ */
190
+ function userMessages(content: readonly ContentBlock[]): WireMessage[] {
191
+ const out: WireMessage[] = [];
192
+ const text: string[] = [];
193
+
194
+ for (const b of content) {
195
+ switch (b.type) {
196
+ case "tool_result":
197
+ out.push({
198
+ role: "tool",
199
+ tool_call_id: b.tool_use_id,
200
+ content: b.content,
201
+ });
202
+ break;
203
+ case "text":
204
+ text.push(b.text);
205
+ break;
206
+ case "thinking":
207
+ case "tool_use":
208
+ // Neither appears in a user turn in any projection this harness
209
+ // produces; dropping them keeps the request valid.
210
+ break;
211
+ default:
212
+ return assertNever(b, "userMessages");
213
+ }
214
+ }
215
+
216
+ if (text.length > 0) out.push({ role: "user", content: text.join("\n") });
217
+ return out;
218
+ }
219
+
220
+ /** Maps our effort onto what this model accepts; `null` in the map means "send nothing". */
221
+ function wireEffort(spec: ModelSpec, effort: Effort): string | null {
222
+ const mapped = spec.thinkingLevelMap?.[effort];
223
+ if (mapped === null) return null;
224
+ return mapped ?? effort;
225
+ }
226
+
227
+ export function buildRequest(
228
+ config: ProviderConfig,
229
+ frozen: FrozenPrefix,
230
+ messages: readonly Message[],
231
+ ): WireRequest {
232
+ const spec = config.spec;
233
+ const compat = spec.compat ?? DEFAULT_COMPAT;
234
+
235
+ const wire: WireMessage[] = [
236
+ // The system prompt leads, which is all the prefix management this
237
+ // provider needs: its cache is automatic and keyed on the literal prefix,
238
+ // so the core's append-only property is what produces the hits. There is
239
+ // no breakpoint to place and none to get wrong.
240
+ {
241
+ role: compat.supportsDeveloperRole && spec.reasoning ? "developer" : "system",
242
+ content: frozen.system,
243
+ },
244
+ ];
245
+
246
+ for (const m of messages) {
247
+ if (m.role === "assistant") {
248
+ const built = assistantMessage(m.content, compat, spec.reasoning);
249
+ // Some providers reject an assistant message with neither content nor
250
+ // tool calls, which is what an aborted turn leaves behind.
251
+ if (built.content !== undefined || built.tool_calls !== undefined) wire.push(built);
252
+ } else {
253
+ wire.push(...userMessages(m.content));
254
+ }
255
+ }
256
+
257
+ const request: WireRequest = { model: spec.id, messages: wire };
258
+
259
+ if (compat.maxTokensField === "max_tokens") request.max_tokens = config.maxTokens;
260
+ else request.max_completion_tokens = config.maxTokens;
261
+
262
+ if (frozen.tools.length > 0) request.tools = toWireTools(frozen.tools);
263
+
264
+ if (spec.reasoning) {
265
+ if (compat.thinkingFormat === "deepseek") request.thinking = { type: "enabled" };
266
+ if (compat.supportsReasoningEffort) {
267
+ const effort = wireEffort(spec, config.effort);
268
+ if (effort !== null) request.reasoning_effort = effort;
269
+ }
270
+ }
271
+
272
+ return request;
273
+ }
274
+
275
+ /** Only the fields we read, so a provider adding more cannot break parsing. */
276
+ interface WireResponse {
277
+ choices?: {
278
+ message?: {
279
+ content?: string | null;
280
+ reasoning_content?: string | null;
281
+ /** OpenRouter's name for the reasoning text. */
282
+ reasoning?: string | null;
283
+ reasoning_details?: unknown;
284
+ tool_calls?: ({
285
+ id?: string;
286
+ function?: { name?: string; arguments?: string };
287
+ } & Record<string, unknown>)[];
288
+ };
289
+ finish_reason?: string | null;
290
+ }[];
291
+ usage?: {
292
+ prompt_tokens?: number;
293
+ completion_tokens?: number;
294
+ prompt_cache_hit_tokens?: number;
295
+ prompt_tokens_details?: { cached_tokens?: number };
296
+ };
297
+ error?: { message?: string };
298
+ }
299
+
300
+ /**
301
+ * Decodes tool arguments, which arrive as a JSON string.
302
+ *
303
+ * A model can emit malformed JSON there. The raw string is kept rather than
304
+ * dropped so the tool layer reports a bad argument, instead of the call
305
+ * vanishing and the turn ending with an unanswered tool_use.
306
+ */
307
+ function decodeArguments(raw: string | undefined): unknown {
308
+ if (raw === undefined || raw.length === 0) return {};
309
+ try {
310
+ return JSON.parse(raw);
311
+ } catch {
312
+ return { __unparsed_arguments: raw };
313
+ }
314
+ }
315
+
316
+ export function parseResponse(body: unknown, node: number, ms: number): Turn {
317
+ const response = body as WireResponse;
318
+ const message = response.choices?.[0]?.message;
319
+ const blocks: AssistantBlock[] = [];
320
+
321
+ // Reasoning first, matching the order the model produced it and the order
322
+ // the Anthropic adapter yields. `raw` is what goes back on the wire; `text`
323
+ // is only for display.
324
+ const reasoning = message?.reasoning_content ?? message?.reasoning;
325
+ const details = message?.reasoning_details;
326
+ if ((typeof reasoning === "string" && reasoning.length > 0) || details !== undefined) {
327
+ const text = typeof reasoning === "string" ? reasoning : "";
328
+ blocks.push({ type: "thinking", text,
329
+ raw: { reasoning_content: text, ...(details === undefined ? {} : { reasoning_details: details }) } });
330
+ }
331
+
332
+ const text = message?.content;
333
+ if (typeof text === "string" && text.length > 0) {
334
+ blocks.push({ type: "text", text });
335
+ }
336
+
337
+ (message?.tool_calls ?? []).forEach((call, index) => {
338
+ const wire = extraFields(call);
339
+ blocks.push({
340
+ type: "tool_use",
341
+ // A missing id would make every call in the batch pair with the same
342
+ // result. The position is deterministic, so a replay derives the same one.
343
+ call_id: typeof call.id === "string" && call.id.length > 0 ? call.id : `call_${index}`,
344
+ name: call.function?.name ?? "",
345
+ input: decodeArguments(call.function?.arguments),
346
+ ...(wire === undefined ? {} : { wire }),
347
+ });
348
+ });
349
+
350
+ const usage = response.usage;
351
+ const prompt = usage?.prompt_tokens ?? 0;
352
+ // DeepSeek reports hits in prompt_cache_hit_tokens; the rest of the family
353
+ // uses prompt_tokens_details.cached_tokens. Both mean the same thing, and
354
+ // both are already included in prompt_tokens -- so the uncached remainder
355
+ // is the difference, not the whole.
356
+ const cacheRead = usage?.prompt_cache_hit_tokens ?? usage?.prompt_tokens_details?.cached_tokens ?? 0;
357
+
358
+ return {
359
+ blocks,
360
+ stopReason: response.choices?.[0]?.finish_reason ?? null,
361
+ usage: {
362
+ input_tokens: Math.max(0, prompt - cacheRead),
363
+ output_tokens: usage?.completion_tokens ?? 0,
364
+ // This family bills nothing for a cache write and reports no count for
365
+ // one. Zero is the actual value, not a missing measurement.
366
+ cache_creation_input_tokens: 0,
367
+ cache_read_input_tokens: cacheRead,
368
+ node,
369
+ ms,
370
+ },
371
+ };
372
+ }
373
+
374
+ /** An API error that carries its status, so the retry layer can read it. */
375
+ /**
376
+ * A failure the server reported after answering 200, as an error object in
377
+ * the stream. It has no HTTP status, so retry.ts decides from `code` (the
378
+ * provider's error type) and the message whether it is worth another attempt.
379
+ */
380
+ export class StreamError extends Error {
381
+ readonly code: string | undefined;
382
+ constructor(message: string, code?: string) {
383
+ super(message);
384
+ this.name = "StreamError";
385
+ this.code = code;
386
+ }
387
+ }
388
+
389
+ export class HttpError extends Error {
390
+ readonly status: number;
391
+ readonly headers: Headers;
392
+
393
+ constructor(status: number, headers: Headers, message: string) {
394
+ super(message);
395
+ this.name = "HttpError";
396
+ this.status = status;
397
+ this.headers = headers;
398
+ }
399
+ }
400
+
401
+ export class OpenAICompletionsProvider implements Provider {
402
+ readonly config: ProviderConfig;
403
+ private readonly apiKey: string;
404
+ private readonly fetchImpl: typeof fetch;
405
+ private readonly retry: RetryPolicy;
406
+ private readonly onRetry: ((attempt: number, delayMs: number, error: unknown) => void) | undefined;
407
+
408
+ constructor(
409
+ config: ProviderConfig,
410
+ apiKey: string,
411
+ options: {
412
+ fetchImpl?: typeof fetch;
413
+ retry?: RetryPolicy;
414
+ onRetry?: (attempt: number, delayMs: number, error: unknown) => void;
415
+ } = {},
416
+ ) {
417
+ this.config = config;
418
+ this.apiKey = apiKey;
419
+ this.fetchImpl = options.fetchImpl ?? fetch;
420
+ this.retry = options.retry ?? DEFAULT_RETRY;
421
+ this.onRetry = options.onRetry;
422
+ }
423
+
424
+ send(
425
+ frozen: FrozenPrefix,
426
+ messages: readonly Message[],
427
+ node: number,
428
+ signal?: AbortSignal,
429
+ onDelta?: OnDelta,
430
+ ): Promise<Turn> {
431
+ // The clock starts inside the retried request, so a reported duration is
432
+ // one attempt rather than the sum of the ones that failed.
433
+ return withRetry(
434
+ () => this.attempt(frozen, messages, node, signal, onDelta),
435
+ this.retry,
436
+ undefined,
437
+ (attempt, delayMs, error) => {
438
+ onDelta?.({ kind: "discard" });
439
+ this.onRetry?.(attempt, delayMs, error);
440
+ },
441
+ signal,
442
+ );
443
+ }
444
+
445
+ private async attempt(
446
+ frozen: FrozenPrefix,
447
+ messages: readonly Message[],
448
+ node: number,
449
+ signal?: AbortSignal,
450
+ onDelta?: OnDelta,
451
+ ): Promise<Turn> {
452
+ const started = Date.now();
453
+ const baseUrl = this.config.spec.baseUrl;
454
+ if (baseUrl === undefined) {
455
+ throw new Error(`model ${this.config.spec.id} has no baseUrl to send to`);
456
+ }
457
+
458
+ const compat = this.config.spec.compat ?? DEFAULT_COMPAT;
459
+ const payload: WireRequest & {
460
+ stream: true;
461
+ stream_options?: { include_usage: true };
462
+ } = { ...buildRequest(this.config, frozen, messages), stream: true };
463
+ // Without include_usage an OpenAI-dialect stream never reports usage, and
464
+ // the loop would treat the resulting zeros as a real prompt size. Servers
465
+ // that 400 on the field opt out via Compat.supportsUsageInStreaming.
466
+ if (compat.supportsUsageInStreaming) {
467
+ payload.stream_options = { include_usage: true };
468
+ }
469
+
470
+ const init: RequestInit = {
471
+ method: "POST",
472
+ headers: {
473
+ "content-type": "application/json",
474
+ authorization: `Bearer ${this.apiKey}`,
475
+ },
476
+ body: JSON.stringify(payload),
477
+ };
478
+ if (signal !== undefined) init.signal = signal;
479
+
480
+ const response = await this.fetchImpl(`${baseUrl.replace(/\/$/, "")}/chat/completions`, init);
481
+
482
+ if (!response.ok) {
483
+ const text = await response.text();
484
+ throw new HttpError(response.status, response.headers, errorMessage(response.status, text));
485
+ }
486
+
487
+ if (response.body === null) {
488
+ throw new Error(`${baseUrl} returned a streaming 200 with no body`);
489
+ }
490
+
491
+ const assembled = await readCompletionsSse(response.body, onDelta);
492
+ return parseResponse(assembled, node, Date.now() - started);
493
+ }
494
+ }
495
+
496
+ function errorMessage(status: number, text: string): string {
497
+ try {
498
+ const parsed = JSON.parse(text) as { error?: { message?: string } };
499
+ const detail = parsed.error?.message;
500
+ if (typeof detail === "string" && detail.length > 0) return `HTTP ${status}: ${detail}`;
501
+ } catch {
502
+ // Fall through to the raw body.
503
+ }
504
+ return `HTTP ${status}: ${text.slice(0, 200)}`;
505
+ }
506
+
507
+ /**
508
+ * Incremental SSE decoder. A TCP chunk is not a frame: the last line of one
509
+ * read is often the first half of the next, and parsing each read as JSON
510
+ * is how a valid stream becomes "non-JSON 200".
511
+ *
512
+ * Ported from pi (earendil-works/pi, MIT) — packages/ai/src/api/anthropic-messages.ts
513
+ * (line-split / half-frame handling). The `data:` / `[DONE]` dialect is ours.
514
+ */
515
+ export function pushSse(buffer: string, chunk: string): { buffer: string; payloads: string[] } {
516
+ buffer += chunk;
517
+ const payloads: string[] = [];
518
+ for (;;) {
519
+ const nl = buffer.search(/\r\n|\n|\r/);
520
+ if (nl < 0) break;
521
+ const crlf = buffer.startsWith("\r\n", nl) ? 2 : 1;
522
+ const line = buffer.slice(0, nl);
523
+ buffer = buffer.slice(nl + crlf);
524
+ if (line.length === 0 || line.startsWith(":")) continue;
525
+ if (line.startsWith("data:")) {
526
+ payloads.push(line.startsWith("data: ") ? line.slice(6) : line.slice(5));
527
+ }
528
+ }
529
+ return { buffer, payloads };
530
+ }
531
+
532
+ interface StreamAcc {
533
+ text: string;
534
+ thinking: string;
535
+ details: unknown[];
536
+ finishReason: string | null;
537
+ usage: WireResponse["usage"];
538
+ tools: Map<number, { id: string; name: string; arguments: string; extra: Record<string, unknown> }>;
539
+ /** Index of the call a chunk without `index` continues. */
540
+ lastIndex: number;
541
+ }
542
+
543
+ function applyCompletionChunk(chunk: WireStreamChunk, acc: StreamAcc, onDelta?: OnDelta): void {
544
+ // A server that fails mid-stream sends an error object instead of a choice.
545
+ // Ignoring it left finish_reason null and the cause invisible -- including
546
+ // an overflow the loop could otherwise recover from.
547
+ if (chunk.error !== undefined) {
548
+ const message = typeof chunk.error.message === "string" ? chunk.error.message : JSON.stringify(chunk.error);
549
+ const code = typeof chunk.error.type === "string" ? chunk.error.type : typeof chunk.error.code === "string" ? chunk.error.code : undefined;
550
+ throw new StreamError(`stream error: ${message}`, code);
551
+ }
552
+ if (chunk.usage !== undefined) acc.usage = chunk.usage;
553
+ const choice = chunk.choices?.[0];
554
+ if (choice === undefined) return;
555
+ if (choice.finish_reason) acc.finishReason = choice.finish_reason;
556
+ const delta = choice.delta;
557
+ if (delta === undefined) return;
558
+
559
+ const reasoning = delta.reasoning_content ?? delta.reasoning;
560
+ if (typeof reasoning === "string" && reasoning.length > 0) {
561
+ acc.thinking += reasoning;
562
+ onDelta?.({ kind: "thinking", text: reasoning });
563
+ }
564
+ if (Array.isArray(delta.reasoning_details)) acc.details.push(...delta.reasoning_details);
565
+ if (typeof delta.content === "string" && delta.content.length > 0) {
566
+ acc.text += delta.content;
567
+ onDelta?.({ kind: "text", text: delta.content });
568
+ }
569
+ for (const call of delta.tool_calls ?? []) {
570
+ // Without an index, a chunk carrying an id the current call does not
571
+ // have starts a new call; one without an id continues the current one.
572
+ // Defaulting every index-less chunk to 0 merged parallel calls into one.
573
+ let index = call.index;
574
+ if (index === undefined) {
575
+ const current = acc.tools.get(acc.lastIndex);
576
+ index = current === undefined ? 0 : call.id && current.id && call.id !== current.id ? acc.lastIndex + 1 : acc.lastIndex;
577
+ }
578
+ acc.lastIndex = index;
579
+ let tool = acc.tools.get(index);
580
+ if (tool === undefined) {
581
+ tool = { id: call.id ?? "", name: call.function?.name ?? "", arguments: "", extra: {} };
582
+ acc.tools.set(index, tool);
583
+ }
584
+ if (call.id) tool.id = call.id;
585
+ if (call.function?.name) tool.name = call.function.name;
586
+ if (call.function?.arguments) tool.arguments += call.function.arguments;
587
+ Object.assign(tool.extra, extraFields(call as Record<string, unknown>) ?? {});
588
+ }
589
+ }
590
+
591
+ interface WireStreamChunk {
592
+ choices?: {
593
+ delta?: {
594
+ content?: string | null;
595
+ reasoning_content?: string | null;
596
+ reasoning?: string | null;
597
+ reasoning_details?: unknown[];
598
+ tool_calls?: {
599
+ index?: number;
600
+ id?: string;
601
+ function?: { name?: string; arguments?: string };
602
+ }[];
603
+ };
604
+ finish_reason?: string | null;
605
+ }[];
606
+ usage?: WireResponse["usage"];
607
+ error?: { message?: unknown; type?: unknown; code?: unknown };
608
+ }
609
+
610
+ async function readCompletionsSse(
611
+ body: ReadableStream<Uint8Array>,
612
+ onDelta: OnDelta | undefined,
613
+ ): Promise<WireResponse> {
614
+ const acc: StreamAcc = {
615
+ text: "",
616
+ thinking: "",
617
+ details: [],
618
+ finishReason: null,
619
+ usage: undefined,
620
+ tools: new Map(),
621
+ lastIndex: 0,
622
+ };
623
+ const reader = body.getReader();
624
+ const decoder = new TextDecoder();
625
+ let buffer = "";
626
+ try {
627
+ while (true) {
628
+ const { value, done } = await reader.read();
629
+ const piece = decoder.decode(value ?? new Uint8Array(), { stream: !done });
630
+ const pushed = pushSse(buffer, piece);
631
+ buffer = pushed.buffer;
632
+ for (const payload of pushed.payloads) {
633
+ if (payload === "[DONE]") return toWireResponse(acc);
634
+ if (payload.length === 0) continue;
635
+ applyCompletionChunk(JSON.parse(payload) as WireStreamChunk, acc, onDelta);
636
+ }
637
+ if (done) break;
638
+ }
639
+ for (const payload of pushSse(buffer, "\n").payloads) {
640
+ if (payload === "[DONE]") break;
641
+ if (payload.length === 0) continue;
642
+ applyCompletionChunk(JSON.parse(payload) as WireStreamChunk, acc, onDelta);
643
+ }
644
+ } finally {
645
+ reader.releaseLock();
646
+ }
647
+ return toWireResponse(acc);
648
+ }
649
+
650
+ function toWireResponse(acc: StreamAcc): WireResponse {
651
+ const tools = [...acc.tools.entries()].sort(([a], [b]) => a - b).map(([, tool]) => tool);
652
+ const response: WireResponse = {
653
+ choices: [
654
+ {
655
+ message: {
656
+ content: acc.text.length > 0 ? acc.text : null,
657
+ ...(acc.thinking.length > 0 ? { reasoning_content: acc.thinking } : {}),
658
+ ...(acc.details.length > 0 ? { reasoning_details: acc.details } : {}),
659
+ ...(tools.length > 0
660
+ ? {
661
+ tool_calls: tools.map((t) => ({
662
+ ...t.extra,
663
+ id: t.id,
664
+ function: { name: t.name, arguments: t.arguments },
665
+ })),
666
+ }
667
+ : {}),
668
+ },
669
+ finish_reason: acc.finishReason,
670
+ },
671
+ ],
672
+ };
673
+ if (acc.usage !== undefined) response.usage = acc.usage;
674
+ return response;
675
+ }