@jini-ai/integrations 0.4.2 → 0.4.3
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/CHANGELOG.md +13 -0
- package/dist/api-connections/access-token.d.ts +9 -0
- package/dist/api-connections/access-token.js +92 -0
- package/dist/api-connections/account-actions.d.ts +40 -0
- package/dist/api-connections/account-actions.js +110 -0
- package/dist/api-connections/attempt-state.d.ts +28 -0
- package/dist/api-connections/attempt-state.js +73 -0
- package/dist/api-connections/authorization.d.ts +45 -0
- package/dist/api-connections/authorization.js +120 -0
- package/dist/api-connections/deps.d.ts +41 -0
- package/dist/api-connections/deps.js +13 -0
- package/dist/api-connections/descriptor.d.ts +6 -0
- package/dist/api-connections/descriptor.js +111 -0
- package/dist/api-connections/errors.d.ts +23 -0
- package/dist/api-connections/errors.js +24 -0
- package/dist/api-connections/finish-authorization.d.ts +24 -0
- package/dist/api-connections/finish-authorization.js +117 -0
- package/dist/api-connections/index.d.ts +18 -0
- package/dist/api-connections/index.js +10 -0
- package/dist/api-connections/install-credential.d.ts +19 -0
- package/dist/api-connections/install-credential.js +12 -0
- package/dist/api-connections/keys.d.ts +27 -0
- package/dist/api-connections/keys.js +22 -0
- package/dist/api-connections/ports.d.ts +73 -0
- package/dist/api-connections/ports.js +2 -0
- package/dist/api-connections/records.d.ts +27 -0
- package/dist/api-connections/records.js +52 -0
- package/dist/api-connections/request-checks.d.ts +18 -0
- package/dist/api-connections/request-checks.js +67 -0
- package/dist/api-connections/service.d.ts +25 -0
- package/dist/api-connections/service.js +26 -0
- package/dist/api-connections/status.d.ts +28 -0
- package/dist/api-connections/status.js +36 -0
- package/dist/api-connections/token-store/errors.d.ts +20 -0
- package/dist/api-connections/token-store/errors.js +38 -0
- package/dist/api-connections/token-store/index.d.ts +6 -0
- package/dist/api-connections/token-store/index.js +6 -0
- package/dist/api-connections/token-store/record.d.ts +69 -0
- package/dist/api-connections/token-store/record.js +97 -0
- package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
- package/dist/api-connections/token-store/vault-token-store.js +215 -0
- package/dist/api-connections/types.d.ts +101 -0
- package/dist/api-connections/types.js +9 -0
- package/dist/credentialed-http/auth-schemes.js +8 -4
- package/dist/credentialed-http/credentialed-request.js +47 -77
- package/dist/credentialed-http/response-redaction.d.ts +5 -0
- package/dist/credentialed-http/response-redaction.js +62 -0
- package/dist/media-providers/catalog.d.ts +3 -1
- package/dist/media-providers/catalog.js +3 -1
- package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
- package/dist/media-providers/dispatch/async-operation-store.js +75 -37
- package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
- package/dist/media-providers/dispatch/context.js +10 -2
- package/dist/media-providers/dispatch/engine.d.ts +6 -3
- package/dist/media-providers/dispatch/engine.js +99 -109
- package/dist/media-providers/dispatch/index.d.ts +4 -2
- package/dist/media-providers/dispatch/index.js +3 -1
- package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
- package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
- package/dist/media-providers/dispatch/node.d.ts +13 -0
- package/dist/media-providers/dispatch/node.js +24 -0
- package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
- package/dist/media-providers/dispatch/openai-compatible.js +90 -87
- package/dist/media-providers/dispatch/operation-runtime.js +116 -89
- package/dist/media-providers/dispatch/outbound.d.ts +8 -4
- package/dist/media-providers/dispatch/outbound.js +27 -26
- package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
- package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
- package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
- package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
- package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/openai.js +51 -47
- package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
- package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
- package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
- package/dist/media-providers/dispatch/response-parsers.js +37 -21
- package/dist/media-providers/dispatch/sqlite-async-operation-store.js +9 -29
- package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
- package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
- package/dist/media-providers/dispatch/types.d.ts +76 -2
- package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
- package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
- package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
- package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
- package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
- package/dist/media-providers/dispatch/vendor-registry.js +14 -42
- package/dist/media-providers/policy.js +25 -17
- package/dist/media-providers/providers.d.ts +5 -0
- package/dist/media-providers/providers.js +2 -0
- package/dist/media-providers/sqlite-task-store.js +12 -80
- package/dist/media-providers/staging.js +77 -58
- package/dist/media-providers/task-lifecycle.d.ts +33 -0
- package/dist/media-providers/task-lifecycle.js +124 -0
- package/dist/media-providers/task-store.js +8 -86
- package/dist/media-providers/ui-defaults.d.ts +10 -0
- package/dist/media-providers/ui-defaults.js +167 -0
- package/dist/media-providers/video-request.js +112 -90
- package/dist/webhooks/delivery.d.ts +14 -0
- package/dist/webhooks/delivery.js +41 -10
- package/dist/webhooks/index.d.ts +1 -0
- package/dist/webhooks/index.js +1 -0
- package/dist/webhooks/ports.d.ts +23 -0
- package/dist/webhooks/worker.d.ts +83 -0
- package/dist/webhooks/worker.js +105 -0
- package/package.json +31 -8
|
@@ -25,7 +25,7 @@ import { partitionArgs } from '../../args.js';
|
|
|
25
25
|
* handed a guarded `httpClient` for, a standing invariant across `@jini-ai/integrations/media-providers`.
|
|
26
26
|
*/
|
|
27
27
|
import { FETCH_TIMEOUT_MS } from '@jini-ai/platform/fetch-with-timeout';
|
|
28
|
-
import { fetchMediaOutbound } from './outbound.js';
|
|
28
|
+
import { fetchMediaOutbound, requireMediaHttpClient } from './outbound.js';
|
|
29
29
|
/** Interactive budget for the inline attempt. Deliberately NOT `FETCH_TIMEOUT_MS.GENERATE` (10min) — that is the backstop for the *request*, this is the ceiling on making a human wait. */
|
|
30
30
|
export const DEFAULT_GRACE_MS = 4_000;
|
|
31
31
|
export const DEFAULT_MAX_ATTEMPTS = 60;
|
|
@@ -51,13 +51,15 @@ function toOperationError(error) {
|
|
|
51
51
|
}
|
|
52
52
|
async function performSigned(deps, request, timeoutMs) {
|
|
53
53
|
const signed = await deps.signer({ request: request });
|
|
54
|
-
return fetchMediaOutbound({ url: signed.url, timeoutMs }, { ...deps, init: signed.init });
|
|
54
|
+
return fetchMediaOutbound({ url: signed.url, timeoutMs }, { ...deps, httpClient: requireMediaHttpClient(deps), init: signed.init });
|
|
55
55
|
}
|
|
56
|
-
/** Thread only the outbound capability into parsers; stores and signers remain runtime-private.
|
|
56
|
+
/** Thread only the outbound capability into parsers; stores and signers remain runtime-private.
|
|
57
|
+
* Both callers parse a response that `performSigned` just fetched through the client, so the client
|
|
58
|
+
* is always present here; `requireMediaHttpClient` states that invariant instead of branching on it. */
|
|
57
59
|
function withRuntimeOutbound({ ctx, deps }) {
|
|
58
60
|
return {
|
|
59
61
|
...ctx,
|
|
60
|
-
|
|
62
|
+
httpClient: requireMediaHttpClient(deps),
|
|
61
63
|
...(deps.allowPrivateNetwork === undefined ? {} : { allowPrivateNetwork: deps.allowPrivateNetwork }),
|
|
62
64
|
...(deps.outboundMessages === undefined ? {} : { outboundMessages: deps.outboundMessages }),
|
|
63
65
|
};
|
|
@@ -189,93 +191,118 @@ export async function pollDueOperations(required, optional = {}) {
|
|
|
189
191
|
leaseMs: params.leaseMs,
|
|
190
192
|
...(params.limit !== undefined ? { limit: params.limit } : {}),
|
|
191
193
|
}, ["now", "leaseOwner", "leaseMs"]));
|
|
192
|
-
|
|
193
|
-
let failed = 0;
|
|
194
|
-
let pending = 0;
|
|
195
|
-
let unknown = 0;
|
|
194
|
+
const tally = { completed: 0, failed: 0, pending: 0, unknown: 0 };
|
|
196
195
|
for (const row of claimed) {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
failed += 1;
|
|
228
|
-
continue;
|
|
229
|
-
}
|
|
230
|
-
const ctx = params.resolveContext(row);
|
|
231
|
-
const request = adapter.buildPollRequest({ state: row.state ?? {}, ctx: ctx });
|
|
232
|
-
// Credentials are resolved here, on this tick — never read from the row.
|
|
233
|
-
const resp = await performSigned(deps, request, FETCH_TIMEOUT_MS.QUICK);
|
|
234
|
-
const outcome = await adapter.parsePollResponse({ resp: resp, ctx: withRuntimeOutbound({ ctx, deps }), state: row.state ?? {} });
|
|
235
|
-
// Every write below is fenced on the lease this tick claimed: if it expired and another
|
|
236
|
-
// worker has since reclaimed (or finished) the row, this write must not clobber that newer
|
|
237
|
-
// outcome — see `AsyncOperationUpdateOptions`.
|
|
238
|
-
if (outcome.kind === 'complete') {
|
|
239
|
-
await deps.store.update({ id: row.id, patch: {
|
|
240
|
-
status: 'succeeded',
|
|
241
|
-
attempts: row.attempts + 1,
|
|
242
|
-
result: resultToPayload(outcome.result),
|
|
243
|
-
} }, { options: { leaseOwner: params.leaseOwner } });
|
|
244
|
-
completed += 1;
|
|
245
|
-
}
|
|
246
|
-
else if (outcome.kind === 'failed') {
|
|
247
|
-
await deps.store.update({ id: row.id, patch: {
|
|
248
|
-
status: 'failed',
|
|
249
|
-
attempts: row.attempts + 1,
|
|
250
|
-
error: { message: outcome.message, ...(outcome.code !== undefined ? { code: outcome.code } : {}) },
|
|
251
|
-
} }, { options: { leaseOwner: params.leaseOwner } });
|
|
252
|
-
failed += 1;
|
|
253
|
-
}
|
|
254
|
-
else {
|
|
255
|
-
await deps.store.update({ id: row.id, patch: {
|
|
256
|
-
status: 'polling',
|
|
257
|
-
attempts: row.attempts + 1,
|
|
258
|
-
nextPollAt: at + (outcome.retryAfterMs ?? DEFAULT_POLL_INTERVAL_MS),
|
|
259
|
-
} }, { options: { leaseOwner: params.leaseOwner } });
|
|
260
|
-
pending += 1;
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
catch (error) {
|
|
264
|
-
// A transport failure is not a vendor verdict: keep the row pollable and let the attempt cap
|
|
265
|
-
// or the deadline end it, rather than reporting a definitive failure we cannot support.
|
|
266
|
-
await deps.store.update({ id: row.id, patch: {
|
|
267
|
-
status: 'polling',
|
|
268
|
-
attempts: row.attempts + 1,
|
|
269
|
-
nextPollAt: now() + DEFAULT_POLL_INTERVAL_MS,
|
|
270
|
-
error: toOperationError(error),
|
|
271
|
-
} }, { options: { leaseOwner: params.leaseOwner } });
|
|
272
|
-
pending += 1;
|
|
273
|
-
}
|
|
274
|
-
finally {
|
|
275
|
-
await deps.store.releaseLease({ id: row.id, leaseOwner: params.leaseOwner });
|
|
276
|
-
}
|
|
196
|
+
tally[await advanceClaimedRow({ row, deps, params, now })] += 1;
|
|
197
|
+
}
|
|
198
|
+
return { claimed: claimed.length, ...tally };
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Advances one claimed row by one tick, writes the verdict, and always releases the lease.
|
|
202
|
+
* Any throw — vendor transport, adapter, or the verdict write itself — becomes a pollable retry.
|
|
203
|
+
*/
|
|
204
|
+
async function advanceClaimedRow(required) {
|
|
205
|
+
const { row, deps, params, now } = required;
|
|
206
|
+
// Every write below is fenced on the lease this tick claimed: if it expired and another
|
|
207
|
+
// worker has since reclaimed (or finished) the row, this write must not clobber that newer
|
|
208
|
+
// outcome — see `AsyncOperationUpdateOptions`.
|
|
209
|
+
const fence = { options: { leaseOwner: params.leaseOwner } };
|
|
210
|
+
let bucket;
|
|
211
|
+
try {
|
|
212
|
+
const verdict = await decideRow({ row, deps, params, at: now() });
|
|
213
|
+
await deps.store.update({ id: row.id, patch: verdict.patch }, fence);
|
|
214
|
+
bucket = verdict.bucket;
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
// A transport failure is not a vendor verdict: keep the row pollable and let the attempt cap
|
|
218
|
+
// or the deadline end it, rather than reporting a definitive failure we cannot support.
|
|
219
|
+
await deps.store.update({ id: row.id, patch: {
|
|
220
|
+
status: 'polling',
|
|
221
|
+
attempts: row.attempts + 1,
|
|
222
|
+
nextPollAt: now() + DEFAULT_POLL_INTERVAL_MS,
|
|
223
|
+
error: toOperationError(error),
|
|
224
|
+
} }, fence);
|
|
225
|
+
bucket = 'pending';
|
|
277
226
|
}
|
|
278
|
-
|
|
227
|
+
finally {
|
|
228
|
+
await deps.store.releaseLease({ id: row.id, leaseOwner: params.leaseOwner });
|
|
229
|
+
}
|
|
230
|
+
return bucket;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Both bounds are checked before any vendor call, and in this order: the absolute deadline (a
|
|
234
|
+
* blown deadline must not cost another request), then the attempt cap, then the adapter lookup.
|
|
235
|
+
*/
|
|
236
|
+
async function decideRow(required) {
|
|
237
|
+
const { row, deps, params, at } = required;
|
|
238
|
+
const bound = boundsVerdict({ row, at });
|
|
239
|
+
if (bound)
|
|
240
|
+
return bound;
|
|
241
|
+
const adapter = params.adapters({ providerId: row.providerId, routeKey: row.routeKey });
|
|
242
|
+
if (!adapter) {
|
|
243
|
+
return {
|
|
244
|
+
bucket: 'failed',
|
|
245
|
+
patch: {
|
|
246
|
+
status: 'failed',
|
|
247
|
+
error: { message: `no polling adapter registered for "${row.providerId}" / "${row.routeKey}"`, code: 'NO_ADAPTER' },
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
const ctx = params.resolveContext(row);
|
|
252
|
+
const state = row.state ?? {};
|
|
253
|
+
const request = adapter.buildPollRequest({ state, ctx });
|
|
254
|
+
// Credentials are resolved here, on this tick — never read from the row.
|
|
255
|
+
const resp = await performSigned(deps, request, FETCH_TIMEOUT_MS.QUICK);
|
|
256
|
+
const outcome = await adapter.parsePollResponse({ resp, ctx: withRuntimeOutbound({ ctx, deps }), state });
|
|
257
|
+
return pollOutcomeVerdict({ outcome, attempts: row.attempts + 1, at });
|
|
258
|
+
}
|
|
259
|
+
/** The deadline / attempt-cap verdict for a row, or `undefined` when it is still within both bounds. */
|
|
260
|
+
function boundsVerdict({ row, at }) {
|
|
261
|
+
if (row.deadlineAt <= at) {
|
|
262
|
+
return {
|
|
263
|
+
bucket: 'unknown',
|
|
264
|
+
patch: {
|
|
265
|
+
status: 'unknown',
|
|
266
|
+
error: {
|
|
267
|
+
message: 'async operation passed its absolute deadline — vendor-side effect is undetermined',
|
|
268
|
+
code: 'DEADLINE_EXPIRED',
|
|
269
|
+
},
|
|
270
|
+
},
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
if (row.attempts >= row.maxAttempts) {
|
|
274
|
+
return {
|
|
275
|
+
bucket: 'failed',
|
|
276
|
+
patch: {
|
|
277
|
+
status: 'failed',
|
|
278
|
+
error: {
|
|
279
|
+
message: `async operation exhausted its ${row.maxAttempts} poll attempts without a terminal answer`,
|
|
280
|
+
code: 'ATTEMPTS_EXHAUSTED',
|
|
281
|
+
},
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
/** Maps a vendor poll answer to the row patch, counting this poll as attempt number `attempts`. */
|
|
288
|
+
function pollOutcomeVerdict({ outcome, attempts, at }) {
|
|
289
|
+
if (outcome.kind === 'complete') {
|
|
290
|
+
return { bucket: 'completed', patch: { status: 'succeeded', attempts, result: resultToPayload(outcome.result) } };
|
|
291
|
+
}
|
|
292
|
+
if (outcome.kind === 'failed') {
|
|
293
|
+
return {
|
|
294
|
+
bucket: 'failed',
|
|
295
|
+
patch: {
|
|
296
|
+
status: 'failed',
|
|
297
|
+
attempts,
|
|
298
|
+
error: { message: outcome.message, ...(outcome.code !== undefined ? { code: outcome.code } : {}) },
|
|
299
|
+
},
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
bucket: 'pending',
|
|
304
|
+
patch: { status: 'polling', attempts, nextPollAt: at + (outcome.retryAfterMs ?? DEFAULT_POLL_INTERVAL_MS) },
|
|
305
|
+
};
|
|
279
306
|
}
|
|
280
307
|
/**
|
|
281
308
|
* Boot-time recovery. Releases dead leases and expires blown deadlines via the store, then handles
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { HttpClientPort } from '@jini-ai/core/primitives';
|
|
2
|
-
import type { DnsResolver } from '@jini-ai/platform/http/guarded';
|
|
3
2
|
/** The host supplies a policy-enforcing client, never a raw fetch implementation. */
|
|
4
3
|
export interface MediaOutboundOptions {
|
|
5
4
|
/** Override caller-facing transport diagnostics without changing policy. */
|
|
6
5
|
readonly outboundMessages?: Partial<typeof defaultMediaOutboundMessages>;
|
|
6
|
+
/** Required for network I/O. Pure context/request builders may omit it. */
|
|
7
7
|
readonly httpClient?: HttpClientPort;
|
|
8
|
-
/**
|
|
8
|
+
/** @deprecated Configure allowPrivateNetwork on the explicit Node client adapter instead. */
|
|
9
9
|
readonly allowPrivateNetwork?: boolean;
|
|
10
10
|
}
|
|
11
11
|
export declare const defaultMediaOutboundMessages: {
|
|
@@ -24,8 +24,12 @@ export declare const defaultMediaOutboundMessages: {
|
|
|
24
24
|
export declare function fetchMediaOutbound({ url, timeoutMs }: {
|
|
25
25
|
url: string;
|
|
26
26
|
timeoutMs: number;
|
|
27
|
-
}, { init, httpClient,
|
|
27
|
+
}, { init, httpClient, outboundMessages }: MediaOutboundOptions & {
|
|
28
|
+
httpClient: HttpClientPort;
|
|
28
29
|
init?: RequestInit;
|
|
29
|
-
dns?: DnsResolver;
|
|
30
30
|
}): Promise<Response>;
|
|
31
|
+
/** Resolve the trusted client on legacy context carriers without constructing a fallback.
|
|
32
|
+
* @throws TypeError before I/O if a standalone renderer/runtime has no injected client.
|
|
33
|
+
*/
|
|
34
|
+
export declare function requireMediaHttpClient({ httpClient }: Pick<MediaOutboundOptions, 'httpClient'>): HttpClientPort;
|
|
31
35
|
//# sourceMappingURL=outbound.d.ts.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { createHttpClient, createNodeGuardedHttpPorts, guardedFetch } from '@jini-ai/platform/http/guarded';
|
|
1
|
+
import { guardedFetch } from '@jini-ai/platform/http/guarded';
|
|
3
2
|
export const defaultMediaOutboundMessages = {
|
|
4
3
|
unsupportedMethod: 'Unsupported media HTTP method',
|
|
5
4
|
unsupportedBody: 'Media HTTP body must be a string or URLSearchParams',
|
|
@@ -13,8 +12,24 @@ export const defaultMediaOutboundMessages = {
|
|
|
13
12
|
* @throws Policy refusals, DNS/transport failures, unsupported bodies or methods.
|
|
14
13
|
* @complexity O(h + b) for h headers and b bounded decoded response bytes.
|
|
15
14
|
*/
|
|
16
|
-
export async function fetchMediaOutbound({ url, timeoutMs }, { init = {}, httpClient,
|
|
15
|
+
export async function fetchMediaOutbound({ url, timeoutMs }, { init = {}, httpClient, outboundMessages }) {
|
|
17
16
|
const messages = { ...defaultMediaOutboundMessages, ...outboundMessages };
|
|
17
|
+
// Every wire refusal happens before any I/O starts.
|
|
18
|
+
const { method, body } = validateMediaWireRequest({ init, messages });
|
|
19
|
+
const client = requireMediaHttpClient({ httpClient });
|
|
20
|
+
return guardedFetch({ client, url, timeoutMs }, {
|
|
21
|
+
method,
|
|
22
|
+
...(init.headers === undefined ? {} : { headers: init.headers }),
|
|
23
|
+
...(body == null ? {} : { body }),
|
|
24
|
+
...(init.signal == null ? {} : { signal: init.signal }),
|
|
25
|
+
totalDeadlineMs: timeoutMs,
|
|
26
|
+
redirect: 'error',
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/** Refuse, in this order: a raw dispatcher, a method outside the guarded client's set, a non-text body.
|
|
30
|
+
* @throws TypeError carrying the matching (possibly host-overridden) message.
|
|
31
|
+
*/
|
|
32
|
+
function validateMediaWireRequest({ init, messages }) {
|
|
18
33
|
if (init.dispatcher !== undefined)
|
|
19
34
|
throw new TypeError(messages.dispatcherRefused);
|
|
20
35
|
const method = (init.method ?? 'GET').toUpperCase();
|
|
@@ -24,29 +39,15 @@ export async function fetchMediaOutbound({ url, timeoutMs }, { init = {}, httpCl
|
|
|
24
39
|
if (body != null && typeof body !== 'string' && !(body instanceof URLSearchParams)) {
|
|
25
40
|
throw new TypeError(messages.unsupportedBody);
|
|
26
41
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
connectTimeoutMs: FETCH_TIMEOUT_MS.GENERATE,
|
|
37
|
-
// Media can contain video; bound buffering at 96 MiB. Hosts may inject a stricter policy.
|
|
38
|
-
maxResponseBytes: 96 * 1024 * 1024,
|
|
39
|
-
maxDecompressedBytes: 96 * 1024 * 1024,
|
|
40
|
-
},
|
|
41
|
-
});
|
|
42
|
-
return guardedFetch({ client, url, timeoutMs }, {
|
|
43
|
-
method,
|
|
44
|
-
...(init.headers === undefined ? {} : { headers: init.headers }),
|
|
45
|
-
...(body == null ? {} : { body }),
|
|
46
|
-
...(init.signal == null ? {} : { signal: init.signal }),
|
|
47
|
-
totalDeadlineMs: timeoutMs,
|
|
48
|
-
redirect: 'error',
|
|
49
|
-
});
|
|
42
|
+
return { method, body };
|
|
43
|
+
}
|
|
44
|
+
/** Resolve the trusted client on legacy context carriers without constructing a fallback.
|
|
45
|
+
* @throws TypeError before I/O if a standalone renderer/runtime has no injected client.
|
|
46
|
+
*/
|
|
47
|
+
export function requireMediaHttpClient({ httpClient }) {
|
|
48
|
+
if (!httpClient)
|
|
49
|
+
throw new TypeError('Media outbound requires an injected guarded HttpClientPort');
|
|
50
|
+
return httpClient;
|
|
50
51
|
}
|
|
51
52
|
function isMediaMethod(method) {
|
|
52
53
|
return method === 'GET' || method === 'HEAD' || method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
|
|
2
|
-
import type { VendorAdapterRegistry } from '../vendor-registry.js';
|
|
2
|
+
import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
|
|
3
3
|
export declare function renderAIHubMixImage({ ctx, credentials }: {
|
|
4
4
|
ctx: RenderContext;
|
|
5
5
|
credentials: ProviderCredentials;
|
|
@@ -58,6 +58,7 @@ import { createRawBytesParser } from '../response-parsers.js';
|
|
|
58
58
|
import { assertAndFetchExternalAsset } from '../ssrf-guard.js';
|
|
59
59
|
import { dispatchVendorRequest, requireApiKey } from '../vendor-adapter.js';
|
|
60
60
|
import { aihubmixAppCodeHeader, aihubmixGeminiImageUrl, aihubmixHeaders, AIHUBMIX_DEFAULT_BASE_URL, aihubmixWireModel, classifyAIHubMixModel } from './aihubmix-shared.js';
|
|
61
|
+
const DEFAULT_IMAGE_PROMPT = 'A high-quality reference image.';
|
|
61
62
|
const NO_CREDENTIAL_MESSAGE = 'no AIHubMix credential — configure an API key or set AIHUBMIX_API_KEY.';
|
|
62
63
|
const aihubmixImageAdapter = {
|
|
63
64
|
requireCredential: requireApiKey({ message: NO_CREDENTIAL_MESSAGE }),
|
|
@@ -78,7 +79,7 @@ const aihubmixImageAdapter = {
|
|
|
78
79
|
...aihubmixAppCodeHeader(),
|
|
79
80
|
},
|
|
80
81
|
body: JSON.stringify({
|
|
81
|
-
contents: [{ role: 'user', parts: [{ text: ctx.prompt ||
|
|
82
|
+
contents: [{ role: 'user', parts: [{ text: ctx.prompt || DEFAULT_IMAGE_PROMPT }] }],
|
|
82
83
|
generationConfig: {
|
|
83
84
|
responseModalities: ['TEXT', 'IMAGE'],
|
|
84
85
|
imageConfig: { aspectRatio: aspect },
|
|
@@ -90,7 +91,7 @@ const aihubmixImageAdapter = {
|
|
|
90
91
|
}
|
|
91
92
|
const body = {
|
|
92
93
|
model: wireModel,
|
|
93
|
-
prompt: ctx.prompt ||
|
|
94
|
+
prompt: ctx.prompt || DEFAULT_IMAGE_PROMPT,
|
|
94
95
|
n: 1,
|
|
95
96
|
size: openaiSizeFor(wireModel, ctx.aspect),
|
|
96
97
|
};
|
|
@@ -112,62 +113,66 @@ const aihubmixImageAdapter = {
|
|
|
112
113
|
};
|
|
113
114
|
},
|
|
114
115
|
async parseResponse({ resp, ctx, request }) {
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
if (!resp.ok) {
|
|
118
|
-
const text = await resp.text().catch(() => '');
|
|
119
|
-
throw new Error(`aihubmix image (gemini) ${resp.status}: ${text.slice(0, 240)}`);
|
|
120
|
-
}
|
|
121
|
-
const data = (await resp.json());
|
|
122
|
-
const parts = data.candidates?.[0]?.content?.parts ?? [];
|
|
123
|
-
const b64 = parts.map((p) => p.inlineData?.data ?? p.inline_data?.data).find((d) => typeof d === 'string' && d.length > 0);
|
|
124
|
-
if (!b64) {
|
|
125
|
-
throw new Error(`aihubmix gemini image response had no inline image data: ${JSON.stringify(data).slice(0, 200)}`);
|
|
126
|
-
}
|
|
127
|
-
const bytes = Buffer.from(b64, 'base64');
|
|
128
|
-
return {
|
|
129
|
-
bytes,
|
|
130
|
-
providerNote: `aihubmix/${wireModel} · ${aspect} · ${bytes.length} bytes (gemini-native)`,
|
|
131
|
-
suggestedExt: '.png',
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
const { wireModel } = request.meta;
|
|
135
|
-
const text = await resp.text();
|
|
136
|
-
if (!resp.ok) {
|
|
137
|
-
throw new Error(`aihubmix ${resp.status}: ${truncate(text, 240)}`);
|
|
138
|
-
}
|
|
139
|
-
let data;
|
|
140
|
-
try {
|
|
141
|
-
data = JSON.parse(text);
|
|
142
|
-
}
|
|
143
|
-
catch {
|
|
144
|
-
throw new Error(`aihubmix non-JSON response: ${truncate(text, 200)}`);
|
|
145
|
-
}
|
|
146
|
-
const entry = Array.isArray(data.data) ? data.data[0] : undefined;
|
|
147
|
-
if (!entry)
|
|
148
|
-
throw new Error('aihubmix response had no data[0]');
|
|
149
|
-
let bytes;
|
|
150
|
-
if (entry.b64_json) {
|
|
151
|
-
bytes = Buffer.from(entry.b64_json, 'base64');
|
|
152
|
-
}
|
|
153
|
-
else if (entry.url) {
|
|
154
|
-
const imgResp = await assertAndFetchExternalAsset({ url: entry.url }, { ...ctx, init: withRequestInit(ctx) });
|
|
155
|
-
if (!imgResp.ok)
|
|
156
|
-
throw new Error(`aihubmix image fetch ${imgResp.status}`);
|
|
157
|
-
bytes = Buffer.from(await imgResp.arrayBuffer());
|
|
158
|
-
}
|
|
159
|
-
else {
|
|
160
|
-
throw new Error('aihubmix response had neither b64_json nor url');
|
|
161
|
-
}
|
|
162
|
-
return {
|
|
163
|
-
bytes,
|
|
164
|
-
providerNote: `aihubmix/${wireModel} · ${ctx.aspect} · ${bytes.length} bytes`,
|
|
165
|
-
suggestedExt: '.png',
|
|
166
|
-
};
|
|
116
|
+
const { meta } = request;
|
|
117
|
+
return meta.kind === 'gemini' ? parseGeminiImageResponse({ resp, meta }) : parseOpenAIImageResponse({ resp, ctx, meta });
|
|
167
118
|
},
|
|
168
119
|
};
|
|
120
|
+
/** First non-empty base64 string across the parts; camelCase `inlineData` wins over `inline_data` within one part. */
|
|
121
|
+
function firstInlineImageData(parts) {
|
|
122
|
+
return parts.map((p) => p.inlineData?.data ?? p.inline_data?.data).find((d) => typeof d === 'string' && d.length > 0);
|
|
123
|
+
}
|
|
124
|
+
async function parseGeminiImageResponse({ resp, meta }) {
|
|
125
|
+
if (!resp.ok) {
|
|
126
|
+
const text = await resp.text().catch(() => '');
|
|
127
|
+
throw new Error(`aihubmix image (gemini) ${resp.status}: ${text.slice(0, 240)}`);
|
|
128
|
+
}
|
|
129
|
+
const data = (await resp.json());
|
|
130
|
+
const b64 = firstInlineImageData(data.candidates?.[0]?.content?.parts ?? []);
|
|
131
|
+
if (!b64) {
|
|
132
|
+
throw new Error(`aihubmix gemini image response had no inline image data: ${JSON.stringify(data).slice(0, 200)}`);
|
|
133
|
+
}
|
|
134
|
+
const bytes = Buffer.from(b64, 'base64');
|
|
135
|
+
return {
|
|
136
|
+
bytes,
|
|
137
|
+
providerNote: `aihubmix/${meta.wireModel} · ${meta.aspect} · ${bytes.length} bytes (gemini-native)`,
|
|
138
|
+
suggestedExt: '.png',
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
async function parseOpenAIImageResponse({ resp, ctx, meta }) {
|
|
142
|
+
const text = await resp.text();
|
|
143
|
+
if (!resp.ok) {
|
|
144
|
+
throw new Error(`aihubmix ${resp.status}: ${truncate(text, 240)}`);
|
|
145
|
+
}
|
|
146
|
+
let data;
|
|
147
|
+
try {
|
|
148
|
+
data = JSON.parse(text);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
throw new Error(`aihubmix non-JSON response: ${truncate(text, 200)}`);
|
|
152
|
+
}
|
|
153
|
+
const entry = Array.isArray(data.data) ? data.data[0] : undefined;
|
|
154
|
+
if (!entry)
|
|
155
|
+
throw new Error('aihubmix response had no data[0]');
|
|
156
|
+
const bytes = await openAIEntryBytes({ entry, ctx });
|
|
157
|
+
return {
|
|
158
|
+
bytes,
|
|
159
|
+
providerNote: `aihubmix/${meta.wireModel} · ${ctx.aspect} · ${bytes.length} bytes`,
|
|
160
|
+
suggestedExt: '.png',
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
/** Inline `b64_json` first; otherwise the `url`, downloaded through the SSRF guard (it is attacker-controllable). */
|
|
164
|
+
async function openAIEntryBytes({ entry, ctx }) {
|
|
165
|
+
if (entry.b64_json)
|
|
166
|
+
return Buffer.from(entry.b64_json, 'base64');
|
|
167
|
+
if (!entry.url)
|
|
168
|
+
throw new Error('aihubmix response had neither b64_json nor url');
|
|
169
|
+
const imgResp = await assertAndFetchExternalAsset({ url: entry.url }, { ...ctx, init: withRequestInit(ctx) });
|
|
170
|
+
if (!imgResp.ok)
|
|
171
|
+
throw new Error(`aihubmix image fetch ${imgResp.status}`);
|
|
172
|
+
return Buffer.from(await imgResp.arrayBuffer());
|
|
173
|
+
}
|
|
169
174
|
export async function renderAIHubMixImage({ ctx, credentials }) {
|
|
170
|
-
return dispatchVendorRequest({ adapter: aihubmixImageAdapter, ctx
|
|
175
|
+
return dispatchVendorRequest({ adapter: aihubmixImageAdapter, ctx, credentials });
|
|
171
176
|
}
|
|
172
177
|
const aihubmixTTSAdapter = {
|
|
173
178
|
requireCredential: requireApiKey({ message: NO_CREDENTIAL_MESSAGE }),
|
|
@@ -197,7 +202,7 @@ const aihubmixTTSAdapter = {
|
|
|
197
202
|
}),
|
|
198
203
|
};
|
|
199
204
|
export async function renderAIHubMixTTS({ ctx, credentials }) {
|
|
200
|
-
return dispatchVendorRequest({ adapter: aihubmixTTSAdapter, ctx
|
|
205
|
+
return dispatchVendorRequest({ adapter: aihubmixTTSAdapter, ctx, credentials });
|
|
201
206
|
}
|
|
202
207
|
/** Explicit composition: importing a renderer never changes another module's registry. */
|
|
203
208
|
export function registerVendorAdapters({ registry }, _optional = {}) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
|
|
2
|
-
import type { VendorAdapterRegistry } from '../vendor-registry.js';
|
|
2
|
+
import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
|
|
3
3
|
export declare const CUSTOM_IMAGE_MODEL_ID = "custom-image";
|
|
4
4
|
export declare function renderCustomOpenAIImage({ ctx, credentials }: {
|
|
5
5
|
ctx: RenderContext;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
|
|
2
|
-
import type { VendorAdapterRegistry } from '../vendor-registry.js';
|
|
2
|
+
import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
|
|
3
3
|
export declare function renderElevenLabsTTS({ ctx, credentials }: {
|
|
4
4
|
ctx: RenderContext;
|
|
5
5
|
credentials: ProviderCredentials;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
|
|
2
|
-
import type { VendorAdapterRegistry } from '../vendor-registry.js';
|
|
2
|
+
import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
|
|
3
3
|
export declare function renderFishAudioTTS({ ctx, credentials }: {
|
|
4
4
|
ctx: RenderContext;
|
|
5
5
|
credentials: ProviderCredentials;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
|
|
2
|
-
import type { VendorAdapterRegistry } from '../vendor-registry.js';
|
|
2
|
+
import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
|
|
3
3
|
/**
|
|
4
4
|
* xAI's Imagine API accepts a wide list of aspect ratios (1:1, 16:9, 9:16,
|
|
5
5
|
* 4:3, 3:4, 3:2, 2:3, 2:1, 1:2, 19.5:9, 9:19.5, 20:9, 9:20, auto) —
|
|
@@ -17,5 +17,5 @@ export interface ImageRouterVideoMeta {
|
|
|
17
17
|
* context's own `wireModel`.
|
|
18
18
|
* @complexity O(1) per built request; one vendor round trip per parse.
|
|
19
19
|
*/
|
|
20
|
-
export declare function createImageRouterVideoPollingAdapter(_required: Record<string, never>,
|
|
20
|
+
export declare function createImageRouterVideoPollingAdapter(_required: Record<string, never>, config?: ImageRouterVideoConfig): PollingVendorAdapter<ImageRouterVideoMeta>;
|
|
21
21
|
//# sourceMappingURL=imagerouter-video-async.d.ts.map
|