@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.
Files changed (132) hide show
  1. package/CHANGELOG.md +99 -1
  2. package/README.md +1 -0
  3. package/dist/api-connections/access-token.d.ts +9 -0
  4. package/dist/api-connections/access-token.js +92 -0
  5. package/dist/api-connections/account-actions.d.ts +40 -0
  6. package/dist/api-connections/account-actions.js +110 -0
  7. package/dist/api-connections/attempt-state.d.ts +28 -0
  8. package/dist/api-connections/attempt-state.js +73 -0
  9. package/dist/api-connections/authorization.d.ts +45 -0
  10. package/dist/api-connections/authorization.js +120 -0
  11. package/dist/api-connections/deps.d.ts +41 -0
  12. package/dist/api-connections/deps.js +13 -0
  13. package/dist/api-connections/descriptor.d.ts +6 -0
  14. package/dist/api-connections/descriptor.js +111 -0
  15. package/dist/api-connections/errors.d.ts +23 -0
  16. package/dist/api-connections/errors.js +24 -0
  17. package/dist/api-connections/finish-authorization.d.ts +24 -0
  18. package/dist/api-connections/finish-authorization.js +117 -0
  19. package/dist/api-connections/index.d.ts +18 -0
  20. package/dist/api-connections/index.js +10 -0
  21. package/dist/api-connections/install-credential.d.ts +19 -0
  22. package/dist/api-connections/install-credential.js +12 -0
  23. package/dist/api-connections/keys.d.ts +27 -0
  24. package/dist/api-connections/keys.js +22 -0
  25. package/dist/api-connections/ports.d.ts +73 -0
  26. package/dist/api-connections/ports.js +2 -0
  27. package/dist/api-connections/records.d.ts +27 -0
  28. package/dist/api-connections/records.js +52 -0
  29. package/dist/api-connections/request-checks.d.ts +18 -0
  30. package/dist/api-connections/request-checks.js +67 -0
  31. package/dist/api-connections/service.d.ts +25 -0
  32. package/dist/api-connections/service.js +26 -0
  33. package/dist/api-connections/status.d.ts +28 -0
  34. package/dist/api-connections/status.js +36 -0
  35. package/dist/api-connections/token-store/errors.d.ts +20 -0
  36. package/dist/api-connections/token-store/errors.js +38 -0
  37. package/dist/api-connections/token-store/index.d.ts +6 -0
  38. package/dist/api-connections/token-store/index.js +6 -0
  39. package/dist/api-connections/token-store/record.d.ts +69 -0
  40. package/dist/api-connections/token-store/record.js +97 -0
  41. package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
  42. package/dist/api-connections/token-store/vault-token-store.js +215 -0
  43. package/dist/api-connections/types.d.ts +101 -0
  44. package/dist/api-connections/types.js +9 -0
  45. package/dist/credentialed-http/auth-schemes.js +8 -4
  46. package/dist/credentialed-http/credentialed-request.d.ts +4 -0
  47. package/dist/credentialed-http/credentialed-request.js +61 -77
  48. package/dist/credentialed-http/response-redaction.d.ts +15 -0
  49. package/dist/credentialed-http/response-redaction.js +82 -0
  50. package/dist/media-providers/catalog.d.ts +3 -1
  51. package/dist/media-providers/catalog.js +3 -1
  52. package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
  53. package/dist/media-providers/dispatch/async-operation-store.js +75 -37
  54. package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
  55. package/dist/media-providers/dispatch/context.js +10 -2
  56. package/dist/media-providers/dispatch/engine.d.ts +6 -3
  57. package/dist/media-providers/dispatch/engine.js +99 -109
  58. package/dist/media-providers/dispatch/index.d.ts +4 -2
  59. package/dist/media-providers/dispatch/index.js +3 -1
  60. package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
  61. package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
  62. package/dist/media-providers/dispatch/node.d.ts +13 -0
  63. package/dist/media-providers/dispatch/node.js +24 -0
  64. package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
  65. package/dist/media-providers/dispatch/openai-compatible.js +90 -87
  66. package/dist/media-providers/dispatch/operation-runtime.js +116 -89
  67. package/dist/media-providers/dispatch/outbound.d.ts +8 -4
  68. package/dist/media-providers/dispatch/outbound.js +27 -26
  69. package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
  70. package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
  71. package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
  72. package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
  73. package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
  74. package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
  75. package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
  76. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
  77. package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
  78. package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
  79. package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
  80. package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
  81. package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
  82. package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
  83. package/dist/media-providers/dispatch/providers/openai.js +51 -47
  84. package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
  85. package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
  86. package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
  87. package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
  88. package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
  89. package/dist/media-providers/dispatch/response-parsers.js +37 -21
  90. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +9 -29
  91. package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
  92. package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
  93. package/dist/media-providers/dispatch/types.d.ts +76 -2
  94. package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
  95. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  96. package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
  97. package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
  98. package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
  99. package/dist/media-providers/dispatch/vendor-registry.js +14 -42
  100. package/dist/media-providers/policy.js +25 -17
  101. package/dist/media-providers/providers.d.ts +5 -0
  102. package/dist/media-providers/providers.js +2 -0
  103. package/dist/media-providers/sqlite-task-store.js +12 -80
  104. package/dist/media-providers/staging.js +77 -58
  105. package/dist/media-providers/task-lifecycle.d.ts +33 -0
  106. package/dist/media-providers/task-lifecycle.js +124 -0
  107. package/dist/media-providers/task-store.js +8 -86
  108. package/dist/media-providers/ui-defaults.d.ts +10 -0
  109. package/dist/media-providers/ui-defaults.js +167 -0
  110. package/dist/media-providers/video-request.js +112 -90
  111. package/dist/saved-requests/definition.d.ts +17 -0
  112. package/dist/saved-requests/definition.js +84 -0
  113. package/dist/saved-requests/execute.d.ts +17 -0
  114. package/dist/saved-requests/execute.js +95 -0
  115. package/dist/saved-requests/index.d.ts +6 -0
  116. package/dist/saved-requests/index.js +4 -0
  117. package/dist/saved-requests/projection.d.ts +9 -0
  118. package/dist/saved-requests/projection.js +48 -0
  119. package/dist/saved-requests/schema.d.ts +7 -0
  120. package/dist/saved-requests/schema.js +73 -0
  121. package/dist/saved-requests/types.d.ts +58 -0
  122. package/dist/saved-requests/types.js +2 -0
  123. package/dist/saved-requests/validation.d.ts +46 -0
  124. package/dist/saved-requests/validation.js +66 -0
  125. package/dist/webhooks/delivery.d.ts +14 -0
  126. package/dist/webhooks/delivery.js +41 -10
  127. package/dist/webhooks/index.d.ts +1 -0
  128. package/dist/webhooks/index.js +1 -0
  129. package/dist/webhooks/ports.d.ts +23 -0
  130. package/dist/webhooks/worker.d.ts +83 -0
  131. package/dist/webhooks/worker.js +105 -0
  132. package/package.json +46 -9
@@ -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
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Media vendors as provider contributions: one `{ provider, models, adapters }` unit per vendor, held
3
+ * in the shared keyed registry (`@jini-ai/core/provider-registry`, contract `media`).
4
+ *
5
+ * Why: the catalogue used to be closed consts (`providers.ts`) enforced by the engine, with adapters
6
+ * registered somewhere else, so a plugin could not add a vendor. The consts are now only the data the
7
+ * built-in contribution is made from; the engine validates against whatever this registry holds.
8
+ *
9
+ * Ids: the shared grammar forbids hyphens and one built-in id has one (`custom-image`), so the
10
+ * registry KEY is the canonical id with `-` -> `_`. The public id on `provider.id` — the one saved
11
+ * credentials, settings and env-var maps use — never changes.
12
+ */
13
+ import { type ProviderDefinition, type ProviderRegistry } from '@jini-ai/core/provider-registry';
14
+ import type { AudioKind, MediaModel, MediaProvider, MediaSurface } from '../types.js';
15
+ import type { MediaModelCatalog, VendorAdapter, VendorAdapterLookup } from './types.js';
16
+ /** A catalogued model plus the surface (and audio kind) it is offered on. */
17
+ export interface MediaProviderModel extends MediaModel {
18
+ readonly surface: MediaSurface;
19
+ readonly audioKind?: AudioKind;
20
+ /** Sort key within a surface; built-ins carry their catalogue index. Unset sorts after, in registration order. */
21
+ readonly order?: number;
22
+ }
23
+ /** Everything one vendor brings, registered as one unit. */
24
+ export interface MediaProviderContribution {
25
+ readonly provider: MediaProvider;
26
+ readonly models: readonly MediaProviderModel[];
27
+ /** Route key (`image`, `video`, `audio:speech`, …) -> the adapter serving it. */
28
+ readonly adapters: Readonly<Record<string, VendorAdapter<never>>>;
29
+ }
30
+ export interface MediaProviderRegistry extends VendorAdapterLookup, MediaModelCatalog {
31
+ /** The shared registry; plugin loaders contribute here (`contributeProviders`). */
32
+ readonly providers: ProviderRegistry<MediaProviderContribution>;
33
+ /** Every registered vendor, registration order. */
34
+ listProviders(_required?: Record<string, never>): readonly MediaProvider[];
35
+ }
36
+ export declare const MEDIA_PROVIDER_CONTRACT = "media";
37
+ /** The registry key for a public media provider id (aliases resolved, `-` -> `_`). @complexity O(n) in id length. */
38
+ export declare function mediaProviderRegistryId({ id }: {
39
+ id: string;
40
+ }, _optional?: Record<string, never>): string;
41
+ /** Wraps one contribution as a shared-registry definition. @complexity O(1). */
42
+ export declare function mediaProviderDefinition({ contribution }: {
43
+ contribution: MediaProviderContribution;
44
+ }, _optional?: Record<string, never>): ProviderDefinition<MediaProviderContribution>;
45
+ /**
46
+ * Builds the media provider registry. Built-ins register with the throwing policy; plugins go through
47
+ * `providers.contribute` (or agent-plugins' `contributeProviders`) and are refused, never thrown.
48
+ * @param optional.contributions - Core contributions; defaults to {@link builtinMediaProviderContributions}.
49
+ * @throws {ProviderRegistryError} When a core contribution is malformed or duplicated.
50
+ * @complexity Lookups O(m) over registered models (tens), registration O(m).
51
+ */
52
+ export declare function createMediaProviderRegistry(_required?: Record<string, never>, { contributions }?: {
53
+ contributions?: readonly MediaProviderContribution[];
54
+ }): MediaProviderRegistry;
55
+ /**
56
+ * Today's built-in vendors as the default contribution set: one unit per `MEDIA_PROVIDERS` entry, its
57
+ * catalogued models, and the adapters its `registerVendorAdapters` registers.
58
+ * @returns Fresh contributions; adapters are the shared module-level adapter objects.
59
+ * @complexity O(p + m + a) providers, models and adapters.
60
+ */
61
+ export declare function builtinMediaProviderContributions(_required?: Record<string, never>): MediaProviderContribution[];
62
+ //# sourceMappingURL=media-provider-registry.d.ts.map
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Media vendors as provider contributions: one `{ provider, models, adapters }` unit per vendor, held
3
+ * in the shared keyed registry (`@jini-ai/core/provider-registry`, contract `media`).
4
+ *
5
+ * Why: the catalogue used to be closed consts (`providers.ts`) enforced by the engine, with adapters
6
+ * registered somewhere else, so a plugin could not add a vendor. The consts are now only the data the
7
+ * built-in contribution is made from; the engine validates against whatever this registry holds.
8
+ *
9
+ * Ids: the shared grammar forbids hyphens and one built-in id has one (`custom-image`), so the
10
+ * registry KEY is the canonical id with `-` -> `_`. The public id on `provider.id` — the one saved
11
+ * credentials, settings and env-var maps use — never changes.
12
+ */
13
+ import { createProviderRegistry, } from '@jini-ai/core/provider-registry';
14
+ import { AUDIO_MODELS_BY_KIND, IMAGE_MODELS, MEDIA_PROVIDERS, VIDEO_MODELS, canonicalMediaProviderId } from '../providers.js';
15
+ import { registerBuiltinVendorAdapters } from './builtin-vendors.js';
16
+ export const MEDIA_PROVIDER_CONTRACT = 'media';
17
+ /** The registry key for a public media provider id (aliases resolved, `-` -> `_`). @complexity O(n) in id length. */
18
+ export function mediaProviderRegistryId({ id }, _optional = {}) {
19
+ return canonicalMediaProviderId({ id }).replaceAll('-', '_');
20
+ }
21
+ /** Wraps one contribution as a shared-registry definition. @complexity O(1). */
22
+ export function mediaProviderDefinition({ contribution }, _optional = {}) {
23
+ return { id: mediaProviderRegistryId({ id: contribution.provider.id }), provider: contribution, label: contribution.provider.label };
24
+ }
25
+ function isAdapter(value) {
26
+ const candidate = value;
27
+ return typeof candidate?.buildRequest === 'function' && typeof candidate.parseResponse === 'function';
28
+ }
29
+ function providerFault(provider) {
30
+ const valid = typeof provider?.id === 'string' && typeof provider.label === 'string' && provider.label.trim() !== '';
31
+ return valid ? undefined : 'provider needs a string id and a non-empty label';
32
+ }
33
+ function modelsFault(models, providerId) {
34
+ if (!Array.isArray(models))
35
+ return 'models must be an array';
36
+ // findIndex, not find: a `find` hit on an `undefined` element is indistinguishable from no hit, which
37
+ // let `models: [undefined]` pass here and then throw in the collision check.
38
+ const at = models.findIndex(model => model?.provider !== providerId || typeof model.id !== 'string' || !model.id);
39
+ return at === -1 ? undefined : `model '${String(models[at]?.id)}' must have an id and belong to provider '${providerId}'`;
40
+ }
41
+ function adaptersFault(adapters) {
42
+ if (typeof adapters !== 'object' || adapters === null)
43
+ return 'adapters must be an object';
44
+ const byRoute = adapters;
45
+ const broken = Object.keys(byRoute).find(routeKey => !isAdapter(byRoute[routeKey]));
46
+ return broken === undefined ? undefined : `adapter for route '${broken}' needs buildRequest and parseResponse functions`;
47
+ }
48
+ /** Shape faults inside one contribution (plugin input is untrusted), independent of what else is registered. */
49
+ function ownFault(contribution) {
50
+ const { provider, models, adapters } = (contribution ?? {});
51
+ return providerFault(provider) ?? modelsFault(models, provider.id) ?? adaptersFault(adapters);
52
+ }
53
+ /**
54
+ * A model id another provider already offers on ANY route. Why not per route: `findModel` (and so
55
+ * dispatch and credential selection) resolves a model by id alone, so a second vendor's `gpt-image-2`
56
+ * on video would be routed to OpenAI — or, with a lower `order`, take OpenAI's image traffic.
57
+ */
58
+ function collisionFault(contribution, registered) {
59
+ const ownKey = mediaProviderRegistryId({ id: contribution.provider.id });
60
+ const taken = new Set(registered.filter(entry => entry.id !== ownKey).flatMap(entry => entry.provider.models.map(model => model.id)));
61
+ const clash = contribution.models.find(model => taken.has(model.id));
62
+ return clash === undefined ? undefined : `model '${clash.id}' is already offered by another provider`;
63
+ }
64
+ function byOrder(left, right) {
65
+ const a = left.model.order ?? Number.MAX_SAFE_INTEGER;
66
+ const b = right.model.order ?? Number.MAX_SAFE_INTEGER;
67
+ return a === b ? left.index - right.index : a - b;
68
+ }
69
+ /** Strips the registry-only fields so callers see the same `MediaModel` shape as the static catalogue. */
70
+ function asMediaModel(model) {
71
+ const { surface: _surface, audioKind: _audioKind, order: _order, ...rest } = model;
72
+ return rest;
73
+ }
74
+ /**
75
+ * Builds the media provider registry. Built-ins register with the throwing policy; plugins go through
76
+ * `providers.contribute` (or agent-plugins' `contributeProviders`) and are refused, never thrown.
77
+ * @param optional.contributions - Core contributions; defaults to {@link builtinMediaProviderContributions}.
78
+ * @throws {ProviderRegistryError} When a core contribution is malformed or duplicated.
79
+ * @complexity Lookups O(m) over registered models (tens), registration O(m).
80
+ */
81
+ export function createMediaProviderRegistry(_required = {}, { contributions = builtinMediaProviderContributions() } = {}) {
82
+ let current;
83
+ const providers = createProviderRegistry({ contract: MEDIA_PROVIDER_CONTRACT }, {
84
+ // `current` is assigned before any registration below; validate only runs from register/contribute.
85
+ validate: ({ provider }) => ownFault(provider) ?? collisionFault(provider, current.list()),
86
+ });
87
+ current = providers;
88
+ for (const contribution of contributions)
89
+ providers.register({ definition: mediaProviderDefinition({ contribution }) });
90
+ const entryFor = (id) => providers.get({ id: mediaProviderRegistryId({ id }) })?.provider;
91
+ const allModels = () => providers.list().flatMap(entry => entry.provider.models).map((model, index) => ({ model, index })).sort(byOrder).map(({ model }) => model);
92
+ return {
93
+ providers,
94
+ get: ({ providerId, routeKey }) => entryFor(providerId)?.adapters[routeKey],
95
+ findModel: ({ id }) => {
96
+ const found = allModels().find(model => model.id === id);
97
+ return found === undefined ? null : asMediaModel(found);
98
+ },
99
+ findProvider: ({ id }) => entryFor(id)?.provider ?? null,
100
+ modelsForSurface: ({ surface }, { audioKind } = {}) => {
101
+ const kind = surface === 'audio' ? audioKind ?? 'music' : undefined;
102
+ return allModels().filter(model => model.surface === surface && (kind === undefined || (model.audioKind ?? 'music') === kind)).map(asMediaModel);
103
+ },
104
+ listProviders: () => providers.list().map(entry => entry.provider.provider),
105
+ };
106
+ }
107
+ /** The static catalogue with each model's surface and catalogue index attached. */
108
+ function builtinModels() {
109
+ const audio = Object.keys(AUDIO_MODELS_BY_KIND).flatMap(audioKind => AUDIO_MODELS_BY_KIND[audioKind].map(model => ({ ...model, surface: 'audio', audioKind })));
110
+ const all = [
111
+ ...IMAGE_MODELS.map(model => ({ ...model, surface: 'image' })),
112
+ ...VIDEO_MODELS.map(model => ({ ...model, surface: 'video' })),
113
+ ...audio,
114
+ ];
115
+ return all.map((model, order) => ({ ...model, order }));
116
+ }
117
+ /**
118
+ * Today's built-in vendors as the default contribution set: one unit per `MEDIA_PROVIDERS` entry, its
119
+ * catalogued models, and the adapters its `registerVendorAdapters` registers.
120
+ * @returns Fresh contributions; adapters are the shared module-level adapter objects.
121
+ * @complexity O(p + m + a) providers, models and adapters.
122
+ */
123
+ export function builtinMediaProviderContributions(_required = {}) {
124
+ const adapters = new Map();
125
+ registerBuiltinVendorAdapters({
126
+ registry: {
127
+ register: ({ providerId, routeKey, adapter }) => {
128
+ const byRoute = adapters.get(providerId) ?? {};
129
+ byRoute[routeKey] = adapter;
130
+ adapters.set(providerId, byRoute);
131
+ },
132
+ },
133
+ });
134
+ const models = builtinModels();
135
+ return MEDIA_PROVIDERS.map(provider => ({
136
+ provider,
137
+ models: models.filter(model => model.provider === provider.id),
138
+ adapters: adapters.get(provider.id) ?? {},
139
+ }));
140
+ }
141
+ //# sourceMappingURL=media-provider-registry.js.map
@@ -0,0 +1,13 @@
1
+ /** Explicit Node adapter entry. Hosts construct this once and inject it into media services. */
2
+ import type { HttpClientPort } from '@jini-ai/core/primitives';
3
+ import type { DnsResolver } from '@jini-ai/platform/http/guarded';
4
+ export interface NodeMediaHttpClientOptions {
5
+ readonly allowPrivateNetwork?: boolean;
6
+ readonly dns?: DnsResolver;
7
+ }
8
+ /** The default policy client: public http(s) peers only unless the caller explicitly opts into
9
+ * private-network development, never following redirects.
10
+ * @returns A DNS-pinned, bounded client; policy and transport failures reject send.
11
+ */
12
+ export declare function createNodeMediaHttpClient(_required: Record<string, never>, { allowPrivateNetwork, dns }?: NodeMediaHttpClientOptions): HttpClientPort;
13
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1,24 @@
1
+ import { FETCH_TIMEOUT_MS } from '@jini-ai/platform/fetch-with-timeout';
2
+ import { createHttpClient, createNodeGuardedHttpPorts } from '@jini-ai/platform/http/guarded';
3
+ /** The default policy client: public http(s) peers only unless the caller explicitly opts into
4
+ * private-network development, never following redirects.
5
+ * @returns A DNS-pinned, bounded client; policy and transport failures reject send.
6
+ */
7
+ export function createNodeMediaHttpClient(_required, { allowPrivateNetwork, dns } = {}) {
8
+ return createHttpClient({
9
+ ...createNodeGuardedHttpPorts({}),
10
+ ...(dns === undefined ? {} : { dns }),
11
+ userAgent: 'media-provider',
12
+ policy: {
13
+ allowedSchemes: ['http', 'https'],
14
+ denyPrivateAddresses: allowPrivateNetwork !== true,
15
+ devHostAllowlist: [],
16
+ maxRedirects: 0,
17
+ connectTimeoutMs: FETCH_TIMEOUT_MS.GENERATE,
18
+ // Media can contain video; bound buffering at 96 MiB. Hosts may inject a stricter policy.
19
+ maxResponseBytes: 96 * 1024 * 1024,
20
+ maxDecompressedBytes: 96 * 1024 * 1024,
21
+ },
22
+ });
23
+ }
24
+ //# sourceMappingURL=node.js.map
@@ -34,7 +34,7 @@ export declare function buildOpenAIImageUrl(baseUrl: string, isAzure: boolean):
34
34
  export declare function buildOpenAIImageEditUrl(baseUrl: string): string;
35
35
  /** Builds the `/videos/generations` URL. */
36
36
  export declare function buildOpenAIVideoUrl(baseUrl: string): string;
37
- /** Picks an image `size` string tuned to the model family + requested aspect ratio. */
37
+ /** Picks an image `size` string tuned to the model family + requested aspect ratio, defaulting to the `1024x1024` square. */
38
38
  export declare function openaiSizeFor(model: string, aspect?: string): string;
39
39
  /** Builds the `/audio/speech` URL, appending the default Azure `api-version` when the caller didn't supply one. */
40
40
  export declare function buildOpenAISpeechUrl(baseUrl: string, isAzure: boolean): string;