@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,396 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/route/executor.ts
2
+ import { Cause, Context, Effect, Layer, Random } from "effect"
3
+ import {
4
+ FetchHttpClient,
5
+ Headers,
6
+ HttpClient,
7
+ HttpClientError,
8
+ HttpClientRequest,
9
+ HttpClientResponse,
10
+ } from "effect/unstable/http"
11
+ import {
12
+ AuthenticationReason,
13
+ ContentPolicyReason,
14
+ ContextOverflowReason,
15
+ HttpContext,
16
+ HttpRateLimitDetails,
17
+ HttpRequestDetails,
18
+ HttpResponseDetails,
19
+ InvalidRequestReason,
20
+ LLMError,
21
+ ProviderInternalReason,
22
+ QuotaExceededReason,
23
+ RateLimitReason,
24
+ TransportReason,
25
+ UnknownProviderReason,
26
+ } from "../schema"
27
+ import { extractOverflowNumbers, isOverflowBody, isOverflowMessage, isOverflowStatus } from "./overflow-detect"
28
+
29
+ export interface Interface {
30
+ readonly execute: (
31
+ request: HttpClientRequest.HttpClientRequest,
32
+ ) => Effect.Effect<HttpClientResponse.HttpClientResponse, LLMError>
33
+ }
34
+
35
+ export class Service extends Context.Service<Service, Interface>()("@tinyweb-agent/LLM/RequestExecutor") {}
36
+
37
+ const BODY_LIMIT = 16_384
38
+ const MAX_RETRIES = 2
39
+ const BASE_DELAY_MS = 500
40
+ const MAX_DELAY_MS = 10_000
41
+ const REDACTED = "<redacted>"
42
+
43
+ const SENSITIVE_NAME_SOURCE =
44
+ "authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|credential|signature|x-amz-signature"
45
+ const SENSITIVE_NAME = new RegExp(SENSITIVE_NAME_SOURCE, "i")
46
+ const SHORT_QUERY_NAME = /^(key|sig)$/i
47
+ const SENSITIVE_BODY_FIELD = new RegExp(`(?:${SENSITIVE_NAME_SOURCE}|key)`, "i")
48
+ const REDACT_JSON_FIELD = new RegExp(`("(?:${SENSITIVE_BODY_FIELD.source})"\\s*:\\s*)"[^"]*"`, "gi")
49
+ const REDACT_QUERY_FIELD = new RegExp(`((?:${SENSITIVE_BODY_FIELD.source})=)[^&\\s"]+`, "gi")
50
+
51
+ const isSensitiveHeaderName = (name: string) => SENSITIVE_NAME.test(name)
52
+
53
+ const isSensitiveQueryName = (name: string) => isSensitiveHeaderName(name) || SHORT_QUERY_NAME.test(name)
54
+
55
+ const redactHeaders = (headers: Headers.Headers, redactedNames: ReadonlyArray<string | RegExp>) =>
56
+ Object.fromEntries(
57
+ Object.entries(Headers.redact(headers, [...redactedNames, SENSITIVE_NAME])).map(([name, value]) => [
58
+ name,
59
+ String(value),
60
+ ]),
61
+ )
62
+
63
+ const redactUrl = (value: string) => {
64
+ if (!URL.canParse(value)) return REDACTED
65
+ const url = new URL(value)
66
+ url.searchParams.forEach((_, key) => {
67
+ if (isSensitiveQueryName(key)) url.searchParams.set(key, REDACTED)
68
+ })
69
+ return url.toString()
70
+ }
71
+
72
+ const normalizedHeaders = (headers: Headers.Headers) =>
73
+ Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]))
74
+
75
+ const requestId = (headers: Record<string, string>) => {
76
+ return (
77
+ headers["x-request-id"] ??
78
+ headers["request-id"] ??
79
+ headers["x-amzn-requestid"] ??
80
+ headers["x-amz-request-id"] ??
81
+ headers["x-goog-request-id"] ??
82
+ headers["cf-ray"]
83
+ )
84
+ }
85
+
86
+ const retryableStatus = (status: number) => status === 429 || status === 503 || status === 504 || status === 529
87
+
88
+ const retryAfterMs = (headers: Record<string, string>) => {
89
+ const millis = Number(headers["retry-after-ms"])
90
+ if (Number.isFinite(millis)) return Math.max(0, millis)
91
+
92
+ const value = headers["retry-after"]
93
+ if (!value) return undefined
94
+
95
+ const seconds = Number(value)
96
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000)
97
+
98
+ const date = Date.parse(value)
99
+ if (!Number.isNaN(date)) return Math.max(0, date - Date.now())
100
+ return undefined
101
+ }
102
+
103
+ const addRateLimitValue = (target: Record<string, string>, key: string, value: string) => {
104
+ if (key.length > 0) target[key] = value
105
+ }
106
+
107
+ const rateLimitDetails = (headers: Record<string, string>, retryAfter: number | undefined) => {
108
+ const limit: Record<string, string> = {}
109
+ const remaining: Record<string, string> = {}
110
+ const reset: Record<string, string> = {}
111
+
112
+ Object.entries(headers).forEach(([name, value]) => {
113
+ const openaiLimit = /^x-ratelimit-limit-(.+)$/.exec(name)?.[1]
114
+ if (openaiLimit) return addRateLimitValue(limit, openaiLimit, value)
115
+
116
+ const openaiRemaining = /^x-ratelimit-remaining-(.+)$/.exec(name)?.[1]
117
+ if (openaiRemaining) return addRateLimitValue(remaining, openaiRemaining, value)
118
+
119
+ const openaiReset = /^x-ratelimit-reset-(.+)$/.exec(name)?.[1]
120
+ if (openaiReset) return addRateLimitValue(reset, openaiReset, value)
121
+
122
+ const anthropic = /^anthropic-ratelimit-(.+)-(limit|remaining|reset)$/.exec(name)
123
+ if (!anthropic) return
124
+ if (anthropic[2] === "limit") return addRateLimitValue(limit, anthropic[1], value)
125
+ if (anthropic[2] === "remaining") return addRateLimitValue(remaining, anthropic[1], value)
126
+ return addRateLimitValue(reset, anthropic[1], value)
127
+ })
128
+
129
+ if (
130
+ retryAfter === undefined &&
131
+ Object.keys(limit).length === 0 &&
132
+ Object.keys(remaining).length === 0 &&
133
+ Object.keys(reset).length === 0
134
+ )
135
+ return undefined
136
+
137
+ return new HttpRateLimitDetails({
138
+ retryAfterMs: retryAfter,
139
+ limit: Object.keys(limit).length === 0 ? undefined : limit,
140
+ remaining: Object.keys(remaining).length === 0 ? undefined : remaining,
141
+ reset: Object.keys(reset).length === 0 ? undefined : reset,
142
+ })
143
+ }
144
+
145
+ const requestDetails = (request: HttpClientRequest.HttpClientRequest, redactedNames: ReadonlyArray<string | RegExp>) =>
146
+ new HttpRequestDetails({
147
+ method: request.method,
148
+ url: redactUrl(request.url),
149
+ headers: redactHeaders(request.headers, redactedNames),
150
+ })
151
+
152
+ const responseDetails = (
153
+ response: HttpClientResponse.HttpClientResponse,
154
+ redactedNames: ReadonlyArray<string | RegExp>,
155
+ ) =>
156
+ new HttpResponseDetails({
157
+ status: response.status,
158
+ headers: redactHeaders(response.headers, redactedNames),
159
+ })
160
+
161
+ const secretValues = (request: HttpClientRequest.HttpClientRequest) => {
162
+ const values = new Set<string>()
163
+ const add = (value: string) => {
164
+ if (value.length < 4) return
165
+ values.add(value)
166
+ values.add(encodeURIComponent(value))
167
+ }
168
+
169
+ Object.entries(request.headers).forEach(([name, value]) => {
170
+ if (!isSensitiveHeaderName(name)) return
171
+ add(value)
172
+ const bearer = /^Bearer\s+(.+)$/i.exec(value)?.[1]
173
+ if (bearer) add(bearer)
174
+ })
175
+
176
+ if (!URL.canParse(request.url)) return values
177
+ new URL(request.url).searchParams.forEach((value, key) => {
178
+ if (isSensitiveQueryName(key)) add(value)
179
+ })
180
+ return values
181
+ }
182
+
183
+ const redactBody = (body: string, request: HttpClientRequest.HttpClientRequest) =>
184
+ Array.from(secretValues(request)).reduce(
185
+ (text, secret) => text.split(secret).join(REDACTED),
186
+ body.replace(REDACT_JSON_FIELD, `$1"${REDACTED}"`).replace(REDACT_QUERY_FIELD, `$1${REDACTED}`),
187
+ )
188
+
189
+ const responseBody = (body: string | void, request: HttpClientRequest.HttpClientRequest) => {
190
+ if (body === undefined) return {}
191
+ const redacted = redactBody(body, request)
192
+ if (redacted.length <= BODY_LIMIT) return { body: redacted }
193
+ return { body: redacted.slice(0, BODY_LIMIT), bodyTruncated: true }
194
+ }
195
+
196
+ const providerMessage = (status: number, body: { readonly body?: string }) => {
197
+ if (body.body && body.body.length <= 500) return `Provider request failed with HTTP ${status}: ${body.body}`
198
+ return `Provider request failed with HTTP ${status}`
199
+ }
200
+
201
+ const responseHttp = (input: {
202
+ readonly request: HttpClientRequest.HttpClientRequest
203
+ readonly response: HttpClientResponse.HttpClientResponse
204
+ readonly redactedNames: ReadonlyArray<string | RegExp>
205
+ readonly body: ReturnType<typeof responseBody>
206
+ readonly requestId?: string | undefined
207
+ readonly rateLimit?: HttpRateLimitDetails | undefined
208
+ }) =>
209
+ new HttpContext({
210
+ request: requestDetails(input.request, input.redactedNames),
211
+ response: responseDetails(input.response, input.redactedNames),
212
+ ...input.body,
213
+ requestId: input.requestId,
214
+ rateLimit: input.rateLimit,
215
+ })
216
+
217
+ const parseJsonBody = (body: string): unknown => {
218
+ if (body.length === 0) return undefined
219
+ try {
220
+ return JSON.parse(body)
221
+ } catch {
222
+ return undefined
223
+ }
224
+ }
225
+
226
+ const isOverflow = (status: number, message: string, body: string) => {
227
+ if (isOverflowStatus(status)) return true
228
+ if (isOverflowMessage(message)) return true
229
+ if (body.length > 0 && isOverflowMessage(body)) return true
230
+ return isOverflowBody(parseJsonBody(body))
231
+ }
232
+
233
+ const overflowReason = (input: { message: string; body: string; http: HttpContext }) => {
234
+ const numbers = extractOverflowNumbers(input.message) ?? extractOverflowNumbers(input.body)
235
+ return new ContextOverflowReason({
236
+ message: input.message,
237
+ promptTokens: numbers?.promptTokens,
238
+ contextWindow: numbers?.contextWindow,
239
+ http: input.http,
240
+ })
241
+ }
242
+
243
+ const statusReason = (input: {
244
+ readonly status: number
245
+ readonly message: string
246
+ readonly retryAfterMs?: number | undefined
247
+ readonly rateLimit?: HttpRateLimitDetails | undefined
248
+ readonly http: HttpContext
249
+ }) => {
250
+ const body = input.http.body ?? ""
251
+ if (isOverflow(input.status, input.message, body)) {
252
+ return overflowReason({ message: input.message, body, http: input.http })
253
+ }
254
+ if (/content[-_\s]?policy|content_filter|safety/i.test(body)) {
255
+ return new ContentPolicyReason({ message: input.message, http: input.http })
256
+ }
257
+ if (input.status === 401) {
258
+ return new AuthenticationReason({ message: input.message, kind: "invalid", http: input.http })
259
+ }
260
+ if (input.status === 403) {
261
+ return new AuthenticationReason({ message: input.message, kind: "insufficient-permissions", http: input.http })
262
+ }
263
+ if (input.status === 429) {
264
+ if (/insufficient[-_\s]?quota|quota[-_\s]?exceeded/i.test(body)) {
265
+ return new QuotaExceededReason({ message: input.message, http: input.http })
266
+ }
267
+ return new RateLimitReason({
268
+ message: input.message,
269
+ retryAfterMs: input.retryAfterMs,
270
+ rateLimit: input.rateLimit,
271
+ http: input.http,
272
+ })
273
+ }
274
+ if (input.status === 400 || input.status === 404 || input.status === 409 || input.status === 422) {
275
+ return new InvalidRequestReason({ message: input.message, http: input.http })
276
+ }
277
+ if (input.status >= 500 || retryableStatus(input.status)) {
278
+ return new ProviderInternalReason({
279
+ message: input.message,
280
+ status: input.status,
281
+ retryAfterMs: input.retryAfterMs,
282
+ http: input.http,
283
+ })
284
+ }
285
+ return new UnknownProviderReason({ message: input.message, status: input.status, http: input.http })
286
+ }
287
+
288
+ const statusError =
289
+ (request: HttpClientRequest.HttpClientRequest, redactedNames: ReadonlyArray<string | RegExp>) =>
290
+ (response: HttpClientResponse.HttpClientResponse) =>
291
+ Effect.gen(function* () {
292
+ if (response.status < 400) return response
293
+ const body = yield* response.text.pipe(Effect.catch(() => Effect.void))
294
+ const headers = normalizedHeaders(response.headers)
295
+ const retryAfter = retryAfterMs(headers)
296
+ const rateLimit = rateLimitDetails(headers, retryAfter)
297
+ const details = responseBody(body, request)
298
+ return yield* new LLMError({
299
+ module: "RequestExecutor",
300
+ method: "execute",
301
+ reason: statusReason({
302
+ status: response.status,
303
+ message: providerMessage(response.status, details),
304
+ retryAfterMs: retryAfter,
305
+ rateLimit,
306
+ http: responseHttp({
307
+ request,
308
+ response,
309
+ redactedNames,
310
+ body: details,
311
+ requestId: requestId(headers),
312
+ rateLimit,
313
+ }),
314
+ }),
315
+ })
316
+ })
317
+
318
+ const toHttpError = (redactedNames: ReadonlyArray<string | RegExp>) => (error: unknown) => {
319
+ const transportError = (input: {
320
+ readonly message: string
321
+ readonly kind?: string | undefined
322
+ readonly request?: HttpClientRequest.HttpClientRequest | undefined
323
+ }) =>
324
+ new LLMError({
325
+ module: "RequestExecutor",
326
+ method: "execute",
327
+ reason: new TransportReason({
328
+ message: input.message,
329
+ kind: input.kind,
330
+ url: input.request ? redactUrl(input.request.url) : undefined,
331
+ http: input.request ? new HttpContext({ request: requestDetails(input.request, redactedNames) }) : undefined,
332
+ }),
333
+ })
334
+
335
+ if (Cause.isTimeoutError(error)) {
336
+ return transportError({ message: error.message, kind: "Timeout" })
337
+ }
338
+ if (!HttpClientError.isHttpClientError(error)) {
339
+ return transportError({ message: "HTTP transport failed" })
340
+ }
341
+ const request = "request" in error ? error.request : undefined
342
+ if (error.reason._tag === "TransportError") {
343
+ return transportError({
344
+ message: error.reason.description ?? "HTTP transport failed",
345
+ kind: error.reason._tag,
346
+ request,
347
+ })
348
+ }
349
+ return transportError({
350
+ message: `HTTP transport failed: ${error.reason._tag}`,
351
+ kind: error.reason._tag,
352
+ request,
353
+ })
354
+ }
355
+
356
+ const retryDelay = (error: LLMError, attempt: number) => {
357
+ if (error.retryAfterMs !== undefined) return Effect.succeed(Math.min(error.retryAfterMs, MAX_DELAY_MS))
358
+ return Random.nextBetween(
359
+ Math.min(BASE_DELAY_MS * 2 ** attempt * 0.8, MAX_DELAY_MS),
360
+ Math.min(BASE_DELAY_MS * 2 ** attempt * 1.2, MAX_DELAY_MS),
361
+ ).pipe(Effect.map((delay) => Math.round(delay)))
362
+ }
363
+
364
+ const retryStatusFailures = <A, R>(
365
+ effect: Effect.Effect<A, LLMError, R>,
366
+ retries = MAX_RETRIES,
367
+ attempt = 0,
368
+ ): Effect.Effect<A, LLMError, R> =>
369
+ Effect.catchTag(effect, "LLM.Error", (error): Effect.Effect<A, LLMError, R> => {
370
+ if (!error.retryable || retries <= 0) return Effect.fail(error)
371
+ return retryDelay(error, attempt).pipe(
372
+ Effect.flatMap((delay) => Effect.sleep(delay)),
373
+ Effect.flatMap(() => retryStatusFailures(effect, retries - 1, attempt + 1)),
374
+ )
375
+ })
376
+
377
+ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient> = Layer.effect(
378
+ Service,
379
+ Effect.gen(function* () {
380
+ const http = yield* HttpClient.HttpClient
381
+ const executeOnce = (request: HttpClientRequest.HttpClientRequest) =>
382
+ Effect.gen(function* () {
383
+ const redactedNames = yield* Headers.CurrentRedactedNames
384
+ return yield* http
385
+ .execute(request)
386
+ .pipe(Effect.mapError(toHttpError(redactedNames)), Effect.flatMap(statusError(request, redactedNames)))
387
+ })
388
+ return Service.of({
389
+ execute: (request) => retryStatusFailures(executeOnce(request)),
390
+ })
391
+ }),
392
+ )
393
+
394
+ export const defaultLayer = layer.pipe(Layer.provide(FetchHttpClient.layer))
395
+
396
+ export * as RequestExecutor from "./executor"
@@ -0,0 +1,13 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/route/framing.ts
2
+ import type { Stream } from "effect"
3
+ import * as ProviderShared from "../protocols/shared"
4
+ import type { LLMError } from "../schema"
5
+
6
+ export interface Framing<Frame> {
7
+ readonly id: string
8
+ readonly frame: (bytes: Stream.Stream<Uint8Array, LLMError>) => Stream.Stream<Frame, LLMError>
9
+ }
10
+
11
+ export const sse: Framing<string> = { id: "sse", frame: ProviderShared.sseFraming }
12
+
13
+ export * as Framing from "./framing"
@@ -0,0 +1,74 @@
1
+ // Adapted from opencode@v1.14.48 packages/opencode/src/provider/error.ts
2
+ //
3
+ // Context-overflow detection. Centralised here so route/executor.ts can map
4
+ // provider 4xx responses to ContextOverflowReason instead of generic
5
+ // InvalidRequestReason, letting the agent layer trigger auto-compaction.
6
+ //
7
+ // Original opencode source attributes the regex catalogue to:
8
+ // https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/overflow.ts
9
+
10
+ const OVERFLOW_PATTERNS: ReadonlyArray<RegExp> = [
11
+ /prompt is too long/i, // Anthropic
12
+ /input is too long for requested model/i, // Amazon Bedrock
13
+ /exceeds the context window/i, // OpenAI
14
+ /input token count.*exceeds the maximum/i, // Google (Gemini)
15
+ /maximum prompt length is \d+/i, // xAI (Grok)
16
+ /reduce the length of the messages/i, // Groq
17
+ /maximum context length is \d+ tokens/i, // OpenRouter, DeepSeek, vLLM
18
+ /exceeds the limit of \d+/i, // GitHub Copilot
19
+ /exceeds the available context size/i, // llama.cpp server
20
+ /greater than the context length/i, // LM Studio
21
+ /context window exceeds limit/i, // MiniMax
22
+ /exceeded model token limit/i, // Kimi, Moonshot
23
+ /context[_ ]length[_ ]exceeded/i, // Generic OpenAI-style code
24
+ /request entity too large/i, // HTTP 413
25
+ /context length is only \d+ tokens/i, // vLLM
26
+ /input length.*exceeds.*context length/i, // vLLM
27
+ /prompt too long; exceeded (?:max )?context length/i, // Ollama
28
+ /too large for model with \d+ maximum context length/i, // Mistral
29
+ /model_context_window_exceeded/i, // z.ai
30
+ ]
31
+
32
+ const NO_BODY_4XX = /^4(00|13)\s*(status code)?\s*\(no body\)/i
33
+
34
+ /** True when the provider-supplied message indicates a context-window overflow. */
35
+ export const isOverflowMessage = (message: string): boolean => {
36
+ if (OVERFLOW_PATTERNS.some((p) => p.test(message))) return true
37
+ // Cerebras / Mistral often emit empty 400 / 413 responses on overflow.
38
+ return NO_BODY_4XX.test(message)
39
+ }
40
+
41
+ /** HTTP 413 (payload too large) is always a context overflow for LLM calls. */
42
+ export const isOverflowStatus = (status: number): boolean => status === 413
43
+
44
+ const TOKENS_GT_MAX = /(\d{4,})\s*tokens?\s*[>≥]\s*(\d{4,})/i
45
+ const PROMPT_LENGTH = /prompt is too long:\s*(\d{4,})\s*tokens?\s*>\s*(\d{4,})\s*maximum/i
46
+ const INPUT_LIMIT = /input length\s*(\d{4,}).*context length\s*(\d{4,})/i
47
+
48
+ /**
49
+ * Best-effort extraction of `{ promptTokens, contextWindow }` from a provider
50
+ * error message. Returns undefined when the shape is not recognised.
51
+ */
52
+ export const extractOverflowNumbers = (
53
+ message: string,
54
+ ): { readonly promptTokens: number; readonly contextWindow: number } | undefined => {
55
+ const match = PROMPT_LENGTH.exec(message) ?? INPUT_LIMIT.exec(message) ?? TOKENS_GT_MAX.exec(message)
56
+ if (!match) return undefined
57
+ const promptTokens = Number(match[1])
58
+ const contextWindow = Number(match[2])
59
+ if (!Number.isFinite(promptTokens) || !Number.isFinite(contextWindow)) return undefined
60
+ return { promptTokens, contextWindow }
61
+ }
62
+
63
+ /**
64
+ * Detect overflow from a JSON-shaped provider error body. Returns true when
65
+ * a recognised structured signal is found (e.g. OpenAI `context_length_exceeded`).
66
+ */
67
+ export const isOverflowBody = (body: unknown): boolean => {
68
+ if (typeof body !== "object" || body === null) return false
69
+ const root = body as Record<string, unknown>
70
+ const code = (root.error as Record<string, unknown> | undefined)?.code ?? root.code
71
+ if (typeof code === "string" && /context[_ ]length[_ ]exceeded/i.test(code)) return true
72
+ if (typeof code === "string" && /model_context_window_exceeded/i.test(code)) return true
73
+ return false
74
+ }
@@ -0,0 +1,48 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/route/protocol.ts
2
+ import { Schema, type Effect } from "effect"
3
+ import type { LLMError, LLMEvent, LLMRequest, ProtocolID } from "../schema"
4
+
5
+ /**
6
+ * The semantic API contract of one model server family.
7
+ *
8
+ * A `Protocol` owns the parts of a route that are intrinsic to "what does
9
+ * this API look like": how a common `LLMRequest` becomes a provider-native
10
+ * body, what schema that body must satisfy before it is JSON-encoded, and
11
+ * how the streaming response decodes back into common `LLMEvent`s.
12
+ */
13
+ export interface Protocol<Body, Frame, Event, State> {
14
+ /** Stable id for the wire protocol implementation. */
15
+ readonly id: ProtocolID
16
+ /** Request side: schema for the provider-native body and how to build it. */
17
+ readonly body: ProtocolBody<Body>
18
+ /** Response side: streaming state machine. */
19
+ readonly stream: ProtocolStream<Frame, Event, State>
20
+ }
21
+
22
+ export interface ProtocolBody<Body> {
23
+ /** Schema for the validated provider-native body sent as the JSON request. */
24
+ readonly schema: Schema.Codec<Body, unknown>
25
+ /** Build the provider-native body from a common `LLMRequest`. */
26
+ readonly from: (request: LLMRequest) => Effect.Effect<Body, LLMError>
27
+ }
28
+
29
+ export interface ProtocolStream<Frame, Event, State> {
30
+ /** Schema for one decoded streaming event, decoded from a transport frame. */
31
+ readonly event: Schema.Codec<Event, Frame>
32
+ /** Initial parser state. Called once per response. */
33
+ readonly initial: () => State
34
+ /** Translate one event into emitted `LLMEvent`s plus the next state. */
35
+ readonly step: (state: State, event: Event) => Effect.Effect<readonly [State, ReadonlyArray<LLMEvent>], LLMError>
36
+ /** Optional request-completion signal for transports that do not end naturally. */
37
+ readonly terminal?: (event: Event) => boolean
38
+ /** Optional flush emitted when the framed stream ends. */
39
+ readonly onHalt?: (state: State) => ReadonlyArray<LLMEvent>
40
+ }
41
+
42
+ export const make = <Body, Frame, Event, State>(
43
+ input: Protocol<Body, Frame, Event, State>,
44
+ ): Protocol<Body, Frame, Event, State> => input
45
+
46
+ export const jsonEvent = <const S extends Schema.Top>(schema: S) => Schema.fromJsonString(schema)
47
+
48
+ export * as Protocol from "./protocol"
@@ -0,0 +1,123 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/route/transport/http.ts
2
+ import { Effect, Stream } from "effect"
3
+ import { Headers, HttpClientRequest } from "effect/unstable/http"
4
+ import { Auth, type Auth as AuthDef } from "../auth"
5
+ import { type Endpoint, render as renderEndpoint } from "../endpoint"
6
+ import type { Framing } from "../framing"
7
+ import type { Transport } from "./index"
8
+ import * as ProviderShared from "../../protocols/shared"
9
+ import { mergeJsonRecords, type LLMRequest } from "../../schema"
10
+
11
+ export interface JsonRequestInput<Body> {
12
+ readonly body: Body
13
+ readonly request: LLMRequest
14
+ readonly endpoint: Endpoint<Body>
15
+ readonly auth: AuthDef
16
+ readonly encodeBody: (body: Body) => string
17
+ readonly headers?: (input: { readonly request: LLMRequest }) => Record<string, string>
18
+ }
19
+
20
+ export interface JsonRequestParts<Body = unknown> {
21
+ readonly url: string
22
+ readonly jsonBody: Body | Record<string, unknown>
23
+ readonly bodyText: string
24
+ readonly headers: Headers.Headers
25
+ }
26
+
27
+ export interface HttpPrepared<Frame> {
28
+ readonly request: HttpClientRequest.HttpClientRequest
29
+ readonly framing: Framing<Frame>
30
+ }
31
+
32
+ const applyQuery = (url: string, query: Record<string, string> | undefined) => {
33
+ if (!query) return url
34
+ const next = new URL(url)
35
+ Object.entries(query).forEach(([key, value]) => next.searchParams.set(key, value))
36
+ return next.toString()
37
+ }
38
+
39
+ const bodyWithOverlay = <Body>(body: Body, request: LLMRequest, encodeBody: (body: Body) => string) =>
40
+ Effect.gen(function* () {
41
+ if (request.http?.body === undefined) return { jsonBody: body, bodyText: encodeBody(body) }
42
+ if (ProviderShared.isRecord(body)) {
43
+ const overlaid = mergeJsonRecords(body, request.http.body) ?? {}
44
+ return { jsonBody: overlaid, bodyText: ProviderShared.encodeJson(overlaid) }
45
+ }
46
+ return yield* ProviderShared.invalidRequest("http.body can only overlay JSON object request bodies")
47
+ })
48
+
49
+ export const jsonRequestParts = <Body>(input: JsonRequestInput<Body>) =>
50
+ Effect.gen(function* () {
51
+ const url = applyQuery(
52
+ renderEndpoint(input.endpoint, { request: input.request, body: input.body }).toString(),
53
+ input.request.http?.query,
54
+ )
55
+ const body = yield* bodyWithOverlay(input.body, input.request, input.encodeBody)
56
+ const headers = yield* Auth.toEffect(Auth.isAuth(input.request.model.auth) ? input.request.model.auth : input.auth)(
57
+ {
58
+ request: input.request,
59
+ method: "POST",
60
+ url,
61
+ body: body.bodyText,
62
+ headers: Headers.fromInput({
63
+ ...(input.headers?.({ request: input.request }) ?? {}),
64
+ ...input.request.model.headers,
65
+ ...input.request.http?.headers,
66
+ }),
67
+ },
68
+ )
69
+ return { url, jsonBody: body.jsonBody, bodyText: body.bodyText, headers }
70
+ })
71
+
72
+ export interface HttpJsonInput<Body, Frame> {
73
+ readonly endpoint: Endpoint<Body>
74
+ readonly auth?: AuthDef
75
+ readonly framing: Framing<Frame>
76
+ readonly encodeBody: (body: Body) => string
77
+ readonly headers?: (input: { readonly request: LLMRequest }) => Record<string, string>
78
+ }
79
+
80
+ export type HttpJsonPatch<Body, Frame> = Partial<HttpJsonInput<Body, Frame>>
81
+
82
+ export interface HttpJsonTransport<Body, Frame> extends Transport<Body, HttpPrepared<Frame>, Frame> {
83
+ readonly with: (patch: HttpJsonPatch<Body, Frame>) => HttpJsonTransport<Body, Frame>
84
+ }
85
+
86
+ export const httpJson = <Body, Frame>(input: HttpJsonInput<Body, Frame>): HttpJsonTransport<Body, Frame> => ({
87
+ id: "http-json",
88
+ with: (patch) => httpJson({ ...input, ...patch }),
89
+ prepare: (body, request) =>
90
+ jsonRequestParts({
91
+ body,
92
+ request,
93
+ endpoint: input.endpoint,
94
+ auth: input.auth ?? Auth.bearer(),
95
+ encodeBody: input.encodeBody,
96
+ headers: input.headers,
97
+ }).pipe(
98
+ Effect.map((parts) => ({
99
+ request: ProviderShared.jsonPost({ url: parts.url, body: parts.bodyText, headers: parts.headers }),
100
+ framing: input.framing,
101
+ })),
102
+ ),
103
+ frames: (prepared, request, runtime) =>
104
+ Stream.unwrap(
105
+ runtime.http
106
+ .execute(prepared.request)
107
+ .pipe(
108
+ Effect.map((response) =>
109
+ prepared.framing.frame(
110
+ response.stream.pipe(
111
+ Stream.mapError((error) =>
112
+ ProviderShared.eventError(
113
+ `${request.model.provider}/${request.model.route}`,
114
+ `Failed to read ${request.model.provider}/${request.model.route} stream`,
115
+ ProviderShared.errorText(error),
116
+ ),
117
+ ),
118
+ ),
119
+ ),
120
+ ),
121
+ ),
122
+ ),
123
+ })
@@ -0,0 +1,21 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/route/transport/index.ts
2
+ // WebSocket transport intentionally omitted at v1 — HTTP only.
3
+ import type { Effect, Stream } from "effect"
4
+ import type { Interface as RequestExecutorInterface } from "../executor"
5
+ import type { LLMError, LLMRequest } from "../../schema"
6
+
7
+ export interface TransportRuntime {
8
+ readonly http: RequestExecutorInterface
9
+ }
10
+
11
+ export interface Transport<Body, Prepared, Frame> {
12
+ readonly id: string
13
+ readonly prepare: (body: Body, request: LLMRequest) => Effect.Effect<Prepared, LLMError>
14
+ readonly frames: (
15
+ prepared: Prepared,
16
+ request: LLMRequest,
17
+ runtime: TransportRuntime,
18
+ ) => Stream.Stream<Frame, LLMError>
19
+ }
20
+
21
+ export * as HttpTransport from "./http"