@opencode/ai 0.0.0-dev-1298 → 0.0.0-dev-1301
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 +23 -0
- package/dist/index.d.ts +13 -6
- package/dist/index.js +17 -15
- package/dist/media.d.ts +9 -1
- package/dist/media.js +14 -7
- package/dist/protocols/openai-chat.js +7 -3
- package/dist/protocols/openrouter-video.js +2 -2
- package/dist/public.d.ts +1 -0
- package/dist/route/executor-service.d.ts +14 -1
- package/dist/route/executor-service.js +28 -1
- package/dist/route/executor.d.ts +5 -2
- package/dist/route/executor.js +20 -5
- package/dist/route/media-protocol.d.ts +4 -3
- package/dist/route/media.js +12 -3
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -249,6 +249,29 @@ const logged = RequestExecutor.middleware((request, next) =>
|
|
|
249
249
|
const everything = AIClient.layerWith(logged) // or AI.make({ layer: logged })
|
|
250
250
|
```
|
|
251
251
|
|
|
252
|
+
To hook only some calls, such as adding a per-user header, scope middleware to them. It runs on every provider request
|
|
253
|
+
they make, whatever the modality: submits, polls, results and cancels. Executor-wide middleware wraps it.
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
const signed: HttpMiddleware = (request, next) => next(HttpClientRequest.setHeader(request, "x-user", "user-1"))
|
|
257
|
+
|
|
258
|
+
// Effect: an Effect or a Stream
|
|
259
|
+
const video =
|
|
260
|
+
yield *
|
|
261
|
+
Effect.gen(function* () {
|
|
262
|
+
const job = yield* ai.video.start({ model, prompt: "A red balloon floats up" })
|
|
263
|
+
return yield* ai.video.result(model, job.id)
|
|
264
|
+
}).pipe(RequestExecutor.withMiddleware(signed))
|
|
265
|
+
|
|
266
|
+
// Promise: `http` on any call's options; a handle it returns keeps it
|
|
267
|
+
await AI.ai.video.start({ model, prompt: "A red balloon floats up" }, { http: signed })
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
Downloading a `url` asset never uses the caller's scoped middleware, so hooks that add credentials can't reach another
|
|
271
|
+
host such as a CDN or a presigned storage URL. A result URL on the provider's own origin carries the middleware of the
|
|
272
|
+
call that returned it (`asset.middleware`), so it downloads the same way later. Set `middleware` yourself with
|
|
273
|
+
`Media.url(url, { middleware })`.
|
|
274
|
+
|
|
252
275
|
## Venice AI
|
|
253
276
|
|
|
254
277
|
`Venice` provides native Chat Completions with streaming tools and reasoning. `model` and `chat`
|
package/dist/index.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { type ImageModel, type ImageRequest, type ImageRequestInput } from "./im
|
|
|
7
7
|
import { LLM } from "./llm.js";
|
|
8
8
|
import { Media } from "./media.js";
|
|
9
9
|
import { type CheckpointRequest, type CompactionRequest, type EndpointCompactOptions, type StreamOptions, type TriggerCompactOptions } from "./route/client.js";
|
|
10
|
-
import { RequestExecutor } from "./route/executor.js";
|
|
10
|
+
import { RequestExecutor, type HttpMiddleware } from "./route/executor.js";
|
|
11
11
|
import { LanguageModel, type CompactionCheckpointResponse, type CompactionResponse, type LLMEvent, type LLMResponse } from "./schema/index.js";
|
|
12
12
|
import type { LoopObjectEvent, ObjectEvent, ObjectResponse, OutputSchema, OutputType, LLMLoopInput, LLMRequestInput } from "./llm.js";
|
|
13
13
|
import { type SpeechModel, type SpeechRequest, type SpeechRequestInput } from "./speech.js";
|
|
@@ -25,7 +25,14 @@ export interface Options {
|
|
|
25
25
|
}
|
|
26
26
|
export interface RunOptions {
|
|
27
27
|
readonly signal?: AbortSignal;
|
|
28
|
+
/**
|
|
29
|
+
* Runs on every provider request the call makes, like `RequestExecutor.withMiddleware`: submits, polls, results and
|
|
30
|
+
* cancels included. A handle the call returns keeps it for its own calls.
|
|
31
|
+
*/
|
|
32
|
+
readonly http?: HttpMiddleware;
|
|
28
33
|
}
|
|
34
|
+
/** Options for reading or writing an asset. Downloads use the asset's own `middleware`, never a caller's `http`. */
|
|
35
|
+
export type AssetRunOptions = Omit<RunOptions, "http">;
|
|
29
36
|
export type Services = AIClient.Services;
|
|
30
37
|
/**
|
|
31
38
|
* Promise view of a `Generation`. Its fields are a snapshot taken when the handle was created; `refresh()` resolves to a
|
|
@@ -47,14 +54,14 @@ export type GenerationHandle<Response> = Snapshot & {
|
|
|
47
54
|
export declare const make: (options?: Options) => {
|
|
48
55
|
run: <A, E>(effect: Effect.Effect<A, E, Services>, options?: RunOptions) => Promise<A>;
|
|
49
56
|
/** Decoded asset bytes, downloading `url` sources through the executor. */
|
|
50
|
-
bytes: (asset: Media.Asset, options?:
|
|
51
|
-
base64: (asset: Media.Asset, options?:
|
|
57
|
+
bytes: (asset: Media.Asset, options?: AssetRunOptions) => Promise<Uint8Array<ArrayBufferLike>>;
|
|
58
|
+
base64: (asset: Media.Asset, options?: AssetRunOptions) => Promise<string>;
|
|
52
59
|
/** Pull a `url` asset into owned bytes before the provider URL expires. */
|
|
53
|
-
materialize: (asset: Media.Asset, options?:
|
|
60
|
+
materialize: (asset: Media.Asset, options?: AssetRunOptions) => Promise<Media.Asset>;
|
|
54
61
|
/** Read a file into an asset like `Media.file`: sniffed media type, then the extension's. */
|
|
55
|
-
file: (path: string, options?: Media.AssetOptions &
|
|
62
|
+
file: (path: string, options?: Media.AssetOptions & AssetRunOptions) => Promise<Media.Asset>;
|
|
56
63
|
/** Write an asset's bytes like `Media.write`: streamed through a temporary file that replaces `path` on success. */
|
|
57
|
-
write: (asset: Media.Asset, path: string, options?:
|
|
64
|
+
write: (asset: Media.Asset, path: string, options?: AssetRunOptions) => Promise<void>;
|
|
58
65
|
request: typeof LLM.request;
|
|
59
66
|
generate: {
|
|
60
67
|
<const Model extends LanguageModel, S extends OutputSchema>(input: LLMRequestInput<Model> & {
|
package/dist/index.js
CHANGED
|
@@ -28,35 +28,36 @@ const abortEffect = (signal) => signal === undefined
|
|
|
28
28
|
export const make = (options = {}) => {
|
|
29
29
|
const runtime = ManagedRuntime.make(AIClient.layerWith(options.layer ?? RequestExecutor.fetchLayer));
|
|
30
30
|
/** Run any package Effect (for example `ai.compact(...)` from `@opencode/ai/effect`) inside this runtime. */
|
|
31
|
-
const run = (effect, options) => runtime.runPromise(Effect.raceFirst(effect, abortEffect(options?.signal)));
|
|
32
|
-
const iterate = (stream, options) => Stream.toAsyncIterable(Stream.unwrap(runtime.contextEffect.pipe(Effect.map((context) => stream.pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context))))));
|
|
31
|
+
const run = (effect, options) => runtime.runPromise(Effect.raceFirst(scoped(effect, options?.http), abortEffect(options?.signal)));
|
|
32
|
+
const iterate = (stream, options) => Stream.toAsyncIterable(Stream.unwrap(runtime.contextEffect.pipe(Effect.map((context) => scoped(stream, options?.http).pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context))))));
|
|
33
|
+
// `run` and `iterate` apply `http` around the whole call, so the LLM call gets none of its own.
|
|
33
34
|
function generate(input, options) {
|
|
34
|
-
return run(LLM.generate(input, options), options);
|
|
35
|
+
return run(LLM.generate(input, { ...options, http: undefined }), options);
|
|
35
36
|
}
|
|
36
37
|
function stream(input, options) {
|
|
37
|
-
return iterate(LLM.stream(input, options), options);
|
|
38
|
+
return iterate(LLM.stream(input, { ...options, http: undefined }), options);
|
|
38
39
|
}
|
|
39
40
|
function loop(input, options) {
|
|
40
|
-
return iterate(LLM.loop(input, options), options);
|
|
41
|
+
return iterate(LLM.loop(input, { ...options, http: undefined }), options);
|
|
41
42
|
}
|
|
42
43
|
/** Read `events` from `stream` or `loop` to the end and fold them into the final result. */
|
|
43
44
|
const collect = (events, options) => run(LLM.collect(Stream.fromAsyncIterable(events, (error) => error)), options);
|
|
44
45
|
// The overloads pair each request type with its mechanism; `LLM.compact` checks the route's capability at runtime.
|
|
45
46
|
function compact(request, options) {
|
|
46
47
|
return options?.mechanism === "trigger"
|
|
47
|
-
? run(LLM.compact(request, options), options)
|
|
48
|
-
: run(LLM.compact(request, options), options);
|
|
48
|
+
? run(LLM.compact(request, { ...options, http: undefined }), options)
|
|
49
|
+
: run(LLM.compact(request, { ...options, http: undefined }), options);
|
|
49
50
|
}
|
|
50
|
-
const handle = (generation) => ({
|
|
51
|
+
const handle = (http) => (generation) => ({
|
|
51
52
|
...generation.snapshot,
|
|
52
53
|
snapshot: generation.snapshot,
|
|
53
54
|
terminal: generation.terminal,
|
|
54
55
|
token: generation.token,
|
|
55
|
-
await: (options) => run(generation.await(options), options),
|
|
56
|
-
events: (options) => iterate(generation.events(options), options),
|
|
57
|
-
result: (options) => run(generation.result(), options),
|
|
58
|
-
refresh: (options) => run(generation.refresh(), options).then(handle),
|
|
59
|
-
cancel: (options) => run(generation.cancel(), options),
|
|
56
|
+
await: (options) => run(generation.await(options), { http, ...options }),
|
|
57
|
+
events: (options) => iterate(generation.events(options), { http, ...options }),
|
|
58
|
+
result: (options) => run(generation.result(), { http, ...options }),
|
|
59
|
+
refresh: (options) => run(generation.refresh(), { http, ...options }).then(handle(options?.http ?? http)),
|
|
60
|
+
cancel: (options) => run(generation.cancel(), { http, ...options }),
|
|
60
61
|
});
|
|
61
62
|
return {
|
|
62
63
|
run,
|
|
@@ -148,13 +149,14 @@ export const make = (options = {}) => {
|
|
|
148
149
|
request: Transcription.request,
|
|
149
150
|
generate: (input, options) => run(Transcription.generate(input, { poll: options?.poll }), options),
|
|
150
151
|
stream: (input, options) => iterate(Transcription.stream(input, { poll: options?.poll }), options),
|
|
151
|
-
start: (input, options) => run(Transcription.start(input), options).then(handle),
|
|
152
|
-
resume: (model, token, options) => run(Transcription.resume(model, token), options).then(handle),
|
|
152
|
+
start: (input, options) => run(Transcription.start(input), options).then(handle(options?.http)),
|
|
153
|
+
resume: (model, token, options) => run(Transcription.resume(model, token), options).then(handle(options?.http)),
|
|
153
154
|
},
|
|
154
155
|
},
|
|
155
156
|
dispose: () => runtime.dispose(),
|
|
156
157
|
};
|
|
157
158
|
};
|
|
159
|
+
const scoped = (self, http) => (http === undefined ? self : RequestExecutor.withMiddleware(http)(self));
|
|
158
160
|
const fileError = (message, cause) => new AIError({ reason: new InvalidRequestError({ message, cause }) });
|
|
159
161
|
/** `tool` from `@opencode/ai/effect`, with an `execute` that returns a value or a Promise and throws to fail. */
|
|
160
162
|
export const tool = (config) => {
|
package/dist/media.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { Effect, FileSystem, Schema, Stream } from "effect";
|
|
|
3
3
|
import { ProviderID } from "./schema/ids.js";
|
|
4
4
|
import { AIError } from "./schema/errors.js";
|
|
5
5
|
import { ProviderMetadata } from "./schema/options.js";
|
|
6
|
-
import { Service } from "./route/executor-service.js";
|
|
6
|
+
import { type HttpMiddleware, Service } from "./route/executor-service.js";
|
|
7
7
|
export { detectMediaType } from "./utils/media-type.js";
|
|
8
8
|
export declare const Source: Schema.Union<readonly [Schema.Struct<{
|
|
9
9
|
readonly type: Schema.Literal<"bytes">;
|
|
@@ -60,6 +60,8 @@ export declare class Asset {
|
|
|
60
60
|
readonly providerMetadata?: ProviderMetadata;
|
|
61
61
|
/** Transient download credentials for `url` sources; see `Asset.Input.headers`. */
|
|
62
62
|
readonly headers?: Record<string, string>;
|
|
63
|
+
/** Middleware for downloading a `url` source; see `Asset.Input.middleware`. */
|
|
64
|
+
readonly middleware?: HttpMiddleware;
|
|
63
65
|
constructor(input: Asset.Input);
|
|
64
66
|
/** Inline payload without effects, for protocols that embed base64 or data URLs directly. */
|
|
65
67
|
inline(): Inline | undefined;
|
|
@@ -122,6 +124,12 @@ export declare namespace Asset {
|
|
|
122
124
|
* credentials and cannot be downloaded again after a round-trip. Call `materialize()` before persisting.
|
|
123
125
|
*/
|
|
124
126
|
readonly headers?: Record<string, string>;
|
|
127
|
+
/**
|
|
128
|
+
* Middleware for downloading a `url` source, runtime-only like `headers`. A download never uses the caller's
|
|
129
|
+
* scoped middleware (`RequestExecutor.withMiddleware`), so hooks that add provider credentials can't reach another
|
|
130
|
+
* host. Routes set this to that middleware only for result URLs on the provider's origin.
|
|
131
|
+
*/
|
|
132
|
+
readonly middleware?: HttpMiddleware;
|
|
125
133
|
}
|
|
126
134
|
}
|
|
127
135
|
/** JSON form of an asset: the serializable `Source` plus caller-supplied metadata. `bytes` sources encode as base64. */
|
package/dist/media.js
CHANGED
|
@@ -5,7 +5,7 @@ import { HttpClientRequest } from "effect/http";
|
|
|
5
5
|
import { ProviderID } from "./schema/ids.js";
|
|
6
6
|
import { AIError, InvalidProviderOutputError, InvalidRequestError } from "./schema/errors.js";
|
|
7
7
|
import { ProviderMetadata } from "./schema/options.js";
|
|
8
|
-
import { responseHttp, Service } from "./route/executor-service.js";
|
|
8
|
+
import { CurrentMiddleware, responseHttp, Service } from "./route/executor-service.js";
|
|
9
9
|
import { detectMediaType, fileMediaType } from "./utils/media-type.js";
|
|
10
10
|
export { detectMediaType } from "./utils/media-type.js";
|
|
11
11
|
const OCTET_STREAM = "application/octet-stream";
|
|
@@ -78,6 +78,8 @@ export class Asset {
|
|
|
78
78
|
providerMetadata;
|
|
79
79
|
/** Transient download credentials for `url` sources; see `Asset.Input.headers`. */
|
|
80
80
|
headers;
|
|
81
|
+
/** Middleware for downloading a `url` source; see `Asset.Input.middleware`. */
|
|
82
|
+
middleware;
|
|
81
83
|
// Derived payload forms are cached on the instance because every protocol lowering re-reads the same payload. The
|
|
82
84
|
// cache is check-then-set (concurrent first reads of a `url` source may both download) and is never observable
|
|
83
85
|
// through `source`, so round-tripping through `Media.from(asset.source)` stays lossless.
|
|
@@ -94,6 +96,7 @@ export class Asset {
|
|
|
94
96
|
this.expiresAt = input.source.type === "url" ? input.source.expiresAt : undefined;
|
|
95
97
|
this.providerMetadata = input.providerMetadata;
|
|
96
98
|
this.headers = input.source.type === "url" ? input.headers : undefined;
|
|
99
|
+
this.middleware = input.source.type === "url" ? input.middleware : undefined;
|
|
97
100
|
}
|
|
98
101
|
/** Inline payload without effects, for protocols that embed base64 or data URLs directly. */
|
|
99
102
|
inline() {
|
|
@@ -116,7 +119,7 @@ export class Asset {
|
|
|
116
119
|
return Effect.fail(invalid(`Cannot materialize provider ref ${source.provider}:${source.id}`));
|
|
117
120
|
const decoded = source.type === "base64"
|
|
118
121
|
? Effect.fromResult(Base64.decode(source.data)).pipe(Effect.mapError((cause) => invalid(`Media asset contains invalid base64 data`, cause)))
|
|
119
|
-
: download(source, this.headers);
|
|
122
|
+
: download(source, this.headers, this.middleware);
|
|
120
123
|
return decoded.pipe(Effect.tap((data) => Effect.sync(() => (this.#bytes = data))));
|
|
121
124
|
});
|
|
122
125
|
}
|
|
@@ -125,7 +128,7 @@ export class Asset {
|
|
|
125
128
|
const source = this.source;
|
|
126
129
|
if (source.type !== "url" || this.#bytes !== undefined)
|
|
127
130
|
return Stream.fromEffect(this.bytes());
|
|
128
|
-
return Stream.unwrap(downloadStream(source, this.headers));
|
|
131
|
+
return Stream.unwrap(downloadStream(source, this.headers, this.middleware));
|
|
129
132
|
}
|
|
130
133
|
base64() {
|
|
131
134
|
return Effect.suspend(() => {
|
|
@@ -185,9 +188,11 @@ export const AssetSchema = AssetEncoded.pipe(Schema.decodeTo(AssetInstance, {
|
|
|
185
188
|
export const ImageAssetSchema = AssetInstance.check(Schema.makeFilter((asset) => asset.kind === "image" ||
|
|
186
189
|
((asset.source.type === "url" || asset.source.type === "ref") && asset.source.mediaType === undefined) ||
|
|
187
190
|
`expected an image, got ${asset.mediaType}`)).pipe(Schema.brand("Media.ImageAsset"));
|
|
188
|
-
const download = Effect.fn("Media.download")(function* (source, headers) {
|
|
191
|
+
const download = Effect.fn("Media.download")(function* (source, headers, middleware) {
|
|
189
192
|
const executor = yield* Service;
|
|
190
|
-
const response = yield* executor
|
|
193
|
+
const response = yield* executor
|
|
194
|
+
.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
|
|
195
|
+
.pipe(Effect.provideService(CurrentMiddleware, middleware));
|
|
191
196
|
const buffer = yield* response.arrayBuffer.pipe(Effect.mapError((cause) => new AIError({
|
|
192
197
|
reason: new InvalidProviderOutputError({
|
|
193
198
|
message: `Failed to read media from ${source.url}`,
|
|
@@ -197,9 +202,11 @@ const download = Effect.fn("Media.download")(function* (source, headers) {
|
|
|
197
202
|
})));
|
|
198
203
|
return new Uint8Array(buffer);
|
|
199
204
|
});
|
|
200
|
-
const downloadStream = Effect.fn("Media.downloadStream")(function* (source, headers) {
|
|
205
|
+
const downloadStream = Effect.fn("Media.downloadStream")(function* (source, headers, middleware) {
|
|
201
206
|
const executor = yield* Service;
|
|
202
|
-
const response = yield* executor
|
|
207
|
+
const response = yield* executor
|
|
208
|
+
.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
|
|
209
|
+
.pipe(Effect.provideService(CurrentMiddleware, middleware));
|
|
203
210
|
return response.stream.pipe(Stream.mapError((cause) => new AIError({
|
|
204
211
|
reason: new InvalidProviderOutputError({
|
|
205
212
|
message: `Failed to read media from ${source.url}`,
|
|
@@ -418,6 +418,9 @@ const lowerAssistantMessage = Effect.fnUntraced(function* (message, configuredFi
|
|
|
418
418
|
})();
|
|
419
419
|
const opaque = reasoningOpaque(reasoning, options.providerMetadataKey);
|
|
420
420
|
const reasoningText = reasoning.length === 0 || (opaque !== undefined && text === "") ? (requireReasoning ? "" : undefined) : text;
|
|
421
|
+
// A model that declares a different reasoning field reads reasoning there, so structured details and opaque values
|
|
422
|
+
// from earlier turns (including another model served under the same provider metadata key) must not be replayed.
|
|
423
|
+
const replaysStructured = configuredField === undefined || configuredField === "reasoning_details";
|
|
421
424
|
const result = {
|
|
422
425
|
role: "assistant",
|
|
423
426
|
content: (() => {
|
|
@@ -428,10 +431,11 @@ const lowerAssistantMessage = Effect.fnUntraced(function* (message, configuredFi
|
|
|
428
431
|
return content.map((part) => part.text).join("");
|
|
429
432
|
})(),
|
|
430
433
|
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
431
|
-
...(details !== undefined ? { reasoning_details: details } : {}),
|
|
432
|
-
...(opaque !== undefined ? { reasoning_opaque: opaque } : {}),
|
|
434
|
+
...(details !== undefined && replaysStructured ? { reasoning_details: details } : {}),
|
|
435
|
+
...(opaque !== undefined && replaysStructured ? { reasoning_opaque: opaque } : {}),
|
|
433
436
|
};
|
|
434
|
-
|
|
437
|
+
// `reasoning_details` is the structured list itself, so scalar text must not be written over it.
|
|
438
|
+
if (field === undefined || reasoningText === undefined || field === "reasoning_details")
|
|
435
439
|
return result;
|
|
436
440
|
return { ...result, [field]: reasoningText };
|
|
437
441
|
});
|
|
@@ -104,10 +104,10 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* (respon
|
|
|
104
104
|
if (urls.length === 0)
|
|
105
105
|
return yield* output.invalid(`${route.name} completed without a video URL`);
|
|
106
106
|
// The content URLs are OpenRouter's own and only download with the API key.
|
|
107
|
-
const videos = yield* Effect.forEach(urls, (url) => context.
|
|
107
|
+
const videos = yield* Effect.forEach(urls, (url) => context.credentials(url).pipe(Effect.map((credentials) => Media.url(url, {
|
|
108
108
|
mediaType: "video/mp4",
|
|
109
109
|
expiresAt: job.expires_at === undefined || job.expires_at === null ? undefined : job.expires_at * 1000,
|
|
110
|
-
|
|
110
|
+
...credentials,
|
|
111
111
|
}))));
|
|
112
112
|
return new VideoResponse({
|
|
113
113
|
videos,
|
package/dist/public.d.ts
CHANGED
|
@@ -14,3 +14,4 @@ export type { AwaitOptions as GenerationAwaitOptions, Event as GenerationEvent,
|
|
|
14
14
|
export type { ExecutableTool, Tool, ToolExecute, ToolExecuteContext, ToolInput, ToolInputType, ToolModelOutputInput, ToolOptions, ToolSchema, ToolToModelOutput, } from "./tool.js";
|
|
15
15
|
export type { LLM } from "./llm.js";
|
|
16
16
|
export type { LLMLoopInput, LLMRequestInput } from "./llm.js";
|
|
17
|
+
export type { HttpHandler, HttpMiddleware } from "./route/executor-service.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Context,
|
|
1
|
+
import { Context, Effect, Stream } from "effect";
|
|
2
2
|
import type { Headers, HttpClientRequest, HttpClientResponse } from "effect/http";
|
|
3
3
|
import { HttpContext, type AIError } from "../schema/errors.js";
|
|
4
4
|
import type { ClientTls } from "../schema/options.js";
|
|
@@ -17,6 +17,19 @@ export declare const Service: typeof RequestExecutorService;
|
|
|
17
17
|
*/
|
|
18
18
|
export declare const CurrentTls: Context.Reference<ClientTls | undefined>;
|
|
19
19
|
export type Service = RequestExecutorService;
|
|
20
|
+
/**
|
|
21
|
+
* Middleware for every provider request made while it is set: model calls, media submits, polls, results and cancels,
|
|
22
|
+
* whatever the modality. Set it with {@link withMiddleware}. Downloads of a `url` asset don't use it; they use the
|
|
23
|
+
* asset's own `middleware`, which a route sets only for URLs on the provider's origin.
|
|
24
|
+
*/
|
|
25
|
+
export declare const CurrentMiddleware: Context.Reference<HttpMiddleware | undefined>;
|
|
26
|
+
/** `outer` wraps `inner`: it sees the request first and the response last. */
|
|
27
|
+
export declare const composeMiddleware: (outer: HttpMiddleware | undefined, inner: HttpMiddleware | undefined) => HttpMiddleware | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Runs `fn` on every provider request `self` makes, an Effect or a Stream. Inside an outer `withMiddleware`, the outer
|
|
30
|
+
* one wraps this one. Executor-wide middleware (`RequestExecutor.middleware`) wraps both.
|
|
31
|
+
*/
|
|
32
|
+
export declare const withMiddleware: (fn: HttpMiddleware) => <Self extends Effect.Effect<unknown, unknown, unknown> | Stream.Stream<unknown, unknown, unknown>>(self: Self) => Self;
|
|
20
33
|
export declare const headerDetails: (headers: Headers.Headers) => {
|
|
21
34
|
[k: string]: string;
|
|
22
35
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Context } from "effect";
|
|
1
|
+
import { Context, Effect, Stream } from "effect";
|
|
2
2
|
import { HttpContext } from "../schema/errors.js";
|
|
3
3
|
export class RequestExecutorService extends Context.Service()("@opencode/AI/RequestExecutor") {
|
|
4
4
|
}
|
|
@@ -10,6 +10,33 @@ export const Service = RequestExecutorService;
|
|
|
10
10
|
export const CurrentTls = Context.Reference("@opencode/AI/RequestExecutor/CurrentTls", {
|
|
11
11
|
defaultValue: () => undefined,
|
|
12
12
|
});
|
|
13
|
+
/**
|
|
14
|
+
* Middleware for every provider request made while it is set: model calls, media submits, polls, results and cancels,
|
|
15
|
+
* whatever the modality. Set it with {@link withMiddleware}. Downloads of a `url` asset don't use it; they use the
|
|
16
|
+
* asset's own `middleware`, which a route sets only for URLs on the provider's origin.
|
|
17
|
+
*/
|
|
18
|
+
export const CurrentMiddleware = Context.Reference("@opencode/AI/RequestExecutor/CurrentMiddleware", { defaultValue: () => undefined });
|
|
19
|
+
/** `outer` wraps `inner`: it sees the request first and the response last. */
|
|
20
|
+
export const composeMiddleware = (outer, inner) => {
|
|
21
|
+
if (outer === undefined)
|
|
22
|
+
return inner;
|
|
23
|
+
if (inner === undefined)
|
|
24
|
+
return outer;
|
|
25
|
+
return (request, handler) => outer(request, (forwarded) => inner(forwarded, handler));
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Runs `fn` on every provider request `self` makes, an Effect or a Stream. Inside an outer `withMiddleware`, the outer
|
|
29
|
+
* one wraps this one. Executor-wide middleware (`RequestExecutor.middleware`) wraps both.
|
|
30
|
+
*/
|
|
31
|
+
export const withMiddleware = (fn) => (self) => {
|
|
32
|
+
const merged = Effect.gen(function* () {
|
|
33
|
+
return composeMiddleware(yield* CurrentMiddleware, fn);
|
|
34
|
+
});
|
|
35
|
+
// One signature for both, so it infers inside `pipe`; each branch returns the same kind it was given.
|
|
36
|
+
return (Stream.isStream(self)
|
|
37
|
+
? Stream.provideServiceEffect(self, CurrentMiddleware, merged)
|
|
38
|
+
: Effect.provideServiceEffect(self, CurrentMiddleware, merged));
|
|
39
|
+
};
|
|
13
40
|
export const headerDetails = (headers) => Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, value]));
|
|
14
41
|
export const responseHttp = (response) => new HttpContext({
|
|
15
42
|
url: response.request.url,
|
package/dist/route/executor.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
|
|
|
3
3
|
import { AIError } from "../schema/index.js";
|
|
4
4
|
import { Service, type HttpMiddleware, type Interface } from "./executor-service.js";
|
|
5
5
|
import type { ClientTls } from "../schema/options.js";
|
|
6
|
-
export { CurrentTls, responseHttp, Service } from "./executor-service.js";
|
|
6
|
+
export { composeMiddleware, CurrentMiddleware, CurrentTls, responseHttp, Service, withMiddleware, } from "./executor-service.js";
|
|
7
7
|
export type { HttpHandler, HttpMiddleware, Interface, RequestExecutorService } from "./executor-service.js";
|
|
8
8
|
/** Preserve HTTP diagnostics for executor and externally captured failures alike. */
|
|
9
9
|
export declare const httpFailure: (input: {
|
|
@@ -29,6 +29,9 @@ export declare const withTls: (execute: Interface["execute"], tls: ClientTls | u
|
|
|
29
29
|
* `middleware` still wrap the call, and status classification still applies.
|
|
30
30
|
*/
|
|
31
31
|
export declare const withFetch: (fetch: typeof globalThis.fetch | undefined, middleware?: HttpMiddleware) => HttpMiddleware | undefined;
|
|
32
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* Run `fn` on every request: it sees the raw response before status classification, inside middleware already on
|
|
34
|
+
* `executor`, and outside per-call and scoped ({@link withMiddleware}) middleware.
|
|
35
|
+
*/
|
|
33
36
|
export declare const middleware: (fn: HttpMiddleware, executor?: Layer.Layer<Service>) => Layer.Layer<Service>;
|
|
34
37
|
export * as RequestExecutor from "./executor.js";
|
package/dist/route/executor.js
CHANGED
|
@@ -2,8 +2,8 @@ import { Cause, Effect, Layer, Option, Schema, Stream } from "effect";
|
|
|
2
2
|
import { FetchHttpClient, Headers, HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse, } from "effect/http";
|
|
3
3
|
import { HttpContext, HttpRateLimitDetails, AIError, TransportError } from "../schema/index.js";
|
|
4
4
|
import { classifyProviderFailure, providerErrorMessage } from "../provider-error.js";
|
|
5
|
-
import { CurrentTls, headerDetails, responseHttp, Service, } from "./executor-service.js";
|
|
6
|
-
export { CurrentTls, responseHttp, Service } from "./executor-service.js";
|
|
5
|
+
import { composeMiddleware, CurrentMiddleware, CurrentTls, headerDetails, responseHttp, Service, } from "./executor-service.js";
|
|
6
|
+
export { composeMiddleware, CurrentMiddleware, CurrentTls, responseHttp, Service, withMiddleware, } from "./executor-service.js";
|
|
7
7
|
const normalizedHeaders = (headers) => Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
|
|
8
8
|
const clampRetryAfterMs = (millis) => Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.ceil(millis)));
|
|
9
9
|
const retryAfterMs = (headers) => {
|
|
@@ -182,7 +182,12 @@ export const layer = Layer.effect(Service, Effect.gen(function* () {
|
|
|
182
182
|
return yield* statusError(response);
|
|
183
183
|
});
|
|
184
184
|
return Service.of({
|
|
185
|
-
|
|
185
|
+
// Scoped middleware runs outside per-call middleware. It is cleared while the request runs, so a request a
|
|
186
|
+
// middleware makes itself isn't wrapped again.
|
|
187
|
+
execute: (request, next) => Effect.gen(function* () {
|
|
188
|
+
const middleware = composeMiddleware(yield* CurrentMiddleware, next);
|
|
189
|
+
return yield* executeOnce(request, middleware).pipe(Effect.provideService(CurrentMiddleware, undefined));
|
|
190
|
+
}),
|
|
186
191
|
});
|
|
187
192
|
}));
|
|
188
193
|
export const fetchLayer = layer.pipe(Layer.provide(FetchHttpClient.layer));
|
|
@@ -201,11 +206,21 @@ export const withFetch = (fetch, middleware) => {
|
|
|
201
206
|
const send = (request) => HttpClient.execute(request).pipe(Effect.provide(FetchHttpClient.layer), Effect.provideService(FetchHttpClient.Fetch, fetch));
|
|
202
207
|
return middleware === undefined ? send : (request) => middleware(request, send);
|
|
203
208
|
};
|
|
204
|
-
/**
|
|
209
|
+
/**
|
|
210
|
+
* Run `fn` on every request: it sees the raw response before status classification, inside middleware already on
|
|
211
|
+
* `executor`, and outside per-call and scoped ({@link withMiddleware}) middleware.
|
|
212
|
+
*/
|
|
205
213
|
export const middleware = (fn, executor = fetchLayer) => Layer.effect(Service, Effect.gen(function* () {
|
|
206
214
|
const inner = yield* Service;
|
|
207
215
|
return Service.of({
|
|
208
|
-
|
|
216
|
+
// Scoped middleware sits where per-call middleware does, inside `fn`; it is read here and cleared so the
|
|
217
|
+
// executors below don't apply it again.
|
|
218
|
+
execute: (request, next) => Effect.gen(function* () {
|
|
219
|
+
const scoped = composeMiddleware(yield* CurrentMiddleware, next);
|
|
220
|
+
return yield* inner
|
|
221
|
+
.execute(request, composeMiddleware(fn, scoped))
|
|
222
|
+
.pipe(Effect.provideService(CurrentMiddleware, undefined));
|
|
223
|
+
}),
|
|
209
224
|
});
|
|
210
225
|
})).pipe(Layer.provide(executor));
|
|
211
226
|
export * as RequestExecutor from "./executor.js";
|
|
@@ -54,10 +54,11 @@ export interface Started<Token> {
|
|
|
54
54
|
export interface PollContext<Token> {
|
|
55
55
|
readonly token: Token;
|
|
56
56
|
/**
|
|
57
|
-
*
|
|
58
|
-
*
|
|
57
|
+
* What an authenticated download of `url` needs, for result URLs that only download with the API key: the headers a
|
|
58
|
+
* GET would send (deployment headers plus auth) and the caller's scoped middleware. Spread it into `Media.url`. URLs
|
|
59
|
+
* on another origin than the route's base URL get neither, so credentials and hooks never leave the provider's host.
|
|
59
60
|
*/
|
|
60
|
-
readonly
|
|
61
|
+
readonly credentials: (url: string) => Effect.Effect<Pick<Media.AssetOptions, "headers" | "middleware">, AIError>;
|
|
61
62
|
/**
|
|
62
63
|
* A further GET with the same auth and headers, retried like the poll itself, for providers whose result needs a
|
|
63
64
|
* second lookup (MiniMax v1 answers with a file id that resolves to a download URL).
|
package/dist/route/media.js
CHANGED
|
@@ -58,7 +58,16 @@ export const queued = (input) => {
|
|
|
58
58
|
// Only the GET exchange retries: a decoded terminal failure (`output.ended`) can be a `ProviderInternal` too, and
|
|
59
59
|
// re-reading it would spin until the caller's deadline.
|
|
60
60
|
const get = (path) => transport.call("GET", path, exchange, execute).pipe(Effect.retry({ schedule: READ_RETRY, while: isRetryable }), Effect.map((sent) => sent.response));
|
|
61
|
-
const poll = (operation) => get(operation.path(token)).pipe(Effect.flatMap((response) => operation.decode(response, {
|
|
61
|
+
const poll = (operation) => get(operation.path(token)).pipe(Effect.flatMap((response) => operation.decode(response, {
|
|
62
|
+
token,
|
|
63
|
+
get,
|
|
64
|
+
credentials: (url) => Effect.gen(function* () {
|
|
65
|
+
const headers = yield* transport.headers(url, exchange);
|
|
66
|
+
if (headers === undefined)
|
|
67
|
+
return {};
|
|
68
|
+
return { headers, middleware: yield* RequestExecutor.CurrentMiddleware };
|
|
69
|
+
}),
|
|
70
|
+
})));
|
|
62
71
|
const status = poll(protocol.status);
|
|
63
72
|
const cancel = protocol.cancel;
|
|
64
73
|
return {
|
|
@@ -167,7 +176,7 @@ const makeTransport = (input) => {
|
|
|
167
176
|
}),
|
|
168
177
|
/**
|
|
169
178
|
* The headers a follow-up GET of `url` sends, for result URLs that only download with the same credentials. A URL
|
|
170
|
-
* on another origin than the route's base URL gets
|
|
179
|
+
* on another origin than the route's base URL gets undefined, so credentials never leave the provider's host.
|
|
171
180
|
*/
|
|
172
181
|
headers: (url, exchange) => URL.canParse(url) && new URL(url).origin === baseURL("").origin
|
|
173
182
|
? authorize({
|
|
@@ -177,7 +186,7 @@ const makeTransport = (input) => {
|
|
|
177
186
|
body: "",
|
|
178
187
|
headers: Headers.fromInput(exchange.headers),
|
|
179
188
|
}).pipe(Effect.map((headers) => ({ ...headers })))
|
|
180
|
-
: Effect.succeed(
|
|
189
|
+
: Effect.succeed(undefined),
|
|
181
190
|
/** Bodiless follow-up call (status, result, cancel) with the same auth and headers as `submit`. */
|
|
182
191
|
call: (method, path, exchange, execute) => {
|
|
183
192
|
// Provider-issued absolute URLs are used as-is; everything else resolves against the base.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
|
-
"version": "0.0.0-dev-
|
|
3
|
+
"version": "0.0.0-dev-1301",
|
|
4
4
|
"name": "@opencode/ai",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -624,7 +624,7 @@
|
|
|
624
624
|
"devDependencies": {
|
|
625
625
|
"@clack/prompts": "1.0.0-alpha.1",
|
|
626
626
|
"@effect/platform-node": "4.1.0",
|
|
627
|
-
"@opencode/http-recorder": "0.0.0-dev-
|
|
627
|
+
"@opencode/http-recorder": "0.0.0-dev-1301",
|
|
628
628
|
"@tsconfig/bun": "1.0.9",
|
|
629
629
|
"@types/bun": "1.4.3",
|
|
630
630
|
"@typescript/native": "npm:typescript@7.1.0-beta",
|
|
@@ -634,7 +634,7 @@
|
|
|
634
634
|
"@aws-sdk/credential-providers": "3.1057.0",
|
|
635
635
|
"@smithy/eventstream-codec": "4.2.14",
|
|
636
636
|
"@smithy/util-utf8": "4.2.2",
|
|
637
|
-
"@opencode/schema": "0.0.0-dev-
|
|
637
|
+
"@opencode/schema": "0.0.0-dev-1301",
|
|
638
638
|
"aws4fetch": "1.0.20",
|
|
639
639
|
"effect": "4.1.0",
|
|
640
640
|
"google-auth-library": "10.5.0"
|