@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
@@ -51,16 +51,53 @@ import { dispatchVendorRequest, requireApiKey } from '../vendor-adapter.js';
51
51
  // especially). The guarded client owns the socket and deadline budgets,
52
52
  // so a caller-configured global fetch default cannot cut a legitimately
53
53
  // slow-but-succeeding generation short. Pooling belongs to the injected guarded client.
54
- const OPENAI_IMAGE_HEADERS_TIMEOUT_MS = 10 * 60 * 1000;
55
- const OPENAI_IMAGE_BODY_TIMEOUT_MS = 10 * 60 * 1000;
54
+ // (Formerly two equal headers/body constants combined with `Math.max`; one
55
+ // ceiling covers both since the request carries a single abort signal.)
56
+ const OPENAI_IMAGE_TIMEOUT_MS = 10 * 60 * 1000;
57
+ const OPENAI_DEFAULT_BASE_URL = 'https://api.openai.com/v1';
58
+ const OPENAI_DEFAULT_SPEECH_VOICE = 'alloy';
56
59
  const OPENAI_IMAGE_NO_CREDENTIAL_MESSAGE = 'no OpenAI credential — configure an API key or set OPENAI_API_KEY.';
57
60
  const OPENAI_SPEECH_NO_CREDENTIAL_MESSAGE = 'no OpenAI credential — configure an API key or set OPENAI_API_KEY';
61
+ /**
62
+ * Resolves the base URL (default OpenAI endpoint), Azure detection, error tag
63
+ * and auth headers from already-validated credentials.
64
+ * @throws never — `requireCredential` has already rejected a missing API key.
65
+ */
66
+ function resolveOpenAITarget({ credentials }) {
67
+ const apiKey = credentials.apiKey; // requireCredential already validated this.
68
+ const rawBase = credentials.baseUrl || OPENAI_DEFAULT_BASE_URL;
69
+ const azure = detectAzureEndpoint(rawBase);
70
+ const headers = {
71
+ authorization: `Bearer ${apiKey}`,
72
+ 'content-type': 'application/json',
73
+ };
74
+ if (azure) {
75
+ // Azure's canonical auth header. Some deployments accept Bearer too,
76
+ // but api-key is what their docs document, so both are sent. OpenAI
77
+ // ignores unknown headers, so this is harmless on the standard
78
+ // endpoint too.
79
+ headers['api-key'] = apiKey;
80
+ }
81
+ return { rawBase, azure, tag: azure ? 'azure-openai' : 'openai', headers };
82
+ }
83
+ /**
84
+ * Splits the caller's `voice` into a concrete OpenAI voice id or free-form
85
+ * speaking-style instructions. A blank voice falls through to the default
86
+ * voice with empty instructions (no voice id is the empty string).
87
+ */
88
+ function resolveSpeechVoice({ voice }) {
89
+ const requestedVoice = voice?.trim() || '';
90
+ if (OPENAI_TTS_VOICES.has(requestedVoice))
91
+ return { voiceId: requestedVoice, instructions: '' };
92
+ // gpt-4o-mini-tts accepts free-form speaking-style instructions. If
93
+ // the caller passed prose rather than a concrete voice id, preserve
94
+ // it here instead of surfacing a provider error.
95
+ return { voiceId: OPENAI_DEFAULT_SPEECH_VOICE, instructions: requestedVoice };
96
+ }
58
97
  const openAIImageAdapter = {
59
98
  requireCredential: requireApiKey({ message: OPENAI_IMAGE_NO_CREDENTIAL_MESSAGE }),
60
99
  buildRequest({ ctx, credentials }) {
61
- const apiKey = credentials.apiKey; // requireCredential already validated this.
62
- const rawBase = credentials.baseUrl || 'https://api.openai.com/v1';
63
- const azure = detectAzureEndpoint(rawBase);
100
+ const { rawBase, azure, tag, headers } = resolveOpenAITarget({ credentials });
64
101
  const url = buildOpenAIImageUrl(rawBase, azure);
65
102
  const body = {
66
103
  prompt: ctx.prompt || 'A high-quality reference image.',
@@ -85,26 +122,15 @@ const openAIImageAdapter = {
85
122
  // gpt-image-* accepts quality 'high' | 'medium' | 'low'.
86
123
  body.quality = 'high';
87
124
  }
88
- const headers = {
89
- authorization: `Bearer ${apiKey}`,
90
- 'content-type': 'application/json',
91
- };
92
- if (azure) {
93
- // Azure's canonical auth header. Some deployments accept Bearer too,
94
- // but api-key is what their docs document, so both are sent. OpenAI
95
- // ignores unknown headers, so this is harmless on the standard
96
- // endpoint too.
97
- headers['api-key'] = apiKey;
98
- }
99
125
  return {
100
126
  url,
101
127
  init: withRequestInit(ctx, {
102
128
  method: 'POST',
103
129
  headers,
104
130
  body: JSON.stringify(body),
105
- signal: AbortSignal.timeout(Math.max(OPENAI_IMAGE_HEADERS_TIMEOUT_MS, OPENAI_IMAGE_BODY_TIMEOUT_MS)),
131
+ signal: AbortSignal.timeout(OPENAI_IMAGE_TIMEOUT_MS),
106
132
  }),
107
- meta: { tag: azure ? 'azure-openai' : 'openai', wireModel: ctx.wireModel },
133
+ meta: { tag, wireModel: ctx.wireModel },
108
134
  };
109
135
  },
110
136
  async parseResponse({ resp, ctx, request }) {
@@ -148,31 +174,16 @@ const openAIImageAdapter = {
148
174
  },
149
175
  };
150
176
  export async function renderOpenAIImage({ ctx, credentials }) {
151
- return dispatchVendorRequest({ adapter: openAIImageAdapter, ctx: ctx, credentials: credentials });
177
+ return dispatchVendorRequest({ adapter: openAIImageAdapter, ctx, credentials });
152
178
  }
153
179
  const openAISpeechAdapter = {
154
180
  requireCredential: requireApiKey({ message: OPENAI_SPEECH_NO_CREDENTIAL_MESSAGE }),
155
181
  buildRequest({ ctx, credentials }) {
156
- const apiKey = credentials.apiKey; // requireCredential already validated this.
157
- const rawBase = credentials.baseUrl || 'https://api.openai.com/v1';
158
- const azure = detectAzureEndpoint(rawBase);
182
+ const { rawBase, azure, tag, headers } = resolveOpenAITarget({ credentials });
159
183
  const url = buildOpenAISpeechUrl(rawBase, azure);
160
184
  const format = ctx.speechFormat;
161
- const text = (ctx.prompt && ctx.prompt.trim()) || 'This is a test.';
162
- let voiceId = 'alloy';
163
- let instructions = '';
164
- const requestedVoice = (ctx.voice && ctx.voice.trim()) || '';
165
- if (requestedVoice) {
166
- if (OPENAI_TTS_VOICES.has(requestedVoice)) {
167
- voiceId = requestedVoice;
168
- }
169
- else {
170
- // gpt-4o-mini-tts accepts free-form speaking-style instructions. If
171
- // the caller passed prose rather than a concrete voice id, preserve
172
- // it here instead of surfacing a provider error.
173
- instructions = requestedVoice;
174
- }
175
- }
185
+ const text = ctx.prompt?.trim() || 'This is a test.';
186
+ const { voiceId, instructions } = resolveSpeechVoice({ voice: ctx.voice });
176
187
  const body = {
177
188
  input: text,
178
189
  voice: voiceId,
@@ -184,13 +195,6 @@ const openAISpeechAdapter = {
184
195
  if (instructions && ctx.model === 'gpt-4o-mini-tts') {
185
196
  body.instructions = instructions;
186
197
  }
187
- const headers = {
188
- authorization: `Bearer ${apiKey}`,
189
- 'content-type': 'application/json',
190
- };
191
- if (azure) {
192
- headers['api-key'] = apiKey;
193
- }
194
198
  return {
195
199
  url,
196
200
  init: withRequestInit(ctx, {
@@ -198,7 +202,7 @@ const openAISpeechAdapter = {
198
202
  headers,
199
203
  body: JSON.stringify(body),
200
204
  }),
201
- meta: { tag: azure ? 'azure-openai' : 'openai', wireModel: ctx.wireModel, voiceId, format, instructions },
205
+ meta: { tag, wireModel: ctx.wireModel, voiceId, format, instructions },
202
206
  };
203
207
  },
204
208
  parseResponse: createRawBytesParser({
@@ -212,11 +216,11 @@ const openAISpeechAdapter = {
212
216
  noteBits.splice(2, 0, 'styled');
213
217
  return noteBits.join(' · ');
214
218
  },
215
- suggestedExt: ({ bytes: _bytes, meta }) => (meta.format === 'opus' ? '.ogg' : `.${meta.format}`),
219
+ suggestedExt: ({ meta }) => (meta.format === 'opus' ? '.ogg' : `.${meta.format}`),
216
220
  }),
217
221
  };
218
222
  export async function renderOpenAISpeech({ ctx, credentials }) {
219
- return dispatchVendorRequest({ adapter: openAISpeechAdapter, ctx: ctx, credentials: credentials });
223
+ return dispatchVendorRequest({ adapter: openAISpeechAdapter, ctx, credentials });
220
224
  }
221
225
  /** Explicit composition: importing a renderer never changes another module's registry. */
222
226
  export function registerVendorAdapters({ registry }, _optional = {}) {
@@ -1,5 +1,5 @@
1
1
  import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
- import type { VendorAdapterRegistry } from '../vendor-registry.js';
2
+ import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
3
  /**
4
4
  * OpenRouter normalizes aspect ratios across the providers it fronts;
5
5
  * `providers.ts`'s `MEDIA_ASPECTS` are all natively supported, default to
@@ -35,9 +35,8 @@ import { sniffImageExt, truncate, withRequestInit } from '../openai-compatible.j
35
35
  import { dispatchVendorRequest, requireApiKey } from '../vendor-adapter.js';
36
36
  // Chat-completions image generation can take a while for some routed
37
37
  // models; matches the same 10-minute ceiling `openai.ts`'s image dispatcher
38
- // uses for the same reason (see `OPENAI_IMAGE_HEADERS_TIMEOUT_MS`/
39
- // `OPENAI_IMAGE_BODY_TIMEOUT_MS` there — this vendor has no separate
40
- // headers/body distinction, so a single `AbortSignal.timeout` suffices).
38
+ // uses for the same reason (see `OPENAI_IMAGE_TIMEOUT_MS` there — a single
39
+ // `AbortSignal.timeout` covers the whole request for both vendors).
41
40
  const OPENROUTER_IMAGE_TIMEOUT_MS = 10 * 60 * 1000;
42
41
  /**
43
42
  * OpenRouter normalizes aspect ratios across the providers it fronts;
@@ -104,39 +103,8 @@ const openRouterImageAdapter = {
104
103
  if (!resp.ok) {
105
104
  throw new Error(`openrouter image ${resp.status}: ${truncate(text, 240)}`);
106
105
  }
107
- let data;
108
- try {
109
- data = JSON.parse(text);
110
- }
111
- catch {
112
- throw new Error(`openrouter image non-JSON response: ${truncate(text, 200)}`);
113
- }
114
- const images = data?.choices?.[0]?.message?.images;
115
- if (!Array.isArray(images) || images.length === 0) {
116
- throw new Error(`openrouter image response contained no images for model ${wireModel}: ${truncate(text, 200)}`);
117
- }
118
- const dataUrl = images[0]?.image_url?.url;
119
- if (typeof dataUrl !== 'string' || !dataUrl) {
120
- throw new Error(`openrouter image response missing image_url.url: ${truncate(text, 200)}`);
121
- }
122
- // Strip a "data:image/...;base64," prefix and decode; fall back to
123
- // downloading a plain URL, or treating the string as raw base64.
124
- const b64Match = dataUrl.match(/^data:image\/[^;]+;base64,(.+)$/s);
125
- let bytes;
126
- if (b64Match) {
127
- bytes = Buffer.from(b64Match[1], 'base64');
128
- }
129
- else if (dataUrl.startsWith('http')) {
130
- // Downloading already-generated bytes, not waiting on generation — UPLOAD-class (2min), not
131
- // the 10-minute GENERATE-class timeout the chat-completions call itself uses above.
132
- const imgResp = await assertAndFetchExternalAsset({ url: dataUrl }, { ...ctx, init: withRequestInit(ctx) });
133
- if (!imgResp.ok)
134
- throw new Error(`openrouter image download ${imgResp.status}`);
135
- bytes = Buffer.from(await imgResp.arrayBuffer());
136
- }
137
- else {
138
- bytes = Buffer.from(dataUrl, 'base64');
139
- }
106
+ const imageUrl = extractOpenRouterImageUrl({ text, wireModel });
107
+ const bytes = await decodeOpenRouterImage({ imageUrl, ctx });
140
108
  return {
141
109
  bytes,
142
110
  providerNote: `openrouter/${wireModel} · ${aspectRatio} · ${bytes.length} bytes`,
@@ -144,8 +112,55 @@ const openRouterImageAdapter = {
144
112
  };
145
113
  },
146
114
  };
115
+ /**
116
+ * Parses an OK chat-completions body and returns
117
+ * `choices[0].message.images[0].image_url.url`.
118
+ * @throws Error — non-JSON body, no images, or a missing/empty/non-string url;
119
+ * each message quotes the truncated body (never request headers/credentials).
120
+ */
121
+ function extractOpenRouterImageUrl({ text, wireModel }) {
122
+ let data;
123
+ try {
124
+ data = JSON.parse(text);
125
+ }
126
+ catch {
127
+ throw new Error(`openrouter image non-JSON response: ${truncate(text, 200)}`);
128
+ }
129
+ const images = firstChoiceImages({ data });
130
+ if (!Array.isArray(images) || images.length === 0) {
131
+ throw new Error(`openrouter image response contained no images for model ${wireModel}: ${truncate(text, 200)}`);
132
+ }
133
+ const imageUrl = images[0]?.image_url?.url;
134
+ if (typeof imageUrl !== 'string' || !imageUrl) {
135
+ throw new Error(`openrouter image response missing image_url.url: ${truncate(text, 200)}`);
136
+ }
137
+ return imageUrl;
138
+ }
139
+ /** `choices[0].message.images` of a parsed body, or `undefined` when any level is absent (a JSON `null` body included). */
140
+ function firstChoiceImages({ data }) {
141
+ return data?.choices?.[0]?.message?.images;
142
+ }
143
+ /**
144
+ * Turns the returned image reference into bytes.
145
+ * @throws Error — the SSRF guard refuses the download URL, or the download is not OK.
146
+ */
147
+ async function decodeOpenRouterImage({ imageUrl, ctx }) {
148
+ // Strip a "data:image/...;base64," prefix and decode; fall back to
149
+ // downloading a plain URL, or treating the string as raw base64.
150
+ const b64Match = imageUrl.match(/^data:image\/[^;]+;base64,(.+)$/s);
151
+ if (b64Match)
152
+ return Buffer.from(b64Match[1], 'base64');
153
+ if (!imageUrl.startsWith('http'))
154
+ return Buffer.from(imageUrl, 'base64');
155
+ // Downloading already-generated bytes, not waiting on generation — UPLOAD-class (2min), not
156
+ // the 10-minute GENERATE-class timeout the chat-completions call itself uses above.
157
+ const imgResp = await assertAndFetchExternalAsset({ url: imageUrl }, { ...ctx, init: withRequestInit(ctx) });
158
+ if (!imgResp.ok)
159
+ throw new Error(`openrouter image download ${imgResp.status}`);
160
+ return Buffer.from(await imgResp.arrayBuffer());
161
+ }
147
162
  export async function renderOpenRouterImage({ ctx, credentials }) {
148
- return dispatchVendorRequest({ adapter: openRouterImageAdapter, ctx: ctx, credentials: credentials });
163
+ return dispatchVendorRequest({ adapter: openRouterImageAdapter, ctx, credentials });
149
164
  }
150
165
  /** Explicit composition: importing a renderer never changes another module's registry. */
151
166
  export function registerVendorAdapters({ registry }, _optional = {}) {
@@ -1,5 +1,5 @@
1
1
  import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
- import type { VendorAdapterRegistry } from '../vendor-registry.js';
2
+ import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
3
  export declare function renderSenseAudioTTS({ ctx, credentials }: {
4
4
  ctx: RenderContext;
5
5
  credentials: ProviderCredentials;
@@ -95,7 +95,7 @@ const senseAudioTTSAdapter = {
95
95
  parseResponse: createHexEnvelopeAudioParser({ errorTag: 'senseaudio tts', providerId: 'senseaudio' }),
96
96
  };
97
97
  export async function renderSenseAudioTTS({ ctx, credentials }) {
98
- return dispatchVendorRequest({ adapter: senseAudioTTSAdapter, ctx: ctx, credentials: credentials });
98
+ return dispatchVendorRequest({ adapter: senseAudioTTSAdapter, ctx, credentials });
99
99
  }
100
100
  /** SenseAudio's image gateway rejects non-standard pixel sizes with a 400; keep this mapping in sync with any other SenseAudio-image call site a future host adds. */
101
101
  function senseAudioImageSize(aspect) {
@@ -117,7 +117,7 @@ const senseAudioImageAdapter = {
117
117
  const promptRaw = (ctx.prompt && ctx.prompt.trim()) || 'A high-quality reference image.';
118
118
  // SenseAudio rejects prompts over 2000 chars with a 4xx; trim
119
119
  // defensively so a verbose caller doesn't dead-end the generation.
120
- const prompt = promptRaw.length > SENSEAUDIO_IMAGE_PROMPT_LIMIT ? promptRaw.slice(0, SENSEAUDIO_IMAGE_PROMPT_LIMIT) : promptRaw;
120
+ const prompt = promptRaw.slice(0, SENSEAUDIO_IMAGE_PROMPT_LIMIT);
121
121
  const size = senseAudioImageSize(ctx.aspect);
122
122
  const reference = ctx.imageRef?.dataUrl;
123
123
  const body = {
@@ -149,31 +149,8 @@ const senseAudioImageAdapter = {
149
149
  if (!resp.ok) {
150
150
  throw new Error(`senseaudio image ${resp.status}: ${truncate(respText, 240)}`);
151
151
  }
152
- let data;
153
- try {
154
- data = JSON.parse(respText);
155
- }
156
- catch {
157
- throw new Error(`senseaudio image non-JSON: ${truncate(respText, 200)}`);
158
- }
159
- if (data.base_resp && data.base_resp.status_code !== 0) {
160
- throw new Error(`senseaudio image api error ${data.base_resp.status_code}: ${data.base_resp.status_msg || 'unknown'}`);
161
- }
162
- if (typeof data.error_message === 'string' && data.error_message) {
163
- throw new Error(`senseaudio image api error: ${data.error_message}`);
164
- }
165
- const url = typeof data.url === 'string' ? data.url : '';
166
- if (!url) {
167
- throw new Error('senseaudio image response missing url');
168
- }
169
- const imgResp = await assertAndFetchExternalAsset({ url: url }, { ...ctx, init: withRequestInit(ctx) });
170
- if (!imgResp.ok) {
171
- throw new Error(`senseaudio image fetch ${imgResp.status}`);
172
- }
173
- const bytes = Buffer.from(await imgResp.arrayBuffer());
174
- if (bytes.length === 0) {
175
- throw new Error('senseaudio image fetch returned zero bytes');
176
- }
152
+ const url = extractSenseAudioImageUrl({ respText });
153
+ const bytes = await downloadSenseAudioImage({ url, ctx });
177
154
  return {
178
155
  bytes,
179
156
  providerNote: `senseaudio/${ctx.wireModel} · ${request.meta.size}${request.meta.hasReference ? ' · i2i' : ''} · ${bytes.length} bytes`,
@@ -181,8 +158,50 @@ const senseAudioImageAdapter = {
181
158
  };
182
159
  },
183
160
  };
161
+ /**
162
+ * Parses an OK image envelope and returns its `url`. Two independent
163
+ * failure-signaling paths are honored in order: a non-zero (or absent)
164
+ * `base_resp.status_code`, then a non-empty `error_message`.
165
+ * @throws Error — non-JSON body, either API-error path, or a missing/non-string url.
166
+ */
167
+ function extractSenseAudioImageUrl({ respText }) {
168
+ let data;
169
+ try {
170
+ data = JSON.parse(respText);
171
+ }
172
+ catch {
173
+ throw new Error(`senseaudio image non-JSON: ${truncate(respText, 200)}`);
174
+ }
175
+ if (data.base_resp && data.base_resp.status_code !== 0) {
176
+ throw new Error(`senseaudio image api error ${data.base_resp.status_code}: ${data.base_resp.status_msg || 'unknown'}`);
177
+ }
178
+ if (typeof data.error_message === 'string' && data.error_message) {
179
+ throw new Error(`senseaudio image api error: ${data.error_message}`);
180
+ }
181
+ if (typeof data.url !== 'string' || !data.url) {
182
+ throw new Error('senseaudio image response missing url');
183
+ }
184
+ return data.url;
185
+ }
186
+ /**
187
+ * Downloads the generated image through the SSRF guard (the url is
188
+ * attacker-controllable inside an otherwise-successful response — see the
189
+ * module doc).
190
+ * @throws Error — the guard refuses the url, the download is not OK, or it is empty.
191
+ */
192
+ async function downloadSenseAudioImage({ url, ctx }) {
193
+ const imgResp = await assertAndFetchExternalAsset({ url }, { ...ctx, init: withRequestInit(ctx) });
194
+ if (!imgResp.ok) {
195
+ throw new Error(`senseaudio image fetch ${imgResp.status}`);
196
+ }
197
+ const bytes = Buffer.from(await imgResp.arrayBuffer());
198
+ if (bytes.length === 0) {
199
+ throw new Error('senseaudio image fetch returned zero bytes');
200
+ }
201
+ return bytes;
202
+ }
184
203
  export async function renderSenseAudioImage({ ctx, credentials }) {
185
- return dispatchVendorRequest({ adapter: senseAudioImageAdapter, ctx: ctx, credentials: credentials });
204
+ return dispatchVendorRequest({ adapter: senseAudioImageAdapter, ctx, credentials });
186
205
  }
187
206
  /** Explicit composition: importing a renderer never changes another module's registry. */
188
207
  export function registerVendorAdapters({ registry }, _optional = {}) {
@@ -1,5 +1,5 @@
1
1
  import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
- import type { VendorAdapterRegistry } from '../vendor-registry.js';
2
+ import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
3
  export declare function renderVolcengineImage({ ctx, credentials }: {
4
4
  ctx: RenderContext;
5
5
  credentials: ProviderCredentials;
@@ -72,31 +72,15 @@ export function createRawBytesParser(options) {
72
72
  * https://help.aliyun.com/zh/model-studio/minimax-synchronous-speech-synthesis-api.
73
73
  */
74
74
  export function createHexEnvelopeAudioParser(options) {
75
+ const { errorTag } = options;
75
76
  return async ({ resp, request }) => {
76
77
  const respText = await resp.text();
77
78
  if (!resp.ok) {
78
- throw new Error(`${options.errorTag} ${resp.status}: ${truncate(respText, 240)}`);
79
+ throw new Error(`${errorTag} ${resp.status}: ${truncate(respText, 240)}`);
79
80
  }
80
- let data;
81
- try {
82
- data = JSON.parse(respText);
83
- }
84
- catch {
85
- throw new Error(`${options.errorTag} non-JSON: ${truncate(respText, 200)}`);
86
- }
87
- if (data.base_resp && data.base_resp.status_code !== 0) {
88
- throw new Error(`${options.errorTag} api error ${data.base_resp.status_code}: ${data.base_resp.status_msg || 'unknown'}`);
89
- }
90
- const hex = data.data?.audio;
91
- if (typeof hex !== 'string' || !hex) {
92
- throw new Error(`${options.errorTag} response missing data.audio`);
93
- }
94
- const bytes = Buffer.from(hex, 'hex');
95
- if (bytes.length === 0) {
96
- throw new Error(`${options.errorTag} decoded zero bytes`);
97
- }
98
- const audioLength = data.extra_info?.audio_length;
99
- const seconds = audioLength ? Math.round(audioLength / 100) / 10 : '?';
81
+ const data = parseHexEnvelopeBody({ respText, errorTag });
82
+ const bytes = decodeHexEnvelopeAudio({ data, errorTag });
83
+ const seconds = formatAudioSeconds(data.extra_info?.audio_length);
100
84
  return {
101
85
  bytes,
102
86
  providerNote: `${options.providerId}/${request.meta.wireModel} · ${request.meta.voiceId} · ${seconds}s · ${bytes.length} bytes`,
@@ -104,4 +88,36 @@ export function createHexEnvelopeAudioParser(options) {
104
88
  };
105
89
  };
106
90
  }
91
+ /** Parses an OK hex-envelope body and rejects a non-JSON body or a logical (`base_resp.status_code !== 0`) failure. */
92
+ function parseHexEnvelopeBody(required) {
93
+ const { respText, errorTag } = required;
94
+ let data;
95
+ try {
96
+ data = JSON.parse(respText);
97
+ }
98
+ catch {
99
+ throw new Error(`${errorTag} non-JSON: ${truncate(respText, 200)}`);
100
+ }
101
+ if (data.base_resp && data.base_resp.status_code !== 0) {
102
+ throw new Error(`${errorTag} api error ${data.base_resp.status_code}: ${data.base_resp.status_msg || 'unknown'}`);
103
+ }
104
+ return data;
105
+ }
106
+ /** Decodes `data.audio` hex into bytes, refusing a missing/non-string/empty payload or one that decodes to zero bytes. */
107
+ function decodeHexEnvelopeAudio(required) {
108
+ const { data, errorTag } = required;
109
+ const hex = data.data?.audio;
110
+ if (typeof hex !== 'string' || !hex) {
111
+ throw new Error(`${errorTag} response missing data.audio`);
112
+ }
113
+ const bytes = Buffer.from(hex, 'hex');
114
+ if (bytes.length === 0) {
115
+ throw new Error(`${errorTag} decoded zero bytes`);
116
+ }
117
+ return bytes;
118
+ }
119
+ /** `audio_length` milliseconds rounded to tenths of a second; `'?'` when absent (or 0), matching both vendors' own formatting. */
120
+ function formatAudioSeconds(audioLength) {
121
+ return audioLength ? Math.round(audioLength / 100) / 10 : '?';
122
+ }
107
123
  //# sourceMappingURL=response-parsers.js.map
@@ -1,5 +1,5 @@
1
1
  import { loadMediaSqliteOpener } from '../sqlite-driver.adapter.js';
2
- import { ASYNC_OPERATION_SCHEMA_VERSION, ASYNC_OPERATION_STATUSES, assertNoCredentialMaterial, assertTransition, hydrateAsyncOperationRecord, TERMINAL_STATUSES, } from './async-operation-store.js';
2
+ import { ASYNC_OPERATION_SCHEMA_VERSION, ASYNC_OPERATION_STATUSES, assertValidCreateInput, hydrateAsyncOperationRecord, isFencedOut, mergeAsyncOperationPatch, TERMINAL_STATUSES, } from './async-operation-store.js';
3
3
  /**
4
4
  * The non-terminal ("live") status values — `ASYNC_OPERATION_STATUSES` minus `TERMINAL_STATUSES`,
5
5
  * built once so this file cannot itself drift from either source set. Used as a positive
@@ -113,23 +113,18 @@ export async function createSqliteAsyncOperationStore({ dbPath, open: injectedOp
113
113
  WHERE status IN (${LIVE_PLACEHOLDERS}) AND lease_owner IS NOT NULL AND (lease_expires_at IS NULL OR lease_expires_at <= ?)
114
114
  RETURNING *
115
115
  `);
116
- function stateJson(state) {
117
- return state == null ? null : JSON.stringify(state);
116
+ /** A nullable JSON column: `null`/`undefined` store SQL NULL, anything else its JSON text. */
117
+ function jsonOrNull(value) {
118
+ return value == null ? null : JSON.stringify(value);
118
119
  }
119
120
  const createTxn = db.transaction((input) => {
120
121
  if (getStmt.get(input.id)) {
121
122
  throw new Error(`async operation "${input.id}" already exists`);
122
123
  }
123
- if (!Number.isFinite(input.maxAttempts) || input.maxAttempts < 1) {
124
- throw new RangeError(`Invalid maxAttempts: ${input.maxAttempts} must be a finite number >= 1`);
125
- }
126
- if (!Number.isFinite(input.deadlineAt)) {
127
- throw new RangeError(`Invalid deadlineAt: ${input.deadlineAt} must be a finite epoch-ms timestamp`);
128
- }
129
- assertNoCredentialMaterial({ state: input.state });
124
+ assertValidCreateInput({ input });
130
125
  const now = Date.now();
131
126
  const status = input.status ?? 'submitted';
132
- insertStmt.run(input.id, input.providerId, input.routeKey, input.ownerRef, status, 0, input.maxAttempts, input.deadlineAt, input.nextPollAt ?? now, stateJson(input.state), ASYNC_OPERATION_SCHEMA_VERSION, now, now);
127
+ insertStmt.run(input.id, input.providerId, input.routeKey, input.ownerRef, status, 0, input.maxAttempts, input.deadlineAt, input.nextPollAt ?? now, jsonOrNull(input.state), ASYNC_OPERATION_SCHEMA_VERSION, now, now);
133
128
  return rowToOperation(getStmt.get(input.id));
134
129
  });
135
130
  const updateTxn = db.transaction((id, patch, options) => {
@@ -139,25 +134,10 @@ export async function createSqliteAsyncOperationStore({ dbPath, open: injectedOp
139
134
  const existing = rowToOperation(existingRow);
140
135
  // Fenced exactly like `releaseLease` and the in-memory store: a caller writing against a
141
136
  // lease it no longer holds gets the row back unchanged, not an overwrite.
142
- if (options?.leaseOwner !== undefined && existing.leaseOwner !== options.leaseOwner) {
137
+ if (isFencedOut({ existing, options }))
143
138
  return existing;
144
- }
145
- if ('state' in patch)
146
- assertNoCredentialMaterial({ state: patch.state });
147
- const status = patch.status ?? existing.status;
148
- assertTransition(existing.status, status);
149
- const next = {
150
- status,
151
- attempts: patch.attempts ?? existing.attempts,
152
- nextPollAt: patch.nextPollAt ?? existing.nextPollAt,
153
- state: 'state' in patch ? (patch.state ?? null) : existing.state,
154
- result: 'result' in patch ? (patch.result ?? null) : existing.result,
155
- error: 'error' in patch ? (patch.error ?? null) : existing.error,
156
- leaseOwner: 'leaseOwner' in patch ? (patch.leaseOwner ?? null) : existing.leaseOwner,
157
- leaseExpiresAt: 'leaseExpiresAt' in patch ? (patch.leaseExpiresAt ?? null) : existing.leaseExpiresAt,
158
- updatedAt: Date.now(),
159
- };
160
- updateStmt.run(next.status, next.attempts, next.nextPollAt, stateJson(next.state), next.result === null ? null : JSON.stringify(next.result), next.error === null ? null : JSON.stringify(next.error), next.leaseOwner, next.leaseExpiresAt, next.updatedAt, id);
139
+ const next = mergeAsyncOperationPatch({ existing, patch }, { now: Date.now() });
140
+ updateStmt.run(next.status, next.attempts, next.nextPollAt, jsonOrNull(next.state), jsonOrNull(next.result), jsonOrNull(next.error), next.leaseOwner, next.leaseExpiresAt, next.updatedAt, id);
161
141
  return rowToOperation(getStmt.get(id));
162
142
  });
163
143
  const claimDueTxn = db.transaction((options) => {
@@ -52,12 +52,13 @@ export declare function assertExternalAssetUrl({ rawUrl }: {
52
52
  * forgotten at a call site); the forced `redirect` is spread last so it
53
53
  * overrides any value the caller passed in `init`. Callers keep their own
54
54
  * `!resp.ok` HTTP-status handling.
55
- * @throws URL/policy refusals and DNS/transport failures, before unsafe I/O.
55
+ * `lookup` is retained for source compatibility; DNS configuration belongs on httpClient.
56
+ * @throws URL/policy refusals, a missing client, and DNS/transport failures before unsafe I/O.
56
57
  * @complexity O(a + b) for a DNS answers and b bounded decoded asset bytes.
57
58
  */
58
59
  export declare function assertAndFetchExternalAsset({ url }: {
59
60
  url: string;
60
- }, { init, lookup, ...outbound }?: MediaOutboundOptions & {
61
+ }, { init, lookup: _lookup, ...outbound }?: MediaOutboundOptions & {
61
62
  init?: RequestInit | undefined;
62
63
  lookup?: DnsLookupFn | undefined;
63
64
  }): Promise<Response>;
@@ -26,7 +26,7 @@
26
26
  * `allowedInternalHosts` argument is empty/absent (its own first line is
27
27
  * `if (!allowedInternalHosts || allowedInternalHosts.length === 0) return
28
28
  * false;`) — so the allowlist branch is provably dead code on this call
29
- * path and is not ported. The default asset-download path is strict. Only an explicit
29
+ * path and is not ported. The explicit Node adapter defaults to strict asset downloads. Only its
30
30
  * `allowPrivateNetwork: true` development capability or a host-supplied
31
31
  * policy-enforcing client can change the network policy; a host
32
32
  * that wants an operator-configurable internal-host allowlist for its own
@@ -40,7 +40,7 @@
40
40
  import { isLoopbackApiHost, isBlockedExternalApiHostname } from '@jini-ai/platform/net';
41
41
  import { promises as dnsPromises } from 'node:dns';
42
42
  import { FETCH_TIMEOUT_MS } from '@jini-ai/platform/fetch-with-timeout';
43
- import { defaultMediaOutboundMessages, fetchMediaOutbound } from './outbound.js';
43
+ import { defaultMediaOutboundMessages, fetchMediaOutbound, requireMediaHttpClient } from './outbound.js';
44
44
  const defaultDnsLookup = async ({ hostname }) => {
45
45
  const result = await dnsPromises.lookup(hostname, { all: true, family: 0 });
46
46
  return result.map(({ address, family }) => ({ address, family }));
@@ -135,10 +135,11 @@ export async function assertExternalAssetUrl({ rawUrl }, { lookup = defaultDnsLo
135
135
  * forgotten at a call site); the forced `redirect` is spread last so it
136
136
  * overrides any value the caller passed in `init`. Callers keep their own
137
137
  * `!resp.ok` HTTP-status handling.
138
- * @throws URL/policy refusals and DNS/transport failures, before unsafe I/O.
138
+ * `lookup` is retained for source compatibility; DNS configuration belongs on httpClient.
139
+ * @throws URL/policy refusals, a missing client, and DNS/transport failures before unsafe I/O.
139
140
  * @complexity O(a + b) for a DNS answers and b bounded decoded asset bytes.
140
141
  */
141
- export async function assertAndFetchExternalAsset({ url }, { init = {}, lookup, ...outbound } = {}) {
142
+ export async function assertAndFetchExternalAsset({ url }, { init = {}, lookup: _lookup, ...outbound } = {}) {
142
143
  // Preserve the early URL diagnostic. DNS vetting belongs to the client that pins the socket,
143
144
  // not an independent lookup followed by a fetch that resolves the hostname a second time.
144
145
  if (outbound.allowPrivateNetwork !== true && outbound.httpClient === undefined) {
@@ -149,8 +150,8 @@ export async function assertAndFetchExternalAsset({ url }, { init = {}, lookup,
149
150
  // Downloading an already-generated asset, not waiting on generation — UPLOAD-class (2min).
150
151
  return fetchMediaOutbound({ url, timeoutMs: FETCH_TIMEOUT_MS.UPLOAD }, {
151
152
  ...outbound,
153
+ httpClient: requireMediaHttpClient(outbound),
152
154
  init: { ...init, redirect: 'error' },
153
- ...(lookup === undefined ? {} : { dns: { resolve: async ({ hostname }) => (await lookup({ hostname })).map(entry => entry.address) } }),
154
155
  });
155
156
  }
156
157
  //# sourceMappingURL=ssrf-guard.js.map