@opencode/ai 0.0.0-dev-455 → 0.0.0-dev-461
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.
- package/README.md +42 -31
- package/dist/effect.d.ts +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/llm.d.ts +11 -4
- package/dist/llm.js +11 -10
- package/dist/media-model.js +7 -5
- package/dist/tool.d.ts +33 -30
- package/dist/tool.js +10 -9
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -47,7 +47,8 @@ await Effect.runPromise(program.pipe(Effect.provide(AIClient.layer)))
|
|
|
47
47
|
```
|
|
48
48
|
|
|
49
49
|
Run `ai.stream(...)` instead of `generate` when you want incremental `LLMEvent`s. Both accept input or a prebuilt
|
|
50
|
-
`ai.request(...)`.
|
|
50
|
+
`ai.request(...)`. Input takes either `prompt`, a single user message, or `messages`, the whole conversation, never
|
|
51
|
+
both; `system` goes with either. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses,
|
|
51
52
|
Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
|
|
52
53
|
|
|
53
54
|
### Tool loop
|
|
@@ -58,7 +59,9 @@ after each step that has tool calls, with every step's `LLMResponse`; returning
|
|
|
58
59
|
them. Tools are an array, sent in the order given so the provider can reuse its cached prompt prefix. Each tool has a
|
|
59
60
|
`name`, and two tools with the same name fail the request. `tool` takes a plain `async` execute; a throw or rejection
|
|
60
61
|
goes back to the model as an error result, and `signal` aborts when the loop is interrupted.
|
|
61
|
-
`
|
|
62
|
+
`input` is an Effect Schema that decodes and types the arguments, or a raw JSON Schema object, such as an MCP tool's,
|
|
63
|
+
whose arguments arrive as `unknown` (pair it with an optional JSON Schema `outputSchema`). `tool` from
|
|
64
|
+
`@opencode/ai/effect` takes the same options (including an optional `success` schema) with an Effect execute:
|
|
62
65
|
|
|
63
66
|
```ts
|
|
64
67
|
import { readFile } from "node:fs/promises"
|
|
@@ -68,7 +71,7 @@ import { ai, tool } from "@opencode/ai"
|
|
|
68
71
|
const read_file = tool({
|
|
69
72
|
name: "read_file",
|
|
70
73
|
description: "Read a UTF-8 file.",
|
|
71
|
-
|
|
74
|
+
input: Schema.Struct({ path: Schema.String }),
|
|
72
75
|
execute: ({ path }, { signal }) => readFile(path, { encoding: "utf8", signal }),
|
|
73
76
|
})
|
|
74
77
|
|
|
@@ -92,7 +95,7 @@ instead of JSON arguments: unconstrained `text`, or text matching a `regex` or `
|
|
|
92
95
|
const run_code = tool({
|
|
93
96
|
name: "run_code",
|
|
94
97
|
description: "Run JavaScript",
|
|
95
|
-
|
|
98
|
+
input: Schema.Struct({ code: Schema.String }),
|
|
96
99
|
freeform: { type: "lark", grammar: JS_GRAMMAR },
|
|
97
100
|
execute: ({ code }) => runCode(code),
|
|
98
101
|
})
|
|
@@ -131,11 +134,15 @@ import { ai, LLMEvent } from "@opencode/ai/effect"
|
|
|
131
134
|
const flagged = (data: unknown) =>
|
|
132
135
|
typeof data === "object" && data !== null && "type" in data && data.type === "moderation.flagged"
|
|
133
136
|
|
|
134
|
-
const events = ai
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
)
|
|
137
|
+
const events = ai
|
|
138
|
+
.stream({ model, prompt: "Say hello.", includeRaw: true })
|
|
139
|
+
.pipe(
|
|
140
|
+
Stream.map((event) =>
|
|
141
|
+
event.type === "raw" && flagged(event.data)
|
|
142
|
+
? LLMEvent.providerError({ message: "Flagged by moderation" })
|
|
143
|
+
: event,
|
|
144
|
+
),
|
|
145
|
+
)
|
|
139
146
|
```
|
|
140
147
|
|
|
141
148
|
### Google Interactions
|
|
@@ -150,11 +157,13 @@ live under `providerMetadata.vertex`. The default is still full-history replay w
|
|
|
150
157
|
|
|
151
158
|
```ts
|
|
152
159
|
const model = Google.configure({ apiKey }).interactions("gemini-3.8-flash")
|
|
153
|
-
const response =
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
160
|
+
const response =
|
|
161
|
+
yield *
|
|
162
|
+
ai.generate({
|
|
163
|
+
model,
|
|
164
|
+
prompt: "Say hello.",
|
|
165
|
+
providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
|
|
166
|
+
})
|
|
158
167
|
```
|
|
159
168
|
|
|
160
169
|
Interactions supports text output, streamed function calls, native tool results, thought signatures, and multimodal
|
|
@@ -669,18 +678,18 @@ Common fields are portable in shape, not in support. Some routes approximate `as
|
|
|
669
678
|
size they offer; others fail with a typed `AIError` before any network call rather than dropping them, so check this
|
|
670
679
|
table before swapping only the `model`:
|
|
671
680
|
|
|
672
|
-
| Provider | `n` | `aspect`
|
|
673
|
-
| --------------------- | --- |
|
|
674
|
-
| OpenAI | ✓¹ | nearest size
|
|
675
|
-
| Google (Gemini) | 1 | ✓
|
|
676
|
-
| xAI | ✓ | ✓
|
|
677
|
-
| Meta | ✓ | ✓ (hint)
|
|
678
|
-
| Z.ai | ✗ | width × height
|
|
679
|
-
| Alibaba | ✓ | width × height
|
|
680
|
-
| MiniMax | ✓ | preset or w × h⁴
|
|
681
|
-
| Vercel AI Gateway | ✓ | as OpenAI³
|
|
682
|
-
| OpenRouter | ✓ | ✓ (`aspect_ratio`)
|
|
683
|
-
| Cloudflare Workers AI | 1 | width × height²
|
|
681
|
+
| Provider | `n` | `aspect` | `resolution` | `images` | Moved to `providerOptions` |
|
|
682
|
+
| --------------------- | --- | ------------------ | ------------------- | -------------------- | ----------------------------------------- |
|
|
683
|
+
| OpenAI | ✓¹ | nearest size | nearest size | ✓ | `size`, `outputFormat`, `mask` |
|
|
684
|
+
| Google (Gemini) | 1 | ✓ | ✓ (`0.5K` as `512`) | ✓ (no public URLs) | `seed` |
|
|
685
|
+
| xAI | ✓ | ✓ | `1k`/`2k` | ✓ | none |
|
|
686
|
+
| Meta | ✓ | ✓ (hint) | ignored | ✓ | `size`, `outputFormat` |
|
|
687
|
+
| Z.ai | ✗ | width × height | width × height | ✗ | `size` |
|
|
688
|
+
| Alibaba | ✓ | width × height | width × height | ✓ | `size`, `seed` |
|
|
689
|
+
| MiniMax | ✓ | preset or w × h⁴ | preset or w × h⁴ | 1 (portrait subject) | `aspect_ratio`, `width`, `height`, `seed` |
|
|
690
|
+
| Vercel AI Gateway | ✓ | as OpenAI³ | as OpenAI³ | per model | as OpenAI |
|
|
691
|
+
| OpenRouter | ✓ | ✓ (`aspect_ratio`) | tier⁵ | per model⁵ | `size`, `outputFormat` (no `mask`) |
|
|
692
|
+
| Cloudflare Workers AI | 1 | width × height² | width × height² | ✗ | `width`, `height`, `seed` |
|
|
684
693
|
|
|
685
694
|
✓ lowers natively; ✗ fails whenever the field is set (including `n: 1`); `1` means `n > 1` fails. "width × height"
|
|
686
695
|
computes a size the provider accepts and fails when the request falls outside its limits. ¹ `ai.image.stream` on OpenAI
|
|
@@ -851,11 +860,13 @@ and emits `image-partial` events before each final `image`; `ai.image.generate`
|
|
|
851
860
|
import { Stream } from "effect"
|
|
852
861
|
import { ImageEvent } from "@opencode/ai/effect"
|
|
853
862
|
|
|
854
|
-
const previews = ai.image
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
863
|
+
const previews = ai.image
|
|
864
|
+
.stream({
|
|
865
|
+
model: openai.image("gpt-image-2"),
|
|
866
|
+
prompt: "A lighthouse at dusk",
|
|
867
|
+
providerOptions: { partialImages: 2 },
|
|
868
|
+
})
|
|
869
|
+
.pipe(Stream.runForEach((event) => (ImageEvent.is.imagePartial(event) ? showPreview(event.image) : Effect.void)))
|
|
859
870
|
```
|
|
860
871
|
|
|
861
872
|
The provider may send fewer previews than requested when the final image is ready first.
|
package/dist/effect.d.ts
CHANGED
|
@@ -62,5 +62,5 @@ export type { AwaitOptions as GenerationAwaitOptions, Event as GenerationEvent,
|
|
|
62
62
|
export { ToolFailure, emptyInputJsonSchema, toDefinitions, tool } from "./tool.js";
|
|
63
63
|
export { ToolRuntime } from "./tool-runtime.js";
|
|
64
64
|
export type { ToolSettlement } from "./tool-runtime.js";
|
|
65
|
-
export type { ExecutableTool, Tool, ToolExecute, ToolExecuteContext, ToolModelOutputInput, ToolOptions, ToolSchema, ToolToModelOutput, } from "./tool.js";
|
|
65
|
+
export type { ExecutableTool, Tool, ToolExecute, ToolExecuteContext, ToolInput, ToolInputType, ToolModelOutputInput, ToolOptions, ToolSchema, ToolToModelOutput, } from "./tool.js";
|
|
66
66
|
export type { LLM } from "./llm.js";
|
package/dist/index.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { LanguageModel, type CompactionCheckpointResponse, type CompactionRespon
|
|
|
11
11
|
import type { LoopInput, LoopObjectEvent, ObjectEvent, ObjectInput, ObjectResponse, OutputSchema, OutputType, RequestInput } from "./llm.js";
|
|
12
12
|
import { type SpeechModel, type SpeechRequest, type SpeechRequestInput } from "./speech.js";
|
|
13
13
|
import { type TranscriptionModel, type TranscriptionRequest, type TranscriptionRequestInput } from "./transcription.js";
|
|
14
|
-
import type { NoExecute, ToolExecuteContext, ToolOptions, ToolSchema } from "./tool.js";
|
|
14
|
+
import type { NoExecute, ToolExecuteContext, ToolInput, ToolInputType, ToolOptions, ToolSchema } from "./tool.js";
|
|
15
15
|
import { type VideoModel, type VideoRequest, type VideoRequestInput } from "./video.js";
|
|
16
16
|
/**
|
|
17
17
|
* Promise-first entrypoint for scripts and non-Effect callers. One `ManagedRuntime` hosts the LLM, image, video, speech,
|
|
@@ -307,9 +307,9 @@ export declare const make: (options?: Options) => {
|
|
|
307
307
|
};
|
|
308
308
|
export type Client = ReturnType<typeof make>;
|
|
309
309
|
/** `tool` from `@opencode/ai/effect`, with an `execute` that returns a value or a Promise and throws to fail. */
|
|
310
|
-
export declare const tool: <
|
|
310
|
+
export declare const tool: <Input extends ToolInput = typeof Schema.Unknown, Success extends ToolSchema<any> = typeof Schema.Unknown, Result extends Schema.Schema.Type<Success> | PromiseLike<Schema.Schema.Type<Success>> | NoExecute = NoExecute>(config: ToolOptions<Input, Success, (input: ToolInputType<Input>, context: Partial<ToolExecuteContext> & {
|
|
311
311
|
signal: AbortSignal;
|
|
312
|
-
}) => Result>) => 0 extends 1 & Result ? import("./tool.js").ExecutableTool<
|
|
312
|
+
}) => Result>) => 0 extends 1 & Result ? import("./tool.js").ExecutableTool<Input, Success> : [Result, NoExecute] extends [NoExecute, Result] ? import("./tool.js").Tool<Input, Success> : import("./tool.js").ExecutableTool<Input, Success>;
|
|
313
313
|
/** Default client over `RequestExecutor.fetchLayer`; the runtime builds its layer on first use and holds nothing to dispose. */
|
|
314
314
|
export declare const ai: Omit<Client, "dispose">;
|
|
315
315
|
export * as AI from "./index.js";
|
|
@@ -322,5 +322,5 @@ export { ChoiceAnswer, ChoiceQuestion, ChoiceValue, DecisionAnswer, DecisionJson
|
|
|
322
322
|
export type { AnswerFor, AnswersFor, DecisionInput, DecisionModelOptions, DecisionOptions, DecisionQuestions, DecisionRequestFor, DecisionRequestInput, DecisionResponseFor, DecisionModelRoute, } from "./decision.js";
|
|
323
323
|
export { Media } from "./media.js";
|
|
324
324
|
export type { AwaitOptions as GenerationAwaitOptions, Event as GenerationEvent, Poll, Route as GenerationRoute, Snapshot as GenerationSnapshot, Status as GenerationStatus, } from "./generation.js";
|
|
325
|
-
export type { ExecutableTool, Tool, ToolExecute, ToolExecuteContext, ToolModelOutputInput, ToolOptions, ToolSchema, ToolToModelOutput, } from "./tool.js";
|
|
325
|
+
export type { ExecutableTool, Tool, ToolExecute, ToolExecuteContext, ToolInput, ToolInputType, ToolModelOutputInput, ToolOptions, ToolSchema, ToolToModelOutput, } from "./tool.js";
|
|
326
326
|
export type { LLM } from "./llm.js";
|
package/dist/index.js
CHANGED
|
@@ -130,8 +130,8 @@ const fileError = (message, cause) => new AIError({ reason: new InvalidRequestEr
|
|
|
130
130
|
export const tool = (config) => {
|
|
131
131
|
const execute = config.execute;
|
|
132
132
|
return build(config, execute &&
|
|
133
|
-
((
|
|
134
|
-
try: async (signal) => execute(
|
|
133
|
+
((input, context) => Effect.tryPromise({
|
|
134
|
+
try: async (signal) => execute(input, { ...context, signal }),
|
|
135
135
|
catch: (error) => new ToolFailure({ message: error instanceof Error ? error.message : String(error), error }),
|
|
136
136
|
})));
|
|
137
137
|
};
|
package/dist/llm.d.ts
CHANGED
|
@@ -3,11 +3,18 @@ import { Service, type StreamOptions } from "./route/client.js";
|
|
|
3
3
|
import { GenerationOptions, HttpOptions, AIError, LLMEvent, LLMRequest, LLMResponse, Message, LanguageModel, SystemPart, type Finish, ToolChoice, type ContentPart, type LanguageModelProviderOptions, type ToolEntryInput } from "./schema/index.js";
|
|
4
4
|
import { type ExecutableTool, type Tool, type ToolSchema } from "./tool.js";
|
|
5
5
|
/** Input accepted by `LLM.request`, normalized into the canonical `LLMRequest` class. */
|
|
6
|
-
export type RequestInput<SelectedLanguageModel extends LanguageModel = LanguageModel> =
|
|
6
|
+
export type RequestInput<SelectedLanguageModel extends LanguageModel = LanguageModel> = RequestFields<SelectedLanguageModel> & PromptOrMessages;
|
|
7
|
+
/** Exactly one of `prompt`, a single user message, or `messages`, the full conversation. */
|
|
8
|
+
export type PromptOrMessages = {
|
|
9
|
+
readonly prompt: string | ContentPart | ReadonlyArray<ContentPart>;
|
|
10
|
+
readonly messages?: never;
|
|
11
|
+
} | {
|
|
12
|
+
readonly messages: ReadonlyArray<Message | Message.Input>;
|
|
13
|
+
readonly prompt?: never;
|
|
14
|
+
};
|
|
15
|
+
type RequestFields<SelectedLanguageModel extends LanguageModel> = Omit<ConstructorParameters<typeof LLMRequest>[0], "model" | "system" | "messages" | "tools" | "toolChoice" | "generation" | "http" | "providerOptions"> & {
|
|
7
16
|
readonly model: SelectedLanguageModel;
|
|
8
17
|
readonly system?: string | SystemPart | ReadonlyArray<SystemPart>;
|
|
9
|
-
readonly prompt?: string | ContentPart | ReadonlyArray<ContentPart>;
|
|
10
|
-
readonly messages?: ReadonlyArray<Message | Message.Input>;
|
|
11
18
|
/** Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. */
|
|
12
19
|
readonly tools?: ReadonlyArray<Tool | ToolEntryInput>;
|
|
13
20
|
readonly toolChoice?: ToolChoice.Input;
|
|
@@ -38,7 +45,7 @@ export declare function generate<const Model extends LanguageModel>(input: Reque
|
|
|
38
45
|
/** Stream one model call. With `schema`, the `finish` event carries the decoded `object`. */
|
|
39
46
|
export declare function stream<const Model extends LanguageModel, S extends OutputSchema>(input: ObjectInput<S, Model>, options?: StreamOptions): Stream.Stream<ObjectEvent<OutputType<S>>, AIError, Service>;
|
|
40
47
|
export declare function stream<const Model extends LanguageModel>(input: RequestInput<Model> | LLMRequest, options?: StreamOptions): Stream.Stream<LLMEvent, AIError, Service>;
|
|
41
|
-
export type LoopInput<SelectedLanguageModel extends LanguageModel = LanguageModel> = Omit<
|
|
48
|
+
export type LoopInput<SelectedLanguageModel extends LanguageModel = LanguageModel> = Omit<RequestFields<SelectedLanguageModel>, "tools"> & PromptOrMessages & {
|
|
42
49
|
readonly tools: ReadonlyArray<ExecutableTool>;
|
|
43
50
|
/** Called after each step that has tool calls; returning `true` ends the loop without running them. */
|
|
44
51
|
readonly until?: (state: {
|
package/dist/llm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Effect, JsonSchema, Schema, Stream } from "effect";
|
|
2
2
|
import { tryRequest } from "./media-model.js";
|
|
3
3
|
import { LLMClient, Service } from "./route/client.js";
|
|
4
|
-
import { GenerationOptions, HttpOptions, InvalidProviderOutputError, AIError, LLMEvent, LLMRequest, LLMResponse, Message, LanguageModel, SystemPart, ToolChoice, ToolEntry, withPartial, } from "./schema/index.js";
|
|
4
|
+
import { GenerationOptions, HttpOptions, InvalidProviderOutputError, InvalidRequestError, AIError, LLMEvent, LLMRequest, LLMResponse, Message, LanguageModel, SystemPart, ToolChoice, ToolEntry, withPartial, } from "./schema/index.js";
|
|
5
5
|
import { tool } from "./tool.js";
|
|
6
6
|
import { ToolRuntime } from "./tool-runtime.js";
|
|
7
7
|
export function generate(input, options) {
|
|
@@ -73,11 +73,7 @@ const prepare = (input) => {
|
|
|
73
73
|
const { schema, ...rest } = input;
|
|
74
74
|
return tryRequest(() => {
|
|
75
75
|
const description = "Return the structured result by calling this tool.";
|
|
76
|
-
const output = schema === undefined
|
|
77
|
-
? undefined
|
|
78
|
-
: Schema.isSchema(schema)
|
|
79
|
-
? tool({ name: OBJECT_TOOL, description, parameters: schema })
|
|
80
|
-
: tool({ name: OBJECT_TOOL, description, jsonSchema: schema });
|
|
76
|
+
const output = schema === undefined ? undefined : tool({ name: OBJECT_TOOL, description, input: schema });
|
|
81
77
|
const tools = rest.tools ?? [];
|
|
82
78
|
const built = request(output === undefined
|
|
83
79
|
? rest
|
|
@@ -95,13 +91,14 @@ const prepare = (input) => {
|
|
|
95
91
|
const decodeObject = (output, response) => {
|
|
96
92
|
const call = response.toolCalls.find((event) => event.name === OBJECT_TOOL);
|
|
97
93
|
const invalid = (message, cause) => new AIError({ reason: new InvalidProviderOutputError({ message, cause }), partial: response });
|
|
94
|
+
// A cut-off call arrives with truncated or empty input, so its decode error would hide the real cause.
|
|
95
|
+
if (response.finishReason.normalized === "length")
|
|
96
|
+
return Effect.fail(invalid("output hit the token limit before the forced tool call completed"));
|
|
98
97
|
if (call)
|
|
99
98
|
return output
|
|
100
99
|
._decode(call.input)
|
|
101
100
|
.pipe(Effect.mapError((error) => invalid(`schema decode failed: ${error.message}`, error)));
|
|
102
|
-
return Effect.fail(invalid(
|
|
103
|
-
? "output hit the token limit before the forced tool call completed"
|
|
104
|
-
: `model did not call the forced \`${OBJECT_TOOL}\` tool`));
|
|
101
|
+
return Effect.fail(invalid(`model did not call the forced \`${OBJECT_TOOL}\` tool`));
|
|
105
102
|
};
|
|
106
103
|
const withObject = (output, event, state) => {
|
|
107
104
|
const response = LLMResponse.complete(state);
|
|
@@ -111,10 +108,14 @@ const withObject = (output, event, state) => {
|
|
|
111
108
|
};
|
|
112
109
|
export const request = (input) => {
|
|
113
110
|
const { system: requestSystem, prompt, messages, tools, toolChoice: requestToolChoice, generation: requestGeneration, providerOptions: requestProviderOptions, http: requestHttp, ...rest } = input;
|
|
111
|
+
if ((prompt === undefined) === (messages === undefined))
|
|
112
|
+
throw new AIError({
|
|
113
|
+
reason: new InvalidRequestError({ message: "Pass exactly one of `prompt` or `messages`, not both or neither" }),
|
|
114
|
+
});
|
|
114
115
|
return new LLMRequest({
|
|
115
116
|
...rest,
|
|
116
117
|
system: SystemPart.content(requestSystem),
|
|
117
|
-
messages:
|
|
118
|
+
messages: prompt === undefined ? (messages ?? []).map(Message.make) : [Message.user(prompt)],
|
|
118
119
|
tools: tools?.map((item) => ("_definition" in item ? item._definition : ToolEntry.make(item))) ?? [],
|
|
119
120
|
toolChoice: requestToolChoice ? ToolChoice.make(requestToolChoice) : undefined,
|
|
120
121
|
generation: requestGeneration === undefined ? undefined : GenerationOptions.make(requestGeneration),
|
package/dist/media-model.js
CHANGED
|
@@ -41,10 +41,12 @@ const isQueuedInput = (route) => route.protocol.kind === "queued";
|
|
|
41
41
|
/** Lift a synchronous Schema-class constructor into a typed `InvalidRequest` failure. */
|
|
42
42
|
export const tryRequest = (make) => Effect.try({
|
|
43
43
|
try: make,
|
|
44
|
-
catch: (error) =>
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
44
|
+
catch: (error) => error instanceof AIError
|
|
45
|
+
? error
|
|
46
|
+
: new AIError({
|
|
47
|
+
reason: new InvalidRequestError({
|
|
48
|
+
message: error instanceof Error ? error.message : String(error),
|
|
49
|
+
cause: error,
|
|
50
|
+
}),
|
|
48
51
|
}),
|
|
49
|
-
}),
|
|
50
52
|
});
|
package/dist/tool.d.ts
CHANGED
|
@@ -3,30 +3,34 @@ import type { Content } from "@opencode/schema/tool";
|
|
|
3
3
|
import type { Freeform, ToolCallPart, ToolDefinition as ToolDefinitionClass, ToolOutput as ToolOutputType } from "./schema/index.js";
|
|
4
4
|
import { ToolFailure } from "./schema/index.js";
|
|
5
5
|
/**
|
|
6
|
-
* Schema constraint for tool
|
|
6
|
+
* Schema constraint for tool input / success values: no decoding or
|
|
7
7
|
* encoding services are allowed. Tools should be self-contained — anything
|
|
8
8
|
* beyond pure data conversion belongs in the handler closure.
|
|
9
9
|
*/
|
|
10
10
|
export type ToolSchema<T> = Schema.Codec<T, any, never, never>;
|
|
11
|
+
/** A tool's `input`: an Effect Schema decodes and types it; a raw JSON Schema leaves it `unknown`. */
|
|
12
|
+
export type ToolInput = ToolSchema<any> | JsonSchema.JsonSchema;
|
|
13
|
+
/** The value `execute` receives for a tool `input`. */
|
|
14
|
+
export type ToolInputType<Input extends ToolInput> = Input extends ToolSchema<infer T> ? T : unknown;
|
|
11
15
|
export interface ToolExecuteContext {
|
|
12
16
|
readonly id: ToolCallPart["id"];
|
|
13
17
|
readonly name: ToolCallPart["name"];
|
|
14
18
|
readonly namespace?: ToolCallPart["namespace"];
|
|
15
19
|
}
|
|
16
|
-
export type ToolExecute<
|
|
17
|
-
export interface ToolModelOutputInput<
|
|
20
|
+
export type ToolExecute<Input extends ToolInput, Success extends ToolSchema<any>> = (input: ToolInputType<Input>, context?: ToolExecuteContext) => Effect.Effect<Schema.Schema.Type<Success>, ToolFailure>;
|
|
21
|
+
export interface ToolModelOutputInput<Input, Output> {
|
|
18
22
|
readonly id: ToolCallPart["id"];
|
|
19
|
-
readonly
|
|
23
|
+
readonly input: Input;
|
|
20
24
|
readonly output: Output;
|
|
21
25
|
}
|
|
22
|
-
export type ToolToModelOutput<
|
|
26
|
+
export type ToolToModelOutput<Input extends ToolInput, Success extends ToolSchema<any>> = (result: ToolModelOutputInput<ToolInputType<Input>, Success["Encoded"]>) => ReadonlyArray<Content>;
|
|
23
27
|
type FreeformField<T> = {
|
|
24
28
|
[K in keyof T]-?: [Exclude<keyof T, K>] extends [never] ? {} extends Pick<T, K> ? never : T[K] extends string ? K : never : never;
|
|
25
29
|
}[keyof T];
|
|
26
|
-
/** `Freeform` for exactly one required string
|
|
27
|
-
export type FreeformOption<
|
|
30
|
+
/** `Freeform` for exactly one required string field or unknown ones (a JSON Schema `input`), otherwise `undefined`. */
|
|
31
|
+
export type FreeformOption<Input extends ToolInput> = unknown extends ToolInputType<Input> ? Freeform : [FreeformField<ToolInputType<Input>>] extends [never] ? undefined : Freeform;
|
|
28
32
|
/**
|
|
29
|
-
* A type-safe LLM tool. Each tool bundles its own description,
|
|
33
|
+
* A type-safe LLM tool. Each tool bundles its own description, input
|
|
30
34
|
* Schema and success Schema. The execute handler is optional: omit it when you
|
|
31
35
|
* only want to expose a tool schema to the model and handle tool calls outside
|
|
32
36
|
* this package.
|
|
@@ -37,48 +41,47 @@ export type FreeformOption<Parameters extends ToolSchema<any>> = unknown extends
|
|
|
37
41
|
* Internally each tool also carries memoized codecs and a precomputed
|
|
38
42
|
* `ToolDefinition` so callers do not rebuild them per invocation.
|
|
39
43
|
*/
|
|
40
|
-
export interface Tool<
|
|
44
|
+
export interface Tool<Input extends ToolInput = any, Success extends ToolSchema<any> = any> {
|
|
41
45
|
/** The tool name the model sees and calls. */
|
|
42
46
|
readonly name: string;
|
|
43
47
|
readonly description: string;
|
|
44
|
-
readonly
|
|
48
|
+
readonly input: Input;
|
|
45
49
|
readonly success: Success;
|
|
46
|
-
readonly execute?: ToolExecute<
|
|
47
|
-
readonly toModelOutput?: ToolToModelOutput<
|
|
50
|
+
readonly execute?: ToolExecute<Input, Success>;
|
|
51
|
+
readonly toModelOutput?: ToolToModelOutput<Input, Success>;
|
|
48
52
|
readonly toStructuredOutput?: (output: Success["Encoded"]) => unknown;
|
|
49
53
|
/** @internal */
|
|
50
|
-
readonly _decode: (input: unknown) => Effect.Effect<
|
|
54
|
+
readonly _decode: (input: unknown) => Effect.Effect<ToolInputType<Input>, Schema.SchemaError>;
|
|
51
55
|
/** @internal */
|
|
52
56
|
_encode(value: Schema.Schema.Type<Success>): Effect.Effect<unknown, Schema.SchemaError>;
|
|
53
57
|
/** @internal */
|
|
54
|
-
_project(
|
|
58
|
+
_project(input: ToolInputType<Input>, id: ToolCallPart["id"], output: unknown): ToolOutputType;
|
|
55
59
|
/** @internal */
|
|
56
60
|
readonly _legacyResult: boolean;
|
|
57
61
|
/** @internal */
|
|
58
62
|
readonly _definition: ToolDefinitionClass;
|
|
59
63
|
}
|
|
60
64
|
/** A tool with an `execute` handler, which `LLM.loop` and `ToolRuntime.dispatch` can run. */
|
|
61
|
-
export type ExecutableTool<
|
|
62
|
-
readonly execute: ToolExecute<
|
|
65
|
+
export type ExecutableTool<Input extends ToolInput = any, Success extends ToolSchema<any> = any> = Tool<Input, Success> & {
|
|
66
|
+
readonly execute: ToolExecute<Input, Success>;
|
|
63
67
|
};
|
|
64
68
|
/**
|
|
65
|
-
* Options for `tool`, where `Execute` is the only part that differs between the Effect and Promise clients. Pass
|
|
66
|
-
* Effect `
|
|
67
|
-
* `undefined` as `null`), or raw `
|
|
68
|
-
* a tool the model can call without running it here.
|
|
69
|
+
* Options for `tool`, where `Execute` is the only part that differs between the Effect and Promise clients. Pass an
|
|
70
|
+
* Effect Schema `input` (and optionally a `success` schema that validates the result, otherwise it is sent as is with
|
|
71
|
+
* `undefined` as `null`), or a raw JSON Schema `input` known only at runtime, such as an MCP tool's, with an optional
|
|
72
|
+
* JSON Schema `outputSchema`. Omit `execute` to declare a tool the model can call without running it here.
|
|
69
73
|
*/
|
|
70
|
-
export type ToolOptions<
|
|
74
|
+
export type ToolOptions<Input extends ToolInput, Success extends ToolSchema<any>, Execute = ToolExecute<Input, Success>> = {
|
|
71
75
|
readonly name: string;
|
|
72
76
|
readonly description: string;
|
|
73
|
-
readonly
|
|
77
|
+
readonly input: Input;
|
|
78
|
+
readonly freeform?: FreeformOption<Input>;
|
|
74
79
|
readonly execute?: Execute;
|
|
75
|
-
readonly toModelOutput?: ToolToModelOutput<
|
|
80
|
+
readonly toModelOutput?: ToolToModelOutput<Input, Success>;
|
|
76
81
|
readonly toStructuredOutput?: (output: Success["Encoded"]) => unknown;
|
|
77
|
-
} & ({
|
|
78
|
-
readonly parameters: Parameters;
|
|
82
|
+
} & (Input extends ToolSchema<any> ? {
|
|
79
83
|
readonly success?: Success;
|
|
80
|
-
}
|
|
81
|
-
readonly jsonSchema: JsonSchema.JsonSchema;
|
|
84
|
+
} : {
|
|
82
85
|
readonly outputSchema?: JsonSchema.JsonSchema;
|
|
83
86
|
});
|
|
84
87
|
/**
|
|
@@ -88,20 +91,20 @@ export type ToolOptions<Parameters extends ToolSchema<any>, Success extends Tool
|
|
|
88
91
|
* tool({
|
|
89
92
|
* name: "weather",
|
|
90
93
|
* description: "Get current weather",
|
|
91
|
-
*
|
|
94
|
+
* input: Schema.Struct({ city: Schema.String }),
|
|
92
95
|
* success: Schema.Struct({ temperature: Schema.Number }),
|
|
93
96
|
* execute: ({ city }) => Effect.succeed({ temperature: 22 }),
|
|
94
97
|
* })
|
|
95
98
|
* ```
|
|
96
99
|
*/
|
|
97
|
-
export declare const tool: <
|
|
100
|
+
export declare const tool: <Input extends ToolInput = typeof Schema.Unknown, Success extends ToolSchema<any> = typeof Schema.Unknown, Result extends Effect.Effect<Schema.Schema.Type<Success>, ToolFailure> | NoExecute = NoExecute>(config: ToolOptions<Input, Success, (input: ToolInputType<Input>, context?: ToolExecuteContext) => Result>) => 0 extends 1 & Result ? ExecutableTool<Input, Success> : [Result, NoExecute] extends [NoExecute, Result] ? Tool<Input, Success> : ExecutableTool<Input, Success>;
|
|
98
101
|
declare const noExecute: unique symbol;
|
|
99
102
|
/** @internal The inferred `execute` result when `execute` is omitted; no function can return it. */
|
|
100
103
|
export type NoExecute = {
|
|
101
104
|
readonly [noExecute]: never;
|
|
102
105
|
};
|
|
103
106
|
/** @internal Builds a tool for both clients from its options and an Effect `execute`. */
|
|
104
|
-
export declare function build<
|
|
107
|
+
export declare function build<Input extends ToolInput, Success extends ToolSchema<any>, Result>(config: ToolOptions<Input, Success, (...args: never) => Result>, execute: ((input: ToolInputType<Input>, context?: ToolExecuteContext) => unknown) | undefined): 0 extends 1 & Result ? ExecutableTool<Input, Success> : [Result, NoExecute] extends [NoExecute, Result] ? Tool<Input, Success> : ExecutableTool<Input, Success>;
|
|
105
108
|
/** The `ToolDefinition[]` that `LLMRequest.tools` expects, in array order. */
|
|
106
109
|
export declare const toDefinitions: (tools: ReadonlyArray<Tool>) => ReadonlyArray<ToolDefinitionClass>;
|
|
107
110
|
/**
|
package/dist/tool.js
CHANGED
|
@@ -8,7 +8,7 @@ import { isRecord } from "./utils/record.js";
|
|
|
8
8
|
* tool({
|
|
9
9
|
* name: "weather",
|
|
10
10
|
* description: "Get current weather",
|
|
11
|
-
*
|
|
11
|
+
* input: Schema.Struct({ city: Schema.String }),
|
|
12
12
|
* success: Schema.Struct({ temperature: Schema.Number }),
|
|
13
13
|
* execute: ({ city }) => Effect.succeed({ temperature: 22 }),
|
|
14
14
|
* })
|
|
@@ -22,12 +22,13 @@ export function build(config, execute) {
|
|
|
22
22
|
execute,
|
|
23
23
|
toModelOutput: config.toModelOutput,
|
|
24
24
|
toStructuredOutput: config.toStructuredOutput,
|
|
25
|
-
_project: (
|
|
25
|
+
_project: (input, id, output) => project(config.toModelOutput, config.toStructuredOutput, input, id, output),
|
|
26
26
|
};
|
|
27
|
-
|
|
27
|
+
const input = config.input;
|
|
28
|
+
if (!Schema.isSchema(input))
|
|
28
29
|
return {
|
|
29
30
|
...shared,
|
|
30
|
-
|
|
31
|
+
input,
|
|
31
32
|
success: Schema.Unknown,
|
|
32
33
|
_decode: Effect.succeed,
|
|
33
34
|
_encode: Effect.succeed,
|
|
@@ -35,22 +36,22 @@ export function build(config, execute) {
|
|
|
35
36
|
_definition: definition({
|
|
36
37
|
name: config.name,
|
|
37
38
|
description: config.description,
|
|
38
|
-
inputSchema:
|
|
39
|
+
inputSchema: input,
|
|
39
40
|
outputSchema: config.outputSchema,
|
|
40
41
|
freeform: config.freeform,
|
|
41
42
|
}),
|
|
42
43
|
};
|
|
43
44
|
return {
|
|
44
45
|
...shared,
|
|
45
|
-
|
|
46
|
+
input,
|
|
46
47
|
success: config.success ?? Schema.Unknown,
|
|
47
|
-
_decode: Schema.decodeUnknownEffect(
|
|
48
|
+
_decode: Schema.decodeUnknownEffect(input),
|
|
48
49
|
_encode: config.success ? Schema.encodeEffect(config.success) : (value) => Effect.succeed(value ?? null),
|
|
49
50
|
_legacyResult: false,
|
|
50
51
|
_definition: definition({
|
|
51
52
|
name: config.name,
|
|
52
53
|
description: config.description,
|
|
53
|
-
inputSchema: emptyInputJsonSchema(
|
|
54
|
+
inputSchema: emptyInputJsonSchema(input) ?? toJsonSchema(input),
|
|
54
55
|
outputSchema: config.success && toJsonSchema(config.success),
|
|
55
56
|
freeform: config.freeform,
|
|
56
57
|
}),
|
|
@@ -87,5 +88,5 @@ const toJsonSchema = (schema) => {
|
|
|
87
88
|
return document.schema;
|
|
88
89
|
return { ...document.schema, $defs: document.definitions };
|
|
89
90
|
};
|
|
90
|
-
const project = (toModelOutput, toStructuredOutput,
|
|
91
|
+
const project = (toModelOutput, toStructuredOutput, input, id, output) => ToolOutput.make(toStructuredOutput?.(output) ?? output, toModelOutput?.({ id, input, output }) ?? (typeof output === "string" ? [{ type: "text", text: output }] : []));
|
|
91
92
|
export { ToolFailure };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
|
-
"version": "0.0.0-dev-
|
|
3
|
+
"version": "0.0.0-dev-461",
|
|
4
4
|
"name": "@opencode/ai",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -520,7 +520,7 @@
|
|
|
520
520
|
"devDependencies": {
|
|
521
521
|
"@clack/prompts": "1.0.0-alpha.1",
|
|
522
522
|
"@effect/platform-node": "4.1.0",
|
|
523
|
-
"@opencode/http-recorder": "0.0.0-dev-
|
|
523
|
+
"@opencode/http-recorder": "0.0.0-dev-461",
|
|
524
524
|
"@tsconfig/bun": "1.0.9",
|
|
525
525
|
"@types/bun": "1.4.3",
|
|
526
526
|
"@typescript/native": "npm:typescript@7.1.0-beta",
|
|
@@ -530,7 +530,7 @@
|
|
|
530
530
|
"@aws-sdk/credential-providers": "3.1057.0",
|
|
531
531
|
"@smithy/eventstream-codec": "4.2.14",
|
|
532
532
|
"@smithy/util-utf8": "4.2.2",
|
|
533
|
-
"@opencode/schema": "0.0.0-dev-
|
|
533
|
+
"@opencode/schema": "0.0.0-dev-461",
|
|
534
534
|
"aws4fetch": "1.0.20",
|
|
535
535
|
"effect": "4.1.0",
|
|
536
536
|
"google-auth-library": "10.5.0"
|