@jini-ai/integrations 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/api-connections/access-token.d.ts +9 -0
  3. package/dist/api-connections/access-token.js +92 -0
  4. package/dist/api-connections/account-actions.d.ts +40 -0
  5. package/dist/api-connections/account-actions.js +110 -0
  6. package/dist/api-connections/attempt-state.d.ts +28 -0
  7. package/dist/api-connections/attempt-state.js +73 -0
  8. package/dist/api-connections/authorization.d.ts +45 -0
  9. package/dist/api-connections/authorization.js +120 -0
  10. package/dist/api-connections/deps.d.ts +41 -0
  11. package/dist/api-connections/deps.js +13 -0
  12. package/dist/api-connections/descriptor.d.ts +6 -0
  13. package/dist/api-connections/descriptor.js +111 -0
  14. package/dist/api-connections/errors.d.ts +23 -0
  15. package/dist/api-connections/errors.js +24 -0
  16. package/dist/api-connections/finish-authorization.d.ts +24 -0
  17. package/dist/api-connections/finish-authorization.js +117 -0
  18. package/dist/api-connections/index.d.ts +18 -0
  19. package/dist/api-connections/index.js +10 -0
  20. package/dist/api-connections/install-credential.d.ts +19 -0
  21. package/dist/api-connections/install-credential.js +12 -0
  22. package/dist/api-connections/keys.d.ts +27 -0
  23. package/dist/api-connections/keys.js +22 -0
  24. package/dist/api-connections/ports.d.ts +73 -0
  25. package/dist/api-connections/ports.js +2 -0
  26. package/dist/api-connections/records.d.ts +27 -0
  27. package/dist/api-connections/records.js +52 -0
  28. package/dist/api-connections/request-checks.d.ts +18 -0
  29. package/dist/api-connections/request-checks.js +67 -0
  30. package/dist/api-connections/service.d.ts +25 -0
  31. package/dist/api-connections/service.js +26 -0
  32. package/dist/api-connections/status.d.ts +28 -0
  33. package/dist/api-connections/status.js +36 -0
  34. package/dist/api-connections/token-store/errors.d.ts +20 -0
  35. package/dist/api-connections/token-store/errors.js +38 -0
  36. package/dist/api-connections/token-store/index.d.ts +6 -0
  37. package/dist/api-connections/token-store/index.js +6 -0
  38. package/dist/api-connections/token-store/record.d.ts +69 -0
  39. package/dist/api-connections/token-store/record.js +97 -0
  40. package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
  41. package/dist/api-connections/token-store/vault-token-store.js +215 -0
  42. package/dist/api-connections/types.d.ts +101 -0
  43. package/dist/api-connections/types.js +9 -0
  44. package/dist/credentialed-http/auth-schemes.js +8 -4
  45. package/dist/credentialed-http/credentialed-request.js +47 -77
  46. package/dist/credentialed-http/response-redaction.d.ts +5 -0
  47. package/dist/credentialed-http/response-redaction.js +62 -0
  48. package/dist/media-providers/catalog.d.ts +3 -1
  49. package/dist/media-providers/catalog.js +3 -1
  50. package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
  51. package/dist/media-providers/dispatch/async-operation-store.js +75 -37
  52. package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
  53. package/dist/media-providers/dispatch/context.js +10 -2
  54. package/dist/media-providers/dispatch/engine.d.ts +6 -3
  55. package/dist/media-providers/dispatch/engine.js +99 -109
  56. package/dist/media-providers/dispatch/index.d.ts +4 -2
  57. package/dist/media-providers/dispatch/index.js +3 -1
  58. package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
  59. package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
  60. package/dist/media-providers/dispatch/node.d.ts +13 -0
  61. package/dist/media-providers/dispatch/node.js +24 -0
  62. package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
  63. package/dist/media-providers/dispatch/openai-compatible.js +90 -87
  64. package/dist/media-providers/dispatch/operation-runtime.js +116 -89
  65. package/dist/media-providers/dispatch/outbound.d.ts +8 -4
  66. package/dist/media-providers/dispatch/outbound.js +27 -26
  67. package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
  68. package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
  69. package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
  70. package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
  71. package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
  72. package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
  73. package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
  74. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
  75. package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
  76. package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
  77. package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
  78. package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
  79. package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
  80. package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
  81. package/dist/media-providers/dispatch/providers/openai.js +51 -47
  82. package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
  83. package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
  84. package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
  85. package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
  86. package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
  87. package/dist/media-providers/dispatch/response-parsers.js +37 -21
  88. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +9 -29
  89. package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
  90. package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
  91. package/dist/media-providers/dispatch/types.d.ts +76 -2
  92. package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
  93. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  94. package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
  95. package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
  96. package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
  97. package/dist/media-providers/dispatch/vendor-registry.js +14 -42
  98. package/dist/media-providers/policy.js +25 -17
  99. package/dist/media-providers/providers.d.ts +5 -0
  100. package/dist/media-providers/providers.js +2 -0
  101. package/dist/media-providers/sqlite-task-store.js +12 -80
  102. package/dist/media-providers/staging.js +77 -58
  103. package/dist/media-providers/task-lifecycle.d.ts +33 -0
  104. package/dist/media-providers/task-lifecycle.js +124 -0
  105. package/dist/media-providers/task-store.js +8 -86
  106. package/dist/media-providers/ui-defaults.d.ts +10 -0
  107. package/dist/media-providers/ui-defaults.js +167 -0
  108. package/dist/media-providers/video-request.js +112 -90
  109. package/dist/webhooks/delivery.d.ts +14 -0
  110. package/dist/webhooks/delivery.js +41 -10
  111. package/dist/webhooks/index.d.ts +1 -0
  112. package/dist/webhooks/index.js +1 -0
  113. package/dist/webhooks/ports.d.ts +23 -0
  114. package/dist/webhooks/worker.d.ts +83 -0
  115. package/dist/webhooks/worker.js +105 -0
  116. package/package.json +31 -8
@@ -14,29 +14,7 @@
14
14
  * `@jini-ai/sqlite-chat` addition) implements the same interface — see
15
15
  * `archived provenance ledger`.
16
16
  */
17
- const VALID_STATUSES = new Set([
18
- 'queued',
19
- 'running',
20
- 'done',
21
- 'failed',
22
- 'interrupted',
23
- ]);
24
- const TERMINAL_STATUSES = new Set(['done', 'failed', 'interrupted']);
25
- // CR-013: `assertValidStatus` alone only proves enum membership, not that a
26
- // transition is legal — it allowed e.g. `done` -> `running`. This is the
27
- // actual lifecycle graph the store's own docs claim
28
- // (queued -> running -> done|failed|interrupted); same-state is included so
29
- // a caller can `update()` progress/file without also having to re-derive the
30
- // current status, but nothing can leave a terminal state once reached.
31
- const ALLOWED_TRANSITIONS = {
32
- // `queued` may go straight to a terminal state too (a caller isn't
33
- // required to make a separate "now running" update before finishing).
34
- queued: new Set(['queued', 'running', 'done', 'failed', 'interrupted']),
35
- running: new Set(['running', 'done', 'failed', 'interrupted']),
36
- done: new Set(['done']),
37
- failed: new Set(['failed']),
38
- interrupted: new Set(['interrupted']),
39
- };
17
+ import { applyTaskPatch, assertValidTerminalTtl, buildNewTask, reconcileAction, TERMINAL_STATUSES } from './task-lifecycle.js';
40
18
  function cloneTask(task) {
41
19
  return {
42
20
  ...task,
@@ -45,10 +23,6 @@ function cloneTask(task) {
45
23
  error: task.error == null ? null : { ...task.error },
46
24
  };
47
25
  }
48
- const INTERRUPTED_ERROR = {
49
- message: 'media task interrupted by daemon restart',
50
- code: 'DAEMON_RESTART',
51
- };
52
26
  /** Creates the in-memory reference `MediaTaskStore`. No persistence — state is lost on process exit. */
53
27
  export function createInMemoryMediaTaskStore() {
54
28
  const tasks = new Map();
@@ -57,24 +31,7 @@ export function createInMemoryMediaTaskStore() {
57
31
  if (tasks.has(input.id)) {
58
32
  throw new Error(`media task "${input.id}" already exists`);
59
33
  }
60
- const status = input.status ?? 'queued';
61
- assertValidStatus(status);
62
- const now = Date.now();
63
- const startedAt = input.startedAt ?? now;
64
- const task = {
65
- id: input.id,
66
- ownerRef: input.ownerRef,
67
- status,
68
- progress: input.progress ? [...input.progress] : [],
69
- file: input.file == null ? null : structuredClone(input.file),
70
- error: input.error == null ? null : { ...input.error },
71
- startedAt,
72
- endedAt: null,
73
- createdAt: now,
74
- updatedAt: now,
75
- ...(input.surface !== undefined ? { surface: input.surface } : {}),
76
- ...(input.model !== undefined ? { model: input.model } : {}),
77
- };
34
+ const task = buildNewTask(input, Date.now());
78
35
  tasks.set(task.id, task);
79
36
  return cloneTask(task);
80
37
  },
@@ -86,29 +43,7 @@ export function createInMemoryMediaTaskStore() {
86
43
  const existing = tasks.get(id);
87
44
  if (!existing)
88
45
  return null;
89
- const status = patch.status ?? existing.status;
90
- assertValidStatus(status);
91
- // CR-013: enum membership alone doesn't prove the transition is legal
92
- // (e.g. `done` -> `running`) — check the actual lifecycle graph too.
93
- if (!ALLOWED_TRANSITIONS[existing.status].has(status)) {
94
- throw new RangeError(`Invalid media task transition: "${existing.status}" -> "${status}"`);
95
- }
96
- const surface = 'surface' in patch ? (patch.surface ?? undefined) : existing.surface;
97
- const model = 'model' in patch ? (patch.model ?? undefined) : existing.model;
98
- const next = {
99
- id: existing.id,
100
- ownerRef: existing.ownerRef,
101
- status,
102
- progress: patch.progress ? [...patch.progress] : existing.progress,
103
- file: 'file' in patch ? (patch.file == null ? null : structuredClone(patch.file)) : existing.file,
104
- error: 'error' in patch ? (patch.error == null ? null : { ...patch.error }) : existing.error,
105
- startedAt: existing.startedAt,
106
- endedAt: 'endedAt' in patch ? (patch.endedAt ?? null) : existing.endedAt,
107
- createdAt: existing.createdAt,
108
- updatedAt: Date.now(),
109
- ...(surface !== undefined ? { surface } : {}),
110
- ...(model !== undefined ? { model } : {}),
111
- };
46
+ const next = applyTaskPatch(existing, patch, Date.now());
112
47
  tasks.set(id, next);
113
48
  return cloneTask(next);
114
49
  },
@@ -124,26 +59,18 @@ export function createInMemoryMediaTaskStore() {
124
59
  tasks.delete(id);
125
60
  },
126
61
  async reconcileOnBoot(options) {
127
- if (!Number.isFinite(options.terminalTtlMs) || options.terminalTtlMs < 0) {
128
- throw new RangeError(`Invalid terminalTtlMs: ${options.terminalTtlMs} must be a non-negative finite number`);
129
- }
62
+ assertValidTerminalTtl(options.terminalTtlMs);
130
63
  const now = options.now ?? Date.now();
131
64
  const cutoff = now - options.terminalTtlMs;
132
65
  let interrupted = 0;
133
66
  let deleted = 0;
134
67
  for (const task of [...tasks.values()]) {
135
- if (task.status === 'queued' || task.status === 'running') {
136
- tasks.set(task.id, {
137
- ...task,
138
- status: 'interrupted',
139
- error: INTERRUPTED_ERROR,
140
- endedAt: task.endedAt ?? now,
141
- updatedAt: now,
142
- });
68
+ const action = reconcileAction(task, now, cutoff);
69
+ if (action.kind === 'interrupt') {
70
+ tasks.set(task.id, action.next);
143
71
  interrupted += 1;
144
- continue;
145
72
  }
146
- if (TERMINAL_STATUSES.has(task.status) && (task.endedAt ?? task.updatedAt) < cutoff) {
73
+ else if (action.kind === 'delete') {
147
74
  tasks.delete(task.id);
148
75
  deleted += 1;
149
76
  }
@@ -152,9 +79,4 @@ export function createInMemoryMediaTaskStore() {
152
79
  },
153
80
  };
154
81
  }
155
- function assertValidStatus(status) {
156
- if (!VALID_STATUSES.has(status)) {
157
- throw new RangeError(`Invalid media task status: "${status}"`);
158
- }
159
- }
160
82
  //# sourceMappingURL=task-store.js.map
@@ -0,0 +1,10 @@
1
+ import type { MediaProviderOption, ProviderPreset } from '@jini-ai/core';
2
+ export declare const DEFAULT_MEDIA_PROVIDER_CATALOG: readonly MediaProviderOption[];
3
+ /**
4
+ * A small, vendor-shaped starting catalog. Deliberately NOT the origin's full
5
+ * ~30-entry list: that list is hand-curated product content that goes stale,
6
+ * and this package's rule for tables like this (see `LanguageTab`) is that the
7
+ * host owns them. Pass these explicitly as `presets` to the UI.
8
+ */
9
+ export declare const DEFAULT_PROVIDER_PRESETS: readonly ProviderPreset<'anthropic' | 'openai' | 'azure' | 'google'>[];
10
+ //# sourceMappingURL=ui-defaults.d.ts.map
@@ -0,0 +1,167 @@
1
+ import { canonicalMediaProviderId, findProvider, VENDOR_API_BASE_URLS } from './providers.js';
2
+ /**
3
+ * An explicit starter catalog for host composition. Sourced by driving the origin's
4
+ * Settings → Media providers
5
+ * panel directly (Playwright) and transcribing its real provider list, base URLs, and default
6
+ * models. Pass this explicitly as `catalog` to `MediaProvidersTab`; Zana or any
7
+ * other host is expected to do so once it has its own provider roster.
8
+ */
9
+ const starterCatalog = [
10
+ {
11
+ id: 'nano-banana',
12
+ label: 'Nano Banana',
13
+ models: ['gemini-3.1-flash-image-preview'],
14
+ },
15
+ {
16
+ id: 'aihubmix',
17
+ label: 'AIHubMix',
18
+ models: ['gemini-3.1-flash-image-preview'],
19
+ },
20
+ {
21
+ id: 'custom-image-api',
22
+ label: 'Custom Media API',
23
+ models: ['gemini-3.1-flash-image-preview'],
24
+ },
25
+ {
26
+ id: 'elevenlabs',
27
+ label: 'ElevenLabs',
28
+ },
29
+ {
30
+ id: 'fal-ai',
31
+ label: 'Fal.ai',
32
+ models: ['gemini-3.1-flash-image-preview'],
33
+ },
34
+ {
35
+ id: 'fishaudio',
36
+ label: 'FishAudio',
37
+ },
38
+ {
39
+ id: 'imagerouter',
40
+ label: 'ImageRouter',
41
+ models: ['gemini-3.1-flash-image-preview'],
42
+ },
43
+ {
44
+ id: 'leonardo-ai',
45
+ label: 'Leonardo.ai',
46
+ },
47
+ {
48
+ id: 'minimax',
49
+ label: 'MiniMax',
50
+ },
51
+ {
52
+ id: 'openai',
53
+ label: 'OpenAI',
54
+ models: ['gpt-image-2', 'dall-e-3'],
55
+ },
56
+ {
57
+ id: 'openrouter',
58
+ label: 'OpenRouter',
59
+ },
60
+ {
61
+ id: 'senseaudio',
62
+ label: 'SenseAudio',
63
+ },
64
+ {
65
+ id: 'tavily-search',
66
+ label: 'Tavily Search',
67
+ },
68
+ {
69
+ id: 'volcengine-ark',
70
+ label: 'Volcengine Ark (Doubao)',
71
+ },
72
+ {
73
+ id: 'xai-grok-imagine',
74
+ label: 'xAI Grok Imagine',
75
+ },
76
+ ];
77
+ export const DEFAULT_MEDIA_PROVIDER_CATALOG = starterCatalog.map((entry) => {
78
+ const id = canonicalMediaProviderId({ id: entry.id });
79
+ const provider = findProvider({ id });
80
+ return { ...entry, id, label: provider.label, ...(provider.defaultBaseUrl ? { defaultBaseUrl: provider.defaultBaseUrl } : {}) };
81
+ });
82
+ /**
83
+ * A small, vendor-shaped starting catalog. Deliberately NOT the origin's full
84
+ * ~30-entry list: that list is hand-curated product content that goes stale,
85
+ * and this package's rule for tables like this (see `LanguageTab`) is that the
86
+ * host owns them. Pass these explicitly as `presets` to the UI.
87
+ */
88
+ export const DEFAULT_PROVIDER_PRESETS = [
89
+ {
90
+ id: 'anthropic',
91
+ title: 'Anthropic',
92
+ protocol: 'anthropic',
93
+ baseUrl: VENDOR_API_BASE_URLS.anthropic,
94
+ preferredModels: ['claude-sonnet-5', 'claude-opus-5', 'claude-haiku-4-5'],
95
+ kind: 'protocol',
96
+ apiKeyPrefix: 'sk-ant-',
97
+ },
98
+ {
99
+ id: 'openai',
100
+ title: 'OpenAI',
101
+ protocol: 'openai',
102
+ baseUrl: VENDOR_API_BASE_URLS.openai,
103
+ // `gpt-4o`/`gpt-4o-mini`/`o3`/`o4-mini` are stale: OpenAI's GPT-5.6 family
104
+ // (released 2026-07-09, per the API changelog) replaced the old
105
+ // flagship/mini/nano naming with named tiers — sol/terra/luna. `sol` is
106
+ // the one the changelog and pricing docs call out as "recommended for
107
+ // production API usage", so it leads (see `preferredModels[0]` default
108
+ // in `rules.ts`) rather than the newer, pricier `gpt-6-astra` flagship
109
+ // (released 2026-09-03) — picking that as the silent default would jump
110
+ // an existing user's cost without them choosing it.
111
+ preferredModels: ['gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'],
112
+ kind: 'protocol',
113
+ apiKeyPrefix: 'sk-',
114
+ },
115
+ {
116
+ id: 'azure-openai',
117
+ title: 'Azure OpenAI',
118
+ protocol: 'azure',
119
+ baseUrl: VENDOR_API_BASE_URLS.azure,
120
+ preferredModels: [],
121
+ kind: 'protocol',
122
+ // No `apiKeyPrefix` deliberately: an Azure OpenAI key is a bare hex string with no vendor
123
+ // prefix, so any value here would be a guess — and a wrong prefix claim does not merely stay
124
+ // silent, it lets some OTHER vendor's valid key be announced as Azure's. Its 32 hex characters
125
+ // are also the shortest real key shape in this catalog, which is what sets
126
+ // `MIN_PLAUSIBLE_API_KEY_LENGTH`.
127
+ },
128
+ {
129
+ id: 'google-gemini',
130
+ title: 'Google Gemini',
131
+ protocol: 'google',
132
+ baseUrl: VENDOR_API_BASE_URLS.google,
133
+ // Ordered newest-first: `rules.ts`'s `saved?.model ?? preset.preferredModels[0]` makes entry [0]
134
+ // the default for anyone who has never picked a model, so a stale head silently pins new users
135
+ // to an old generation. Reported live: the field defaulted to `gemini-2.5-flash` while the
136
+ // operator was actually running `gemini-3.6-flash`. This list is only a FALLBACK — the form
137
+ // prefers live `listModels` discovery and drops back here when that call fails.
138
+ preferredModels: ['gemini-3.6-flash', 'gemini-2.5-flash', 'gemini-2.5-pro'],
139
+ kind: 'protocol',
140
+ // `AIza` + 35 characters is the classic Google key shape, and it is recorded here so a key of
141
+ // this shape is recognised as GOOGLE'S when it turns up in some other provider's field.
142
+ // Emphatically not a test that a Google key must look like this: an operator pasted a real,
143
+ // working Gemini key in a newer shape and the old allowlist told them it was not a Google key.
144
+ apiKeyPrefix: 'AIza',
145
+ },
146
+ {
147
+ id: 'openrouter',
148
+ title: 'OpenRouter',
149
+ protocol: 'openai',
150
+ baseUrl: VENDOR_API_BASE_URLS.openrouter,
151
+ preferredModels: ['anthropic/claude-sonnet-5', 'google/gemini-2.5-pro', 'openai/gpt-5.6-sol'],
152
+ kind: 'gateway',
153
+ // Longer than OpenAI's `sk-`, and deliberately so: `apiKeyFormatWarning` resolves a key to the
154
+ // MOST specific prefix that claims it, so `sk-or-v1-…` is attributed here rather than to OpenAI.
155
+ apiKeyPrefix: 'sk-or-',
156
+ },
157
+ {
158
+ id: 'ollama',
159
+ title: 'Ollama',
160
+ protocol: 'openai',
161
+ baseUrl: VENDOR_API_BASE_URLS.ollama,
162
+ preferredModels: [],
163
+ kind: 'gateway',
164
+ requiresApiKey: false,
165
+ },
166
+ ];
167
+ //# sourceMappingURL=ui-defaults.js.map
@@ -95,11 +95,13 @@ function mergeExtraBody(body, cap, passthrough) {
95
95
  body[def.name] = def.default;
96
96
  }
97
97
  if (passthrough && cap.allowedPassthroughParameters?.length) {
98
- const allow = new Set(cap.allowedPassthroughParameters);
99
- for (const [k, v] of Object.entries(passthrough)) {
100
- if (allow.has(k) && v !== undefined)
101
- body[k] = v;
102
- }
98
+ applyAllowedPassthrough(body, new Set(cap.allowedPassthroughParameters), passthrough);
99
+ }
100
+ }
101
+ function applyAllowedPassthrough(body, allow, passthrough) {
102
+ for (const [k, v] of Object.entries(passthrough)) {
103
+ if (allow.has(k) && v !== undefined)
104
+ body[k] = v;
103
105
  }
104
106
  }
105
107
  /** Builds the seedance multimodal content array (text + reference images). */
@@ -115,105 +117,125 @@ function buildSeedanceContent(input) {
115
117
  }
116
118
  return content;
117
119
  }
120
+ /** `generate_audio` (only a real boolean) then `seed` (only a real number), in that wire order. */
121
+ function audioAndSeed(input) {
122
+ return {
123
+ ...(typeof input.generateAudio === 'boolean' ? { generate_audio: input.generateAudio } : {}),
124
+ ...seedField(input),
125
+ };
126
+ }
127
+ function seedField(input) {
128
+ return typeof input.seed === 'number' ? { seed: input.seed } : {};
129
+ }
130
+ function buildSeedanceBody({ input, wireModel, seconds }) {
131
+ return {
132
+ model: wireModel,
133
+ prompt: input.prompt,
134
+ duration: seconds,
135
+ content: buildSeedanceContent(input),
136
+ resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }),
137
+ ...(input.aspectRatio ? { ratio: input.aspectRatio } : {}),
138
+ ...audioAndSeed(input),
139
+ };
140
+ }
141
+ function buildWanBody({ input, wireModel, seconds, referenceUrl }) {
142
+ return {
143
+ model: wireModel,
144
+ input: {
145
+ prompt: input.prompt,
146
+ ...(referenceUrl ? { media: [{ type: 'first_frame', url: referenceUrl }] } : {}),
147
+ },
148
+ parameters: {
149
+ resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }).toUpperCase(),
150
+ duration: seconds,
151
+ prompt_extend: true,
152
+ watermark: false,
153
+ ...(input.aspectRatio ? { aspect_ratio: input.aspectRatio } : {}),
154
+ ...seedField(input),
155
+ },
156
+ };
157
+ }
158
+ function buildVeoBody({ input, wireModel, seconds }) {
159
+ return {
160
+ model: wireModel,
161
+ prompt: input.prompt,
162
+ seconds,
163
+ size: snapVeoSize({ size: input.size }),
164
+ ...audioAndSeed(input),
165
+ };
166
+ }
167
+ function buildGenericBody({ cap, input, wireModel, seconds, referenceUrl }) {
168
+ const genericSize = snapSizeToSupported({ size: input.size, supported: cap.supportedSizes });
169
+ return {
170
+ model: wireModel,
171
+ prompt: input.prompt,
172
+ seconds: String(seconds),
173
+ ...(genericSize ? { size: genericSize } : {}),
174
+ ...(input.resolution ? { resolution: input.resolution } : {}),
175
+ ...(referenceUrl ? { input_reference: referenceUrl } : {}),
176
+ ...audioAndSeed(input),
177
+ };
178
+ }
179
+ const FAMILY_BODY_BUILDERS = {
180
+ seedance: buildSeedanceBody,
181
+ wan: buildWanBody,
182
+ veo: buildVeoBody,
183
+ generic: buildGenericBody,
184
+ };
185
+ /**
186
+ * An unrecognized `cap.family` (untyped host config) gets the generic body,
187
+ * as the original if/else chain's final `else` did. `Object.hasOwn` keeps a
188
+ * prototype key such as `"toString"` from resolving to a non-builder.
189
+ */
190
+ function bodyBuilderFor(family) {
191
+ return Object.hasOwn(FAMILY_BODY_BUILDERS, family) ? FAMILY_BODY_BUILDERS[family] : buildGenericBody;
192
+ }
118
193
  /**
119
194
  * Builds the upstream video request body for a model. Pure: no fetch, no
120
195
  * auth. Caller: `POST \`${baseUrl}${pathSuffix}\`` with auth headers +
121
196
  * `JSON.stringify(body)`.
122
197
  */
123
198
  export function buildVideoRequest({ cap, input }) {
124
- const hasReference = Boolean(input.imageRef?.dataUrl);
125
- const wireModel = resolveWireModel({ cap: cap, hasReference: hasReference });
126
- const family = deriveVideoFamily({ wireModel: wireModel }, { cap: cap });
127
- const seconds = snapDuration({ cap: cap, requested: input.durationSeconds });
128
- let body;
129
- if (family === 'seedance') {
130
- body = {
131
- model: wireModel,
132
- prompt: input.prompt,
133
- duration: seconds,
134
- content: buildSeedanceContent(input),
135
- resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }),
136
- };
137
- if (input.aspectRatio)
138
- body.ratio = input.aspectRatio;
139
- if (typeof input.generateAudio === 'boolean')
140
- body.generate_audio = input.generateAudio;
141
- if (typeof input.seed === 'number')
142
- body.seed = input.seed;
143
- }
144
- else if (family === 'wan') {
145
- const wanInput = { prompt: input.prompt };
146
- if (hasReference) {
147
- wanInput.media = [{ type: 'first_frame', url: input.imageRef.dataUrl }];
148
- }
149
- const parameters = {
150
- resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }).toUpperCase(),
151
- duration: seconds,
152
- prompt_extend: true,
153
- watermark: false,
154
- };
155
- if (input.aspectRatio)
156
- parameters.aspect_ratio = input.aspectRatio;
157
- if (typeof input.seed === 'number')
158
- parameters.seed = input.seed;
159
- body = { model: wireModel, input: wanInput, parameters };
160
- }
161
- else if (family === 'veo') {
162
- body = {
163
- model: wireModel,
164
- prompt: input.prompt,
165
- seconds,
166
- size: snapVeoSize({ size: input.size }),
167
- };
168
- if (typeof input.generateAudio === 'boolean')
169
- body.generate_audio = input.generateAudio;
170
- if (typeof input.seed === 'number')
171
- body.seed = input.seed;
172
- }
173
- else {
174
- body = {
175
- model: wireModel,
176
- prompt: input.prompt,
177
- seconds: String(seconds),
178
- };
179
- const genericSize = snapSizeToSupported({ size: input.size, supported: cap.supportedSizes });
180
- if (genericSize)
181
- body.size = genericSize;
182
- if (input.resolution)
183
- body.resolution = input.resolution;
184
- if (hasReference)
185
- body.input_reference = input.imageRef.dataUrl;
186
- if (typeof input.generateAudio === 'boolean')
187
- body.generate_audio = input.generateAudio;
188
- if (typeof input.seed === 'number')
189
- body.seed = input.seed;
190
- }
199
+ const referenceUrl = input.imageRef?.dataUrl;
200
+ const hasReference = Boolean(referenceUrl);
201
+ const wireModel = resolveWireModel({ cap, hasReference });
202
+ const family = deriveVideoFamily({ wireModel }, { cap });
203
+ const seconds = snapDuration({ cap, requested: input.durationSeconds });
204
+ const body = bodyBuilderFor(family)({ cap, input, wireModel, seconds, referenceUrl });
191
205
  mergeExtraBody(body, cap, input.passthrough);
192
206
  return { wireModel, family, pathSuffix: '/videos', contentType: 'application/json', body, hasReference };
193
207
  }
208
+ /** The first value that is neither `undefined` nor `null` — a `??` chain over a list. */
209
+ function firstPresent(...values) {
210
+ return values.find((v) => v !== undefined && v !== null);
211
+ }
212
+ /** `error.message` (object form), the string `error`, then `failure_reason`, then `message`. */
213
+ function responseError(d) {
214
+ const errorObj = d.error;
215
+ const fromObject = typeof errorObj === 'object' && errorObj ? errorObj.message : undefined;
216
+ const fromString = typeof errorObj === 'string' ? errorObj : undefined;
217
+ return firstPresent(fromObject, fromString, d.failure_reason, d.message);
218
+ }
219
+ function responseUrl(d, data) {
220
+ const dataArray = Array.isArray(d.data) ? d.data : undefined;
221
+ const unsignedUrls = Array.isArray(d.unsigned_urls) ? d.unsigned_urls : undefined;
222
+ return firstPresent(d.video_url, d.url, d.output_url, data?.video_url, data?.url, dataArray?.[0]?.url, unsignedUrls?.[0]);
223
+ }
194
224
  /** Best-effort normalization of an async-submit / poll response across vendor families. */
195
225
  export function normalizeVideoResponse({ raw }) {
196
226
  const d = (raw ?? {});
197
227
  const data = d.data;
198
- const dataArray = Array.isArray(d.data) ? d.data : undefined;
199
- const unsignedUrls = Array.isArray(d.unsigned_urls) ? d.unsigned_urls : undefined;
200
- const id = d.id ?? d.task_id ?? data?.id ?? data?.task_id;
201
- const status = d.status ?? data?.status;
202
- const url = d.video_url ?? d.url ?? d.output_url ?? data?.video_url ?? data?.url ?? dataArray?.[0]?.url ?? unsignedUrls?.[0];
203
- const errorObj = d.error;
204
- const error = (typeof errorObj === 'object' && errorObj ? errorObj.message : undefined) ??
205
- (typeof errorObj === 'string' ? errorObj : undefined) ??
206
- d.failure_reason ??
207
- d.message;
228
+ const fields = {
229
+ id: firstPresent(d.id, d.task_id, data?.id, data?.task_id),
230
+ status: firstPresent(d.status, data?.status),
231
+ url: responseUrl(d, data),
232
+ error: responseError(d),
233
+ };
208
234
  const result = {};
209
- if (id !== undefined && id !== null)
210
- result.id = String(id);
211
- if (status !== undefined && status !== null)
212
- result.status = String(status);
213
- if (url !== undefined && url !== null)
214
- result.url = String(url);
215
- if (error !== undefined && error !== null)
216
- result.error = String(error);
235
+ for (const key of Object.keys(fields)) {
236
+ if (fields[key] !== undefined)
237
+ result[key] = String(fields[key]);
238
+ }
217
239
  return result;
218
240
  }
219
241
  //# sourceMappingURL=video-request.js.map
@@ -61,10 +61,24 @@ export interface ProcessDueDeliveriesRequired {
61
61
  export interface ProcessDueDeliveriesOptional {
62
62
  batchSize?: number;
63
63
  hooks?: readonly WebhookBeforeDispatchHook[];
64
+ /** Socket idle budget per request. A receiver that keeps trickling bytes never trips it. */
64
65
  requestTimeoutMs?: number;
66
+ /** Whole-request budget (DNS, connect, body) per delivery; default {@link DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS}. */
67
+ requestTotalDeadlineMs?: number;
68
+ /** Claim lease; default batchSize x requestTotalDeadlineMs + {@link WEBHOOK_CLAIM_LEASE_MARGIN_MS}. */
69
+ claimLeaseMs?: number;
70
+ /** Host shutdown: aborts the in-flight request and releases the batch's unattempted claims. */
71
+ signal?: AbortSignal;
65
72
  maxAttempts?: number;
66
73
  random?: (() => number) | undefined;
67
74
  }
75
+ /**
76
+ * The idle timeout alone lets one receiver that trickles a byte at a time hold the single-flight
77
+ * worker, and every other subscription's delivery, indefinitely. 30 s bounds each delivery.
78
+ */
79
+ export declare const DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS = 30000;
80
+ /** Slack for hooks, signing and storage writes on top of the batch's request deadlines. */
81
+ export declare const WEBHOOK_CLAIM_LEASE_MARGIN_MS = 60000;
68
82
  export interface ProcessDueDeliveriesResult {
69
83
  processed: number;
70
84
  delivered: number;
@@ -91,16 +91,32 @@ async function isAlreadyEnqueued(params) {
91
91
  });
92
92
  return existing.some((delivery) => delivery.eventId === params.eventId);
93
93
  }
94
+ /**
95
+ * The idle timeout alone lets one receiver that trickles a byte at a time hold the single-flight
96
+ * worker, and every other subscription's delivery, indefinitely. 30 s bounds each delivery.
97
+ */
98
+ export const DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS = 30_000;
99
+ /** Slack for hooks, signing and storage writes on top of the batch's request deadlines. */
100
+ export const WEBHOOK_CLAIM_LEASE_MARGIN_MS = 60_000;
94
101
  // Throwing/rejecting redaction hooks and explicit vetoes fail this attempt before signing/sending;
95
102
  // an unfiltered envelope must never fall through. Retry with normal backoff, then dead-letter.
96
103
  /** Claim and process a bounded batch; hooks fail closed and unsuccessful attempts back off or dead-letter. */
97
104
  export async function processDueDeliveries(required, optional = {}) {
98
105
  const { deliveryRepo, subscriptionRepo, envelopeStore, httpClient, signer, clock, headers } = required.deps;
99
- const { batchSize, hooks, requestTimeoutMs, maxAttempts, random } = resolveProcessDueDeliveriesOptions(optional);
106
+ const { batchSize, hooks, request, claimLeaseMs, signal, maxAttempts, random } = resolveProcessDueDeliveriesOptions(optional);
107
+ const result = { processed: 0, delivered: 0, failed: 0, dead: 0 };
108
+ if (signal?.aborted)
109
+ return result;
100
110
  const claimedAt = nowIso({ clock });
101
- const claimed = await deliveryRepo.claimPending({ batchSize, nowIso: claimedAt });
102
- const result = { processed: claimed.length, delivered: 0, failed: 0, dead: 0 };
103
- for (const row of claimed) {
111
+ // The lease makes a batch abandoned mid-flight (crash, or a shutdown that outlived its grace)
112
+ // reclaimable instead of stranding its rows in `delivering`; it covers the whole batch's deadlines.
113
+ const claimed = await deliveryRepo.claimPending({ batchSize, nowIso: claimedAt }, { claimLeaseMs });
114
+ result.processed = claimed.length;
115
+ for (const [index, row] of claimed.entries()) {
116
+ if (signal?.aborted) {
117
+ await releaseClaims(claimed.slice(index), { deliveryRepo, nextAttemptAt: claimedAt });
118
+ break;
119
+ }
104
120
  const outcome = await attemptOneDelivery(row, {
105
121
  subscriptionRepo,
106
122
  envelopeStore,
@@ -109,7 +125,7 @@ export async function processDueDeliveries(required, optional = {}) {
109
125
  headers,
110
126
  clock,
111
127
  hooks,
112
- requestTimeoutMs,
128
+ request,
113
129
  });
114
130
  const disposition = await recordDeliveryOutcome(row, outcome, { deliveryRepo, clock, maxAttempts, random });
115
131
  result[disposition] += 1;
@@ -117,8 +133,23 @@ export async function processDueDeliveries(required, optional = {}) {
117
133
  return result;
118
134
  }
119
135
  function resolveProcessDueDeliveriesOptions(optional) {
120
- const { batchSize = 20, hooks = [], requestTimeoutMs = 10_000, maxAttempts = MAX_DELIVERY_ATTEMPTS, random, } = optional;
121
- return { batchSize, hooks, requestTimeoutMs, maxAttempts, random };
136
+ const { batchSize = 20, hooks = [], requestTimeoutMs = 10_000, requestTotalDeadlineMs = DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS, signal, maxAttempts = MAX_DELIVERY_ATTEMPTS, random, } = optional;
137
+ const claimLeaseMs = optional.claimLeaseMs ?? batchSize * requestTotalDeadlineMs + WEBHOOK_CLAIM_LEASE_MARGIN_MS;
138
+ const request = { timeoutMs: requestTimeoutMs, totalDeadlineMs: requestTotalDeadlineMs, ...(signal ? { signal } : {}) };
139
+ return { batchSize, hooks, request, claimLeaseMs, signal, maxAttempts, random };
140
+ }
141
+ /**
142
+ * Cancelled before these rows were attempted: hand them straight back (attempts restored, due at
143
+ * once) so a restart delivers them without waiting out the lease. A repo without `releaseClaim`
144
+ * leaves them to the lease.
145
+ */
146
+ async function releaseClaims(rows, deps) {
147
+ const { deliveryRepo, nextAttemptAt } = deps;
148
+ if (!deliveryRepo.releaseClaim)
149
+ return;
150
+ for (const row of rows) {
151
+ await deliveryRepo.releaseClaim({ workspaceId: row.workspaceId, id: row.id, claimedAttempts: row.attempts, nextAttemptAt });
152
+ }
122
153
  }
123
154
  async function recordDeliveryOutcome(row, outcome, deps) {
124
155
  if (outcome.ok) {
@@ -127,7 +158,7 @@ async function recordDeliveryOutcome(row, outcome, deps) {
127
158
  id: row.id,
128
159
  responseStatus: outcome.responseStatus,
129
160
  deliveredAtIso: nowIso({ clock: deps.clock }),
130
- });
161
+ }, { claimedAttempts: row.attempts });
131
162
  return "delivered";
132
163
  }
133
164
  const isExhausted = row.attempts >= deps.maxAttempts;
@@ -143,7 +174,7 @@ async function recordDeliveryOutcome(row, outcome, deps) {
143
174
  responseStatus: outcome.responseStatus,
144
175
  nextStatus,
145
176
  nextAttemptAt,
146
- }, isExhausted ? { deadAtIso: failedAtIso } : {});
177
+ }, { claimedAttempts: row.attempts, ...(isExhausted ? { deadAtIso: failedAtIso } : {}) });
147
178
  return isExhausted ? "dead" : "failed";
148
179
  }
149
180
  // Missing/inactive subscriptions, missing envelopes, hook failures, transport failures and
@@ -185,7 +216,7 @@ async function attemptOneDelivery(row, deps) {
185
216
  [deps.headers.deliveryId]: row.id,
186
217
  [deps.headers.eventId]: row.eventId,
187
218
  },
188
- timeoutMs: deps.requestTimeoutMs,
219
+ ...deps.request,
189
220
  body: rawBody,
190
221
  } });
191
222
  if (response.status >= 200 && response.status < 300) {