@opencode/ai 0.0.0-dev-469 → 0.0.0-dev-470
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 +5 -2
- package/dist/llm.d.ts +5 -22
- package/dist/llm.js +37 -139
- package/dist/loop.d.ts +38 -0
- package/dist/loop.js +135 -0
- package/dist/tool-runtime.d.ts +7 -0
- package/dist/tool-runtime.js +4 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -59,8 +59,11 @@ it fails). Each step ends with its own `step-finish`; one `finish` ends the loop
|
|
|
59
59
|
and the usage summed across steps. `until` is checked
|
|
60
60
|
after each step that has tool calls, with every step's `LLMResponse`; returning `true` ends the loop without running
|
|
61
61
|
them. Tools are an array, sent in the order given so the provider can reuse its cached prompt prefix. Each tool has a
|
|
62
|
-
`name`, and two tools with the same name fail the request.
|
|
63
|
-
|
|
62
|
+
`name`, and two tools with the same name fail the request. Tool arguments that are not valid JSON go back to the model
|
|
63
|
+
as an error result so it can retry. A step that hits the output token limit ends the loop without running its tool
|
|
64
|
+
calls, which may be cut off. A forced `toolChoice` applies to the first step only; later steps use `auto`. `tool` takes
|
|
65
|
+
a plain `async` execute; a throw or rejection goes back to the model as an error result, and `signal` aborts when the
|
|
66
|
+
loop is interrupted.
|
|
64
67
|
`input` is an Effect Schema that decodes and types the arguments, or a raw JSON Schema object, such as an MCP tool's,
|
|
65
68
|
whose arguments arrive as `unknown` (pair it with an optional JSON Schema `outputSchema`). `tool` from
|
|
66
69
|
`@opencode/ai/effect` takes the same options (including an optional `success` schema) with an Effect execute:
|
package/dist/llm.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Effect, JsonSchema, Schema, Stream } from "effect";
|
|
2
2
|
import { Service, canCompact, type CheckpointRequest, type CompactionRequest, type EndpointCompactOptions, type StreamOptions, type TriggerCompactOptions } from "./route/client.js";
|
|
3
|
-
import { GenerationOptions, HttpOptions, AIError, LLMEvent, LLMResponse, Message, LanguageModel, SystemPart, type CachePolicy, type CompactionCheckpointResponse, type CompactionResponse, type Finish,
|
|
3
|
+
import { GenerationOptions, HttpOptions, AIError, LLMEvent, LLMResponse, Message, LanguageModel, SystemPart, type CachePolicy, type CompactionCheckpointResponse, type CompactionResponse, type Finish, ToolChoice, type ContentPart, type LanguageModelProviderOptions, type LLMRequest, type ToolEntryInput } from "./schema/index.js";
|
|
4
4
|
import { type ExecutableTool, type Tool, type ToolSchema } from "./tool.js";
|
|
5
5
|
/** Input accepted by `ai.request`, `ai.generate`, `ai.stream` and `ai.compact`. An `LLMRequest` is also a valid input. */
|
|
6
6
|
export type LLMRequestInput<Model extends LanguageModel = LanguageModel> = TextRequestFields<Model> & PromptOrMessages;
|
|
@@ -64,8 +64,9 @@ export type LLMLoopInput<Model extends LanguageModel = LanguageModel> = Omit<Tex
|
|
|
64
64
|
}) => boolean;
|
|
65
65
|
};
|
|
66
66
|
/**
|
|
67
|
-
* Stream model calls, running the model's tool calls between them, until a step has no client-executed tool calls
|
|
68
|
-
* `until` returns `true`.
|
|
67
|
+
* Stream model calls, running the model's tool calls between them, until a step has no client-executed tool calls,
|
|
68
|
+
* hits the output token limit, or `until` returns `true`. Tool calls whose input is not valid JSON get an error result
|
|
69
|
+
* so the model can retry. A forced `toolChoice` applies to the first step only. Each step's `step-start` and `step-finish` carry its step index and usage; one `finish` ends
|
|
69
70
|
* the loop with the final step's reason and `message` and the usage summed across steps. With `schema`, the model ends
|
|
70
71
|
* by calling the hidden answer tool, decoded into `object` on the `finish`.
|
|
71
72
|
*/
|
|
@@ -73,25 +74,7 @@ export declare function loop<const Model extends LanguageModel, S extends Output
|
|
|
73
74
|
readonly schema: S;
|
|
74
75
|
}, options?: StreamOptions): Stream.Stream<LoopObjectEvent<OutputType<S>>, AIError, Service>;
|
|
75
76
|
export declare function loop<const Model extends LanguageModel>(input: LLMLoopInput<Model>, options?: StreamOptions): Stream.Stream<LLMEvent, AIError, Service>;
|
|
76
|
-
|
|
77
|
-
export interface Collected {
|
|
78
|
-
/** Text of the final step. */
|
|
79
|
-
readonly text: string;
|
|
80
|
-
/** One response per model call, in order. */
|
|
81
|
-
readonly steps: ReadonlyArray<LLMResponse>;
|
|
82
|
-
/** Each step's assistant message followed by its tool results, ready to append to the request's messages. */
|
|
83
|
-
readonly messages: ReadonlyArray<Message>;
|
|
84
|
-
/** Usage from the terminal `finish`, summed across steps for a loop. */
|
|
85
|
-
readonly usage?: Usage;
|
|
86
|
-
readonly finishReason: FinishReasonDetails;
|
|
87
|
-
}
|
|
88
|
-
type FinishOf<Event> = Extract<Event, {
|
|
89
|
-
readonly type: "finish";
|
|
90
|
-
}>;
|
|
91
|
-
/** `Collected`, plus `object` when the stream was started with `schema`. */
|
|
92
|
-
export type CollectResult<Event> = "object" extends keyof FinishOf<Event> ? Collected & Pick<FinishOf<Event>, "object"> : Collected;
|
|
93
|
-
/** Run a stream from `stream` or `loop` to the end and fold its events into the final result. */
|
|
94
|
-
export declare function collect<Event extends LLMEvent, E, R>(events: Stream.Stream<Event, E, R>): Effect.Effect<CollectResult<Event>, E | AIError, R>;
|
|
77
|
+
export { collect, type Collected, type CollectResult } from "./loop.js";
|
|
95
78
|
/** Normalize text request input into a plain `LLMRequest`, with `prompt` turned into the one user message. */
|
|
96
79
|
export declare const request: <const Model extends LanguageModel>(input: LLMRequestInput<Model>) => LLMRequest<Model>;
|
|
97
80
|
/** Compact a text request: a replacement window, or a checkpoint with `mechanism: "trigger"`. */
|
package/dist/llm.js
CHANGED
|
@@ -3,150 +3,54 @@ import { tryRequest } from "./media-model.js";
|
|
|
3
3
|
import { LLMClient, Service, canCompact, compactRequest, } from "./route/client.js";
|
|
4
4
|
import { GenerationOptions, HttpOptions, InvalidProviderOutputError, InvalidRequestError, AIError, LLMEvent, LLMResponse, Message, LanguageModel, SystemPart, ToolChoice, ToolEntry, Usage, withPartial, } from "./schema/index.js";
|
|
5
5
|
import { tool } from "./tool.js";
|
|
6
|
-
import {
|
|
6
|
+
import { runTools } from "./tool-runtime.js";
|
|
7
|
+
import { addUsage, nextRequest, pendingCalls } from "./loop.js";
|
|
7
8
|
export function generate(input, options) {
|
|
8
9
|
return prepare(input).pipe(Effect.flatMap(({ request, output }) => LLMClient.generate(request, options).pipe(Effect.flatMap((response) => output === undefined
|
|
9
10
|
? Effect.succeed(response)
|
|
10
11
|
: decodeObject(output, response).pipe(Effect.map((object) => Object.assign(response, { object })))))));
|
|
11
12
|
}
|
|
12
13
|
export function stream(input, options) {
|
|
13
|
-
return Stream.unwrap(prepare(input).pipe(Effect.map(({ request, output }) =>
|
|
14
|
-
let state = LLMResponse.empty();
|
|
15
|
-
return LLMClient.stream(request, options).pipe(Stream.mapEffect((event) => {
|
|
16
|
-
state = LLMResponse.reduce(state, event);
|
|
17
|
-
const response = event.type === "finish" ? LLMResponse.complete(state) : undefined;
|
|
18
|
-
if (!response || event.type !== "finish")
|
|
19
|
-
return Effect.succeed(event);
|
|
20
|
-
const finish = { ...event, usage: response.usage, message: response.message };
|
|
21
|
-
return output === undefined ? Effect.succeed(finish) : withObject(output, finish, state);
|
|
22
|
-
}));
|
|
23
|
-
}))));
|
|
14
|
+
return Stream.unwrap(prepare(input).pipe(Effect.map(({ request, output }) => stepStream(request, undefined, options, (step) => Stream.fromEffect(finishStep(step, step.response.usage, output))))));
|
|
24
15
|
}
|
|
25
16
|
export function loop(input, options) {
|
|
26
17
|
const { tools, until, ...rest } = input;
|
|
27
|
-
|
|
28
|
-
const clientCalls = (response, output) => output && response.toolCalls.some((call) => call.name === OBJECT_TOOL)
|
|
29
|
-
? []
|
|
30
|
-
: response.toolCalls.filter((call) => call.providerExecuted !== true);
|
|
31
|
-
const step = (request, steps, usage, output) => Stream.suspend(() => {
|
|
32
|
-
let state = LLMResponse.empty();
|
|
33
|
-
return LLMClient.stream(request, options).pipe(Stream.map((event) => event.type === "step-start" || event.type === "step-finish" ? { ...event, index: steps.length } : event), Stream.tap((event) => Effect.sync(() => (state = LLMResponse.reduce(state, event)))),
|
|
34
|
-
// Each call's `finish` ends only this step; the loop emits its own once it stops.
|
|
35
|
-
Stream.filter((event) => event.type !== "finish"), Stream.mapError((error) => withPartial(error, LLMResponse.partial(state))), Stream.concat(Stream.unwrap(Effect.gen(function* () {
|
|
36
|
-
const response = LLMResponse.complete(state);
|
|
37
|
-
const finish = state.events.findLast(LLMEvent.is.finish);
|
|
38
|
-
if (!response || !finish)
|
|
39
|
-
return Stream.empty;
|
|
40
|
-
const total = addUsage(usage, response.usage);
|
|
41
|
-
const calls = clientCalls(response, output);
|
|
42
|
-
const done = [...steps, response];
|
|
43
|
-
if (calls.length === 0 || until?.({ steps: done })) {
|
|
44
|
-
const event = { ...finish, usage: total, message: response.message };
|
|
45
|
-
return Stream.fromEffect(output === undefined || calls.length > 0 ? Effect.succeed(event) : withObject(output, event, state));
|
|
46
|
-
}
|
|
47
|
-
const results = yield* Effect.forEach(calls, (call) => ToolRuntime.dispatch(tools, call), {
|
|
48
|
-
concurrency: "unbounded",
|
|
49
|
-
});
|
|
50
|
-
const next = {
|
|
51
|
-
...request,
|
|
52
|
-
messages: [
|
|
53
|
-
...request.messages,
|
|
54
|
-
response.message,
|
|
55
|
-
...calls.map((call, i) => Message.tool({
|
|
56
|
-
id: call.id,
|
|
57
|
-
name: call.name,
|
|
58
|
-
namespace: call.namespace,
|
|
59
|
-
result: results[i].result,
|
|
60
|
-
providerMetadata: call.providerMetadata,
|
|
61
|
-
})),
|
|
62
|
-
],
|
|
63
|
-
};
|
|
64
|
-
return Stream.fromIterable(results.flatMap((result) => result.events)).pipe(Stream.concat(step(next, done, total, output)));
|
|
65
|
-
}))));
|
|
66
|
-
});
|
|
67
|
-
return Stream.unwrap(prepare({ ...rest, tools }).pipe(Effect.map(({ request, output }) => step(request, [], undefined, output))));
|
|
18
|
+
return Stream.unwrap(prepare({ ...rest, tools }).pipe(Effect.map(({ request, output }) => driveLoop({ tools, until, output, options }, request, [], undefined))));
|
|
68
19
|
}
|
|
69
|
-
export
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
if (event.type === "tool-result" && betweenSteps) {
|
|
97
|
-
messages.push(Message.tool({
|
|
98
|
-
id: event.id,
|
|
99
|
-
name: event.name,
|
|
100
|
-
namespace: event.namespace,
|
|
101
|
-
result: event.result,
|
|
102
|
-
providerMetadata: event.providerMetadata,
|
|
103
|
-
}));
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
if (event.type === "step-start")
|
|
107
|
-
betweenSteps = false;
|
|
108
|
-
step = LLMResponse.reduce(step, event);
|
|
109
|
-
if (event.type !== "step-finish")
|
|
110
|
-
return;
|
|
111
|
-
close(event.reason, event.usage);
|
|
112
|
-
betweenSteps = true;
|
|
113
|
-
})).pipe(Effect.flatMap(() => {
|
|
114
|
-
if (finish === undefined)
|
|
115
|
-
return Effect.fail(new AIError({
|
|
116
|
-
reason: new InvalidProviderOutputError({
|
|
117
|
-
message: "The stream ended without a finish event.",
|
|
118
|
-
classification: "incomplete-stream",
|
|
119
|
-
}),
|
|
120
|
-
}));
|
|
121
|
-
const result = {
|
|
122
|
-
text: steps.at(-1)?.text ?? "",
|
|
123
|
-
steps,
|
|
124
|
-
messages,
|
|
125
|
-
usage: finish.usage,
|
|
126
|
-
finishReason: finish.reason,
|
|
127
|
-
...("object" in finish ? { object: finish.object } : {}),
|
|
128
|
-
};
|
|
129
|
-
return Effect.succeed(result);
|
|
130
|
-
}));
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
const addUsage = (total, step) => {
|
|
134
|
-
if (total === undefined || step === undefined)
|
|
135
|
-
return total ?? step;
|
|
136
|
-
const sum = (key) => (total[key] === undefined && step[key] === undefined ? undefined : (total[key] ?? 0) + (step[key] ?? 0));
|
|
137
|
-
return new Usage({
|
|
138
|
-
// Context size describes the latest call, not a running total.
|
|
139
|
-
contextTokens: step.contextTokens ?? total.contextTokens,
|
|
140
|
-
inputTokens: sum("inputTokens"),
|
|
141
|
-
outputTokens: sum("outputTokens"),
|
|
142
|
-
nonCachedInputTokens: sum("nonCachedInputTokens"),
|
|
143
|
-
cacheReadInputTokens: sum("cacheReadInputTokens"),
|
|
144
|
-
cacheWriteInputTokens: sum("cacheWriteInputTokens"),
|
|
145
|
-
reasoningTokens: sum("reasoningTokens"),
|
|
146
|
-
totalTokens: sum("totalTokens"),
|
|
147
|
-
cost: sum("cost"),
|
|
148
|
-
});
|
|
20
|
+
export { collect } from "./loop.js";
|
|
21
|
+
/**
|
|
22
|
+
* Stream one model call. Its `finish` is held back: `after` gets the completed step and streams what follows it.
|
|
23
|
+
* With `index`, the step's `step-start` and `step-finish` carry it.
|
|
24
|
+
*/
|
|
25
|
+
const stepStream = (request, index, options, after) => Stream.suspend(() => {
|
|
26
|
+
let state = LLMResponse.empty();
|
|
27
|
+
let finish;
|
|
28
|
+
return LLMClient.stream(request, options).pipe(Stream.map((event) => index !== undefined && (event.type === "step-start" || event.type === "step-finish")
|
|
29
|
+
? { ...event, index }
|
|
30
|
+
: event), Stream.tap((event) => Effect.sync(() => {
|
|
31
|
+
state = LLMResponse.reduce(state, event);
|
|
32
|
+
if (event.type === "finish")
|
|
33
|
+
finish = event;
|
|
34
|
+
})), Stream.filter((event) => event.type !== "finish"), Stream.mapError((error) => withPartial(error, LLMResponse.partial(state))), Stream.concat(Stream.suspend(() => {
|
|
35
|
+
const response = LLMResponse.complete(state);
|
|
36
|
+
return response && finish ? after({ response, finish }) : Stream.empty;
|
|
37
|
+
})));
|
|
38
|
+
});
|
|
39
|
+
/** The `finish` that ends a stream or loop: the final step's `message`, the given `usage`, and the decoded `object`. */
|
|
40
|
+
const finishStep = (step, usage, output) => {
|
|
41
|
+
const event = { ...step.finish, usage, message: step.response.message };
|
|
42
|
+
if (output === undefined)
|
|
43
|
+
return Effect.succeed(event);
|
|
44
|
+
return decodeObject(output, step.response).pipe(Effect.map((object) => ({ ...event, object })));
|
|
149
45
|
};
|
|
46
|
+
const driveLoop = (context, request, steps, usage) => stepStream(request, steps.length, context.options, (step) => {
|
|
47
|
+
const total = addUsage(usage, step.response.usage);
|
|
48
|
+
const calls = pendingCalls(step.response, context.output && OBJECT_TOOL);
|
|
49
|
+
const done = [...steps, step.response];
|
|
50
|
+
if (calls.length === 0 || context.until?.({ steps: done }))
|
|
51
|
+
return Stream.fromEffect(finishStep(step, total, calls.length === 0 ? context.output : undefined));
|
|
52
|
+
return Stream.unwrap(runTools(context.tools, calls).pipe(Effect.map((results) => Stream.fromIterable(results.flatMap((result) => result.events)).pipe(Stream.concat(driveLoop(context, nextRequest(request, step.response, calls, results, context.output !== undefined), done, total))))));
|
|
53
|
+
});
|
|
150
54
|
const OBJECT_TOOL = "generate_object";
|
|
151
55
|
// `schema` adds a hidden tool whose input is the answer. With other tools the model only has to call some tool.
|
|
152
56
|
const prepare = (input) => {
|
|
@@ -180,12 +84,6 @@ const decodeObject = (output, response) => {
|
|
|
180
84
|
.pipe(Effect.mapError((error) => invalid(`schema decode failed: ${error.message}`, error)));
|
|
181
85
|
return Effect.fail(invalid(`model did not call the forced \`${OBJECT_TOOL}\` tool`));
|
|
182
86
|
};
|
|
183
|
-
const withObject = (output, event, state) => {
|
|
184
|
-
const response = LLMResponse.complete(state);
|
|
185
|
-
return response === undefined
|
|
186
|
-
? Effect.succeed(event)
|
|
187
|
-
: decodeObject(output, response).pipe(Effect.map((object) => ({ ...event, object })));
|
|
188
|
-
};
|
|
189
87
|
/** Normalize text request input into a plain `LLMRequest`, with `prompt` turned into the one user message. */
|
|
190
88
|
export const request = (input) => {
|
|
191
89
|
if ((input.prompt === undefined) === (input.messages === undefined))
|
package/dist/loop.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Effect, Stream } from "effect";
|
|
2
|
+
import { AIError, LLMResponse, Message, Usage, LLMEvent, type FinishReasonDetails, type LLMRequest } from "./schema/index.js";
|
|
3
|
+
import type { DispatchResult, PendingCall } from "./tool-runtime.js";
|
|
4
|
+
/**
|
|
5
|
+
* Client calls to answer before the next step. A call whose input was not valid JSON carries the error the model
|
|
6
|
+
* gets back, so it can retry. A step is final when it calls `answerTool`, even alongside other tools, or when it hits
|
|
7
|
+
* the output token limit, which may have cut its calls off.
|
|
8
|
+
*/
|
|
9
|
+
export declare const pendingCalls: (response: LLMResponse, answerTool?: string) => ReadonlyArray<PendingCall>;
|
|
10
|
+
/** The step's assistant message followed by one tool message per call, in call order. */
|
|
11
|
+
export declare const stepMessages: (response: LLMResponse, calls: ReadonlyArray<PendingCall>, results: ReadonlyArray<DispatchResult>) => ReadonlyArray<Message>;
|
|
12
|
+
/**
|
|
13
|
+
* The request for the step after `response`, with its messages and tool results appended. A caller's forced
|
|
14
|
+
* `toolChoice` applies to the first step only; with `keepForcedChoice` (the answer tool's) it stays.
|
|
15
|
+
*/
|
|
16
|
+
export declare const nextRequest: (request: LLMRequest, response: LLMResponse, calls: ReadonlyArray<PendingCall>, results: ReadonlyArray<DispatchResult>, keepForcedChoice: boolean) => LLMRequest;
|
|
17
|
+
/** Sum usage across steps. */
|
|
18
|
+
export declare const addUsage: (total: Usage | undefined, step: Usage | undefined) => Usage | undefined;
|
|
19
|
+
/** The result of `collect`: every step of a stream from `stream` or `loop`, folded into one value. */
|
|
20
|
+
export interface Collected {
|
|
21
|
+
/** Text of the final step. */
|
|
22
|
+
readonly text: string;
|
|
23
|
+
/** One response per model call, in order. */
|
|
24
|
+
readonly steps: ReadonlyArray<LLMResponse>;
|
|
25
|
+
/** Each step's assistant message followed by its tool results, ready to append to the request's messages. */
|
|
26
|
+
readonly messages: ReadonlyArray<Message>;
|
|
27
|
+
/** Usage from the terminal `finish`, summed across steps for a loop. */
|
|
28
|
+
readonly usage?: Usage;
|
|
29
|
+
readonly finishReason: FinishReasonDetails;
|
|
30
|
+
}
|
|
31
|
+
type FinishOf<Event> = Extract<Event, {
|
|
32
|
+
readonly type: "finish";
|
|
33
|
+
}>;
|
|
34
|
+
/** `Collected`, plus `object` when the stream was started with `schema`. */
|
|
35
|
+
export type CollectResult<Event> = "object" extends keyof FinishOf<Event> ? Collected & Pick<FinishOf<Event>, "object"> : Collected;
|
|
36
|
+
/** Run a stream from `stream` or `loop` to the end and fold its events into the final result. */
|
|
37
|
+
export declare function collect<Event extends LLMEvent, E, R>(events: Stream.Stream<Event, E, R>): Effect.Effect<CollectResult<Event>, E | AIError, R>;
|
|
38
|
+
export {};
|
package/dist/loop.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { Effect, Stream } from "effect";
|
|
2
|
+
import { AIError, InvalidProviderOutputError, LLMResponse, Message, Usage, LLMEvent, ToolCallPart, ToolChoice, } from "./schema/index.js";
|
|
3
|
+
/**
|
|
4
|
+
* Client calls to answer before the next step. A call whose input was not valid JSON carries the error the model
|
|
5
|
+
* gets back, so it can retry. A step is final when it calls `answerTool`, even alongside other tools, or when it hits
|
|
6
|
+
* the output token limit, which may have cut its calls off.
|
|
7
|
+
*/
|
|
8
|
+
export const pendingCalls = (response, answerTool) => {
|
|
9
|
+
if (response.finishReason.normalized === "length")
|
|
10
|
+
return [];
|
|
11
|
+
if (answerTool !== undefined && response.toolCalls.some((call) => call.name === answerTool))
|
|
12
|
+
return [];
|
|
13
|
+
return [
|
|
14
|
+
...response.toolCalls.filter((call) => call.providerExecuted !== true).map((call) => ({ call })),
|
|
15
|
+
...response.events.filter(LLMEvent.is.toolInputError).map((event) => ({
|
|
16
|
+
call: invalidCall(event),
|
|
17
|
+
error: `Invalid tool arguments: the input is not valid JSON. Received: ${event.raw}`,
|
|
18
|
+
})),
|
|
19
|
+
];
|
|
20
|
+
};
|
|
21
|
+
/** The call to replay for input that was not valid JSON. Providers require an object input, so it is empty. */
|
|
22
|
+
const invalidCall = (event) => ToolCallPart.make({ id: event.id, name: event.name, namespace: event.namespace, input: {} });
|
|
23
|
+
/** Add the replayed calls for invalid input to the assistant message, so each tool result has its call. */
|
|
24
|
+
const withInvalidCalls = (message, calls) => calls.length === 0 ? message : new Message({ ...message, content: [...message.content, ...calls] });
|
|
25
|
+
/** The step's assistant message followed by one tool message per call, in call order. */
|
|
26
|
+
export const stepMessages = (response, calls, results) => [
|
|
27
|
+
withInvalidCalls(response.message, calls.flatMap((item) => (item.error === undefined ? [] : [item.call]))),
|
|
28
|
+
...calls.map((item, i) => Message.tool({
|
|
29
|
+
id: item.call.id,
|
|
30
|
+
name: item.call.name,
|
|
31
|
+
namespace: item.call.namespace,
|
|
32
|
+
result: results[i].result,
|
|
33
|
+
providerMetadata: item.call.providerMetadata,
|
|
34
|
+
})),
|
|
35
|
+
];
|
|
36
|
+
/**
|
|
37
|
+
* The request for the step after `response`, with its messages and tool results appended. A caller's forced
|
|
38
|
+
* `toolChoice` applies to the first step only; with `keepForcedChoice` (the answer tool's) it stays.
|
|
39
|
+
*/
|
|
40
|
+
export const nextRequest = (request, response, calls, results, keepForcedChoice) => ({
|
|
41
|
+
...request,
|
|
42
|
+
toolChoice: !keepForcedChoice && (request.toolChoice?.type === "required" || request.toolChoice?.type === "tool")
|
|
43
|
+
? new ToolChoice({ type: "auto", disableParallelToolUse: request.toolChoice.disableParallelToolUse })
|
|
44
|
+
: request.toolChoice,
|
|
45
|
+
messages: [...request.messages, ...stepMessages(response, calls, results)],
|
|
46
|
+
});
|
|
47
|
+
/** Sum usage across steps. */
|
|
48
|
+
export const addUsage = (total, step) => {
|
|
49
|
+
if (total === undefined || step === undefined)
|
|
50
|
+
return total ?? step;
|
|
51
|
+
const sum = (key) => (total[key] === undefined && step[key] === undefined ? undefined : (total[key] ?? 0) + (step[key] ?? 0));
|
|
52
|
+
return new Usage({
|
|
53
|
+
// Context size describes the latest call, not a running total.
|
|
54
|
+
contextTokens: step.contextTokens ?? total.contextTokens,
|
|
55
|
+
inputTokens: sum("inputTokens"),
|
|
56
|
+
outputTokens: sum("outputTokens"),
|
|
57
|
+
nonCachedInputTokens: sum("nonCachedInputTokens"),
|
|
58
|
+
cacheReadInputTokens: sum("cacheReadInputTokens"),
|
|
59
|
+
cacheWriteInputTokens: sum("cacheWriteInputTokens"),
|
|
60
|
+
reasoningTokens: sum("reasoningTokens"),
|
|
61
|
+
totalTokens: sum("totalTokens"),
|
|
62
|
+
cost: sum("cost"),
|
|
63
|
+
});
|
|
64
|
+
};
|
|
65
|
+
export function collect(events) {
|
|
66
|
+
return Effect.suspend(() => {
|
|
67
|
+
const steps = [];
|
|
68
|
+
const messages = [];
|
|
69
|
+
let step = LLMResponse.empty();
|
|
70
|
+
// Between a `step-finish` and the next `step-start`, tool results come from the loop running tools.
|
|
71
|
+
let betweenSteps = false;
|
|
72
|
+
// The last step's assistant message, and its calls with invalid input that the loop may answer.
|
|
73
|
+
let assistant = -1;
|
|
74
|
+
let invalid = [];
|
|
75
|
+
let finish;
|
|
76
|
+
const close = (reason, usage) => {
|
|
77
|
+
if (step.events.length === 0)
|
|
78
|
+
return;
|
|
79
|
+
const response = new LLMResponse({
|
|
80
|
+
message: step.message,
|
|
81
|
+
events: step.events,
|
|
82
|
+
usage: usage ?? step.usage,
|
|
83
|
+
finishReason: reason,
|
|
84
|
+
});
|
|
85
|
+
steps.push(response);
|
|
86
|
+
assistant = messages.push(response.message) - 1;
|
|
87
|
+
invalid = step.events.filter(LLMEvent.is.toolInputError).map(invalidCall);
|
|
88
|
+
step = LLMResponse.empty();
|
|
89
|
+
};
|
|
90
|
+
return Stream.runForEach(events, (event) => Effect.sync(() => {
|
|
91
|
+
if (event.type === "finish") {
|
|
92
|
+
close(event.reason, event.usage);
|
|
93
|
+
finish = event;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (event.type === "tool-result" && betweenSteps) {
|
|
97
|
+
const call = invalid.find((item) => item.id === event.id);
|
|
98
|
+
if (call)
|
|
99
|
+
messages[assistant] = withInvalidCalls(messages[assistant], [call]);
|
|
100
|
+
messages.push(Message.tool({
|
|
101
|
+
id: event.id,
|
|
102
|
+
name: event.name,
|
|
103
|
+
namespace: event.namespace,
|
|
104
|
+
result: event.result,
|
|
105
|
+
providerMetadata: event.providerMetadata,
|
|
106
|
+
}));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (event.type === "step-start")
|
|
110
|
+
betweenSteps = false;
|
|
111
|
+
step = LLMResponse.reduce(step, event);
|
|
112
|
+
if (event.type !== "step-finish")
|
|
113
|
+
return;
|
|
114
|
+
close(event.reason, event.usage);
|
|
115
|
+
betweenSteps = true;
|
|
116
|
+
})).pipe(Effect.flatMap(() => {
|
|
117
|
+
if (finish === undefined)
|
|
118
|
+
return Effect.fail(new AIError({
|
|
119
|
+
reason: new InvalidProviderOutputError({
|
|
120
|
+
message: "The stream ended without a finish event.",
|
|
121
|
+
classification: "incomplete-stream",
|
|
122
|
+
}),
|
|
123
|
+
}));
|
|
124
|
+
const result = {
|
|
125
|
+
text: steps.at(-1)?.text ?? "",
|
|
126
|
+
steps,
|
|
127
|
+
messages,
|
|
128
|
+
usage: finish.usage,
|
|
129
|
+
finishReason: finish.reason,
|
|
130
|
+
...("object" in finish ? { object: finish.object } : {}),
|
|
131
|
+
};
|
|
132
|
+
return Effect.succeed(result);
|
|
133
|
+
}));
|
|
134
|
+
});
|
|
135
|
+
}
|
package/dist/tool-runtime.d.ts
CHANGED
|
@@ -10,6 +10,13 @@ export interface DispatchResult extends ToolSettlement {
|
|
|
10
10
|
}
|
|
11
11
|
/** Execute one canonical tool call without owning provider IO or continuation. */
|
|
12
12
|
export declare const dispatch: (tools: ReadonlyArray<Tool>, call: ToolCallPart) => Effect.Effect<DispatchResult>;
|
|
13
|
+
/** A call the loop answers before the next step. With `error`, it is not run and the model gets the error back. */
|
|
14
|
+
export interface PendingCall {
|
|
15
|
+
readonly call: ToolCallPart;
|
|
16
|
+
readonly error?: string;
|
|
17
|
+
}
|
|
18
|
+
/** Run a step's tool calls concurrently, with results in call order. */
|
|
19
|
+
export declare const runTools: (tools: ReadonlyArray<Tool>, calls: ReadonlyArray<PendingCall>) => Effect.Effect<DispatchResult[], never, never>;
|
|
13
20
|
export declare const ToolRuntime: {
|
|
14
21
|
readonly dispatch: typeof dispatch;
|
|
15
22
|
};
|
package/dist/tool-runtime.js
CHANGED
|
@@ -14,6 +14,10 @@ export const dispatch = (tools, call) => {
|
|
|
14
14
|
return Effect.succeed(result(call, { type: "error", value: `Tool has no execute handler: ${name}` }));
|
|
15
15
|
return decodeAndExecute(tool, call).pipe(Effect.map((value) => result(call, value)), Effect.catchTag("Tool.Error", (failure) => Effect.succeed(result(call, { type: "error", value: failure.message }))));
|
|
16
16
|
};
|
|
17
|
+
/** Run a step's tool calls concurrently, with results in call order. */
|
|
18
|
+
export const runTools = (tools, calls) => Effect.forEach(calls, (item) => item.error === undefined
|
|
19
|
+
? dispatch(tools, item.call)
|
|
20
|
+
: Effect.succeed(result(item.call, { type: "error", value: item.error })), { concurrency: "unbounded" });
|
|
17
21
|
const decodeAndExecute = (tool, call) => tool._decode(call.input).pipe(Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })), Effect.flatMap((decoded) => tool.execute(decoded, {
|
|
18
22
|
id: call.id,
|
|
19
23
|
name: call.name,
|
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-470",
|
|
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-470",
|
|
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-470",
|
|
534
534
|
"aws4fetch": "1.0.20",
|
|
535
535
|
"effect": "4.1.0",
|
|
536
536
|
"google-auth-library": "10.5.0"
|