@opencode/ai 2.2.4 → 2.2.6
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 +133 -69
- package/dist/cache-policy.d.ts +1 -1
- package/dist/cache-policy.js +16 -4
- package/dist/decision-client.d.ts +3 -3
- package/dist/decision.d.ts +20 -125
- package/dist/decision.js +25 -15
- package/dist/effect.d.ts +4 -15
- package/dist/effect.js +2 -6
- package/dist/effort-updates.d.ts +3 -3
- package/dist/effort-updates.js +2 -2
- package/dist/experimental/cloudflare-run-extraction.d.ts +7 -3
- package/dist/experimental/cloudflare-run-extraction.js +4 -1
- package/dist/experimental/extraction.d.ts +10 -40
- package/dist/experimental/extraction.js +14 -13
- package/dist/experimental.d.ts +8 -8
- package/dist/experimental.js +4 -4
- package/dist/generation.d.ts +0 -2
- package/dist/generation.js +2 -2
- package/dist/image-client.d.ts +13 -7
- package/dist/image-client.js +1 -1
- package/dist/image.d.ts +357 -464
- package/dist/image.js +17 -15
- package/dist/index.d.ts +28 -465
- package/dist/index.js +18 -17
- package/dist/llm.d.ts +65 -266
- package/dist/llm.js +101 -92
- package/dist/loop.d.ts +38 -0
- package/dist/loop.js +136 -0
- package/dist/media-model.d.ts +1 -1
- package/dist/media-model.js +8 -6
- package/dist/media.d.ts +9 -0
- package/dist/media.js +37 -2
- package/dist/protocols/alibaba-chat.d.ts +5 -1
- package/dist/protocols/alibaba-chat.js +3 -3
- package/dist/protocols/alibaba-images.d.ts +2 -2
- package/dist/protocols/alibaba-messages.js +3 -3
- package/dist/protocols/alibaba-responses.js +8 -20
- package/dist/protocols/anthropic-messages.d.ts +1 -1
- package/dist/protocols/anthropic-messages.js +57 -185
- package/dist/protocols/assemblyai-transcription.d.ts +2 -2
- package/dist/protocols/bedrock-converse.js +11 -22
- package/dist/protocols/cartesia-speech.d.ts +2 -2
- package/dist/protocols/cloudflare-workers-ai-images.d.ts +2 -2
- package/dist/protocols/cohere-chat.js +9 -12
- package/dist/protocols/deepgram-speech.d.ts +2 -2
- package/dist/protocols/deepgram-transcription.d.ts +2 -2
- package/dist/protocols/elevenlabs-speech.d.ts +2 -2
- package/dist/protocols/elevenlabs-transcription.d.ts +2 -2
- package/dist/protocols/gemini.d.ts +3 -0
- package/dist/protocols/gemini.js +56 -89
- package/dist/protocols/google-images.d.ts +2 -2
- package/dist/protocols/google-interactions.d.ts +3 -4
- package/dist/protocols/google-interactions.js +54 -32
- package/dist/protocols/google-speech.d.ts +2 -2
- package/dist/protocols/google-transcription.d.ts +2 -2
- package/dist/protocols/google-video.d.ts +2 -2
- package/dist/protocols/meta-images.d.ts +2 -2
- package/dist/protocols/meta-responses.js +26 -23
- package/dist/protocols/minimax-images.d.ts +2 -2
- package/dist/protocols/mistral-chat.js +14 -20
- package/dist/protocols/open-responses-channel.js +6 -19
- package/dist/protocols/open-responses-continuation.d.ts +1 -5
- package/dist/protocols/open-responses-continuation.js +1 -3
- package/dist/protocols/open-responses.d.ts +1 -21
- package/dist/protocols/open-responses.js +10 -15
- package/dist/protocols/openai-chat.d.ts +3 -23
- package/dist/protocols/openai-chat.js +26 -47
- package/dist/protocols/openai-compatible-chat.d.ts +1 -1
- package/dist/protocols/openai-compatible-responses.d.ts +2 -2
- package/dist/protocols/openai-compatible-responses.js +1 -1
- package/dist/protocols/openai-decisions.js +1 -1
- package/dist/protocols/openai-images.d.ts +2 -2
- package/dist/protocols/openai-responses.js +10 -29
- package/dist/protocols/openai-speech.d.ts +2 -2
- package/dist/protocols/openai-transcription.d.ts +2 -2
- package/dist/protocols/runway-video.d.ts +2 -2
- package/dist/protocols/shared.d.ts +1 -4
- package/dist/protocols/shared.js +13 -11
- package/dist/protocols/system-one.d.ts +4 -4
- package/dist/protocols/utils/bedrock-cache.js +2 -5
- package/dist/protocols/utils/bedrock-media.d.ts +0 -3
- package/dist/protocols/utils/cache.d.ts +3 -0
- package/dist/protocols/utils/cache.js +15 -2
- package/dist/protocols/utils/image-sizing.d.ts +1 -1
- package/dist/protocols/utils/responses-checkpoint.js +1 -1
- package/dist/protocols/utils/responses-compaction.d.ts +1 -1
- package/dist/protocols/utils/responses-compaction.js +6 -5
- package/dist/protocols/utils/responses-hosted-tools.d.ts +97 -1
- package/dist/protocols/utils/responses-hosted-tools.js +31 -0
- package/dist/protocols/utils/tool-stream.d.ts +5 -271
- package/dist/protocols/utils/tool-stream.js +3 -13
- package/dist/protocols/venice-chat.d.ts +3 -1
- package/dist/protocols/venice-chat.js +4 -4
- package/dist/protocols/xai-images.d.ts +2 -2
- package/dist/protocols/xai-responses.js +5 -25
- package/dist/protocols/xai-video.d.ts +2 -2
- package/dist/protocols/zai-chat.d.ts +5 -1
- package/dist/protocols/zai-chat.js +1 -1
- package/dist/protocols/zai-images.d.ts +2 -2
- package/dist/protocols/zai-messages.js +3 -3
- package/dist/provider-error.d.ts +0 -1
- package/dist/provider-error.js +9 -80
- package/dist/providers/alibaba.d.ts +67 -4
- package/dist/providers/alibaba.js +6 -1
- package/dist/providers/amazon-bedrock-mantle.d.ts +6 -3
- package/dist/providers/amazon-bedrock-mantle.js +6 -3
- package/dist/providers/amazon-bedrock.d.ts +6 -7
- package/dist/providers/amazon-bedrock.js +1 -1
- package/dist/providers/anthropic-compatible.d.ts +7 -8
- package/dist/providers/anthropic-compatible.js +2 -5
- package/dist/providers/anthropic.d.ts +8 -9
- package/dist/providers/anthropic.js +2 -7
- package/dist/providers/assemblyai.d.ts +2 -2
- package/dist/providers/assemblyai.js +2 -7
- package/dist/providers/azure/messages.d.ts +2 -0
- package/dist/providers/azure/messages.js +1 -0
- package/dist/providers/azure.d.ts +322 -7
- package/dist/providers/azure.js +25 -9
- package/dist/providers/baseten.d.ts +5 -5
- package/dist/providers/baseten.js +7 -21
- package/dist/providers/cartesia.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +5 -5
- package/dist/providers/cerebras.js +4 -15
- package/dist/providers/cloudflare-ai-gateway.d.ts +21 -13
- package/dist/providers/cloudflare-ai-gateway.js +28 -40
- package/dist/providers/cloudflare-shared.d.ts +9 -0
- package/dist/providers/cloudflare-shared.js +25 -0
- package/dist/providers/cloudflare-workers-ai.d.ts +4 -4
- package/dist/providers/cloudflare-workers-ai.js +4 -20
- package/dist/providers/cohere/chat.js +2 -7
- package/dist/providers/cohere.d.ts +6 -5
- package/dist/providers/cohere.js +7 -13
- package/dist/providers/deepgram.d.ts +2 -2
- package/dist/providers/deepgram.js +2 -7
- package/dist/providers/deepinfra.d.ts +5 -5
- package/dist/providers/deepinfra.js +5 -13
- package/dist/providers/deepseek.d.ts +5 -5
- package/dist/providers/deepseek.js +3 -14
- package/dist/providers/digitalocean.d.ts +8 -5
- package/dist/providers/digitalocean.js +13 -14
- package/dist/providers/elevenlabs.d.ts +2 -2
- package/dist/providers/elevenlabs.js +2 -7
- package/dist/providers/fireworks.d.ts +5 -5
- package/dist/providers/fireworks.js +4 -15
- package/dist/providers/google/interactions.d.ts +1 -1
- package/dist/providers/google/interactions.js +2 -7
- package/dist/providers/google-vertex-chat.d.ts +3 -3
- package/dist/providers/google-vertex-chat.js +3 -29
- package/dist/providers/google-vertex-interactions.d.ts +3 -3
- package/dist/providers/google-vertex-messages.d.ts +3 -3
- package/dist/providers/google-vertex-messages.js +3 -29
- package/dist/providers/google-vertex-mistral.d.ts +3 -3
- package/dist/providers/google-vertex-mistral.js +3 -29
- package/dist/providers/google-vertex-responses.d.ts +3 -3
- package/dist/providers/google-vertex-responses.js +4 -30
- package/dist/providers/google-vertex-shared.d.ts +31 -0
- package/dist/providers/google-vertex-shared.js +25 -0
- package/dist/providers/google-vertex.d.ts +3 -3
- package/dist/providers/google.d.ts +15 -13
- package/dist/providers/google.js +9 -19
- package/dist/providers/groq.d.ts +5 -5
- package/dist/providers/groq.js +4 -15
- package/dist/providers/meta.d.ts +5 -5
- package/dist/providers/meta.js +10 -24
- package/dist/providers/minimax/chat.js +2 -7
- package/dist/providers/minimax/responses.js +2 -7
- package/dist/providers/minimax.d.ts +5 -5
- package/dist/providers/minimax.js +11 -23
- package/dist/providers/mistral.d.ts +10 -11
- package/dist/providers/mistral.js +3 -14
- package/dist/providers/moonshot/messages.js +2 -7
- package/dist/providers/moonshot/responses.js +2 -7
- package/dist/providers/moonshot.d.ts +5 -5
- package/dist/providers/moonshot.js +4 -16
- package/dist/providers/openai-compatible-responses.d.ts +6 -7
- package/dist/providers/openai-compatible-responses.js +2 -8
- package/dist/providers/openai-compatible.d.ts +6 -7
- package/dist/providers/openai-compatible.js +4 -10
- package/dist/providers/openai.d.ts +4 -4
- package/dist/providers/openai.js +3 -3
- package/dist/providers/opencode.d.ts +4 -4
- package/dist/providers/opencode.js +6 -2
- package/dist/providers/openrouter.d.ts +8 -5
- package/dist/providers/openrouter.js +16 -24
- package/dist/providers/runway.d.ts +1 -1
- package/dist/providers/settings.d.ts +40 -0
- package/dist/providers/settings.js +19 -0
- package/dist/providers/togetherai.d.ts +5 -5
- package/dist/providers/togetherai.js +5 -15
- package/dist/providers/typesafe-ai.d.ts +4 -4
- package/dist/providers/typesafe-ai.js +6 -2
- package/dist/providers/venice.d.ts +4 -4
- package/dist/providers/venice.js +6 -2
- package/dist/providers/vercel-ai-gateway.d.ts +5 -5
- package/dist/providers/vercel-ai-gateway.js +15 -28
- package/dist/providers/xai.d.ts +4 -4
- package/dist/providers/xai.js +4 -12
- package/dist/providers/zai-coding-plan/messages.js +2 -7
- package/dist/providers/zai-coding-plan/responses.js +2 -7
- package/dist/providers/zai-coding-plan.d.ts +5 -5
- package/dist/providers/zai-coding-plan.js +8 -15
- package/dist/providers/zai.d.ts +5 -5
- package/dist/providers/zai.js +10 -22
- package/dist/public.d.ts +12 -0
- package/dist/public.js +5 -0
- package/dist/route/auth-options.d.ts +9 -5
- package/dist/route/auth-options.js +10 -7
- package/dist/route/client.d.ts +50 -37
- package/dist/route/client.js +42 -53
- package/dist/route/decision.d.ts +8 -8
- package/dist/route/decision.js +3 -3
- package/dist/route/executor.d.ts +5 -0
- package/dist/route/executor.js +10 -0
- package/dist/route/index.d.ts +5 -7
- package/dist/route/index.js +1 -1
- package/dist/route/media.d.ts +7 -11
- package/dist/route/media.js +22 -26
- package/dist/route/transport/http.js +6 -5
- package/dist/route/transport/websocket.js +7 -1
- package/dist/schema/errors.d.ts +16 -17
- package/dist/schema/errors.js +63 -12
- package/dist/schema/events.d.ts +2563 -2954
- package/dist/schema/events.js +54 -109
- package/dist/schema/messages.d.ts +194 -137
- package/dist/schema/messages.js +66 -83
- package/dist/schema/options.d.ts +112 -65
- package/dist/schema/options.js +52 -101
- package/dist/speech-client.d.ts +7 -7
- package/dist/speech.d.ts +306 -316
- package/dist/speech.js +16 -14
- package/dist/testing.d.ts +31 -175
- package/dist/testing.js +60 -5
- package/dist/tool-history.d.ts +1 -1
- package/dist/tool-history.js +3 -10
- package/dist/tool-runtime.d.ts +9 -2
- package/dist/tool-runtime.js +17 -31
- package/dist/tool.d.ts +39 -43
- package/dist/tool.js +16 -26
- package/dist/transcription-client.d.ts +7 -7
- package/dist/transcription.d.ts +314 -265
- package/dist/transcription.js +16 -14
- package/dist/utils/provider-codes.d.ts +3 -0
- package/dist/utils/provider-codes.js +41 -0
- package/dist/video-client.d.ts +7 -7
- package/dist/video-client.js +1 -1
- package/dist/video.d.ts +269 -287
- package/dist/video.js +16 -14
- package/package.json +9 -9
- package/dist/experimental/testing.d.ts +0 -3
- package/dist/experimental/testing.js +0 -3
- package/dist/testing/decision.d.ts +0 -16
- package/dist/testing/decision.js +0 -20
- package/dist/testing/image.d.ts +0 -14
- package/dist/testing/image.js +0 -12
- package/dist/testing/media.d.ts +0 -18
- package/dist/testing/media.js +0 -36
- package/dist/testing/script.d.ts +0 -28
- package/dist/testing/script.js +0 -60
- package/dist/testing/speech.d.ts +0 -14
- package/dist/testing/speech.js +0 -12
- package/dist/testing/transcription.d.ts +0 -14
- package/dist/testing/transcription.js +0 -12
- package/dist/testing/video.d.ts +0 -14
- package/dist/testing/video.js +0 -12
package/dist/route/client.js
CHANGED
|
@@ -10,7 +10,7 @@ import { normalizeToolHistory } from "../tool-history.js";
|
|
|
10
10
|
import { sanitizeSurrogates } from "../utils/sanitize.js";
|
|
11
11
|
import * as ProviderShared from "../protocols/shared.js";
|
|
12
12
|
import { ToolSchemaProjection } from "../protocols/utils/tool-schema.js";
|
|
13
|
-
import { AIError, CompactionResponse, CompactionCheckpointResponse, AIErrorReason,
|
|
13
|
+
import { AIError, CompactionResponse, CompactionCheckpointResponse, AIErrorReason, LLMResponse, ResponseFold, LanguageModel, Message, LLMEvent, InvalidProviderOutputError, ProviderConfigurationError, ProviderID, ToolChoice, ToolEntry, mergeGeneration, mergeRequestOptions, mergeProviderOptions, mergeTransport, withPartial, } from "../schema/index.js";
|
|
14
14
|
const makeRouteLanguageModel = (route, mapped) => {
|
|
15
15
|
const provider = route.provider ?? ("provider" in mapped ? mapped.provider : undefined);
|
|
16
16
|
if (!provider)
|
|
@@ -26,38 +26,22 @@ const makeRouteLanguageModel = (route, mapped) => {
|
|
|
26
26
|
route,
|
|
27
27
|
});
|
|
28
28
|
};
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
return {
|
|
32
|
-
...base,
|
|
33
|
-
...patch,
|
|
34
|
-
headers,
|
|
35
|
-
generation: mergeGenerationOptions(base?.generation, patch.generation),
|
|
36
|
-
providerOptions: mergeProviderOptions(base?.providerOptions, patch.providerOptions),
|
|
37
|
-
http: mergeHttpOptions(base?.http, HttpOptions.make(patch.http), headers === undefined ? undefined : new HttpOptions({ headers })),
|
|
38
|
-
};
|
|
39
|
-
};
|
|
40
|
-
const mergeHeaders = (...items) => {
|
|
41
|
-
const entries = items.flatMap((item) => item === undefined ? [] : Object.entries(item).filter((entry) => entry[1] !== undefined));
|
|
42
|
-
if (entries.length === 0)
|
|
43
|
-
return undefined;
|
|
44
|
-
return Object.fromEntries(entries);
|
|
45
|
-
};
|
|
46
|
-
export function canCompact(request, options) {
|
|
29
|
+
export function canCompact(target, options) {
|
|
30
|
+
const model = target instanceof LanguageModel ? target : target.model;
|
|
47
31
|
if (options?.mechanism === "trigger")
|
|
48
|
-
return
|
|
32
|
+
return model.route.compact?.trigger !== undefined;
|
|
49
33
|
if (options?.mechanism !== undefined && options.mechanism !== "endpoint")
|
|
50
34
|
return false;
|
|
51
|
-
return
|
|
35
|
+
return model.route.compact?.endpoint !== undefined;
|
|
52
36
|
}
|
|
53
|
-
const unsupportedCompaction = (
|
|
37
|
+
const unsupportedCompaction = (model, mechanism) => {
|
|
54
38
|
if (mechanism !== undefined && mechanism !== "endpoint" && mechanism !== "trigger")
|
|
55
39
|
return ProviderShared.invalidRequest(`Unknown compaction mechanism: ${mechanism}`);
|
|
56
40
|
return ProviderShared.unsupportedOperation({
|
|
57
41
|
operation: mechanism === "trigger" ? "compact.trigger" : "compact",
|
|
58
|
-
provider:
|
|
59
|
-
route:
|
|
60
|
-
message: `${
|
|
42
|
+
provider: model.provider,
|
|
43
|
+
route: model.route.id,
|
|
44
|
+
message: `${model.provider}/${model.route.id} does not support ${mechanism === "trigger" ? "trigger" : "explicit"} compaction`,
|
|
61
45
|
});
|
|
62
46
|
};
|
|
63
47
|
export class LLMClientService extends Context.Service()("@opencode/LLMClient") {
|
|
@@ -65,15 +49,14 @@ export class LLMClientService extends Context.Service()("@opencode/LLMClient") {
|
|
|
65
49
|
export const Service = LLMClientService;
|
|
66
50
|
const resolveRequestOptions = (request) => {
|
|
67
51
|
const messages = normalizeToolHistory(request.messages);
|
|
68
|
-
const normalized = messages === request.messages ? request :
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
});
|
|
52
|
+
const normalized = messages === request.messages ? request : { ...request, messages };
|
|
53
|
+
const options = normalized.model.options;
|
|
54
|
+
return {
|
|
55
|
+
...normalized,
|
|
56
|
+
...mergeGeneration(options, normalized),
|
|
57
|
+
providerOptions: mergeProviderOptions(options?.providerOptions, normalized.providerOptions),
|
|
58
|
+
...mergeTransport(options, normalized),
|
|
59
|
+
};
|
|
77
60
|
};
|
|
78
61
|
const streamError = (route, message, cause) => {
|
|
79
62
|
const failed = cause.reasons.find(Cause.isFailReason)?.error;
|
|
@@ -94,7 +77,7 @@ const requireTerminalEvent = (route) => (events) => Stream.suspend(() => {
|
|
|
94
77
|
// Raw events carry provider frames that may trail the terminal event.
|
|
95
78
|
if (terminal && !LLMEvent.is.raw(event))
|
|
96
79
|
return Effect.fail(ProviderShared.eventError(route, `Provider emitted ${event.type} after the terminal event`));
|
|
97
|
-
if (LLMEvent.is.finish(event)
|
|
80
|
+
if (LLMEvent.is.finish(event))
|
|
98
81
|
terminal = true;
|
|
99
82
|
return Effect.succeed(event);
|
|
100
83
|
}), Stream.onEnd(Effect.suspend(() => (terminal ? Effect.void : Effect.fail(incompleteStreamError(route))))));
|
|
@@ -122,12 +105,12 @@ function makeFromTransport(input) {
|
|
|
122
105
|
auth: routeInput.auth ?? Auth.none,
|
|
123
106
|
headers: routeInput.headers,
|
|
124
107
|
transport: routeInput.transport,
|
|
125
|
-
|
|
108
|
+
options: routeInput.options,
|
|
126
109
|
body: protocol.body,
|
|
127
110
|
supportsEffortUpdates: protocol.supportsEffortUpdates,
|
|
128
111
|
sanitizer: protocol.sanitizer,
|
|
129
112
|
with: (patch) => {
|
|
130
|
-
const { compact, id, provider, providerMetadataKey, auth, transport, endpoint, ...
|
|
113
|
+
const { compact, id, provider, providerMetadataKey, auth, transport, endpoint, ...options } = patch;
|
|
131
114
|
return build({
|
|
132
115
|
...routeInput,
|
|
133
116
|
compact: "compact" in patch ? compact : routeInput.compact,
|
|
@@ -138,7 +121,7 @@ function makeFromTransport(input) {
|
|
|
138
121
|
auth: auth ?? routeInput.auth,
|
|
139
122
|
endpoint: endpoint ? Endpoint.merge(routeInput.endpoint, endpoint) : routeInput.endpoint,
|
|
140
123
|
transport: transport ?? routeInput.transport,
|
|
141
|
-
|
|
124
|
+
options: mergeRequestOptions(route.options, options),
|
|
142
125
|
});
|
|
143
126
|
},
|
|
144
127
|
model: (input) => makeRouteLanguageModel(route, input),
|
|
@@ -148,7 +131,7 @@ function makeFromTransport(input) {
|
|
|
148
131
|
endpoint: routeInput.endpoint,
|
|
149
132
|
auth: routeInput.auth ?? Auth.none,
|
|
150
133
|
encodeBody: ProviderShared.encodeJson,
|
|
151
|
-
middleware: options?.http,
|
|
134
|
+
middleware: RequestExecutor.withFetch(request.fetch, options?.http),
|
|
152
135
|
webSocket: options?.webSocket,
|
|
153
136
|
}),
|
|
154
137
|
streamPrepared: (prepared, request, runtime, options) => {
|
|
@@ -194,7 +177,7 @@ function makeFromTransport(input) {
|
|
|
194
177
|
};
|
|
195
178
|
return route;
|
|
196
179
|
};
|
|
197
|
-
return build({ ...input,
|
|
180
|
+
return build({ ...input, options: mergeRequestOptions(input.options) });
|
|
198
181
|
}
|
|
199
182
|
export function make(input) {
|
|
200
183
|
if ("transport" in input)
|
|
@@ -210,20 +193,25 @@ export function make(input) {
|
|
|
210
193
|
auth: input.auth,
|
|
211
194
|
headers: input.headers,
|
|
212
195
|
transport: HttpTransport.httpJson({ framing: input.framing }),
|
|
213
|
-
|
|
196
|
+
options: input.options,
|
|
214
197
|
});
|
|
215
198
|
}
|
|
216
199
|
const prepareRequest = (request) => {
|
|
217
200
|
const original = resolveRequestOptions(request);
|
|
218
|
-
const sanitized =
|
|
201
|
+
const sanitized = restoreClasses({ ...sanitizeSurrogates({ ...original, model: undefined }), model: original.model });
|
|
219
202
|
// Deduplicate per sibling level; a tool and a namespace may share a name.
|
|
220
203
|
const dedupe = (tools) => [...new Map(tools.map((tool) => [`${tool.type}:${tool.name}`, tool])).values()].map((tool) => tool.type === "tool" ? tool : { ...tool, tools: dedupe(tool.tools) });
|
|
221
|
-
const resolved = applyCachePolicy(applyEffortUpdates(
|
|
204
|
+
const resolved = applyCachePolicy(applyEffortUpdates({ ...sanitized, tools: ToolSchemaProjection.tools(dedupe(sanitized.tools), sanitized.model) }));
|
|
222
205
|
const headers = resolved.model.route.headers?.({ request: resolved });
|
|
223
|
-
return headers === undefined
|
|
224
|
-
? resolved
|
|
225
|
-
: LLMRequest.update(resolved, { http: mergeHttpOptions(new HttpOptions({ headers }), resolved.http) });
|
|
206
|
+
return headers === undefined ? resolved : { ...resolved, headers: { ...headers, ...resolved.headers } };
|
|
226
207
|
};
|
|
208
|
+
// Sanitizing copies changed class instances into plain records; rebuild them so protocols see the canonical classes.
|
|
209
|
+
const restoreClasses = (request) => ({
|
|
210
|
+
...request,
|
|
211
|
+
messages: request.messages.map(Message.make),
|
|
212
|
+
tools: request.tools.map(ToolEntry.make),
|
|
213
|
+
toolChoice: request.toolChoice === undefined ? undefined : ToolChoice.make(request.toolChoice),
|
|
214
|
+
});
|
|
227
215
|
const compile = Effect.fn("LLM.compile")(function* (request, options) {
|
|
228
216
|
const references = request.messages.flatMap((message) => message.content.flatMap((part) => {
|
|
229
217
|
if (part.type === "media") {
|
|
@@ -264,12 +252,12 @@ const streamRequestWith = (runtime) => (request, options) => Stream.unwrap(Effec
|
|
|
264
252
|
return compiled.route.streamPrepared(compiled.prepared, compiled.request, runtime, options);
|
|
265
253
|
}));
|
|
266
254
|
export const generateWith = (stream) => Effect.fn("LLM.generate")(function* (request, options) {
|
|
267
|
-
let state =
|
|
268
|
-
yield* stream(request, options).pipe(Stream.runForEach((event) => Effect.sync(() => (state =
|
|
269
|
-
const response =
|
|
255
|
+
let state = ResponseFold.empty();
|
|
256
|
+
yield* stream(request, options).pipe(Stream.runForEach((event) => Effect.sync(() => (state = ResponseFold.reduce(state, event)))), Effect.mapError((error) => withPartial(error, ResponseFold.partial(state))));
|
|
257
|
+
const response = ResponseFold.complete(state);
|
|
270
258
|
if (response)
|
|
271
259
|
return response;
|
|
272
|
-
return yield* withPartial(incompleteStreamError(`${request.model.provider}/${request.model.route.id}`),
|
|
260
|
+
return yield* withPartial(incompleteStreamError(`${request.model.provider}/${request.model.route.id}`), ResponseFold.partial(state));
|
|
273
261
|
});
|
|
274
262
|
export function stream(request, options) {
|
|
275
263
|
return Stream.unwrap(Effect.gen(function* () {
|
|
@@ -281,14 +269,15 @@ export function generate(request, options) {
|
|
|
281
269
|
return yield* (yield* Service).generate(request, options);
|
|
282
270
|
});
|
|
283
271
|
}
|
|
284
|
-
|
|
272
|
+
/** Compact through the client for `options.mechanism`, failing typed when the request's route does not support it. */
|
|
273
|
+
export function compactRequest(request, options) {
|
|
285
274
|
return Effect.gen(function* () {
|
|
286
275
|
const client = yield* Service;
|
|
287
276
|
if (options?.mechanism === "trigger" && canCompact(request, options))
|
|
288
277
|
return yield* client.compact(request, options);
|
|
289
278
|
if ((options?.mechanism === undefined || options.mechanism === "endpoint") && canCompact(request))
|
|
290
279
|
return yield* client.compact(request, options);
|
|
291
|
-
return yield* unsupportedCompaction(request, options?.mechanism);
|
|
280
|
+
return yield* unsupportedCompaction(request.model, options?.mechanism);
|
|
292
281
|
});
|
|
293
282
|
}
|
|
294
283
|
export const layer = Layer.effect(Service, Effect.gen(function* () {
|
|
@@ -300,7 +289,7 @@ export const layer = Layer.effect(Service, Effect.gen(function* () {
|
|
|
300
289
|
return request.model.route.compact.trigger(prepareRequest(request), executor, options);
|
|
301
290
|
if ((options?.mechanism === undefined || options.mechanism === "endpoint") && canCompact(request))
|
|
302
291
|
return request.model.route.compact.endpoint(prepareRequest(request), executor, options);
|
|
303
|
-
return unsupportedCompaction(request, options?.mechanism);
|
|
292
|
+
return unsupportedCompaction(request.model, options?.mechanism);
|
|
304
293
|
});
|
|
305
294
|
}
|
|
306
295
|
return Service.of({
|
package/dist/route/decision.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
2
|
import type { HttpClientResponse } from "effect/http";
|
|
3
|
-
import { DecisionModel, DecisionModelCompatibility, type DecisionOptions, type
|
|
4
|
-
import {
|
|
3
|
+
import { DecisionModel, DecisionModelCompatibility, type DecisionOptions, type DecisionRequest, type DecisionResponse } from "../decision.js";
|
|
4
|
+
import { ProviderID, type HttpOptions, type AIError, type ProviderOptions } from "../schema/index.js";
|
|
5
5
|
import { Auth } from "./auth.js";
|
|
6
6
|
import { Endpoint } from "./endpoint.js";
|
|
7
7
|
import { MediaProtocol } from "./media-protocol.js";
|
|
@@ -12,11 +12,11 @@ export interface Protocol {
|
|
|
12
12
|
/** The host only takes inline data, so URL media is downloaded before `body.from`. */
|
|
13
13
|
readonly inlineMedia?: boolean;
|
|
14
14
|
readonly body: {
|
|
15
|
-
readonly from: (request:
|
|
15
|
+
readonly from: (request: DecisionRequest) => Effect.Effect<Record<string, unknown>, AIError>;
|
|
16
16
|
};
|
|
17
17
|
readonly response: {
|
|
18
18
|
readonly decode: (response: HttpClientResponse.HttpClientResponse, context: {
|
|
19
|
-
readonly request:
|
|
19
|
+
readonly request: DecisionRequest;
|
|
20
20
|
readonly providerMetadataKey: string;
|
|
21
21
|
}) => Effect.Effect<DecisionResponse, AIError>;
|
|
22
22
|
};
|
|
@@ -27,17 +27,17 @@ export interface Patch {
|
|
|
27
27
|
readonly provider?: string | ProviderID;
|
|
28
28
|
/** ProviderMetadata namespace for responses; defaults to the provider. */
|
|
29
29
|
readonly providerMetadataKey?: string;
|
|
30
|
-
readonly endpoint?: Endpoint.EndpointPatch<MediaProtocol.Body,
|
|
30
|
+
readonly endpoint?: Endpoint.EndpointPatch<MediaProtocol.Body, DecisionRequest>;
|
|
31
31
|
readonly auth?: Auth.Definition;
|
|
32
32
|
readonly headers?: Record<string, string>;
|
|
33
|
-
readonly http?: HttpOptions
|
|
33
|
+
readonly http?: HttpOptions;
|
|
34
34
|
}
|
|
35
35
|
export interface Route {
|
|
36
36
|
readonly id: string;
|
|
37
37
|
readonly provider: ProviderID;
|
|
38
38
|
readonly providerMetadataKey: string;
|
|
39
39
|
readonly protocol: Protocol;
|
|
40
|
-
readonly endpoint: Endpoint.Definition<MediaProtocol.Body,
|
|
40
|
+
readonly endpoint: Endpoint.Definition<MediaProtocol.Body, DecisionRequest>;
|
|
41
41
|
readonly auth: Auth.Definition;
|
|
42
42
|
readonly headers?: Record<string, string>;
|
|
43
43
|
readonly http?: HttpOptions;
|
|
@@ -52,7 +52,7 @@ export interface MakeInput extends Omit<Patch, "endpoint"> {
|
|
|
52
52
|
readonly id: string;
|
|
53
53
|
readonly provider: string | ProviderID;
|
|
54
54
|
readonly protocol: Protocol;
|
|
55
|
-
readonly endpoint: Endpoint.Definition<MediaProtocol.Body,
|
|
55
|
+
readonly endpoint: Endpoint.Definition<MediaProtocol.Body, DecisionRequest>;
|
|
56
56
|
}
|
|
57
57
|
export declare const make: (input: MakeInput) => Route;
|
|
58
58
|
export * as DecisionRoute from "./decision.js";
|
package/dist/route/decision.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
2
|
import { DecisionModel, DecisionModelCompatibility, } from "../decision.js";
|
|
3
|
-
import {
|
|
3
|
+
import { ProviderID } from "../schema/index.js";
|
|
4
4
|
import { Auth } from "./auth.js";
|
|
5
5
|
import { Endpoint } from "./endpoint.js";
|
|
6
6
|
import { RequestExecutorService } from "./executor-service.js";
|
|
@@ -17,7 +17,7 @@ export const make = (input) => {
|
|
|
17
17
|
endpoint: input.endpoint,
|
|
18
18
|
auth: input.auth ?? Auth.none,
|
|
19
19
|
headers: input.headers,
|
|
20
|
-
http:
|
|
20
|
+
http: input.http,
|
|
21
21
|
};
|
|
22
22
|
return {
|
|
23
23
|
...route,
|
|
@@ -28,7 +28,7 @@ export const make = (input) => {
|
|
|
28
28
|
providerMetadataKey: patch.providerMetadataKey ?? (patch.provider === undefined ? route.providerMetadataKey : undefined),
|
|
29
29
|
endpoint: patch.endpoint === undefined ? route.endpoint : Endpoint.merge(route.endpoint, patch.endpoint),
|
|
30
30
|
headers: patch.headers === undefined ? route.headers : { ...route.headers, ...patch.headers },
|
|
31
|
-
http: patch.http
|
|
31
|
+
http: patch.http ?? route.http,
|
|
32
32
|
}),
|
|
33
33
|
model: (model) => {
|
|
34
34
|
const send = transport(route);
|
package/dist/route/executor.d.ts
CHANGED
|
@@ -18,6 +18,11 @@ export declare const responseStream: (response: HttpClientResponse.HttpClientRes
|
|
|
18
18
|
export declare const stream: (executor: Interface, request: HttpClientRequest.HttpClientRequest, middleware?: HttpMiddleware) => Stream.Stream<Uint8Array, AIError>;
|
|
19
19
|
export declare const layer: Layer.Layer<Service, never, HttpClient.HttpClient>;
|
|
20
20
|
export declare const fetchLayer: Layer.Layer<import("./executor-service.js").RequestExecutorService, never, never>;
|
|
21
|
+
/**
|
|
22
|
+
* Per-call middleware that sends through `fetch` instead of the executor's HTTP client. Executor middleware and
|
|
23
|
+
* `middleware` still wrap the call, and status classification still applies.
|
|
24
|
+
*/
|
|
25
|
+
export declare const withFetch: (fetch: typeof globalThis.fetch | undefined, middleware?: HttpMiddleware) => HttpMiddleware | undefined;
|
|
21
26
|
/** Run `fn` on every request: it sees the raw response before status classification, inside middleware already on `executor`, and outside per-call middleware. */
|
|
22
27
|
export declare const middleware: (fn: HttpMiddleware, executor?: Layer.Layer<Service>) => Layer.Layer<Service>;
|
|
23
28
|
export * as RequestExecutor from "./executor.js";
|
package/dist/route/executor.js
CHANGED
|
@@ -186,6 +186,16 @@ export const layer = Layer.effect(Service, Effect.gen(function* () {
|
|
|
186
186
|
});
|
|
187
187
|
}));
|
|
188
188
|
export const fetchLayer = layer.pipe(Layer.provide(FetchHttpClient.layer));
|
|
189
|
+
/**
|
|
190
|
+
* Per-call middleware that sends through `fetch` instead of the executor's HTTP client. Executor middleware and
|
|
191
|
+
* `middleware` still wrap the call, and status classification still applies.
|
|
192
|
+
*/
|
|
193
|
+
export const withFetch = (fetch, middleware) => {
|
|
194
|
+
if (fetch === undefined)
|
|
195
|
+
return middleware;
|
|
196
|
+
const send = (request) => HttpClient.execute(request).pipe(Effect.provide(FetchHttpClient.layer), Effect.provideService(FetchHttpClient.Fetch, fetch));
|
|
197
|
+
return middleware === undefined ? send : (request) => middleware(request, send);
|
|
198
|
+
};
|
|
189
199
|
/** Run `fn` on every request: it sees the raw response before status classification, inside middleware already on `executor`, and outside per-call middleware. */
|
|
190
200
|
export const middleware = (fn, executor = fetchLayer) => Layer.effect(Service, Effect.gen(function* () {
|
|
191
201
|
const inner = yield* Service;
|
package/dist/route/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { Route, LLMClient } from "./client.js";
|
|
2
|
-
export type {
|
|
2
|
+
export type { RouteLanguageModelInput, RouteRoutedLanguageModelInput, 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";
|
|
@@ -12,10 +12,8 @@ export { HttpTransport, WebSocketTransport } from "./transport/index.js";
|
|
|
12
12
|
export * as Transport from "./transport/index.js";
|
|
13
13
|
export { ProviderShared } from "../protocols/shared.js";
|
|
14
14
|
export { classifyProviderFailure } from "../provider-error.js";
|
|
15
|
-
export {
|
|
16
|
-
export type {
|
|
15
|
+
export { mergeTransport } from "../schema/index.js";
|
|
16
|
+
export type { AuthInput, Credential, CredentialError } from "./auth.js";
|
|
17
17
|
export type { ApiKeyMode, AuthOverride, ProviderAuthOption } from "./auth-options.js";
|
|
18
|
-
export type {
|
|
19
|
-
export type {
|
|
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";
|
package/dist/route/index.js
CHANGED
|
@@ -11,4 +11,4 @@ export { HttpTransport, WebSocketTransport } from "./transport/index.js";
|
|
|
11
11
|
export * as Transport from "./transport/index.js";
|
|
12
12
|
export { ProviderShared } from "../protocols/shared.js";
|
|
13
13
|
export { classifyProviderFailure } from "../provider-error.js";
|
|
14
|
-
export {
|
|
14
|
+
export { mergeTransport } from "../schema/index.js";
|
package/dist/route/media.d.ts
CHANGED
|
@@ -4,19 +4,15 @@ import { Endpoint } from "./endpoint.js";
|
|
|
4
4
|
import type { Interface } from "./executor-service.js";
|
|
5
5
|
import { MediaProtocol } from "./media-protocol.js";
|
|
6
6
|
import { Generation } from "../generation.js";
|
|
7
|
-
import { AIError,
|
|
7
|
+
import { AIError, ProviderID, type BaseRequest, type HttpOptions, type ProviderOptions } from "../schema/index.js";
|
|
8
8
|
export type Execute = Interface["execute"];
|
|
9
9
|
/** The minimum a media request must carry for the route to build a transport request. */
|
|
10
|
-
export
|
|
11
|
-
readonly
|
|
12
|
-
|
|
13
|
-
readonly provider: ProviderID;
|
|
14
|
-
readonly http?: HttpOptions;
|
|
15
|
-
readonly providerOptions?: ProviderOptions;
|
|
16
|
-
};
|
|
17
|
-
readonly providerOptions?: ProviderOptions;
|
|
10
|
+
export type MediaRequest = BaseRequest<{
|
|
11
|
+
readonly id: string;
|
|
12
|
+
readonly provider: ProviderID;
|
|
18
13
|
readonly http?: HttpOptions;
|
|
19
|
-
|
|
14
|
+
readonly providerOptions?: ProviderOptions;
|
|
15
|
+
}>;
|
|
20
16
|
/** Deployment inputs every media model factory accepts; provider facades fill these from `configure(...)`. */
|
|
21
17
|
export interface ModelInput {
|
|
22
18
|
readonly id: string;
|
|
@@ -31,7 +27,7 @@ export interface ModelInput {
|
|
|
31
27
|
export declare const deployment: (input: {
|
|
32
28
|
readonly baseURL?: string;
|
|
33
29
|
readonly headers?: Record<string, string>;
|
|
34
|
-
readonly http?: HttpOptions
|
|
30
|
+
readonly http?: HttpOptions;
|
|
35
31
|
}, auth: Auth.Definition) => Omit<ModelInput, "id">;
|
|
36
32
|
/** One request, one response. */
|
|
37
33
|
export interface InlineRoute<Request extends MediaRequest, Response> {
|
package/dist/route/media.js
CHANGED
|
@@ -6,16 +6,11 @@ import { RequestExecutor } from "./executor.js";
|
|
|
6
6
|
import { MediaProtocol } from "./media-protocol.js";
|
|
7
7
|
import { Generation, isTerminal } from "../generation.js";
|
|
8
8
|
import { isRetryable } from "../provider-error.js";
|
|
9
|
-
import { AIError, AIErrorReason,
|
|
9
|
+
import { AIError, AIErrorReason, InvalidRequestError, ProviderID, UnsupportedOperationError, mergeProviderOptions, mergeTransport, } from "../schema/index.js";
|
|
10
10
|
import { encodeJson } from "../utils/json.js";
|
|
11
11
|
import { sanitizeSurrogates } from "../utils/sanitize.js";
|
|
12
12
|
/** A provider facade's `configure(...)` input as the `ModelInput` every media selector shares, minus the model id. */
|
|
13
|
-
export const deployment = (input, auth) => ({
|
|
14
|
-
auth,
|
|
15
|
-
baseURL: input.baseURL,
|
|
16
|
-
headers: input.headers,
|
|
17
|
-
http: HttpOptions.make(input.http),
|
|
18
|
-
});
|
|
13
|
+
export const deployment = (input, auth) => ({ auth, baseURL: input.baseURL, headers: input.headers, http: input.http });
|
|
19
14
|
/**
|
|
20
15
|
* Compose an inline media protocol with an endpoint and auth into a runnable route. The route owns the transport
|
|
21
16
|
* plumbing every media protocol would otherwise duplicate: option merging, surrogate sanitizing, unsupported-field
|
|
@@ -59,15 +54,15 @@ export const queued = (input) => {
|
|
|
59
54
|
const decodeToken = Schema.decodeUnknownEffect(protocol.token);
|
|
60
55
|
// A protocol producing a token its own codec rejects is a programmer defect, not a provider error.
|
|
61
56
|
const encodeToken = Schema.encodeSync(protocol.token);
|
|
62
|
-
const generationRoute = (token,
|
|
57
|
+
const generationRoute = (token, exchange, execute) => {
|
|
63
58
|
// Only the GET exchange retries: a decoded terminal failure (`output.ended`) can be a `ProviderInternal` too, and
|
|
64
59
|
// re-reading it would spin until the caller's deadline.
|
|
65
|
-
const poll = (operation) => transport.call("GET", operation.path(token),
|
|
60
|
+
const poll = (operation) => transport.call("GET", operation.path(token), exchange, execute).pipe(Effect.retry({ schedule: READ_RETRY, while: isRetryable }), Effect.flatMap((sent) => operation.decode(sent.response, { token, auth: sent.auth })));
|
|
66
61
|
const status = poll(protocol.status);
|
|
67
62
|
const cancel = protocol.cancel;
|
|
68
63
|
const send = cancel === undefined
|
|
69
64
|
? undefined
|
|
70
|
-
: transport.call(cancel.method, cancel.path(token),
|
|
65
|
+
: transport.call(cancel.method, cancel.path(token), exchange, execute).pipe(Effect.asVoid);
|
|
71
66
|
return {
|
|
72
67
|
status,
|
|
73
68
|
result: poll(protocol.result),
|
|
@@ -79,7 +74,7 @@ export const queued = (input) => {
|
|
|
79
74
|
const start = Effect.fn("MediaRoute.start")(function* (request, execute) {
|
|
80
75
|
const submitted = yield* transport.submit(request, { unsupported: protocol.unsupported, prepare: protocol.start.prepare, from: protocol.start.body.from }, execute);
|
|
81
76
|
const started = yield* protocol.start.decode(submitted.response, submitted.context);
|
|
82
|
-
const route = generationRoute(started.token, submitted.
|
|
77
|
+
const route = generationRoute(started.token, submitted.exchange, execute);
|
|
83
78
|
return new Generation(route, encodeToken(started.token), started.snapshot);
|
|
84
79
|
});
|
|
85
80
|
const resume = Effect.fn("MediaRoute.resume")(function* (model, raw, execute) {
|
|
@@ -89,7 +84,7 @@ export const queued = (input) => {
|
|
|
89
84
|
cause,
|
|
90
85
|
}),
|
|
91
86
|
})));
|
|
92
|
-
const route = generationRoute(token, transport.
|
|
87
|
+
const route = generationRoute(token, transport.exchange(model), execute);
|
|
93
88
|
return new Generation(route, encodeToken(token), yield* route.status);
|
|
94
89
|
});
|
|
95
90
|
return { kind: "queued", id: protocol.id, provider: protocol.provider, protocol: protocol.id, start, resume };
|
|
@@ -132,11 +127,10 @@ export const stream = (input) => {
|
|
|
132
127
|
// Transport plumbing shared by every kind
|
|
133
128
|
// ---------------------------------------------------------------------------
|
|
134
129
|
const makeTransport = (input) => {
|
|
135
|
-
const routeHttp = input.headers === undefined ? undefined : new HttpOptions({ headers: input.headers });
|
|
136
130
|
const authorize = Auth.toEffect(input.auth);
|
|
137
131
|
const baseURL = (path) => new URL(`${Endpoint.trimBaseUrl(input.endpoint.baseURL ?? "")}${path}`);
|
|
138
132
|
/** `auth` is only what `Auth` added or changed, never untouched deployment headers. */
|
|
139
|
-
const send = Effect.fn("MediaRoute.send")(function* (call, execute) {
|
|
133
|
+
const send = Effect.fn("MediaRoute.send")(function* (call, fetch, execute) {
|
|
140
134
|
const encoded = encode(call.body, call.headers);
|
|
141
135
|
const url = call.url.toString();
|
|
142
136
|
const headers = yield* authorize({
|
|
@@ -146,41 +140,43 @@ const makeTransport = (input) => {
|
|
|
146
140
|
body: encoded.text,
|
|
147
141
|
headers: encoded.headers,
|
|
148
142
|
});
|
|
149
|
-
const response = yield* execute(encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))));
|
|
143
|
+
const response = yield* execute(encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))), RequestExecutor.withFetch(fetch));
|
|
150
144
|
return {
|
|
151
145
|
response,
|
|
152
146
|
auth: Object.fromEntries(Object.entries(headers).filter(([key, value]) => encoded.headers[key] !== value)),
|
|
153
147
|
};
|
|
154
148
|
});
|
|
155
149
|
return {
|
|
156
|
-
/** Route and model overlays; `start` additionally merges the request's own
|
|
157
|
-
|
|
150
|
+
/** Route and model overlays; `start` additionally merges the request's own. */
|
|
151
|
+
exchange: (model) => mergeTransport({ headers: input.headers, http: model.http }),
|
|
158
152
|
/** POST the protocol body to the route endpoint. */
|
|
159
153
|
submit: Effect.fn("MediaRoute.submit")(function* (request, protocol, execute) {
|
|
160
154
|
yield* rejectUnsupported(input.protocol.id, input.protocol.provider, request, protocol.unsupported);
|
|
161
|
-
const http =
|
|
155
|
+
const { headers: merged, http } = mergeTransport({ headers: input.headers, http: request.model.http }, request);
|
|
156
|
+
const exchange = { headers: merged, http, fetch: request.fetch };
|
|
162
157
|
const providerOptions = mergeProviderOptions(request.model.providerOptions, request.providerOptions);
|
|
163
|
-
const headers = Headers.fromInput(
|
|
158
|
+
const headers = Headers.fromInput(merged);
|
|
164
159
|
const prepared = protocol.prepare === undefined
|
|
165
160
|
? request
|
|
166
|
-
: yield* protocol.prepare(request, (path, body) => send({ method: "POST", url: baseURL(path), headers, request, body }, execute).pipe(Effect.map((sent) => sent.response)));
|
|
161
|
+
: yield* protocol.prepare(request, (path, body) => send({ method: "POST", url: baseURL(path), headers, request, body }, request.fetch, execute).pipe(Effect.map((sent) => sent.response)));
|
|
167
162
|
// Sanitize after merging so model-level overlays are covered; the model value is restored, not sanitized.
|
|
168
163
|
const resolved = {
|
|
169
|
-
...sanitizeSurrogates({ ...prepared, http, providerOptions }),
|
|
164
|
+
...sanitizeSurrogates({ ...prepared, headers: merged, http, providerOptions }),
|
|
170
165
|
model: request.model,
|
|
171
166
|
};
|
|
172
167
|
const body = yield* protocol.from(resolved);
|
|
173
168
|
const url = withQuery(withQuery(Endpoint.render(input.endpoint, { request: resolved, body }), body.type === "multipart" ? undefined : body.query), http?.query);
|
|
174
|
-
const sent = yield* send({ method: "POST", url, headers, request: resolved, body }, execute);
|
|
175
|
-
return { response: sent.response, context: { request: resolved, body } };
|
|
169
|
+
const sent = yield* send({ method: "POST", url, headers, request: resolved, body }, request.fetch, execute);
|
|
170
|
+
return { response: sent.response, context: { request: resolved, body }, exchange };
|
|
176
171
|
}),
|
|
177
172
|
/** Bodiless follow-up call (status, result, cancel) with the same auth and headers as `submit`. */
|
|
178
|
-
call: (method, path,
|
|
173
|
+
call: (method, path, exchange, execute) => {
|
|
179
174
|
// Provider-issued absolute URLs are used as-is; everything else resolves against the base.
|
|
180
|
-
const url = withQuery(/^https?:\/\//.test(path) ? new URL(path) : baseURL(path), http?.query);
|
|
175
|
+
const url = withQuery(/^https?:\/\//.test(path) ? new URL(path) : baseURL(path), exchange.http?.query);
|
|
181
176
|
for (const [key, value] of Object.entries(input.endpoint.query ?? {}))
|
|
182
177
|
url.searchParams.set(key, value);
|
|
183
|
-
|
|
178
|
+
const headers = Headers.fromInput(exchange.headers);
|
|
179
|
+
return send({ method, url, headers, request: { http: exchange.http } }, exchange.fetch, execute);
|
|
184
180
|
},
|
|
185
181
|
};
|
|
186
182
|
};
|
|
@@ -4,7 +4,7 @@ import { Auth } from "../auth.js";
|
|
|
4
4
|
import { render as renderEndpoint } from "../endpoint.js";
|
|
5
5
|
import { Framing } from "../framing.js";
|
|
6
6
|
import * as ProviderShared from "../../protocols/shared.js";
|
|
7
|
-
import { AIError, DEFAULT_CHUNK_TIMEOUT_MS, DEFAULT_HTTP_TIMEOUT_MS, mergeJsonRecords, TransportError, } from "../../schema/index.js";
|
|
7
|
+
import { AIError, DEFAULT_CHUNK_TIMEOUT_MS, DEFAULT_HTTP_TIMEOUT_MS, mergeJsonRecords, timeoutConfig, TransportError, } from "../../schema/index.js";
|
|
8
8
|
import { RequestExecutor } from "../executor.js";
|
|
9
9
|
const bodyWithOverlay = (body, request, encodeBody) => Effect.gen(function* () {
|
|
10
10
|
if (request.http?.body === undefined)
|
|
@@ -29,7 +29,7 @@ export const jsonRequestParts = (input) => Effect.gen(function* () {
|
|
|
29
29
|
body: body.bodyText,
|
|
30
30
|
headers: Headers.fromInput({
|
|
31
31
|
...input.headers?.({ request: input.request }),
|
|
32
|
-
...input.request.
|
|
32
|
+
...input.request.headers,
|
|
33
33
|
}),
|
|
34
34
|
});
|
|
35
35
|
return { url, jsonBody: body.jsonBody, bodyText: body.bodyText, headers };
|
|
@@ -63,17 +63,18 @@ export const httpJson = (input) => ({
|
|
|
63
63
|
}),
|
|
64
64
|
});
|
|
65
65
|
const started = yield* Clock.currentTimeMillis;
|
|
66
|
+
const limits = timeoutConfig(request.timeout);
|
|
66
67
|
// Unlike the header and chunk limits, the whole-request budget has no default.
|
|
67
|
-
const total =
|
|
68
|
+
const total = limits.total ? Duration.millis(limits.total) : Duration.infinity;
|
|
68
69
|
const response = yield* runtime.http.execute(prepared.request, prepared.middleware).pipe(Effect.timeoutOrElse({
|
|
69
|
-
duration: Duration.min(timeoutDuration(
|
|
70
|
+
duration: Duration.min(timeoutDuration(limits.headers), total),
|
|
70
71
|
orElse: () => timeout("request", "Timed out waiting for response headers"),
|
|
71
72
|
}));
|
|
72
73
|
const http = RequestExecutor.responseHttp(response);
|
|
73
74
|
const remaining = Duration.subtract(total, Duration.millis((yield* Clock.currentTimeMillis) - started));
|
|
74
75
|
return {
|
|
75
76
|
frames: prepared.framing.frame(RequestExecutor.responseStream(response).pipe(Stream.timeoutOrElse({
|
|
76
|
-
duration: timeoutDuration(
|
|
77
|
+
duration: timeoutDuration(limits.chunk, DEFAULT_CHUNK_TIMEOUT_MS),
|
|
77
78
|
orElse: () => Stream.fail(timeout("read", "Timed out waiting for response data", http)),
|
|
78
79
|
}), Stream.interruptWhen(Effect.sleep(remaining).pipe(Effect.andThen(Effect.fail(timeout("read", "Timed out waiting for the response to complete", http))))))),
|
|
79
80
|
http,
|
|
@@ -32,6 +32,9 @@ const eventMessage = (event) => {
|
|
|
32
32
|
return event.message;
|
|
33
33
|
return event.type ?? "error";
|
|
34
34
|
};
|
|
35
|
+
const systemCode = (cause) => typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string"
|
|
36
|
+
? cause.code
|
|
37
|
+
: undefined;
|
|
35
38
|
const binaryMessage = (data) => {
|
|
36
39
|
if (data instanceof Uint8Array)
|
|
37
40
|
return data;
|
|
@@ -75,10 +78,13 @@ const waitOpen = (ws, input) => {
|
|
|
75
78
|
};
|
|
76
79
|
const onError = (event) => {
|
|
77
80
|
cleanup();
|
|
81
|
+
const cause = "error" in event ? (event.error ?? event) : event;
|
|
78
82
|
resume(Effect.fail(transportError(`Failed to open WebSocket: ${eventMessage(event)}`, {
|
|
79
|
-
cause
|
|
83
|
+
cause,
|
|
80
84
|
url: input.url,
|
|
81
85
|
operation: "request",
|
|
86
|
+
// Bun puts the system code (ENOTFOUND, ECONNREFUSED) on the event's error; lift it like HTTP failures do.
|
|
87
|
+
code: systemCode(cause),
|
|
82
88
|
phase: "connect",
|
|
83
89
|
delivery: "not-sent",
|
|
84
90
|
})));
|