@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,56 @@
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"
@@ -0,0 +1,135 @@
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"
@@ -0,0 +1,32 @@
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"
@@ -0,0 +1,24 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/providers/openai-compatible-profile.ts
2
+ // Added: ollama, lmstudio (local OpenAI-compatible servers).
3
+ export interface OpenAICompatibleProfile {
4
+ readonly provider: string
5
+ readonly baseURL: string
6
+ }
7
+
8
+ export const profiles = {
9
+ baseten: { provider: "baseten", baseURL: "https://inference.baseten.co/v1" },
10
+ cerebras: { provider: "cerebras", baseURL: "https://api.cerebras.ai/v1" },
11
+ deepinfra: { provider: "deepinfra", baseURL: "https://api.deepinfra.com/v1/openai" },
12
+ deepseek: { provider: "deepseek", baseURL: "https://api.deepseek.com/v1" },
13
+ fireworks: { provider: "fireworks", baseURL: "https://api.fireworks.ai/inference/v1" },
14
+ groq: { provider: "groq", baseURL: "https://api.groq.com/openai/v1" },
15
+ openrouter: { provider: "openrouter", baseURL: "https://openrouter.ai/api/v1" },
16
+ togetherai: { provider: "togetherai", baseURL: "https://api.together.xyz/v1" },
17
+ xai: { provider: "xai", baseURL: "https://api.x.ai/v1" },
18
+ ollama: { provider: "ollama", baseURL: "http://localhost:11434/v1" },
19
+ lmstudio: { provider: "lmstudio", baseURL: "http://localhost:1234/v1" },
20
+ } as const satisfies Record<string, OpenAICompatibleProfile>
21
+
22
+ export const byProvider: Record<string, OpenAICompatibleProfile> = Object.fromEntries(
23
+ Object.values(profiles).map((profile) => [profile.provider, profile]),
24
+ )
@@ -0,0 +1,69 @@
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"
@@ -0,0 +1,71 @@
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"
@@ -0,0 +1,39 @@
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"
@@ -0,0 +1,48 @@
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"
@@ -0,0 +1,198 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/route/auth.ts
2
+ import { Config, Effect, Redacted } from "effect"
3
+ import { Headers } from "effect/unstable/http"
4
+ import { AuthenticationReason, InvalidRequestReason, LLMError, type LLMRequest } from "../schema"
5
+
6
+ export class MissingCredentialError extends Error {
7
+ readonly _tag = "MissingCredentialError"
8
+
9
+ constructor(readonly source: string) {
10
+ super(`Missing auth credential: ${source}`)
11
+ }
12
+ }
13
+
14
+ export type CredentialError = MissingCredentialError | Config.ConfigError
15
+ export type AuthError = CredentialError | LLMError
16
+
17
+ export interface AuthInput {
18
+ readonly request: LLMRequest
19
+ readonly method: "POST" | "GET"
20
+ readonly url: string
21
+ readonly body: string
22
+ readonly headers: Headers.Headers
23
+ }
24
+
25
+ export interface Credential {
26
+ readonly load: Effect.Effect<Redacted.Redacted<string>, CredentialError>
27
+ readonly orElse: (that: Credential) => Credential
28
+ readonly bearer: () => Auth
29
+ readonly header: (name: string) => Auth
30
+ readonly pipe: <A>(f: (self: Credential) => A) => A
31
+ }
32
+
33
+ export interface Auth {
34
+ readonly apply: (input: AuthInput) => Effect.Effect<Headers.Headers, AuthError>
35
+ readonly andThen: (that: Auth) => Auth
36
+ readonly orElse: (that: Auth) => Auth
37
+ readonly pipe: <A>(f: (self: Auth) => A) => A
38
+ }
39
+
40
+ export const isAuth = (input: unknown): input is Auth =>
41
+ typeof input === "object" && input !== null && "apply" in input && typeof input.apply === "function"
42
+
43
+ const credential = (load: Effect.Effect<Redacted.Redacted<string>, CredentialError>): Credential => {
44
+ const self: Credential = {
45
+ load,
46
+ orElse: (that) => credential(load.pipe(Effect.catch(() => that.load))),
47
+ bearer: () => fromCredential(self, (secret) => ({ authorization: `Bearer ${secret}` })),
48
+ header: (name) => fromCredential(self, (secret) => ({ [name]: secret })),
49
+ pipe: (f) => f(self),
50
+ }
51
+ return self
52
+ }
53
+
54
+ const auth = (apply: Auth["apply"]): Auth => {
55
+ const self: Auth = {
56
+ apply,
57
+ andThen: (that) =>
58
+ auth((input) => apply(input).pipe(Effect.flatMap((headers) => that.apply({ ...input, headers })))),
59
+ orElse: (that) => auth((input) => apply(input).pipe(Effect.catch(() => that.apply(input)))),
60
+ pipe: (f) => f(self),
61
+ }
62
+ return self
63
+ }
64
+
65
+ const fromCredential = (source: Credential, render: (secret: string) => Headers.Input) =>
66
+ auth((input) =>
67
+ source.load.pipe(Effect.map((secret) => Headers.setAll(input.headers, render(Redacted.value(secret))))),
68
+ )
69
+
70
+ const secretEffect = (secret: string | Redacted.Redacted<string>, source: string) => {
71
+ const redacted = typeof secret === "string" ? Redacted.make(secret) : secret
72
+ if (Redacted.value(redacted) === "") return Effect.fail(new MissingCredentialError(source))
73
+ return Effect.succeed(redacted)
74
+ }
75
+
76
+ const credentialFromSecret = (
77
+ secret: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>>,
78
+ source: string,
79
+ ) => {
80
+ if (typeof secret === "string" || Redacted.isRedacted(secret)) return credential(secretEffect(secret, source))
81
+ return credential(
82
+ Effect.gen(function* () {
83
+ return yield* secretEffect(yield* secret, source)
84
+ }),
85
+ )
86
+ }
87
+
88
+ export const value = (secret: string, source = "value") => credentialFromSecret(secret, source)
89
+
90
+ export const optional = (
91
+ secret: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | undefined,
92
+ source = "optional value",
93
+ ) =>
94
+ secret === undefined
95
+ ? credential(Effect.fail(new MissingCredentialError(source)))
96
+ : credentialFromSecret(secret, source)
97
+
98
+ export const config = (name: string) => credentialFromSecret(Config.redacted(name), name)
99
+
100
+ export const effect = (load: Effect.Effect<Redacted.Redacted<string>, CredentialError>) => credential(load)
101
+
102
+ export const none = auth((input) => Effect.succeed(input.headers))
103
+
104
+ export const headers = (input: Headers.Input) =>
105
+ auth((inputAuth) => Effect.succeed(Headers.setAll(inputAuth.headers, input)))
106
+
107
+ export const remove = (name: string) => auth((input) => Effect.succeed(Headers.remove(input.headers, name)))
108
+
109
+ export const custom = (apply: (input: AuthInput) => Effect.Effect<Headers.Headers, LLMError>) => auth(apply)
110
+
111
+ export const passthrough = none
112
+
113
+ const fromModelApiKey = (from: (apiKey: string) => Headers.Input) =>
114
+ auth(({ request, headers }) => {
115
+ const key = request.model.apiKey
116
+ if (!key) return Effect.succeed(headers)
117
+ return Effect.succeed(Headers.setAll(headers, from(key)))
118
+ })
119
+
120
+ const credentialInput = (
121
+ source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
122
+ ) =>
123
+ typeof source === "string" || Redacted.isRedacted(source) || Config.isConfig(source)
124
+ ? credentialFromSecret(source, "value")
125
+ : source
126
+
127
+ export function bearer(): Auth
128
+ export function bearer(
129
+ source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
130
+ ): Auth
131
+ export function bearer(
132
+ source?: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
133
+ ) {
134
+ if (source === undefined) return fromModelApiKey((key) => ({ authorization: `Bearer ${key}` }))
135
+ return credentialInput(source).bearer()
136
+ }
137
+
138
+ export const apiKey = bearer
139
+
140
+ export const apiKeyHeader = (name: string) => fromModelApiKey((key) => ({ [name]: key }))
141
+
142
+ export function header(
143
+ name: string,
144
+ ): (source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential) => Auth
145
+ export function header(
146
+ name: string,
147
+ source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
148
+ ): Auth
149
+ export function header(
150
+ name: string,
151
+ source?: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
152
+ ) {
153
+ if (source === undefined) {
154
+ return (
155
+ next: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
156
+ ) => credentialInput(next).header(name)
157
+ }
158
+ return credentialInput(source).header(name)
159
+ }
160
+
161
+ export function bearerHeader(
162
+ name: string,
163
+ ): (source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential) => Auth
164
+ export function bearerHeader(
165
+ name: string,
166
+ source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
167
+ ): Auth
168
+ export function bearerHeader(
169
+ name: string,
170
+ source?: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
171
+ ) {
172
+ const render = (
173
+ input: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
174
+ ) => fromCredential(credentialInput(input), (secret) => ({ [name]: `Bearer ${secret}` }))
175
+ if (source === undefined) return render
176
+ return render(source)
177
+ }
178
+
179
+ const toLLMError = (error: AuthError): LLMError => {
180
+ if (error instanceof MissingCredentialError || error instanceof Config.ConfigError) {
181
+ return new LLMError({
182
+ module: "Auth",
183
+ method: "apply",
184
+ reason:
185
+ error instanceof MissingCredentialError
186
+ ? new AuthenticationReason({ message: error.message, kind: "missing" })
187
+ : new InvalidRequestReason({ message: `Failed to resolve auth config: ${error.message}` }),
188
+ })
189
+ }
190
+ return error
191
+ }
192
+
193
+ export const toEffect =
194
+ (input: Auth) =>
195
+ (authInput: AuthInput): Effect.Effect<Headers.Headers, LLMError> =>
196
+ input.apply(authInput).pipe(Effect.mapError(toLLMError))
197
+
198
+ export * as Auth from "./auth"