@happyvertical/ai 0.97.0 → 0.99.0
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 +123 -3
- package/dist/chunks/{anthropic-CD9Ud7a5.js → anthropic-6ZDF32jo.js} +181 -27
- package/dist/chunks/anthropic-6ZDF32jo.js.map +1 -0
- package/dist/chunks/{bedrock-Bv1qCquH.js → bedrock-BQi3Z9jR.js} +71 -21
- package/dist/chunks/bedrock-BQi3Z9jR.js.map +1 -0
- package/dist/chunks/{bifrost-DzT2J0Lq.js → bifrost-DsI2I4ka.js} +9 -6
- package/dist/chunks/bifrost-DsI2I4ka.js.map +1 -0
- package/dist/chunks/{byteplus-modelark-BIEXaTWw.js → byteplus-modelark-Dq8AgCQD.js} +7 -5
- package/dist/chunks/byteplus-modelark-Dq8AgCQD.js.map +1 -0
- package/dist/chunks/{claude-cli-Chfnckyj.js → claude-cli-DIFxvG3c.js} +7 -5
- package/dist/chunks/claude-cli-DIFxvG3c.js.map +1 -0
- package/dist/chunks/continuation-D0NisZA1.js +209 -0
- package/dist/chunks/continuation-D0NisZA1.js.map +1 -0
- package/dist/chunks/{gateway-admin-04mvbDHC.js → gateway-audio-models-Dn7Wrc6P.js} +53 -3
- package/dist/chunks/gateway-audio-models-Dn7Wrc6P.js.map +1 -0
- package/dist/chunks/{gemini-BGwrHeGc.js → gemini-BLFwWN90.js} +131 -13
- package/dist/chunks/gemini-BLFwWN90.js.map +1 -0
- package/dist/chunks/{huggingface-mthYVbLR.js → huggingface-BuRwlABZ.js} +8 -6
- package/dist/chunks/huggingface-BuRwlABZ.js.map +1 -0
- package/dist/chunks/{litellm-xCO8QlGI.js → litellm-CpfCT6jN.js} +9 -6
- package/dist/chunks/litellm-CpfCT6jN.js.map +1 -0
- package/dist/chunks/{ollama-Bedt8Agy.js → ollama-CnrskTUg.js} +38 -7
- package/dist/chunks/ollama-CnrskTUg.js.map +1 -0
- package/dist/chunks/{openai-compat-video-B-xVe9bW.js → openai-compat-video-CJIDdkUO.js} +7 -5
- package/dist/chunks/openai-compat-video-CJIDdkUO.js.map +1 -0
- package/dist/chunks/{qwen-tts-D-UmiMMy.js → qwen-tts-PzEkWcEb.js} +2 -2
- package/dist/chunks/{qwen-tts-D-UmiMMy.js.map → qwen-tts-PzEkWcEb.js.map} +1 -1
- package/dist/chunks/rate-limit-BzWfHA0e.js +713 -0
- package/dist/chunks/rate-limit-BzWfHA0e.js.map +1 -0
- package/dist/chunks/{seevio-BJRiguLc.js → seevio-D2y5Io7C.js} +4 -5
- package/dist/chunks/seevio-D2y5Io7C.js.map +1 -0
- package/dist/chunks/{src-BUQUZK2M.js → src-CLT6r1W0.js} +36 -23
- package/dist/chunks/src-CLT6r1W0.js.map +1 -0
- package/dist/chunks/tool-messages-0ND35mYX.js +57 -0
- package/dist/chunks/tool-messages-0ND35mYX.js.map +1 -0
- package/dist/chunks/{types-BpnNcTU1.js → types-DB5W6_F-.js} +37 -5
- package/dist/chunks/types-DB5W6_F-.js.map +1 -0
- package/dist/chunks/{typesafe-B0gPZQJg.js → typesafe-CVUqQ8N1.js} +7 -5
- package/dist/chunks/typesafe-CVUqQ8N1.js.map +1 -0
- package/dist/index.js +4 -4
- package/dist/node.js +5 -5
- package/dist/shared/continuation.d.ts +51 -0
- package/dist/shared/continuation.d.ts.map +1 -0
- package/dist/shared/factory.d.ts.map +1 -1
- package/dist/shared/providers/anthropic.d.ts +53 -0
- package/dist/shared/providers/anthropic.d.ts.map +1 -1
- package/dist/shared/providers/bedrock.d.ts +13 -0
- package/dist/shared/providers/bedrock.d.ts.map +1 -1
- package/dist/shared/providers/bifrost.d.ts.map +1 -1
- package/dist/shared/providers/claude-cli.d.ts.map +1 -1
- package/dist/shared/providers/gateway-audio-models.d.ts +24 -0
- package/dist/shared/providers/gateway-audio-models.d.ts.map +1 -0
- package/dist/shared/providers/gemini.d.ts +28 -0
- package/dist/shared/providers/gemini.d.ts.map +1 -1
- package/dist/shared/providers/huggingface.d.ts.map +1 -1
- package/dist/shared/providers/litellm.d.ts.map +1 -1
- package/dist/shared/providers/ollama.d.ts.map +1 -1
- package/dist/shared/providers/openai.d.ts.map +1 -1
- package/dist/shared/providers/seevio.d.ts.map +1 -1
- package/dist/shared/providers/typesafe.d.ts.map +1 -1
- package/dist/shared/rate-limit.d.ts +19 -1
- package/dist/shared/rate-limit.d.ts.map +1 -1
- package/dist/shared/safety.d.ts.map +1 -1
- package/dist/shared/tool-messages.d.ts +27 -0
- package/dist/shared/tool-messages.d.ts.map +1 -0
- package/dist/shared/types.d.ts +191 -22
- package/dist/shared/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/chunks/anthropic-CD9Ud7a5.js.map +0 -1
- package/dist/chunks/bedrock-Bv1qCquH.js.map +0 -1
- package/dist/chunks/bifrost-DzT2J0Lq.js.map +0 -1
- package/dist/chunks/byteplus-modelark-BIEXaTWw.js.map +0 -1
- package/dist/chunks/claude-cli-Chfnckyj.js.map +0 -1
- package/dist/chunks/gateway-admin-04mvbDHC.js.map +0 -1
- package/dist/chunks/gemini-BGwrHeGc.js.map +0 -1
- package/dist/chunks/huggingface-mthYVbLR.js.map +0 -1
- package/dist/chunks/litellm-xCO8QlGI.js.map +0 -1
- package/dist/chunks/ollama-Bedt8Agy.js.map +0 -1
- package/dist/chunks/openai-compat-video-B-xVe9bW.js.map +0 -1
- package/dist/chunks/rate-limit-BVW_1Tey.js +0 -202
- package/dist/chunks/rate-limit-BVW_1Tey.js.map +0 -1
- package/dist/chunks/safety-BKswBoqy.js +0 -279
- package/dist/chunks/safety-BKswBoqy.js.map +0 -1
- package/dist/chunks/seevio-BJRiguLc.js.map +0 -1
- package/dist/chunks/src-BUQUZK2M.js.map +0 -1
- package/dist/chunks/types-BpnNcTU1.js.map +0 -1
- package/dist/chunks/typesafe-B0gPZQJg.js.map +0 -1
|
@@ -1,279 +0,0 @@
|
|
|
1
|
-
import { t as AIError } from "./types-BpnNcTU1.js";
|
|
2
|
-
//#region src/shared/safety.ts
|
|
3
|
-
var DEFAULT_AI_TIMEOUT_MS = 12e4;
|
|
4
|
-
var DEFAULT_AI_MAX_RETRIES = 0;
|
|
5
|
-
var DEFAULT_AI_GENERATION_LIMITS = Object.freeze({
|
|
6
|
-
maxOutputTokens: 4096,
|
|
7
|
-
maxReasoningTokens: 1024,
|
|
8
|
-
maxImagesPerRequest: 1,
|
|
9
|
-
onExceeded: "error"
|
|
10
|
-
});
|
|
11
|
-
function positiveInteger(value, fallback, field) {
|
|
12
|
-
if (value === void 0) return fallback;
|
|
13
|
-
if (!Number.isFinite(value) || value <= 0) throw new AIError(`${field} must be a positive finite number`, "AI_LIMIT_INVALID");
|
|
14
|
-
return Math.trunc(value);
|
|
15
|
-
}
|
|
16
|
-
function normalizeBaseAIOptions(options) {
|
|
17
|
-
const configuredLimits = options.generationLimits || {};
|
|
18
|
-
const generationLimits = {
|
|
19
|
-
maxOutputTokens: positiveInteger(configuredLimits.maxOutputTokens, DEFAULT_AI_GENERATION_LIMITS.maxOutputTokens, "generationLimits.maxOutputTokens"),
|
|
20
|
-
maxReasoningTokens: positiveInteger(configuredLimits.maxReasoningTokens, DEFAULT_AI_GENERATION_LIMITS.maxReasoningTokens, "generationLimits.maxReasoningTokens"),
|
|
21
|
-
maxImagesPerRequest: positiveInteger(configuredLimits.maxImagesPerRequest, DEFAULT_AI_GENERATION_LIMITS.maxImagesPerRequest, "generationLimits.maxImagesPerRequest"),
|
|
22
|
-
onExceeded: configuredLimits.onExceeded || DEFAULT_AI_GENERATION_LIMITS.onExceeded
|
|
23
|
-
};
|
|
24
|
-
if (!["error", "clamp"].includes(generationLimits.onExceeded)) throw new AIError("generationLimits.onExceeded must be \"error\" or \"clamp\"", "AI_LIMIT_INVALID");
|
|
25
|
-
return {
|
|
26
|
-
...options,
|
|
27
|
-
timeout: positiveInteger(options.timeout, DEFAULT_AI_TIMEOUT_MS, "timeout"),
|
|
28
|
-
maxRetries: (() => {
|
|
29
|
-
if (options.maxRetries === void 0) return 0;
|
|
30
|
-
if (!Number.isFinite(options.maxRetries) || options.maxRetries < 0) throw new AIError("maxRetries must be a non-negative finite number", "AI_LIMIT_INVALID");
|
|
31
|
-
return Math.trunc(options.maxRetries);
|
|
32
|
-
})(),
|
|
33
|
-
generationLimits
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
function reasoningTokensForEffort(effort) {
|
|
37
|
-
switch (effort) {
|
|
38
|
-
case false:
|
|
39
|
-
case "none": return 0;
|
|
40
|
-
case "minimal": return 1024;
|
|
41
|
-
case "low": return 2048;
|
|
42
|
-
case "medium": return 4096;
|
|
43
|
-
case "high": return 8192;
|
|
44
|
-
default: return;
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
function enforceLimit(requested, limit, behavior, label, provider, model) {
|
|
48
|
-
if (!Number.isFinite(requested) || requested < 0) throw new AIError(`${label} must be a non-negative finite number`, "AI_LIMIT_INVALID", provider, model);
|
|
49
|
-
const normalized = Math.trunc(requested);
|
|
50
|
-
if (normalized <= limit) return normalized;
|
|
51
|
-
if (behavior === "clamp") return limit;
|
|
52
|
-
throw new AIError(`${label} ${normalized} exceeds configured ceiling ${limit}`, "AI_LIMIT_EXCEEDED", provider, model);
|
|
53
|
-
}
|
|
54
|
-
function normalizeChatOptions(providerOptions, options, provider, model) {
|
|
55
|
-
const limits = normalizeBaseAIOptions(providerOptions).generationLimits;
|
|
56
|
-
const requestedOutput = options.maxTokens ?? limits.maxOutputTokens;
|
|
57
|
-
const legacyEffort = options.thinkingLevel ?? providerOptions.thinkingLevel;
|
|
58
|
-
const requestedReasoning = options.reasoning !== void 0 || legacyEffort !== void 0 || options.includeThoughts === true ? options.reasoning?.maxTokens ?? reasoningTokensForEffort(options.reasoning?.effort ?? legacyEffort) ?? limits.maxReasoningTokens : 0;
|
|
59
|
-
return {
|
|
60
|
-
...options,
|
|
61
|
-
maxTokens: enforceLimit(requestedOutput, limits.maxOutputTokens, limits.onExceeded, "maxTokens", provider, model),
|
|
62
|
-
reasoning: {
|
|
63
|
-
...options.reasoning,
|
|
64
|
-
maxTokens: enforceLimit(requestedReasoning, limits.maxReasoningTokens, limits.onExceeded, "reasoning.maxTokens", provider, model),
|
|
65
|
-
includeThoughts: options.reasoning?.includeThoughts ?? options.includeThoughts
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
function normalizeImageGenerationOptions(providerOptions, options, provider, model) {
|
|
70
|
-
const limits = normalizeBaseAIOptions(providerOptions).generationLimits;
|
|
71
|
-
return {
|
|
72
|
-
...options,
|
|
73
|
-
n: enforceLimit(options.n ?? 1, limits.maxImagesPerRequest, limits.onExceeded, "n", provider, model)
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
function prepareRequestControls(providerOptions, requestOptions = {}) {
|
|
77
|
-
const normalized = normalizeBaseAIOptions(providerOptions);
|
|
78
|
-
const timeout = positiveInteger(requestOptions.timeout, normalized.timeout, "timeout");
|
|
79
|
-
const controller = new AbortController();
|
|
80
|
-
let timedOut = false;
|
|
81
|
-
const abortFromCaller = () => controller.abort(requestOptions.signal?.reason);
|
|
82
|
-
if (requestOptions.signal?.aborted) abortFromCaller();
|
|
83
|
-
else requestOptions.signal?.addEventListener("abort", abortFromCaller, { once: true });
|
|
84
|
-
const timer = setTimeout(() => {
|
|
85
|
-
timedOut = true;
|
|
86
|
-
controller.abort(/* @__PURE__ */ new Error(`AI request timed out after ${timeout}ms`));
|
|
87
|
-
}, timeout);
|
|
88
|
-
return {
|
|
89
|
-
signal: controller.signal,
|
|
90
|
-
timeout,
|
|
91
|
-
didTimeout: () => timedOut,
|
|
92
|
-
cleanup: () => {
|
|
93
|
-
clearTimeout(timer);
|
|
94
|
-
requestOptions.signal?.removeEventListener("abort", abortFromCaller);
|
|
95
|
-
}
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
function mergeTags(providerOptions, callTags) {
|
|
99
|
-
return providerOptions.usageTags || callTags ? {
|
|
100
|
-
...providerOptions.usageTags,
|
|
101
|
-
...callTags
|
|
102
|
-
} : void 0;
|
|
103
|
-
}
|
|
104
|
-
function emitRequestEvent(providerOptions, event) {
|
|
105
|
-
if (!providerOptions.onRequest) return;
|
|
106
|
-
try {
|
|
107
|
-
providerOptions.onRequest({
|
|
108
|
-
...event,
|
|
109
|
-
tags: mergeTags(providerOptions, event.tags)
|
|
110
|
-
});
|
|
111
|
-
} catch {}
|
|
112
|
-
}
|
|
113
|
-
function classifyRequestFailure(error, didTimeout = false) {
|
|
114
|
-
const code = error instanceof AIError ? error.code : void 0;
|
|
115
|
-
if (code === "AI_LIMIT_EXCEEDED" || code === "AI_LIMIT_INVALID") return {
|
|
116
|
-
status: "rejected",
|
|
117
|
-
errorCode: code
|
|
118
|
-
};
|
|
119
|
-
if (didTimeout || code === "AI_TIMEOUT" || code === "TIMEOUT" || code === "REQUEST_TIMEOUT") return {
|
|
120
|
-
status: "timed_out",
|
|
121
|
-
errorCode: code || "AI_TIMEOUT"
|
|
122
|
-
};
|
|
123
|
-
if (error instanceof Error && error.name === "AbortError") return {
|
|
124
|
-
status: "aborted",
|
|
125
|
-
errorCode: "ABORTED"
|
|
126
|
-
};
|
|
127
|
-
if (code === "AI_ABORTED" || code === "REQUEST_ABORTED") return {
|
|
128
|
-
status: "aborted",
|
|
129
|
-
errorCode: code
|
|
130
|
-
};
|
|
131
|
-
return {
|
|
132
|
-
status: "failed",
|
|
133
|
-
errorCode: code || (error instanceof Error ? error.name : void 0)
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
function requestEventBase(options) {
|
|
137
|
-
const normalized = normalizeBaseAIOptions(options.providerOptions);
|
|
138
|
-
return {
|
|
139
|
-
provider: options.provider,
|
|
140
|
-
model: options.model,
|
|
141
|
-
operation: options.operation,
|
|
142
|
-
attempts: normalized.maxRetries + 1,
|
|
143
|
-
requestedMaxOutputTokens: options.operation === "decide" ? void 0 : options.callOptions?.maxTokens,
|
|
144
|
-
effectiveMaxOutputTokens: options.operation === "decide" || options.operation === "generateImage" || VIDEO_GENERATION_OPERATIONS.has(options.operation) ? void 0 : options.effectiveMaxOutputTokens ?? normalized.generationLimits.maxOutputTokens,
|
|
145
|
-
tags: options.callOptions?.usageTags
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
var OBSERVED_OPERATIONS = /* @__PURE__ */ new Set([
|
|
149
|
-
"decide",
|
|
150
|
-
"chat",
|
|
151
|
-
"complete",
|
|
152
|
-
"message",
|
|
153
|
-
"describeImage",
|
|
154
|
-
"generateImage",
|
|
155
|
-
"stream",
|
|
156
|
-
"submitVideoGenerationJob",
|
|
157
|
-
"getVideoGenerationJob",
|
|
158
|
-
"fetchVideoGenerationResult",
|
|
159
|
-
"cancelVideoGenerationJob"
|
|
160
|
-
]);
|
|
161
|
-
/**
|
|
162
|
-
* `getVideoGenerationJob` / `fetchVideoGenerationResult` /
|
|
163
|
-
* `cancelVideoGenerationJob` take a `VideoGenerationJob` handle as their
|
|
164
|
-
* first (and only) argument rather than a chat-shaped `options` object as
|
|
165
|
-
* the second argument. The handle still carries a `model` field, so
|
|
166
|
-
* `callOptionsFor` reads it from the same position as `submitVideoGenerationJob`'s
|
|
167
|
-
* `options` (index 0) rather than index 1.
|
|
168
|
-
*/
|
|
169
|
-
var VIDEO_HANDLE_OPERATIONS = /* @__PURE__ */ new Set([
|
|
170
|
-
"getVideoGenerationJob",
|
|
171
|
-
"fetchVideoGenerationResult",
|
|
172
|
-
"cancelVideoGenerationJob"
|
|
173
|
-
]);
|
|
174
|
-
var VIDEO_GENERATION_OPERATIONS = /* @__PURE__ */ new Set(["submitVideoGenerationJob", ...VIDEO_HANDLE_OPERATIONS]);
|
|
175
|
-
function callOptionsFor(operation, args) {
|
|
176
|
-
const value = args[operation === "decide" ? 1 : operation === "describeImage" ? 2 : operation === "submitVideoGenerationJob" || VIDEO_HANDLE_OPERATIONS.has(operation) ? 0 : 1];
|
|
177
|
-
return value && typeof value === "object" ? value : void 0;
|
|
178
|
-
}
|
|
179
|
-
function providerName(options) {
|
|
180
|
-
return options.type || "openai";
|
|
181
|
-
}
|
|
182
|
-
function effectiveOutputTokens(operation, providerOptions, callOptions) {
|
|
183
|
-
if (operation === "decide" || operation === "generateImage" || VIDEO_GENERATION_OPERATIONS.has(operation)) {
|
|
184
|
-
if (operation === "generateImage") normalizeImageGenerationOptions(providerOptions, callOptions || {}, providerName(providerOptions), callOptions?.model);
|
|
185
|
-
return;
|
|
186
|
-
}
|
|
187
|
-
return normalizeChatOptions(providerOptions, callOptions || {}, providerName(providerOptions), callOptions?.model || providerOptions.defaultModel).maxTokens;
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
|
-
* Wrap a public provider instance with prompt-free lifecycle observation.
|
|
191
|
-
* Provider adapters still enforce limits internally so direct construction is
|
|
192
|
-
* protected; this wrapper adds one terminal event to the public getAI() path.
|
|
193
|
-
*/
|
|
194
|
-
function createObservedAI(client, providerOptions) {
|
|
195
|
-
if (!providerOptions.onRequest) return client;
|
|
196
|
-
return new Proxy(client, { get(target, property, receiver) {
|
|
197
|
-
const value = Reflect.get(target, property, receiver);
|
|
198
|
-
if (typeof property !== "string" || typeof value !== "function" || !OBSERVED_OPERATIONS.has(property)) return typeof value === "function" ? value.bind(target) : value;
|
|
199
|
-
const operation = property;
|
|
200
|
-
if (operation === "stream") return async function* (...args) {
|
|
201
|
-
const startedAt = Date.now();
|
|
202
|
-
const callOptions = callOptionsFor(operation, args);
|
|
203
|
-
let base;
|
|
204
|
-
try {
|
|
205
|
-
base = requestEventBase({
|
|
206
|
-
providerOptions,
|
|
207
|
-
provider: providerName(providerOptions),
|
|
208
|
-
model: callOptions?.model || providerOptions.defaultModel || "unknown",
|
|
209
|
-
operation,
|
|
210
|
-
callOptions,
|
|
211
|
-
effectiveMaxOutputTokens: effectiveOutputTokens(operation, providerOptions, callOptions)
|
|
212
|
-
});
|
|
213
|
-
const iterable = Reflect.apply(value, target, args);
|
|
214
|
-
for await (const chunk of iterable) yield chunk;
|
|
215
|
-
emitRequestEvent(providerOptions, {
|
|
216
|
-
...base,
|
|
217
|
-
status: "succeeded",
|
|
218
|
-
duration: Date.now() - startedAt
|
|
219
|
-
});
|
|
220
|
-
} catch (error) {
|
|
221
|
-
const failure = classifyRequestFailure(error);
|
|
222
|
-
base ||= requestEventBase({
|
|
223
|
-
providerOptions,
|
|
224
|
-
provider: providerName(providerOptions),
|
|
225
|
-
model: callOptions?.model || providerOptions.defaultModel || "unknown",
|
|
226
|
-
operation,
|
|
227
|
-
callOptions
|
|
228
|
-
});
|
|
229
|
-
emitRequestEvent(providerOptions, {
|
|
230
|
-
...base,
|
|
231
|
-
...failure,
|
|
232
|
-
duration: Date.now() - startedAt
|
|
233
|
-
});
|
|
234
|
-
throw error;
|
|
235
|
-
}
|
|
236
|
-
};
|
|
237
|
-
return async (...args) => {
|
|
238
|
-
const startedAt = Date.now();
|
|
239
|
-
const callOptions = callOptionsFor(operation, args);
|
|
240
|
-
let base;
|
|
241
|
-
try {
|
|
242
|
-
base = requestEventBase({
|
|
243
|
-
providerOptions,
|
|
244
|
-
provider: providerName(providerOptions),
|
|
245
|
-
model: callOptions?.model || providerOptions.defaultModel || "unknown",
|
|
246
|
-
operation,
|
|
247
|
-
callOptions,
|
|
248
|
-
effectiveMaxOutputTokens: effectiveOutputTokens(operation, providerOptions, callOptions)
|
|
249
|
-
});
|
|
250
|
-
const result = await Reflect.apply(value, target, args);
|
|
251
|
-
emitRequestEvent(providerOptions, {
|
|
252
|
-
...base,
|
|
253
|
-
status: "succeeded",
|
|
254
|
-
duration: Date.now() - startedAt
|
|
255
|
-
});
|
|
256
|
-
return result;
|
|
257
|
-
} catch (error) {
|
|
258
|
-
const failure = classifyRequestFailure(error);
|
|
259
|
-
base ||= requestEventBase({
|
|
260
|
-
providerOptions,
|
|
261
|
-
provider: providerName(providerOptions),
|
|
262
|
-
model: callOptions?.model || providerOptions.defaultModel || "unknown",
|
|
263
|
-
operation,
|
|
264
|
-
callOptions
|
|
265
|
-
});
|
|
266
|
-
emitRequestEvent(providerOptions, {
|
|
267
|
-
...base,
|
|
268
|
-
...failure,
|
|
269
|
-
duration: Date.now() - startedAt
|
|
270
|
-
});
|
|
271
|
-
throw error;
|
|
272
|
-
}
|
|
273
|
-
};
|
|
274
|
-
} });
|
|
275
|
-
}
|
|
276
|
-
//#endregion
|
|
277
|
-
export { normalizeBaseAIOptions as a, prepareRequestControls as c, createObservedAI as i, DEFAULT_AI_MAX_RETRIES as n, normalizeChatOptions as o, DEFAULT_AI_TIMEOUT_MS as r, normalizeImageGenerationOptions as s, DEFAULT_AI_GENERATION_LIMITS as t };
|
|
278
|
-
|
|
279
|
-
//# sourceMappingURL=safety-BKswBoqy.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"safety-BKswBoqy.js","names":[],"sources":["../../src/shared/safety.ts"],"sourcesContent":["import type {\n AIGenerationLimits,\n AIInterface,\n AIReasoningOptions,\n AIRequestControls,\n AIRequestEvent,\n AIRequestOperation,\n AIRequestStatus,\n BaseAIOptions,\n ChatOptions,\n ImageGenerationOptions,\n} from './types';\nimport { AIError } from './types';\n\nexport const DEFAULT_AI_TIMEOUT_MS = 120_000;\nexport const DEFAULT_AI_MAX_RETRIES = 0;\n\nexport const DEFAULT_AI_GENERATION_LIMITS: Readonly<AIGenerationLimits> =\n Object.freeze({\n maxOutputTokens: 4096,\n maxReasoningTokens: 1024,\n maxImagesPerRequest: 1,\n onExceeded: 'error',\n });\n\nexport interface NormalizedBaseAIOptions extends BaseAIOptions {\n timeout: number;\n maxRetries: number;\n generationLimits: AIGenerationLimits;\n}\n\nexport interface PreparedRequestControls {\n signal: AbortSignal;\n timeout: number;\n cleanup(): void;\n didTimeout(): boolean;\n}\n\nfunction positiveInteger(\n value: number | undefined,\n fallback: number,\n field: string,\n): number {\n if (value === undefined) return fallback;\n if (!Number.isFinite(value) || value <= 0) {\n throw new AIError(\n `${field} must be a positive finite number`,\n 'AI_LIMIT_INVALID',\n );\n }\n return Math.trunc(value);\n}\n\nexport function normalizeBaseAIOptions<T extends BaseAIOptions>(\n options: T,\n): T & NormalizedBaseAIOptions {\n const configuredLimits = options.generationLimits || {};\n const generationLimits: AIGenerationLimits = {\n maxOutputTokens: positiveInteger(\n configuredLimits.maxOutputTokens,\n DEFAULT_AI_GENERATION_LIMITS.maxOutputTokens,\n 'generationLimits.maxOutputTokens',\n ),\n maxReasoningTokens: positiveInteger(\n configuredLimits.maxReasoningTokens,\n DEFAULT_AI_GENERATION_LIMITS.maxReasoningTokens,\n 'generationLimits.maxReasoningTokens',\n ),\n maxImagesPerRequest: positiveInteger(\n configuredLimits.maxImagesPerRequest,\n DEFAULT_AI_GENERATION_LIMITS.maxImagesPerRequest,\n 'generationLimits.maxImagesPerRequest',\n ),\n onExceeded:\n configuredLimits.onExceeded || DEFAULT_AI_GENERATION_LIMITS.onExceeded,\n };\n\n if (!['error', 'clamp'].includes(generationLimits.onExceeded)) {\n throw new AIError(\n 'generationLimits.onExceeded must be \"error\" or \"clamp\"',\n 'AI_LIMIT_INVALID',\n );\n }\n\n return {\n ...options,\n timeout: positiveInteger(options.timeout, DEFAULT_AI_TIMEOUT_MS, 'timeout'),\n maxRetries: (() => {\n if (options.maxRetries === undefined) return DEFAULT_AI_MAX_RETRIES;\n if (!Number.isFinite(options.maxRetries) || options.maxRetries < 0) {\n throw new AIError(\n 'maxRetries must be a non-negative finite number',\n 'AI_LIMIT_INVALID',\n );\n }\n return Math.trunc(options.maxRetries);\n })(),\n generationLimits,\n };\n}\n\nfunction reasoningTokensForEffort(\n effort: AIReasoningOptions['effort'] | false | undefined,\n): number | undefined {\n switch (effort) {\n case false:\n case 'none':\n return 0;\n case 'minimal':\n return 1024;\n case 'low':\n return 2048;\n case 'medium':\n return 4096;\n case 'high':\n return 8192;\n default:\n return undefined;\n }\n}\n\nfunction enforceLimit(\n requested: number,\n limit: number,\n behavior: AIGenerationLimits['onExceeded'],\n label: string,\n provider?: string,\n model?: string,\n): number {\n if (!Number.isFinite(requested) || requested < 0) {\n throw new AIError(\n `${label} must be a non-negative finite number`,\n 'AI_LIMIT_INVALID',\n provider,\n model,\n );\n }\n const normalized = Math.trunc(requested);\n if (normalized <= limit) return normalized;\n if (behavior === 'clamp') return limit;\n throw new AIError(\n `${label} ${normalized} exceeds configured ceiling ${limit}`,\n 'AI_LIMIT_EXCEEDED',\n provider,\n model,\n );\n}\n\nexport function normalizeChatOptions<\n T extends AIRequestControls & {\n maxTokens?: number;\n thinkingLevel?: ChatOptions['thinkingLevel'];\n includeThoughts?: boolean;\n },\n>(\n providerOptions: BaseAIOptions,\n options: T,\n provider?: string,\n model?: string,\n): T & { maxTokens: number; reasoning: AIReasoningOptions } {\n const normalizedProvider = normalizeBaseAIOptions(providerOptions);\n const limits = normalizedProvider.generationLimits;\n const requestedOutput = options.maxTokens ?? limits.maxOutputTokens;\n const legacyEffort =\n options.thinkingLevel ??\n (\n providerOptions as BaseAIOptions & {\n thinkingLevel?: ChatOptions['thinkingLevel'];\n }\n ).thinkingLevel;\n const reasoningWasRequested =\n options.reasoning !== undefined ||\n legacyEffort !== undefined ||\n options.includeThoughts === true;\n const requestedReasoning = reasoningWasRequested\n ? (options.reasoning?.maxTokens ??\n reasoningTokensForEffort(options.reasoning?.effort ?? legacyEffort) ??\n limits.maxReasoningTokens)\n : 0;\n\n return {\n ...options,\n maxTokens: enforceLimit(\n requestedOutput,\n limits.maxOutputTokens,\n limits.onExceeded,\n 'maxTokens',\n provider,\n model,\n ),\n reasoning: {\n ...options.reasoning,\n maxTokens: enforceLimit(\n requestedReasoning,\n limits.maxReasoningTokens,\n limits.onExceeded,\n 'reasoning.maxTokens',\n provider,\n model,\n ),\n includeThoughts:\n options.reasoning?.includeThoughts ?? options.includeThoughts,\n },\n };\n}\n\nexport function normalizeImageGenerationOptions<\n T extends ImageGenerationOptions,\n>(\n providerOptions: BaseAIOptions,\n options: T,\n provider?: string,\n model?: string,\n): T & { n: number } {\n const normalizedProvider = normalizeBaseAIOptions(providerOptions);\n const limits = normalizedProvider.generationLimits;\n return {\n ...options,\n n: enforceLimit(\n options.n ?? 1,\n limits.maxImagesPerRequest,\n limits.onExceeded,\n 'n',\n provider,\n model,\n ),\n };\n}\n\nexport function prepareRequestControls(\n providerOptions: BaseAIOptions,\n requestOptions: AIRequestControls = {},\n): PreparedRequestControls {\n const normalized = normalizeBaseAIOptions(providerOptions);\n const timeout = positiveInteger(\n requestOptions.timeout,\n normalized.timeout,\n 'timeout',\n );\n const controller = new AbortController();\n let timedOut = false;\n\n const abortFromCaller = () => controller.abort(requestOptions.signal?.reason);\n if (requestOptions.signal?.aborted) {\n abortFromCaller();\n } else {\n requestOptions.signal?.addEventListener('abort', abortFromCaller, {\n once: true,\n });\n }\n\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort(new Error(`AI request timed out after ${timeout}ms`));\n }, timeout);\n\n return {\n signal: controller.signal,\n timeout,\n didTimeout: () => timedOut,\n cleanup: () => {\n clearTimeout(timer);\n requestOptions.signal?.removeEventListener('abort', abortFromCaller);\n },\n };\n}\n\nfunction mergeTags(\n providerOptions: BaseAIOptions,\n callTags?: Record<string, string>,\n): Record<string, string> | undefined {\n return providerOptions.usageTags || callTags\n ? { ...providerOptions.usageTags, ...callTags }\n : undefined;\n}\n\nexport function emitRequestEvent(\n providerOptions: BaseAIOptions,\n event: Omit<AIRequestEvent, 'tags'> & {\n tags?: Record<string, string>;\n },\n): void {\n if (!providerOptions.onRequest) return;\n try {\n providerOptions.onRequest({\n ...event,\n tags: mergeTags(providerOptions, event.tags),\n });\n } catch {\n // Consumer telemetry must never affect an AI request.\n }\n}\n\nexport function classifyRequestFailure(\n error: unknown,\n didTimeout = false,\n): { status: AIRequestStatus; errorCode?: string } {\n const code = error instanceof AIError ? error.code : undefined;\n if (code === 'AI_LIMIT_EXCEEDED' || code === 'AI_LIMIT_INVALID') {\n return { status: 'rejected', errorCode: code };\n }\n if (\n didTimeout ||\n code === 'AI_TIMEOUT' ||\n code === 'TIMEOUT' ||\n code === 'REQUEST_TIMEOUT'\n ) {\n return { status: 'timed_out', errorCode: code || 'AI_TIMEOUT' };\n }\n if (error instanceof Error && error.name === 'AbortError') {\n return { status: 'aborted', errorCode: 'ABORTED' };\n }\n if (code === 'AI_ABORTED' || code === 'REQUEST_ABORTED') {\n return { status: 'aborted', errorCode: code };\n }\n return {\n status: 'failed',\n errorCode: code || (error instanceof Error ? error.name : undefined),\n };\n}\n\nexport function requestEventBase(options: {\n providerOptions: BaseAIOptions;\n provider: string;\n model: string;\n operation: AIRequestOperation;\n callOptions?: { maxTokens?: number; usageTags?: Record<string, string> };\n effectiveMaxOutputTokens?: number;\n}): Omit<AIRequestEvent, 'status' | 'duration'> & {\n tags?: Record<string, string>;\n} {\n const normalized = normalizeBaseAIOptions(options.providerOptions);\n return {\n provider: options.provider,\n model: options.model,\n operation: options.operation,\n attempts: normalized.maxRetries + 1,\n requestedMaxOutputTokens:\n options.operation === 'decide'\n ? undefined\n : options.callOptions?.maxTokens,\n effectiveMaxOutputTokens:\n options.operation === 'decide' ||\n options.operation === 'generateImage' ||\n VIDEO_GENERATION_OPERATIONS.has(options.operation)\n ? undefined\n : (options.effectiveMaxOutputTokens ??\n normalized.generationLimits.maxOutputTokens),\n tags: options.callOptions?.usageTags,\n };\n}\n\nconst OBSERVED_OPERATIONS = new Set<AIRequestOperation>([\n 'decide',\n 'chat',\n 'complete',\n 'message',\n 'describeImage',\n 'generateImage',\n 'stream',\n 'submitVideoGenerationJob',\n 'getVideoGenerationJob',\n 'fetchVideoGenerationResult',\n 'cancelVideoGenerationJob',\n]);\n\n/**\n * `getVideoGenerationJob` / `fetchVideoGenerationResult` /\n * `cancelVideoGenerationJob` take a `VideoGenerationJob` handle as their\n * first (and only) argument rather than a chat-shaped `options` object as\n * the second argument. The handle still carries a `model` field, so\n * `callOptionsFor` reads it from the same position as `submitVideoGenerationJob`'s\n * `options` (index 0) rather than index 1.\n */\nconst VIDEO_HANDLE_OPERATIONS = new Set<AIRequestOperation>([\n 'getVideoGenerationJob',\n 'fetchVideoGenerationResult',\n 'cancelVideoGenerationJob',\n]);\n\nconst VIDEO_GENERATION_OPERATIONS = new Set<AIRequestOperation>([\n 'submitVideoGenerationJob',\n ...VIDEO_HANDLE_OPERATIONS,\n]);\n\nfunction callOptionsFor(\n operation: AIRequestOperation,\n args: unknown[],\n):\n | (AIRequestControls & {\n model?: string;\n maxTokens?: number;\n usageTags?: Record<string, string>;\n })\n | undefined {\n const index =\n operation === 'decide'\n ? 1\n : operation === 'describeImage'\n ? 2\n : operation === 'submitVideoGenerationJob' ||\n VIDEO_HANDLE_OPERATIONS.has(operation)\n ? 0\n : 1;\n const value = args[index];\n return value && typeof value === 'object'\n ? (value as AIRequestControls & {\n model?: string;\n maxTokens?: number;\n usageTags?: Record<string, string>;\n })\n : undefined;\n}\n\nfunction providerName(options: BaseAIOptions): string {\n const configured = (options as BaseAIOptions & { type?: string }).type;\n return configured || 'openai';\n}\n\nfunction effectiveOutputTokens(\n operation: AIRequestOperation,\n providerOptions: BaseAIOptions,\n callOptions:\n | (AIRequestControls & {\n model?: string;\n maxTokens?: number;\n n?: number;\n })\n | undefined,\n): number | undefined {\n if (\n operation === 'decide' ||\n operation === 'generateImage' ||\n VIDEO_GENERATION_OPERATIONS.has(operation)\n ) {\n // maxTokens/reasoning concepts don't apply to video-generation jobs;\n // avoid attaching a misleading chat-shaped token ceiling to the event.\n if (operation === 'generateImage') {\n normalizeImageGenerationOptions(\n providerOptions,\n callOptions || {},\n providerName(providerOptions),\n callOptions?.model,\n );\n }\n return undefined;\n }\n\n return normalizeChatOptions(\n providerOptions,\n callOptions || {},\n providerName(providerOptions),\n callOptions?.model || providerOptions.defaultModel,\n ).maxTokens;\n}\n\n/**\n * Wrap a public provider instance with prompt-free lifecycle observation.\n * Provider adapters still enforce limits internally so direct construction is\n * protected; this wrapper adds one terminal event to the public getAI() path.\n */\nexport function createObservedAI<T extends AIInterface>(\n client: T,\n providerOptions: BaseAIOptions,\n): T {\n if (!providerOptions.onRequest) return client;\n\n return new Proxy(client, {\n get(target, property, receiver) {\n const value = Reflect.get(target, property, receiver);\n if (\n typeof property !== 'string' ||\n typeof value !== 'function' ||\n !OBSERVED_OPERATIONS.has(property as AIRequestOperation)\n ) {\n return typeof value === 'function' ? value.bind(target) : value;\n }\n\n const operation = property as AIRequestOperation;\n if (operation === 'stream') {\n return async function* (...args: unknown[]) {\n const startedAt = Date.now();\n const callOptions = callOptionsFor(operation, args);\n let base: ReturnType<typeof requestEventBase> | undefined;\n try {\n base = requestEventBase({\n providerOptions,\n provider: providerName(providerOptions),\n model:\n callOptions?.model || providerOptions.defaultModel || 'unknown',\n operation,\n callOptions,\n effectiveMaxOutputTokens: effectiveOutputTokens(\n operation,\n providerOptions,\n callOptions,\n ),\n });\n const iterable = Reflect.apply(\n value,\n target,\n args,\n ) as AsyncIterable<string>;\n for await (const chunk of iterable) yield chunk;\n emitRequestEvent(providerOptions, {\n ...base,\n status: 'succeeded',\n duration: Date.now() - startedAt,\n });\n } catch (error) {\n const failure = classifyRequestFailure(error);\n base ||= requestEventBase({\n providerOptions,\n provider: providerName(providerOptions),\n model:\n callOptions?.model || providerOptions.defaultModel || 'unknown',\n operation,\n callOptions,\n });\n emitRequestEvent(providerOptions, {\n ...base,\n ...failure,\n duration: Date.now() - startedAt,\n });\n throw error;\n }\n };\n }\n\n return async (...args: unknown[]) => {\n const startedAt = Date.now();\n const callOptions = callOptionsFor(operation, args);\n let base: ReturnType<typeof requestEventBase> | undefined;\n try {\n base = requestEventBase({\n providerOptions,\n provider: providerName(providerOptions),\n model:\n callOptions?.model || providerOptions.defaultModel || 'unknown',\n operation,\n callOptions,\n effectiveMaxOutputTokens: effectiveOutputTokens(\n operation,\n providerOptions,\n callOptions,\n ),\n });\n const result = await Reflect.apply(value, target, args);\n emitRequestEvent(providerOptions, {\n ...base,\n status: 'succeeded',\n duration: Date.now() - startedAt,\n });\n return result;\n } catch (error) {\n const failure = classifyRequestFailure(error);\n base ||= requestEventBase({\n providerOptions,\n provider: providerName(providerOptions),\n model:\n callOptions?.model || providerOptions.defaultModel || 'unknown',\n operation,\n callOptions,\n });\n emitRequestEvent(providerOptions, {\n ...base,\n ...failure,\n duration: Date.now() - startedAt,\n });\n throw error;\n }\n };\n },\n });\n}\n"],"mappings":";;AAcA,IAAa,wBAAwB;AACrC,IAAa,yBAAyB;AAEtC,IAAa,+BACX,OAAO,OAAO;CACZ,iBAAiB;CACjB,oBAAoB;CACpB,qBAAqB;CACrB,YAAY;AACd,CAAC;AAeH,SAAS,gBACP,OACA,UACA,OACQ;CACR,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,GACtC,MAAM,IAAI,QACR,GAAG,MAAM,oCACT,kBACF;CAEF,OAAO,KAAK,MAAM,KAAK;AACzB;AAEA,SAAgB,uBACd,SAC6B;CAC7B,MAAM,mBAAmB,QAAQ,oBAAoB,CAAC;CACtD,MAAM,mBAAuC;EAC3C,iBAAiB,gBACf,iBAAiB,iBACjB,6BAA6B,iBAC7B,kCACF;EACA,oBAAoB,gBAClB,iBAAiB,oBACjB,6BAA6B,oBAC7B,qCACF;EACA,qBAAqB,gBACnB,iBAAiB,qBACjB,6BAA6B,qBAC7B,sCACF;EACA,YACE,iBAAiB,cAAc,6BAA6B;CAChE;CAEA,IAAI,CAAC,CAAC,SAAS,OAAO,CAAC,CAAC,SAAS,iBAAiB,UAAU,GAC1D,MAAM,IAAI,QACR,8DACA,kBACF;CAGF,OAAO;EACL,GAAG;EACH,SAAS,gBAAgB,QAAQ,SAAS,uBAAuB,SAAS;EAC1E,mBAAmB;GACjB,IAAI,QAAQ,eAAe,KAAA,GAAW,OAAA;GACtC,IAAI,CAAC,OAAO,SAAS,QAAQ,UAAU,KAAK,QAAQ,aAAa,GAC/D,MAAM,IAAI,QACR,mDACA,kBACF;GAEF,OAAO,KAAK,MAAM,QAAQ,UAAU;EACtC,EAAA,CAAG;EACH;CACF;AACF;AA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,IAAI;GAC3B,MAAM,cAAc,eAAe,WAAW,IAAI;GAClD,IAAI;GACJ,IAAI;IACF,OAAO,iBAAiB;KACtB;KACA,UAAU,aAAa,eAAe;KACtC,OACE,aAAa,SAAS,gBAAgB,gBAAgB;KACxD;KACA;KACA,0BAA0B,sBACxB,WACA,iBACA,WACF;IACF,CAAC;IACD,MAAM,SAAS,MAAM,QAAQ,MAAM,OAAO,QAAQ,IAAI;IACtD,iBAAiB,iBAAiB;KAChC,GAAG;KACH,QAAQ;KACR,UAAU,KAAK,IAAI,IAAI;IACzB,CAAC;IACD,OAAO;GACT,SAAS,OAAO;IACd,MAAM,UAAU,uBAAuB,KAAK;IAC5C,SAAS,iBAAiB;KACxB;KACA,UAAU,aAAa,eAAe;KACtC,OACE,aAAa,SAAS,gBAAgB,gBAAgB;KACxD;KACA;IACF,CAAC;IACD,iBAAiB,iBAAiB;KAChC,GAAG;KACH,GAAG;KACH,UAAU,KAAK,IAAI,IAAI;IACzB,CAAC;IACD,MAAM;GACR;EACF;CACF,EACF,CAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"seevio-BJRiguLc.js","names":[],"sources":["../../src/shared/providers/seevio.ts"],"sourcesContent":["/**\n * Seevio's native asynchronous Seedance 2.5 video-generation provider.\n *\n * Seevio is deliberately implemented as its own raw-HTTP adapter rather than\n * being shaped to ModelArk. Both services can run Seedance, but their task,\n * billing, and media contracts differ.\n *\n * @see https://seevio.ai/api-docs\n */\n\nimport { ValidationError } from '@happyvertical/utils';\nimport { extractRetryAfterSeconds } from '../rate-limit';\nimport { normalizeBaseAIOptions } from '../safety';\nimport type {\n AICapabilities,\n AIInterface,\n AIMessage,\n AIModel,\n AIResponse,\n ChatOptions,\n CompletionOptions,\n EmbeddingOptions,\n EmbeddingResponse,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n MessageOptions,\n SeevioOptions,\n TTSOptions,\n TTSResponse,\n VideoGenerationBillingMetadata,\n VideoGenerationJob,\n VideoGenerationOptions,\n VideoGenerationReferenceMedia,\n VideoGenerationResult,\n VideoGenerationStatusResult,\n Voice,\n VoiceCloneOptions,\n VoiceDesignOptions,\n VoiceListOptions,\n} from '../types';\nimport { AIError, AuthenticationError, RateLimitError } from '../types';\nimport { emitUsage } from './usage';\n\nconst DEFAULT_BASE_URL = 'https://api.seevio.ai';\nconst DEFAULT_RESULT_ORIGIN = 'https://cdn.seevio.ai';\nconst MODEL = 'seedance-2-5';\nconst MIN_POLL_INTERVAL_MS = 10_000;\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_MAX_RESULT_BYTES = 200 * 1024 * 1024;\nconst COMPLETED_SNAPSHOT_TTL_MS = MIN_POLL_INTERVAL_MS;\nconst MAX_COMPLETED_SNAPSHOTS = 128;\n\ninterface SeevioTask {\n id: string;\n status: string;\n model?: string;\n billing_status?: string;\n credits?: number;\n failed_reason?: string | null;\n data?: {\n results?: string[];\n video_expires_at?: string;\n last_frame_url?: string | null;\n processing_time?: number;\n };\n}\n\ninterface SeevioErrorResponse {\n error?: {\n code?: string;\n message?: string;\n required?: number;\n available?: number;\n };\n}\n\ninterface SeevioCreateResponse {\n taskId: string;\n credits?: number;\n}\n\ninterface SeevioInput {\n prompt: string;\n generation_type: 'text-to-video' | 'image-to-video' | 'reference-to-video';\n image_urls?: string[];\n video_urls?: string[];\n audio_urls?: string[];\n duration: number;\n aspect_ratio: 'adaptive' | '16:9' | '9:16' | '1:1' | '4:3' | '3:4' | '21:9';\n resolution: '480p' | '720p';\n generate_audio: boolean;\n return_last_frame: boolean;\n}\n\nfunction ensureOptions(options: SeevioOptions): SeevioOptions {\n const baseUrl = (options.baseUrl || DEFAULT_BASE_URL)\n .trim()\n .replace(/\\/+$/, '');\n const parsedBaseUrl = new URL(baseUrl);\n if (parsedBaseUrl.protocol !== 'https:') {\n throw new ValidationError('seevio baseUrl must use HTTPS', {\n provider: 'seevio',\n });\n }\n const origins = options.resultUrlOrigins?.length\n ? options.resultUrlOrigins\n : [DEFAULT_RESULT_ORIGIN];\n for (const origin of origins) {\n const parsed = new URL(origin);\n if (\n parsed.protocol !== 'https:' ||\n parsed.origin !== origin.replace(/\\/+$/, '')\n ) {\n throw new ValidationError(\n 'seevio resultUrlOrigins must contain HTTPS origins only',\n {\n provider: 'seevio',\n },\n );\n }\n }\n if (\n options.maxResultBytes !== undefined &&\n (!Number.isSafeInteger(options.maxResultBytes) ||\n options.maxResultBytes <= 0)\n ) {\n throw new ValidationError(\n 'seevio maxResultBytes must be a positive safe integer',\n { provider: 'seevio' },\n );\n }\n return {\n ...options,\n baseUrl,\n resultUrlOrigins: origins.map((origin) => origin.replace(/\\/+$/, '')),\n };\n}\n\nfunction validatedHttpsUrl(value: string, label: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new ValidationError(`${label} must be a valid public HTTPS URL`, {\n provider: 'seevio',\n });\n }\n if (url.protocol !== 'https:') {\n throw new ValidationError(`${label} must use HTTPS`, {\n provider: 'seevio',\n });\n }\n const host = url.hostname.toLowerCase();\n if (\n url.username ||\n url.password ||\n host === 'localhost' ||\n host.endsWith('.localhost') ||\n host.includes(':') ||\n /^\\d{1,3}(?:\\.\\d{1,3}){3}$/.test(host)\n ) {\n throw new ValidationError(\n `${label} must not use credentials, localhost, or an IP-literal host`,\n { provider: 'seevio' },\n );\n }\n return url.toString();\n}\n\nfunction normalizeBilling(\n task: SeevioTask,\n): VideoGenerationBillingMetadata | undefined {\n if (task.credits === undefined && !task.billing_status) return undefined;\n const normalized = [\n 'reserved',\n 'charged',\n 'refunded',\n 'refund_failed',\n ].includes(task.billing_status || '')\n ? (task.billing_status as VideoGenerationBillingMetadata['status'])\n : undefined;\n return {\n ...(task.credits !== undefined ? { credits: task.credits } : {}),\n ...(normalized ? { status: normalized } : {}),\n ...(!normalized && task.billing_status\n ? { rawStatus: task.billing_status }\n : {}),\n };\n}\n\n/** Native Seevio adapter for the pinned `seedance-2-5` model. */\nexport class SeevioProvider implements AIInterface {\n private readonly options: SeevioOptions;\n private readonly resultOrigins: Set<string>;\n private readonly nextPollAt = new Map<string, number>();\n private readonly completedSnapshots = new Map<\n string,\n { task: SeevioTask; recordedAt: number }\n >();\n\n /** Creates a Seevio task client using the documented HTTPS API root. */\n constructor(options: SeevioOptions) {\n this.options = normalizeBaseAIOptions(ensureOptions(options));\n this.resultOrigins = new Set(this.options.resultUrlOrigins);\n }\n\n private async request<T>(\n path: string,\n options: {\n method?: 'GET' | 'POST';\n body?: unknown;\n signal?: AbortSignal;\n timeout?: number;\n allowNotFound?: boolean;\n } = {},\n ): Promise<T> {\n const response = await this.rawRequest(path, options);\n const text = await response.text();\n return text ? (JSON.parse(text) as T) : ({} as T);\n }\n\n private async rawRequest(\n path: string,\n options: {\n method?: 'GET' | 'POST';\n body?: unknown;\n signal?: AbortSignal;\n timeout?: number;\n allowNotFound?: boolean;\n } = {},\n ): Promise<Response> {\n if (options.signal?.aborted)\n throw new AIError(\n 'Seevio request aborted by caller',\n 'AI_ABORTED',\n 'seevio',\n );\n const controller = new AbortController();\n const timeoutMs = options.timeout ?? this.options.timeout;\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n const abort = () => controller.abort(options.signal?.reason);\n options.signal?.addEventListener('abort', abort, { once: true });\n // An abort may occur between the preflight check and listener\n // registration. Re-check after registration so that race still reaches\n // the fetch signal rather than allowing a paid request to continue.\n if (options.signal?.aborted) abort();\n try {\n let response: Response;\n try {\n response = await fetch(`${this.options.baseUrl}${path}`, {\n method: options.method || 'GET',\n headers: {\n Authorization: `Bearer ${this.options.apiKey ?? ''}`,\n ...(options.body !== undefined\n ? { 'Content-Type': 'application/json' }\n : {}),\n ...(this.options.headers || {}),\n },\n body:\n options.body === undefined\n ? undefined\n : JSON.stringify(options.body),\n signal: controller.signal,\n });\n } catch (error) {\n if (timedOut)\n throw new AIError(\n `Seevio request to ${path} timed out after ${timeoutMs}ms`,\n 'AI_TIMEOUT',\n 'seevio',\n undefined,\n options.method !== 'POST',\n );\n if (options.signal?.aborted)\n throw new AIError(\n 'Seevio request aborted by caller',\n 'AI_ABORTED',\n 'seevio',\n );\n throw new AIError(\n `Network error calling Seevio ${path}: ${error instanceof Error ? error.message : String(error)}`,\n 'NETWORK_ERROR',\n 'seevio',\n undefined,\n options.method !== 'POST',\n );\n }\n if (response.status === 404 && options.allowNotFound) return response;\n if (response.ok) return response;\n const errorText = await response.text();\n let payload: SeevioErrorResponse = {};\n try {\n payload = JSON.parse(errorText) as SeevioErrorResponse;\n } catch {\n /* preserve status fallback below */\n }\n const message =\n payload.error?.message ||\n `Seevio request to ${path} failed with HTTP ${response.status}`;\n if (response.status === 401) throw new AuthenticationError('seevio');\n if (response.status === 403)\n throw new AIError(message, 'SEEVIO_FORBIDDEN', 'seevio');\n if (response.status === 402)\n throw new AIError(message, 'INSUFFICIENT_CREDITS', 'seevio');\n if (response.status === 429)\n throw new RateLimitError(\n 'seevio',\n extractRetryAfterSeconds({ headers: response.headers }),\n );\n throw new AIError(\n message,\n 'SEEVIO_REQUEST_FAILED',\n 'seevio',\n undefined,\n response.status >= 500 && options.method !== 'POST',\n );\n } finally {\n clearTimeout(timer);\n options.signal?.removeEventListener('abort', abort);\n }\n }\n\n private assertReviewedResultUrl(value: string): string {\n const url = validatedHttpsUrl(value, 'Seevio result URL');\n if (!this.resultOrigins.has(new URL(url).origin)) {\n throw new AIError(\n 'Seevio returned a result URL outside configured reviewed origins',\n 'UNTRUSTED_RESULT_URL',\n 'seevio',\n );\n }\n return url;\n }\n\n private async downloadReviewedResult(\n initialUrl: string,\n ): Promise<{ data: Buffer; mimeType: string; url: string }> {\n let current = this.assertReviewedResultUrl(initialUrl);\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.options.timeout);\n const maxBytes = this.options.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES;\n try {\n for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects += 1) {\n const response = await fetch(current, {\n redirect: 'manual',\n signal: controller.signal,\n });\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n if (!location)\n throw new AIError(\n 'Seevio result redirect omitted Location',\n 'SEEVIO_RESULT_DOWNLOAD_FAILED',\n 'seevio',\n );\n current = this.assertReviewedResultUrl(\n new URL(location, current).toString(),\n );\n continue;\n }\n if (!response.ok)\n throw new AIError(\n `Seevio result download failed with HTTP ${response.status}`,\n 'SEEVIO_RESULT_DOWNLOAD_FAILED',\n 'seevio',\n );\n const contentType = response.headers.get('content-type');\n if (!contentType?.toLowerCase().startsWith('video/'))\n throw new AIError(\n `Seevio result download returned non-video content type ${contentType}`,\n 'SEEVIO_RESULT_MIME_INVALID',\n 'seevio',\n );\n const contentLength = response.headers.get('content-length');\n if (contentLength && Number(contentLength) > maxBytes)\n throw new AIError(\n `Seevio result exceeds configured ${maxBytes}-byte download limit`,\n 'SEEVIO_RESULT_TOO_LARGE',\n 'seevio',\n );\n if (!response.body)\n throw new AIError(\n 'Seevio result download had no response body',\n 'SEEVIO_RESULT_DOWNLOAD_FAILED',\n 'seevio',\n );\n const chunks: Uint8Array[] = [];\n let size = 0;\n const reader = response.body.getReader();\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxBytes) {\n await reader.cancel();\n throw new AIError(\n `Seevio result exceeds configured ${maxBytes}-byte download limit`,\n 'SEEVIO_RESULT_TOO_LARGE',\n 'seevio',\n );\n }\n chunks.push(value);\n }\n return {\n data: Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))),\n mimeType: contentType,\n url: current,\n };\n }\n throw new AIError(\n 'Seevio result exceeded the maximum redirect count',\n 'SEEVIO_RESULT_DOWNLOAD_FAILED',\n 'seevio',\n );\n } catch (error) {\n if (controller.signal.aborted)\n throw new AIError(\n `Seevio result download timed out after ${this.options.timeout}ms`,\n 'AI_TIMEOUT',\n 'seevio',\n undefined,\n true,\n );\n throw error;\n } finally {\n clearTimeout(timer);\n }\n }\n\n private mediaUrls(options: VideoGenerationOptions): {\n images: string[];\n videos: string[];\n audio: string[];\n } {\n const images = (options.referenceImages ?? []).map((reference) => {\n if (\n typeof reference.image !== 'string' ||\n reference.image.startsWith('data:')\n ) {\n throw new ValidationError(\n 'Seevio referenceImages must be public HTTPS URLs; it cannot retrieve bytes or data URLs',\n { provider: 'seevio' },\n );\n }\n return validatedHttpsUrl(reference.image, 'Seevio reference image');\n });\n const references = options.referenceMedia ?? [];\n if (references.length + images.length > 50)\n throw new ValidationError(\n 'Seevio accepts at most 50 total reference assets',\n { provider: 'seevio' },\n );\n const collect = (type: VideoGenerationReferenceMedia['type']) =>\n references\n .filter((reference) => reference.type === type)\n .map((reference) =>\n validatedHttpsUrl(reference.url, `Seevio ${type} reference`),\n );\n const mediaImages = collect('image');\n const videos = collect('video');\n const audio = collect('audio');\n if (\n images.length + mediaImages.length > 30 ||\n videos.length > 10 ||\n audio.length > 10\n ) {\n throw new ValidationError(\n 'Seevio reference limits are 30 images, 10 videos, and 10 audio files',\n { provider: 'seevio' },\n );\n }\n for (const reference of references) {\n if (\n (reference.type === 'video' || reference.type === 'audio') &&\n reference.durationSeconds !== undefined &&\n (!Number.isFinite(reference.durationSeconds) ||\n reference.durationSeconds < 2 ||\n reference.durationSeconds > 30)\n ) {\n throw new ValidationError(\n 'Seevio video/audio reference durations must be 2-30 seconds when supplied',\n { provider: 'seevio' },\n );\n }\n }\n for (const [label, type] of [\n ['video', 'video'],\n ['audio', 'audio'],\n ] as const) {\n const durations = references\n .filter((reference) => reference.type === type)\n .flatMap((reference) =>\n reference.durationSeconds === undefined\n ? []\n : [reference.durationSeconds],\n );\n if (durations.reduce((total, duration) => total + duration, 0) > 30) {\n throw new ValidationError(\n `Seevio ${label} reference durations must total no more than 30 seconds`,\n { provider: 'seevio' },\n );\n }\n }\n return { images: [...images, ...mediaImages], videos, audio };\n }\n\n private async pollTask(jobId: string): Promise<SeevioTask> {\n const now = Date.now();\n for (const [knownJobId, expiry] of this.nextPollAt) {\n if (expiry <= now) this.nextPollAt.delete(knownJobId);\n }\n const next = this.nextPollAt.get(jobId);\n if (next && now < next)\n throw new AIError(\n `Seevio tasks may be polled no more than once every 10 seconds; retry after ${Math.ceil((next - now) / 1000)} seconds`,\n 'VIDEO_POLL_TOO_FREQUENT',\n 'seevio',\n );\n const expiry = now + MIN_POLL_INTERVAL_MS;\n this.nextPollAt.set(jobId, expiry);\n const cleanup = setTimeout(() => {\n if (this.nextPollAt.get(jobId) === expiry) this.nextPollAt.delete(jobId);\n }, MIN_POLL_INTERVAL_MS);\n // Let idle Node workers exit rather than keeping the process alive for a\n // cadence cleanup timer. Browser timer handles do not expose `unref`.\n if (typeof cleanup === 'object' && 'unref' in cleanup) cleanup.unref();\n const task = await this.request<SeevioTask>(\n `/v1/tasks/${encodeURIComponent(jobId)}`,\n );\n if (task.status === 'completed') {\n // This is a bounded, short-lived handoff cache, not task history. A\n // completed task can be fetched without another status request only\n // within the provider's ten-second cadence window.\n if (!this.completedSnapshots.has(jobId)) {\n const oldestJobId = this.completedSnapshots.keys().next().value;\n if (\n this.completedSnapshots.size >= MAX_COMPLETED_SNAPSHOTS &&\n oldestJobId !== undefined\n ) {\n this.completedSnapshots.delete(oldestJobId);\n }\n }\n this.completedSnapshots.set(jobId, { task, recordedAt: Date.now() });\n }\n return task;\n }\n\n private completedSnapshot(jobId: string): SeevioTask | undefined {\n const snapshot = this.completedSnapshots.get(jobId);\n if (!snapshot) return undefined;\n if (Date.now() - snapshot.recordedAt >= COMPLETED_SNAPSHOT_TTL_MS) {\n this.completedSnapshots.delete(jobId);\n return undefined;\n }\n return snapshot.task;\n }\n\n /** Submits one unambiguous, non-retried Seedance 2.5 task. */\n async submitVideoGenerationJob(\n options: VideoGenerationOptions,\n ): Promise<VideoGenerationJob> {\n const startTime = Date.now();\n const model = options.model || this.options.defaultModel || MODEL;\n if (model !== MODEL)\n throw new ValidationError(\n `Seevio provider supports the pinned model ${MODEL}`,\n { provider: 'seevio' },\n );\n if (!options.prompt?.trim())\n throw new ValidationError('Seevio requires a non-empty prompt', {\n provider: 'seevio',\n });\n if (options.seed !== undefined)\n throw new ValidationError(\n 'seed is not supported by Seevio Seedance 2.5',\n { provider: 'seevio' },\n );\n const duration = options.durationSeconds ?? 5;\n if (!Number.isInteger(duration) || duration < 4 || duration > 30)\n throw new ValidationError(\n 'Seevio durationSeconds must be an integer from 4 through 30',\n { provider: 'seevio' },\n );\n const resolution = options.resolution ?? '720p';\n if (resolution !== '480p' && resolution !== '720p')\n throw new ValidationError('Seevio resolution must be 480p or 720p', {\n provider: 'seevio',\n });\n const { images, videos, audio } = this.mediaUrls(options);\n const isImageToVideo =\n images.length >= 1 &&\n images.length <= 2 &&\n videos.length === 0 &&\n audio.length === 0;\n const generationType = isImageToVideo\n ? 'image-to-video'\n : images.length || videos.length || audio.length\n ? 'reference-to-video'\n : 'text-to-video';\n const aspectRatio = options.aspectRatio ?? 'adaptive';\n const supportedRatios: SeevioInput['aspect_ratio'][] = [\n 'adaptive',\n '16:9',\n '9:16',\n '1:1',\n '4:3',\n '3:4',\n '21:9',\n ];\n if (!supportedRatios.includes(aspectRatio as SeevioInput['aspect_ratio']))\n throw new ValidationError('Unsupported Seevio aspectRatio', {\n provider: 'seevio',\n });\n if (isImageToVideo && aspectRatio !== 'adaptive')\n throw new ValidationError(\n 'Seevio image-to-video requires aspectRatio: adaptive',\n { provider: 'seevio' },\n );\n const input: SeevioInput = {\n prompt: options.prompt.trim(),\n generation_type: generationType,\n duration,\n aspect_ratio: aspectRatio as SeevioInput['aspect_ratio'],\n resolution: resolution as '480p' | '720p',\n generate_audio: options.generateAudio ?? true,\n return_last_frame: options.returnLastFrame ?? false,\n ...(images.length ? { image_urls: images } : {}),\n ...(videos.length ? { video_urls: videos } : {}),\n ...(audio.length ? { audio_urls: audio } : {}),\n };\n const created = await this.request<SeevioCreateResponse>(\n '/v1/videos/generations',\n {\n method: 'POST',\n body: { model: MODEL, input },\n signal: options.signal,\n timeout: options.timeout,\n },\n );\n if (!created.taskId)\n throw new AIError(\n 'Seevio accepted submission without a taskId',\n 'SEEVIO_INVALID_RESPONSE',\n 'seevio',\n );\n emitUsage(\n this.options,\n 'seevio',\n 'submitVideoGenerationJob',\n MODEL,\n undefined,\n startTime,\n {\n durationSeconds: String(duration),\n resolution,\n aspectRatio,\n ...options.usageTags,\n },\n );\n return {\n jobId: created.taskId,\n provider: 'seevio',\n model: MODEL,\n createdAt: new Date().toISOString(),\n raw:\n created.credits === undefined\n ? undefined\n : { credits: created.credits, billingStatus: 'reserved' },\n };\n }\n\n /** Returns a normalized task snapshot, enforcing Seevio's 10-second poll cadence. */\n async getVideoGenerationJob(\n handle: VideoGenerationJob,\n ): Promise<VideoGenerationStatusResult> {\n return this.mapTask(await this.pollTask(handle.jobId));\n }\n\n /** Downloads a completed video while validating the initial URL and every redirect. */\n async fetchVideoGenerationResult(\n handle: VideoGenerationJob,\n ): Promise<VideoGenerationResult> {\n const task =\n this.completedSnapshot(handle.jobId) ??\n (await this.pollTask(handle.jobId));\n const status = this.mapTask(task);\n if (status.status !== 'succeeded' || !status.result?.url)\n throw new AIError(\n `Seevio job ${handle.jobId} has not succeeded (status: ${status.status})`,\n 'VIDEO_JOB_NOT_READY',\n 'seevio',\n handle.model,\n );\n try {\n const downloaded = await this.downloadReviewedResult(status.result.url);\n return { ...status.result, ...downloaded };\n } finally {\n // The handoff cache exists only to make an immediate status → fetch\n // flow cadence-safe. Do not retain expired signed URLs after any fetch\n // attempt; a later fetch will authenticate a fresh task snapshot.\n this.completedSnapshots.delete(handle.jobId);\n }\n }\n\n /** Reports cancellation as unsupported because Seevio documents no cancellation endpoint. */\n async cancelVideoGenerationJob(_handle: VideoGenerationJob): Promise<void> {\n throw new AIError(\n 'Seevio does not document a video-task cancellation endpoint',\n 'NOT_IMPLEMENTED',\n 'seevio',\n );\n }\n\n /** Performs an unbilled random task-id probe; an authenticated 404 is valid access. */\n async validateVideoGenerationAccess(): Promise<boolean> {\n const response = await this.rawRequest(\n `/v1/tasks/have-ai-access-probe-${crypto.randomUUID()}`,\n { allowNotFound: true },\n );\n return response.ok || response.status === 404;\n }\n\n private mapTask(task: SeevioTask): VideoGenerationStatusResult {\n const billing = normalizeBilling(task);\n if (task.status === 'queued')\n return { status: 'queued', ...(billing ? { billing } : {}) };\n if (task.status === 'generating')\n return { status: 'running', ...(billing ? { billing } : {}) };\n if (task.status === 'failed')\n return {\n status: 'failed',\n error: task.failed_reason || 'Seevio video generation failed',\n ...(billing ? { billing } : {}),\n };\n if (task.status !== 'completed')\n return {\n status: 'running',\n rawStatus: task.status,\n ...(billing ? { billing } : {}),\n };\n const url = task.data?.results?.[0];\n if (!url)\n return {\n status: 'failed',\n error: 'Seevio reported completion with no result URL',\n ...(billing ? { billing } : {}),\n };\n const result: VideoGenerationResult = {\n url: this.assertReviewedResultUrl(url),\n mimeType: 'video/mp4',\n ...(task.data?.video_expires_at\n ? { expiresAt: task.data.video_expires_at }\n : {}),\n ...(task.data?.last_frame_url\n ? {\n lastFrameUrl: this.assertReviewedResultUrl(\n task.data.last_frame_url,\n ),\n }\n : {}),\n };\n return { status: 'succeeded', result, ...(billing ? { billing } : {}) };\n }\n\n /** Lists the single intentional Seevio model selection. */\n async getModels(): Promise<AIModel[]> {\n return [\n {\n id: MODEL,\n name: 'Seedance 2.5',\n description: 'Seevio Seedance 2.5 async video generation',\n contextLength: 0,\n capabilities: ['video_generation'],\n supportsFunctions: false,\n supportsVision: true,\n },\n ];\n }\n /** Reports Seevio's video-only capability surface. */\n async getCapabilities(): Promise<AICapabilities> {\n return {\n chat: false,\n completion: false,\n embeddings: false,\n streaming: false,\n functions: false,\n vision: false,\n fineTuning: false,\n imageEmbeddings: false,\n imageGeneration: false,\n videoGeneration: true,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 0,\n supportedOperations: [\n 'submitVideoGenerationJob',\n 'getVideoGenerationJob',\n 'fetchVideoGenerationResult',\n ],\n };\n }\n\n private unsupported(): never {\n throw new AIError(\n 'This operation is not supported by the Seevio video-only provider.',\n 'NOT_IMPLEMENTED',\n 'seevio',\n );\n }\n /** @inheritdoc */ async chat(\n _messages: AIMessage[],\n _options?: ChatOptions,\n ): Promise<AIResponse> {\n return this.unsupported();\n }\n /** @inheritdoc */ async complete(\n _prompt: string,\n _options?: CompletionOptions,\n ): Promise<AIResponse> {\n return this.unsupported();\n }\n /** @inheritdoc */ async message(\n _text: string,\n _options?: MessageOptions,\n ): Promise<string> {\n return this.unsupported();\n }\n /** @inheritdoc */ async embed(\n _text: string | string[],\n _options?: EmbeddingOptions,\n ): Promise<EmbeddingResponse> {\n return this.unsupported();\n }\n /** @inheritdoc */ async embedImage(\n _image: string | Buffer,\n _options?: ImageEmbeddingOptions,\n ): Promise<EmbeddingResponse> {\n return this.unsupported();\n }\n /** @inheritdoc */ async describeImage(\n _image: string | Buffer,\n _prompt?: string,\n _options?: ImageDescriptionOptions,\n ): Promise<string> {\n return this.unsupported();\n }\n /** @inheritdoc */ async generateImage(\n _prompt: string,\n _options?: ImageGenerationOptions,\n ): Promise<ImageGenerationResponse> {\n return this.unsupported();\n }\n /** @inheritdoc */ stream(\n _messages: AIMessage[],\n _options?: ChatOptions,\n ): AsyncIterable<string> {\n const error = new AIError(\n 'Chat streaming is not supported by the Seevio video-only provider.',\n 'NOT_IMPLEMENTED',\n 'seevio',\n );\n return {\n [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) }),\n };\n }\n /** @inheritdoc */ async countTokens(_text: string): Promise<number> {\n return this.unsupported();\n }\n /** @inheritdoc */ async synthesizeSpeech(\n _text: string,\n _options?: TTSOptions,\n ): Promise<TTSResponse> {\n return this.unsupported();\n }\n /** @inheritdoc */ streamSpeech(\n _text: string,\n _options?: TTSOptions,\n ): AsyncIterable<Buffer> {\n const error = new AIError(\n 'TTS streaming is not supported by the Seevio video-only provider.',\n 'NOT_IMPLEMENTED',\n 'seevio',\n );\n return {\n [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) }),\n };\n }\n /** @inheritdoc */ async cloneVoice(\n _options: VoiceCloneOptions,\n ): Promise<Voice> {\n return this.unsupported();\n }\n /** @inheritdoc */ async designVoice(\n _options: VoiceDesignOptions,\n ): Promise<Voice> {\n return this.unsupported();\n }\n /** @inheritdoc */ async getVoices(\n _options?: VoiceListOptions,\n ): Promise<Voice[]> {\n return this.unsupported();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6CA,IAAM,mBAAmB;AACzB,IAAM,wBAAwB;AAC9B,IAAM,QAAQ;AACd,IAAM,uBAAuB;AAC7B,IAAM,gBAAgB;AACtB,IAAM,2BAA2B,MAAM,OAAO;AAC9C,IAAM,4BAA4B;AAClC,IAAM,0BAA0B;AA4ChC,SAAS,cAAc,SAAuC;CAC5D,MAAM,WAAW,QAAQ,WAAW,iBAAA,CACjC,KAAK,CAAC,CACN,QAAQ,QAAQ,EAAE;CAErB,IAAI,IADsB,IAAI,OAC1B,CAAA,CAAc,aAAa,UAC7B,MAAM,IAAI,gBAAgB,iCAAiC,EACzD,UAAU,SACZ,CAAC;CAEH,MAAM,UAAU,QAAQ,kBAAkB,SACtC,QAAQ,mBACR,CAAC,qBAAqB;CAC1B,KAAK,MAAM,UAAU,SAAS;EAC5B,MAAM,SAAS,IAAI,IAAI,MAAM;EAC7B,IACE,OAAO,aAAa,YACpB,OAAO,WAAW,OAAO,QAAQ,QAAQ,EAAE,GAE3C,MAAM,IAAI,gBACR,2DACA,EACE,UAAU,SACZ,CACF;CAEJ;CACA,IACE,QAAQ,mBAAmB,KAAA,MAC1B,CAAC,OAAO,cAAc,QAAQ,cAAc,KAC3C,QAAQ,kBAAkB,IAE5B,MAAM,IAAI,gBACR,yDACA,EAAE,UAAU,SAAS,CACvB;CAEF,OAAO;EACL,GAAG;EACH;EACA,kBAAkB,QAAQ,KAAK,WAAW,OAAO,QAAQ,QAAQ,EAAE,CAAC;CACtE;AACF;AAEA,SAAS,kBAAkB,OAAe,O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