@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,263 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/tool-runtime.ts
2
- import { Effect, Stream } from "effect"
3
- import type { Concurrency } from "effect/Types"
4
- import {
5
- type ContentPart,
6
- type FinishReason,
7
- type LLMError,
8
- LLMEvent,
9
- LLMRequest,
10
- Message,
11
- type ProviderMetadata,
12
- ToolCallPart,
13
- ToolFailure,
14
- ToolResultPart,
15
- type ToolResultValue,
16
- } from "./schema"
17
- import { type AnyTool, type ExecutableTools, type Tools, toDefinitions } from "./tool"
18
-
19
- export interface RuntimeState {
20
- readonly step: number
21
- readonly request: LLMRequest
22
- /** Tool calls emitted by the model in the step that just finished (before dispatch follow-up). */
23
- readonly toolCalls: ReadonlyArray<ToolCallPart>
24
- }
25
-
26
- export type StopCondition = (state: RuntimeState) => boolean
27
-
28
- /** Stop the loop once the model emits a tool call with the given name. */
29
- export const hasToolCall =
30
- (name: string): StopCondition =>
31
- (state) =>
32
- state.toolCalls.some((call) => call.name === name)
33
-
34
- /** Combine multiple stop conditions with OR semantics. */
35
- export const stopWhenAny =
36
- (...conditions: ReadonlyArray<StopCondition>): StopCondition =>
37
- (state) =>
38
- conditions.some((condition) => condition(state))
39
-
40
- export type ToolExecution = "auto" | "none"
41
-
42
- interface RunOptionsBase {
43
- readonly request: LLMRequest
44
- readonly concurrency?: Concurrency
45
- readonly stopWhen?: StopCondition
46
- }
47
-
48
- export type RunOptions<T extends Tools> = RunOptionsAuto<T & ExecutableTools> | RunOptionsNone<T>
49
-
50
- export interface RunOptionsAuto<T extends ExecutableTools> extends RunOptionsBase {
51
- readonly request: LLMRequest
52
- readonly tools: T
53
- readonly toolExecution?: "auto"
54
- }
55
-
56
- export interface RunOptionsNone<T extends Tools> extends RunOptionsBase {
57
- readonly request: LLMRequest
58
- readonly tools: T
59
- /** Advertise tool schemas but leave model-emitted tool calls for the caller. */
60
- readonly toolExecution: "none"
61
- }
62
-
63
- export type StreamOptions<T extends Tools> = RunOptions<T> & {
64
- readonly stream: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMError>
65
- }
66
-
67
- export const stepCountIs =
68
- (count: number): StopCondition =>
69
- (state) =>
70
- state.step + 1 >= count
71
-
72
- /**
73
- * Run a model with typed tools. This helper owns tool orchestration, while the
74
- * caller supplies the actual model stream function. It can advertise schemas
75
- * only (`toolExecution: "none"`), execute one step, or continue model rounds
76
- * when `stopWhen` is provided.
77
- */
78
- export const stream = <T extends Tools>(options: StreamOptions<T>): Stream.Stream<LLMEvent, LLMError> => {
79
- const concurrency = options.concurrency ?? 10
80
- const tools = options.tools as Tools
81
- const runtimeTools = toDefinitions(tools)
82
- const runtimeToolNames = new Set(runtimeTools.map((tool) => tool.name))
83
- const initialRequest =
84
- runtimeTools.length === 0
85
- ? options.request
86
- : LLMRequest.update(options.request, {
87
- tools: [...options.request.tools.filter((tool) => !runtimeToolNames.has(tool.name)), ...runtimeTools],
88
- })
89
-
90
- const loop = (request: LLMRequest, step: number): Stream.Stream<LLMEvent, LLMError> =>
91
- Stream.unwrap(
92
- Effect.gen(function* () {
93
- const state: StepState = { assistantContent: [], toolCalls: [], finishReason: undefined }
94
-
95
- const modelStream = options
96
- .stream(request)
97
- .pipe(Stream.tap((event) => Effect.sync(() => accumulate(state, event))))
98
-
99
- const continuation = Stream.unwrap(
100
- Effect.gen(function* () {
101
- if (state.finishReason !== "tool-calls" || state.toolCalls.length === 0) return Stream.empty
102
- if (options.toolExecution === "none") return Stream.empty
103
-
104
- const dispatched = yield* Effect.forEach(
105
- state.toolCalls,
106
- (call) => dispatch(tools, call).pipe(Effect.map((result) => [call, result] as const)),
107
- { concurrency },
108
- )
109
- const resultStream = Stream.fromIterable(dispatched.flatMap(([call, result]) => emitEvents(call, result)))
110
-
111
- if (!options.stopWhen) return resultStream
112
- if (options.stopWhen({ step, request, toolCalls: state.toolCalls })) return resultStream
113
-
114
- return resultStream.pipe(Stream.concat(loop(followUpRequest(request, state, dispatched), step + 1)))
115
- }),
116
- )
117
-
118
- return modelStream.pipe(Stream.concat(continuation))
119
- }),
120
- )
121
-
122
- return loop(initialRequest, 0)
123
- }
124
-
125
- interface StepState {
126
- assistantContent: ContentPart[]
127
- toolCalls: ToolCallPart[]
128
- finishReason: FinishReason | undefined
129
- }
130
-
131
- const accumulate = (state: StepState, event: LLMEvent) => {
132
- if (event.type === "text-delta") {
133
- appendStreamingText(state, "text", event.text, undefined)
134
- return
135
- }
136
- if (event.type === "reasoning-delta") {
137
- appendStreamingText(state, "reasoning", event.text, undefined)
138
- return
139
- }
140
- if (event.type === "reasoning-end") {
141
- appendStreamingText(state, "reasoning", "", event.providerMetadata)
142
- return
143
- }
144
- if (event.type === "text-end") {
145
- appendStreamingText(state, "text", "", event.providerMetadata)
146
- return
147
- }
148
- if (event.type === "tool-call") {
149
- const part = ToolCallPart.make({
150
- id: event.id,
151
- name: event.name,
152
- input: event.input,
153
- providerExecuted: event.providerExecuted,
154
- providerMetadata: event.providerMetadata,
155
- })
156
- state.assistantContent.push(part)
157
- if (!event.providerExecuted) state.toolCalls.push(part)
158
- return
159
- }
160
- if (event.type === "tool-result" && event.providerExecuted) {
161
- state.assistantContent.push(
162
- ToolResultPart.make({
163
- id: event.id,
164
- name: event.name,
165
- result: event.result,
166
- providerExecuted: true,
167
- providerMetadata: event.providerMetadata,
168
- }),
169
- )
170
- return
171
- }
172
- if (event.type === "request-finish") {
173
- state.finishReason = event.reason
174
- }
175
- }
176
-
177
- const sameProviderMetadata = (left: ProviderMetadata | undefined, right: ProviderMetadata | undefined) =>
178
- left === right || JSON.stringify(left) === JSON.stringify(right)
179
-
180
- const mergeProviderMetadata = (left: ProviderMetadata | undefined, right: ProviderMetadata | undefined) => {
181
- if (!left) return right
182
- if (!right) return left
183
- return Object.fromEntries(
184
- Array.from(new Set([...Object.keys(left), ...Object.keys(right)])).map((provider) => [
185
- provider,
186
- { ...left[provider], ...right[provider] },
187
- ]),
188
- )
189
- }
190
-
191
- const appendStreamingText = (
192
- state: StepState,
193
- type: "text" | "reasoning",
194
- text: string,
195
- providerMetadata: ProviderMetadata | undefined,
196
- ) => {
197
- const last = state.assistantContent.at(-1)
198
- if (last?.type === type && text.length === 0) {
199
- state.assistantContent[state.assistantContent.length - 1] = {
200
- ...last,
201
- providerMetadata: mergeProviderMetadata(last.providerMetadata, providerMetadata),
202
- }
203
- return
204
- }
205
- if (last?.type === type && sameProviderMetadata(last.providerMetadata, providerMetadata)) {
206
- state.assistantContent[state.assistantContent.length - 1] = { ...last, text: `${last.text}${text}` }
207
- return
208
- }
209
- state.assistantContent.push({ type, text, providerMetadata })
210
- }
211
-
212
- const dispatch = (tools: Tools, call: ToolCallPart): Effect.Effect<ToolResultValue> => {
213
- const tool = tools[call.name]
214
- if (!tool) return Effect.succeed({ type: "error" as const, value: `Unknown tool: ${call.name}` })
215
- if (!tool.execute)
216
- return Effect.succeed({ type: "error" as const, value: `Tool has no execute handler: ${call.name}` })
217
-
218
- return decodeAndExecute(tool, call.input).pipe(
219
- Effect.catchTag("LLM.ToolFailure", (failure) =>
220
- Effect.succeed({ type: "error" as const, value: failure.message } satisfies ToolResultValue),
221
- ),
222
- )
223
- }
224
-
225
- const decodeAndExecute = (tool: AnyTool, input: unknown): Effect.Effect<ToolResultValue, ToolFailure> =>
226
- tool._decode(input).pipe(
227
- Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })),
228
- Effect.flatMap((decoded) => tool.execute!(decoded)),
229
- Effect.flatMap((value) =>
230
- tool._encode(value).pipe(
231
- Effect.mapError(
232
- (error) =>
233
- new ToolFailure({
234
- message: `Tool returned an invalid value for its success schema: ${error.message}`,
235
- }),
236
- ),
237
- ),
238
- ),
239
- Effect.map((encoded): ToolResultValue => ({ type: "json", value: encoded })),
240
- )
241
-
242
- const emitEvents = (call: ToolCallPart, result: ToolResultValue): ReadonlyArray<LLMEvent> =>
243
- result.type === "error"
244
- ? [
245
- LLMEvent.toolError({ id: call.id, name: call.name, message: String(result.value) }),
246
- LLMEvent.toolResult({ id: call.id, name: call.name, result }),
247
- ]
248
- : [LLMEvent.toolResult({ id: call.id, name: call.name, result })]
249
-
250
- const followUpRequest = (
251
- request: LLMRequest,
252
- state: StepState,
253
- dispatched: ReadonlyArray<readonly [ToolCallPart, ToolResultValue]>,
254
- ) =>
255
- LLMRequest.update(request, {
256
- messages: [
257
- ...request.messages,
258
- Message.assistant(state.assistantContent),
259
- ...dispatched.map(([call, result]) => Message.tool({ id: call.id, name: call.name, result })),
260
- ],
261
- })
262
-
263
- export const ToolRuntime = { stream, stepCountIs } as const
package/src/tool.ts DELETED
@@ -1,212 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/tool.ts
2
- import { Effect, JsonSchema, Schema } from "effect"
3
- import type { ToolDefinition as ToolDefinitionClass } from "./schema"
4
- import { ToolDefinition, ToolFailure } from "./schema"
5
-
6
- /**
7
- * Schema constraint for tool parameters / success values: no decoding or
8
- * encoding services are allowed. Tools should be self-contained — anything
9
- * beyond pure data conversion belongs in the handler closure.
10
- */
11
- export type ToolSchema<T> = Schema.Codec<T, any, never, never>
12
-
13
- export type ToolExecute<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>> = (
14
- params: Schema.Schema.Type<Parameters>,
15
- ) => Effect.Effect<Schema.Schema.Type<Success>, ToolFailure>
16
-
17
- /**
18
- * A type-safe LLM tool. Each tool bundles its own description, parameter
19
- * Schema and success Schema. The execute handler is optional: omit it when you
20
- * only want to expose a tool schema to the model and handle tool calls outside
21
- * this package.
22
- *
23
- * Errors must be expressed as `ToolFailure`. Unmapped errors and defects fail
24
- * the stream.
25
- *
26
- * Internally each tool also carries memoized codecs and a precomputed
27
- * `ToolDefinition` so the runtime doesn't rebuild them per invocation.
28
- */
29
- export interface Tool<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>> {
30
- readonly description: string
31
- readonly parameters: Parameters
32
- readonly success: Success
33
- readonly execute?: ToolExecute<Parameters, Success>
34
- /** @internal */
35
- readonly _decode: (input: unknown) => Effect.Effect<Schema.Schema.Type<Parameters>, Schema.SchemaError>
36
- /** @internal */
37
- readonly _encode: (value: Schema.Schema.Type<Success>) => Effect.Effect<unknown, Schema.SchemaError>
38
- /** @internal */
39
- readonly _definition: ToolDefinitionClass
40
- }
41
-
42
- export type AnyTool = Tool<ToolSchema<any>, ToolSchema<any>>
43
-
44
- export type ExecutableTool<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>> = Tool<
45
- Parameters,
46
- Success
47
- > & {
48
- readonly execute: ToolExecute<Parameters, Success>
49
- }
50
-
51
- export type AnyExecutableTool = ExecutableTool<ToolSchema<any>, ToolSchema<any>>
52
-
53
- export type ExecutableTools = Record<string, AnyExecutableTool>
54
-
55
- type TypedToolConfig = {
56
- readonly description: string
57
- readonly parameters: ToolSchema<any>
58
- readonly success: ToolSchema<any>
59
- readonly execute?: ToolExecute<ToolSchema<any>, ToolSchema<any>>
60
- }
61
-
62
- type DynamicToolConfig = {
63
- readonly description: string
64
- readonly jsonSchema: JsonSchema.JsonSchema
65
- readonly execute?: (params: unknown) => Effect.Effect<unknown, ToolFailure>
66
- }
67
-
68
- /**
69
- * Constructs a tool. Two input modes:
70
- *
71
- * 1. **Typed** — pass Effect `parameters` and `success` Schemas; inputs and
72
- * outputs are statically typed and decoded/encoded automatically.
73
- *
74
- * ```ts
75
- * Tool.make({
76
- * description: "Get current weather",
77
- * parameters: Schema.Struct({ city: Schema.String }),
78
- * success: Schema.Struct({ temperature: Schema.Number }),
79
- * execute: ({ city }) => Effect.succeed({ temperature: 22 }),
80
- * })
81
- * ```
82
- *
83
- * 2. **Dynamic** — pass raw JSON Schema as `jsonSchema`. Use this when the
84
- * schema comes from an external source (MCP server, plugin manifest,
85
- * dynamic config) and is not known at compile time. Inputs are typed as
86
- * `unknown`; the handler is responsible for any validation it needs.
87
- *
88
- * ```ts
89
- * Tool.make({
90
- * description: "Look something up",
91
- * jsonSchema: { type: "object", properties: { ... } },
92
- * execute: (params) => Effect.succeed(...),
93
- * })
94
- * ```
95
- *
96
- * In both modes the produced tool flows through `toDefinitions(...)` and the
97
- * runtime identically.
98
- */
99
- export function make<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>>(config: {
100
- readonly description: string
101
- readonly parameters: Parameters
102
- readonly success: Success
103
- readonly execute: ToolExecute<Parameters, Success>
104
- }): ExecutableTool<Parameters, Success>
105
- export function make<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>>(config: {
106
- readonly description: string
107
- readonly parameters: Parameters
108
- readonly success: Success
109
- readonly execute?: undefined
110
- }): Tool<Parameters, Success>
111
- export function make(config: {
112
- readonly description: string
113
- readonly jsonSchema: JsonSchema.JsonSchema
114
- readonly execute: (params: unknown) => Effect.Effect<unknown, ToolFailure>
115
- }): AnyExecutableTool
116
- export function make(config: {
117
- readonly description: string
118
- readonly jsonSchema: JsonSchema.JsonSchema
119
- readonly execute?: undefined
120
- }): AnyTool
121
- export function make(config: TypedToolConfig | DynamicToolConfig): AnyTool {
122
- if ("jsonSchema" in config) {
123
- return {
124
- description: config.description,
125
- parameters: Schema.Unknown as ToolSchema<unknown>,
126
- success: Schema.Unknown as ToolSchema<unknown>,
127
- execute: config.execute,
128
- _decode: Effect.succeed,
129
- _encode: Effect.succeed,
130
- _definition: new ToolDefinition({
131
- name: "",
132
- description: config.description,
133
- inputSchema: config.jsonSchema,
134
- }),
135
- }
136
- }
137
- return {
138
- description: config.description,
139
- parameters: config.parameters,
140
- success: config.success,
141
- execute: config.execute,
142
- _decode: Schema.decodeUnknownEffect(config.parameters),
143
- _encode: Schema.encodeEffect(config.success),
144
- _definition: new ToolDefinition({
145
- name: "",
146
- description: config.description,
147
- inputSchema: toJsonSchema(config.parameters),
148
- }),
149
- }
150
- }
151
-
152
- export const tool = make
153
-
154
- /**
155
- * A record of named tools. The record key becomes the tool name on the wire.
156
- */
157
- export type Tools = Record<string, AnyTool>
158
-
159
- /**
160
- * Convert a tools record into the `ToolDefinition[]` shape that
161
- * `LLMRequest.tools` expects. The runtime calls this internally; consumers
162
- * that build `LLMRequest` themselves can use it too.
163
- *
164
- * Tool names come from the record keys, so the per-tool cached
165
- * `_definition` is rebuilt with the correct name here. The JSON Schema body
166
- * is reused.
167
- */
168
- export const toDefinitions = (tools: Tools): ReadonlyArray<ToolDefinitionClass> =>
169
- Object.entries(tools).map(
170
- ([name, item]) =>
171
- new ToolDefinition({
172
- name,
173
- description: item._definition.description,
174
- inputSchema: item._definition.inputSchema,
175
- }),
176
- )
177
-
178
- const toJsonSchema = (schema: Schema.Top): JsonSchema.JsonSchema => {
179
- const document = Schema.toJsonSchemaDocument(schema)
180
- const base =
181
- Object.keys(document.definitions).length === 0
182
- ? document.schema
183
- : { ...document.schema, $defs: document.definitions }
184
- // OpenAI/Anthropic both require the top-level tool parameters schema to be
185
- // `type: "object"`. Effect Schema emits `anyOf: [{object},{array}]` for
186
- // empty structs, which OpenAI rejects. Normalize here.
187
- return normalizeTopLevel(base)
188
- }
189
-
190
- const normalizeTopLevel = (s: JsonSchema.JsonSchema): JsonSchema.JsonSchema => {
191
- if (!s || typeof s !== "object") {
192
- return { type: "object", properties: {}, additionalProperties: false } as JsonSchema.JsonSchema
193
- }
194
- const obj = s as { type?: unknown; anyOf?: ReadonlyArray<JsonSchema.JsonSchema> }
195
- if (obj.type === "object") return s
196
- if (Array.isArray(obj.anyOf)) {
197
- const objectVariant = obj.anyOf.find(
198
- (v): v is JsonSchema.JsonSchema =>
199
- v != null && typeof v === "object" && (v as { type?: unknown }).type === "object",
200
- )
201
- if (objectVariant) {
202
- const { anyOf: _omit, ...rest } = obj
203
- void _omit
204
- return { ...rest, ...(objectVariant as object) } as JsonSchema.JsonSchema
205
- }
206
- }
207
- return { type: "object", properties: {}, additionalProperties: false } as JsonSchema.JsonSchema
208
- }
209
-
210
- export { ToolFailure }
211
-
212
- export * as Tool from "./tool"