@opencode/ai 2.2.3 → 2.2.5

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.js CHANGED
@@ -2,9 +2,9 @@ import { Effect, Layer, ManagedRuntime, Schema, Stream } from "effect";
2
2
  import { AIClient } from "./ai-client.js";
3
3
  import { Decision } from "./decision.js";
4
4
  import { Image } from "./image.js";
5
- import { LLM } from "./effect.js";
5
+ import { LLM } from "./llm.js";
6
6
  import { Media } from "./media.js";
7
- import { LLMClient, } from "./route/client.js";
7
+ import {} from "./route/client.js";
8
8
  import { RequestExecutor } from "./route/executor.js";
9
9
  import { AIError, InvalidRequestError, LanguageModel, } from "./schema/index.js";
10
10
  import { Speech } from "./speech.js";
@@ -28,17 +28,17 @@ export const make = (options = {}) => {
28
28
  const runtime = ManagedRuntime.make(Layer.merge(AIClient.layerWith(options.layer ?? RequestExecutor.fetchLayer),
29
29
  // `R` is only inferred from `clients`, so it is `never` whenever `clients` is omitted.
30
30
  (options.clients ?? Layer.empty)));
31
- /** Run any package Effect (for example `LLMClient.compact(...)`) inside this runtime. */
31
+ /** Run any package Effect (for example `ai.compact(...)` from `@opencode/ai/effect`) inside this runtime. */
32
32
  const run = (effect, options) => runtime.runPromise(Effect.raceFirst(effect, abortEffect(options?.signal)));
33
33
  const iterate = (stream, options) => Stream.toAsyncIterable(Stream.unwrap(runtime.contextEffect.pipe(Effect.map((context) => stream.pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context))))));
34
34
  function generateObject(input, options) {
35
35
  return run("schema" in input ? LLM.generateObject(input) : LLM.generateObject(input), options);
36
36
  }
37
- // The overloads pair each request type with its mechanism; `LLMClient.compact` checks the route's capability at runtime.
37
+ // The overloads pair each request type with its mechanism; `LLM.compact` checks the route's capability at runtime.
38
38
  function compact(request, options) {
39
39
  return options?.mechanism === "trigger"
40
- ? run(LLMClient.compact(request, options), options)
41
- : run(LLMClient.compact(request, options), options);
40
+ ? run(LLM.compact(request, options), options)
41
+ : run(LLM.compact(request, options), options);
42
42
  }
43
43
  const handle = (generation) => ({
44
44
  ...generation.snapshot,
@@ -77,18 +77,16 @@ export const make = (options = {}) => {
77
77
  catch: (cause) => fileError(`Failed to write media file ${path}`, cause),
78
78
  }))), options);
79
79
  },
80
- llm: {
81
- request: LLM.request,
82
- generate: (input, options) => run(LLM.generate(input, options), options),
83
- stream: (input, options) => iterate(LLM.stream(input, options), options),
84
- /** Stream model calls, running their tool calls, until the model stops calling tools or `until` is true. */
85
- loop: (input, options) => iterate(LLM.loop(input, options), options),
86
- /** Decode the model's output against `schema` (or `jsonSchema`, unvalidated) like `LLM.generateObject`. */
87
- generateObject,
88
- /** Compact a Responses request like `LLMClient.compact`: a replacement window, or a checkpoint with `mechanism: "trigger"`. */
89
- compact,
90
- canCompact: LLMClient.canCompact,
91
- },
80
+ request: LLM.request,
81
+ generate: (input, options) => run(LLM.generate(input, options), options),
82
+ stream: (input, options) => iterate(LLM.stream(input, options), options),
83
+ /** Stream model calls, running their tool calls, until the model stops calling tools or `until` is true. */
84
+ loop: (input, options) => iterate(LLM.loop(input, options), options),
85
+ /** Decode the model's output against `schema` (or `jsonSchema`, unvalidated). */
86
+ generateObject,
87
+ /** Compact a Responses request: a replacement window, or a checkpoint with `mechanism: "trigger"`. */
88
+ compact,
89
+ canCompact: LLM.canCompact,
92
90
  image: {
93
91
  request: Image.request,
94
92
  generate: (input, options) => run(Image.generate(input, options), options),
@@ -135,7 +133,11 @@ export const tool = (config) => {
135
133
  catch: (error) => new ToolFailure({ message: error instanceof Error ? error.message : String(error), error }),
136
134
  })));
137
135
  };
138
- /** Default client over `RequestExecutor.fetchLayer` for scripts; the runtime builds its layer on first use. */
136
+ /** Default client over `RequestExecutor.fetchLayer`; the runtime builds its layer on first use and holds nothing to dispose. */
139
137
  export const ai = make();
140
- export { AIError } from "./schema/index.js";
141
138
  export * as AI from "./index.js";
139
+ export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
140
+ export { ProtocolID, RouteID, ModelID, ProviderID, ResponseID, ContentBlockID, ToolCallID, JsonSchema, ProviderOptions, ProviderMetadata, HttpTimeout, RequestEncoding, HttpOptions, GenerationOptions, LanguageModelDefaults, ReasoningEfforts, ReasoningEffort, LanguageModelCompatibility, LanguageModel, LanguageModelSchema, CacheTTL, CacheHint, CachePolicyObject, CachePolicy, MessageRole, SystemPart, TextPart, MediaPart, ToolResultValue, ToolOutput, ToolCallPart, ToolResultPart, ReasoningPart, CompactionPart, EffortPart, ContentPart, Message, Freeform, ToolDefinition, ToolNamespace, ToolEntry, ToolChoice, LLMRequest, FinishReason, Usage, MediaUsage, CompactionResponse, CompactionCheckpointResponse, StepStart, TextStart, TextDelta, TextEnd, ReasoningStart, ReasoningDelta, ReasoningEnd, ToolInputStart, ToolInputDelta, ToolInputEnd, ToolInputError, ToolCall, ToolResult, ToolError, FinishReasonDetails, StepFinish, Finish, MediaEvent, ProviderErrorEvent, LLMEvent, LLMResponse, HttpContext, HttpRateLimitDetails, InvalidRequestError, UnsupportedOperationError, ProviderConfigurationError, NoRouteError, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
141
+ export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js";
142
+ export { ChoiceAnswer, ChoiceQuestion, ChoiceValue, DecisionAnswer, DecisionJsonPart, DecisionMediaPart, DecisionModel, DecisionModelCompatibility, DecisionModelSchema, DecisionPart, DecisionQuestion, DecisionRequest, DecisionResponse, DecisionTextPart, DecisionUsage, ErrorAnswer, ErrorReason, PredicateAnswer, PredicateQuestion, ScoreAnswer, ScoreQuestion, } from "./decision.js";
143
+ export { Media } from "./media.js";
package/dist/llm.d.ts CHANGED
@@ -276,4 +276,5 @@ export interface GenerateObjectDynamicOptions<SelectedLanguageModel extends Lang
276
276
  */
277
277
  export declare function generateObject<const SelectedLanguageModel extends LanguageModel, S extends ToolSchema<any>>(options: GenerateObjectOptions<S, SelectedLanguageModel>): Effect.Effect<GenerateObjectResponse<Schema.Schema.Type<S>>, AIError, Service>;
278
278
  export declare function generateObject<const SelectedLanguageModel extends LanguageModel>(options: GenerateObjectDynamicOptions<SelectedLanguageModel>): Effect.Effect<GenerateObjectResponse<unknown>, AIError, Service>;
279
- export {};
279
+ export { canCompact, compact } from "./route/client.js";
280
+ export * as LLM from "./llm.js";
package/dist/llm.js CHANGED
@@ -102,3 +102,5 @@ export function generateObject(options) {
102
102
  const { jsonSchema, ...rest } = options;
103
103
  return runGenerateObject(rest, tool({ description: GENERATE_OBJECT_TOOL_DESCRIPTION, jsonSchema }));
104
104
  }
105
+ export { canCompact, compact } from "./route/client.js";
106
+ export * as LLM from "./llm.js";
@@ -699,6 +699,8 @@ const requireThinkingSignature = (request) => {
699
699
  return false;
700
700
  if (provider.includes("xiaomi") || model.includes("mimo") || baseURL.includes("xiaomimimo.com"))
701
701
  return false;
702
+ if (model.startsWith("qwen") || model.startsWith("minimax-"))
703
+ return false;
702
704
  return true;
703
705
  };
704
706
  // Opus 4.8 and every Claude 5 model accept mid-conversation system messages; later versions inherit support.
@@ -822,20 +824,9 @@ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
822
824
  continue;
823
825
  }
824
826
  if (!signature || signature.trim().length === 0) {
825
- if (part.text.trim().length === 0)
826
- continue;
827
- if (!requireThinkingSignature(request)) {
827
+ if (part.text.trim().length > 0 && !requireThinkingSignature(request)) {
828
828
  content.push({ type: "thinking", thinking: part.text, signature: "" });
829
- continue;
830
829
  }
831
- // Without a signature this cannot be a valid thinking block per
832
- // the SDK ThinkingBlockParam:3217 — demote to text so the
833
- // conversation remains sendable.
834
- content.push({
835
- type: "text",
836
- text: part.text,
837
- cache_control: cacheControl(breakpoints, part.cache),
838
- });
839
830
  continue;
840
831
  }
841
832
  content.push({ type: "thinking", thinking: part.text, signature });
@@ -335,13 +335,8 @@ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
335
335
  content.push({ reasoningContent: { redactedContent: redactedData } });
336
336
  continue;
337
337
  }
338
- if (signature === undefined || signature.trim().length === 0) {
339
- // Interrupted streams and model switches can leave unsigned reasoning.
340
- // Preserve readable history as text rather than replay invalid reasoningContent.
341
- if (part.text.trim().length > 0)
342
- content.push(...textWithCache(breakpoints, part.text, part.cache));
338
+ if (signature === undefined || signature.trim().length === 0)
343
339
  continue;
344
- }
345
340
  content.push({ reasoningContent: { reasoningText: { text: part.text, signature } } });
346
341
  continue;
347
342
  }
@@ -13,23 +13,11 @@ import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
13
13
  import { Lifecycle } from "./utils/lifecycle.js";
14
14
  const ADAPTER = "gemini";
15
15
  const CONTINUATION = "CONTINUATION";
16
- // Google documents this sentinel for replaying Gemini 3 function calls after their original signature was lost.
16
+ // Google documents this sentinel for replaying function calls after their original signature was lost.
17
17
  const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator";
18
18
  // Gemini 2.5 rejects a budget under the model's minimum: 512 on Flash-Lite, the highest, and 128 on Pro.
19
19
  const MIN_THINKING_BUDGET = 512;
20
20
  export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
21
- // Gemini 3 rejects replayed function calls without a thought signature. Google's SDKs avoid that in normal chats by
22
- // retaining complete model responses, but OpenCode reconstructs durable history and may encounter an unsigned call
23
- // from an older or external session. Model IDs are open-ended, so unknown Gemini aliases inherit current behavior.
24
- const requiresThoughtSignatureFallback = (modelID) => {
25
- if (!/(^|\/)gemini-/i.test(modelID))
26
- return false;
27
- if (/(^|\/)gemini-(?:1|2)(?:[.-]|$)/i.test(modelID))
28
- return false;
29
- if (/(^|\/)gemini-pro(?:-vision)?$/i.test(modelID))
30
- return false;
31
- return !/(^|\/)gemini-robotics-er-1\.5(?:[.-]|$)/i.test(modelID);
32
- };
33
21
  // Gemini 3 accepts media nested inside function responses; matched Gemini 2.5 variants reject it,
34
22
  // so their tool-result attachments lower as a separate user turn instead.
35
23
  const routesLegacyToolMedia = (modelID) => /gemini-2[.-]5(?:[.-]|$)/i.test(modelID);
@@ -293,10 +281,7 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
293
281
  const signature = lowered.thoughtSignature;
294
282
  parts.push({
295
283
  ...lowered,
296
- thoughtSignature: signature ??
297
- (requiresThoughtSignatureFallback(request.model.id) && !hasSignedToolCall
298
- ? SKIP_THOUGHT_SIGNATURE_VALIDATOR
299
- : undefined),
284
+ thoughtSignature: signature ?? (!hasSignedToolCall ? SKIP_THOUGHT_SIGNATURE_VALIDATOR : undefined),
300
285
  });
301
286
  if (signature !== undefined)
302
287
  hasSignedToolCall = true;
@@ -14,6 +14,7 @@ import { MediaInput } from "./utils/media-input.js";
14
14
  import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
15
15
  import { ToolStream } from "./utils/tool-stream.js";
16
16
  const ADAPTER = "google-interactions";
17
+ const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator";
17
18
  export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
18
19
  // =============================================================================
19
20
  // Public Model Input
@@ -205,6 +206,7 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
205
206
  else
206
207
  steps.push({ type, content: [content] });
207
208
  };
209
+ let hasSignedStep = false;
208
210
  for (const part of message.content) {
209
211
  if (message.role === "tool") {
210
212
  if (part.type !== "tool-result")
@@ -227,21 +229,27 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
227
229
  continue;
228
230
  }
229
231
  if (message.role === "assistant" && part.type === "reasoning") {
232
+ const thoughtSignature = signature(part.providerMetadata, key);
230
233
  steps.push({
231
234
  type: "thought",
232
- signature: signature(part.providerMetadata, key),
235
+ signature: thoughtSignature,
233
236
  summary: part.text ? [{ type: "text", text: part.text }] : undefined,
234
237
  });
238
+ if (thoughtSignature !== undefined)
239
+ hasSignedStep = true;
235
240
  continue;
236
241
  }
237
242
  if (message.role === "assistant" && part.type === "tool-call") {
243
+ const toolSignature = signature(part.providerMetadata, key);
238
244
  steps.push({
239
245
  type: "function_call",
240
246
  id: part.id,
241
247
  name: part.name,
242
248
  arguments: part.input,
243
- signature: signature(part.providerMetadata, key),
249
+ signature: toolSignature ?? (!hasSignedStep ? SKIP_THOUGHT_SIGNATURE_VALIDATOR : undefined),
244
250
  });
251
+ if (toolSignature !== undefined)
252
+ hasSignedStep = true;
245
253
  continue;
246
254
  }
247
255
  return yield* ProviderShared.unsupportedContent(ADAPTER, message.role, message.role === "user" ? ["text", "media"] : ["text", "media", "reasoning", "tool-call"]);
@@ -176,7 +176,7 @@ const lowerToolCall = (part, normalizeID) => ({
176
176
  type: "function",
177
177
  function: { name: part.name, arguments: ProviderShared.encodeJson(part.input) },
178
178
  });
179
- const lowerAssistant = Effect.fnUntraced(function* (message, normalizeID, prefix) {
179
+ const lowerAssistant = Effect.fnUntraced(function* (message, normalizeID) {
180
180
  const structured = message.content.some((part) => part.type === "reasoning" && isMistralThinkingContent(part.providerMetadata?.mistral?.thinking));
181
181
  const content = [];
182
182
  const text = [];
@@ -193,10 +193,6 @@ const lowerAssistant = Effect.fnUntraced(function* (message, normalizeID, prefix
193
193
  const native = part.providerMetadata?.mistral?.thinking;
194
194
  if (structured && isMistralThinkingContent(native))
195
195
  content.push(native);
196
- else if (structured)
197
- content.push({ type: "text", text: part.text });
198
- else
199
- text.push(part.text);
200
196
  continue;
201
197
  }
202
198
  if (part.type === "tool-call") {
@@ -209,7 +205,6 @@ const lowerAssistant = Effect.fnUntraced(function* (message, normalizeID, prefix
209
205
  role: "assistant",
210
206
  content: structured ? content : text.join(""),
211
207
  ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
212
- ...(prefix ? { prefix: true } : {}),
213
208
  };
214
209
  });
215
210
  const lowerToolResults = Effect.fnUntraced(function* (message, normalizeID) {
@@ -273,16 +268,18 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
273
268
  if (message.role === "assistant") {
274
269
  const hasToolCalls = message.content.some((part) => part.type === "tool-call");
275
270
  const hasNativeThinking = message.content.some((part) => part.type === "reasoning" && isMistralThinkingContent(part.providerMetadata?.mistral?.thinking));
276
- const text = message.content
277
- .flatMap((part) => (part.type === "text" || part.type === "reasoning" ? [part.text] : []))
278
- .join("");
271
+ const text = message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("");
279
272
  if (!hasToolCalls && !hasNativeThinking && text.trim() === "")
280
273
  continue;
281
- messages.push(yield* lowerAssistant(message, normalizeID, !hasToolCalls && message === request.messages.at(-1)));
274
+ messages.push(yield* lowerAssistant(message, normalizeID));
282
275
  continue;
283
276
  }
284
277
  messages.push(...(yield* lowerToolResults(message, normalizeID)));
285
278
  }
279
+ const trailing = messages.at(-1);
280
+ if (trailing?.role === "assistant" && !trailing.tool_calls) {
281
+ messages[messages.length - 1] = { ...trailing, prefix: true };
282
+ }
286
283
  return messages;
287
284
  });
288
285
  const lowerTool = (tool) => ({
@@ -50,7 +50,7 @@ const fromRequest = Effect.fn("XAIResponses.fromRequest")(function* (request) {
50
50
  operation: "in-band-compaction",
51
51
  provider: request.model.provider,
52
52
  route: request.model.route.id,
53
- message: "xAI requires explicit compaction through LLMClient.compact; automatic context management is not supported",
53
+ message: "xAI requires explicit compaction through ai.compact; automatic context management is not supported",
54
54
  });
55
55
  const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Options))(request.providerOptions ?? {});
56
56
  const body = yield* OpenResponses.fromRequestWithAdapter(request, adapter);
@@ -29,6 +29,8 @@ const patterns = [
29
29
  // Hugging Face Text Generation Inference, e.g. Together
30
30
  /`inputs` tokens \+ `max_new_tokens` must be <= \d+/i,
31
31
  /context window exceeds limit/i,
32
+ // LiteLLM's ContextWindowExceededError
33
+ /context window exceeded/i,
32
34
  /exceeded model token limit/i,
33
35
  /context[_ ]length[_ ]exceeded/i,
34
36
  /context length is only \d+ tokens/i,
@@ -83,7 +83,6 @@ export const configure = (input = {}) => {
83
83
  });
84
84
  const messages = (modelID) => configuredMessages.model({
85
85
  id: modelID,
86
- compatibility: { requireSignature: false },
87
86
  });
88
87
  const media = MediaRoute.deployment(input, options.auth);
89
88
  const image = (modelID) => MetaImages.model({ ...media, id: modelID });
@@ -70,7 +70,10 @@ export const configure = (input = {}) => {
70
70
  endpoint: baseURL === undefined ? undefined : { baseURL },
71
71
  auth,
72
72
  };
73
- const messages = (modelID) => messagesRoute.with(defaults).model({ id: modelID });
73
+ const messages = (modelID) => messagesRoute.with(defaults).model({
74
+ id: modelID,
75
+ compatibility: { requireSignature: false },
76
+ });
74
77
  const chat = (modelID) => chatRoute.with(defaults).model({
75
78
  id: modelID,
76
79
  compatibility: { supportsStrictMode: false },
@@ -220,8 +220,6 @@ export declare const Route: {
220
220
  readonly make: typeof make;
221
221
  };
222
222
  export declare const LLMClient: {
223
- readonly canCompact: typeof canCompact;
224
- readonly compact: typeof compact;
225
223
  readonly Service: typeof LLMClientService;
226
224
  readonly layer: Layer.Layer<LLMClientService, never, RequestExecutor.RequestExecutorService>;
227
225
  readonly stream: typeof stream;
@@ -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,
@@ -313,8 +311,6 @@ export const layer = Layer.effect(Service, Effect.gen(function* () {
313
311
  }));
314
312
  export const Route = { make };
315
313
  export const LLMClient = {
316
- canCompact,
317
- compact,
318
314
  Service,
319
315
  layer,
320
316
  stream,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
- "version": "2.2.3",
3
+ "version": "2.2.5",
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.0.6",
523
- "@opencode/http-recorder": "2.2.3",
523
+ "@opencode/http-recorder": "2.2.5",
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": "2.2.3",
533
+ "@opencode/schema": "2.2.5",
534
534
  "aws4fetch": "1.0.20",
535
535
  "effect": "4.0.6",
536
536
  "google-auth-library": "10.5.0"