@jini-ai/integrations 0.6.15-rc.1 → 0.6.15

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 (29) hide show
  1. package/dist/api-connections/token-store/record.js +3 -2
  2. package/dist/credentialed-http/credentialed-request.js +7 -1
  3. package/dist/credentialed-http/response-redaction.js +2 -3
  4. package/dist/media-providers/dispatch/async-operation-store.js +5 -12
  5. package/dist/media-providers/dispatch/media-provider-registry.js +5 -1
  6. package/dist/media-providers/dispatch/openai-compatible.d.ts +14 -0
  7. package/dist/media-providers/dispatch/openai-compatible.js +27 -2
  8. package/dist/media-providers/dispatch/operation-runtime.js +1 -1
  9. package/dist/media-providers/dispatch/outbound.js +2 -1
  10. package/dist/media-providers/dispatch/providers/grok.d.ts +40 -13
  11. package/dist/media-providers/dispatch/providers/grok.js +2 -24
  12. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +3 -2
  13. package/dist/media-providers/dispatch/providers/imagerouter.js +1 -1
  14. package/dist/media-providers/dispatch/providers/openrouter.d.ts +2 -12
  15. package/dist/media-providers/dispatch/providers/openrouter.js +2 -23
  16. package/dist/media-providers/dispatch/ssrf-guard.js +2 -1
  17. package/dist/media-providers/policy.js +1 -1
  18. package/dist/media-providers/providers.d.ts +0 -1
  19. package/dist/media-providers/providers.js +6 -4
  20. package/dist/media-providers/sqlite-task-store.js +12 -7
  21. package/dist/media-providers/staging.js +2 -5
  22. package/dist/media-providers/task-store.js +12 -7
  23. package/dist/media-providers/ui-defaults.js +7 -5
  24. package/dist/saved-requests/execute.js +2 -1
  25. package/dist/saved-requests/projection.js +2 -1
  26. package/dist/saved-requests/validation.js +2 -1
  27. package/dist/webhooks/delivery.js +4 -1
  28. package/dist/webhooks/signing.js +3 -2
  29. package/package.json +10 -10
@@ -60,8 +60,9 @@ export function parseTokenSet({ value }) {
60
60
  if (!isRecord(value))
61
61
  throw invalid();
62
62
  const { accessToken, refreshToken, tokenType, scopes, expiresAt } = value;
63
- const valid = typeof accessToken === "string" && accessToken.length > 0 && isNullableString(refreshToken) &&
64
- typeof tokenType === "string" && isStringList(scopes) && isNullableString(expiresAt);
63
+ const hasAccessToken = typeof accessToken === "string" && accessToken.length > 0;
64
+ const grantValid = isNullableString(refreshToken) && typeof tokenType === "string";
65
+ const valid = hasAccessToken && grantValid && isStringList(scopes) && isNullableString(expiresAt);
65
66
  if (!valid)
66
67
  throw invalid();
67
68
  return { accessToken, refreshToken, tokenType, scopes: [...scopes], expiresAt };
@@ -8,6 +8,12 @@
8
8
  */
9
9
  import { IntegrationError } from "../argument-error.js";
10
10
  import { CredentialedRequestValidationError } from "../contracts/credentialed-request-errors.js";
11
+ /** The scheme name a resolved authorization actually sends. */
12
+ function schemeLabel(resolved) {
13
+ if (resolved.kind === "self-describing")
14
+ return resolved.scheme;
15
+ return resolved.kind === "basic" ? "Basic" : "Bearer";
16
+ }
11
17
  export { CredentialedRequestValidationError } from "../contracts/credentialed-request-errors.js";
12
18
  import { nowIso } from "@jini-ai/core/primitives";
13
19
  import { detectSelfDescribingAuthScheme } from "./auth-schemes.js";
@@ -148,7 +154,7 @@ function buildBasicAuthPayload(username, token) {
148
154
  function buildAuthFailureDiagnostic(connection, status, schemes) {
149
155
  const usernameStored = connection.username !== undefined;
150
156
  const resolved = resolveAuthorizationScheme(connection, schemes);
151
- const schemeSent = resolved.kind === "self-describing" ? resolved.scheme : resolved.kind === "basic" ? "Basic" : "Bearer";
157
+ const schemeSent = schemeLabel(resolved);
152
158
  // A provider once returned 403 for a missing User-Agent, and suggesting Basic auth led to an
153
159
  // ineffective username repair. Scope/policy/header refusals explain 403 too; retain facts without
154
160
  // guessing. Gate on the scheme actually sent, not username presence alone.
@@ -20,9 +20,8 @@ const BODY_WITHHELD_SHORT_TOKEN_MARKER = "[body withheld: credential too short t
20
20
  export function redactResponseHeaders(headers, secrets) {
21
21
  const result = {};
22
22
  for (const [key, value] of Object.entries(headers)) {
23
- if (FORBIDDEN_RESPONSE_HEADER_NAMES.has(key.trim().toLowerCase()))
24
- continue;
25
- if (secrets.some((secret) => secret !== "" && value.includes(secret)))
23
+ const forbidden = FORBIDDEN_RESPONSE_HEADER_NAMES.has(key.trim().toLowerCase());
24
+ if (forbidden || secrets.some((secret) => secret !== "" && value.includes(secret)))
26
25
  continue;
27
26
  result[key] = value;
28
27
  }
@@ -273,17 +273,12 @@ export function createInMemoryAsyncOperationStore() {
273
273
  const { now, leaseOwner, leaseMs } = options;
274
274
  const limit = options.limit ?? 10;
275
275
  const claimed = [];
276
- for (const row of [...rows.values()].sort((a, b) => a.nextPollAt - b.nextPollAt)) {
276
+ // A live lease held by anyone (including this worker's previous tick) blocks the claim;
277
+ // an expired one does not, which is what makes a dead worker's rows recoverable.
278
+ const blocked = (row) => TERMINAL_STATUSES.has(row.status) || row.nextPollAt > now || (row.leaseExpiresAt !== null && row.leaseExpiresAt > now);
279
+ for (const row of [...rows.values()].sort((a, b) => a.nextPollAt - b.nextPollAt).filter((each) => !blocked(each))) {
277
280
  if (claimed.length >= limit)
278
281
  break;
279
- if (TERMINAL_STATUSES.has(row.status))
280
- continue;
281
- if (row.nextPollAt > now)
282
- continue;
283
- // A live lease held by anyone (including this worker's previous tick) blocks the claim;
284
- // an expired one does not, which is what makes a dead worker's rows recoverable.
285
- if (row.leaseExpiresAt !== null && row.leaseExpiresAt > now)
286
- continue;
287
282
  const leased = {
288
283
  ...row,
289
284
  leaseOwner,
@@ -309,9 +304,7 @@ export function createInMemoryAsyncOperationStore() {
309
304
  const { now } = options;
310
305
  let leasesReleased = 0;
311
306
  let deadlineExpired = 0;
312
- for (const row of [...rows.values()]) {
313
- if (TERMINAL_STATUSES.has(row.status))
314
- continue;
307
+ for (const row of [...rows.values()].filter((each) => !TERMINAL_STATUSES.has(each.status))) {
315
308
  if (row.deadlineAt <= now) {
316
309
  rows.set(row.id, {
317
310
  ...row,
@@ -68,7 +68,11 @@ function byOrder(left, right) {
68
68
  }
69
69
  /** Strips the registry-only fields so callers see the same `MediaModel` shape as the static catalogue. */
70
70
  function asMediaModel(model) {
71
- const { surface: _surface, audioKind: _audioKind, order: _order, ...rest } = model;
71
+ // Registry-only placement fields are not part of the public model shape.
72
+ const rest = { ...model };
73
+ delete rest.surface;
74
+ delete rest.audioKind;
75
+ delete rest.order;
72
76
  return rest;
73
77
  }
74
78
  /**
@@ -4,6 +4,20 @@ import type { MediaGenerationRequestInit, MediaSpeechFormat, RenderContext } fro
4
4
  export declare const OPENAI_TTS_VOICES: ReadonlySet<string>;
5
5
  /** Validates a caller-requested speech format, defaulting to `'mp3'` for anything unrecognized. */
6
6
  export declare function resolveSpeechFormat(requested: MediaSpeechFormat | undefined): MediaSpeechFormat;
7
+ /**
8
+ * OpenRouter normalizes aspect ratios across the providers it fronts;
9
+ * `providers.ts`'s `MEDIA_ASPECTS` are all natively supported. xAI's Imagine
10
+ * API accepts a wider list (1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 2:1, 1:2,
11
+ * 19.5:9, 9:19.5, 20:9, 9:20, auto), of which `MEDIA_ASPECTS` is a strict
12
+ * subset. Both mappings pass through the same five values and default to 16:9.
13
+ * Written as independent `if` returns (rather than the origin's one
14
+ * `||`-chained condition) to match the established aspect-mapping style
15
+ * (see `providers/imagerouter.ts`'s `imageRouterSizeFor`) — same input ->
16
+ * output mapping for every case, not a behavior change.
17
+ */
18
+ export declare function standardImageAspectFor({ aspect }: {
19
+ aspect: string | undefined;
20
+ }, _options?: Record<string, never>): string;
7
21
  /** Truncates a string for inclusion in an error message, appending an ellipsis when truncated. */
8
22
  export declare function truncate(s: unknown, n: number): string;
9
23
  /** Merges a per-request `requestInit` (e.g. a caller-supplied `dispatcher`) under an explicit `init`, so per-call overrides win. */
@@ -6,6 +6,7 @@
6
6
  * helpers inside Open Design's `apps/daemon/src/media/index.ts` — see
7
7
  * `archived provenance ledger`.
8
8
  */
9
+ import { trimCharsEnd } from '@jini-ai/core/primitives';
9
10
  import { assertAndFetchExternalAsset } from './ssrf-guard.js';
10
11
  const VALID_SPEECH_FORMATS = new Set(['mp3', 'wav', 'flac', 'aac', 'opus']);
11
12
  /** OpenAI's recognized `/audio/speech` voice ids — shared by every vendor whose TTS wire shape matches OpenAI's (OpenAI itself, AIHubMix). A requested voice outside this set is treated by callers as free-form speaking-style instructions rather than a voice id (see `openai.ts`'s `renderOpenAISpeech`). */
@@ -14,6 +15,30 @@ export const OPENAI_TTS_VOICES = new Set(['alloy', 'ash', 'ballad', 'coral', 'ec
14
15
  export function resolveSpeechFormat(requested) {
15
16
  return requested && VALID_SPEECH_FORMATS.has(requested) ? requested : 'mp3';
16
17
  }
18
+ /**
19
+ * OpenRouter normalizes aspect ratios across the providers it fronts;
20
+ * `providers.ts`'s `MEDIA_ASPECTS` are all natively supported. xAI's Imagine
21
+ * API accepts a wider list (1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 2:1, 1:2,
22
+ * 19.5:9, 9:19.5, 20:9, 9:20, auto), of which `MEDIA_ASPECTS` is a strict
23
+ * subset. Both mappings pass through the same five values and default to 16:9.
24
+ * Written as independent `if` returns (rather than the origin's one
25
+ * `||`-chained condition) to match the established aspect-mapping style
26
+ * (see `providers/imagerouter.ts`'s `imageRouterSizeFor`) — same input ->
27
+ * output mapping for every case, not a behavior change.
28
+ */
29
+ export function standardImageAspectFor({ aspect }, _options = {}) {
30
+ if (aspect === '1:1')
31
+ return '1:1';
32
+ if (aspect === '16:9')
33
+ return '16:9';
34
+ if (aspect === '9:16')
35
+ return '9:16';
36
+ if (aspect === '4:3')
37
+ return '4:3';
38
+ if (aspect === '3:4')
39
+ return '3:4';
40
+ return '16:9';
41
+ }
17
42
  /** Truncates a string for inclusion in an error message, appending an ellipsis when truncated. */
18
43
  export function truncate(s, n) {
19
44
  const v = String(s || '');
@@ -71,7 +96,7 @@ export function detectAzureEndpoint(baseUrl) {
71
96
  }
72
97
  /** Rewrites a pathname to end in `/{endpoint}/generations` or (images only) `/images/edits`, preserving any other path prefix. */
73
98
  export function normalizeOpenAICompatiblePath(pathname, endpoint, mode) {
74
- const strippedPath = pathname.replace(/\/+$/, '');
99
+ const strippedPath = trimCharsEnd({ text: pathname, chars: '/' });
75
100
  const generationsSuffix = `/${endpoint}/generations`;
76
101
  if (endpoint === 'videos') {
77
102
  // Videos have no edits endpoint, so `edits` mode still targets generations.
@@ -163,7 +188,7 @@ export function buildOpenAISpeechUrl(baseUrl, isAzure) {
163
188
  const stripped = baseUrl.replace(/\/$/, '');
164
189
  return `${stripped}/audio/speech`;
165
190
  }
166
- parsed.pathname = parsed.pathname.replace(/\/+$/, '') + '/audio/speech';
191
+ parsed.pathname = trimCharsEnd({ text: parsed.pathname, chars: '/' }) + '/audio/speech';
167
192
  applyDefaultAzureApiVersion(parsed, isAzure);
168
193
  return parsed.toString();
169
194
  }
@@ -112,7 +112,7 @@ export async function startOperation(required, optional = {}) {
112
112
  const deps = { ...required, ...optional };
113
113
  const params = { ...required, ...optional };
114
114
  const now = deps.clock ?? Date.now;
115
- const newId = deps.newId ?? (() => `op_${Math.random().toString(36).slice(2, 10)}_${now()}`);
115
+ const newId = deps.newId ?? (() => `op_${globalThis.crypto.randomUUID().slice(0, 8)}_${now()}`);
116
116
  const startedAt = now();
117
117
  const operationId = newId();
118
118
  // Before any HTTP call — this ordering IS the crash-safety mechanism.
@@ -49,7 +49,8 @@ export function requireMediaHttpClient({ httpClient }) {
49
49
  throw new TypeError('Media outbound requires an injected guarded HttpClientPort');
50
50
  return httpClient;
51
51
  }
52
+ const MEDIA_METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']);
52
53
  function isMediaMethod(method) {
53
- return method === 'GET' || method === 'HEAD' || method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE';
54
+ return MEDIA_METHODS.has(method);
54
55
  }
55
56
  //# sourceMappingURL=outbound.js.map
@@ -1,18 +1,45 @@
1
- import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
- import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
1
  /**
4
- * xAI's Imagine API accepts a wide list of aspect ratios (1:1, 16:9, 9:16,
5
- * 4:3, 3:4, 3:2, 2:3, 2:1, 1:2, 19.5:9, 9:19.5, 20:9, 9:20, auto) —
6
- * `providers.ts`'s `MEDIA_ASPECTS` is a strict subset, so a recognized
7
- * value passes through and anything else defaults to 16:9. Written as
8
- * independent `if` returns (rather than the origin's one `||`-chained
9
- * condition) to match this package's established aspect-mapping style
10
- * (see `imagerouter.ts`'s `imageRouterSizeFor`) — same input -> output
11
- * mapping for every case, not a behavior change.
2
+ * Provider: xAI Grok — image generation via an OpenAI-images-compatible
3
+ * `/images/generations` endpoint (`renderGrokImage`), plus text-to-speech
4
+ * via a dedicated `/tts` endpoint (`renderXAITTS`). Ported near-verbatim
5
+ * from Open Design's `apps/daemon/src/media/index.ts` `renderGrokImage`/
6
+ * `renderXAITTS` — see `archived provenance ledger`.
7
+ *
8
+ * Image response shape (`{ data: [{ b64_json | url }] }`) is identical to
9
+ * OpenAI's images API, so `renderGrokImage` routes through
10
+ * `openai-compatible.ts`'s already-ported JSON-parsing/byte-extraction/
11
+ * URL-building helpers rather than re-implementing them. `/tts` is xAI's
12
+ * own dedicated endpoint (not the OpenAI `/audio/speech` shape) — it
13
+ * returns raw audio bytes directly from a plain JSON POST, with no
14
+ * per-request format negotiation the caller can control, so `renderXAITTS`
15
+ * doesn't route through `openai-compatible.ts` at all (only the generic
16
+ * `truncate`/`withRequestInit` helpers are shared).
17
+ *
18
+ * Dropped from the origin's no-credential error messages (both
19
+ * functions): the OD-specific "sign in with your SuperGrok subscription
20
+ * (in OD or via `hermes auth add xai-oauth`)" OAuth guidance — this
21
+ * package has no OAuth chain or local-CLI-login concept; credentials are
22
+ * always host-injected (see `types.ts`'s `ProviderCredentials`), matching
23
+ * every other ported provider's error-message style (e.g. `openai.ts`'s
24
+ * `OPENAI_IMAGE_NO_CREDENTIAL_MESSAGE`).
25
+ *
26
+ * 2026-07-21: migrated onto the generic vendor-adapter dispatch engine
27
+ * (`vendor-adapter.ts`/`vendor-registry.ts`) — two adapters registered on
28
+ * the same `grok` provider id (`image`/`audio:speech`). External behavior
29
+ * is unchanged (verified against `grok.test.ts`, which asserts URL/body/
30
+ * header/error-message/providerNote shape and passes unmodified) — only
31
+ * the internal implementation moved. The image adapter is not routed
32
+ * through `response-parsers.ts`'s factories (reuses
33
+ * `openai-compatible.ts`'s JSON-parsing helpers directly, same as before —
34
+ * see `imagerouter.ts`'s module doc for the identical reasoning); the TTS
35
+ * adapter's response (raw bytes, no envelope) is the same shape
36
+ * `fishaudio.ts`/`openai.ts`'s speech renderer return, so it now shares
37
+ * `response-parsers.ts`'s `createRawBytesParser`.
12
38
  */
13
- export declare function grokAspectFor({ aspect }: {
14
- aspect: string | undefined;
15
- }): string;
39
+ import { standardImageAspectFor as grokAspectFor } from '../openai-compatible.js';
40
+ import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
41
+ import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
42
+ export { grokAspectFor };
16
43
  export declare function renderGrokImage({ ctx, credentials }: {
17
44
  ctx: RenderContext;
18
45
  credentials: ProviderCredentials;
@@ -36,32 +36,10 @@
36
36
  * `fishaudio.ts`/`openai.ts`'s speech renderer return, so it now shares
37
37
  * `response-parsers.ts`'s `createRawBytesParser`.
38
38
  */
39
- import { buildOpenAIImageUrl, bytesFromOpenAICompatibleData, parseOpenAICompatibleJson, sniffImageExt, withRequestInit } from '../openai-compatible.js';
39
+ import { buildOpenAIImageUrl, bytesFromOpenAICompatibleData, parseOpenAICompatibleJson, sniffImageExt, standardImageAspectFor as grokAspectFor, withRequestInit } from '../openai-compatible.js';
40
40
  import { createRawBytesParser } from '../response-parsers.js';
41
41
  import { dispatchVendorRequest, requireApiKey } from '../vendor-adapter.js';
42
- /**
43
- * xAI's Imagine API accepts a wide list of aspect ratios (1:1, 16:9, 9:16,
44
- * 4:3, 3:4, 3:2, 2:3, 2:1, 1:2, 19.5:9, 9:19.5, 20:9, 9:20, auto) —
45
- * `providers.ts`'s `MEDIA_ASPECTS` is a strict subset, so a recognized
46
- * value passes through and anything else defaults to 16:9. Written as
47
- * independent `if` returns (rather than the origin's one `||`-chained
48
- * condition) to match this package's established aspect-mapping style
49
- * (see `imagerouter.ts`'s `imageRouterSizeFor`) — same input -> output
50
- * mapping for every case, not a behavior change.
51
- */
52
- export function grokAspectFor({ aspect }) {
53
- if (aspect === '1:1')
54
- return '1:1';
55
- if (aspect === '16:9')
56
- return '16:9';
57
- if (aspect === '9:16')
58
- return '9:16';
59
- if (aspect === '4:3')
60
- return '4:3';
61
- if (aspect === '3:4')
62
- return '3:4';
63
- return '16:9';
64
- }
42
+ export { grokAspectFor };
65
43
  const NO_CREDENTIAL_MESSAGE = 'no xAI credential — configure an API key or set XAI_API_KEY.';
66
44
  const grokImageAdapter = {
67
45
  requireCredential: requireApiKey({ message: NO_CREDENTIAL_MESSAGE }),
@@ -32,10 +32,11 @@
32
32
  import { bytesFromOpenAICompatibleData, parseOpenAICompatibleJson } from '../openai-compatible.js';
33
33
  import { imageRouterSizeFor } from './imagerouter.js';
34
34
  import { withUnsignedRequestInit } from '../polling-adapter.js';
35
+ import { trimCharsEnd } from '@jini-ai/core/primitives';
35
36
  const DEFAULT_BASE_URL = 'https://api.imagerouter.io/v1/openai';
36
37
  const TERMINAL_FAILED_STATUSES = new Set(['failed', 'error', 'cancelled', 'canceled']);
37
38
  function trimTrailingSlash(value) {
38
- return value.replace(/\/+$/, '');
39
+ return trimCharsEnd({ text: value, chars: '/' });
39
40
  }
40
41
  /** Reads a vendor-supplied `Retry-After` (seconds) header, ignoring anything non-numeric. */
41
42
  function retryAfterMsFrom(resp) {
@@ -61,7 +62,7 @@ async function completedVideo({ data, ctx, meta }) {
61
62
  kind: 'complete',
62
63
  result: {
63
64
  bytes,
64
- providerNote: `imagerouter/${wireModel} · ${size} · ${seconds === 'auto' ? 'auto' : `${seconds}s`} · ${bytes.length} bytes`,
65
+ providerNote: `imagerouter/${wireModel} · ${size} · ${seconds === 'auto' ? 'auto' : seconds + 's'} · ${bytes.length} bytes`,
65
66
  suggestedExt: '.mp4',
66
67
  },
67
68
  };
@@ -104,7 +104,7 @@ const imageRouterVideoAdapter = {
104
104
  const { wireModel, size, seconds } = request.meta;
105
105
  return {
106
106
  bytes,
107
- providerNote: `imagerouter/${wireModel} · ${size} · ${seconds === 'auto' ? 'auto' : `${seconds}s`} · ${bytes.length} bytes`,
107
+ providerNote: `imagerouter/${wireModel} · ${size} · ${seconds === 'auto' ? 'auto' : seconds + 's'} · ${bytes.length} bytes`,
108
108
  suggestedExt: '.mp4',
109
109
  };
110
110
  },
@@ -1,17 +1,7 @@
1
+ import { standardImageAspectFor as openRouterAspectFor } from '../openai-compatible.js';
1
2
  import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
3
  import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
- /**
4
- * OpenRouter normalizes aspect ratios across the providers it fronts;
5
- * `providers.ts`'s `MEDIA_ASPECTS` are all natively supported, default to
6
- * 16:9 for anything else. Written as independent `if` returns (rather than
7
- * the origin's one `||`-chained condition) to match this package's
8
- * established aspect-mapping style (see `imagerouter.ts`'s
9
- * `imageRouterSizeFor`) — same input -> output mapping for every case, not
10
- * a behavior change.
11
- */
12
- export declare function openRouterAspectFor({ aspect }: {
13
- aspect: string | undefined;
14
- }): string;
4
+ export { openRouterAspectFor };
15
5
  export declare function renderOpenRouterImage({ ctx, credentials }: {
16
6
  ctx: RenderContext;
17
7
  credentials: ProviderCredentials;
@@ -31,35 +31,14 @@
31
31
  * `parseResponse`.
32
32
  */
33
33
  import { assertAndFetchExternalAsset } from '../ssrf-guard.js';
34
- import { sniffImageExt, truncate, withRequestInit } from '../openai-compatible.js';
34
+ import { sniffImageExt, standardImageAspectFor as openRouterAspectFor, truncate, withRequestInit } from '../openai-compatible.js';
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
38
  // uses for the same reason (see `OPENAI_IMAGE_TIMEOUT_MS` there — a single
39
39
  // `AbortSignal.timeout` covers the whole request for both vendors).
40
40
  const OPENROUTER_IMAGE_TIMEOUT_MS = 10 * 60 * 1000;
41
- /**
42
- * OpenRouter normalizes aspect ratios across the providers it fronts;
43
- * `providers.ts`'s `MEDIA_ASPECTS` are all natively supported, default to
44
- * 16:9 for anything else. Written as independent `if` returns (rather than
45
- * the origin's one `||`-chained condition) to match this package's
46
- * established aspect-mapping style (see `imagerouter.ts`'s
47
- * `imageRouterSizeFor`) — same input -> output mapping for every case, not
48
- * a behavior change.
49
- */
50
- export function openRouterAspectFor({ aspect }) {
51
- if (aspect === '1:1')
52
- return '1:1';
53
- if (aspect === '16:9')
54
- return '16:9';
55
- if (aspect === '9:16')
56
- return '9:16';
57
- if (aspect === '4:3')
58
- return '4:3';
59
- if (aspect === '3:4')
60
- return '3:4';
61
- return '16:9';
62
- }
41
+ export { openRouterAspectFor };
63
42
  const NO_CREDENTIAL_MESSAGE = 'no OpenRouter API key — configure it or set OPENROUTER_API_KEY';
64
43
  const openRouterImageAdapter = {
65
44
  requireCredential: requireApiKey({ message: NO_CREDENTIAL_MESSAGE }),
@@ -39,6 +39,7 @@
39
39
  */
40
40
  import { isLoopbackApiHost, isBlockedExternalApiHostname } from '@jini-ai/platform/net';
41
41
  import { promises as dnsPromises } from 'node:dns';
42
+ import { trimCharsEnd } from '@jini-ai/core/primitives';
42
43
  import { FETCH_TIMEOUT_MS } from '@jini-ai/platform/fetch-with-timeout';
43
44
  import { defaultMediaOutboundMessages, fetchMediaOutbound, requireMediaHttpClient } from './outbound.js';
44
45
  const defaultDnsLookup = async ({ hostname }) => {
@@ -55,7 +56,7 @@ function looksLikeIpLiteral(hostname) {
55
56
  function validateBaseUrlSync(baseUrl) {
56
57
  let parsed;
57
58
  try {
58
- parsed = new URL(String(baseUrl).replace(/\/+$/, ''));
59
+ parsed = new URL(trimCharsEnd({ text: String(baseUrl), chars: '/' }));
59
60
  }
60
61
  catch {
61
62
  return { ok: false, error: 'Invalid baseUrl', forbidden: false };
@@ -25,7 +25,7 @@ function modelDenial(policy, model) {
25
25
  return null;
26
26
  return {
27
27
  code: 'MEDIA_MODEL_DENIED',
28
- message: `media model ${normalizedModel ? `"${normalizedModel}"` : '(none specified)'} is not allowed for this run`,
28
+ message: `media model ${normalizedModel ? JSON.stringify(normalizedModel) : '(none specified)'} is not allowed for this run`,
29
29
  };
30
30
  }
31
31
  /**
@@ -7,7 +7,6 @@
7
7
  * it ports as data. See `archived provenance ledger` for exactly what was dropped.
8
8
  */
9
9
  import type { AudioKind, MediaModel, MediaProvider, MediaSurface } from './types.js';
10
- /** One adapter-owned endpoint catalog; protocols and UI presets project this data. */
11
10
  export declare const VENDOR_API_BASE_URLS: {
12
11
  readonly anthropic: "https://api.anthropic.com";
13
12
  readonly openai: "https://api.openai.com/v1";
@@ -1,4 +1,6 @@
1
1
  /** One adapter-owned endpoint catalog; protocols and UI presets project this data. */
2
+ /** The OpenAI-compatible custom image endpoint's provider id. */
3
+ const CUSTOM_IMAGE_PROVIDER_ID = 'custom-image';
2
4
  export const VENDOR_API_BASE_URLS = {
3
5
  anthropic: 'https://api.anthropic.com', openai: 'https://api.openai.com/v1', azure: '',
4
6
  google: 'https://generativelanguage.googleapis.com', openrouter: 'https://openrouter.ai/api/v1',
@@ -12,7 +14,7 @@ export const VENDOR_API_BASE_URLS = {
12
14
  };
13
15
  /** Old UI ids remain accepted at boundaries; canonical ids match the existing dispatch catalog. */
14
16
  export const MEDIA_PROVIDER_ID_ALIASES = {
15
- 'nano-banana': 'nanobanana', 'custom-image-api': 'custom-image', 'fal-ai': 'fal',
17
+ 'nano-banana': 'nanobanana', 'custom-image-api': CUSTOM_IMAGE_PROVIDER_ID, 'fal-ai': 'fal',
16
18
  'leonardo-ai': 'leonardo', 'tavily-search': 'tavily', 'volcengine-ark': 'volcengine', 'xai-grok-imagine': 'grok',
17
19
  };
18
20
  /** Resolve legacy aliases without changing unknown extension IDs. @complexity O(1). */
@@ -38,7 +40,7 @@ export const MEDIA_PROVIDERS = [
38
40
  { id: 'nanobanana', label: 'Nano Banana', hint: 'Google official by default; custom gateway configurable', integrated: true, defaultBaseUrl: VENDOR_API_BASE_URLS.google, supportsCustomModel: true },
39
41
  { id: 'imagerouter', label: 'ImageRouter', hint: 'OpenAI-compatible image + video routing', integrated: true, defaultBaseUrl: VENDOR_API_BASE_URLS.imagerouter, docsUrl: 'https://docs.imagerouter.io/api-reference/image-generation/', supportsCustomModel: true, customModelPlaceholder: 'openai/gpt-image-2 or xAI/grok-imagine-video' },
40
42
  { id: 'openrouter', label: 'OpenRouter', hint: 'Unified gateway for image + video models', integrated: true, credentialsRequired: true, settingsVisible: true, defaultBaseUrl: VENDOR_API_BASE_URLS.openrouter, docsUrl: 'https://openrouter.ai/settings/keys' },
41
- { id: 'custom-image', label: 'Custom Media API', hint: 'OpenAI-compatible images/generations + images/edits (local or cloud)', integrated: true, docsUrl: 'https://platform.openai.com/docs/api-reference/images', supportsCustomModel: true, customModelPlaceholder: 'my-image-model' },
43
+ { id: CUSTOM_IMAGE_PROVIDER_ID, label: 'Custom Media API', hint: 'OpenAI-compatible images/generations + images/edits (local or cloud)', integrated: true, docsUrl: 'https://platform.openai.com/docs/api-reference/images', supportsCustomModel: true, customModelPlaceholder: 'my-image-model' },
42
44
  { id: 'comfyui', label: 'ComfyUI', hint: 'Local JSON workflow server (planned adapter)', integrated: false, defaultBaseUrl: VENDOR_API_BASE_URLS.comfyui, docsUrl: 'https://docs.comfy.org/development/core-concepts/workflow' },
43
45
  { id: 'bfl', label: 'Black Forest Labs', hint: 'FLUX 1.1 Pro / FLUX Pro / Dev', integrated: false, defaultBaseUrl: VENDOR_API_BASE_URLS.bfl },
44
46
  { id: 'fal', label: 'Fal.ai', hint: 'FLUX / Sora / Veo / Wan / Ideogram / Recraft and any fal-ai/* model', integrated: false, defaultBaseUrl: VENDOR_API_BASE_URLS.fal, supportsCustomModel: true },
@@ -90,7 +92,7 @@ export const IMAGE_MODELS = [
90
92
  { id: 'openrouter/google/gemini-2.5-flash-image', label: 'gemini-flash-image (OR)', hint: 'OpenRouter · Gemini', provider: 'openrouter', caps: ['t2i'] },
91
93
  { id: 'openrouter/black-forest-labs/flux-1.1-pro', label: 'flux-1.1-pro (OR)', hint: 'OpenRouter · BFL', provider: 'openrouter', caps: ['t2i'] },
92
94
  { id: 'openrouter/recraft/recraft-v3', label: 'recraft-v3 (OR)', hint: 'OpenRouter · Recraft', provider: 'openrouter', caps: ['t2i'] },
93
- { id: 'custom-image', label: 'custom-image', hint: 'Custom · OpenAI-compatible endpoint', provider: 'custom-image', caps: ['t2i', 'i2i'] },
95
+ { id: CUSTOM_IMAGE_PROVIDER_ID, label: CUSTOM_IMAGE_PROVIDER_ID, hint: 'Custom · OpenAI-compatible endpoint', provider: CUSTOM_IMAGE_PROVIDER_ID, caps: ['t2i', 'i2i'] },
94
96
  { id: 'flux-1.1-pro', label: 'flux-1.1-pro', hint: 'BFL · flagship', provider: 'bfl', caps: ['t2i', 'i2i'] },
95
97
  { id: 'flux-pro', label: 'flux-pro', hint: 'BFL', provider: 'bfl', caps: ['t2i'] },
96
98
  { id: 'flux-dev', label: 'flux-dev', hint: 'BFL · open weights', provider: 'bfl', caps: ['t2i'] },
@@ -215,7 +217,7 @@ export const PROVIDER_CREDENTIAL_ENV_VARS = {
215
217
  nanobanana: ['GOOGLE_API_KEY', 'GEMINI_API_KEY'],
216
218
  imagerouter: ['IMAGEROUTER_API_KEY'],
217
219
  openrouter: ['OPENROUTER_API_KEY'],
218
- 'custom-image': ['CUSTOM_IMAGE_API_KEY'],
220
+ [CUSTOM_IMAGE_PROVIDER_ID]: ['CUSTOM_IMAGE_API_KEY'],
219
221
  bfl: ['BFL_API_KEY'],
220
222
  fal: ['FAL_KEY'],
221
223
  replicate: ['REPLICATE_API_TOKEN'],
@@ -128,13 +128,18 @@ export async function createSqliteMediaTaskStore(required, options = {}) {
128
128
  for (const row of selectAllStmt.all()) {
129
129
  const task = rowToTask(row);
130
130
  const action = reconcileAction(task, now, cutoff);
131
- if (action.kind === 'interrupt') {
132
- writeRow(action.next, false);
133
- interrupted += 1;
134
- }
135
- else if (action.kind === 'delete') {
136
- deleteStmt.run(task.id);
137
- deleted += 1;
131
+ switch (action.kind) {
132
+ case 'interrupt':
133
+ writeRow(action.next, false);
134
+ interrupted += 1;
135
+ break;
136
+ case 'delete':
137
+ deleteStmt.run(task.id);
138
+ deleted += 1;
139
+ break;
140
+ default:
141
+ // 'keep': the task stays as it is.
142
+ break;
138
143
  }
139
144
  }
140
145
  return { interrupted, deleted };
@@ -25,12 +25,9 @@ function isWithinRoot(root, candidate) {
25
25
  return relativePath === '' || (relativePath.length > 0 && !relativePath.startsWith('..') && !path.isAbsolute(relativePath));
26
26
  }
27
27
  function assertSafeStagingDirName(stagingDirName) {
28
- if (stagingDirName.length === 0 ||
28
+ if (['', '.', '..'].includes(stagingDirName) ||
29
29
  path.isAbsolute(stagingDirName) ||
30
- stagingDirName === '.' ||
31
- stagingDirName === '..' ||
32
- stagingDirName.includes('/') ||
33
- stagingDirName.includes('\\')) {
30
+ /[/\\]/.test(stagingDirName)) {
34
31
  throw new Error(`attachment staging: stagingDirName must be a single safe path component, got ${JSON.stringify(stagingDirName)}`);
35
32
  }
36
33
  }
@@ -66,13 +66,18 @@ export function createInMemoryMediaTaskStore() {
66
66
  let deleted = 0;
67
67
  for (const task of [...tasks.values()]) {
68
68
  const action = reconcileAction(task, now, cutoff);
69
- if (action.kind === 'interrupt') {
70
- tasks.set(task.id, action.next);
71
- interrupted += 1;
72
- }
73
- else if (action.kind === 'delete') {
74
- tasks.delete(task.id);
75
- deleted += 1;
69
+ switch (action.kind) {
70
+ case 'interrupt':
71
+ tasks.set(task.id, action.next);
72
+ interrupted += 1;
73
+ break;
74
+ case 'delete':
75
+ tasks.delete(task.id);
76
+ deleted += 1;
77
+ break;
78
+ default:
79
+ // 'keep': the task stays as it is.
80
+ break;
76
81
  }
77
82
  }
78
83
  return { interrupted, deleted };
@@ -6,21 +6,23 @@ import { canonicalMediaProviderId, findProvider, VENDOR_API_BASE_URLS } from './
6
6
  * models. Pass this explicitly as `catalog` to `MediaProvidersTab`; Zana or any
7
7
  * other host is expected to do so once it has its own provider roster.
8
8
  */
9
+ /** Default model of every Nano Banana-compatible preset below. */
10
+ const NANO_BANANA_MODEL = 'gemini-3.1-flash-image-preview';
9
11
  const starterCatalog = [
10
12
  {
11
13
  id: 'nano-banana',
12
14
  label: 'Nano Banana',
13
- models: ['gemini-3.1-flash-image-preview'],
15
+ models: [NANO_BANANA_MODEL],
14
16
  },
15
17
  {
16
18
  id: 'aihubmix',
17
19
  label: 'AIHubMix',
18
- models: ['gemini-3.1-flash-image-preview'],
20
+ models: [NANO_BANANA_MODEL],
19
21
  },
20
22
  {
21
23
  id: 'custom-image-api',
22
24
  label: 'Custom Media API',
23
- models: ['gemini-3.1-flash-image-preview'],
25
+ models: [NANO_BANANA_MODEL],
24
26
  },
25
27
  {
26
28
  id: 'elevenlabs',
@@ -29,7 +31,7 @@ const starterCatalog = [
29
31
  {
30
32
  id: 'fal-ai',
31
33
  label: 'Fal.ai',
32
- models: ['gemini-3.1-flash-image-preview'],
34
+ models: [NANO_BANANA_MODEL],
33
35
  },
34
36
  {
35
37
  id: 'fishaudio',
@@ -38,7 +40,7 @@ const starterCatalog = [
38
40
  {
39
41
  id: 'imagerouter',
40
42
  label: 'ImageRouter',
41
- models: ['gemini-3.1-flash-image-preview'],
43
+ models: [NANO_BANANA_MODEL],
42
44
  },
43
45
  {
44
46
  id: 'leonardo-ai',
@@ -67,7 +67,8 @@ async function resolveCredential({ deps, workspaceId, definition }, _options = {
67
67
  requireCondition({ valid: credential.revision === definition.credential.revision, code: "credential_changed" });
68
68
  requireCondition({ valid: new URL(credential.baseUrl).origin === definition.credential.origin, code: "credential_changed" });
69
69
  // Legacy credentials allow additional hosts; visitor release approval covers only the base origin.
70
- requireCondition({ valid: !/[\r\n\u0000]/u.test(credential.connection.token), code: "credential_changed" });
70
+ const token = credential.connection.token;
71
+ requireCondition({ valid: !/[\r\n]/.test(token) && !token.includes("\0"), code: "credential_changed" });
71
72
  return { ...credential, additionalHosts: [] };
72
73
  }
73
74
  function boundedHttpClient({ deps, signal, onResponse }, _options = {}) {
@@ -43,6 +43,7 @@ function checkValue({ value, field }, _options = {}) {
43
43
  function checkPublicUrl({ value, origin }, _options = {}) {
44
44
  const url = new URL(value);
45
45
  requireCondition({ valid: url.protocol === "https:" && url.origin === origin && !url.username && !url.password, code: "invalid_response" });
46
- requireCondition({ valid: !/[\s\u0000-\u001f\u007f]/u.test(value), code: "invalid_response" });
46
+ // \s already covers \u0009-\u000d, so the control ranges skip them.
47
+ requireCondition({ valid: !/[\s\u0000-\u0008\u000e-\u001f\u007f]/u.test(value), code: "invalid_response" });
47
48
  }
48
49
  //# sourceMappingURL=projection.js.map
@@ -44,7 +44,8 @@ export function httpsUrl({ value }, _options = {}) {
44
44
  // No template syntax or parser normalization of control characters in persisted targets.
45
45
  requireCondition({ valid: !/[\s{}<>`\\]/u.test(decodeURIComponent(value)) });
46
46
  const url = new URL(value);
47
- requireCondition({ valid: url.protocol === "https:" && url.port === "" && !url.username && !url.password && !url.hash });
47
+ const bareOrigin = !url.username && !url.password && !url.hash;
48
+ requireCondition({ valid: url.protocol === "https:" && url.port === "" && bareOrigin });
48
49
  return url;
49
50
  }
50
51
  catch {
@@ -82,7 +82,10 @@ export async function enqueueDelivery(required, _optional = {}) {
82
82
  function publicWebhookEnvelope({ envelope }, _options = {}) {
83
83
  if (envelope.topic !== 'form.submission.received')
84
84
  return envelope;
85
- const { analyticsProvenance: _proof, deliveryMode: _mode, ...data } = envelope.data;
85
+ // Internal provenance and delivery-mode fields never leave the host.
86
+ const data = { ...envelope.data };
87
+ delete data.analyticsProvenance;
88
+ delete data.deliveryMode;
86
89
  return { ...envelope, data };
87
90
  }
88
91
  /**
@@ -50,10 +50,11 @@ function applyHeaderPart(acc, part, vocabulary) {
50
50
  if (!Number.isFinite(parsedTimestamp))
51
51
  return false;
52
52
  acc.timestamp = parsedTimestamp;
53
+ return true;
53
54
  }
54
- else if (part.key === vocabulary.signatureField) {
55
+ // Unknown keys are ignored.
56
+ if (part.key === vocabulary.signatureField)
55
57
  acc.signatures.push(part.value);
56
- }
57
58
  return true;
58
59
  }
59
60
  function parseSignatureHeader(header, vocabulary) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/integrations",
3
- "version": "0.6.15-rc.1",
3
+ "version": "0.6.15",
4
4
  "description": "Third-party vendor integrations and outbound services, each independently importable: media generation, credentialed HTTP and webhooks.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -103,13 +103,13 @@
103
103
  "registry": "https://registry.npmjs.org"
104
104
  },
105
105
  "dependencies": {
106
- "@jini-ai/core": "^0.6.15-rc.1"
106
+ "@jini-ai/core": "^0.6.15"
107
107
  },
108
108
  "peerDependencies": {
109
- "@jini-ai/db": "^0.6.15-rc.1",
109
+ "@jini-ai/db": "^0.6.10",
110
110
  "better-sqlite3": "^13.0.0",
111
- "@jini-ai/platform": "^0.6.15-rc.1",
112
- "@jini-ai/oauth": "^0.6.15-rc.1",
111
+ "@jini-ai/platform": "^0.6.10",
112
+ "@jini-ai/oauth": "^0.6.10",
113
113
  "@cfworker/json-schema": "^4.1.1"
114
114
  },
115
115
  "peerDependenciesMeta": {
@@ -134,11 +134,11 @@
134
134
  "better-sqlite3": "^13.0.0",
135
135
  "@vitest/coverage-v8": "^2.1.9",
136
136
  "@cfworker/json-schema": "^4.1.1",
137
- "@jini-ai/core": "0.6.15-rc.1",
138
- "@jini-ai/platform": "0.6.15-rc.1",
139
- "@jini-ai/oauth": "0.6.15-rc.1",
140
- "@jini-ai/agent-plugins": "0.6.15-rc.1",
141
- "@jini-ai/db": "^0.6.15-rc.1"
137
+ "@jini-ai/db": "^0.6.15",
138
+ "@jini-ai/core": "0.6.15",
139
+ "@jini-ai/oauth": "0.6.15",
140
+ "@jini-ai/agent-plugins": "0.6.15",
141
+ "@jini-ai/platform": "0.6.15"
142
142
  },
143
143
  "scripts": {
144
144
  "build": "tsc -p tsconfig.json",