@tinyweb_dev/agent-framework-llm 0.1.0 → 0.3.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 (177) hide show
  1. package/dist/cache-policy.d.ts +3 -0
  2. package/dist/cache-policy.d.ts.map +1 -0
  3. package/dist/index.cjs +2956 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.ts +23 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +2831 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/llm.cjs +1718 -0
  10. package/dist/llm.cjs.map +1 -0
  11. package/dist/llm.d.ts +284 -0
  12. package/dist/llm.d.ts.map +1 -0
  13. package/dist/llm.js +1692 -0
  14. package/dist/llm.js.map +1 -0
  15. package/dist/protocols/openai-chat.cjs +2443 -0
  16. package/dist/protocols/openai-chat.cjs.map +1 -0
  17. package/dist/protocols/openai-chat.d.ts +357 -0
  18. package/dist/protocols/openai-chat.d.ts.map +1 -0
  19. package/dist/protocols/openai-chat.js +2414 -0
  20. package/dist/protocols/openai-chat.js.map +1 -0
  21. package/dist/protocols/openai-compatible-chat.cjs +2443 -0
  22. package/dist/protocols/openai-compatible-chat.cjs.map +1 -0
  23. package/dist/protocols/openai-compatible-chat.d.ts +77 -0
  24. package/dist/protocols/openai-compatible-chat.d.ts.map +1 -0
  25. package/dist/protocols/openai-compatible-chat.js +2419 -0
  26. package/dist/protocols/openai-compatible-chat.js.map +1 -0
  27. package/dist/protocols/shared.cjs +904 -0
  28. package/dist/protocols/shared.cjs.map +1 -0
  29. package/dist/protocols/shared.d.ts +51 -0
  30. package/dist/protocols/shared.d.ts.map +1 -0
  31. package/dist/protocols/shared.js +857 -0
  32. package/dist/protocols/shared.js.map +1 -0
  33. package/dist/protocols/utils/openai-options.d.ts +15 -0
  34. package/dist/protocols/utils/openai-options.d.ts.map +1 -0
  35. package/dist/protocols/utils/tool-stream.d.ts +78 -0
  36. package/dist/protocols/utils/tool-stream.d.ts.map +1 -0
  37. package/dist/provider.cjs +20 -0
  38. package/dist/provider.cjs.map +1 -0
  39. package/dist/provider.d.ts +19 -0
  40. package/dist/provider.d.ts.map +1 -0
  41. package/dist/provider.js +17 -0
  42. package/dist/provider.js.map +1 -0
  43. package/{src/providers/openai-compatible-profile.ts → dist/providers/openai-compatible-profile.cjs} +12 -12
  44. package/dist/providers/openai-compatible-profile.cjs.map +1 -0
  45. package/dist/providers/openai-compatible-profile.d.ts +52 -0
  46. package/dist/providers/openai-compatible-profile.d.ts.map +1 -0
  47. package/dist/providers/openai-compatible-profile.js +21 -0
  48. package/dist/providers/openai-compatible-profile.js.map +1 -0
  49. package/dist/providers/openai-compatible.cjs +2533 -0
  50. package/dist/providers/openai-compatible.cjs.map +1 -0
  51. package/dist/providers/openai-compatible.d.ts +128 -0
  52. package/dist/providers/openai-compatible.d.ts.map +1 -0
  53. package/dist/providers/openai-compatible.js +2495 -0
  54. package/dist/providers/openai-compatible.js.map +1 -0
  55. package/dist/providers/openai-options.cjs +797 -0
  56. package/dist/providers/openai-options.cjs.map +1 -0
  57. package/dist/providers/openai-options.d.ts +29 -0
  58. package/dist/providers/openai-options.d.ts.map +1 -0
  59. package/dist/providers/openai-options.js +792 -0
  60. package/dist/providers/openai-options.js.map +1 -0
  61. package/dist/providers/openai.cjs +2517 -0
  62. package/dist/providers/openai.cjs.map +1 -0
  63. package/dist/providers/openai.d.ts +87 -0
  64. package/dist/providers/openai.d.ts.map +1 -0
  65. package/dist/providers/openai.js +2489 -0
  66. package/dist/providers/openai.js.map +1 -0
  67. package/dist/route/auth-options.cjs +855 -0
  68. package/dist/route/auth-options.cjs.map +1 -0
  69. package/dist/route/auth-options.d.ts +25 -0
  70. package/dist/route/auth-options.d.ts.map +1 -0
  71. package/dist/route/auth-options.js +852 -0
  72. package/dist/route/auth-options.js.map +1 -0
  73. package/dist/route/auth.cjs +855 -0
  74. package/dist/route/auth.cjs.map +1 -0
  75. package/dist/route/auth.d.ts +51 -0
  76. package/dist/route/auth.d.ts.map +1 -0
  77. package/dist/route/auth.js +836 -0
  78. package/dist/route/auth.js.map +1 -0
  79. package/dist/route/client.cjs +1844 -0
  80. package/dist/route/client.cjs.map +1 -0
  81. package/dist/route/client.d.ts +268 -0
  82. package/dist/route/client.d.ts.map +1 -0
  83. package/dist/route/client.js +1830 -0
  84. package/dist/route/client.js.map +1 -0
  85. package/dist/route/endpoint.cjs +756 -0
  86. package/dist/route/endpoint.cjs.map +1 -0
  87. package/dist/route/endpoint.d.ts +13 -0
  88. package/dist/route/endpoint.d.ts.map +1 -0
  89. package/dist/route/endpoint.js +752 -0
  90. package/dist/route/endpoint.js.map +1 -0
  91. package/dist/route/executor.cjs +1077 -0
  92. package/dist/route/executor.cjs.map +1 -0
  93. package/dist/route/executor.d.ts +13 -0
  94. package/dist/route/executor.d.ts.map +1 -0
  95. package/dist/route/executor.js +1072 -0
  96. package/dist/route/executor.js.map +1 -0
  97. package/dist/route/framing.cjs +773 -0
  98. package/dist/route/framing.cjs.map +1 -0
  99. package/dist/route/framing.d.ts +9 -0
  100. package/dist/route/framing.d.ts.map +1 -0
  101. package/dist/route/framing.js +750 -0
  102. package/dist/route/framing.js.map +1 -0
  103. package/dist/route/overflow-detect.d.ts +18 -0
  104. package/dist/route/overflow-detect.d.ts.map +1 -0
  105. package/dist/route/protocol.cjs +25 -0
  106. package/dist/route/protocol.cjs.map +1 -0
  107. package/dist/route/protocol.d.ts +40 -0
  108. package/dist/route/protocol.d.ts.map +1 -0
  109. package/dist/route/protocol.js +21 -0
  110. package/dist/route/protocol.js.map +1 -0
  111. package/dist/route/transport/http.d.ts +48 -0
  112. package/dist/route/transport/http.d.ts.map +1 -0
  113. package/dist/route/transport/index.cjs +969 -0
  114. package/dist/route/transport/index.cjs.map +1 -0
  115. package/dist/route/transport/index.d.ts +13 -0
  116. package/dist/route/transport/index.d.ts.map +1 -0
  117. package/dist/route/transport/index.js +967 -0
  118. package/dist/route/transport/index.js.map +1 -0
  119. package/dist/schema/errors.d.ts +181 -0
  120. package/dist/schema/errors.d.ts.map +1 -0
  121. package/dist/schema/events.d.ts +3224 -0
  122. package/dist/schema/events.d.ts.map +1 -0
  123. package/dist/schema/ids.d.ts +31 -0
  124. package/dist/schema/ids.d.ts.map +1 -0
  125. package/dist/schema/index.cjs +847 -0
  126. package/dist/schema/index.cjs.map +1 -0
  127. package/dist/schema/index.d.ts +6 -0
  128. package/dist/schema/index.d.ts.map +1 -0
  129. package/dist/schema/index.js +777 -0
  130. package/dist/schema/index.js.map +1 -0
  131. package/dist/schema/messages.d.ts +292 -0
  132. package/dist/schema/messages.d.ts.map +1 -0
  133. package/dist/schema/options.d.ts +123 -0
  134. package/dist/schema/options.d.ts.map +1 -0
  135. package/dist/tool-runtime.cjs +907 -0
  136. package/dist/tool-runtime.cjs.map +1 -0
  137. package/dist/tool-runtime.d.ts +50 -0
  138. package/dist/tool-runtime.d.ts.map +1 -0
  139. package/dist/tool-runtime.js +901 -0
  140. package/dist/tool-runtime.js.map +1 -0
  141. package/dist/tool.cjs +802 -0
  142. package/dist/tool.cjs.map +1 -0
  143. package/dist/tool.d.ts +111 -0
  144. package/dist/tool.d.ts.map +1 -0
  145. package/dist/tool.js +796 -0
  146. package/dist/tool.js.map +1 -0
  147. package/package.json +112 -29
  148. package/src/cache-policy.ts +0 -92
  149. package/src/index.ts +0 -62
  150. package/src/llm.ts +0 -210
  151. package/src/protocols/openai-chat.ts +0 -422
  152. package/src/protocols/openai-compatible-chat.ts +0 -29
  153. package/src/protocols/shared.ts +0 -204
  154. package/src/protocols/utils/openai-options.ts +0 -56
  155. package/src/protocols/utils/tool-stream.ts +0 -135
  156. package/src/provider.ts +0 -32
  157. package/src/providers/openai-compatible.ts +0 -69
  158. package/src/providers/openai-options.ts +0 -71
  159. package/src/providers/openai.ts +0 -39
  160. package/src/route/auth-options.ts +0 -48
  161. package/src/route/auth.ts +0 -198
  162. package/src/route/client.ts +0 -459
  163. package/src/route/endpoint.ts +0 -28
  164. package/src/route/executor.ts +0 -396
  165. package/src/route/framing.ts +0 -13
  166. package/src/route/overflow-detect.ts +0 -74
  167. package/src/route/protocol.ts +0 -48
  168. package/src/route/transport/http.ts +0 -123
  169. package/src/route/transport/index.ts +0 -21
  170. package/src/schema/errors.ts +0 -225
  171. package/src/schema/events.ts +0 -333
  172. package/src/schema/ids.ts +0 -44
  173. package/src/schema/index.ts +0 -6
  174. package/src/schema/messages.ts +0 -240
  175. package/src/schema/options.ts +0 -231
  176. package/src/tool-runtime.ts +0 -263
  177. package/src/tool.ts +0 -212
@@ -1,204 +0,0 @@
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"
@@ -1,56 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/protocols/utils/openai-options.ts
2
- import { Schema } from "effect"
3
- import type { LLMRequest, ReasoningEffort, TextVerbosity as TextVerbosityValue } from "../../schema"
4
- import { ReasoningEfforts, TextVerbosity } from "../../schema"
5
-
6
- export const OpenAIReasoningEfforts = ReasoningEfforts.filter(
7
- (effort): effort is Exclude<ReasoningEffort, "max"> => effort !== "max",
8
- )
9
- export type OpenAIReasoningEffort = (typeof OpenAIReasoningEfforts)[number]
10
-
11
- const REASONING_EFFORTS = new Set<string>(ReasoningEfforts)
12
- const OPENAI_REASONING_EFFORTS = new Set<string>(OpenAIReasoningEfforts)
13
- const TEXT_VERBOSITY = new Set<string>(["low", "medium", "high"])
14
-
15
- export const OpenAIReasoningEffort = Schema.Literals(OpenAIReasoningEfforts)
16
- export const OpenAITextVerbosity = TextVerbosity
17
-
18
- const isAnyReasoningEffort = (effort: unknown): effort is ReasoningEffort =>
19
- typeof effort === "string" && REASONING_EFFORTS.has(effort)
20
-
21
- export const isReasoningEffort = (effort: unknown): effort is OpenAIReasoningEffort =>
22
- typeof effort === "string" && OPENAI_REASONING_EFFORTS.has(effort)
23
-
24
- const isTextVerbosity = (value: unknown): value is TextVerbosityValue =>
25
- typeof value === "string" && TEXT_VERBOSITY.has(value)
26
-
27
- const options = (request: LLMRequest) => request.providerOptions?.openai
28
-
29
- export const store = (request: LLMRequest): boolean | undefined => {
30
- const value = options(request)?.store
31
- return typeof value === "boolean" ? value : undefined
32
- }
33
-
34
- export const reasoningEffort = (request: LLMRequest): ReasoningEffort | undefined => {
35
- const value = options(request)?.reasoningEffort
36
- return isAnyReasoningEffort(value) ? value : undefined
37
- }
38
-
39
- export const reasoningSummary = (request: LLMRequest): "auto" | undefined => {
40
- return options(request)?.reasoningSummary === "auto" ? "auto" : undefined
41
- }
42
-
43
- export const encryptedReasoning = (request: LLMRequest) =>
44
- options(request)?.includeEncryptedReasoning === true ? true : undefined
45
-
46
- export const promptCacheKey = (request: LLMRequest) => {
47
- const value = options(request)?.promptCacheKey
48
- return typeof value === "string" ? value : undefined
49
- }
50
-
51
- export const textVerbosity = (request: LLMRequest) => {
52
- const value = options(request)?.textVerbosity
53
- return isTextVerbosity(value) ? value : undefined
54
- }
55
-
56
- export * as OpenAIOptions from "./openai-options"
@@ -1,135 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/protocols/utils/tool-stream.ts
2
- import { Effect } from "effect"
3
- import { LLMError, LLMEvent, type ProviderMetadata, type ToolCall, type ToolInputDelta } from "../../schema"
4
- import { eventError, parseToolInput, type ToolAccumulator } from "../shared"
5
-
6
- type StreamKey = string | number
7
-
8
- export interface PendingTool extends ToolAccumulator {
9
- readonly providerExecuted?: boolean
10
- readonly providerMetadata?: ProviderMetadata
11
- }
12
-
13
- export type State<K extends StreamKey> = Partial<Record<K, PendingTool>>
14
-
15
- export interface AppendOutcome<K extends StreamKey> {
16
- readonly tools: State<K>
17
- readonly tool: PendingTool
18
- readonly event?: ToolInputDelta
19
- }
20
-
21
- export const empty = <K extends StreamKey>(): State<K> => ({})
22
-
23
- const withTool = <K extends StreamKey>(tools: State<K>, key: K, tool: PendingTool): State<K> => {
24
- return { ...tools, [key]: tool }
25
- }
26
-
27
- const withoutTool = <K extends StreamKey>(tools: State<K>, key: K): State<K> => {
28
- const next = { ...tools }
29
- delete next[key]
30
- return next
31
- }
32
-
33
- const inputDelta = (tool: PendingTool, text: string): ToolInputDelta =>
34
- LLMEvent.toolInputDelta({
35
- id: tool.id,
36
- name: tool.name,
37
- text,
38
- })
39
-
40
- const toolCall = (route: string, tool: PendingTool, inputOverride?: string) =>
41
- parseToolInput(route, tool.name, inputOverride ?? tool.input).pipe(
42
- Effect.map(
43
- (input): ToolCall =>
44
- LLMEvent.toolCall({
45
- id: tool.id,
46
- name: tool.name,
47
- input,
48
- providerExecuted: tool.providerExecuted ? true : undefined,
49
- providerMetadata: tool.providerMetadata,
50
- }),
51
- ),
52
- )
53
-
54
- const appendTool = <K extends StreamKey>(
55
- tools: State<K>,
56
- key: K,
57
- tool: PendingTool,
58
- text: string,
59
- ): AppendOutcome<K> => ({
60
- tools: withTool(tools, key, tool),
61
- tool,
62
- event: text.length === 0 ? undefined : inputDelta(tool, text),
63
- })
64
-
65
- export const isError = <K extends StreamKey>(result: AppendOutcome<K> | LLMError): result is LLMError =>
66
- result instanceof LLMError
67
-
68
- export const start = <K extends StreamKey>(
69
- tools: State<K>,
70
- key: K,
71
- tool: Omit<PendingTool, "input"> & { readonly input?: string },
72
- ) => withTool(tools, key, { ...tool, input: tool.input ?? "" })
73
-
74
- export const appendOrStart = <K extends StreamKey>(
75
- route: string,
76
- tools: State<K>,
77
- key: K,
78
- delta: { readonly id?: string; readonly name?: string; readonly text: string },
79
- missingToolMessage: string,
80
- ): AppendOutcome<K> | LLMError => {
81
- const current = tools[key]
82
- const id = delta.id ?? current?.id
83
- const name = delta.name ?? current?.name
84
- if (!id || !name) return eventError(route, missingToolMessage)
85
-
86
- const tool = {
87
- id,
88
- name,
89
- input: `${current?.input ?? ""}${delta.text}`,
90
- providerExecuted: current?.providerExecuted,
91
- providerMetadata: current?.providerMetadata,
92
- }
93
- if (current && delta.text.length === 0 && current.id === id && current.name === name) return { tools, tool: current }
94
- return appendTool(tools, key, tool, delta.text)
95
- }
96
-
97
- export const appendExisting = <K extends StreamKey>(
98
- route: string,
99
- tools: State<K>,
100
- key: K,
101
- text: string,
102
- missingToolMessage: string,
103
- ): AppendOutcome<K> | LLMError => {
104
- const current = tools[key]
105
- if (!current) return eventError(route, missingToolMessage)
106
- if (text.length === 0) return { tools, tool: current }
107
- return appendTool(tools, key, { ...current, input: `${current.input}${text}` }, text)
108
- }
109
-
110
- export const finish = <K extends StreamKey>(route: string, tools: State<K>, key: K) =>
111
- Effect.gen(function* () {
112
- const tool = tools[key]
113
- if (!tool) return { tools }
114
- return { tools: withoutTool(tools, key), event: yield* toolCall(route, tool) }
115
- })
116
-
117
- export const finishWithInput = <K extends StreamKey>(route: string, tools: State<K>, key: K, input: string) =>
118
- Effect.gen(function* () {
119
- const tool = tools[key]
120
- if (!tool) return { tools }
121
- return { tools: withoutTool(tools, key), event: yield* toolCall(route, tool, input) }
122
- })
123
-
124
- export const finishAll = <K extends StreamKey>(route: string, tools: State<K>) =>
125
- Effect.gen(function* () {
126
- const pending = Object.values<PendingTool | undefined>(tools).filter(
127
- (tool): tool is PendingTool => tool !== undefined,
128
- )
129
- return {
130
- tools: empty<K>(),
131
- events: yield* Effect.forEach(pending, (tool) => toolCall(route, tool)),
132
- }
133
- })
134
-
135
- export * as ToolStream from "./tool-stream"
package/src/provider.ts DELETED
@@ -1,32 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/provider.ts
2
- import type { RouteModelInput } from "./route/client"
3
- import type { ModelID, ModelRef, ProviderID } from "./schema"
4
-
5
- export type ModelOptions = Omit<RouteModelInput, "id">
6
-
7
- export type ModelFactory<Options extends ModelOptions = ModelOptions> = (
8
- id: string | ModelID,
9
- options?: Options,
10
- ) => ModelRef
11
-
12
- type AnyModelFactory = (...args: never[]) => ModelRef
13
-
14
- export interface Definition<Factory extends AnyModelFactory = ModelFactory> {
15
- readonly id: ProviderID
16
- readonly model: Factory
17
- readonly apis?: Record<string, AnyModelFactory>
18
- }
19
-
20
- type DefinitionShape = {
21
- readonly id: ProviderID
22
- readonly model: (...args: never[]) => ModelRef
23
- readonly apis?: Record<string, (...args: never[]) => ModelRef>
24
- }
25
-
26
- type NoExtraFields<Input, Shape> = Input & Record<Exclude<keyof Input, keyof Shape>, never>
27
-
28
- export const make = <DefinitionType extends DefinitionShape>(
29
- definition: NoExtraFields<DefinitionType, DefinitionShape>,
30
- ) => definition
31
-
32
- export * as Provider from "./provider"
@@ -1,69 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/providers/openai-compatible.ts
2
- // Added: ollama, lmstudio family helpers.
3
- import { Provider } from "../provider"
4
- import { ProviderID, type ModelID } from "../schema"
5
- import * as OpenAICompatibleChat from "../protocols/openai-compatible-chat"
6
- import type { OpenAICompatibleChatModelInput } from "../protocols/openai-compatible-chat"
7
- import { profiles, type OpenAICompatibleProfile } from "./openai-compatible-profile"
8
-
9
- export const id = ProviderID.make("openai-compatible")
10
-
11
- export type ModelOptions = Omit<OpenAICompatibleChatModelInput, "id" | "provider"> & {
12
- readonly provider: string
13
- }
14
-
15
- type GenericModelOptions = Omit<ModelOptions, "provider"> & {
16
- readonly provider?: string
17
- }
18
-
19
- export type FamilyModelOptions = Omit<OpenAICompatibleChatModelInput, "id" | "provider" | "baseURL"> & {
20
- readonly baseURL?: string
21
- }
22
-
23
- export const routes = [OpenAICompatibleChat.route]
24
-
25
- export const model = (id: string | ModelID, options: ModelOptions) => {
26
- return OpenAICompatibleChat.model({
27
- ...options,
28
- id,
29
- provider: ProviderID.make(options.provider),
30
- })
31
- }
32
-
33
- export const profileModel = (
34
- profile: OpenAICompatibleProfile,
35
- id: string | ModelID,
36
- options: FamilyModelOptions = {},
37
- ) =>
38
- OpenAICompatibleChat.model({
39
- ...options,
40
- id,
41
- provider: profile.provider,
42
- baseURL: options.baseURL ?? profile.baseURL,
43
- })
44
-
45
- const define = (profile: OpenAICompatibleProfile) =>
46
- Provider.make({
47
- id: ProviderID.make(profile.provider),
48
- model: (id: string | ModelID, options: FamilyModelOptions = {}) => profileModel(profile, id, options),
49
- })
50
-
51
- export const provider = Provider.make({
52
- id,
53
- model: (id: string | ModelID, options: GenericModelOptions) =>
54
- model(id, { ...options, provider: options.provider ?? "openai-compatible" }),
55
- })
56
-
57
- export const baseten = define(profiles.baseten)
58
- export const cerebras = define(profiles.cerebras)
59
- export const deepinfra = define(profiles.deepinfra)
60
- export const deepseek = define(profiles.deepseek)
61
- export const fireworks = define(profiles.fireworks)
62
- export const groq = define(profiles.groq)
63
- export const openrouter = define(profiles.openrouter)
64
- export const togetherai = define(profiles.togetherai)
65
- export const xai = define(profiles.xai)
66
- export const ollama = define(profiles.ollama)
67
- export const lmstudio = define(profiles.lmstudio)
68
-
69
- export * as OpenAICompatible from "./openai-compatible"
@@ -1,71 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/providers/openai-options.ts
2
- import type { ProviderOptions, ReasoningEffort, TextVerbosity } from "../schema"
3
- import { mergeProviderOptions } from "../schema"
4
-
5
- export interface OpenAIOptionsInput {
6
- readonly [key: string]: unknown
7
- readonly store?: boolean
8
- readonly promptCacheKey?: string
9
- readonly reasoningEffort?: ReasoningEffort
10
- readonly reasoningSummary?: "auto"
11
- readonly includeEncryptedReasoning?: boolean
12
- readonly textVerbosity?: TextVerbosity
13
- }
14
-
15
- export type OpenAIProviderOptionsInput = ProviderOptions & {
16
- readonly openai?: OpenAIOptionsInput
17
- }
18
-
19
- const definedEntries = (input: Record<string, unknown>) =>
20
- Object.entries(input).filter((entry) => entry[1] !== undefined)
21
-
22
- const openAIProviderOptions = (options: OpenAIOptionsInput | undefined): ProviderOptions | undefined => {
23
- const openai = Object.fromEntries(
24
- definedEntries({
25
- store: options?.store,
26
- promptCacheKey: options?.promptCacheKey,
27
- reasoningEffort: options?.reasoningEffort,
28
- reasoningSummary: options?.reasoningSummary,
29
- includeEncryptedReasoning: options?.includeEncryptedReasoning,
30
- textVerbosity: options?.textVerbosity,
31
- }),
32
- )
33
- if (Object.keys(openai).length === 0) return undefined
34
- return { openai }
35
- }
36
-
37
- export const gpt5DefaultOptions = (
38
- modelID: string,
39
- options: { readonly textVerbosity?: boolean } = {},
40
- ): ProviderOptions | undefined => {
41
- const id = modelID.toLowerCase()
42
- if (!id.includes("gpt-5") || id.includes("gpt-5-chat") || id.includes("gpt-5-pro")) return undefined
43
- return openAIProviderOptions({
44
- reasoningEffort: "medium",
45
- reasoningSummary: "auto",
46
- textVerbosity:
47
- options.textVerbosity === true && id.includes("gpt-5.") && !id.includes("codex") && !id.includes("-chat")
48
- ? "low"
49
- : undefined,
50
- })
51
- }
52
-
53
- export const openAIDefaultOptions = (
54
- modelID: string,
55
- options: { readonly textVerbosity?: boolean } = {},
56
- ): ProviderOptions | undefined =>
57
- mergeProviderOptions(openAIProviderOptions({ store: false }), gpt5DefaultOptions(modelID, options))
58
-
59
- export const withOpenAIOptions = <Options extends { readonly providerOptions?: OpenAIProviderOptionsInput }>(
60
- modelID: string,
61
- options: Options,
62
- defaults: { readonly textVerbosity?: boolean } = {},
63
- ): Options & { readonly id: string; readonly providerOptions?: ProviderOptions } => {
64
- return {
65
- ...options,
66
- id: modelID,
67
- providerOptions: mergeProviderOptions(openAIDefaultOptions(modelID, defaults), options.providerOptions),
68
- }
69
- }
70
-
71
- export * as OpenAIProviderOptions from "./openai-options"
@@ -1,39 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/providers/openai.ts
2
- // Simplified: v1 only ships OpenAIChat (no Responses, no WebSocket routes).
3
- // `model` resolves to OpenAIChat.model with bearer auth + OpenAI option defaults.
4
- import { AuthOptions, type ProviderAuthOption } from "../route/auth-options"
5
- import type { RouteModelInput } from "../route/client"
6
- import { Provider } from "../provider"
7
- import { ProviderID, type ModelID } from "../schema"
8
- import * as OpenAIChat from "../protocols/openai-chat"
9
- import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-options"
10
-
11
- export type { OpenAIOptionsInput } from "./openai-options"
12
-
13
- export const id = ProviderID.make("openai")
14
-
15
- export const routes = [OpenAIChat.route]
16
-
17
- type OpenAIModelInput<ModelInput> = Omit<ModelInput, "apiKey" | "auth" | "baseURL"> &
18
- ProviderAuthOption<"optional"> & {
19
- readonly baseURL?: string
20
- readonly providerOptions?: OpenAIProviderOptionsInput
21
- }
22
-
23
- const auth = (options: ProviderAuthOption<"optional">) => AuthOptions.bearer(options, "OPENAI_API_KEY")
24
-
25
- export const chat = (id: string | ModelID, options: OpenAIModelInput<Omit<RouteModelInput, "id">> = {}) => {
26
- const { apiKey: _, ...rest } = options
27
- return OpenAIChat.model(withOpenAIOptions(id, { ...rest, auth: auth(options) }))
28
- }
29
-
30
- export const provider = Provider.make({
31
- id,
32
- model: chat,
33
- apis: { chat },
34
- })
35
-
36
- export const model = provider.model
37
- export const apis = provider.apis
38
-
39
- export * as OpenAI from "./openai"
@@ -1,48 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/route/auth-options.ts
2
- import type { Config, Redacted } from "effect"
3
- import { Auth } from "./auth"
4
-
5
- export type ApiKeyMode = "optional" | "required"
6
-
7
- export type AuthOverride = {
8
- readonly auth: Auth
9
- readonly apiKey?: never
10
- }
11
-
12
- export type OptionalApiKeyAuth = {
13
- readonly apiKey?: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>>
14
- readonly auth?: never
15
- }
16
-
17
- export type RequiredApiKeyAuth = {
18
- readonly apiKey: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>>
19
- readonly auth?: never
20
- }
21
-
22
- export type ProviderAuthOption<Mode extends ApiKeyMode> =
23
- | AuthOverride
24
- | (Mode extends "optional" ? OptionalApiKeyAuth : RequiredApiKeyAuth)
25
-
26
- export type ModelOptions<Base, Mode extends ApiKeyMode> = Omit<Base, "apiKey" | "auth"> & ProviderAuthOption<Mode>
27
-
28
- export type ModelArgs<Base, Mode extends ApiKeyMode> = Mode extends "optional"
29
- ? readonly [options?: ModelOptions<Base, Mode>]
30
- : readonly [options: ModelOptions<Base, Mode>]
31
-
32
- export type ModelFactory<Base, Mode extends ApiKeyMode, Model> = (id: string, ...args: ModelArgs<Base, Mode>) => Model
33
-
34
- export type AtLeastOne<T> = {
35
- [K in keyof T]: Required<Pick<T, K>> & Partial<Omit<T, K>>
36
- }[keyof T]
37
-
38
- export const bearer = (options: ProviderAuthOption<"optional">, envVar: string | ReadonlyArray<string>): Auth => {
39
- if ("auth" in options && options.auth) return options.auth
40
- return (Array.isArray(envVar) ? envVar : [envVar])
41
- .reduce(
42
- (auth, name) => auth.orElse(Auth.config(name)),
43
- Auth.optional("apiKey" in options ? options.apiKey : undefined, "apiKey"),
44
- )
45
- .bearer()
46
- }
47
-
48
- export * as AuthOptions from "./auth-options"