@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.
Files changed (116) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/api-connections/access-token.d.ts +9 -0
  3. package/dist/api-connections/access-token.js +92 -0
  4. package/dist/api-connections/account-actions.d.ts +40 -0
  5. package/dist/api-connections/account-actions.js +110 -0
  6. package/dist/api-connections/attempt-state.d.ts +28 -0
  7. package/dist/api-connections/attempt-state.js +73 -0
  8. package/dist/api-connections/authorization.d.ts +45 -0
  9. package/dist/api-connections/authorization.js +120 -0
  10. package/dist/api-connections/deps.d.ts +41 -0
  11. package/dist/api-connections/deps.js +13 -0
  12. package/dist/api-connections/descriptor.d.ts +6 -0
  13. package/dist/api-connections/descriptor.js +111 -0
  14. package/dist/api-connections/errors.d.ts +23 -0
  15. package/dist/api-connections/errors.js +24 -0
  16. package/dist/api-connections/finish-authorization.d.ts +24 -0
  17. package/dist/api-connections/finish-authorization.js +117 -0
  18. package/dist/api-connections/index.d.ts +18 -0
  19. package/dist/api-connections/index.js +10 -0
  20. package/dist/api-connections/install-credential.d.ts +19 -0
  21. package/dist/api-connections/install-credential.js +12 -0
  22. package/dist/api-connections/keys.d.ts +27 -0
  23. package/dist/api-connections/keys.js +22 -0
  24. package/dist/api-connections/ports.d.ts +73 -0
  25. package/dist/api-connections/ports.js +2 -0
  26. package/dist/api-connections/records.d.ts +27 -0
  27. package/dist/api-connections/records.js +52 -0
  28. package/dist/api-connections/request-checks.d.ts +18 -0
  29. package/dist/api-connections/request-checks.js +67 -0
  30. package/dist/api-connections/service.d.ts +25 -0
  31. package/dist/api-connections/service.js +26 -0
  32. package/dist/api-connections/status.d.ts +28 -0
  33. package/dist/api-connections/status.js +36 -0
  34. package/dist/api-connections/token-store/errors.d.ts +20 -0
  35. package/dist/api-connections/token-store/errors.js +38 -0
  36. package/dist/api-connections/token-store/index.d.ts +6 -0
  37. package/dist/api-connections/token-store/index.js +6 -0
  38. package/dist/api-connections/token-store/record.d.ts +69 -0
  39. package/dist/api-connections/token-store/record.js +97 -0
  40. package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
  41. package/dist/api-connections/token-store/vault-token-store.js +215 -0
  42. package/dist/api-connections/types.d.ts +101 -0
  43. package/dist/api-connections/types.js +9 -0
  44. package/dist/credentialed-http/auth-schemes.js +8 -4
  45. package/dist/credentialed-http/credentialed-request.js +47 -77
  46. package/dist/credentialed-http/response-redaction.d.ts +5 -0
  47. package/dist/credentialed-http/response-redaction.js +62 -0
  48. package/dist/media-providers/catalog.d.ts +3 -1
  49. package/dist/media-providers/catalog.js +3 -1
  50. package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
  51. package/dist/media-providers/dispatch/async-operation-store.js +75 -37
  52. package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
  53. package/dist/media-providers/dispatch/context.js +10 -2
  54. package/dist/media-providers/dispatch/engine.d.ts +6 -3
  55. package/dist/media-providers/dispatch/engine.js +99 -109
  56. package/dist/media-providers/dispatch/index.d.ts +4 -2
  57. package/dist/media-providers/dispatch/index.js +3 -1
  58. package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
  59. package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
  60. package/dist/media-providers/dispatch/node.d.ts +13 -0
  61. package/dist/media-providers/dispatch/node.js +24 -0
  62. package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
  63. package/dist/media-providers/dispatch/openai-compatible.js +90 -87
  64. package/dist/media-providers/dispatch/operation-runtime.js +116 -89
  65. package/dist/media-providers/dispatch/outbound.d.ts +8 -4
  66. package/dist/media-providers/dispatch/outbound.js +27 -26
  67. package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
  68. package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
  69. package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
  70. package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
  71. package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
  72. package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
  73. package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
  74. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
  75. package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
  76. package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
  77. package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
  78. package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
  79. package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
  80. package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
  81. package/dist/media-providers/dispatch/providers/openai.js +51 -47
  82. package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
  83. package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
  84. package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
  85. package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
  86. package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
  87. package/dist/media-providers/dispatch/response-parsers.js +37 -21
  88. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +9 -29
  89. package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
  90. package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
  91. package/dist/media-providers/dispatch/types.d.ts +76 -2
  92. package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
  93. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  94. package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
  95. package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
  96. package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
  97. package/dist/media-providers/dispatch/vendor-registry.js +14 -42
  98. package/dist/media-providers/policy.js +25 -17
  99. package/dist/media-providers/providers.d.ts +5 -0
  100. package/dist/media-providers/providers.js +2 -0
  101. package/dist/media-providers/sqlite-task-store.js +12 -80
  102. package/dist/media-providers/staging.js +77 -58
  103. package/dist/media-providers/task-lifecycle.d.ts +33 -0
  104. package/dist/media-providers/task-lifecycle.js +124 -0
  105. package/dist/media-providers/task-store.js +8 -86
  106. package/dist/media-providers/ui-defaults.d.ts +10 -0
  107. package/dist/media-providers/ui-defaults.js +167 -0
  108. package/dist/media-providers/video-request.js +112 -90
  109. package/dist/webhooks/delivery.d.ts +14 -0
  110. package/dist/webhooks/delivery.js +41 -10
  111. package/dist/webhooks/index.d.ts +1 -0
  112. package/dist/webhooks/index.js +1 -0
  113. package/dist/webhooks/ports.d.ts +23 -0
  114. package/dist/webhooks/worker.d.ts +83 -0
  115. package/dist/webhooks/worker.js +105 -0
  116. package/package.json +31 -8
@@ -211,6 +211,37 @@ export declare function hydrateAsyncOperationRecord({ raw }: {
211
211
  }): AsyncOperationRecord;
212
212
  /** Exported for the same reason as `TERMINAL_STATUSES` — see its doc. */
213
213
  export declare function assertTransition(from: AsyncOperationStatus, to: AsyncOperationStatus): void;
214
+ /**
215
+ * Create-time validation shared by every store, in order: `maxAttempts`, `deadlineAt`, then the
216
+ * `state` allowlist. The duplicate-id check stays with each store, which alone knows its storage
217
+ * and runs it first. Exported for the same reason as `TERMINAL_STATUSES` — see its doc.
218
+ * @throws RangeError for a bad bound; `Error` (see `assertNoCredentialMaterial`) for a bad state.
219
+ */
220
+ export declare function assertValidCreateInput({ input }: {
221
+ input: AsyncOperationCreateInput;
222
+ }): void;
223
+ /**
224
+ * True when a fenced write names a lease owner the row no longer has. Such a write is a no-op that
225
+ * returns the row unchanged — see `AsyncOperationUpdateOptions.leaseOwner`. Exported for the same
226
+ * reason as `TERMINAL_STATUSES`.
227
+ */
228
+ export declare function isFencedOut({ existing, options }: {
229
+ existing: AsyncOperationRecord;
230
+ options: AsyncOperationUpdateOptions | undefined;
231
+ }): boolean;
232
+ /**
233
+ * The update rule every store applies after its lease fence: reject credential material in a
234
+ * patched `state`, then an illegal status transition, then merge. Returns the next record without
235
+ * copying `state` — the caller decides how to store it. Exported for the same reason as
236
+ * `TERMINAL_STATUSES`.
237
+ * @throws `Error` for credential material; `RangeError` for an illegal transition.
238
+ */
239
+ export declare function mergeAsyncOperationPatch({ existing, patch }: {
240
+ existing: AsyncOperationRecord;
241
+ patch: AsyncOperationPatch;
242
+ }, { now }: {
243
+ now: number;
244
+ }): AsyncOperationRecord;
214
245
  /**
215
246
  * Creates the in-memory reference `AsyncOperationStore`. No persistence — a durable adapter
216
247
  * implements the same interface; every method here is written so the equivalent SQL is a direct
@@ -103,7 +103,7 @@ export function assertNoCredentialMaterial({ state }) {
103
103
  * @complexity O(1).
104
104
  */
105
105
  export function hydrateAsyncOperationRecord({ raw }) {
106
- const stored = typeof raw.schemaVersion === 'number' ? raw.schemaVersion : 0;
106
+ const stored = numberOr(raw.schemaVersion, 0);
107
107
  if (stored > ASYNC_OPERATION_SCHEMA_VERSION) {
108
108
  throw new Error(`async operation row was written at schema version ${stored}, newer than this build understands (${ASYNC_OPERATION_SCHEMA_VERSION}) — upgrade rather than risk misreading it`);
109
109
  }
@@ -117,23 +117,31 @@ export function hydrateAsyncOperationRecord({ raw }) {
117
117
  routeKey: String(raw.routeKey),
118
118
  ownerRef: String(raw.ownerRef),
119
119
  status: raw.status ?? 'submitted',
120
- attempts: typeof raw.attempts === 'number' ? raw.attempts : 0,
120
+ attempts: numberOr(raw.attempts, 0),
121
121
  maxAttempts: Number(raw.maxAttempts),
122
122
  deadlineAt: Number(raw.deadlineAt),
123
- nextPollAt: typeof raw.nextPollAt === 'number' ? raw.nextPollAt : now,
123
+ nextPollAt: numberOr(raw.nextPollAt, now),
124
124
  leaseOwner: raw.leaseOwner ?? null,
125
125
  leaseExpiresAt: raw.leaseExpiresAt ?? null,
126
126
  state: raw.state ?? null,
127
127
  result: raw.result ?? null,
128
128
  error: raw.error ?? null,
129
- createdAt: typeof raw.createdAt === 'number' ? raw.createdAt : now,
130
- updatedAt: typeof raw.updatedAt === 'number' ? raw.updatedAt : now,
129
+ createdAt: numberOr(raw.createdAt, now),
130
+ updatedAt: numberOr(raw.updatedAt, now),
131
131
  };
132
132
  }
133
+ /** A persisted number column, or `fallback` when the raw value is absent or not a number. */
134
+ function numberOr(value, fallback) {
135
+ return typeof value === 'number' ? value : fallback;
136
+ }
137
+ /** Deep-copies a `state` handle so no caller-held object aliases a stored row. */
138
+ function cloneState(state) {
139
+ return state === null ? null : structuredClone(state);
140
+ }
133
141
  function cloneRecord(row) {
134
142
  return {
135
143
  ...row,
136
- state: row.state === null ? null : structuredClone(row.state),
144
+ state: cloneState(row.state),
137
145
  result: row.result === null ? null : { ...row.result },
138
146
  error: row.error === null ? null : { ...row.error },
139
147
  };
@@ -147,6 +155,58 @@ export function assertTransition(from, to) {
147
155
  throw new RangeError(`Invalid async operation transition: "${from}" -> "${to}"`);
148
156
  }
149
157
  }
158
+ /**
159
+ * Create-time validation shared by every store, in order: `maxAttempts`, `deadlineAt`, then the
160
+ * `state` allowlist. The duplicate-id check stays with each store, which alone knows its storage
161
+ * and runs it first. Exported for the same reason as `TERMINAL_STATUSES` — see its doc.
162
+ * @throws RangeError for a bad bound; `Error` (see `assertNoCredentialMaterial`) for a bad state.
163
+ */
164
+ export function assertValidCreateInput({ input }) {
165
+ if (!Number.isFinite(input.maxAttempts) || input.maxAttempts < 1) {
166
+ throw new RangeError(`Invalid maxAttempts: ${input.maxAttempts} must be a finite number >= 1`);
167
+ }
168
+ if (!Number.isFinite(input.deadlineAt)) {
169
+ throw new RangeError(`Invalid deadlineAt: ${input.deadlineAt} must be a finite epoch-ms timestamp`);
170
+ }
171
+ assertNoCredentialMaterial({ state: input.state });
172
+ }
173
+ /**
174
+ * True when a fenced write names a lease owner the row no longer has. Such a write is a no-op that
175
+ * returns the row unchanged — see `AsyncOperationUpdateOptions.leaseOwner`. Exported for the same
176
+ * reason as `TERMINAL_STATUSES`.
177
+ */
178
+ export function isFencedOut({ existing, options }) {
179
+ return options?.leaseOwner !== undefined && existing.leaseOwner !== options.leaseOwner;
180
+ }
181
+ /** A key present in the patch replaces the field (`undefined` clears it to `null`); an absent key keeps it. */
182
+ function patchedNullable({ patch, existing, key }) {
183
+ return key in patch ? (patch[key] ?? null) : existing[key];
184
+ }
185
+ /**
186
+ * The update rule every store applies after its lease fence: reject credential material in a
187
+ * patched `state`, then an illegal status transition, then merge. Returns the next record without
188
+ * copying `state` — the caller decides how to store it. Exported for the same reason as
189
+ * `TERMINAL_STATUSES`.
190
+ * @throws `Error` for credential material; `RangeError` for an illegal transition.
191
+ */
192
+ export function mergeAsyncOperationPatch({ existing, patch }, { now }) {
193
+ if ('state' in patch)
194
+ assertNoCredentialMaterial({ state: patch.state });
195
+ const status = patch.status ?? existing.status;
196
+ assertTransition(existing.status, status);
197
+ return {
198
+ ...existing,
199
+ status,
200
+ attempts: patch.attempts ?? existing.attempts,
201
+ nextPollAt: patch.nextPollAt ?? existing.nextPollAt,
202
+ state: patchedNullable({ patch, existing, key: 'state' }),
203
+ result: patchedNullable({ patch, existing, key: 'result' }),
204
+ error: patchedNullable({ patch, existing, key: 'error' }),
205
+ leaseOwner: patchedNullable({ patch, existing, key: 'leaseOwner' }),
206
+ leaseExpiresAt: patchedNullable({ patch, existing, key: 'leaseExpiresAt' }),
207
+ updatedAt: now,
208
+ };
209
+ }
150
210
  /**
151
211
  * Creates the in-memory reference `AsyncOperationStore`. No persistence — a durable adapter
152
212
  * implements the same interface; every method here is written so the equivalent SQL is a direct
@@ -154,20 +214,13 @@ export function assertTransition(from, to) {
154
214
  */
155
215
  export function createInMemoryAsyncOperationStore() {
156
216
  const rows = new Map();
157
- const requireRow = (id) => rows.get(id);
158
217
  return {
159
218
  async create(required, optional = {}) {
160
219
  const input = { ...required, ...optional };
161
220
  if (rows.has(input.id)) {
162
221
  throw new Error(`async operation "${input.id}" already exists`);
163
222
  }
164
- if (!Number.isFinite(input.maxAttempts) || input.maxAttempts < 1) {
165
- throw new RangeError(`Invalid maxAttempts: ${input.maxAttempts} must be a finite number >= 1`);
166
- }
167
- if (!Number.isFinite(input.deadlineAt)) {
168
- throw new RangeError(`Invalid deadlineAt: ${input.deadlineAt} must be a finite epoch-ms timestamp`);
169
- }
170
- assertNoCredentialMaterial({ state: input.state });
223
+ assertValidCreateInput({ input });
171
224
  const now = Date.now();
172
225
  const row = {
173
226
  schemaVersion: ASYNC_OPERATION_SCHEMA_VERSION,
@@ -182,7 +235,7 @@ export function createInMemoryAsyncOperationStore() {
182
235
  nextPollAt: input.nextPollAt ?? now,
183
236
  leaseOwner: null,
184
237
  leaseExpiresAt: null,
185
- state: input.state === undefined || input.state === null ? null : structuredClone(input.state),
238
+ state: cloneState(input.state ?? null),
186
239
  result: null,
187
240
  error: null,
188
241
  createdAt: now,
@@ -192,35 +245,20 @@ export function createInMemoryAsyncOperationStore() {
192
245
  return cloneRecord(row);
193
246
  },
194
247
  async get({ id }) {
195
- const row = requireRow(id);
248
+ const row = rows.get(id);
196
249
  return row ? cloneRecord(row) : null;
197
250
  },
198
251
  async update({ id, patch }, { options } = {}) {
199
- const existing = requireRow(id);
252
+ const existing = rows.get(id);
200
253
  if (!existing)
201
254
  return null;
202
255
  // Fenced, like releaseLease: a caller writing against a lease it no longer holds gets a
203
256
  // no-op, not an overwrite of whoever holds (or now holds none of) it.
204
- if (options?.leaseOwner !== undefined && existing.leaseOwner !== options.leaseOwner) {
257
+ if (isFencedOut({ existing, options }))
205
258
  return cloneRecord(existing);
206
- }
207
- if ('state' in patch)
208
- assertNoCredentialMaterial({ state: patch.state });
209
- const status = patch.status ?? existing.status;
210
- assertTransition(existing.status, status);
211
- const next = {
212
- ...existing,
213
- schemaVersion: existing.schemaVersion,
214
- status,
215
- attempts: patch.attempts ?? existing.attempts,
216
- nextPollAt: patch.nextPollAt ?? existing.nextPollAt,
217
- state: 'state' in patch ? (patch.state == null ? null : structuredClone(patch.state)) : existing.state,
218
- result: 'result' in patch ? (patch.result ?? null) : existing.result,
219
- error: 'error' in patch ? (patch.error ?? null) : existing.error,
220
- leaseOwner: 'leaseOwner' in patch ? (patch.leaseOwner ?? null) : existing.leaseOwner,
221
- leaseExpiresAt: 'leaseExpiresAt' in patch ? (patch.leaseExpiresAt ?? null) : existing.leaseExpiresAt,
222
- updatedAt: Date.now(),
223
- };
259
+ const merged = mergeAsyncOperationPatch({ existing, patch }, { now: Date.now() });
260
+ // Store a private copy of `state` so the caller's patch object never aliases the row.
261
+ const next = { ...merged, state: cloneState(merged.state) };
224
262
  rows.set(id, next);
225
263
  return cloneRecord(next);
226
264
  },
@@ -258,7 +296,7 @@ export function createInMemoryAsyncOperationStore() {
258
296
  return claimed;
259
297
  },
260
298
  async releaseLease({ id, leaseOwner }) {
261
- const row = requireRow(id);
299
+ const row = rows.get(id);
262
300
  if (!row)
263
301
  return;
264
302
  // Fenced: a stale owner's late release must not clear a lease another worker has since
@@ -1,5 +1,5 @@
1
1
  /** Built-in registration has one owner and runs on first registry use, never on import. */
2
- import type { VendorAdapterRegistry } from './vendor-registry.js';
2
+ import type { VendorAdapterRegistry } from './vendor-registry-core.js';
3
3
  export declare function registerBuiltinVendorAdapters({ registry }: {
4
4
  registry: Pick<VendorAdapterRegistry, 'register'>;
5
5
  }, _optional?: Record<string, never>): void;
@@ -6,6 +6,14 @@ function defaultAspectFor(surface) {
6
6
  return '16:9';
7
7
  return undefined;
8
8
  }
9
+ /** Never forward a non-finite number (NaN/Infinity) to a provider. */
10
+ function finiteOrUndefined(value) {
11
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
12
+ }
13
+ /** An explicit `imageRefs` wins; otherwise derive a one-element list from `imageRef`. */
14
+ function resolveImageRefs(request) {
15
+ return request.imageRefs ?? (request.imageRef ? [request.imageRef] : []);
16
+ }
9
17
  /**
10
18
  * @param request The caller's original request.
11
19
  * @param resolvedAudioKind Already resolved by the caller (defaults to `'music'` for an audio surface with no explicit `audioKind`).
@@ -25,9 +33,9 @@ export function buildRenderContext({ request, resolvedAudioKind, length, duratio
25
33
  audioKind: resolvedAudioKind,
26
34
  language: request.language || '',
27
35
  loop: request.loop === true,
28
- promptInfluence: typeof request.promptInfluence === 'number' && Number.isFinite(request.promptInfluence) ? request.promptInfluence : undefined,
36
+ promptInfluence: finiteOrUndefined(request.promptInfluence),
29
37
  imageRef: request.imageRef ?? null,
30
- imageRefs: request.imageRefs ?? (request.imageRef ? [request.imageRef] : []),
38
+ imageRefs: resolveImageRefs(request),
31
39
  requestInit: request.requestInit || {},
32
40
  speechFormat: resolveSpeechFormat(request.speechFormat),
33
41
  onProgress: request.onProgress,
@@ -1,4 +1,4 @@
1
- import type { MediaDispatchEngine, MediaDispatchEngineOptions, ProviderCredentials, RenderContext, RenderResult } from './types.js';
1
+ import type { MediaDispatchEngine, MediaDispatchEngineRequired, MediaDispatchEngineOptions, ProviderCredentials, RenderContext, RenderResult } from './types.js';
2
2
  export type Renderer = (required: {
3
3
  ctx: RenderContext;
4
4
  credentials: ProviderCredentials;
@@ -10,7 +10,7 @@ export type Renderer = (required: {
10
10
  * constant) specifically so its `providerId`-found/not-found and
11
11
  * `routeKey`-found/not-found branches stay directly testable even while
12
12
  * the production `ROUTES` table itself is empty (every vendor wired into
13
- * this engine has migrated onto `mediaVendorRegistry` — see `ROUTES`'s own
13
+ * this engine has migrated onto vendor adapters — see `ROUTES`'s own
14
14
  * doc comment above): exercising every branch through `resolveRenderer`
15
15
  * end-to-end would otherwise need a real, currently-nonexistent
16
16
  * ROUTES-only vendor to hit the "found" side. Same "extract to a
@@ -18,5 +18,8 @@ export type Renderer = (required: {
18
18
  * `buildRenderContext` already established for the same reason.
19
19
  */
20
20
  export declare function lookupRoute(routes: Readonly<Record<string, Readonly<Record<string, Renderer>>>>, providerId: string, routeKey: string): Renderer | undefined;
21
- export declare function createMediaDispatchEngine(_required: Record<string, never>, optional?: MediaDispatchEngineOptions): MediaDispatchEngine;
21
+ /** Creates an engine over the host's registry; registration remains live between requests.
22
+ * @returns A generation service; validation, missing routes and provider failures reject generate.
23
+ */
24
+ export declare function createMediaDispatchEngine({ registry, httpClient }: MediaDispatchEngineRequired, options?: MediaDispatchEngineOptions): MediaDispatchEngine;
22
25
  //# sourceMappingURL=engine.d.ts.map
@@ -1,40 +1,16 @@
1
+ import { requireMediaHttpClient } from './outbound.js';
1
2
  import { normalizeMediaProviderMap } from '../providers.js';
2
- /**
3
- * The media dispatch engine — validates a generation request against the
4
- * catalogue, clamps registry-bound numeric inputs, resolves per-provider
5
- * credentials, and routes to the matching renderer (or a deterministic
6
- * placeholder when `allowStubFallback` is set and no real renderer is
7
- * wired up for the pair). Generalized from Open Design's
8
- * `apps/daemon/src/media/index.ts` `generateMedia` orchestration — see
9
- * `types.ts`'s module doc for the boundary redesign (no filesystem I/O,
10
- * no OD project resolution) and `archived provenance ledger` for the full port record.
11
- *
12
- * 2026-07-21: renderer resolution now checks `vendor-registry.ts`'s
13
- * `mediaVendorRegistry` first (populated by every vendor migrated onto the
14
- * generic vendor-adapter dispatch engine — see `vendor-adapter.ts`'s
15
- * module doc), falling back to the static `ROUTES` table below for vendors
16
- * not yet migrated. Every vendor wired into this engine as of this pass
17
- * (`openai`/`minimax`/`senseaudio`/`fishaudio`/`imagerouter`/`custom-image`/
18
- * `grok`/`nanobanana`/`openrouter`/`volcengine`/`elevenlabs`/`aihubmix`) is
19
- * now registered in `mediaVendorRegistry` instead — every module below is
20
- * imported for its registration side effect only (not by name), except
21
- * `custom-image.js`, whose `renderCustomOpenAIImage`/
22
- * `customImageOverridesOpenAIModel` exports are still referenced directly
23
- * by the openai-image-override branch further down. `ROUTES` itself is
24
- * therefore empty right now — kept as the fallback mechanism `resolveRenderer`
25
- * still checks second, for whichever vendor is ported next without going
26
- * through the registry (e.g. one of the async-polling vendors in
27
- * `archived provenance ledger`'s deferred bucket, if a future pass chooses not to build
28
- * its own polling-aware adapter shape).
3
+ /** Media dispatch validates catalogue inputs, resolves live credentials and returns generated
4
+ * bytes. Registries belong to the host so embedded engines cannot alter each other's routes.
5
+ * Filesystem/project resolution remains outside this engine (locked architecture §2.1).
29
6
  */
30
7
  import { AUDIO_DURATIONS_SEC, VIDEO_LENGTHS_SEC, findMediaModel, findProvider, modelsForSurface } from '../providers.js';
8
+ /** The built-in catalogue, for hosts that pass no `catalog` (unchanged behaviour). */
9
+ const STATIC_CATALOG = { findModel: findMediaModel, findProvider, modelsForSurface };
31
10
  import { buildRenderContext } from './context.js';
32
- // Built-ins are now registered lazily by vendor-registry; the historical rationale above
33
- // describes the former import-time mechanism. No renderer module mutates that registry.
34
11
  import { renderCustomOpenAIImage, customImageOverridesOpenAIModel } from './providers/custom-image.js';
35
12
  import { renderStub } from './stub.js';
36
13
  import { dispatchVendorRequest } from './vendor-adapter.js';
37
- import { mediaVendorRegistry } from './vendor-registry.js';
38
14
  const SURFACES = new Set(['image', 'video', 'audio']);
39
15
  const AUDIO_KINDS = new Set(['music', 'speech', 'sfx']);
40
16
  /**
@@ -66,7 +42,9 @@ function clampNumber(value, allowed) {
66
42
  }
67
43
  function clampWithWarning(value, allowed, flagName) {
68
44
  const clamped = clampNumber(value, allowed);
69
- if (typeof value === 'number' && Number.isFinite(value) && typeof clamped === 'number' && clamped !== value) {
45
+ // `clampNumber` returns a number only for a finite numeric `value`, so a
46
+ // defined `clamped` that differs from `value` is exactly "it moved".
47
+ if (clamped !== undefined && clamped !== value) {
70
48
  return { value: clamped, warning: `${flagName} ${value} clamped to ${clamped} (allowed: ${allowed.join(', ')})` };
71
49
  }
72
50
  return { value: clamped, warning: null };
@@ -81,9 +59,8 @@ function clampWithWarning(value, allowed, flagName) {
81
59
  * Empty as of 2026-07-21: every vendor previously listed here
82
60
  * (`imagerouter`/`custom-image`/`grok`/`nanobanana`/`openrouter`/
83
61
  * `volcengine`/`elevenlabs`/`aihubmix`) has migrated onto
84
- * `vendor-registry.ts`'s `mediaVendorRegistry` (see `resolveRenderer`
85
- * below and each vendor's own module for its `mediaVendorRegistry.register(...)`
86
- * call) — joining `openai`/`minimax`/`senseaudio`/`fishaudio`, migrated the
62
+ * host-populated vendor registries (see `builtin-vendors.ts` and each vendor's
63
+ * explicit registration function) — joining `openai`/`minimax`/`senseaudio`/`fishaudio`, migrated the
87
64
  * pass before. Kept (not deleted) as `resolveRenderer`'s fallback path for
88
65
  * the next vendor this engine wires up.
89
66
  */
@@ -98,7 +75,7 @@ function routeKeyFor(surface, audioKind) {
98
75
  * constant) specifically so its `providerId`-found/not-found and
99
76
  * `routeKey`-found/not-found branches stay directly testable even while
100
77
  * the production `ROUTES` table itself is empty (every vendor wired into
101
- * this engine has migrated onto `mediaVendorRegistry` — see `ROUTES`'s own
78
+ * this engine has migrated onto vendor adapters — see `ROUTES`'s own
102
79
  * doc comment above): exercising every branch through `resolveRenderer`
103
80
  * end-to-end would otherwise need a real, currently-nonexistent
104
81
  * ROUTES-only vendor to hit the "found" side. Same "extract to a
@@ -110,101 +87,114 @@ export function lookupRoute(routes, providerId, routeKey) {
110
87
  }
111
88
  /**
112
89
  * Resolves the renderer for `(providerId, routeKey)`: checks
113
- * `mediaVendorRegistry` first (vendors migrated onto the generic engine),
90
+ * the host registry first (vendors migrated onto the generic engine),
114
91
  * falling back to the static `ROUTES` table for everything else.
115
92
  */
116
- function resolveRenderer(providerId, routeKey) {
117
- const adapter = mediaVendorRegistry.get({ providerId: providerId, routeKey: routeKey });
93
+ function resolveRenderer({ registry, providerId, routeKey }) {
94
+ const adapter = registry.get({ providerId, routeKey });
118
95
  if (adapter) {
119
96
  return ({ ctx, credentials }) => dispatchVendorRequest({ adapter, ctx, credentials });
120
97
  }
121
98
  return lookupRoute(ROUTES, providerId, routeKey);
122
99
  }
123
- export function createMediaDispatchEngine(_required, optional = {}) {
124
- const options = optional;
100
+ /** Creates an engine over the host's registry; registration remains live between requests.
101
+ * @returns A generation service; validation, missing routes and provider failures reject generate.
102
+ */
103
+ export function createMediaDispatchEngine({ registry, httpClient }, options = {}) {
104
+ requireMediaHttpClient({ httpClient });
125
105
  const allowStubFallback = options.allowStubFallback === true;
106
+ const catalog = options.catalog ?? STATIC_CATALOG;
126
107
  return {
127
108
  async generate(required, optional = {}) {
128
109
  // Credentials remain live: a host may rotate them between generation requests.
129
110
  const configuredCredentials = options.credentials ? normalizeMediaProviderMap({ providers: options.credentials }) : {};
130
111
  const request = { ...required, ...optional };
131
- const { surface, model } = request;
132
- if (!SURFACES.has(surface)) {
133
- throw new Error(`unsupported surface: ${String(surface)}`);
134
- }
135
- if (typeof model !== 'string' || !model) {
136
- throw new Error('model required');
137
- }
138
- if (surface === 'audio' && request.audioKind && !AUDIO_KINDS.has(request.audioKind)) {
139
- throw new Error(`unsupported audioKind: ${request.audioKind}. Allowed: music | speech | sfx.`);
140
- }
141
- const def = findMediaModel({ id: model });
142
- if (!def) {
143
- throw new Error(`unknown model: ${model}. Pass a model from the registered catalogue (see @jini-ai/integrations/media-providers's modelsForSurface()).`);
144
- }
145
- const resolvedAudioKind = surface === 'audio' ? request.audioKind || 'music' : undefined;
146
- const allowed = modelsForSurface({ surface: surface }, { audioKind: resolvedAudioKind });
147
- if (!allowed.some((m) => m.id === model)) {
148
- const ids = allowed.map((m) => m.id).join(', ');
149
- const where = surface === 'audio' ? `audio · ${resolvedAudioKind}` : surface;
150
- throw new Error(`model "${model}" is not registered for surface "${where}". Allowed: ${ids}.`);
151
- }
152
- const warnings = [];
153
- let length;
154
- let duration;
155
- if (surface === 'video') {
156
- const clamp = clampWithWarning(request.length, VIDEO_LENGTHS_SEC, 'length');
157
- length = clamp.value;
158
- if (clamp.warning)
159
- warnings.push(clamp.warning);
160
- }
161
- if (surface === 'audio') {
162
- const clamp = clampWithWarning(request.duration, AUDIO_DURATIONS_SEC, 'duration');
163
- duration = clamp.value;
164
- if (clamp.warning)
165
- warnings.push(clamp.warning);
166
- }
167
- // Every catalogued model's `provider` id resolves via `findProvider` —
168
- // proven by providers.test.ts's "every model provider id exists in
169
- // MEDIA_PROVIDERS" catalogue-integrity test, given `def` itself is
170
- // already a real catalogued model at this point (findMediaModel
171
- // above didn't throw). Not re-guarded with a runtime null check.
172
- const provider = findProvider({ id: def.provider });
173
- const ctx = {
174
- ...buildRenderContext({ request: request, resolvedAudioKind: resolvedAudioKind, length: length, duration: duration }),
175
- ...(options.httpClient === undefined ? {} : { httpClient: options.httpClient }),
176
- ...(options.allowPrivateNetwork === undefined ? {} : { allowPrivateNetwork: options.allowPrivateNetwork }),
177
- ...(options.outboundMessages === undefined ? {} : { outboundMessages: options.outboundMessages }),
178
- };
179
- const credentials = configuredCredentials[def.provider] ?? {};
180
- // `openai` + image can be overridden by a caller-configured
181
- // `custom-image` credential that names the same model — mirrors the
182
- // origin's `customImageOverridesOpenAIModel` precedence.
183
- let providerId = def.provider;
184
- let renderer;
185
- let effectiveCredentials = credentials;
186
- if (def.provider === 'openai' && surface === 'image') {
187
- const customImageCredentials = configuredCredentials['custom-image'] ?? null;
188
- const override = { ctx, credentials: customImageCredentials };
189
- if (customImageOverridesOpenAIModel(override)) {
190
- providerId = 'custom-image';
191
- renderer = renderCustomOpenAIImage;
192
- effectiveCredentials = override.credentials;
193
- }
194
- }
195
- if (!renderer) {
196
- renderer = resolveRenderer(def.provider, routeKeyFor(surface, resolvedAudioKind));
197
- }
112
+ assertRequestShape(request);
113
+ const { def, resolvedAudioKind } = resolveCatalogModel(request, catalog);
114
+ const { length, duration, warnings } = clampRequestInputs(request);
115
+ const ctx = engineRenderContext({ request, resolvedAudioKind, length, duration, options: { ...options, httpClient } });
116
+ const { providerId, renderer, credentials } = selectRenderer({ registry, def, surface: request.surface, resolvedAudioKind, ctx, configuredCredentials });
198
117
  if (!renderer) {
199
118
  if (!allowStubFallback) {
200
- throw new Error(`no renderer configured for provider "${def.provider}" / surface "${routeKeyFor(surface, resolvedAudioKind)}" — pass allowStubFallback: true to get placeholder bytes instead, or wire up a real integration for this pair.`);
119
+ throw new Error(`no renderer configured for provider "${def.provider}" / surface "${routeKeyFor(request.surface, resolvedAudioKind)}" — pass allowStubFallback: true to get placeholder bytes instead, or wire up a real integration for this pair.`);
201
120
  }
121
+ // Every catalogued model's `provider` id resolves via `findProvider` —
122
+ // proven by providers.test.ts's "every model provider id exists in
123
+ // MEDIA_PROVIDERS" catalogue-integrity test, given `def` itself is
124
+ // already a real catalogued model at this point (findMediaModel
125
+ // above didn't throw). Not re-guarded with a runtime null check.
126
+ const provider = catalog.findProvider({ id: def.provider });
202
127
  const stub = await renderStub({ ctx: ctx, providerId: providerId, integrated: provider.integrated });
203
128
  return { ...stub, providerId, usedStubFallback: true, warnings };
204
129
  }
205
- const result = await renderer({ ctx, credentials: effectiveCredentials });
130
+ const result = await renderer({ ctx, credentials });
206
131
  return { ...result, providerId, usedStubFallback: false, warnings };
207
132
  },
208
133
  };
209
134
  }
135
+ /** Rejects an unsupported surface, a missing/non-string model, or an unknown audio kind — in that order. */
136
+ function assertRequestShape(request) {
137
+ const { surface, model } = request;
138
+ if (!SURFACES.has(surface)) {
139
+ throw new Error(`unsupported surface: ${String(surface)}`);
140
+ }
141
+ if (typeof model !== 'string' || !model) {
142
+ throw new Error('model required');
143
+ }
144
+ if (surface === 'audio' && request.audioKind && !AUDIO_KINDS.has(request.audioKind)) {
145
+ throw new Error(`unsupported audioKind: ${request.audioKind}. Allowed: music | speech | sfx.`);
146
+ }
147
+ }
148
+ /** Finds the catalogue entry for `request.model` and checks it is registered for the request's surface (and, for audio, the resolved kind — `'music'` by default). */
149
+ function resolveCatalogModel(request, catalog) {
150
+ const { surface, model } = request;
151
+ const def = catalog.findModel({ id: model });
152
+ if (!def) {
153
+ throw new Error(`unknown model: ${model}. Pass a model from the registered catalogue (see @jini-ai/integrations/media-providers's modelsForSurface()).`);
154
+ }
155
+ const resolvedAudioKind = surface === 'audio' ? request.audioKind || 'music' : undefined;
156
+ const allowed = catalog.modelsForSurface({ surface: surface }, { audioKind: resolvedAudioKind });
157
+ if (!allowed.some((m) => m.id === model)) {
158
+ const ids = allowed.map((m) => m.id).join(', ');
159
+ const where = surface === 'audio' ? `audio · ${resolvedAudioKind}` : surface;
160
+ throw new Error(`model "${model}" is not registered for surface "${where}". Allowed: ${ids}.`);
161
+ }
162
+ return { def, resolvedAudioKind };
163
+ }
164
+ const NOT_CLAMPED = { value: undefined, warning: null };
165
+ /** Clamps `length` for video and `duration` for audio to their registry-allowed values; every other surface/input pair is dropped (left undefined). */
166
+ function clampRequestInputs(request) {
167
+ const length = request.surface === 'video' ? clampWithWarning(request.length, VIDEO_LENGTHS_SEC, 'length') : NOT_CLAMPED;
168
+ const duration = request.surface === 'audio' ? clampWithWarning(request.duration, AUDIO_DURATIONS_SEC, 'duration') : NOT_CLAMPED;
169
+ const warnings = [length.warning, duration.warning].filter((warning) => warning !== null);
170
+ return { length: length.value, duration: duration.value, warnings };
171
+ }
172
+ /** The renderer context plus whichever outbound options the host configured on the engine. */
173
+ function engineRenderContext(required) {
174
+ const { request, resolvedAudioKind, length, duration, options } = required;
175
+ return {
176
+ ...buildRenderContext({ request: request, resolvedAudioKind: resolvedAudioKind, length: length, duration: duration }),
177
+ httpClient: options.httpClient,
178
+ ...(options.allowPrivateNetwork === undefined ? {} : { allowPrivateNetwork: options.allowPrivateNetwork }),
179
+ ...(options.outboundMessages === undefined ? {} : { outboundMessages: options.outboundMessages }),
180
+ };
181
+ }
182
+ /** Picks the provider id, renderer (undefined when none is wired) and credentials for a validated request. */
183
+ function selectRenderer(required) {
184
+ const { registry, def, surface, resolvedAudioKind, ctx, configuredCredentials } = required;
185
+ // `openai` + image can be overridden by a caller-configured
186
+ // `custom-image` credential that names the same model — mirrors the
187
+ // origin's `customImageOverridesOpenAIModel` precedence.
188
+ if (def.provider === 'openai' && surface === 'image') {
189
+ const override = { ctx, credentials: configuredCredentials['custom-image'] ?? null };
190
+ if (customImageOverridesOpenAIModel(override)) {
191
+ return { providerId: 'custom-image', renderer: renderCustomOpenAIImage, credentials: override.credentials };
192
+ }
193
+ }
194
+ return {
195
+ providerId: def.provider,
196
+ renderer: resolveRenderer({ registry, providerId: def.provider, routeKey: routeKeyFor(surface, resolvedAudioKind) }),
197
+ credentials: configuredCredentials[def.provider] ?? {},
198
+ };
199
+ }
210
200
  //# sourceMappingURL=engine.js.map
@@ -17,10 +17,12 @@ export { renderStub, svgPlaceholder } from './stub.js';
17
17
  export { assertAndFetchExternalAsset, assertExternalAssetUrl, validateBaseUrlResolved } from './ssrf-guard.js';
18
18
  export { isBlockedExternalApiHostname, isLoopbackApiHost } from '@jini-ai/platform/net';
19
19
  export type { DnsLookupAddress, DnsLookupFn } from './ssrf-guard.js';
20
- export type { MediaDispatchEngine, MediaDispatchEngineOptions, MediaGenerationRequest, MediaGenerationRequestInit, MediaGenerationResult, MediaImageReference, MediaSpeechFormat, ProviderCredentials, } from './types.js';
20
+ export type { MediaDispatchEngine, MediaDispatchEngineOptions, MediaDispatchEngineRequired, VendorAdapterLookup, MediaGenerationRequest, MediaGenerationRequestInit, MediaGenerationResult, MediaImageReference, MediaModelCatalog, MediaSpeechFormat, ProviderCredentials, } from './types.js';
21
21
  export { dispatchVendorRequest, requireApiKey } from './vendor-adapter.js';
22
22
  export type { VendorAdapter, VendorCredentialGuard, VendorRequest, VendorRequestBuilder, VendorResponseParser } from './vendor-adapter.js';
23
- export { createVendorAdapterRegistry, mediaVendorRegistry, VendorAdapterRegistry } from './vendor-registry.js';
23
+ export { createBuiltinVendorAdapterRegistry, createVendorAdapterRegistry, mediaVendorRegistry, VendorAdapterRegistry } from './vendor-registry.js';
24
+ export { builtinMediaProviderContributions, createMediaProviderRegistry, MEDIA_PROVIDER_CONTRACT, mediaProviderDefinition, mediaProviderRegistryId, } from './media-provider-registry.js';
25
+ export type { MediaProviderContribution, MediaProviderModel, MediaProviderRegistry } from './media-provider-registry.js';
24
26
  export { createHexEnvelopeAudioParser, createRawBytesParser } from './response-parsers.js';
25
27
  export { ASYNC_OPERATION_SCHEMA_VERSION, assertNoCredentialMaterial, createInMemoryAsyncOperationStore, CREDENTIAL_IN_STATE_MESSAGE, hydrateAsyncOperationRecord, } from './async-operation-store.js';
26
28
  export type { AsyncOperationClaimOptions, AsyncOperationCreateInput, AsyncOperationError, AsyncOperationPatch, AsyncOperationReconcileResult, AsyncOperationRecord, AsyncOperationResult, AsyncOperationStatus, AsyncOperationStore, } from './async-operation-store.js';
@@ -20,7 +20,9 @@ export { isBlockedExternalApiHostname, isLoopbackApiHost } from '@jini-ai/platfo
20
20
  // `vendor-adapter.ts`'s module doc and `archived provenance ledger` for the design and
21
21
  // which vendors are registered onto it.
22
22
  export { dispatchVendorRequest, requireApiKey } from './vendor-adapter.js';
23
- export { createVendorAdapterRegistry, mediaVendorRegistry, VendorAdapterRegistry } from './vendor-registry.js';
23
+ export { createBuiltinVendorAdapterRegistry, createVendorAdapterRegistry, mediaVendorRegistry, VendorAdapterRegistry } from './vendor-registry.js';
24
+ // Vendors as one-unit provider contributions on the shared keyed registry (2026-10-21).
25
+ export { builtinMediaProviderContributions, createMediaProviderRegistry, MEDIA_PROVIDER_CONTRACT, mediaProviderDefinition, mediaProviderRegistryId, } from './media-provider-registry.js';
24
26
  export { createHexEnvelopeAudioParser, createRawBytesParser } from './response-parsers.js';
25
27
  // The submit-then-poll tier (added 2026-09-02) — purely additive alongside `VendorAdapter`, for
26
28
  // vendors that hand back a job handle instead of finishing inside one request/response. See