@jini-ai/integrations 0.4.2 → 0.6.10
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 +99 -1
- package/README.md +1 -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.d.ts +4 -0
- package/dist/credentialed-http/credentialed-request.js +61 -77
- package/dist/credentialed-http/response-redaction.d.ts +15 -0
- package/dist/credentialed-http/response-redaction.js +82 -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/saved-requests/definition.d.ts +17 -0
- package/dist/saved-requests/definition.js +84 -0
- package/dist/saved-requests/execute.d.ts +17 -0
- package/dist/saved-requests/execute.js +95 -0
- package/dist/saved-requests/index.d.ts +6 -0
- package/dist/saved-requests/index.js +4 -0
- package/dist/saved-requests/projection.d.ts +9 -0
- package/dist/saved-requests/projection.js +48 -0
- package/dist/saved-requests/schema.d.ts +7 -0
- package/dist/saved-requests/schema.js +73 -0
- package/dist/saved-requests/types.d.ts +58 -0
- package/dist/saved-requests/types.js +2 -0
- package/dist/saved-requests/validation.d.ts +46 -0
- package/dist/saved-requests/validation.js +66 -0
- 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 +46 -9
|
@@ -28,26 +28,24 @@ export function withRequestInit(ctx, init = {}) {
|
|
|
28
28
|
...init,
|
|
29
29
|
};
|
|
30
30
|
}
|
|
31
|
+
// PNG (`89 50 4E 47`, min 8 bytes) has no entry: it is also the default, so
|
|
32
|
+
// matching it explicitly could never change the result.
|
|
33
|
+
const IMAGE_SIGNATURES = [
|
|
34
|
+
{ ext: '.jpg', runs: [[0, [0xff, 0xd8, 0xff]]] },
|
|
35
|
+
{
|
|
36
|
+
ext: '.webp',
|
|
37
|
+
runs: [
|
|
38
|
+
[0, [0x52, 0x49, 0x46, 0x46]], // RIFF
|
|
39
|
+
[8, [0x57, 0x45, 0x42, 0x50]], // WEBP
|
|
40
|
+
],
|
|
41
|
+
},
|
|
42
|
+
];
|
|
43
|
+
function matchesSignature(bytes, signature) {
|
|
44
|
+
return signature.runs.every(([offset, magic]) => magic.every((byte, i) => bytes[offset + i] === byte));
|
|
45
|
+
}
|
|
31
46
|
/** Sniffs an image byte buffer's format from its magic bytes (jpg/png/webp), defaulting to `.png`. */
|
|
32
47
|
export function sniffImageExt(bytes) {
|
|
33
|
-
|
|
34
|
-
return '.jpg';
|
|
35
|
-
}
|
|
36
|
-
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) {
|
|
37
|
-
return '.png';
|
|
38
|
-
}
|
|
39
|
-
if (bytes.length >= 12 &&
|
|
40
|
-
bytes[0] === 0x52 &&
|
|
41
|
-
bytes[1] === 0x49 &&
|
|
42
|
-
bytes[2] === 0x46 &&
|
|
43
|
-
bytes[3] === 0x46 &&
|
|
44
|
-
bytes[8] === 0x57 &&
|
|
45
|
-
bytes[9] === 0x45 &&
|
|
46
|
-
bytes[10] === 0x42 &&
|
|
47
|
-
bytes[11] === 0x50) {
|
|
48
|
-
return '.webp';
|
|
49
|
-
}
|
|
50
|
-
return '.png';
|
|
48
|
+
return IMAGE_SIGNATURES.find((signature) => matchesSignature(bytes, signature))?.ext ?? '.png';
|
|
51
49
|
}
|
|
52
50
|
export const AZURE_DEFAULT_API_VERSION = '2024-02-01';
|
|
53
51
|
/**
|
|
@@ -75,90 +73,85 @@ export function detectAzureEndpoint(baseUrl) {
|
|
|
75
73
|
export function normalizeOpenAICompatiblePath(pathname, endpoint, mode) {
|
|
76
74
|
const strippedPath = pathname.replace(/\/+$/, '');
|
|
77
75
|
const generationsSuffix = `/${endpoint}/generations`;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
return strippedPath;
|
|
87
|
-
return `${strippedPath.slice(0, -editsSuffix.length)}${generationsSuffix}`;
|
|
88
|
-
}
|
|
89
|
-
return mode === 'edits' && editsSuffix ? `${strippedPath}${editsSuffix}` : `${strippedPath}${generationsSuffix}`;
|
|
76
|
+
if (endpoint === 'videos') {
|
|
77
|
+
// Videos have no edits endpoint, so `edits` mode still targets generations.
|
|
78
|
+
return strippedPath.endsWith(generationsSuffix) ? strippedPath : `${strippedPath}${generationsSuffix}`;
|
|
79
|
+
}
|
|
80
|
+
const editsSuffix = '/images/edits';
|
|
81
|
+
const knownSuffix = [generationsSuffix, editsSuffix].find((suffix) => strippedPath.endsWith(suffix));
|
|
82
|
+
const prefix = knownSuffix ? strippedPath.slice(0, -knownSuffix.length) : strippedPath;
|
|
83
|
+
return `${prefix}${mode === 'edits' ? editsSuffix : generationsSuffix}`;
|
|
90
84
|
}
|
|
91
|
-
/**
|
|
92
|
-
|
|
85
|
+
/** Points `baseUrl`'s path at the given endpoint/mode, keeping any query string; an unparseable base URL is normalized as a bare path. */
|
|
86
|
+
function buildOpenAICompatibleUrl(baseUrl, endpoint, mode) {
|
|
93
87
|
let parsed;
|
|
94
88
|
try {
|
|
95
89
|
parsed = new URL(baseUrl);
|
|
96
90
|
}
|
|
97
91
|
catch {
|
|
98
|
-
|
|
99
|
-
return normalizeOpenAICompatiblePath(stripped, endpoint, 'generations');
|
|
92
|
+
return normalizeOpenAICompatiblePath(baseUrl, endpoint, mode);
|
|
100
93
|
}
|
|
101
|
-
parsed.pathname = normalizeOpenAICompatiblePath(parsed.pathname, endpoint,
|
|
94
|
+
parsed.pathname = normalizeOpenAICompatiblePath(parsed.pathname, endpoint, mode);
|
|
102
95
|
return parsed.toString();
|
|
103
96
|
}
|
|
97
|
+
/** Appends the default Azure `api-version` when the endpoint is Azure and the caller didn't supply one. */
|
|
98
|
+
function applyDefaultAzureApiVersion(parsed, isAzure) {
|
|
99
|
+
if (isAzure && !parsed.searchParams.has('api-version')) {
|
|
100
|
+
parsed.searchParams.set('api-version', AZURE_DEFAULT_API_VERSION);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** Builds the full `/{endpoint}/generations` URL, preserving any user-supplied query string. */
|
|
104
|
+
export function buildOpenAICompatibleGenerationUrl(baseUrl, endpoint) {
|
|
105
|
+
return buildOpenAICompatibleUrl(baseUrl, endpoint, 'generations');
|
|
106
|
+
}
|
|
104
107
|
/** Builds the `/images/generations` URL, appending the default Azure `api-version` when the caller didn't supply one. */
|
|
105
108
|
export function buildOpenAIImageUrl(baseUrl, isAzure) {
|
|
109
|
+
const url = buildOpenAICompatibleGenerationUrl(baseUrl, 'images');
|
|
106
110
|
let parsed;
|
|
107
111
|
try {
|
|
108
|
-
parsed = new URL(
|
|
112
|
+
parsed = new URL(url);
|
|
109
113
|
}
|
|
110
114
|
catch {
|
|
111
115
|
// Bad URL — fall back to naive concat so the upstream error is
|
|
112
116
|
// surfaced through the normal HTTP path rather than a parse crash.
|
|
113
|
-
return
|
|
114
|
-
}
|
|
115
|
-
if (isAzure && !parsed.searchParams.has('api-version')) {
|
|
116
|
-
parsed.searchParams.set('api-version', AZURE_DEFAULT_API_VERSION);
|
|
117
|
+
return url;
|
|
117
118
|
}
|
|
119
|
+
applyDefaultAzureApiVersion(parsed, isAzure);
|
|
118
120
|
return parsed.toString();
|
|
119
121
|
}
|
|
120
122
|
/** Builds the `/images/edits` URL (used when a reference image is present). */
|
|
121
123
|
export function buildOpenAIImageEditUrl(baseUrl) {
|
|
122
|
-
|
|
123
|
-
try {
|
|
124
|
-
parsed = new URL(baseUrl);
|
|
125
|
-
}
|
|
126
|
-
catch {
|
|
127
|
-
const stripped = baseUrl.replace(/\/$/, '');
|
|
128
|
-
return normalizeOpenAICompatiblePath(stripped, 'images', 'edits');
|
|
129
|
-
}
|
|
130
|
-
parsed.pathname = normalizeOpenAICompatiblePath(parsed.pathname, 'images', 'edits');
|
|
131
|
-
return parsed.toString();
|
|
124
|
+
return buildOpenAICompatibleUrl(baseUrl, 'images', 'edits');
|
|
132
125
|
}
|
|
133
126
|
/** Builds the `/videos/generations` URL. */
|
|
134
127
|
export function buildOpenAIVideoUrl(baseUrl) {
|
|
135
128
|
return buildOpenAICompatibleGenerationUrl(baseUrl, 'videos');
|
|
136
129
|
}
|
|
137
|
-
|
|
130
|
+
// gpt-image-1.5 / gpt-image-2 accept arbitrary sizes up to 4096; concrete
|
|
131
|
+
// sizes tuned to common aspects are picked so the API never negotiates
|
|
132
|
+
// them down silently.
|
|
133
|
+
const GPT_IMAGE_SIZES = new Map([
|
|
134
|
+
['16:9', '1792x1024'],
|
|
135
|
+
['9:16', '1024x1792'],
|
|
136
|
+
['4:3', '1408x1056'],
|
|
137
|
+
['3:4', '1056x1408'],
|
|
138
|
+
]);
|
|
139
|
+
const DALLE_3_SIZES = new Map([
|
|
140
|
+
['16:9', '1792x1024'],
|
|
141
|
+
['9:16', '1024x1792'],
|
|
142
|
+
]);
|
|
143
|
+
// dall-e-2 only supports 256/512/1024 squares.
|
|
144
|
+
const SQUARE_ONLY_SIZES = new Map();
|
|
145
|
+
function sizeTableFor(model) {
|
|
146
|
+
if (model.startsWith('gpt-image-'))
|
|
147
|
+
return GPT_IMAGE_SIZES;
|
|
148
|
+
if (model === 'dall-e-3')
|
|
149
|
+
return DALLE_3_SIZES;
|
|
150
|
+
return SQUARE_ONLY_SIZES;
|
|
151
|
+
}
|
|
152
|
+
/** Picks an image `size` string tuned to the model family + requested aspect ratio, defaulting to the `1024x1024` square. */
|
|
138
153
|
export function openaiSizeFor(model, aspect) {
|
|
139
|
-
|
|
140
|
-
// sizes tuned to common aspects are picked so the API never negotiates
|
|
141
|
-
// them down silently.
|
|
142
|
-
if (model.startsWith('gpt-image-')) {
|
|
143
|
-
if (aspect === '16:9')
|
|
144
|
-
return '1792x1024';
|
|
145
|
-
if (aspect === '9:16')
|
|
146
|
-
return '1024x1792';
|
|
147
|
-
if (aspect === '4:3')
|
|
148
|
-
return '1408x1056';
|
|
149
|
-
if (aspect === '3:4')
|
|
150
|
-
return '1056x1408';
|
|
151
|
-
return '1024x1024';
|
|
152
|
-
}
|
|
153
|
-
if (model === 'dall-e-3') {
|
|
154
|
-
if (aspect === '16:9')
|
|
155
|
-
return '1792x1024';
|
|
156
|
-
if (aspect === '9:16')
|
|
157
|
-
return '1024x1792';
|
|
158
|
-
return '1024x1024';
|
|
159
|
-
}
|
|
160
|
-
// dall-e-2 only supports 256/512/1024 squares.
|
|
161
|
-
return '1024x1024';
|
|
154
|
+
return sizeTableFor(model).get(aspect ?? '') ?? '1024x1024';
|
|
162
155
|
}
|
|
163
156
|
/** Builds the `/audio/speech` URL, appending the default Azure `api-version` when the caller didn't supply one. */
|
|
164
157
|
export function buildOpenAISpeechUrl(baseUrl, isAzure) {
|
|
@@ -171,9 +164,7 @@ export function buildOpenAISpeechUrl(baseUrl, isAzure) {
|
|
|
171
164
|
return `${stripped}/audio/speech`;
|
|
172
165
|
}
|
|
173
166
|
parsed.pathname = parsed.pathname.replace(/\/+$/, '') + '/audio/speech';
|
|
174
|
-
|
|
175
|
-
parsed.searchParams.set('api-version', AZURE_DEFAULT_API_VERSION);
|
|
176
|
-
}
|
|
167
|
+
applyDefaultAzureApiVersion(parsed, isAzure);
|
|
177
168
|
return parsed.toString();
|
|
178
169
|
}
|
|
179
170
|
/** Parses an OpenAI-compatible JSON response, throwing a clear, provider-tagged error on a non-OK status or non-JSON body. */
|
|
@@ -195,24 +186,36 @@ export async function parseOpenAICompatibleJson(resp, providerTag) {
|
|
|
195
186
|
* @complexity O(b) time and space for b generated bytes, bounded by outbound policy for downloads.
|
|
196
187
|
*/
|
|
197
188
|
export async function bytesFromOpenAICompatibleData({ data, providerTag }, { requestInit = {}, ...outbound } = {}) {
|
|
198
|
-
const
|
|
199
|
-
const entry = record && Array.isArray(record.data) ? record.data[0] : undefined;
|
|
189
|
+
const entry = firstDataEntry(data);
|
|
200
190
|
if (!entry)
|
|
201
191
|
throw new Error(`${providerTag} response had no data[0]`);
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
192
|
+
const b64Json = stringOrUndefined(entry.b64_json);
|
|
193
|
+
if (b64Json) {
|
|
194
|
+
// A data-URL (`data:<mime>;base64,<payload>`) keeps only what follows its first comma;
|
|
195
|
+
// with no comma `indexOf` is -1, so the whole string is decoded.
|
|
196
|
+
return Buffer.from(b64Json.slice(b64Json.indexOf(',') + 1), 'base64');
|
|
197
|
+
}
|
|
198
|
+
const url = stringOrUndefined(entry.url);
|
|
199
|
+
if (url) {
|
|
207
200
|
// Downloading already-generated bytes from the vendor's CDN, not waiting on generation itself
|
|
208
201
|
// — UPLOAD-class (2min), not GENERATE-class (10min): see FETCH_TIMEOUT_MS's own doc.
|
|
209
|
-
const mediaResp = await assertAndFetchExternalAsset({ url
|
|
202
|
+
const mediaResp = await assertAndFetchExternalAsset({ url }, { ...outbound, init: requestInit });
|
|
210
203
|
if (!mediaResp.ok) {
|
|
211
204
|
throw new Error(`${providerTag} media fetch ${mediaResp.status}`);
|
|
212
205
|
}
|
|
213
|
-
|
|
214
|
-
return Buffer.from(arr);
|
|
206
|
+
return Buffer.from(await mediaResp.arrayBuffer());
|
|
215
207
|
}
|
|
216
208
|
throw new Error(`${providerTag} response had neither b64_json nor url`);
|
|
217
209
|
}
|
|
210
|
+
/** `data.data[0]` of an OpenAI-compatible response, or `undefined` when the body has no such entry. */
|
|
211
|
+
function firstDataEntry(data) {
|
|
212
|
+
const record = data;
|
|
213
|
+
if (!record || !Array.isArray(record.data))
|
|
214
|
+
return undefined;
|
|
215
|
+
return record.data[0] ?? undefined;
|
|
216
|
+
}
|
|
217
|
+
/** Narrows to a string; callers treat an empty string as absent through their own truthiness check. */
|
|
218
|
+
function stringOrUndefined(value) {
|
|
219
|
+
return typeof value === 'string' ? value : undefined;
|
|
220
|
+
}
|
|
218
221
|
//# sourceMappingURL=openai-compatible.js.map
|
|
@@ -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;
|