@opencode/ai 0.0.0-dev-434 → 0.0.0-dev-439

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 CHANGED
@@ -55,8 +55,9 @@ Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployme
55
55
  `stream` runs one model call; `loop` runs the model's tool calls and calls the model again until it stops calling
56
56
  tools. Events from every step arrive on one stream, with a `tool-result` after each tool runs. `until` is checked
57
57
  after each step that has tool calls, with every step's `LLMResponse`; returning `true` ends the loop without running
58
- them. `tool` takes a plain `async` execute; a throw or rejection goes back to the model as an error result, and
59
- `signal` aborts when the loop is interrupted.
58
+ them. Tools are an array, sent in the order given so the provider can reuse its cached prompt prefix. Each tool has a
59
+ `name`, and two tools with the same name fail the request. `tool` takes a plain `async` execute; a throw or rejection
60
+ goes back to the model as an error result, and `signal` aborts when the loop is interrupted.
60
61
  `tool` from `@opencode/ai/effect` takes the same options (including an optional `success` schema) with an Effect execute:
61
62
 
62
63
  ```ts
@@ -65,6 +66,7 @@ import { Schema } from "effect"
65
66
  import { ai, tool } from "@opencode/ai"
66
67
 
67
68
  const read_file = tool({
69
+ name: "read_file",
68
70
  description: "Read a UTF-8 file.",
69
71
  parameters: Schema.Struct({ path: Schema.String }),
70
72
  execute: ({ path }, { signal }) => readFile(path, { encoding: "utf8", signal }),
@@ -73,7 +75,7 @@ const read_file = tool({
73
75
  const events = ai.loop({
74
76
  model,
75
77
  prompt: "Summarize package.json.",
76
- tools: { read_file },
78
+ tools: [read_file],
77
79
  until: ({ steps }) => steps.length >= 8,
78
80
  })
79
81
  for await (const event of events) {
@@ -88,6 +90,7 @@ instead of JSON arguments: unconstrained `text`, or text matching a `regex` or `
88
90
 
89
91
  ```ts
90
92
  const run_code = tool({
93
+ name: "run_code",
91
94
  description: "Run JavaScript",
92
95
  parameters: Schema.Struct({ code: Schema.String }),
93
96
  freeform: { type: "lark", grammar: JS_GRAMMAR },
@@ -894,17 +897,17 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
894
897
  - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
895
898
  - **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
896
899
  - **`AIClient.layer` / `AIClient.layerWith(executor)`** — every modality client plus the request executor in one layer.
897
- - **`@opencode/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `compact`, `canCompact`) at the top level plus `image` and `decision` (plus `experimental.video`, `experimental.speech`, and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer?, clients? })` builds a client over a custom executor or test layers. The same `ai` from `@opencode/ai/effect` returns `Effect` and `Stream`.
900
+ - **`@opencode/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `compact`, `canCompact`) at the top level plus `image` and `decision` (plus `experimental.video`, `experimental.speech`, and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer? })` builds a client over a custom executor. The same `ai` from `@opencode/ai/effect` returns `Effect` and `Stream`.
898
901
  - **`@opencode/ai/experimental`** — APIs that may change without compatibility guarantees: `Video`, `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental).
899
902
 
900
903
  ## Experimental
901
904
 
902
905
  These APIs may change without compatibility guarantees. The Effect API is exported from `@opencode/ai/experimental`,
903
- the Promise client exposes it under `ai.experimental`, and test layers come from `@opencode/ai/experimental/testing`.
906
+ and the Promise client exposes it under `ai.experimental`.
904
907
 
905
908
  - **`Video`**, **`Speech`**, and **`Transcription`** — media generation and speech-to-text, with `VideoClient`,
906
909
  `SpeechClient`, and `TranscriptionClient` as their Effect services. Promise: `ai.experimental.video`, `.speech`, and
907
- `.transcription`. Testing: `TestVideo`, `TestSpeech`, and `TestTranscription`.
910
+ `.transcription`.
908
911
  - **`Extraction`** — typed values read out of text.
909
912
  - **`Realtime`** — `Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or
910
913
  a short-lived WebSocket URL and token.
@@ -1233,13 +1236,16 @@ For explicit compaction, script a `CompactionResponse` through `push`, `always`,
1233
1236
 
1234
1237
  For `compact(request, { mechanism: "trigger" })`, script a `CompactionCheckpointResponse` instead. It carries `checkpoint`, `responseID`, and optional `usage`. Endpoint and trigger calls reject each other's fixtures; both share the same queue, gates, lazy recording, and fallback controls.
1235
1238
 
1236
- `TestImage` and `TestDecision` (and `TestVideo`, `TestSpeech`, and `TestTranscription` from `@opencode/ai/experimental/testing`) follow the same pattern: `testLayer()` provides the modality's client and `Test`, with the same `push`, `always`, `serve`, `requests`, `wait`, and `gate` controls. Script an `ImageResponse` (or the modality's response) or an `AIError`. `stream` expands the response into its events, and `start` returns an already finished generation that `resume` accepts by token. Decision responses are returned as scripted, without checking the answers against the questions.
1239
+ Response helpers build common event arrays: `TestLLM.text(value, id)`, `textWithUsage(value, id, inputTokens)`,
1240
+ `toolCall(id, name, input)`, `stop(...events)`, `toolCalls(...events)`, and
1241
+ `complete({ reason, usage?, providerMetadata? }, ...events)`. `failAfter(error, ...events)` and `hangAfter(...events)`
1242
+ return streams that fail or never finish after the given events.
1237
1243
 
1238
- The Promise client accepts the same layers as `AI.make({ clients: TestImage.testLayer() })`; `ai.run(TestImage.Test.use(...))` reaches the controls.
1244
+ `compileRequest`, also from `@opencode/ai/testing`, compiles an `LLMRequest` through its route without sending it, so
1245
+ tests can assert the provider payload.
1239
1246
 
1240
- The published legacy `Service`, `layer`, `clientLayer`, and module-level controls remain available as adapters
1241
- over the same implementation, including the legacy live `requests` array. New tests should use `Test` and
1242
- `testLayer`.
1247
+ Other modalities and the Promise client have no test double. Test them over a custom executor layer, such as
1248
+ `AI.make({ layer })`, that answers the HTTP requests.
1243
1249
 
1244
1250
  ## Provider compaction
1245
1251
 
package/dist/effect.d.ts CHANGED
@@ -47,8 +47,8 @@ export { ImageClient } from "./image-client.js";
47
47
  export { Auth } from "./route/auth.js";
48
48
  export { ProviderPackage } from "./provider-package.js";
49
49
  export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
50
- export type { Interface as LLMClientShape, LLMClientService } from "./route/client.js";
51
- 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";
50
+ export type { LLMClientService } from "./route/client.js";
51
+ 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, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
52
52
  export type { GenerationOptionsFields, GenerationOptionsInput, LanguageModelInput, LanguageModelProviderOptions, ToolDefinitionInput, ToolNamespaceInput, ToolNamespaceEntryInput, ToolEntryInput, UsageInput, } from "./schema/index.js";
53
53
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js";
54
54
  export type { ImageModelOptions, ImageOptions, ImageRequestFor, ImageRequestInput, ImageResolution, ImageRoute, } from "./image.js";
@@ -61,7 +61,6 @@ export { Generation } from "./generation.js";
61
61
  export type { AwaitOptions as GenerationAwaitOptions, Event as GenerationEvent, Poll, Route as GenerationRoute, Snapshot as GenerationSnapshot, Status as GenerationStatus, } from "./generation.js";
62
62
  export { ToolFailure, emptyInputJsonSchema, toDefinitions, tool } from "./tool.js";
63
63
  export { ToolRuntime } from "./tool-runtime.js";
64
- export type { DispatchResult as ToolDispatchResult, ToolSettlement } from "./tool-runtime.js";
65
- export type { ExecutableTool, Tool, ToolExecute, ToolExecuteContext, ToolModelOutputInput, ToolOptions, Tools, ToolSchema, ToolToModelOutput, } from "./tool.js";
64
+ export type { ToolSettlement } from "./tool-runtime.js";
65
+ export type { ExecutableTool, Tool, ToolExecute, ToolExecuteContext, ToolModelOutputInput, ToolOptions, ToolSchema, ToolToModelOutput, } from "./tool.js";
66
66
  export type { LLM } from "./llm.js";
67
- export type { Definition as ProviderPackageDefinition, Settings as ProviderPackageSettings, } from "./provider-package.js";
package/dist/effect.js CHANGED
@@ -27,7 +27,7 @@ export { ImageClient } from "./image-client.js";
27
27
  export { Auth } from "./route/auth.js";
28
28
  export { ProviderPackage } from "./provider-package.js";
29
29
  export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
30
- 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";
30
+ 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, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
31
31
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js";
32
32
  export { DecisionClient } from "./decision-client.js";
33
33
  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";
@@ -26,8 +26,6 @@ export interface Poll {
26
26
  export interface AwaitOptions {
27
27
  readonly poll?: Poll;
28
28
  }
29
- export declare const DEFAULT_POLL_INTERVAL: Duration.Duration;
30
- export declare const DEFAULT_POLL_TIMEOUT: Duration.Duration;
31
29
  export declare const QueuedEvent: Schema.Struct<{
32
30
  readonly type: Schema.tag<"generation-queued">;
33
31
  readonly id: Schema.String;
@@ -1,8 +1,8 @@
1
1
  import { Clock, Duration, Effect, Schedule, Schema, Stream } from "effect";
2
2
  import { AIError, TimeoutError } from "./schema/errors.js";
3
3
  export const Status = Schema.Literals(["queued", "running", "completed", "failed", "cancelled", "expired"]);
4
- export const DEFAULT_POLL_INTERVAL = Duration.seconds(5);
5
- export const DEFAULT_POLL_TIMEOUT = Duration.minutes(10);
4
+ const DEFAULT_POLL_INTERVAL = Duration.seconds(5);
5
+ const DEFAULT_POLL_TIMEOUT = Duration.minutes(10);
6
6
  export const QueuedEvent = Schema.Struct({
7
7
  type: Schema.tag("generation-queued"),
8
8
  id: Schema.String,
package/dist/index.d.ts CHANGED
@@ -18,11 +18,9 @@ import { type VideoModel, type VideoRequest, type VideoRequestInput } from "./vi
18
18
  * transcription and decision clients over a request executor; every method runs the corresponding Effect API and rethrows
19
19
  * `AIError` unchanged. `file` and `write` load `node:fs/promises` on first use, so importing this module does not.
20
20
  */
21
- export interface Options<R = never> {
21
+ export interface Options {
22
22
  /** Executor layer; defaults to `RequestExecutor.fetchLayer`. Inject a recorder or `RequestExecutor.middleware(fn)` here. */
23
23
  readonly layer?: Layer.Layer<RequestExecutor.Service>;
24
- /** Replaces default clients, for example with `TestImage.testLayer()`; its other services are available to `run`. */
25
- readonly clients?: Layer.Layer<R>;
26
24
  }
27
25
  export interface RunOptions {
28
26
  readonly signal?: AbortSignal;
@@ -45,8 +43,8 @@ export type GenerationHandle<Response> = Snapshot & {
45
43
  readonly refresh: (options?: RunOptions) => Promise<GenerationHandle<Response>>;
46
44
  readonly cancel: (options?: RunOptions) => Promise<void>;
47
45
  };
48
- export declare const make: <R = never>(options?: Options<R>) => {
49
- run: <A, E>(effect: Effect.Effect<A, E, Services | R>, options?: RunOptions) => Promise<A>;
46
+ export declare const make: (options?: Options) => {
47
+ run: <A, E>(effect: Effect.Effect<A, E, Services>, options?: RunOptions) => Promise<A>;
50
48
  /** Decoded asset bytes, downloading `url` sources through the executor. */
51
49
  bytes: (asset: Media.Asset, options?: RunOptions) => Promise<Uint8Array<ArrayBufferLike>>;
52
50
  base64: (asset: Media.Asset, options?: RunOptions) => Promise<string>;
@@ -307,7 +305,7 @@ export declare const make: <R = never>(options?: Options<R>) => {
307
305
  };
308
306
  dispose: () => Promise<void>;
309
307
  };
310
- export type Client<R = never> = ReturnType<typeof make<R>>;
308
+ export type Client = ReturnType<typeof make>;
311
309
  /** `tool` from `@opencode/ai/effect`, with an `execute` that returns a value or a Promise and throws to fail. */
312
310
  export declare const tool: <Parameters extends ToolSchema<any> = typeof Schema.Unknown, Success extends ToolSchema<any> = typeof Schema.Unknown, Result extends Schema.Schema.Type<Success> | PromiseLike<Schema.Schema.Type<Success>> | NoExecute = NoExecute>(config: ToolOptions<Parameters, Success, (params: Schema.Schema.Type<Parameters>, context: Partial<ToolExecuteContext> & {
313
311
  signal: AbortSignal;
@@ -316,7 +314,7 @@ export declare const tool: <Parameters extends ToolSchema<any> = typeof Schema.U
316
314
  export declare const ai: Omit<Client, "dispose">;
317
315
  export * as AI from "./index.js";
318
316
  export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
319
- 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";
317
+ 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, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
320
318
  export type { GenerationOptionsFields, GenerationOptionsInput, LanguageModelInput, LanguageModelProviderOptions, ToolDefinitionInput, ToolNamespaceInput, ToolNamespaceEntryInput, ToolEntryInput, UsageInput, } from "./schema/index.js";
321
319
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js";
322
320
  export type { ImageModelOptions, ImageOptions, ImageRequestFor, ImageRequestInput, ImageResolution, ImageRoute, } from "./image.js";
@@ -324,5 +322,5 @@ export { ChoiceAnswer, ChoiceQuestion, ChoiceValue, DecisionAnswer, DecisionJson
324
322
  export type { AnswerFor, AnswersFor, DecisionInput, DecisionModelOptions, DecisionOptions, DecisionQuestions, DecisionRequestFor, DecisionRequestInput, DecisionResponseFor, DecisionModelRoute, } from "./decision.js";
325
323
  export { Media } from "./media.js";
326
324
  export type { AwaitOptions as GenerationAwaitOptions, Event as GenerationEvent, Poll, Route as GenerationRoute, Snapshot as GenerationSnapshot, Status as GenerationStatus, } from "./generation.js";
327
- export type { ExecutableTool, Tool, ToolExecute, ToolExecuteContext, ToolModelOutputInput, ToolOptions, Tools, ToolSchema, ToolToModelOutput, } from "./tool.js";
325
+ export type { ExecutableTool, Tool, ToolExecute, ToolExecuteContext, ToolModelOutputInput, ToolOptions, ToolSchema, ToolToModelOutput, } from "./tool.js";
328
326
  export type { LLM } from "./llm.js";
package/dist/index.js CHANGED
@@ -25,9 +25,7 @@ const abortEffect = (signal) => signal === undefined
25
25
  return Effect.sync(() => signal.removeEventListener("abort", onAbort));
26
26
  });
27
27
  export const make = (options = {}) => {
28
- const runtime = ManagedRuntime.make(Layer.merge(AIClient.layerWith(options.layer ?? RequestExecutor.fetchLayer),
29
- // `R` is only inferred from `clients`, so it is `never` whenever `clients` is omitted.
30
- (options.clients ?? Layer.empty)));
28
+ const runtime = ManagedRuntime.make(AIClient.layerWith(options.layer ?? RequestExecutor.fetchLayer));
31
29
  /** Run any package Effect (for example `ai.compact(...)` from `@opencode/ai/effect`) inside this runtime. */
32
30
  const run = (effect, options) => runtime.runPromise(Effect.raceFirst(effect, abortEffect(options?.signal)));
33
31
  const iterate = (stream, options) => Stream.toAsyncIterable(Stream.unwrap(runtime.contextEffect.pipe(Effect.map((context) => stream.pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context))))));
@@ -141,7 +139,7 @@ export const tool = (config) => {
141
139
  export const ai = make();
142
140
  export * as AI from "./index.js";
143
141
  export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
144
- 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";
142
+ 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, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
145
143
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js";
146
144
  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";
147
145
  export { Media } from "./media.js";
package/dist/llm.d.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import { Effect, JsonSchema, Schema, Stream } from "effect";
2
2
  import { Service, type StreamOptions } from "./route/client.js";
3
3
  import { GenerationOptions, HttpOptions, AIError, LLMEvent, LLMRequest, LLMResponse, Message, LanguageModel, SystemPart, type Finish, ToolChoice, type ContentPart, type LanguageModelProviderOptions, type ToolEntryInput } from "./schema/index.js";
4
- import { type ExecutableTool, type ToolSchema } from "./tool.js";
4
+ import { type ExecutableTool, type Tool, type ToolSchema } from "./tool.js";
5
5
  /** Input accepted by `LLM.request`, normalized into the canonical `LLMRequest` class. */
6
6
  export type RequestInput<SelectedLanguageModel extends LanguageModel = LanguageModel> = Omit<ConstructorParameters<typeof LLMRequest>[0], "model" | "system" | "messages" | "tools" | "toolChoice" | "generation" | "http" | "providerOptions"> & {
7
7
  readonly model: SelectedLanguageModel;
8
8
  readonly system?: string | SystemPart | ReadonlyArray<SystemPart>;
9
9
  readonly prompt?: string | ContentPart | ReadonlyArray<ContentPart>;
10
10
  readonly messages?: ReadonlyArray<Message | Message.Input>;
11
- readonly tools?: ReadonlyArray<ToolEntryInput>;
11
+ /** Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. */
12
+ readonly tools?: ReadonlyArray<Tool | ToolEntryInput>;
12
13
  readonly toolChoice?: ToolChoice.Input;
13
14
  readonly generation?: GenerationOptions.Input;
14
15
  readonly providerOptions?: NoInfer<LanguageModelProviderOptions<SelectedLanguageModel>>;
@@ -38,7 +39,7 @@ export declare function generate<const Model extends LanguageModel>(input: Reque
38
39
  export declare function stream<const Model extends LanguageModel, S extends OutputSchema>(input: ObjectInput<S, Model>, options?: StreamOptions): Stream.Stream<ObjectEvent<OutputType<S>>, AIError, Service>;
39
40
  export declare function stream<const Model extends LanguageModel>(input: RequestInput<Model> | LLMRequest, options?: StreamOptions): Stream.Stream<LLMEvent, AIError, Service>;
40
41
  export type LoopInput<SelectedLanguageModel extends LanguageModel = LanguageModel> = Omit<RequestInput<SelectedLanguageModel>, "tools"> & {
41
- readonly tools: Record<string, ExecutableTool>;
42
+ readonly tools: ReadonlyArray<ExecutableTool>;
42
43
  /** Called after each step that has tool calls; returning `true` ends the loop without running them. */
43
44
  readonly until?: (state: {
44
45
  readonly steps: ReadonlyArray<LLMResponse>;
package/dist/llm.js CHANGED
@@ -2,7 +2,7 @@ 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
4
  import { GenerationOptions, HttpOptions, InvalidProviderOutputError, AIError, LLMEvent, LLMRequest, LLMResponse, Message, LanguageModel, SystemPart, ToolChoice, ToolEntry, withPartial, } from "./schema/index.js";
5
- import { tool, toDefinitions } from "./tool.js";
5
+ import { tool } from "./tool.js";
6
6
  import { ToolRuntime } from "./tool-runtime.js";
7
7
  export function generate(input, options) {
8
8
  return prepare(input).pipe(Effect.flatMap(({ request, output }) => LLMClient.generate(request, options).pipe(Effect.flatMap((response) => output === undefined
@@ -63,7 +63,7 @@ export function loop(input, options) {
63
63
  return Stream.fromIterable(results.flatMap((result) => result.events)).pipe(Stream.concat(step(next, done, output)));
64
64
  }))));
65
65
  });
66
- return Stream.unwrap(prepare({ ...rest, tools: toDefinitions(tools) }).pipe(Effect.map(({ request, output }) => step(request, [], output))));
66
+ return Stream.unwrap(prepare({ ...rest, tools }).pipe(Effect.map(({ request, output }) => step(request, [], output))));
67
67
  }
68
68
  const OBJECT_TOOL = "generate_object";
69
69
  // `schema` adds a hidden tool whose input is the answer. With other tools the model only has to call some tool.
@@ -72,21 +72,24 @@ const prepare = (input) => {
72
72
  return Effect.succeed({ request: input, output: undefined });
73
73
  const { schema, ...rest } = input;
74
74
  return tryRequest(() => {
75
- const base = request(rest);
76
- if (schema === undefined)
77
- return { request: base, output: undefined };
78
75
  const description = "Return the structured result by calling this tool.";
79
- const output = Schema.isSchema(schema)
80
- ? tool({ description, parameters: schema })
81
- : tool({ description, jsonSchema: schema });
82
- const toolChoice = base.tools.length === 0 ? ToolChoice.named(OBJECT_TOOL) : new ToolChoice({ type: "required" });
83
- return {
84
- output,
85
- request: LLMRequest.update(base, {
86
- tools: [...base.tools, ...toDefinitions({ [OBJECT_TOOL]: output })],
87
- toolChoice,
88
- }),
89
- };
76
+ const output = schema === undefined
77
+ ? undefined
78
+ : Schema.isSchema(schema)
79
+ ? tool({ name: OBJECT_TOOL, description, parameters: schema })
80
+ : tool({ name: OBJECT_TOOL, description, jsonSchema: schema });
81
+ const tools = rest.tools ?? [];
82
+ const built = request(output === undefined
83
+ ? rest
84
+ : {
85
+ ...rest,
86
+ tools: [...tools, output],
87
+ toolChoice: tools.length === 0 ? ToolChoice.named(OBJECT_TOOL) : new ToolChoice({ type: "required" }),
88
+ });
89
+ const duplicate = built.tools.find((entry, index) => built.tools.findIndex((other) => other.name === entry.name) !== index);
90
+ if (duplicate)
91
+ throw new Error(`Duplicate tool name: ${duplicate.name}`);
92
+ return { request: built, output };
90
93
  });
91
94
  };
92
95
  const decodeObject = (output, response) => {
@@ -112,7 +115,7 @@ export const request = (input) => {
112
115
  ...rest,
113
116
  system: SystemPart.content(requestSystem),
114
117
  messages: [...(messages?.map(Message.make) ?? []), ...(prompt === undefined ? [] : [Message.user(prompt)])],
115
- tools: tools?.map(ToolEntry.make) ?? [],
118
+ tools: tools?.map((item) => ("_definition" in item ? item._definition : ToolEntry.make(item))) ?? [],
116
119
  toolChoice: requestToolChoice ? ToolChoice.make(requestToolChoice) : undefined,
117
120
  generation: requestGeneration === undefined ? undefined : GenerationOptions.make(requestGeneration),
118
121
  providerOptions: requestProviderOptions,
@@ -1,6 +1,5 @@
1
1
  import { AIError, type HttpContext, type HttpRateLimitDetails } from "./schema/index.js";
2
2
  export declare const isContextOverflow: (message: string) => boolean;
3
- export declare const isPayloadTooLarge: (message: string) => boolean;
4
3
  export declare const isContextOverflowFailure: (failure: unknown) => boolean;
5
4
  /**
6
5
  * Whether a failed call may succeed when sent again: rate limits, provider-side failures, transport failures that did
@@ -57,7 +57,7 @@ const exclusions = [
57
57
  ];
58
58
  export const isContextOverflow = (message) => !exclusions.some((pattern) => pattern.test(message)) &&
59
59
  (patterns.some((pattern) => pattern.test(message)) || /^4(?:00|13)\s*(status code)?\s*\(no body\)/i.test(message));
60
- export const isPayloadTooLarge = (message) => payloadPatterns.some((pattern) => pattern.test(message));
60
+ const isPayloadTooLarge = (message) => payloadPatterns.some((pattern) => pattern.test(message));
61
61
  export const isContextOverflowFailure = (failure) => failure instanceof AIError
62
62
  ? failure.reason._tag === "InvalidRequest" && failure.reason.classification === "context-overflow"
63
63
  : Schema.is(ProviderErrorEvent)(failure) && failure.classification === "context-overflow";
@@ -92,7 +92,6 @@ export const isRetryable = (error) => {
92
92
  case "ContentPolicy":
93
93
  case "InvalidRequest":
94
94
  case "UnsupportedOperation":
95
- case "NoRoute":
96
95
  case "Timeout":
97
96
  return false;
98
97
  default: {
@@ -1,5 +1,5 @@
1
1
  export { Route, LLMClient } from "./client.js";
2
- export type { Route as RouteShape, RouteLanguageModelInput, RouteRoutedLanguageModelInput, RouteDefaults, RouteDefaultsInput, AnyRoute, Interface as LLMClientShape, LLMClientService, StreamOptions, CompactMethod, CompactionOperations, CompactionRequest, CheckpointRequest, EndpointCompactOptions, TriggerCompactOptions, } from "./client.js";
2
+ export type { RouteLanguageModelInput, RouteRoutedLanguageModelInput, RouteDefaults, RouteDefaultsInput, AnyRoute, LLMClientService, StreamOptions, CompactMethod, CompactionOperations, CompactionRequest, CheckpointRequest, EndpointCompactOptions, TriggerCompactOptions, } from "./client.js";
3
3
  export * from "./executor.js";
4
4
  export { Auth } from "./auth.js";
5
5
  export { AuthOptions } from "./auth-options.js";
@@ -13,9 +13,7 @@ export * as Transport from "./transport/index.js";
13
13
  export { ProviderShared } from "../protocols/shared.js";
14
14
  export { classifyProviderFailure } from "../provider-error.js";
15
15
  export { mergeHttpOptions } from "../schema/index.js";
16
- export type { Definition as AuthShape, AuthInput, Credential, CredentialError } from "./auth.js";
16
+ export type { AuthInput, Credential, CredentialError } from "./auth.js";
17
17
  export type { ApiKeyMode, AuthOverride, ProviderAuthOption } from "./auth-options.js";
18
- export type { Definition as EndpointFn, EndpointInput } from "./endpoint.js";
19
- export type { Definition as FramingDef } from "./framing.js";
20
- export type { Protocol as ProtocolDef } from "./protocol.js";
21
- export type { ChannelCheckpoint, ChannelCreate, ChannelObservation, HttpHandler, HttpMiddleware, Transport as TransportDef, TransportExecuteOptions, TransportExecution, TransportRuntime, WebSocketConnection, WebSocketChannelDriver, WebSocketChannelExchange, WebSocketChannelExecution, WebSocketChannelExecutor, WebSocketConnector, WebSocketRequest, } from "./transport/index.js";
18
+ export type { EndpointInput } from "./endpoint.js";
19
+ export type { ChannelCheckpoint, ChannelCreate, ChannelObservation, HttpHandler, HttpMiddleware, TransportExecuteOptions, TransportExecution, TransportRuntime, WebSocketConnection, WebSocketChannelDriver, WebSocketChannelExchange, WebSocketChannelExecution, WebSocketChannelExecutor, WebSocketConnector, WebSocketRequest, } from "./transport/index.js";
@@ -57,17 +57,6 @@ declare const ProviderConfigurationError_base: Schema.Class<ProviderConfiguratio
57
57
  */
58
58
  export declare class ProviderConfigurationError extends ProviderConfigurationError_base {
59
59
  }
60
- declare const NoRouteError_base: Schema.Class<NoRouteError, Schema.TaggedStruct<"NoRoute", {
61
- readonly message: Schema.String;
62
- readonly body: Schema.optional<Schema.String>;
63
- readonly http: Schema.optional<typeof HttpContext>;
64
- readonly cause: Schema.optional<Schema.Defect>;
65
- readonly route: Schema.String;
66
- readonly provider: Schema.brand<Schema.String, "AI.ProviderID">;
67
- readonly model: Schema.brand<Schema.String, "AI.ModelID">;
68
- }>, import("effect/Cause").YieldableError>;
69
- export declare class NoRouteError extends NoRouteError_base {
70
- }
71
60
  declare const AuthenticationError_base: Schema.Class<AuthenticationError, Schema.TaggedStruct<"Authentication", {
72
61
  message: Schema.String;
73
62
  body: Schema.optional<Schema.String>;
@@ -159,13 +148,13 @@ declare const TimeoutError_base: Schema.Class<TimeoutError, Schema.TaggedStruct<
159
148
  /** A caller-supplied deadline elapsed, such as `Generation.await` polling past its `Poll.timeout`. */
160
149
  export declare class TimeoutError extends TimeoutError_base {
161
150
  }
162
- export declare const AIErrorReason: Schema.toTaggedUnion<"_tag", readonly [typeof InvalidRequestError, typeof UnsupportedOperationError, typeof NoRouteError, typeof AuthenticationError, typeof RateLimitError, typeof QuotaExceededError, typeof ContentPolicyError, typeof ProviderInternalError, typeof TransportError, typeof InvalidProviderOutputError, typeof UnknownProviderError, typeof TimeoutError]>;
151
+ export declare const AIErrorReason: Schema.toTaggedUnion<"_tag", readonly [typeof InvalidRequestError, typeof UnsupportedOperationError, typeof AuthenticationError, typeof RateLimitError, typeof QuotaExceededError, typeof ContentPolicyError, typeof ProviderInternalError, typeof TransportError, typeof InvalidProviderOutputError, typeof UnknownProviderError, typeof TimeoutError]>;
163
152
  export type AIErrorReason = Schema.Schema.Type<typeof AIErrorReason>;
164
153
  declare const AIError_base: Schema.Class<AIError, Schema.TaggedStruct<"AI.Error", {
165
- readonly reason: Schema.toTaggedUnion<"_tag", readonly [typeof InvalidRequestError, typeof UnsupportedOperationError, typeof NoRouteError, typeof AuthenticationError, typeof RateLimitError, typeof QuotaExceededError, typeof ContentPolicyError, typeof ProviderInternalError, typeof TransportError, typeof InvalidProviderOutputError, typeof UnknownProviderError, typeof TimeoutError]>;
154
+ readonly reason: Schema.toTaggedUnion<"_tag", readonly [typeof InvalidRequestError, typeof UnsupportedOperationError, typeof AuthenticationError, typeof RateLimitError, typeof QuotaExceededError, typeof ContentPolicyError, typeof ProviderInternalError, typeof TransportError, typeof InvalidProviderOutputError, typeof UnknownProviderError, typeof TimeoutError]>;
166
155
  }>, import("effect/Cause").YieldableError>;
167
156
  export declare class AIError extends AIError_base {
168
- readonly cause: AuthenticationError | ContentPolicyError | InvalidProviderOutputError | InvalidRequestError | NoRouteError | ProviderInternalError | QuotaExceededError | RateLimitError | TimeoutError | TransportError | UnknownProviderError | UnsupportedOperationError;
157
+ readonly cause: AuthenticationError | ContentPolicyError | InvalidProviderOutputError | InvalidRequestError | ProviderInternalError | QuotaExceededError | RateLimitError | TimeoutError | TransportError | UnknownProviderError | UnsupportedOperationError;
169
158
  /** Output that arrived before `generate` (including its `schema` decode) or a `loop` step failed. Not in the schema, so encoding omits it. */
170
159
  readonly partial?: LLMResponse;
171
160
  constructor(props: Pick<AIError, "reason" | "partial">);
@@ -1,7 +1,7 @@
1
1
  import { Schema } from "effect";
2
2
  import { NonNegativeInt } from "@opencode/schema";
3
3
  import { Tool } from "@opencode/schema/tool";
4
- import { ModelID, ProviderID, RouteID } from "./ids.js";
4
+ import { ProviderID, RouteID } from "./ids.js";
5
5
  export const ProviderFailureClassification = Schema.Literals(["context-overflow", "payload-too-large"]);
6
6
  export class HttpContext extends Schema.Class("AI.HttpContext")({
7
7
  url: Schema.String,
@@ -53,13 +53,6 @@ export class ProviderConfigurationError extends Schema.TaggedError("AI.Error.Pro
53
53
  message: Schema.String,
54
54
  }) {
55
55
  }
56
- export class NoRouteError extends Schema.TaggedError("AI.Error.NoRoute")("NoRoute", {
57
- ...ReasonFields,
58
- route: RouteID,
59
- provider: ProviderID,
60
- model: ModelID,
61
- }) {
62
- }
63
56
  export class AuthenticationError extends Schema.TaggedError("AI.Error.Authentication")("Authentication", ReasonFields) {
64
57
  }
65
58
  export class RateLimitError extends Schema.TaggedError("AI.Error.RateLimit")("RateLimit", {
@@ -110,7 +103,6 @@ export class TimeoutError extends Schema.TaggedError("AI.Error.Timeout")("Timeou
110
103
  export const AIErrorReason = Schema.Union([
111
104
  InvalidRequestError,
112
105
  UnsupportedOperationError,
113
- NoRouteError,
114
106
  AuthenticationError,
115
107
  RateLimitError,
116
108
  QuotaExceededError,
package/dist/testing.d.ts CHANGED
@@ -1,21 +1,37 @@
1
1
  export * as TestLLM from "./testing.js";
2
2
  export { compileRequest } from "./route/client.js";
3
- export { TestDecision } from "./testing/decision.js";
4
- export { TestImage } from "./testing/image.js";
5
3
  import { LLMClient } from "./route/client.js";
6
4
  import { LLMEvent, CompactionResponse, CompactionCheckpointResponse, type FinishReasonDetails, type AIError, type LLMRequest, type ProviderMetadata, type UsageInput } from "./schema/index.js";
7
- import { Context, Layer, Stream } from "effect";
8
- import { TestScript } from "./testing/script.js";
5
+ import { Context, Effect, Layer, Scope, Stream } from "effect";
9
6
  export type Response = readonly LLMEvent[] | Stream.Stream<LLMEvent, AIError> | CompactionResponse | CompactionCheckpointResponse;
10
- export type Gate = TestScript.Gate;
7
+ export type Gate = Readonly<{
8
+ started: Effect.Effect<void>;
9
+ release: Effect.Effect<void>;
10
+ }>;
11
11
  type ClientInterface = Context.Service.Shape<typeof LLMClient.Service>;
12
12
  export type Responder = (request: LLMRequest) => Response;
13
- export interface TestInterface extends ClientInterface, TestScript.Controls<LLMRequest, Response> {
13
+ interface Controls {
14
+ /** Returns a snapshot of requests observed at execution time. */
15
+ readonly requests: () => Effect.Effect<readonly LLMRequest[]>;
16
+ readonly push: (...responses: readonly Response[]) => Effect.Effect<void>;
17
+ /** Replaces the fallback without changing queued responses. */
18
+ readonly always: (response: Response) => Effect.Effect<void>;
19
+ /** Answers requests after the one-shot queue is exhausted; receives the original request. */
20
+ readonly serve: (responder: Responder) => Effect.Effect<void>;
21
+ /** Waits for request arrivals, not output or completion. */
22
+ readonly wait: (count: number) => Effect.Effect<void>;
23
+ readonly gate: () => Effect.Effect<Gate, never, Scope.Scope>;
24
+ }
25
+ export interface TestInterface extends ClientInterface, Controls {
14
26
  }
15
27
  declare const Test_base: Context.ServiceClass<Test, "@opencode/ai/TestLLM/Test", TestInterface>;
16
28
  export declare class Test extends Test_base {
17
29
  }
18
- export type LayerOptions = TestScript.Options<LLMRequest, Response>;
30
+ export interface LayerOptions {
31
+ readonly transformRequest?: (request: LLMRequest) => LLMRequest;
32
+ /** Used after the one-shot response queue is exhausted. Omit to defect on unexpected requests. */
33
+ readonly fallback?: Response;
34
+ }
19
35
  export declare const complete: (options: {
20
36
  readonly reason: FinishReasonDetails;
21
37
  readonly usage?: UsageInput;
package/dist/testing.js CHANGED
@@ -1,11 +1,8 @@
1
1
  export * as TestLLM from "./testing.js";
2
2
  export { compileRequest } from "./route/client.js";
3
- export { TestDecision } from "./testing/decision.js";
4
- export { TestImage } from "./testing/image.js";
5
3
  import { LLMClient, generateWith, } from "./route/client.js";
6
4
  import { LLMEvent, CompactionResponse, CompactionCheckpointResponse, } from "./schema/index.js";
7
- import { Context, Effect, Layer, Stream } from "effect";
8
- import { TestScript } from "./testing/script.js";
5
+ import { Context, Deferred, Effect, Latch, Layer, Queue, Scope, Stream } from "effect";
9
6
  export class Test extends Context.Service()("@opencode/ai/TestLLM/Test") {
10
7
  }
11
8
  export const complete = (options, ...events) => [
@@ -32,7 +29,7 @@ export const toolCall = (id, name, input) => toolCalls(LLMEvent.toolCall({ id, n
32
29
  export const failAfter = (error, ...events) => Stream.fromIterable(events).pipe(Stream.concat(Stream.fail(error)));
33
30
  export const hangAfter = (...events) => Stream.concat(Stream.fromIterable(events), Stream.never);
34
31
  const make = (options) => Effect.sync(() => {
35
- const script = TestScript.make("TestLLM", options);
32
+ const script = makeScript(options);
36
33
  const stream = (request) => Stream.unwrap(script.take(request).pipe(Effect.map((response) => {
37
34
  if (response instanceof CompactionResponse || response instanceof CompactionCheckpointResponse)
38
35
  return Stream.die("TestLLM generation requires an event response");
@@ -58,3 +55,61 @@ const make = (options) => Effect.sync(() => {
58
55
  });
59
56
  /** Provides one shared implementation under the normal client and test-control tags. */
60
57
  export const testLayer = (options = {}) => Layer.effectContext(Effect.map(make(options), (test) => Context.make(LLMClient.Service, test).pipe(Context.add(Test, test))));
58
+ /** The response queue, fallback, request log, and gates behind the test controls. */
59
+ const makeScript = (options) => {
60
+ const requests = [];
61
+ const responses = [];
62
+ let started = Deferred.makeUnsafe();
63
+ const initial = options.fallback;
64
+ let fallback = initial === undefined ? undefined : () => initial;
65
+ let activeGate;
66
+ const wait = (count) => Effect.suspend(() => requests.length >= count ? Effect.void : Deferred.await(started).pipe(Effect.andThen(wait(count))));
67
+ const take = (request) => Effect.suspend(() => {
68
+ const count = requests.push(options.transformRequest?.(request) ?? request);
69
+ const waiting = started;
70
+ started = Deferred.makeUnsafe();
71
+ const gate = activeGate;
72
+ try {
73
+ const response = responses.shift() ?? fallback?.(request);
74
+ if (!response)
75
+ return Effect.die(new Error(`TestLLM has no response for request ${count}`));
76
+ if (!gate)
77
+ return Effect.succeed(response);
78
+ return Queue.offer(gate.started, undefined).pipe(Effect.andThen(gate.release.await), Effect.as(response));
79
+ }
80
+ finally {
81
+ // Waiters can resume synchronously; assign the reply and gate before notifying them.
82
+ Deferred.doneUnsafe(waiting, Effect.void);
83
+ }
84
+ });
85
+ const controls = {
86
+ requests: () => Effect.sync(() => [...requests]),
87
+ push: (...input) => Effect.sync(() => {
88
+ responses.push(...input);
89
+ }),
90
+ always: (response) => Effect.sync(() => {
91
+ fallback = () => response;
92
+ }),
93
+ serve: (responder) => Effect.sync(() => {
94
+ fallback = responder;
95
+ }),
96
+ wait,
97
+ gate: () => Effect.gen(function* () {
98
+ const gate = {
99
+ started: yield* Effect.acquireRelease(Queue.unbounded(), Queue.shutdown),
100
+ release: yield* Latch.make(),
101
+ };
102
+ activeGate = gate;
103
+ const release = Effect.sync(() => {
104
+ if (activeGate === gate)
105
+ activeGate = undefined;
106
+ }).pipe(Effect.andThen(gate.release.open), Effect.asVoid);
107
+ yield* Effect.addFinalizer(() => release);
108
+ return {
109
+ started: Queue.take(gate.started),
110
+ release,
111
+ };
112
+ }),
113
+ };
114
+ return { take, controls };
115
+ };
@@ -1,6 +1,6 @@
1
1
  import { Effect } from "effect";
2
2
  import { LLMEvent, type ToolCallPart, type ToolOutput as ToolOutputType, type ToolResultValue as ToolResultValueType } from "./schema/index.js";
3
- import { type Tools } from "./tool.js";
3
+ import { type Tool } from "./tool.js";
4
4
  export interface ToolSettlement {
5
5
  readonly result: ToolResultValueType;
6
6
  readonly output?: ToolOutputType;
@@ -9,7 +9,7 @@ export interface DispatchResult extends ToolSettlement {
9
9
  readonly events: ReadonlyArray<LLMEvent>;
10
10
  }
11
11
  /** Execute one canonical tool call without owning provider IO or continuation. */
12
- export declare const dispatch: (tools: Tools, call: ToolCallPart) => Effect.Effect<DispatchResult>;
12
+ export declare const dispatch: (tools: ReadonlyArray<Tool>, call: ToolCallPart) => Effect.Effect<DispatchResult>;
13
13
  export declare const ToolRuntime: {
14
14
  readonly dispatch: typeof dispatch;
15
15
  };
@@ -4,7 +4,7 @@ import {} from "./tool.js";
4
4
  /** Execute one canonical tool call without owning provider IO or continuation. */
5
5
  export const dispatch = (tools, call) => {
6
6
  const name = call.namespace === undefined ? call.name : `${call.namespace}.${call.name}`;
7
- const tool = tools[name];
7
+ const tool = tools.find((item) => item.name === name);
8
8
  if (!tool)
9
9
  return Effect.succeed(result(call, {
10
10
  type: "error",
package/dist/tool.d.ts CHANGED
@@ -38,6 +38,8 @@ export type FreeformOption<Parameters extends ToolSchema<any>> = unknown extends
38
38
  * `ToolDefinition` so callers do not rebuild them per invocation.
39
39
  */
40
40
  export interface Tool<Parameters extends ToolSchema<any> = any, Success extends ToolSchema<any> = any> {
41
+ /** The tool name the model sees and calls. */
42
+ readonly name: string;
41
43
  readonly description: string;
42
44
  readonly parameters: Parameters;
43
45
  readonly success: Success;
@@ -66,6 +68,7 @@ export type ExecutableTool<Parameters extends ToolSchema<any> = any, Success ext
66
68
  * a tool the model can call without running it here.
67
69
  */
68
70
  export type ToolOptions<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>, Execute = ToolExecute<Parameters, Success>> = {
71
+ readonly name: string;
69
72
  readonly description: string;
70
73
  readonly freeform?: FreeformOption<Parameters>;
71
74
  readonly execute?: Execute;
@@ -83,6 +86,7 @@ export type ToolOptions<Parameters extends ToolSchema<any>, Success extends Tool
83
86
  *
84
87
  * ```ts
85
88
  * tool({
89
+ * name: "weather",
86
90
  * description: "Get current weather",
87
91
  * parameters: Schema.Struct({ city: Schema.String }),
88
92
  * success: Schema.Struct({ temperature: Schema.Number }),
@@ -98,19 +102,8 @@ export type NoExecute = {
98
102
  };
99
103
  /** @internal Builds a tool for both clients from its options and an Effect `execute`. */
100
104
  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>;
101
- /**
102
- * A record of named tools. The record key becomes the tool name on the wire.
103
- */
104
- export type Tools = Record<string, Tool>;
105
- /**
106
- * Convert a tools record into the `ToolDefinition[]` shape that
107
- * `LLMRequest.tools` expects.
108
- *
109
- * Tool names come from the record keys, so the per-tool cached
110
- * `_definition` is rebuilt with the correct name here. The JSON Schema body
111
- * is reused.
112
- */
113
- export declare const toDefinitions: (tools: Tools) => ReadonlyArray<ToolDefinitionClass>;
105
+ /** The `ToolDefinition[]` that `LLMRequest.tools` expects, in array order. */
106
+ export declare const toDefinitions: (tools: ReadonlyArray<Tool>) => ReadonlyArray<ToolDefinitionClass>;
114
107
  /**
115
108
  * Describes a no-argument Effect tool input as an empty object, or returns
116
109
  * `undefined` when the input takes arguments.
package/dist/tool.js CHANGED
@@ -6,6 +6,7 @@ import { isRecord } from "./utils/record.js";
6
6
  *
7
7
  * ```ts
8
8
  * tool({
9
+ * name: "weather",
9
10
  * description: "Get current weather",
10
11
  * parameters: Schema.Struct({ city: Schema.String }),
11
12
  * success: Schema.Struct({ temperature: Schema.Number }),
@@ -16,6 +17,7 @@ import { isRecord } from "./utils/record.js";
16
17
  export const tool = (config) => build(config, config.execute);
17
18
  export function build(config, execute) {
18
19
  const shared = {
20
+ name: config.name,
19
21
  description: config.description,
20
22
  execute,
21
23
  toModelOutput: config.toModelOutput,
@@ -31,7 +33,7 @@ export function build(config, execute) {
31
33
  _encode: Effect.succeed,
32
34
  _legacyResult: config.toModelOutput === undefined && config.toStructuredOutput === undefined,
33
35
  _definition: definition({
34
- name: "",
36
+ name: config.name,
35
37
  description: config.description,
36
38
  inputSchema: config.jsonSchema,
37
39
  outputSchema: config.outputSchema,
@@ -46,7 +48,7 @@ export function build(config, execute) {
46
48
  _encode: config.success ? Schema.encodeEffect(config.success) : (value) => Effect.succeed(value ?? null),
47
49
  _legacyResult: false,
48
50
  _definition: definition({
49
- name: "",
51
+ name: config.name,
50
52
  description: config.description,
51
53
  inputSchema: emptyInputJsonSchema(config.parameters) ?? toJsonSchema(config.parameters),
52
54
  outputSchema: config.success && toJsonSchema(config.success),
@@ -54,21 +56,8 @@ export function build(config, execute) {
54
56
  }),
55
57
  };
56
58
  }
57
- /**
58
- * Convert a tools record into the `ToolDefinition[]` shape that
59
- * `LLMRequest.tools` expects.
60
- *
61
- * Tool names come from the record keys, so the per-tool cached
62
- * `_definition` is rebuilt with the correct name here. The JSON Schema body
63
- * is reused.
64
- */
65
- export const toDefinitions = (tools) => Object.entries(tools).map(([name, item]) => new ToolDefinition({
66
- name,
67
- description: item._definition.description,
68
- inputSchema: item._definition.inputSchema,
69
- outputSchema: item._definition.outputSchema,
70
- freeform: item._definition.freeform,
71
- }));
59
+ /** The `ToolDefinition[]` that `LLMRequest.tools` expects, in array order. */
60
+ export const toDefinitions = (tools) => tools.map((item) => item._definition);
72
61
  /**
73
62
  * Describes a no-argument Effect tool input as an empty object, or returns
74
63
  * `undefined` when the input takes arguments.
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-434",
3
+ "version": "0.0.0-dev-439",
4
4
  "name": "@opencode/ai",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,10 +32,6 @@
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
- },
39
35
  "./route": {
40
36
  "import": "./dist/route.js",
41
37
  "types": "./dist/route.d.ts"
@@ -520,7 +516,7 @@
520
516
  "devDependencies": {
521
517
  "@clack/prompts": "1.0.0-alpha.1",
522
518
  "@effect/platform-node": "4.1.0",
523
- "@opencode/http-recorder": "0.0.0-dev-434",
519
+ "@opencode/http-recorder": "0.0.0-dev-439",
524
520
  "@tsconfig/bun": "1.0.9",
525
521
  "@types/bun": "1.4.3",
526
522
  "@typescript/native": "npm:typescript@7.1.0-beta",
@@ -530,7 +526,7 @@
530
526
  "@aws-sdk/credential-providers": "3.1057.0",
531
527
  "@smithy/eventstream-codec": "4.2.14",
532
528
  "@smithy/util-utf8": "4.2.2",
533
- "@opencode/schema": "0.0.0-dev-434",
529
+ "@opencode/schema": "0.0.0-dev-439",
534
530
  "aws4fetch": "1.0.20",
535
531
  "effect": "4.1.0",
536
532
  "google-auth-library": "10.5.0"
@@ -1,3 +0,0 @@
1
- export { TestSpeech } from "../testing/speech.js";
2
- export { TestTranscription } from "../testing/transcription.js";
3
- export { TestVideo } from "../testing/video.js";
@@ -1,3 +0,0 @@
1
- export { TestSpeech } from "../testing/speech.js";
2
- export { TestTranscription } from "../testing/transcription.js";
3
- export { TestVideo } from "../testing/video.js";
@@ -1,16 +0,0 @@
1
- import { Context, Layer } from "effect";
2
- import { type Interface } from "../decision-client.js";
3
- import type { DecisionRequestFor, DecisionResponse } from "../decision.js";
4
- import { AIError } from "../schema/index.js";
5
- import { TestScript } from "./script.js";
6
- /** Returned as scripted, without checking its answers against the request's questions. */
7
- export type Response = DecisionResponse | AIError;
8
- export interface TestInterface extends Interface, TestScript.Controls<DecisionRequestFor, Response> {
9
- }
10
- declare const Test_base: Context.ServiceClass<Test, "@opencode/ai/TestDecision/Test", TestInterface>;
11
- export declare class Test extends Test_base {
12
- }
13
- export type LayerOptions = TestScript.Options<DecisionRequestFor, Response>;
14
- /** Provides one shared implementation under `DecisionClient.Service` and `TestDecision.Test`. */
15
- export declare const testLayer: (options?: LayerOptions) => Layer.Layer<import("../decision-client.js").Service | Test, never, never>;
16
- export * as TestDecision from "./decision.js";
@@ -1,20 +0,0 @@
1
- import { Context, Effect, Layer } from "effect";
2
- import { DecisionClient } from "../decision-client.js";
3
- import { AIError } from "../schema/index.js";
4
- import { TestScript } from "./script.js";
5
- export class Test extends Context.Service()("@opencode/ai/TestDecision/Test") {
6
- }
7
- /** Provides one shared implementation under `DecisionClient.Service` and `TestDecision.Test`. */
8
- export const testLayer = (options = {}) => Layer.effectContext(Effect.sync(() => {
9
- const script = TestScript.make("TestDecision", options);
10
- const client = Test.of({
11
- ...script.controls,
12
- generate: (request) => script
13
- .take(request)
14
- .pipe(Effect.flatMap((response) => response instanceof AIError
15
- ? Effect.fail(response)
16
- : Effect.succeed(response))),
17
- });
18
- return Context.make(DecisionClient.Service, client).pipe(Context.add(Test, client));
19
- }));
20
- export * as TestDecision from "./decision.js";
@@ -1,14 +0,0 @@
1
- import { Context } from "effect";
2
- import type { ImageEvent, ImageRequestFor, ImageResponse } from "../image.js";
3
- import { TestMedia } from "./media.js";
4
- import type { TestScript } from "./script.js";
5
- export type Response = TestMedia.Response<ImageResponse>;
6
- export interface TestInterface extends TestMedia.TestInterface<ImageRequestFor, ImageEvent, ImageResponse> {
7
- }
8
- declare const Test_base: Context.ServiceClass<Test, "@opencode/ai/TestImage/Test", TestInterface>;
9
- export declare class Test extends Test_base {
10
- }
11
- export type LayerOptions = TestScript.Options<ImageRequestFor, Response>;
12
- /** Provides one shared implementation under `ImageClient.Service` and `TestImage.Test`. */
13
- export declare const testLayer: (options?: LayerOptions) => import("effect/Layer").Layer<import("../image-client.js").ImageClientService | Test, never, never>;
14
- export * as TestImage from "./image.js";
@@ -1,12 +0,0 @@
1
- import { Context } from "effect";
2
- import { ImageClient } from "../image-client.js";
3
- import { TestMedia } from "./media.js";
4
- export class Test extends Context.Service()("@opencode/ai/TestImage/Test") {
5
- }
6
- /** Provides one shared implementation under `ImageClient.Service` and `TestImage.Test`. */
7
- export const testLayer = (options = {}) => TestMedia.testLayer(ImageClient.Service, Test, {
8
- name: "TestImage",
9
- responseEvents: ImageClient.responseEvents,
10
- options,
11
- });
12
- export * as TestImage from "./image.js";
@@ -1,18 +0,0 @@
1
- import { Context, Layer } from "effect";
2
- import type { MediaClient } from "../media-client.js";
3
- import { AIError } from "../schema/index.js";
4
- import { TestScript } from "./script.js";
5
- /** A scripted reply: the response every operation returns, or the error it fails with. */
6
- export type Response<Value> = Value | AIError;
7
- export interface TestInterface<Req extends MediaClient.RoutedRequest<Req, Event, Value>, Event, Value> extends MediaClient.Interface<Req, Event, Value>, TestScript.Controls<Req, Response<Value>> {
8
- }
9
- /**
10
- * Builds one media test client. `stream` expands the response like an inline route, and `start` returns an already
11
- * finished generation whose token `resume` accepts.
12
- */
13
- export declare const testLayer: <Self, Test, Req extends MediaClient.RoutedRequest<Req, Event, Value>, Event, Value>(service: Context.Service<Self, MediaClient.Interface<Req, Event, Value>>, test: Context.Service<Test, TestInterface<Req, Event, Value>>, input: {
14
- readonly name: string;
15
- readonly responseEvents: (response: Value) => ReadonlyArray<Event>;
16
- readonly options: TestScript.Options<Req, Response<Value>>;
17
- }) => Layer.Layer<Self | Test, never, never>;
18
- export * as TestMedia from "./media.js";
@@ -1,36 +0,0 @@
1
- import { Context, Effect, Layer, Stream } from "effect";
2
- import { Generation } from "../generation.js";
3
- import { AIError } from "../schema/index.js";
4
- import { TestScript } from "./script.js";
5
- /**
6
- * Builds one media test client. `stream` expands the response like an inline route, and `start` returns an already
7
- * finished generation whose token `resume` accepts.
8
- */
9
- export const testLayer = (service, test, input) => Layer.effectContext(Effect.sync(() => {
10
- const script = TestScript.make(input.name, input.options);
11
- const generations = new Map();
12
- const result = (response) => response instanceof AIError ? Effect.fail(response) : Effect.succeed(response);
13
- const completed = (id, response) => {
14
- const snapshot = { id, status: response instanceof AIError ? "failed" : "completed" };
15
- return new Generation({ status: Effect.succeed(snapshot), result: result(response) }, id, snapshot);
16
- };
17
- const generate = (request) => script.take(request).pipe(Effect.flatMap(result));
18
- const client = test.of({
19
- ...script.controls,
20
- generate,
21
- stream: (request) => Stream.fromIterableEffect(Effect.map(generate(request), input.responseEvents)),
22
- start: (request) => script.take(request).pipe(Effect.map((response) => {
23
- const id = `${input.name}-${generations.size + 1}`;
24
- generations.set(id, response);
25
- return completed(id, response);
26
- })),
27
- resume: (_model, token) => {
28
- const response = typeof token === "string" ? generations.get(token) : undefined;
29
- if (response === undefined)
30
- return Effect.die(new Error(`${input.name} has no generation ${String(token)}`));
31
- return Effect.succeed(completed(String(token), response));
32
- },
33
- });
34
- return Context.make(service, client).pipe(Context.add(test, client));
35
- }));
36
- export * as TestMedia from "./media.js";
@@ -1,28 +0,0 @@
1
- import { Effect, Scope } from "effect";
2
- export type Gate = Readonly<{
3
- started: Effect.Effect<void>;
4
- release: Effect.Effect<void>;
5
- }>;
6
- export interface Controls<Request, Response> {
7
- /** Returns a snapshot of requests observed at execution time. */
8
- readonly requests: () => Effect.Effect<readonly Request[]>;
9
- readonly push: (...responses: readonly Response[]) => Effect.Effect<void>;
10
- /** Replaces the fallback without changing queued responses. */
11
- readonly always: (response: Response) => Effect.Effect<void>;
12
- /** Answers requests after the one-shot queue is exhausted; receives the original request. */
13
- readonly serve: (responder: (request: Request) => Response) => Effect.Effect<void>;
14
- /** Waits for request arrivals, not output or completion. */
15
- readonly wait: (count: number) => Effect.Effect<void>;
16
- readonly gate: () => Effect.Effect<Gate, never, Scope.Scope>;
17
- }
18
- export interface Options<Request, Response> {
19
- readonly transformRequest?: (request: Request) => Request;
20
- /** Used after the one-shot response queue is exhausted. Omit to defect on unexpected requests. */
21
- readonly fallback?: Response;
22
- }
23
- /** The response queue, fallback, request log, and gates shared by every test client. */
24
- export declare const make: <Request, Response>(name: string, options: Options<Request, Response>) => {
25
- take: (request: Request) => Effect.Effect<NonNullable<Response>, never, never>;
26
- controls: Controls<Request, Response>;
27
- };
28
- export * as TestScript from "./script.js";
@@ -1,60 +0,0 @@
1
- import { Deferred, Effect, Latch, Queue, Scope } from "effect";
2
- /** The response queue, fallback, request log, and gates shared by every test client. */
3
- export const make = (name, options) => {
4
- const requests = [];
5
- const responses = [];
6
- let started = Deferred.makeUnsafe();
7
- const initial = options.fallback;
8
- let fallback = initial === undefined ? undefined : () => initial;
9
- let activeGate;
10
- const wait = (count) => Effect.suspend(() => requests.length >= count ? Effect.void : Deferred.await(started).pipe(Effect.andThen(wait(count))));
11
- const take = (request) => Effect.suspend(() => {
12
- const count = requests.push(options.transformRequest?.(request) ?? request);
13
- const waiting = started;
14
- started = Deferred.makeUnsafe();
15
- const gate = activeGate;
16
- try {
17
- const response = responses.shift() ?? fallback?.(request);
18
- if (!response)
19
- return Effect.die(new Error(`${name} has no response for request ${count}`));
20
- if (!gate)
21
- return Effect.succeed(response);
22
- return Queue.offer(gate.started, undefined).pipe(Effect.andThen(gate.release.await), Effect.as(response));
23
- }
24
- finally {
25
- // Waiters can resume synchronously; assign the reply and gate before notifying them.
26
- Deferred.doneUnsafe(waiting, Effect.void);
27
- }
28
- });
29
- const controls = {
30
- requests: () => Effect.sync(() => [...requests]),
31
- push: (...input) => Effect.sync(() => {
32
- responses.push(...input);
33
- }),
34
- always: (response) => Effect.sync(() => {
35
- fallback = () => response;
36
- }),
37
- serve: (responder) => Effect.sync(() => {
38
- fallback = responder;
39
- }),
40
- wait,
41
- gate: () => Effect.gen(function* () {
42
- const gate = {
43
- started: yield* Effect.acquireRelease(Queue.unbounded(), Queue.shutdown),
44
- release: yield* Latch.make(),
45
- };
46
- activeGate = gate;
47
- const release = Effect.sync(() => {
48
- if (activeGate === gate)
49
- activeGate = undefined;
50
- }).pipe(Effect.andThen(gate.release.open), Effect.asVoid);
51
- yield* Effect.addFinalizer(() => release);
52
- return {
53
- started: Queue.take(gate.started),
54
- release,
55
- };
56
- }),
57
- };
58
- return { take, controls };
59
- };
60
- export * as TestScript from "./script.js";
@@ -1,14 +0,0 @@
1
- import { Context } from "effect";
2
- import type { SpeechEvent, SpeechRequestFor, SpeechResponse } from "../speech.js";
3
- import { TestMedia } from "./media.js";
4
- import type { TestScript } from "./script.js";
5
- export type Response = TestMedia.Response<SpeechResponse>;
6
- export interface TestInterface extends TestMedia.TestInterface<SpeechRequestFor, SpeechEvent, SpeechResponse> {
7
- }
8
- declare const Test_base: Context.ServiceClass<Test, "@opencode/ai/TestSpeech/Test", TestInterface>;
9
- export declare class Test extends Test_base {
10
- }
11
- export type LayerOptions = TestScript.Options<SpeechRequestFor, Response>;
12
- /** Provides one shared implementation under `SpeechClient.Service` and `TestSpeech.Test`. */
13
- export declare const testLayer: (options?: LayerOptions) => import("effect/Layer").Layer<import("../speech-client.js").SpeechClientService | Test, never, never>;
14
- export * as TestSpeech from "./speech.js";
@@ -1,12 +0,0 @@
1
- import { Context } from "effect";
2
- import { SpeechClient } from "../speech-client.js";
3
- import { TestMedia } from "./media.js";
4
- export class Test extends Context.Service()("@opencode/ai/TestSpeech/Test") {
5
- }
6
- /** Provides one shared implementation under `SpeechClient.Service` and `TestSpeech.Test`. */
7
- export const testLayer = (options = {}) => TestMedia.testLayer(SpeechClient.Service, Test, {
8
- name: "TestSpeech",
9
- responseEvents: SpeechClient.responseEvents,
10
- options,
11
- });
12
- export * as TestSpeech from "./speech.js";
@@ -1,14 +0,0 @@
1
- import { Context } from "effect";
2
- import type { TranscriptionEvent, TranscriptionRequestFor, TranscriptionResponse } from "../transcription.js";
3
- import { TestMedia } from "./media.js";
4
- import type { TestScript } from "./script.js";
5
- export type Response = TestMedia.Response<TranscriptionResponse>;
6
- export interface TestInterface extends TestMedia.TestInterface<TranscriptionRequestFor, TranscriptionEvent, TranscriptionResponse> {
7
- }
8
- declare const Test_base: Context.ServiceClass<Test, "@opencode/ai/TestTranscription/Test", TestInterface>;
9
- export declare class Test extends Test_base {
10
- }
11
- export type LayerOptions = TestScript.Options<TranscriptionRequestFor, Response>;
12
- /** Provides one shared implementation under `TranscriptionClient.Service` and `TestTranscription.Test`. */
13
- export declare const testLayer: (options?: LayerOptions) => import("effect/Layer").Layer<Test | import("../transcription-client.js").TranscriptionClientService, never, never>;
14
- export * as TestTranscription from "./transcription.js";
@@ -1,12 +0,0 @@
1
- import { Context } from "effect";
2
- import { TranscriptionClient } from "../transcription-client.js";
3
- import { TestMedia } from "./media.js";
4
- export class Test extends Context.Service()("@opencode/ai/TestTranscription/Test") {
5
- }
6
- /** Provides one shared implementation under `TranscriptionClient.Service` and `TestTranscription.Test`. */
7
- export const testLayer = (options = {}) => TestMedia.testLayer(TranscriptionClient.Service, Test, {
8
- name: "TestTranscription",
9
- responseEvents: TranscriptionClient.responseEvents,
10
- options,
11
- });
12
- export * as TestTranscription from "./transcription.js";
@@ -1,14 +0,0 @@
1
- import { Context } from "effect";
2
- import type { VideoEvent, VideoRequestFor, VideoResponse } from "../video.js";
3
- import { TestMedia } from "./media.js";
4
- import type { TestScript } from "./script.js";
5
- export type Response = TestMedia.Response<VideoResponse>;
6
- export interface TestInterface extends TestMedia.TestInterface<VideoRequestFor, VideoEvent, VideoResponse> {
7
- }
8
- declare const Test_base: Context.ServiceClass<Test, "@opencode/ai/TestVideo/Test", TestInterface>;
9
- export declare class Test extends Test_base {
10
- }
11
- export type LayerOptions = TestScript.Options<VideoRequestFor, Response>;
12
- /** Provides one shared implementation under `VideoClient.Service` and `TestVideo.Test`. */
13
- export declare const testLayer: (options?: LayerOptions) => import("effect/Layer").Layer<Test | import("../video-client.js").VideoClientService, never, never>;
14
- export * as TestVideo from "./video.js";
@@ -1,12 +0,0 @@
1
- import { Context } from "effect";
2
- import { VideoClient } from "../video-client.js";
3
- import { TestMedia } from "./media.js";
4
- export class Test extends Context.Service()("@opencode/ai/TestVideo/Test") {
5
- }
6
- /** Provides one shared implementation under `VideoClient.Service` and `TestVideo.Test`. */
7
- export const testLayer = (options = {}) => TestMedia.testLayer(VideoClient.Service, Test, {
8
- name: "TestVideo",
9
- responseEvents: VideoClient.responseEvents,
10
- options,
11
- });
12
- export * as TestVideo from "./video.js";