minicode-ai 0.9.26

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 (162) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cli/args.ts +195 -0
  5. package/cli/auto-update.ts +108 -0
  6. package/cli/commands/auth.ts +166 -0
  7. package/cli/commands/config.ts +382 -0
  8. package/cli/commands/doctor.ts +128 -0
  9. package/cli/commands/exec.ts +179 -0
  10. package/cli/commands/mcp.ts +35 -0
  11. package/cli/commands/memory.ts +107 -0
  12. package/cli/commands/pricing.ts +100 -0
  13. package/cli/commands/providers.ts +162 -0
  14. package/cli/commands/sessions.ts +128 -0
  15. package/cli/commands/skills.ts +61 -0
  16. package/cli/commands/stats.ts +82 -0
  17. package/cli/commands.ts +317 -0
  18. package/cli/index.ts +539 -0
  19. package/cli/model-manager.ts +112 -0
  20. package/cli/provider-manager.ts +111 -0
  21. package/cli/repl.ts +734 -0
  22. package/cli/router.ts +124 -0
  23. package/cli/setup.ts +780 -0
  24. package/cli/wizard.ts +21 -0
  25. package/docs/ARCHITECTURE.html +1222 -0
  26. package/docs/README.md +109 -0
  27. package/docs/architecture.md +44 -0
  28. package/docs/changelog.md +3 -0
  29. package/package.json +91 -0
  30. package/src/agents/pool.ts +43 -0
  31. package/src/app/mentions.ts +50 -0
  32. package/src/app/provider-layer.ts +118 -0
  33. package/src/app/rag-layer.ts +105 -0
  34. package/src/app/session.ts +154 -0
  35. package/src/app/tool-layer.ts +56 -0
  36. package/src/config.ts +372 -0
  37. package/src/constants.ts +119 -0
  38. package/src/hooks/run.ts +89 -0
  39. package/src/lib/atomic-write.ts +88 -0
  40. package/src/lib/db-path.ts +36 -0
  41. package/src/lib/git-hardening.ts +91 -0
  42. package/src/lib/ignore.ts +58 -0
  43. package/src/lib/keystore.ts +202 -0
  44. package/src/lib/net.ts +70 -0
  45. package/src/lib/safe-open.ts +138 -0
  46. package/src/lib/session-id.ts +23 -0
  47. package/src/lib/trash.ts +38 -0
  48. package/src/lib/trusted-exec.ts +81 -0
  49. package/src/lsp/client.ts +395 -0
  50. package/src/mcp/client.ts +400 -0
  51. package/src/mcp/http-transport.ts +344 -0
  52. package/src/mcp/server.ts +538 -0
  53. package/src/mcp/transport.ts +150 -0
  54. package/src/memory/files.ts +159 -0
  55. package/src/memory/vector.ts +775 -0
  56. package/src/policy/allowlist.ts +67 -0
  57. package/src/policy/bash-guard.ts +465 -0
  58. package/src/policy/compaction.ts +271 -0
  59. package/src/policy/context.ts +161 -0
  60. package/src/policy/executor.ts +199 -0
  61. package/src/policy/jail.ts +127 -0
  62. package/src/policy/permission.ts +517 -0
  63. package/src/policy/pricing.ts +336 -0
  64. package/src/policy/ratelimit.ts +54 -0
  65. package/src/policy/sandbox-policy.ts +157 -0
  66. package/src/policy/scrub.ts +138 -0
  67. package/src/policy/update-check.ts +200 -0
  68. package/src/policy/usage.ts +292 -0
  69. package/src/policy/verifier.ts +181 -0
  70. package/src/providers/anthropic.ts +401 -0
  71. package/src/providers/auth-store.ts +139 -0
  72. package/src/providers/build.ts +136 -0
  73. package/src/providers/detect.ts +126 -0
  74. package/src/providers/effort.ts +165 -0
  75. package/src/providers/guards.ts +107 -0
  76. package/src/providers/oauth.ts +326 -0
  77. package/src/providers/presets.ts +122 -0
  78. package/src/providers/provision.ts +298 -0
  79. package/src/providers/responses.ts +371 -0
  80. package/src/providers/router.ts +247 -0
  81. package/src/repo/repomap.ts +470 -0
  82. package/src/sandbox/docker.ts +129 -0
  83. package/src/sandbox/os.ts +193 -0
  84. package/src/session/checkpoint.ts +543 -0
  85. package/src/session/journal.ts +1347 -0
  86. package/src/session/persistence.ts +446 -0
  87. package/src/session/shadow-git.ts +351 -0
  88. package/src/session/turn-marker.ts +118 -0
  89. package/src/skills/loader.ts +117 -0
  90. package/src/telemetry/trace.ts +283 -0
  91. package/src/tools/ask_user.ts +54 -0
  92. package/src/tools/bash.ts +400 -0
  93. package/src/tools/code_run.ts +96 -0
  94. package/src/tools/delete_file.ts +31 -0
  95. package/src/tools/edit.ts +204 -0
  96. package/src/tools/git.ts +301 -0
  97. package/src/tools/glob.ts +90 -0
  98. package/src/tools/grep.ts +281 -0
  99. package/src/tools/hashline.ts +66 -0
  100. package/src/tools/index.ts +103 -0
  101. package/src/tools/lsp.ts +346 -0
  102. package/src/tools/mcp_call.ts +163 -0
  103. package/src/tools/memory.ts +144 -0
  104. package/src/tools/move_file.ts +47 -0
  105. package/src/tools/patch.ts +86 -0
  106. package/src/tools/read_file.ts +130 -0
  107. package/src/tools/read_image.ts +80 -0
  108. package/src/tools/submit_result.ts +49 -0
  109. package/src/tools/task.ts +346 -0
  110. package/src/tools/todo.ts +201 -0
  111. package/src/tools/web_fetch.ts +161 -0
  112. package/src/tools/web_search.ts +156 -0
  113. package/src/tools/write_file.ts +42 -0
  114. package/src/ui/approval/prompt.ts +76 -0
  115. package/src/ui/assistant/simple.ts +568 -0
  116. package/src/ui/assistant/turn-status.ts +303 -0
  117. package/src/ui/contract.ts +55 -0
  118. package/src/ui/footer.ts +105 -0
  119. package/src/ui/input/input.ts +805 -0
  120. package/src/ui/input/prompt-engine.ts +606 -0
  121. package/src/ui/render/collapse.ts +84 -0
  122. package/src/ui/render/detail.ts +24 -0
  123. package/src/ui/render/diff.ts +181 -0
  124. package/src/ui/render/errors.ts +239 -0
  125. package/src/ui/render/format.ts +54 -0
  126. package/src/ui/render/highlight.ts +294 -0
  127. package/src/ui/render/markdown.ts +120 -0
  128. package/src/ui/render/money.ts +12 -0
  129. package/src/ui/render/reasoning.ts +20 -0
  130. package/src/ui/render/sanitize.ts +80 -0
  131. package/src/ui/render/table.ts +88 -0
  132. package/src/ui/render/theme.ts +339 -0
  133. package/src/ui/render/width.ts +256 -0
  134. package/src/ui/render/wrap.ts +120 -0
  135. package/src/ui/runtime/bus-debug.ts +83 -0
  136. package/src/ui/runtime/chrome.ts +301 -0
  137. package/src/ui/runtime/spinner.ts +77 -0
  138. package/src/ui/runtime/statusline.ts +227 -0
  139. package/src/ui/screens/model-manager.ts +434 -0
  140. package/src/ui/screens/overlay.ts +61 -0
  141. package/src/ui/screens/picker.ts +307 -0
  142. package/src/ui/screens/provider-manager.ts +450 -0
  143. package/src/ui/screens/wizard.ts +132 -0
  144. package/vendor/minicore/VENDOR.md +29 -0
  145. package/vendor/minicore/package.json +21 -0
  146. package/vendor/minicore/src/core/budget.ts +26 -0
  147. package/vendor/minicore/src/core/compact.ts +76 -0
  148. package/vendor/minicore/src/core/errors.ts +60 -0
  149. package/vendor/minicore/src/core/events.ts +74 -0
  150. package/vendor/minicore/src/core/executor.ts +139 -0
  151. package/vendor/minicore/src/core/history.ts +32 -0
  152. package/vendor/minicore/src/core/index.ts +42 -0
  153. package/vendor/minicore/src/core/loop.ts +344 -0
  154. package/vendor/minicore/src/core/permission.ts +24 -0
  155. package/vendor/minicore/src/core/provider.ts +39 -0
  156. package/vendor/minicore/src/core/recovery.ts +34 -0
  157. package/vendor/minicore/src/core/session.ts +327 -0
  158. package/vendor/minicore/src/core/snapshot.ts +142 -0
  159. package/vendor/minicore/src/core/tokens.ts +111 -0
  160. package/vendor/minicore/src/core/tool.ts +118 -0
  161. package/vendor/minicore/src/core/types.ts +50 -0
  162. package/vendor/minicore/src/providers/openai-compat.ts +366 -0
@@ -0,0 +1,50 @@
1
+ // Universal message & call records. No imports; the kernel's leaf type layer.
2
+ // These are the records that flow between the runtime, its context store, and
3
+ // provider adapters — never wire-specific shapes.
4
+
5
+ /** A single content part: plain text or inline image bytes. */
6
+ export type ContentPart =
7
+ | { type: "text"; text: string }
8
+ | { type: "image"; data: Uint8Array; mime: string };
9
+
10
+ /** Message content: a plain string or an ordered list of parts. */
11
+ export type Content = string | readonly ContentPart[];
12
+
13
+ /** A model-requested tool invocation, dispatched by the executor. */
14
+ export interface ToolCall {
15
+ readonly id: string;
16
+ readonly name: string;
17
+ readonly args: unknown;
18
+ }
19
+
20
+ /**
21
+ * The observation produced by executing a tool call. `isError: true` marks a
22
+ * failed execution (unknown tool, denied permission, invalid args, or a thrown
23
+ * tool error); the loop treats it as a normal observation, never a kernel
24
+ * failure.
25
+ */
26
+ export interface ToolResult {
27
+ readonly role: "tool";
28
+ readonly toolCallId: string;
29
+ readonly name: string;
30
+ readonly content: unknown;
31
+ readonly isError?: boolean;
32
+ }
33
+
34
+ /** A user turn. The first message of every run is appended by the kernel. */
35
+ export interface UserMessage {
36
+ readonly role: "user";
37
+ readonly content: Content;
38
+ }
39
+
40
+ /** A model turn: text output, optionally carrying tool calls to dispatch. */
41
+ export interface AssistantMessage {
42
+ readonly role: "assistant";
43
+ readonly content: Content;
44
+ readonly toolCalls?: readonly ToolCall[];
45
+ /** DeepSeek-style thinking content (reasoning), di-preservasi untuk multi-turn. */
46
+ readonly reasoning?: string;
47
+ }
48
+
49
+ /** Everything the context store can hold, discriminated by `role`. */
50
+ export type Message = UserMessage | AssistantMessage | ToolResult;
@@ -0,0 +1,366 @@
1
+ // OpenAI-compatible provider adapter. Covers OpenAI, OpenRouter, Ollama,
2
+ // DeepSeek, vLLM, and any other /chat/completions endpoint. Lives OUTSIDE the
3
+ // kernel; implements the ModelProvider contract.
4
+
5
+ import { ProviderError } from "../core/errors.ts";
6
+ import type { ModelProvider, ProviderEvent, StreamRequest } from "../core/provider.ts";
7
+ import type { ToolSchema } from "../core/tool.ts";
8
+ import type { Content, Message } from "../core/types.ts";
9
+
10
+ // P13 M0.1 (revisi S1) — side-map toolCallId → extra_content (mis. Gemini
11
+ // thought_signature). Versi sebelumnya menaruhnya di `args` sebagai
12
+ // `__extra_content`, tapi executor menolaknya ("unknown property", semua schema
13
+ // additionalProperties:false) sehingga tool call Gemini thinking justru gagal
14
+ // validasi. Side-map menjaga args bersih; consume-once + cap agar tak bocor.
15
+ const providerMetaByCallId = new Map<string, unknown>()
16
+ function stashProviderMeta(id: string, meta: unknown): void {
17
+ if (!id || meta == null) return
18
+ providerMetaByCallId.set(id, meta)
19
+ // cap: buang yang terlama bila menumpuk (sesi sangat panjang)
20
+ if (providerMetaByCallId.size > 500) {
21
+ const first = providerMetaByCallId.keys().next()
22
+ if (!first.done) providerMetaByCallId.delete(first.value)
23
+ }
24
+ }
25
+ function takeProviderMeta(id: string): unknown {
26
+ const v = providerMetaByCallId.get(id)
27
+ if (v != null) providerMetaByCallId.delete(id)
28
+ return v
29
+ }
30
+
31
+ /** Configuration for an OpenAI-compatible chat completions endpoint. */
32
+ export interface OpenAICompatConfig {
33
+ /** Adapter id reported on the ModelProvider. Defaults to "openai-compat". */
34
+ id?: string;
35
+ /** Base URL of the API, e.g. "https://api.openai.com/v1". Trailing slashes are trimmed. */
36
+ baseUrl: string;
37
+ /** Models this endpoint serves (used by the runtime for routing). */
38
+ models: readonly string[];
39
+ /** Model used when a request carries none. */
40
+ defaultModel?: string;
41
+ /** Bearer token; omitted entirely when absent (e.g. local endpoints). */
42
+ apiKey?: string;
43
+ /** Extra headers; these override the default content-type/authorization. */
44
+ headers?: Readonly<Record<string, string>>;
45
+ /**
46
+ * Send stream_options.include_usage (P4). Some strict OpenAI-compat
47
+ * endpoints reject the unknown field with 400; when enabled the adapter
48
+ * retries once without it. Defaults to true.
49
+ */
50
+ includeUsage?: boolean;
51
+ /** Generic reasoning effort knob — mapped per-wire (openai reasoning_effort, anthropic thinking). */
52
+ reasoningEffort?: string;
53
+ }
54
+
55
+ /**
56
+ * Build a ModelProvider for any OpenAI-compatible /chat/completions endpoint.
57
+ * Wire errors are normalized to ProviderError categories; network-level
58
+ * failures (DNS, connection refused) surface as `ProviderError("network")`;
59
+ * user aborts propagate as-is so the kernel can map them to `aborted`.
60
+ */
61
+ export function createOpenAICompatProvider(config: OpenAICompatConfig): ModelProvider {
62
+ const baseUrl = config.baseUrl.replace(/\/+$/, "");
63
+ const endpoint = `${baseUrl}/chat/completions`;
64
+ const headers: Record<string, string> = {
65
+ "content-type": "application/json",
66
+ "accept": "text/event-stream",
67
+ ...(config.apiKey ? { authorization: `Bearer ${config.apiKey}` } : {}),
68
+ ...config.headers,
69
+ };
70
+
71
+ return {
72
+ id: config.id ?? "openai-compat",
73
+ models: config.models,
74
+ async *stream(request: StreamRequest, signal: AbortSignal): AsyncIterable<ProviderEvent> {
75
+ const includeUsage = config.includeUsage ?? true;
76
+ const buildBody = (withUsage: boolean): string =>
77
+ JSON.stringify({
78
+ model: request.model ?? config.defaultModel,
79
+ messages: toMessages(request.messages),
80
+ tools: request.tools?.length ? toTools(request.tools) : undefined,
81
+ stream: true,
82
+ // JSON.stringify drops undefined keys, so the field is omitted entirely.
83
+ stream_options: withUsage ? { include_usage: true } : undefined,
84
+ // DeepSeek-style thinking: provider seperti b.ai butuh reasoning_content
85
+ // di history saat thinking aktif. OFF via env agar multi-turn aman.
86
+ ...(process.env.MINICODE_THINKING === "off" ? { enable_thinking: false } : {}),
87
+ ...(config.reasoningEffort ? { reasoning_effort: config.reasoningEffort } : {}),
88
+ });
89
+ let body = buildBody(includeUsage);
90
+ let response = await fetchOrThrow(endpoint, headers, body, signal);
91
+ // P4: strict OpenAI-compat endpoints reject the unknown stream_options
92
+ // field with 400. Retry once without it; a second 400 is a real error.
93
+ if (!response.ok && includeUsage && response.status === 400) {
94
+ body = buildBody(false);
95
+ response = await fetchOrThrow(endpoint, headers, body, signal);
96
+ }
97
+ if (!response.ok) {
98
+ const text = await response.text().catch(() => "");
99
+ throw toProviderError(response.status, text, response.headers);
100
+ }
101
+ if (!response.body) throw new ProviderError("network", "empty response body");
102
+
103
+ const calls = new Map<number, { id: string; name: string; args: string }>();
104
+ const order: number[] = [];
105
+ // A non-conforming provider may repeat finish_reason across chunks; emit
106
+ // the accumulated tool calls and the finish event only once, otherwise
107
+ // the kernel would see (and execute) the same tool call twice.
108
+ let finished = false;
109
+ for await (const chunk of sse(response.body, signal)) {
110
+ const usage = chunk.usage as { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | undefined;
111
+ // P8 + race: beberapa provider (b.ai dll) mengirim `usage` pada chunk
112
+ // TERAKHIR setelah finish_reason. Jangan di-drop karena `finished`.
113
+ if (usage && (usage.prompt_tokens != null || usage.completion_tokens != null || usage.total_tokens != null)) {
114
+ yield {
115
+ type: "extension",
116
+ kind: "usage",
117
+ data: { inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens, totalTokens: usage.total_tokens },
118
+ };
119
+ }
120
+ if (finished) {
121
+ const postTool = (chunk as { choices?: Array<{ delta?: Record<string, unknown> }> }).choices?.[0]?.delta?.tool_calls;
122
+ if (Array.isArray(postTool)) throw new ProviderError("network", "tool deltas after finish_reason");
123
+ continue;
124
+ }
125
+ const choices = chunk.choices as
126
+ | Array<{ delta?: Record<string, unknown>; finish_reason?: string | null }>
127
+ | undefined;
128
+ const first = choices?.[0];
129
+ if (!first) continue;
130
+ const delta = first.delta ?? {};
131
+ // Beberapa provider (mis. b.ai/Gemini) mengirim chunk berisi content
132
+ // SETELAH finish_reason — jangan di-forward (kernel tolak event setelah finish).
133
+ const content = delta.content;
134
+ if (!finished && typeof content === "string" && content.length > 0) yield { type: "text", text: content };
135
+ // Reasoning is surfaced as an extension event, never a kernel
136
+ // primitive. Handles DeepSeek-style delta.reasoning_content (string or
137
+ // content-part array) and OpenAI o-series delta.reasoning (string).
138
+ const rawReasoning = (delta as { reasoning_content?: unknown; reasoning?: unknown }).reasoning_content ??
139
+ (delta as { reasoning?: unknown }).reasoning;
140
+ let reasoningText: string | undefined;
141
+ if (typeof rawReasoning === "string") reasoningText = rawReasoning;
142
+ else if (Array.isArray(rawReasoning)) {
143
+ reasoningText = (rawReasoning as Array<{ type?: string; text?: unknown }>)
144
+ .filter((part) => part?.type === "text" && typeof part.text === "string")
145
+ .map((part) => part.text as string)
146
+ .join("");
147
+ }
148
+ if (!finished && reasoningText && reasoningText.length > 0) {
149
+ yield { type: "extension", kind: "reasoning", data: { text: reasoningText } };
150
+ }
151
+ const toolDeltas = delta.tool_calls;
152
+ if (Array.isArray(toolDeltas)) {
153
+ // A conforming provider sends every tool delta before finish_reason.
154
+ // Deltas that arrive after `finished` would be accumulated but never
155
+ // emitted, silently turning a broken stream into an empty success;
156
+ // fail loud as a retryable network error instead.
157
+ if (finished) {
158
+ throw new ProviderError("network", "tool deltas after finish_reason");
159
+ }
160
+ for (const td of toolDeltas as Array<Record<string, unknown>>) {
161
+ const index = Number(td.index ?? 0);
162
+ const acc = calls.get(index) ?? { id: "", name: "", args: "" };
163
+ calls.set(index, acc);
164
+ if (order.indexOf(index) < 0) order.push(index);
165
+ if (typeof td.id === "string" && td.id) acc.id = td.id;
166
+ // P13 M0.1 (S1) — preserve Gemini thought_signature (extra_content)
167
+ // verbatim di side-map (BUKAN di args — executor menolak properti
168
+ // tak dikenal). Di-echo saat replay history di toMessages.
169
+ const extra =
170
+ (td as Record<string, unknown>).extra_content ??
171
+ (td as Record<string, unknown>).thought_signature ??
172
+ (td as Record<string, unknown>).providerMeta;
173
+ if (extra != null) (acc as Record<string, unknown>)._extra = extra;
174
+ const fnExtra =
175
+ (td.function as Record<string, unknown> | undefined)?.extra_content ??
176
+ (td.function as Record<string, unknown> | undefined)?.thought_signature;
177
+ if (fnExtra != null) (acc as Record<string, unknown>)._extra = fnExtra;
178
+ const fn = td.function as { name?: unknown; arguments?: unknown } | undefined;
179
+ if (fn) {
180
+ // A tool name is never split across deltas (only `arguments` is),
181
+ // and some providers repeat the full name on every chunk. Take the
182
+ // first non-empty name instead of concatenating, which used to
183
+ // turn a repeated name into "echoecho" (unknown tool error).
184
+ if (typeof fn.name === "string" && fn.name) acc.name = acc.name || fn.name;
185
+ if (typeof fn.arguments === "string") acc.args += fn.arguments;
186
+ }
187
+ }
188
+ }
189
+ if (!finished && first.finish_reason) {
190
+ finished = true;
191
+ for (const index of order) {
192
+ const acc = calls.get(index) as unknown as { id: string; name: string; args: string; _extra?: unknown };
193
+ if (!acc) continue;
194
+ let args: unknown = acc.args;
195
+ if (acc.args) {
196
+ try {
197
+ args = JSON.parse(acc.args);
198
+ } catch {
199
+ args = { raw: acc.args };
200
+ }
201
+ }
202
+ // P13 M0.1 (S1) — args TETAP bersih (executor validateArgs menolak
203
+ // properti tak dikenal); signature disimpan di side-map by call id.
204
+ const callId = acc.id || `call_${index}`
205
+ if (acc._extra != null) stashProviderMeta(callId, acc._extra);
206
+ yield { type: "tool_call", id: callId, name: acc.name, args };
207
+ }
208
+ // P6: content_filter (OpenAI safety filter) must not be invisible as
209
+ // a plain "stop" — surface it as an extension event so observers can
210
+ // distinguish a blocked response from a normal completion.
211
+ if (first.finish_reason === "content_filter") {
212
+ yield { type: "extension", kind: "content_filter", data: {} };
213
+ }
214
+ yield { type: "finish", reason: mapFinishReason(first.finish_reason) };
215
+ }
216
+ }
217
+ // Provider quirky bisa berakhir tanpa finish_reason (mis. [DONE] langsung).
218
+ // Emit finish("stop") agar kernel tidak menganggap stream terputus.
219
+ if (!finished) {
220
+ yield { type: "finish", reason: "stop" };
221
+ }
222
+ },
223
+ };
224
+ }
225
+
226
+ function toMessages(messages: readonly Message[]): unknown[] {
227
+ return messages.map((message) => {
228
+ switch (message.role) {
229
+ case "user":
230
+ return { role: "user", content: toContent(message.content) };
231
+ case "assistant":
232
+ return {
233
+ role: "assistant",
234
+ content: toContent(message.content),
235
+ // DeepSeek-style thinking: provider butuh reasoning_content di history
236
+ // saat thinking mode aktif, agar multi-turn tidak 400.
237
+ ...((message as { reasoning?: string }).reasoning ? { reasoning_content: (message as { reasoning?: string }).reasoning } : {}),
238
+ tool_calls: message.toolCalls?.length
239
+ ? message.toolCalls.map((call) => {
240
+ // P13 M0.1 (S1) — echo signature dari side-map (consume-once),
241
+ // args dikirim apa adanya tanpa kunci siluman.
242
+ const extra = takeProviderMeta(call.id)
243
+ return {
244
+ id: call.id,
245
+ type: "function",
246
+ function: { name: call.name, arguments: JSON.stringify(call.args ?? {}) },
247
+ ...(extra != null ? { extra_content: extra } : {}),
248
+ }
249
+ })
250
+ : undefined,
251
+ };
252
+ case "tool":
253
+ return {
254
+ role: "tool",
255
+ tool_call_id: message.toolCallId,
256
+ content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
257
+ };
258
+ }
259
+ });
260
+ }
261
+
262
+ function toContent(content: Content): unknown {
263
+ if (typeof content === "string") return content;
264
+ const parts: unknown[] = [];
265
+ for (const part of content) {
266
+ if (part.type === "text") parts.push({ type: "text", text: part.text });
267
+ else parts.push({ type: "image_url", image_url: { url: `data:${part.mime};base64,${bytesToBase64(part.data)}` } });
268
+ }
269
+ return parts;
270
+ }
271
+
272
+ function bytesToBase64(bytes: Uint8Array): string {
273
+ // btoa rejects inputs beyond ~0x80000000 bytes in some engines, and one giant
274
+ // string concat is wasteful for multi-MB images. Chunk the input. The chunk
275
+ // size is a multiple of 3 so every chunk ends on a base64 group boundary:
276
+ // concatenating the raw outputs reproduces the whole-buffer encoding exactly
277
+ // (only the final chunk carries '=' padding, which is then the correct
278
+ // padding for the whole buffer). A non-multiple-of-3 chunk size breaks the
279
+ // alignment and produces invalid base64 — see the chunked-base64 test.
280
+ let out = "";
281
+ const chunk = 0x7fe0; // 32736 = 10912 × 3
282
+ for (let i = 0; i < bytes.length; i += chunk) {
283
+ let part = "";
284
+ const end = Math.min(i + chunk, bytes.length);
285
+ for (let j = i; j < end; j++) part += String.fromCharCode(bytes[j]!);
286
+ out += btoa(part);
287
+ }
288
+ return out;
289
+ }
290
+
291
+ function toTools(tools: readonly ToolSchema[]): unknown[] {
292
+ return tools.map((tool) => ({
293
+ type: "function",
294
+ function: {
295
+ name: tool.name,
296
+ description: tool.description,
297
+ parameters: tool.parameters,
298
+ },
299
+ }));
300
+ }
301
+
302
+ function mapFinishReason(reason: string): "stop" | "tool_calls" | "length" {
303
+ if (reason === "tool_calls" || reason === "function_call") return "tool_calls";
304
+ if (reason === "length") return "length";
305
+ return "stop";
306
+ }
307
+
308
+ async function fetchOrThrow(url: string, headers: Record<string, string>, body: string, signal: AbortSignal): Promise<Response> {
309
+ // Network-level failures (DNS, refused, dropped) must surface as a
310
+ // retryable ProviderError("network"), not a raw TypeError that the kernel
311
+ // would later guess at as "unknown". A user abort is not a network failure:
312
+ // propagate the AbortError as-is so the kernel maps it to AgentError aborted.
313
+ try {
314
+ return await fetch(url, { method: "POST", headers, body, signal });
315
+ } catch (error) {
316
+ if (error instanceof Error && error.name === "AbortError") throw error;
317
+ throw new ProviderError("network", error instanceof Error ? error.message : String(error));
318
+ }
319
+ }
320
+
321
+ async function* sse(body: ReadableStream<Uint8Array>, signal: AbortSignal): AsyncGenerator<Record<string, unknown>> {
322
+ const reader = body.getReader();
323
+ const decoder = new TextDecoder();
324
+ let buffer = "";
325
+ try {
326
+ while (true) {
327
+ if (signal.aborted) throw new Error("AbortError");
328
+ const { done, value } = await reader.read();
329
+ if (done) break;
330
+ buffer += decoder.decode(value, { stream: true });
331
+ let index: number;
332
+ while ((index = buffer.indexOf("\n")) >= 0) {
333
+ const line = buffer.slice(0, index).replace(/\r$/, "");
334
+ buffer = buffer.slice(index + 1);
335
+ if (!line.startsWith("data:")) continue;
336
+ const payload = line.slice(5).trim();
337
+ if (payload === "[DONE]") return;
338
+ if (payload) {
339
+ try {
340
+ yield JSON.parse(payload) as Record<string, unknown>;
341
+ } catch {
342
+ // Skip malformed SSE payloads; the next chunk may complete them.
343
+ }
344
+ }
345
+ }
346
+ }
347
+ } finally {
348
+ reader.releaseLock();
349
+ }
350
+ }
351
+
352
+ function toProviderError(status: number, body: string, headers: Headers): ProviderError {
353
+ const detail = body.slice(0, 500);
354
+ const retryAfter = headers.get("retry-after");
355
+ if (status === 429) {
356
+ const ms = retryAfter ? Number(retryAfter) * 1_000 : undefined;
357
+ return new ProviderError("rate_limit", `rate limited (${status}): ${detail}`, Number.isFinite(ms) ? ms : undefined);
358
+ }
359
+ if (status === 401 || status === 403) return new ProviderError("auth", `auth failed (${status}): ${detail}`);
360
+ if (status === 400 || status === 404 || status === 422) {
361
+ const isContext = body.toLowerCase().includes("context_length") || body.toLowerCase().includes("maximum context");
362
+ return new ProviderError(isContext ? "context_length_exceeded" : "invalid_request", `${status}: ${detail}`);
363
+ }
364
+ if (status >= 500) return new ProviderError("server", `server error (${status}): ${detail}`);
365
+ return new ProviderError("unknown", `${status}: ${detail}`);
366
+ }