@opencode/ai 0.0.0-dev-329 → 0.0.0-dev-338

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/dist/index.d.ts CHANGED
@@ -1437,5 +1437,6 @@ export declare const ai: {
1437
1437
  };
1438
1438
  dispose: () => Promise<void>;
1439
1439
  };
1440
+ export { AIError } from "./schema/index.js";
1440
1441
  export * as AI from "./index.js";
1441
1442
  export type { ExecutableTool, Tool, ToolOptions, Tools } from "./tool.js";
package/dist/index.js CHANGED
@@ -134,4 +134,5 @@ export const tool = (config) => {
134
134
  };
135
135
  /** Default client over `RequestExecutor.fetchLayer` for scripts; the runtime builds its layer on first use. */
136
136
  export const ai = make();
137
+ export { AIError } from "./schema/index.js";
137
138
  export * as AI from "./index.js";
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, } from "./schema/index.js";
4
+ import { GenerationOptions, HttpOptions, InvalidProviderOutputError, AIError, LLMEvent, LLMRequest, LLMResponse, Message, LanguageModel, SystemPart, ToolChoice, ToolEntry, withPartial, } from "./schema/index.js";
5
5
  import { tool, toDefinitions } from "./tool.js";
6
6
  import { ToolRuntime } from "./tool-runtime.js";
7
7
  export function generate(input, options) {
@@ -13,11 +13,11 @@ export function stream(input, options) {
13
13
  export function loop(input, options) {
14
14
  const { tools, until, ...rest } = input;
15
15
  const step = (request, steps) => Stream.suspend(() => {
16
- const events = [];
17
- 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(() => events.push(event))), Stream.concat(Stream.unwrap(Effect.gen(function* () {
18
- const response = LLMResponse.fromEvents(events);
16
+ let state = LLMResponse.empty();
17
+ 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)))), Stream.mapError((error) => withPartial(error, LLMResponse.partial(state))), Stream.concat(Stream.unwrap(Effect.gen(function* () {
18
+ const response = LLMResponse.complete(state);
19
19
  const calls = response?.toolCalls.filter((call) => call.providerExecuted !== true) ?? [];
20
- if (!response || calls.length === 0 || events.some(LLMEvent.is.providerError))
20
+ if (!response || calls.length === 0 || state.events.some(LLMEvent.is.providerError))
21
21
  return Stream.empty;
22
22
  const done = [...steps, response];
23
23
  if (until?.({ steps: done }))
@@ -81,18 +81,17 @@ const runGenerateObject = Effect.fn("LLM.generateObject")(function* (options, to
81
81
  });
82
82
  const response = yield* LLMClient.generate(generateRequest);
83
83
  const call = response.toolCalls.find((event) => event.name === GENERATE_OBJECT_TOOL_NAME);
84
- if (!call)
85
- return yield* new AIError({
86
- reason: new InvalidProviderOutputError({
87
- message: `generateObject: model did not call the forced \`${GENERATE_OBJECT_TOOL_NAME}\` tool`,
88
- }),
89
- });
90
- const object = yield* tool._decode(call.input).pipe(Effect.mapError((error) => new AIError({
91
- reason: new InvalidProviderOutputError({
92
- message: `generateObject: tool input failed schema decode: ${error.message}`,
93
- cause: error,
94
- }),
95
- })));
84
+ const invalidOutput = (reason) => new AIError({ reason, partial: response });
85
+ if (!call) {
86
+ const message = response.finishReason.normalized === "length"
87
+ ? "generateObject: output hit the token limit before the forced tool call completed"
88
+ : `generateObject: model did not call the forced \`${GENERATE_OBJECT_TOOL_NAME}\` tool`;
89
+ return yield* invalidOutput(new InvalidProviderOutputError({ message }));
90
+ }
91
+ const object = yield* tool._decode(call.input).pipe(Effect.mapError((error) => invalidOutput(new InvalidProviderOutputError({
92
+ message: `generateObject: tool input failed schema decode: ${error.message}`,
93
+ cause: error,
94
+ }))));
96
95
  return new GenerateObjectResponse(object, response);
97
96
  });
98
97
  export function generateObject(options) {
@@ -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>;
@@ -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)
@@ -265,12 +265,13 @@ const streamRequestWith = (runtime) => (request, options) => Stream.unwrap(Effec
265
265
  const compiled = yield* compile(request, options);
266
266
  return compiled.route.streamPrepared(compiled.prepared, compiled.request, runtime, options);
267
267
  }));
268
- const generateWith = (stream) => Effect.fn("LLM.generate")(function* (request, options) {
269
- const state = yield* stream(request, options).pipe(Stream.runFold(LLMResponse.empty, LLMResponse.reduce));
268
+ export const generateWith = (stream) => Effect.fn("LLM.generate")(function* (request, options) {
269
+ let state = LLMResponse.empty();
270
+ yield* stream(request, options).pipe(Stream.runForEach((event) => Effect.sync(() => (state = LLMResponse.reduce(state, event)))), Effect.mapError((error) => withPartial(error, LLMResponse.partial(state))));
270
271
  const response = LLMResponse.complete(state);
271
272
  if (response)
272
273
  return response;
273
- return yield* incompleteStreamError(`${request.model.provider}/${request.model.route.id}`);
274
+ return yield* withPartial(incompleteStreamError(`${request.model.provider}/${request.model.route.id}`), LLMResponse.partial(state));
274
275
  });
275
276
  export function stream(request, options) {
276
277
  return Stream.unwrap(Effect.gen(function* () {
@@ -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
@@ -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
@@ -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. */
@@ -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.js CHANGED
@@ -5,8 +5,8 @@ export { TestImage } from "./testing/image.js";
5
5
  export { TestSpeech } from "./testing/speech.js";
6
6
  export { TestTranscription } from "./testing/transcription.js";
7
7
  export { TestVideo } from "./testing/video.js";
8
- import { LLMClient, } from "./route/client.js";
9
- import { LLMEvent, LLMResponse, CompactionResponse, CompactionCheckpointResponse, } from "./schema/index.js";
8
+ import { LLMClient, generateWith, } from "./route/client.js";
9
+ import { LLMEvent, CompactionResponse, CompactionCheckpointResponse, } from "./schema/index.js";
10
10
  import { Context, Effect, Layer, Stream } from "effect";
11
11
  import { TestScript } from "./testing/script.js";
12
12
  export class Test extends Context.Service()("@opencode/ai/TestLLM/Test") {
@@ -56,12 +56,7 @@ const make = (options) => Effect.sync(() => {
56
56
  ...script.controls,
57
57
  compact,
58
58
  stream,
59
- generate: (request) => stream(request).pipe(Stream.runFold(LLMResponse.empty, LLMResponse.reduce), Effect.flatMap((state) => {
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
- })),
59
+ generate: generateWith(stream),
65
60
  });
66
61
  });
67
62
  /** Provides one shared implementation under the normal client and test-control tags. */
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-329",
3
+ "version": "0.0.0-dev-338",
4
4
  "name": "@opencode/ai",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -516,7 +516,7 @@
516
516
  "devDependencies": {
517
517
  "@clack/prompts": "1.0.0-alpha.1",
518
518
  "@effect/platform-node": "4.0.6",
519
- "@opencode/http-recorder": "0.0.0-dev-329",
519
+ "@opencode/http-recorder": "0.0.0-dev-338",
520
520
  "@tsconfig/bun": "1.0.9",
521
521
  "@types/bun": "1.4.3",
522
522
  "@typescript/native": "npm:typescript@7.1.0-beta",
@@ -526,7 +526,7 @@
526
526
  "@aws-sdk/credential-providers": "3.1057.0",
527
527
  "@smithy/eventstream-codec": "4.2.14",
528
528
  "@smithy/util-utf8": "4.2.2",
529
- "@opencode/schema": "0.0.0-dev-329",
529
+ "@opencode/schema": "0.0.0-dev-338",
530
530
  "aws4fetch": "1.0.20",
531
531
  "effect": "4.0.6",
532
532
  "google-auth-library": "10.5.0"