@tinyweb_dev/agent-framework-llm 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.
@@ -0,0 +1,422 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/protocols/openai-chat.ts
2
+ import { Array as Arr, Effect, Schema } from "effect"
3
+ import { Route } from "../route/client"
4
+ import { Auth } from "../route/auth"
5
+ import { Endpoint } from "../route/endpoint"
6
+ import { Framing } from "../route/framing"
7
+ import { HttpTransport } from "../route/transport"
8
+ import { Protocol } from "../route/protocol"
9
+ import {
10
+ LLMEvent,
11
+ Usage,
12
+ type FinishReason,
13
+ type LLMRequest,
14
+ type MediaPart,
15
+ type TextPart,
16
+ type ToolCallPart,
17
+ type ToolDefinition,
18
+ } from "../schema"
19
+ import { isRecord, JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared"
20
+ import { OpenAIOptions } from "./utils/openai-options"
21
+ import { ToolStream } from "./utils/tool-stream"
22
+
23
+ const ADAPTER = "openai-chat"
24
+ export const DEFAULT_BASE_URL = "https://api.openai.com/v1"
25
+ export const PATH = "/chat/completions"
26
+
27
+ // =============================================================================
28
+ // Request Body Schema
29
+ // =============================================================================
30
+ const OpenAIChatFunction = Schema.Struct({
31
+ name: Schema.String,
32
+ description: Schema.String,
33
+ parameters: JsonObject,
34
+ })
35
+
36
+ const OpenAIChatTool = Schema.Struct({
37
+ type: Schema.tag("function"),
38
+ function: OpenAIChatFunction,
39
+ })
40
+ type OpenAIChatTool = Schema.Schema.Type<typeof OpenAIChatTool>
41
+
42
+ const OpenAIChatAssistantToolCall = Schema.Struct({
43
+ id: Schema.String,
44
+ type: Schema.tag("function"),
45
+ function: Schema.Struct({
46
+ name: Schema.String,
47
+ arguments: Schema.String,
48
+ }),
49
+ })
50
+ type OpenAIChatAssistantToolCall = Schema.Schema.Type<typeof OpenAIChatAssistantToolCall>
51
+
52
+ const OpenAIChatUserContentText = Schema.Struct({
53
+ type: Schema.Literal("text"),
54
+ text: Schema.String,
55
+ })
56
+ const OpenAIChatUserContentImageUrl = Schema.Struct({
57
+ type: Schema.Literal("image_url"),
58
+ image_url: Schema.Struct({ url: Schema.String }),
59
+ })
60
+ const OpenAIChatUserContentPart = Schema.Union([OpenAIChatUserContentText, OpenAIChatUserContentImageUrl]).pipe(
61
+ Schema.toTaggedUnion("type"),
62
+ )
63
+ type OpenAIChatUserContentPart = Schema.Schema.Type<typeof OpenAIChatUserContentPart>
64
+ const OpenAIChatUserContent = Schema.Union([Schema.String, Schema.Array(OpenAIChatUserContentPart)])
65
+
66
+ const OpenAIChatMessage = Schema.Union([
67
+ Schema.Struct({ role: Schema.Literal("system"), content: Schema.String }),
68
+ Schema.Struct({ role: Schema.Literal("user"), content: OpenAIChatUserContent }),
69
+ Schema.Struct({
70
+ role: Schema.Literal("assistant"),
71
+ content: Schema.NullOr(Schema.String),
72
+ tool_calls: optionalArray(OpenAIChatAssistantToolCall),
73
+ reasoning_content: Schema.optional(Schema.String),
74
+ }),
75
+ Schema.Struct({ role: Schema.Literal("tool"), tool_call_id: Schema.String, content: Schema.String }),
76
+ ]).pipe(Schema.toTaggedUnion("role"))
77
+ type OpenAIChatMessage = Schema.Schema.Type<typeof OpenAIChatMessage>
78
+
79
+ const OpenAIChatToolChoice = Schema.Union([
80
+ Schema.Literals(["auto", "none", "required"]),
81
+ Schema.Struct({
82
+ type: Schema.tag("function"),
83
+ function: Schema.Struct({ name: Schema.String }),
84
+ }),
85
+ ])
86
+
87
+ export const bodyFields = {
88
+ model: Schema.String,
89
+ messages: Schema.Array(OpenAIChatMessage),
90
+ tools: optionalArray(OpenAIChatTool),
91
+ tool_choice: Schema.optional(OpenAIChatToolChoice),
92
+ stream: Schema.Literal(true),
93
+ stream_options: Schema.optional(Schema.Struct({ include_usage: Schema.Boolean })),
94
+ store: Schema.optional(Schema.Boolean),
95
+ reasoning_effort: Schema.optional(OpenAIOptions.OpenAIReasoningEffort),
96
+ max_tokens: Schema.optional(Schema.Number),
97
+ temperature: Schema.optional(Schema.Number),
98
+ top_p: Schema.optional(Schema.Number),
99
+ frequency_penalty: Schema.optional(Schema.Number),
100
+ presence_penalty: Schema.optional(Schema.Number),
101
+ seed: Schema.optional(Schema.Number),
102
+ stop: optionalArray(Schema.String),
103
+ }
104
+ const OpenAIChatBody = Schema.Struct(bodyFields)
105
+ export type OpenAIChatBody = Schema.Schema.Type<typeof OpenAIChatBody>
106
+
107
+ // =============================================================================
108
+ // Streaming Event Schema
109
+ // =============================================================================
110
+ const OpenAIChatUsage = Schema.Struct({
111
+ prompt_tokens: Schema.optional(Schema.Number),
112
+ completion_tokens: Schema.optional(Schema.Number),
113
+ total_tokens: Schema.optional(Schema.Number),
114
+ prompt_tokens_details: optionalNull(
115
+ Schema.Struct({
116
+ cached_tokens: Schema.optional(Schema.Number),
117
+ }),
118
+ ),
119
+ completion_tokens_details: optionalNull(
120
+ Schema.Struct({
121
+ reasoning_tokens: Schema.optional(Schema.Number),
122
+ }),
123
+ ),
124
+ })
125
+
126
+ const OpenAIChatToolCallDeltaFunction = Schema.Struct({
127
+ name: optionalNull(Schema.String),
128
+ arguments: optionalNull(Schema.String),
129
+ })
130
+
131
+ const OpenAIChatToolCallDelta = Schema.Struct({
132
+ index: Schema.Number,
133
+ id: optionalNull(Schema.String),
134
+ function: optionalNull(OpenAIChatToolCallDeltaFunction),
135
+ })
136
+ type OpenAIChatToolCallDelta = Schema.Schema.Type<typeof OpenAIChatToolCallDelta>
137
+
138
+ const OpenAIChatDelta = Schema.Struct({
139
+ content: optionalNull(Schema.String),
140
+ tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta)),
141
+ })
142
+
143
+ const OpenAIChatChoice = Schema.Struct({
144
+ delta: optionalNull(OpenAIChatDelta),
145
+ finish_reason: optionalNull(Schema.String),
146
+ })
147
+
148
+ const OpenAIChatEvent = Schema.Struct({
149
+ choices: Schema.Array(OpenAIChatChoice),
150
+ usage: optionalNull(OpenAIChatUsage),
151
+ })
152
+ type OpenAIChatEvent = Schema.Schema.Type<typeof OpenAIChatEvent>
153
+ type OpenAIChatRequestMessage = LLMRequest["messages"][number]
154
+
155
+ interface ParserState {
156
+ readonly tools: ToolStream.State<number>
157
+ readonly toolCallEvents: ReadonlyArray<LLMEvent>
158
+ readonly usage?: Usage
159
+ readonly finishReason?: FinishReason
160
+ }
161
+
162
+ const invalid = ProviderShared.invalidRequest
163
+
164
+ // =============================================================================
165
+ // Request Lowering
166
+ // =============================================================================
167
+ const lowerTool = (tool: ToolDefinition): OpenAIChatTool => ({
168
+ type: "function",
169
+ function: {
170
+ name: tool.name,
171
+ description: tool.description,
172
+ parameters: tool.inputSchema,
173
+ },
174
+ })
175
+
176
+ const lowerToolChoice = (toolChoice: NonNullable<LLMRequest["toolChoice"]>) =>
177
+ ProviderShared.matchToolChoice("OpenAI Chat", toolChoice, {
178
+ auto: () => "auto" as const,
179
+ none: () => "none" as const,
180
+ required: () => "required" as const,
181
+ tool: (name) => ({ type: "function" as const, function: { name } }),
182
+ })
183
+
184
+ const lowerToolCall = (part: ToolCallPart): OpenAIChatAssistantToolCall => ({
185
+ id: part.id,
186
+ type: "function",
187
+ function: {
188
+ name: part.name,
189
+ arguments: ProviderShared.encodeJson(part.input),
190
+ },
191
+ })
192
+
193
+ const openAICompatibleReasoningContent = (native: unknown) =>
194
+ isRecord(native) && typeof native.reasoning_content === "string" ? native.reasoning_content : undefined
195
+
196
+ const mediaToImageUrl = (part: MediaPart): string => {
197
+ const data = part.data
198
+ if (typeof data === "string") {
199
+ if (data.startsWith("http://") || data.startsWith("https://") || data.startsWith("data:") || data.startsWith("file://"))
200
+ return data
201
+ return `data:${part.mediaType};base64,${data}`
202
+ }
203
+ return `data:${part.mediaType};base64,${ProviderShared.mediaBytes(part)}`
204
+ }
205
+
206
+ const lowerUserMessage = Effect.fn("OpenAIChat.lowerUserMessage")(function* (message: OpenAIChatRequestMessage) {
207
+ const parts: OpenAIChatUserContentPart[] = []
208
+ let hasMedia = false
209
+ const textParts: TextPart[] = []
210
+ for (const part of message.content) {
211
+ if (!ProviderShared.supportsContent(part, ["text", "media"]))
212
+ return yield* ProviderShared.unsupportedContent("OpenAI Chat", "user", ["text", "media"])
213
+ if (part.type === "text") {
214
+ textParts.push(part)
215
+ parts.push({ type: "text", text: part.text })
216
+ continue
217
+ }
218
+ if (!part.mediaType.startsWith("image/"))
219
+ return yield* ProviderShared.invalidRequest(
220
+ `OpenAI Chat user messages only support image/* media (received ${part.mediaType})`,
221
+ )
222
+ hasMedia = true
223
+ parts.push({ type: "image_url", image_url: { url: mediaToImageUrl(part) } })
224
+ }
225
+ if (!hasMedia) return { role: "user" as const, content: ProviderShared.joinText(textParts) }
226
+ return { role: "user" as const, content: parts }
227
+ })
228
+
229
+ const lowerAssistantMessage = Effect.fn("OpenAIChat.lowerAssistantMessage")(function* (
230
+ message: OpenAIChatRequestMessage,
231
+ ) {
232
+ const content: TextPart[] = []
233
+ const toolCalls: OpenAIChatAssistantToolCall[] = []
234
+ for (const part of message.content) {
235
+ if (!ProviderShared.supportsContent(part, ["text", "tool-call"]))
236
+ return yield* ProviderShared.unsupportedContent("OpenAI Chat", "assistant", ["text", "tool-call"])
237
+ if (part.type === "text") {
238
+ content.push(part)
239
+ continue
240
+ }
241
+ if (part.type === "tool-call") {
242
+ toolCalls.push(lowerToolCall(part))
243
+ continue
244
+ }
245
+ }
246
+ return {
247
+ role: "assistant" as const,
248
+ content: content.length === 0 ? null : ProviderShared.joinText(content),
249
+ tool_calls: toolCalls.length === 0 ? undefined : toolCalls,
250
+ reasoning_content: openAICompatibleReasoningContent(message.native?.openaiCompatible),
251
+ }
252
+ })
253
+
254
+ const lowerToolMessages = Effect.fn("OpenAIChat.lowerToolMessages")(function* (message: OpenAIChatRequestMessage) {
255
+ const messages: OpenAIChatMessage[] = []
256
+ for (const part of message.content) {
257
+ if (!ProviderShared.supportsContent(part, ["tool-result"]))
258
+ return yield* ProviderShared.unsupportedContent("OpenAI Chat", "tool", ["tool-result"])
259
+ messages.push({ role: "tool", tool_call_id: part.id, content: ProviderShared.toolResultText(part) })
260
+ }
261
+ return messages
262
+ })
263
+
264
+ const lowerMessage = Effect.fn("OpenAIChat.lowerMessage")(function* (message: OpenAIChatRequestMessage) {
265
+ if (message.role === "user") return [yield* lowerUserMessage(message)]
266
+ if (message.role === "assistant") return [yield* lowerAssistantMessage(message)]
267
+ return yield* lowerToolMessages(message)
268
+ })
269
+
270
+ const lowerMessages = Effect.fn("OpenAIChat.lowerMessages")(function* (request: LLMRequest) {
271
+ const system: OpenAIChatMessage[] =
272
+ request.system.length === 0 ? [] : [{ role: "system", content: ProviderShared.joinText(request.system) }]
273
+ return [...system, ...Arr.flatten(yield* Effect.forEach(request.messages, lowerMessage))]
274
+ })
275
+
276
+ const lowerOptions = Effect.fn("OpenAIChat.lowerOptions")(function* (request: LLMRequest) {
277
+ const store = OpenAIOptions.store(request)
278
+ const reasoningEffort = OpenAIOptions.reasoningEffort(request)
279
+ if (reasoningEffort && !OpenAIOptions.isReasoningEffort(reasoningEffort))
280
+ return yield* invalid(`OpenAI Chat does not support reasoning effort ${reasoningEffort}`)
281
+ return {
282
+ ...(store !== undefined ? { store } : {}),
283
+ ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),
284
+ }
285
+ })
286
+
287
+ const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (request: LLMRequest) {
288
+ const generation = request.generation
289
+ return {
290
+ model: request.model.id,
291
+ messages: yield* lowerMessages(request),
292
+ tools: request.tools.length === 0 ? undefined : request.tools.map(lowerTool),
293
+ tool_choice: request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined,
294
+ stream: true as const,
295
+ stream_options: { include_usage: true },
296
+ max_tokens: generation?.maxTokens,
297
+ temperature: generation?.temperature,
298
+ top_p: generation?.topP,
299
+ frequency_penalty: generation?.frequencyPenalty,
300
+ presence_penalty: generation?.presencePenalty,
301
+ seed: generation?.seed,
302
+ stop: generation?.stop,
303
+ ...(yield* lowerOptions(request)),
304
+ }
305
+ })
306
+
307
+ // =============================================================================
308
+ // Stream Parsing
309
+ // =============================================================================
310
+ const mapFinishReason = (reason: string | null | undefined): FinishReason => {
311
+ if (reason === "stop") return "stop"
312
+ if (reason === "length") return "length"
313
+ if (reason === "content_filter") return "content-filter"
314
+ if (reason === "function_call" || reason === "tool_calls") return "tool-calls"
315
+ return "unknown"
316
+ }
317
+
318
+ const mapUsage = (usage: OpenAIChatEvent["usage"]): Usage | undefined => {
319
+ if (!usage) return undefined
320
+ const cached = usage.prompt_tokens_details?.cached_tokens
321
+ const reasoning = usage.completion_tokens_details?.reasoning_tokens
322
+ const nonCached = ProviderShared.subtractTokens(usage.prompt_tokens, cached)
323
+ return new Usage({
324
+ inputTokens: usage.prompt_tokens,
325
+ outputTokens: usage.completion_tokens,
326
+ nonCachedInputTokens: nonCached,
327
+ cacheReadInputTokens: cached,
328
+ reasoningTokens: reasoning,
329
+ totalTokens: ProviderShared.totalTokens(usage.prompt_tokens, usage.completion_tokens, usage.total_tokens),
330
+ providerMetadata: { openai: usage },
331
+ })
332
+ }
333
+
334
+ const step = (state: ParserState, event: OpenAIChatEvent) =>
335
+ Effect.gen(function* () {
336
+ const events: LLMEvent[] = []
337
+ const usage = mapUsage(event.usage) ?? state.usage
338
+ const choice = event.choices[0]
339
+ const finishReason = choice?.finish_reason ? mapFinishReason(choice.finish_reason) : state.finishReason
340
+ const delta = choice?.delta
341
+ const toolDeltas = delta?.tool_calls ?? []
342
+ let tools = state.tools
343
+
344
+ if (delta?.content) events.push(LLMEvent.textDelta({ id: "text-0", text: delta.content }))
345
+
346
+ for (const tool of toolDeltas) {
347
+ const result = ToolStream.appendOrStart(
348
+ ADAPTER,
349
+ tools,
350
+ tool.index,
351
+ { id: tool.id ?? undefined, name: tool.function?.name ?? undefined, text: tool.function?.arguments ?? "" },
352
+ "OpenAI Chat tool call delta is missing id or name",
353
+ )
354
+ if (ToolStream.isError(result)) return yield* result
355
+ tools = result.tools
356
+ if (result.event) events.push(result.event)
357
+ }
358
+
359
+ const finished =
360
+ finishReason !== undefined && state.finishReason === undefined && Object.keys(tools).length > 0
361
+ ? yield* ToolStream.finishAll(ADAPTER, tools)
362
+ : undefined
363
+
364
+ return [
365
+ {
366
+ tools: finished?.tools ?? tools,
367
+ toolCallEvents: finished?.events ?? state.toolCallEvents,
368
+ usage,
369
+ finishReason,
370
+ },
371
+ events,
372
+ ] as const
373
+ })
374
+
375
+ const finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {
376
+ const hasToolCalls = state.toolCallEvents.length > 0
377
+ const reason = state.finishReason === "stop" && hasToolCalls ? "tool-calls" : state.finishReason
378
+ return [...state.toolCallEvents, ...(reason ? [LLMEvent.requestFinish({ reason, usage: state.usage })] : [])]
379
+ }
380
+
381
+ // =============================================================================
382
+ // Protocol And OpenAI Route
383
+ // =============================================================================
384
+ export const protocol = Protocol.make({
385
+ id: ADAPTER,
386
+ body: {
387
+ schema: OpenAIChatBody,
388
+ from: fromRequest,
389
+ },
390
+ stream: {
391
+ event: Protocol.jsonEvent(OpenAIChatEvent),
392
+ initial: () => ({ tools: ToolStream.empty<number>(), toolCallEvents: [] }),
393
+ step,
394
+ onHalt: finishEvents,
395
+ },
396
+ })
397
+
398
+ const encodeBody = Schema.encodeSync(Schema.fromJsonString(OpenAIChatBody))
399
+
400
+ export const httpTransport = HttpTransport.httpJson({
401
+ endpoint: Endpoint.path(PATH),
402
+ auth: Auth.bearer(),
403
+ framing: Framing.sse,
404
+ encodeBody,
405
+ })
406
+
407
+ export const route = Route.make({
408
+ id: ADAPTER,
409
+ provider: "openai",
410
+ protocol,
411
+ transport: httpTransport,
412
+ defaults: {
413
+ baseURL: DEFAULT_BASE_URL,
414
+ },
415
+ })
416
+
417
+ // =============================================================================
418
+ // Model Helper
419
+ // =============================================================================
420
+ export const model = route.model
421
+
422
+ export * as OpenAIChat from "./openai-chat"
@@ -0,0 +1,29 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/protocols/openai-compatible-chat.ts
2
+ import { Route, type RouteRoutedModelInput } from "../route/client"
3
+ import { Endpoint } from "../route/endpoint"
4
+ import { Framing } from "../route/framing"
5
+ import * as OpenAIChat from "./openai-chat"
6
+
7
+ const ADAPTER = "openai-compatible-chat"
8
+
9
+ export type OpenAICompatibleChatModelInput = Omit<RouteRoutedModelInput, "baseURL"> & {
10
+ readonly baseURL: string
11
+ }
12
+
13
+ /**
14
+ * Route for non-OpenAI providers that expose an OpenAI Chat-compatible
15
+ * `/chat/completions` endpoint. Reuses `OpenAIChat.protocol` end-to-end and
16
+ * overrides only the route id so providers can be resolved per-family without
17
+ * colliding with native OpenAI. The model carries the host on `baseURL`,
18
+ * supplied by whichever profile/provider helper builds it.
19
+ */
20
+ export const route = Route.make({
21
+ id: ADAPTER,
22
+ protocol: OpenAIChat.protocol,
23
+ endpoint: Endpoint.path("/chat/completions"),
24
+ framing: Framing.sse,
25
+ })
26
+
27
+ export const model = Route.model<OpenAICompatibleChatModelInput>(route)
28
+
29
+ export * as OpenAICompatibleChat from "./openai-compatible-chat"
@@ -0,0 +1,204 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/protocols/shared.ts
2
+ import { Buffer } from "node:buffer"
3
+ import { Effect, Schema, Stream } from "effect"
4
+ import * as Sse from "effect/unstable/encoding/Sse"
5
+ import { Headers, HttpClientRequest } from "effect/unstable/http"
6
+ import {
7
+ InvalidProviderOutputReason,
8
+ InvalidRequestReason,
9
+ LLMError,
10
+ type ContentPart,
11
+ type LLMRequest,
12
+ type MediaPart,
13
+ type ToolResultPart,
14
+ } from "../schema"
15
+
16
+ export const Json = Schema.fromJsonString(Schema.Unknown)
17
+ export const decodeJson = Schema.decodeUnknownSync(Json)
18
+ export const encodeJson = Schema.encodeSync(Json)
19
+ export const JsonObject = Schema.Record(Schema.String, Schema.Unknown)
20
+ export const optionalArray = <const S extends Schema.Top>(schema: S) => Schema.optional(Schema.Array(schema))
21
+ export const optionalNull = <const S extends Schema.Top>(schema: S) => Schema.optional(Schema.NullOr(schema))
22
+
23
+ export const isRecord = (value: unknown): value is Record<string, unknown> =>
24
+ typeof value === "object" && value !== null && !Array.isArray(value)
25
+
26
+ export interface ToolAccumulator {
27
+ readonly id: string
28
+ readonly name: string
29
+ readonly input: string
30
+ }
31
+
32
+ export const totalTokens = (
33
+ inputTokens: number | undefined,
34
+ outputTokens: number | undefined,
35
+ total: number | undefined,
36
+ ) => {
37
+ if (total !== undefined) return total
38
+ if (inputTokens === undefined && outputTokens === undefined) return undefined
39
+ return (inputTokens ?? 0) + (outputTokens ?? 0)
40
+ }
41
+
42
+ export const subtractTokens = (total: number | undefined, subtrahend: number | undefined): number | undefined => {
43
+ if (total === undefined) return undefined
44
+ if (subtrahend === undefined) return total
45
+ return Math.max(0, total - subtrahend)
46
+ }
47
+
48
+ export const sumTokens = (...values: ReadonlyArray<number | undefined>): number | undefined => {
49
+ if (values.every((value) => value === undefined)) return undefined
50
+ return values.reduce<number>((acc, value) => acc + (value ?? 0), 0)
51
+ }
52
+
53
+ export const eventError = (route: string, message: string, raw?: string) =>
54
+ new LLMError({
55
+ module: "ProviderShared",
56
+ method: "stream",
57
+ reason: new InvalidProviderOutputReason({ route, message, raw }),
58
+ })
59
+
60
+ export const parseJson = (route: string, input: string, message: string) =>
61
+ Effect.try({
62
+ try: () => decodeJson(input),
63
+ catch: () => eventError(route, message, input),
64
+ })
65
+
66
+ export const joinText = (parts: ReadonlyArray<{ readonly text: string }>) => parts.map((part) => part.text).join("\n")
67
+
68
+ export const parseToolInput = (route: string, name: string, raw: string) =>
69
+ parseJson(route, raw || "{}", `Invalid JSON input for ${route} tool call ${name}`)
70
+
71
+ export const mediaBytes = (part: MediaPart) =>
72
+ typeof part.data === "string" ? part.data : Buffer.from(part.data).toString("base64")
73
+
74
+ export const trimBaseUrl = (value: string) => value.replace(/\/+$/, "")
75
+
76
+ /**
77
+ * Redact image payloads before a tool result is serialised into the LLM
78
+ * context.
79
+ *
80
+ * Drivers like `computer.screenshot` and `browser.screenshot` return their
81
+ * capture as a base64-encoded string inside a result object that also carries
82
+ * `mimeType`, `width`, and `height`. The base64 may run into the megabytes —
83
+ * fine for the UI (we render it as an `<img>`), useless for a text-only LLM
84
+ * (the model can't decode bytes, and stuffing them into a `role: tool` text
85
+ * frame eats tens of thousands of tokens and routinely overflows the context
86
+ * window on the very next turn).
87
+ *
88
+ * We detect the image case structurally (any object with `mimeType: "image/*"`)
89
+ * and replace the base64 field with a short marker. The model still receives
90
+ * the diagnostic fields — width/height/mime — which are what it needs to
91
+ * coordinate click/move follow-ups. The original event delivered to the UI
92
+ * is untouched, so the image preview still renders.
93
+ *
94
+ * NOTE: Future vision-capable transports should re-promote the screenshot
95
+ * into a proper `image_url` content part on the *next* user turn instead of
96
+ * smuggling raw bytes through a tool-result text frame.
97
+ */
98
+ const IMAGE_BASE64_FIELDS = new Set(["imageBase64", "base64", "data"])
99
+
100
+ const isImageResult = (value: unknown): value is { mimeType: string } & Record<string, unknown> =>
101
+ typeof value === "object" &&
102
+ value !== null &&
103
+ !Array.isArray(value) &&
104
+ typeof (value as { mimeType?: unknown }).mimeType === "string" &&
105
+ ((value as { mimeType: string }).mimeType).startsWith("image/")
106
+
107
+ const redactImagePayload = (value: unknown): unknown => {
108
+ if (Array.isArray(value)) return value.map(redactImagePayload)
109
+ if (!value || typeof value !== "object") return value
110
+ if (isImageResult(value)) {
111
+ const out: Record<string, unknown> = {}
112
+ for (const [k, v] of Object.entries(value)) {
113
+ if (IMAGE_BASE64_FIELDS.has(k) && typeof v === "string") {
114
+ out[k] = `<image elided; ${v.length} chars base64 already shown to user>`
115
+ continue
116
+ }
117
+ out[k] = v
118
+ }
119
+ return out
120
+ }
121
+ const out: Record<string, unknown> = {}
122
+ for (const [k, v] of Object.entries(value)) out[k] = redactImagePayload(v)
123
+ return out
124
+ }
125
+
126
+ export const toolResultText = (part: ToolResultPart) => {
127
+ if (part.result.type === "text" || part.result.type === "error") return String(part.result.value)
128
+ return encodeJson(redactImagePayload(part.result.value))
129
+ }
130
+
131
+ export const errorText = (error: unknown) => {
132
+ if (error instanceof Error) return error.message
133
+ if (typeof error === "string") return error
134
+ if (typeof error === "number" || typeof error === "boolean" || typeof error === "bigint") return String(error)
135
+ if (error === null) return "null"
136
+ if (error === undefined) return "undefined"
137
+ return "Unknown stream error"
138
+ }
139
+
140
+ export const sseFraming = (bytes: Stream.Stream<Uint8Array, LLMError>): Stream.Stream<string, LLMError> =>
141
+ bytes.pipe(
142
+ Stream.decodeText(),
143
+ Stream.pipeThroughChannel(Sse.decode()),
144
+ Stream.catchTag("Retry", () => Stream.empty),
145
+ Stream.filter((event) => event.data.length > 0 && event.data !== "[DONE]"),
146
+ Stream.map((event) => event.data),
147
+ )
148
+
149
+ export const invalidRequest = (message: string) =>
150
+ new LLMError({
151
+ module: "ProviderShared",
152
+ method: "request",
153
+ reason: new InvalidRequestReason({ message }),
154
+ })
155
+
156
+ export const matchToolChoice = <Auto, None, Required, Tool>(
157
+ route: string,
158
+ toolChoice: NonNullable<LLMRequest["toolChoice"]>,
159
+ cases: {
160
+ readonly auto: () => Auto
161
+ readonly none: () => None
162
+ readonly required: () => Required
163
+ readonly tool: (name: string) => Tool
164
+ },
165
+ ) =>
166
+ Effect.gen(function* () {
167
+ if (toolChoice.type === "auto") return cases.auto()
168
+ if (toolChoice.type === "none") return cases.none()
169
+ if (toolChoice.type === "required") return cases.required()
170
+ if (!toolChoice.name) return yield* invalidRequest(`${route} tool choice requires a tool name`)
171
+ return cases.tool(toolChoice.name)
172
+ })
173
+
174
+ type ContentType = ContentPart["type"]
175
+
176
+ const formatContentTypes = (types: ReadonlyArray<ContentType>) => {
177
+ if (types.length <= 1) return types[0] ?? ""
178
+ if (types.length === 2) return `${types[0]} and ${types[1]}`
179
+ return `${types.slice(0, -1).join(", ")}, and ${types.at(-1)}`
180
+ }
181
+
182
+ export const supportsContent = <const Type extends ContentType>(
183
+ part: ContentPart,
184
+ types: ReadonlyArray<Type>,
185
+ ): part is Extract<ContentPart, { readonly type: Type }> => (types as ReadonlyArray<ContentType>).includes(part.type)
186
+
187
+ export const unsupportedContent = (
188
+ route: string,
189
+ role: LLMRequest["messages"][number]["role"],
190
+ types: ReadonlyArray<ContentType>,
191
+ ) => invalidRequest(`${route} ${role} messages only support ${formatContentTypes(types)} content for now`)
192
+
193
+ export const validateWith =
194
+ <A, I, E extends { readonly message: string }>(decode: (input: I) => Effect.Effect<A, E>) =>
195
+ (payload: I) =>
196
+ decode(payload).pipe(Effect.mapError((error) => invalidRequest(error.message)))
197
+
198
+ export const jsonPost = (input: { readonly url: string; readonly body: string; readonly headers?: Headers.Input }) =>
199
+ HttpClientRequest.post(input.url).pipe(
200
+ HttpClientRequest.setHeaders(Headers.set(Headers.fromInput(input.headers), "content-type", "application/json")),
201
+ HttpClientRequest.bodyText(input.body, "application/json"),
202
+ )
203
+
204
+ export * as ProviderShared from "./shared"