@opencode/ai 2.2.2 → 2.2.4
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 +159 -144
- package/dist/decision.d.ts +0 -1
- package/dist/effect.d.ts +47 -17
- package/dist/effect.js +25 -13
- package/dist/experimental/testing.d.ts +3 -0
- package/dist/experimental/testing.js +3 -0
- package/dist/experimental.d.ts +12 -0
- package/dist/experimental.js +9 -0
- package/dist/index.d.ts +637 -1323
- package/dist/index.js +60 -56
- package/dist/llm.d.ts +4 -3
- package/dist/llm.js +21 -29
- package/dist/protocols/alibaba-responses.d.ts +2 -2
- package/dist/protocols/assemblyai-transcription.js +3 -3
- package/dist/protocols/meta-responses.d.ts +4 -4
- package/dist/protocols/open-responses.d.ts +18 -18
- package/dist/protocols/open-responses.js +4 -2
- package/dist/protocols/openai-compatible-responses.d.ts +2 -2
- package/dist/protocols/openai-responses.d.ts +12 -12
- package/dist/protocols/runway-video.js +2 -2
- package/dist/protocols/xai-responses.d.ts +2 -2
- package/dist/protocols/xai-responses.js +1 -1
- package/dist/protocols/xai-video.js +2 -2
- package/dist/providers/alibaba.d.ts +2 -2
- package/dist/providers/amazon-bedrock-mantle.d.ts +2 -2
- package/dist/providers/azure.d.ts +4 -4
- package/dist/providers/cloudflare-ai-gateway.d.ts +4 -4
- package/dist/providers/digitalocean.d.ts +2 -2
- package/dist/providers/google-vertex-responses.d.ts +2 -2
- package/dist/providers/meta.d.ts +2 -2
- package/dist/providers/minimax.d.ts +2 -2
- package/dist/providers/moonshot.d.ts +2 -2
- package/dist/providers/openai-compatible-responses.d.ts +2 -2
- package/dist/providers/openai.d.ts +2 -2
- package/dist/providers/openrouter/responses.d.ts +1 -2
- package/dist/providers/openrouter.d.ts +36 -23
- package/dist/providers/openrouter.js +29 -10
- package/dist/providers/venice.d.ts +2 -2
- package/dist/providers/zai-coding-plan.d.ts +2 -2
- package/dist/route/client.d.ts +3 -2
- package/dist/route/client.js +6 -9
- package/dist/route/media-protocol.d.ts +2 -3
- package/dist/route/media-protocol.js +2 -6
- package/dist/schema/errors.d.ts +6 -0
- package/dist/schema/errors.js +8 -0
- package/dist/schema/events.d.ts +2 -0
- package/dist/schema/events.js +4 -0
- package/dist/testing.d.ts +1 -4
- package/dist/testing.js +4 -12
- package/dist/tool.d.ts +40 -73
- package/dist/tool.js +27 -18
- package/package.json +7 -3
|
@@ -7,6 +7,7 @@ import { ProviderID } from "../schema/index.js";
|
|
|
7
7
|
import { SystemOne } from "../protocols/system-one.js";
|
|
8
8
|
import { OpenAIImages } from "../protocols/openai-images.js";
|
|
9
9
|
import { MediaRoute } from "../route/media.js";
|
|
10
|
+
import { HttpTransport } from "../route/transport/index.js";
|
|
10
11
|
import { OpenAIChat } from "../protocols/openai-chat.js";
|
|
11
12
|
import { OpenResponses } from "../protocols/open-responses.js";
|
|
12
13
|
import { cacheControl } from "../protocols/utils/cache.js";
|
|
@@ -14,14 +15,17 @@ import { isRecord, JsonObject, lenient, ProviderShared } from "../protocols/shar
|
|
|
14
15
|
export const id = ProviderID.make("openrouter");
|
|
15
16
|
const baseURL = "https://openrouter.ai/api/v1";
|
|
16
17
|
const ADAPTER = "openrouter";
|
|
17
|
-
const
|
|
18
|
-
usage: lenient(Schema.Union([Schema.Boolean, JsonObject])),
|
|
18
|
+
const SharedOptions = Schema.Struct({
|
|
19
19
|
models: lenient(Schema.Array(Schema.String)),
|
|
20
20
|
provider: lenient(JsonObject),
|
|
21
21
|
plugins: lenient(Schema.Array(JsonObject)),
|
|
22
|
-
web_search_options: lenient(JsonObject),
|
|
23
22
|
debug: lenient(JsonObject),
|
|
24
23
|
user: lenient(Schema.String),
|
|
24
|
+
});
|
|
25
|
+
const Options = Schema.Struct({
|
|
26
|
+
...SharedOptions.fields,
|
|
27
|
+
usage: lenient(Schema.Union([Schema.Boolean, JsonObject])),
|
|
28
|
+
web_search_options: lenient(JsonObject),
|
|
25
29
|
reasoning: lenient(JsonObject),
|
|
26
30
|
});
|
|
27
31
|
const decodeOptions = Schema.decodeUnknownSync(Options);
|
|
@@ -74,12 +78,8 @@ const bodyOptions = (body, input, maxTokens) => {
|
|
|
74
78
|
...options,
|
|
75
79
|
...body,
|
|
76
80
|
...(usage !== undefined ? { usage } : {}),
|
|
77
|
-
...(known
|
|
78
|
-
...(known.provider !== undefined ? { provider: known.provider } : {}),
|
|
79
|
-
...(known.plugins !== undefined ? { plugins: known.plugins } : {}),
|
|
81
|
+
...sharedOptions(known),
|
|
80
82
|
...(known.web_search_options !== undefined ? { web_search_options: known.web_search_options } : {}),
|
|
81
|
-
...(known.debug !== undefined ? { debug: known.debug } : {}),
|
|
82
|
-
...(known.user !== undefined ? { user: known.user } : {}),
|
|
83
83
|
...(known.reasoning !== undefined ? { reasoning: fitReasoning(known.reasoning, maxTokens) } : {}),
|
|
84
84
|
};
|
|
85
85
|
};
|
|
@@ -96,6 +96,25 @@ const imageSizing = (request) => {
|
|
|
96
96
|
resolution: resolution !== undefined && IMAGE_RESOLUTIONS.has(resolution) ? resolution : undefined,
|
|
97
97
|
};
|
|
98
98
|
};
|
|
99
|
+
const sharedOptions = (known) => ({
|
|
100
|
+
...(known.models !== undefined ? { models: known.models } : {}),
|
|
101
|
+
...(known.provider !== undefined ? { provider: known.provider } : {}),
|
|
102
|
+
...(known.plugins !== undefined ? { plugins: known.plugins } : {}),
|
|
103
|
+
...(known.debug !== undefined ? { debug: known.debug } : {}),
|
|
104
|
+
...(known.user !== undefined ? { user: known.user } : {}),
|
|
105
|
+
});
|
|
106
|
+
const OpenRouterResponsesBody = Schema.Struct({
|
|
107
|
+
...OpenResponses.OpenResponsesBody.fields,
|
|
108
|
+
...SharedOptions.fields,
|
|
109
|
+
});
|
|
110
|
+
const responsesProtocol = Protocol.make({
|
|
111
|
+
id: "openrouter-responses",
|
|
112
|
+
body: {
|
|
113
|
+
schema: OpenRouterResponsesBody,
|
|
114
|
+
from: (request) => OpenResponses.fromRequest(request).pipe(Effect.map((body) => ({ ...body, ...sharedOptions(decodeOptions(request.providerOptions ?? {})) }))),
|
|
115
|
+
},
|
|
116
|
+
stream: OpenResponses.protocol.stream,
|
|
117
|
+
});
|
|
99
118
|
export const route = Route.make({
|
|
100
119
|
id: ADAPTER,
|
|
101
120
|
provider: id,
|
|
@@ -108,9 +127,9 @@ const responsesRoute = Route.make({
|
|
|
108
127
|
id: "openrouter-responses",
|
|
109
128
|
provider: id,
|
|
110
129
|
providerMetadataKey: "openrouter",
|
|
111
|
-
protocol:
|
|
130
|
+
protocol: responsesProtocol,
|
|
112
131
|
endpoint: Endpoint.path("/responses", { baseURL }),
|
|
113
|
-
transport:
|
|
132
|
+
transport: HttpTransport.sseJson.with(),
|
|
114
133
|
defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } },
|
|
115
134
|
});
|
|
116
135
|
export const routes = [route, responsesRoute];
|
|
@@ -46,7 +46,7 @@ export declare const routes: (Route<{
|
|
|
46
46
|
readonly detail?: string | undefined;
|
|
47
47
|
} | {
|
|
48
48
|
readonly type: "input_file";
|
|
49
|
-
readonly filename
|
|
49
|
+
readonly filename?: string | undefined;
|
|
50
50
|
readonly detail?: string | undefined;
|
|
51
51
|
readonly file_data?: string | undefined;
|
|
52
52
|
readonly file_url?: string | undefined;
|
|
@@ -78,7 +78,7 @@ export declare const routes: (Route<{
|
|
|
78
78
|
readonly detail?: string | undefined;
|
|
79
79
|
} | {
|
|
80
80
|
readonly type: "input_file";
|
|
81
|
-
readonly filename
|
|
81
|
+
readonly filename?: string | undefined;
|
|
82
82
|
readonly detail?: string | undefined;
|
|
83
83
|
readonly file_data?: string | undefined;
|
|
84
84
|
readonly file_url?: string | undefined;
|
|
@@ -49,7 +49,7 @@ export declare const routes: (Route<{
|
|
|
49
49
|
readonly detail?: string | undefined;
|
|
50
50
|
} | {
|
|
51
51
|
readonly type: "input_file";
|
|
52
|
-
readonly filename
|
|
52
|
+
readonly filename?: string | undefined;
|
|
53
53
|
readonly detail?: string | undefined;
|
|
54
54
|
readonly file_data?: string | undefined;
|
|
55
55
|
readonly file_url?: string | undefined;
|
|
@@ -81,7 +81,7 @@ export declare const routes: (Route<{
|
|
|
81
81
|
readonly detail?: string | undefined;
|
|
82
82
|
} | {
|
|
83
83
|
readonly type: "input_file";
|
|
84
|
-
readonly filename
|
|
84
|
+
readonly filename?: string | undefined;
|
|
85
85
|
readonly detail?: string | undefined;
|
|
86
86
|
readonly file_data?: string | undefined;
|
|
87
87
|
readonly file_url?: string | undefined;
|
package/dist/route/client.d.ts
CHANGED
|
@@ -208,6 +208,9 @@ export declare const compileRequest: (request: LLMRequest<LanguageModel<{
|
|
|
208
208
|
transport: string;
|
|
209
209
|
};
|
|
210
210
|
}, AIError, never>;
|
|
211
|
+
export declare const generateWith: (stream: Interface["stream"]) => (request: LLMRequest<LanguageModel<{
|
|
212
|
+
readonly [x: string]: unknown;
|
|
213
|
+
}, CompactionOperations | undefined>>, options?: StreamOptions | undefined) => Effect.Effect<LLMResponse, AIError, never>;
|
|
211
214
|
export declare function stream(request: LLMRequest, options?: StreamOptions): Stream.Stream<LLMEvent, AIError, Service>;
|
|
212
215
|
export declare function generate(request: LLMRequest, options?: StreamOptions): Effect.Effect<LLMResponse, AIError, Service>;
|
|
213
216
|
export declare function compact(request: CheckpointRequest, options: TriggerCompactOptions): Effect.Effect<CompactionCheckpointResponse, AIError, Service>;
|
|
@@ -217,8 +220,6 @@ export declare const Route: {
|
|
|
217
220
|
readonly make: typeof make;
|
|
218
221
|
};
|
|
219
222
|
export declare const LLMClient: {
|
|
220
|
-
readonly canCompact: typeof canCompact;
|
|
221
|
-
readonly compact: typeof compact;
|
|
222
223
|
readonly Service: typeof LLMClientService;
|
|
223
224
|
readonly layer: Layer.Layer<LLMClientService, never, RequestExecutor.RequestExecutorService>;
|
|
224
225
|
readonly stream: typeof stream;
|
package/dist/route/client.js
CHANGED
|
@@ -10,7 +10,7 @@ import { normalizeToolHistory } from "../tool-history.js";
|
|
|
10
10
|
import { sanitizeSurrogates } from "../utils/sanitize.js";
|
|
11
11
|
import * as ProviderShared from "../protocols/shared.js";
|
|
12
12
|
import { ToolSchemaProjection } from "../protocols/utils/tool-schema.js";
|
|
13
|
-
import { AIError, CompactionResponse, CompactionCheckpointResponse, AIErrorReason, GenerationOptions, HttpOptions, LLMRequest, LLMResponse, LanguageModel, LLMEvent, InvalidProviderOutputError, ProviderConfigurationError, ProviderID, mergeGenerationOptions, mergeHttpOptions, mergeProviderOptions, } from "../schema/index.js";
|
|
13
|
+
import { AIError, CompactionResponse, CompactionCheckpointResponse, AIErrorReason, GenerationOptions, HttpOptions, LLMRequest, LLMResponse, LanguageModel, LLMEvent, InvalidProviderOutputError, ProviderConfigurationError, ProviderID, mergeGenerationOptions, mergeHttpOptions, mergeProviderOptions, withPartial, } from "../schema/index.js";
|
|
14
14
|
const makeRouteLanguageModel = (route, mapped) => {
|
|
15
15
|
const provider = route.provider ?? ("provider" in mapped ? mapped.provider : undefined);
|
|
16
16
|
if (!provider)
|
|
@@ -134,9 +134,7 @@ function makeFromTransport(input) {
|
|
|
134
134
|
id: id ?? routeInput.id,
|
|
135
135
|
provider: provider ?? routeInput.provider,
|
|
136
136
|
providerMetadataKey: providerMetadataKey ??
|
|
137
|
-
(provider !== undefined && provider !== routeInput.provider
|
|
138
|
-
? provider
|
|
139
|
-
: routeInput.providerMetadataKey),
|
|
137
|
+
(provider !== undefined && provider !== routeInput.provider ? provider : routeInput.providerMetadataKey),
|
|
140
138
|
auth: auth ?? routeInput.auth,
|
|
141
139
|
endpoint: endpoint ? Endpoint.merge(routeInput.endpoint, endpoint) : routeInput.endpoint,
|
|
142
140
|
transport: transport ?? routeInput.transport,
|
|
@@ -265,12 +263,13 @@ const streamRequestWith = (runtime) => (request, options) => Stream.unwrap(Effec
|
|
|
265
263
|
const compiled = yield* compile(request, options);
|
|
266
264
|
return compiled.route.streamPrepared(compiled.prepared, compiled.request, runtime, options);
|
|
267
265
|
}));
|
|
268
|
-
const generateWith = (stream) => Effect.fn("LLM.generate")(function* (request, options) {
|
|
269
|
-
|
|
266
|
+
export const generateWith = (stream) => Effect.fn("LLM.generate")(function* (request, options) {
|
|
267
|
+
let state = LLMResponse.empty();
|
|
268
|
+
yield* stream(request, options).pipe(Stream.runForEach((event) => Effect.sync(() => (state = LLMResponse.reduce(state, event)))), Effect.mapError((error) => withPartial(error, LLMResponse.partial(state))));
|
|
270
269
|
const response = LLMResponse.complete(state);
|
|
271
270
|
if (response)
|
|
272
271
|
return response;
|
|
273
|
-
return yield* incompleteStreamError(`${request.model.provider}/${request.model.route.id}`);
|
|
272
|
+
return yield* withPartial(incompleteStreamError(`${request.model.provider}/${request.model.route.id}`), LLMResponse.partial(state));
|
|
274
273
|
});
|
|
275
274
|
export function stream(request, options) {
|
|
276
275
|
return Stream.unwrap(Effect.gen(function* () {
|
|
@@ -312,8 +311,6 @@ export const layer = Layer.effect(Service, Effect.gen(function* () {
|
|
|
312
311
|
}));
|
|
313
312
|
export const Route = { make };
|
|
314
313
|
export const LLMClient = {
|
|
315
|
-
canCompact,
|
|
316
|
-
compact,
|
|
317
314
|
Service,
|
|
318
315
|
layer,
|
|
319
316
|
stream,
|
|
@@ -171,9 +171,8 @@ export declare const identity: (input: {
|
|
|
171
171
|
unsupported: (operation: string, message: string) => AIError;
|
|
172
172
|
};
|
|
173
173
|
export type Identity = ReturnType<typeof identity>;
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
export declare const status: <Table extends Record<string, Status>>(table: Table, raw: string, output: Output) => Effect.Effect<Status, AIError>;
|
|
174
|
+
/** Map a provider status string through the protocol's table; unknown values keep the generation running. */
|
|
175
|
+
export declare const status: (table: Readonly<Record<string, Status>>, raw: string) => Status;
|
|
177
176
|
/** Map a provider error code through the protocol's table; missing or unmapped codes are `ProviderInternal`. */
|
|
178
177
|
export declare const failure: (table: Readonly<Record<string, Failure>>, code: string | number | undefined) => Failure;
|
|
179
178
|
/** A `url` asset whose provider-declared retention window starts now. */
|
|
@@ -109,12 +109,8 @@ export const identity = (input) => {
|
|
|
109
109
|
unsupported: (operation, message) => new AIError({ reason: new UnsupportedOperationError({ operation, provider, route: input.id, message }) }),
|
|
110
110
|
};
|
|
111
111
|
};
|
|
112
|
-
/** Map a provider status string through the protocol's table; unknown values
|
|
113
|
-
export const status = (table, raw,
|
|
114
|
-
if (!Object.hasOwn(table, raw))
|
|
115
|
-
return Effect.fail(output.invalid(`Unknown generation status "${raw}"`));
|
|
116
|
-
return Effect.succeed(table[raw]);
|
|
117
|
-
};
|
|
112
|
+
/** Map a provider status string through the protocol's table; unknown values keep the generation running. */
|
|
113
|
+
export const status = (table, raw) => Object.hasOwn(table, raw) ? table[raw] : "running";
|
|
118
114
|
/** Map a provider error code through the protocol's table; missing or unmapped codes are `ProviderInternal`. */
|
|
119
115
|
export const failure = (table, code) => code !== undefined && Object.hasOwn(table, code) ? table[code] : "ProviderInternal";
|
|
120
116
|
/** A `url` asset whose provider-declared retention window starts now. */
|
package/dist/schema/errors.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
2
|
import { Tool } from "@opencode/schema/tool";
|
|
3
|
+
import type { LLMResponse } from "./events.js";
|
|
3
4
|
export declare const ProviderFailureClassification: Schema.Literals<readonly ["context-overflow", "payload-too-large"]>;
|
|
4
5
|
export type ProviderFailureClassification = typeof ProviderFailureClassification.Type;
|
|
5
6
|
declare const HttpContext_base: Schema.Class<HttpContext, Schema.Struct<{
|
|
@@ -165,8 +166,13 @@ declare const AIError_base: Schema.Class<AIError, Schema.TaggedStruct<"AI.Error"
|
|
|
165
166
|
}>, import("effect/Cause").YieldableError>;
|
|
166
167
|
export declare class AIError extends AIError_base {
|
|
167
168
|
readonly cause: AuthenticationError | ContentPolicyError | InvalidProviderOutputError | InvalidRequestError | NoRouteError | ProviderInternalError | QuotaExceededError | RateLimitError | TimeoutError | TransportError | UnknownProviderError | UnsupportedOperationError;
|
|
169
|
+
/** Output that arrived before `generate`, `generateObject` or a `loop` step failed. Not in the schema, so encoding omits it. */
|
|
170
|
+
readonly partial?: LLMResponse;
|
|
171
|
+
constructor(props: Pick<AIError, "reason" | "partial">);
|
|
168
172
|
get message(): string;
|
|
169
173
|
}
|
|
174
|
+
/** Return `error` with `partial` attached, or unchanged when there is no partial output. */
|
|
175
|
+
export declare const withPartial: (error: AIError, partial: LLMResponse | undefined) => AIError;
|
|
170
176
|
/**
|
|
171
177
|
* Failure type for tool execute handlers. Handlers must map their internal
|
|
172
178
|
* errors to this shape; the runtime catches `ToolFailure`s and surfaces them
|
package/dist/schema/errors.js
CHANGED
|
@@ -125,10 +125,18 @@ export class AIError extends Schema.TaggedError()("AI.Error", {
|
|
|
125
125
|
reason: AIErrorReason,
|
|
126
126
|
}) {
|
|
127
127
|
cause = this.reason;
|
|
128
|
+
/** Output that arrived before `generate`, `generateObject` or a `loop` step failed. Not in the schema, so encoding omits it. */
|
|
129
|
+
partial;
|
|
130
|
+
constructor(props) {
|
|
131
|
+
super({ reason: props.reason });
|
|
132
|
+
this.partial = props.partial;
|
|
133
|
+
}
|
|
128
134
|
get message() {
|
|
129
135
|
return this.reason.message;
|
|
130
136
|
}
|
|
131
137
|
}
|
|
138
|
+
/** Return `error` with `partial` attached, or unchanged when there is no partial output. */
|
|
139
|
+
export const withPartial = (error, partial) => partial === undefined ? error : new AIError({ reason: error.reason, partial });
|
|
132
140
|
/**
|
|
133
141
|
* Failure type for tool execute handlers. Handlers must map their internal
|
|
134
142
|
* errors to this shape; the runtime catches `ToolFailure`s and surfaces them
|
package/dist/schema/events.d.ts
CHANGED
|
@@ -8738,6 +8738,8 @@ export declare namespace LLMResponse {
|
|
|
8738
8738
|
const complete: (state: State) => LLMResponse | undefined;
|
|
8739
8739
|
/** Convenience reducer for callers that already have a collected event list. */
|
|
8740
8740
|
const fromEvents: (events: ReadonlyArray<LLMEvent>) => LLMResponse | undefined;
|
|
8741
|
+
/** Output that arrived before a failure, or `undefined` if only `step-start` did; an unfinished response reports `error`. */
|
|
8742
|
+
const partial: (state: State) => LLMResponse | undefined;
|
|
8741
8743
|
/** Concatenate assistant text from a response or collected event list. */
|
|
8742
8744
|
const text: (response: Output) => string;
|
|
8743
8745
|
/** Return response usage, falling back to the latest usage-bearing event. */
|
package/dist/schema/events.js
CHANGED
|
@@ -596,6 +596,10 @@ export class LLMResponse extends Schema.Class("LLM.Response")({
|
|
|
596
596
|
});
|
|
597
597
|
/** Convenience reducer for callers that already have a collected event list. */
|
|
598
598
|
LLMResponse.fromEvents = (events) => LLMResponse.complete(events.reduce(LLMResponse.reduce, LLMResponse.empty()));
|
|
599
|
+
/** Output that arrived before a failure, or `undefined` if only `step-start` did; an unfinished response reports `error`. */
|
|
600
|
+
LLMResponse.partial = (state) => state.events.every(LLMEvent.is.stepStart)
|
|
601
|
+
? undefined
|
|
602
|
+
: LLMResponse.complete({ ...state, finishReason: state.finishReason ?? { normalized: "error" } });
|
|
599
603
|
/** Concatenate assistant text from a response or collected event list. */
|
|
600
604
|
LLMResponse.text = (response) => responseText(response.events);
|
|
601
605
|
/** Return response usage, falling back to the latest usage-bearing event. */
|
package/dist/testing.d.ts
CHANGED
|
@@ -2,9 +2,6 @@ export * as TestLLM from "./testing.js";
|
|
|
2
2
|
export { compileRequest } from "./route/client.js";
|
|
3
3
|
export { TestDecision } from "./testing/decision.js";
|
|
4
4
|
export { TestImage } from "./testing/image.js";
|
|
5
|
-
export { TestSpeech } from "./testing/speech.js";
|
|
6
|
-
export { TestTranscription } from "./testing/transcription.js";
|
|
7
|
-
export { TestVideo } from "./testing/video.js";
|
|
8
5
|
import { LLMClient } from "./route/client.js";
|
|
9
6
|
import { LLMEvent, CompactionResponse, CompactionCheckpointResponse, type FinishReasonDetails, type AIError, type LLMRequest, type ProviderMetadata, type UsageInput } from "./schema/index.js";
|
|
10
7
|
import { Context, Layer, Stream } from "effect";
|
|
@@ -1118,7 +1115,7 @@ export declare const textWithUsage: (value: string, id: string, inputTokens: num
|
|
|
1118
1115
|
readonly text: string | null;
|
|
1119
1116
|
readonly encrypted?: never;
|
|
1120
1117
|
})))[];
|
|
1121
|
-
export declare const
|
|
1118
|
+
export declare const toolCall: (id: string, name: string, input: unknown) => ({
|
|
1122
1119
|
readonly type: "step-start";
|
|
1123
1120
|
readonly index: number;
|
|
1124
1121
|
} | {
|
package/dist/testing.js
CHANGED
|
@@ -2,11 +2,8 @@ export * as TestLLM from "./testing.js";
|
|
|
2
2
|
export { compileRequest } from "./route/client.js";
|
|
3
3
|
export { TestDecision } from "./testing/decision.js";
|
|
4
4
|
export { TestImage } from "./testing/image.js";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
export { TestVideo } from "./testing/video.js";
|
|
8
|
-
import { LLMClient, } from "./route/client.js";
|
|
9
|
-
import { LLMEvent, LLMResponse, CompactionResponse, CompactionCheckpointResponse, } from "./schema/index.js";
|
|
5
|
+
import { LLMClient, generateWith, } from "./route/client.js";
|
|
6
|
+
import { LLMEvent, CompactionResponse, CompactionCheckpointResponse, } from "./schema/index.js";
|
|
10
7
|
import { Context, Effect, Layer, Stream } from "effect";
|
|
11
8
|
import { TestScript } from "./testing/script.js";
|
|
12
9
|
export class Test extends Context.Service()("@opencode/ai/TestLLM/Test") {
|
|
@@ -31,7 +28,7 @@ const textEvents = (value, id) => [
|
|
|
31
28
|
];
|
|
32
29
|
export const text = (value, id) => stop(...textEvents(value, id));
|
|
33
30
|
export const textWithUsage = (value, id, inputTokens) => complete({ reason: { normalized: "stop" }, usage: { inputTokens, nonCachedInputTokens: inputTokens } }, ...textEvents(value, id));
|
|
34
|
-
export const
|
|
31
|
+
export const toolCall = (id, name, input) => toolCalls(LLMEvent.toolCall({ id, name, input }));
|
|
35
32
|
export const failAfter = (error, ...events) => Stream.fromIterable(events).pipe(Stream.concat(Stream.fail(error)));
|
|
36
33
|
export const hangAfter = (...events) => Stream.concat(Stream.fromIterable(events), Stream.never);
|
|
37
34
|
const make = (options) => Effect.sync(() => {
|
|
@@ -56,12 +53,7 @@ const make = (options) => Effect.sync(() => {
|
|
|
56
53
|
...script.controls,
|
|
57
54
|
compact,
|
|
58
55
|
stream,
|
|
59
|
-
generate: (
|
|
60
|
-
const response = LLMResponse.complete(state);
|
|
61
|
-
if (response)
|
|
62
|
-
return Effect.succeed(response);
|
|
63
|
-
return Effect.die("TestLLM response ended without a terminal finish event");
|
|
64
|
-
})),
|
|
56
|
+
generate: generateWith(stream),
|
|
65
57
|
});
|
|
66
58
|
});
|
|
67
59
|
/** Provides one shared implementation under the normal client and test-control tags. */
|
package/dist/tool.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Effect, JsonSchema, Schema } from "effect";
|
|
2
|
-
import {
|
|
2
|
+
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
|
/**
|
|
@@ -19,14 +19,12 @@ export interface ToolModelOutputInput<Parameters, Output> {
|
|
|
19
19
|
readonly parameters: Parameters;
|
|
20
20
|
readonly output: Output;
|
|
21
21
|
}
|
|
22
|
-
export type ToolToModelOutput<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>> = (input: ToolModelOutputInput<Schema.Schema.Type<Parameters>, Success["Encoded"]>) => ReadonlyArray<
|
|
22
|
+
export type ToolToModelOutput<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>> = (input: ToolModelOutputInput<Schema.Schema.Type<Parameters>, Success["Encoded"]>) => ReadonlyArray<Content>;
|
|
23
23
|
type FreeformField<T> = {
|
|
24
24
|
[K in keyof T]-?: [Exclude<keyof T, K>] extends [never] ? {} extends Pick<T, K> ? never : T[K] extends string ? K : never : never;
|
|
25
25
|
}[keyof T];
|
|
26
|
-
/** `Freeform`
|
|
27
|
-
export type FreeformOption<Parameters extends ToolSchema<any>> = [
|
|
28
|
-
FreeformField<Schema.Schema.Type<Parameters>>
|
|
29
|
-
] extends [never] ? undefined : Freeform;
|
|
26
|
+
/** `Freeform` for exactly one required string parameter or unknown ones (`jsonSchema`), otherwise `undefined`. */
|
|
27
|
+
export type FreeformOption<Parameters extends ToolSchema<any>> = unknown extends Schema.Schema.Type<Parameters> ? Freeform : [FreeformField<Schema.Schema.Type<Parameters>>] extends [never] ? undefined : Freeform;
|
|
30
28
|
/**
|
|
31
29
|
* A type-safe LLM tool. Each tool bundles its own description, parameter
|
|
32
30
|
* Schema and success Schema. The execute handler is optional: omit it when you
|
|
@@ -39,7 +37,7 @@ export type FreeformOption<Parameters extends ToolSchema<any>> = [
|
|
|
39
37
|
* Internally each tool also carries memoized codecs and a precomputed
|
|
40
38
|
* `ToolDefinition` so callers do not rebuild them per invocation.
|
|
41
39
|
*/
|
|
42
|
-
export interface
|
|
40
|
+
export interface Tool<Parameters extends ToolSchema<any> = any, Success extends ToolSchema<any> = any> {
|
|
43
41
|
readonly description: string;
|
|
44
42
|
readonly parameters: Parameters;
|
|
45
43
|
readonly success: Success;
|
|
@@ -49,91 +47,61 @@ export interface Definition<Parameters extends ToolSchema<any>, Success extends
|
|
|
49
47
|
/** @internal */
|
|
50
48
|
readonly _decode: (input: unknown) => Effect.Effect<Schema.Schema.Type<Parameters>, Schema.SchemaError>;
|
|
51
49
|
/** @internal */
|
|
52
|
-
|
|
50
|
+
_encode(value: Schema.Schema.Type<Success>): Effect.Effect<unknown, Schema.SchemaError>;
|
|
53
51
|
/** @internal */
|
|
54
|
-
|
|
52
|
+
_project(parameters: Schema.Schema.Type<Parameters>, id: ToolCallPart["id"], output: unknown): ToolOutputType;
|
|
55
53
|
/** @internal */
|
|
56
54
|
readonly _legacyResult: boolean;
|
|
57
55
|
/** @internal */
|
|
58
56
|
readonly _definition: ToolDefinitionClass;
|
|
59
57
|
}
|
|
60
|
-
|
|
61
|
-
export type ExecutableTool<Parameters extends ToolSchema<any
|
|
58
|
+
/** A tool with an `execute` handler, which `LLM.loop` and `ToolRuntime.dispatch` can run. */
|
|
59
|
+
export type ExecutableTool<Parameters extends ToolSchema<any> = any, Success extends ToolSchema<any> = any> = Tool<Parameters, Success> & {
|
|
62
60
|
readonly execute: ToolExecute<Parameters, Success>;
|
|
63
61
|
};
|
|
64
|
-
export type AnyExecutableTool = ExecutableTool<any, any>;
|
|
65
|
-
export type ExecutableTools = Record<string, AnyExecutableTool>;
|
|
66
62
|
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* ```ts
|
|
73
|
-
* Tool.make({
|
|
74
|
-
* description: "Get current weather",
|
|
75
|
-
* parameters: Schema.Struct({ city: Schema.String }),
|
|
76
|
-
* success: Schema.Struct({ temperature: Schema.Number }),
|
|
77
|
-
* execute: ({ city }) => Effect.succeed({ temperature: 22 }),
|
|
78
|
-
* })
|
|
79
|
-
* ```
|
|
80
|
-
*
|
|
81
|
-
* 2. **Dynamic** — pass raw JSON Schema as `jsonSchema`. Use this when the
|
|
82
|
-
* schema comes from an external source (MCP server, plugin manifest,
|
|
83
|
-
* dynamic config) and is not known at compile time. Inputs are typed as
|
|
84
|
-
* `unknown`; the handler is responsible for any validation it needs.
|
|
85
|
-
*
|
|
86
|
-
* ```ts
|
|
87
|
-
* Tool.make({
|
|
88
|
-
* description: "Look something up",
|
|
89
|
-
* jsonSchema: { type: "object", properties: { ... } },
|
|
90
|
-
* execute: (params) => Effect.succeed(...),
|
|
91
|
-
* })
|
|
92
|
-
* ```
|
|
93
|
-
*
|
|
94
|
-
* In both modes the produced tool flows through `toDefinitions(...)`
|
|
95
|
-
* identically.
|
|
63
|
+
* Options for `tool`, where `Execute` is the only part that differs between the Effect and Promise clients. Pass
|
|
64
|
+
* Effect `parameters` (and optionally a `success` schema that validates the result, otherwise it is sent as is with
|
|
65
|
+
* `undefined` as `null`), or raw `jsonSchema` known only at runtime, such as an MCP tool's. Omit `execute` to declare
|
|
66
|
+
* a tool the model can call without running it here.
|
|
96
67
|
*/
|
|
97
|
-
export
|
|
68
|
+
export type ToolOptions<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>, Execute = ToolExecute<Parameters, Success>> = {
|
|
98
69
|
readonly description: string;
|
|
99
|
-
readonly parameters: Parameters;
|
|
100
|
-
readonly success: Success;
|
|
101
70
|
readonly freeform?: FreeformOption<Parameters>;
|
|
102
|
-
readonly execute
|
|
71
|
+
readonly execute?: Execute;
|
|
103
72
|
readonly toModelOutput?: ToolToModelOutput<Parameters, Success>;
|
|
104
73
|
readonly toStructuredOutput?: (output: Success["Encoded"]) => unknown;
|
|
105
|
-
}
|
|
106
|
-
export declare function make<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>>(config: {
|
|
107
|
-
readonly description: string;
|
|
74
|
+
} & ({
|
|
108
75
|
readonly parameters: Parameters;
|
|
109
|
-
readonly success
|
|
110
|
-
|
|
111
|
-
readonly execute?: undefined;
|
|
112
|
-
readonly toModelOutput?: ToolToModelOutput<Parameters, Success>;
|
|
113
|
-
readonly toStructuredOutput?: (output: Success["Encoded"]) => unknown;
|
|
114
|
-
}): Definition<Parameters, Success>;
|
|
115
|
-
export declare function make(config: {
|
|
116
|
-
readonly description: string;
|
|
117
|
-
readonly jsonSchema: JsonSchema.JsonSchema;
|
|
118
|
-
readonly outputSchema?: JsonSchema.JsonSchema;
|
|
119
|
-
readonly freeform?: Freeform;
|
|
120
|
-
readonly execute: (params: unknown, context?: ToolExecuteContext) => Effect.Effect<unknown, ToolFailure>;
|
|
121
|
-
readonly toModelOutput?: (input: ToolModelOutputInput<unknown, unknown>) => ReadonlyArray<Tool.Content>;
|
|
122
|
-
readonly toStructuredOutput?: (output: unknown) => unknown;
|
|
123
|
-
}): AnyExecutableTool;
|
|
124
|
-
export declare function make(config: {
|
|
125
|
-
readonly description: string;
|
|
76
|
+
readonly success?: Success;
|
|
77
|
+
} | {
|
|
126
78
|
readonly jsonSchema: JsonSchema.JsonSchema;
|
|
127
79
|
readonly outputSchema?: JsonSchema.JsonSchema;
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
80
|
+
});
|
|
81
|
+
/**
|
|
82
|
+
* Constructs a tool whose `execute` returns an Effect that fails with `ToolFailure`.
|
|
83
|
+
*
|
|
84
|
+
* ```ts
|
|
85
|
+
* tool({
|
|
86
|
+
* description: "Get current weather",
|
|
87
|
+
* parameters: Schema.Struct({ city: Schema.String }),
|
|
88
|
+
* success: Schema.Struct({ temperature: Schema.Number }),
|
|
89
|
+
* execute: ({ city }) => Effect.succeed({ temperature: 22 }),
|
|
90
|
+
* })
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
export declare const tool: <Parameters extends ToolSchema<any> = typeof Schema.Unknown, Success extends ToolSchema<any> = typeof Schema.Unknown, Result extends Effect.Effect<Schema.Schema.Type<Success>, ToolFailure> | NoExecute = NoExecute>(config: ToolOptions<Parameters, Success, (params: Schema.Schema.Type<Parameters>, context?: ToolExecuteContext) => Result>) => 0 extends 1 & Result ? ExecutableTool<Parameters, Success> : [Result, NoExecute] extends [NoExecute, Result] ? Tool<Parameters, Success> : ExecutableTool<Parameters, Success>;
|
|
94
|
+
declare const noExecute: unique symbol;
|
|
95
|
+
/** @internal The inferred `execute` result when `execute` is omitted; no function can return it. */
|
|
96
|
+
export type NoExecute = {
|
|
97
|
+
readonly [noExecute]: never;
|
|
98
|
+
};
|
|
99
|
+
/** @internal Builds a tool for both clients from its options and an Effect `execute`. */
|
|
100
|
+
export declare function build<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>, Result>(config: ToolOptions<Parameters, Success, (...args: never) => Result>, execute: ((params: Schema.Schema.Type<Parameters>, context?: ToolExecuteContext) => unknown) | undefined): 0 extends 1 & Result ? ExecutableTool<Parameters, Success> : [Result, NoExecute] extends [NoExecute, Result] ? Tool<Parameters, Success> : ExecutableTool<Parameters, Success>;
|
|
133
101
|
/**
|
|
134
102
|
* A record of named tools. The record key becomes the tool name on the wire.
|
|
135
103
|
*/
|
|
136
|
-
export type Tools = Record<string,
|
|
104
|
+
export type Tools = Record<string, Tool>;
|
|
137
105
|
/**
|
|
138
106
|
* Convert a tools record into the `ToolDefinition[]` shape that
|
|
139
107
|
* `LLMRequest.tools` expects.
|
|
@@ -154,4 +122,3 @@ export declare const toDefinitions: (tools: Tools) => ReadonlyArray<ToolDefiniti
|
|
|
154
122
|
*/
|
|
155
123
|
export declare const emptyInputJsonSchema: (schema: Schema.Top) => JsonSchema.JsonSchema | undefined;
|
|
156
124
|
export { ToolFailure };
|
|
157
|
-
export * as Tool from "./tool.js";
|
package/dist/tool.js
CHANGED
|
@@ -1,19 +1,34 @@
|
|
|
1
1
|
import { Effect, JsonSchema, Schema } from "effect";
|
|
2
|
-
import { Tool } from "@opencode/schema/tool";
|
|
3
2
|
import { ToolDefinition, ToolFailure, ToolOutput } from "./schema/index.js";
|
|
4
3
|
import { isRecord } from "./utils/record.js";
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Constructs a tool whose `execute` returns an Effect that fails with `ToolFailure`.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* tool({
|
|
9
|
+
* description: "Get current weather",
|
|
10
|
+
* parameters: Schema.Struct({ city: Schema.String }),
|
|
11
|
+
* success: Schema.Struct({ temperature: Schema.Number }),
|
|
12
|
+
* execute: ({ city }) => Effect.succeed({ temperature: 22 }),
|
|
13
|
+
* })
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export const tool = (config) => build(config, config.execute);
|
|
17
|
+
export function build(config, execute) {
|
|
18
|
+
const shared = {
|
|
19
|
+
description: config.description,
|
|
20
|
+
execute,
|
|
21
|
+
toModelOutput: config.toModelOutput,
|
|
22
|
+
toStructuredOutput: config.toStructuredOutput,
|
|
23
|
+
_project: (parameters, id, output) => project(config.toModelOutput, config.toStructuredOutput, parameters, id, output),
|
|
24
|
+
};
|
|
25
|
+
if ("jsonSchema" in config)
|
|
7
26
|
return {
|
|
8
|
-
|
|
27
|
+
...shared,
|
|
9
28
|
parameters: Schema.Unknown,
|
|
10
29
|
success: Schema.Unknown,
|
|
11
|
-
execute: config.execute,
|
|
12
|
-
toModelOutput: config.toModelOutput,
|
|
13
|
-
toStructuredOutput: config.toStructuredOutput,
|
|
14
30
|
_decode: Effect.succeed,
|
|
15
31
|
_encode: Effect.succeed,
|
|
16
|
-
_project: (parameters, id, output) => project(config.toModelOutput, config.toStructuredOutput, parameters, id, output),
|
|
17
32
|
_legacyResult: config.toModelOutput === undefined && config.toStructuredOutput === undefined,
|
|
18
33
|
_definition: definition({
|
|
19
34
|
name: "",
|
|
@@ -23,23 +38,18 @@ export function make(config) {
|
|
|
23
38
|
freeform: config.freeform,
|
|
24
39
|
}),
|
|
25
40
|
};
|
|
26
|
-
}
|
|
27
41
|
return {
|
|
28
|
-
|
|
42
|
+
...shared,
|
|
29
43
|
parameters: config.parameters,
|
|
30
|
-
success: config.success,
|
|
31
|
-
execute: config.execute,
|
|
32
|
-
toModelOutput: config.toModelOutput,
|
|
33
|
-
toStructuredOutput: config.toStructuredOutput,
|
|
44
|
+
success: config.success ?? Schema.Unknown,
|
|
34
45
|
_decode: Schema.decodeUnknownEffect(config.parameters),
|
|
35
|
-
_encode: Schema.encodeEffect(config.success),
|
|
36
|
-
_project: (parameters, id, output) => project(config.toModelOutput, config.toStructuredOutput, parameters, id, output),
|
|
46
|
+
_encode: config.success ? Schema.encodeEffect(config.success) : (value) => Effect.succeed(value ?? null),
|
|
37
47
|
_legacyResult: false,
|
|
38
48
|
_definition: definition({
|
|
39
49
|
name: "",
|
|
40
50
|
description: config.description,
|
|
41
51
|
inputSchema: emptyInputJsonSchema(config.parameters) ?? toJsonSchema(config.parameters),
|
|
42
|
-
outputSchema: toJsonSchema(config.success),
|
|
52
|
+
outputSchema: config.success && toJsonSchema(config.success),
|
|
43
53
|
freeform: config.freeform,
|
|
44
54
|
}),
|
|
45
55
|
};
|
|
@@ -90,4 +100,3 @@ const toJsonSchema = (schema) => {
|
|
|
90
100
|
};
|
|
91
101
|
const project = (toModelOutput, toStructuredOutput, parameters, id, output) => ToolOutput.make(toStructuredOutput?.(output) ?? output, toModelOutput?.({ id, parameters, output }) ?? (typeof output === "string" ? [{ type: "text", text: output }] : []));
|
|
92
102
|
export { ToolFailure };
|
|
93
|
-
export * as Tool from "./tool.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.4",
|
|
4
4
|
"name": "@opencode/ai",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,6 +32,10 @@
|
|
|
32
32
|
"import": "./dist/experimental.js",
|
|
33
33
|
"types": "./dist/experimental.d.ts"
|
|
34
34
|
},
|
|
35
|
+
"./experimental/testing": {
|
|
36
|
+
"import": "./dist/experimental/testing.js",
|
|
37
|
+
"types": "./dist/experimental/testing.d.ts"
|
|
38
|
+
},
|
|
35
39
|
"./route": {
|
|
36
40
|
"import": "./dist/route.js",
|
|
37
41
|
"types": "./dist/route.d.ts"
|
|
@@ -516,7 +520,7 @@
|
|
|
516
520
|
"devDependencies": {
|
|
517
521
|
"@clack/prompts": "1.0.0-alpha.1",
|
|
518
522
|
"@effect/platform-node": "4.0.6",
|
|
519
|
-
"@opencode/http-recorder": "2.2.
|
|
523
|
+
"@opencode/http-recorder": "2.2.4",
|
|
520
524
|
"@tsconfig/bun": "1.0.9",
|
|
521
525
|
"@types/bun": "1.4.3",
|
|
522
526
|
"@typescript/native": "npm:typescript@7.1.0-beta",
|
|
@@ -526,7 +530,7 @@
|
|
|
526
530
|
"@aws-sdk/credential-providers": "3.1057.0",
|
|
527
531
|
"@smithy/eventstream-codec": "4.2.14",
|
|
528
532
|
"@smithy/util-utf8": "4.2.2",
|
|
529
|
-
"@opencode/schema": "2.2.
|
|
533
|
+
"@opencode/schema": "2.2.4",
|
|
530
534
|
"aws4fetch": "1.0.20",
|
|
531
535
|
"effect": "4.0.6",
|
|
532
536
|
"google-auth-library": "10.5.0"
|