@tangle-network/agent-app 0.60.250 → 0.60.252

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 (222) hide show
  1. package/dist/DesignCanvas-L6J72JQ2.js +15 -0
  2. package/dist/DesignCanvasEditor-QFQD63MR.js +18 -0
  3. package/dist/agent-enrollment/drizzle.js +3 -3
  4. package/dist/agent-enrollment/index.js +3 -3
  5. package/dist/app-auth/drizzle.d.ts +475 -0
  6. package/dist/app-auth/drizzle.js +86 -0
  7. package/dist/app-auth/drizzle.js.map +1 -0
  8. package/dist/app-auth/index.js +5 -3
  9. package/dist/app-auth/index.js.map +1 -1
  10. package/dist/app-oauth/drizzle.d.ts +2080 -0
  11. package/dist/app-oauth/drizzle.js +161 -0
  12. package/dist/app-oauth/drizzle.js.map +1 -0
  13. package/dist/app-oauth/index.d.ts +4 -0
  14. package/dist/app-oauth/index.js +8 -222
  15. package/dist/app-oauth/index.js.map +1 -1
  16. package/dist/app-oauth/issuer.d.ts +133 -0
  17. package/dist/app-oauth/issuer.js +247 -0
  18. package/dist/app-oauth/issuer.js.map +1 -0
  19. package/dist/assistant/index.js +13 -13
  20. package/dist/chat-react/index.js +4 -4
  21. package/dist/chat-routes/index.js +37 -67
  22. package/dist/chat-routes/index.js.map +1 -1
  23. package/dist/chat-routes/promote-file-part.d.ts +2 -3
  24. package/dist/chat-store/index.js +4 -4
  25. package/dist/{chunk-MY3EJJ6Y.js → chunk-4FEH6266.js} +2 -2
  26. package/dist/{chunk-5Y7Z5G3Y.js → chunk-4GCPADYG.js} +20 -336
  27. package/dist/chunk-4GCPADYG.js.map +1 -0
  28. package/dist/{chunk-X556WVBG.js → chunk-4ZSLX3LY.js} +2 -2
  29. package/dist/chunk-57XPEL7X.js +26 -0
  30. package/dist/chunk-57XPEL7X.js.map +1 -0
  31. package/dist/chunk-6Z7TZVKZ.js +26 -0
  32. package/dist/chunk-6Z7TZVKZ.js.map +1 -0
  33. package/dist/{chunk-7KKOFMLD.js → chunk-AWIQQEFP.js} +1 -1
  34. package/dist/chunk-AWIQQEFP.js.map +1 -0
  35. package/dist/{chunk-VBKP2NLI.js → chunk-BTKI4XMM.js} +2 -2
  36. package/dist/{chunk-63QAQP7I.js → chunk-CNBVWPQC.js} +7 -7
  37. package/dist/{chunk-FENBDSIW.js → chunk-CQGEGPY7.js} +75 -3
  38. package/dist/chunk-CQGEGPY7.js.map +1 -0
  39. package/dist/chunk-CTREXL3O.js +335 -0
  40. package/dist/chunk-CTREXL3O.js.map +1 -0
  41. package/dist/chunk-DLWO3J7D.js +238 -0
  42. package/dist/chunk-DLWO3J7D.js.map +1 -0
  43. package/dist/{chunk-LWSJK546.js → chunk-DSMGS4IV.js} +5 -5
  44. package/dist/{chunk-LWSJK546.js.map → chunk-DSMGS4IV.js.map} +1 -1
  45. package/dist/{chunk-A3KPDLSF.js → chunk-EFPIHR6F.js} +18 -18
  46. package/dist/chunk-FRAICFTZ.js +191 -0
  47. package/dist/chunk-FRAICFTZ.js.map +1 -0
  48. package/dist/chunk-GS7VWV26.js +61 -0
  49. package/dist/chunk-GS7VWV26.js.map +1 -0
  50. package/dist/{chunk-NMSAZFRL.js → chunk-H5GQMLHA.js} +2 -2
  51. package/dist/{chunk-OQE6WMDP.js → chunk-HN6MZ2XL.js} +5 -5
  52. package/dist/chunk-HY57QRRW.js +11 -0
  53. package/dist/chunk-HY57QRRW.js.map +1 -0
  54. package/dist/{chunk-TCGZFSN5.js → chunk-KH4QSBNI.js} +2 -2
  55. package/dist/{chunk-JH3CKHF4.js → chunk-KJODHPWM.js} +8 -8
  56. package/dist/chunk-LSBI5MWS.js +66 -0
  57. package/dist/chunk-LSBI5MWS.js.map +1 -0
  58. package/dist/chunk-MDRH3SDA.js +106 -0
  59. package/dist/chunk-MDRH3SDA.js.map +1 -0
  60. package/dist/{chunk-VBWYH7UZ.js → chunk-NHYRIM4I.js} +3 -3
  61. package/dist/{chunk-BYP54FMI.js → chunk-O2RCDK5D.js} +30 -15
  62. package/dist/{chunk-BYP54FMI.js.map → chunk-O2RCDK5D.js.map} +1 -1
  63. package/dist/{chunk-EWOJATDS.js → chunk-PDD5A43Y.js} +3 -3
  64. package/dist/{chunk-23JUSUUB.js → chunk-RZLCBWGG.js} +2 -2
  65. package/dist/chunk-SFZELD6V.js +52 -0
  66. package/dist/chunk-SFZELD6V.js.map +1 -0
  67. package/dist/{chunk-Y4W6GK5X.js → chunk-UGFCLD32.js} +2 -2
  68. package/dist/{chunk-ZGUXI5SI.js → chunk-VUBJZEZB.js} +2 -2
  69. package/dist/{chunk-LQYIBL3G.js → chunk-WL7PZK7Q.js} +71 -1
  70. package/dist/chunk-WL7PZK7Q.js.map +1 -0
  71. package/dist/{chunk-7HZCFG2A.js → chunk-WP2GYFZ4.js} +38 -1
  72. package/dist/chunk-WP2GYFZ4.js.map +1 -0
  73. package/dist/{chunk-JK7R7BZQ.js → chunk-ZWJ3SZ2G.js} +2 -2
  74. package/dist/crypto/digest.d.ts +2 -0
  75. package/dist/crypto/index.d.ts +1 -0
  76. package/dist/crypto/index.js +6 -2
  77. package/dist/design-canvas/index.js +5 -3
  78. package/dist/design-canvas/index.js.map +1 -1
  79. package/dist/design-canvas-react/engine.js +7 -5
  80. package/dist/design-canvas-react/index.js +14 -12
  81. package/dist/design-canvas-react/index.js.map +1 -1
  82. package/dist/design-canvas-react/lazy.js +1 -1
  83. package/dist/eval/index.d.ts +4 -0
  84. package/dist/eval/index.js +125 -0
  85. package/dist/eval/index.js.map +1 -1
  86. package/dist/eval/persona-driver.d.ts +37 -0
  87. package/dist/eval/research-plan.d.ts +25 -0
  88. package/dist/eval/research-plan.js +55 -0
  89. package/dist/eval/research-plan.js.map +1 -0
  90. package/dist/eval/scorecard.d.ts +38 -0
  91. package/dist/forms/blank.d.ts +2 -2
  92. package/dist/forms/index.js +4 -5
  93. package/dist/forms/index.js.map +1 -1
  94. package/dist/hosted-agent/application.js +2 -2
  95. package/dist/interactions/index.js +3 -3
  96. package/dist/knowledge/prelaunch-audit.d.ts +17 -0
  97. package/dist/knowledge/prelaunch-audit.js +67 -0
  98. package/dist/knowledge/prelaunch-audit.js.map +1 -0
  99. package/dist/media/drizzle.d.ts +207 -0
  100. package/dist/media/drizzle.js +26 -0
  101. package/dist/media/drizzle.js.map +1 -0
  102. package/dist/media/generate-request.d.ts +53 -0
  103. package/dist/media/generation-record.d.ts +68 -0
  104. package/dist/media/index.d.ts +13 -0
  105. package/dist/media/index.js +653 -0
  106. package/dist/media/index.js.map +1 -0
  107. package/dist/media/model-catalog.d.ts +109 -0
  108. package/dist/media/router-client.d.ts +40 -0
  109. package/dist/media/router-generation.d.ts +44 -0
  110. package/dist/media/speech-script.d.ts +20 -0
  111. package/dist/openui/index.js +1 -1
  112. package/dist/operator/index.js +4 -5
  113. package/dist/operator/index.js.map +1 -1
  114. package/dist/plans/decision.d.ts +48 -0
  115. package/dist/plans/drizzle.d.ts +25 -0
  116. package/dist/plans/drizzle.js +97 -0
  117. package/dist/plans/drizzle.js.map +1 -0
  118. package/dist/plans/index.d.ts +1 -1
  119. package/dist/plans/index.js +11 -3
  120. package/dist/platform/billing-config.d.ts +22 -0
  121. package/dist/platform/billing-config.js +36 -0
  122. package/dist/platform/billing-config.js.map +1 -0
  123. package/dist/platform/index.js +13 -11
  124. package/dist/platform/index.js.map +1 -1
  125. package/dist/preset-cloudflare/index.js +2 -1
  126. package/dist/preset-cloudflare/index.js.map +1 -1
  127. package/dist/profile/index.js +4 -5
  128. package/dist/profile/index.js.map +1 -1
  129. package/dist/public-consultation/index.d.ts +1 -1
  130. package/dist/public-consultation/index.js +13 -11
  131. package/dist/public-consultation/index.js.map +1 -1
  132. package/dist/runtime/telemetry-cap.d.ts +24 -0
  133. package/dist/runtime/telemetry-cap.js +36 -0
  134. package/dist/runtime/telemetry-cap.js.map +1 -0
  135. package/dist/sandbox/index.js +12 -9
  136. package/dist/sequences/index.js +4 -2
  137. package/dist/sequences/index.js.map +1 -1
  138. package/dist/skills-placement/box.d.ts +50 -0
  139. package/dist/skills-placement/box.js +204 -0
  140. package/dist/skills-placement/box.js.map +1 -0
  141. package/dist/skills-placement/index.js +8 -96
  142. package/dist/skills-placement/index.js.map +1 -1
  143. package/dist/spend/budget.d.ts +13 -0
  144. package/dist/spend/drizzle.d.ts +55 -0
  145. package/dist/spend/drizzle.js +131 -0
  146. package/dist/spend/drizzle.js.map +1 -0
  147. package/dist/spend/index.d.ts +2 -1
  148. package/dist/spend/index.js +77 -58
  149. package/dist/spend/index.js.map +1 -1
  150. package/dist/spend/platform-settlements.d.ts +46 -0
  151. package/dist/stream/index.js +19 -19
  152. package/dist/studio/generated-media/index.d.ts +6 -0
  153. package/dist/studio/generated-media/index.js +590 -0
  154. package/dist/studio/generated-media/index.js.map +1 -0
  155. package/dist/studio/generated-media/output.d.ts +27 -0
  156. package/dist/studio/generated-media/store.d.ts +175 -0
  157. package/dist/studio-react/download-generations.d.ts +7 -0
  158. package/dist/studio-react/index.d.ts +1 -0
  159. package/dist/studio-react/index.js +85 -0
  160. package/dist/studio-react/index.js.map +1 -1
  161. package/dist/studio-react/use-studio-route.d.ts +44 -0
  162. package/dist/teams/invitations-api.d.ts +4 -0
  163. package/dist/teams/invitations-api.js +44 -32
  164. package/dist/teams/invitations-api.js.map +1 -1
  165. package/dist/theme/dom.d.ts +22 -0
  166. package/dist/theme/dom.js +18 -0
  167. package/dist/theme/dom.js.map +1 -0
  168. package/dist/vault/collaboration.d.ts +83 -0
  169. package/dist/vault/collaboration.js +215 -0
  170. package/dist/vault/collaboration.js.map +1 -0
  171. package/dist/vault/server.js +6 -53
  172. package/dist/vault/server.js.map +1 -1
  173. package/dist/vault/store/coordinator.d.ts +64 -0
  174. package/dist/vault/store/index.d.ts +12 -0
  175. package/dist/vault/store/index.js +1202 -0
  176. package/dist/vault/store/index.js.map +1 -0
  177. package/dist/vault/store/paths.d.ts +65 -0
  178. package/dist/vault/store/revisions.d.ts +211 -0
  179. package/dist/vault/store/sandbox-sync.d.ts +74 -0
  180. package/dist/vault/store/store.d.ts +161 -0
  181. package/dist/vault/store/tree.d.ts +11 -0
  182. package/dist/web/entry-server.d.ts +7 -0
  183. package/dist/web/entry-server.js +29 -0
  184. package/dist/web/entry-server.js.map +1 -0
  185. package/dist/web/fetch-guard.d.ts +6 -0
  186. package/dist/web/index.d.ts +3 -0
  187. package/dist/web/index.js +20 -4
  188. package/dist/web/mime.d.ts +16 -0
  189. package/dist/web/rate-limit.d.ts +25 -0
  190. package/dist/web/timeout.d.ts +9 -0
  191. package/dist/web-react/agent-profile-editor.js +3 -3
  192. package/dist/web-react/api-access-panel.d.ts +4 -2
  193. package/dist/web-react/document.d.ts +41 -0
  194. package/dist/web-react/document.js +103 -0
  195. package/dist/web-react/document.js.map +1 -0
  196. package/dist/web-react/index.js +31 -31
  197. package/dist/workspace-react/index.js +5 -5
  198. package/package.json +95 -4
  199. package/dist/DesignCanvas-OW3W2QXW.js +0 -13
  200. package/dist/DesignCanvasEditor-TCHZF25W.js +0 -16
  201. package/dist/chunk-5Y7Z5G3Y.js.map +0 -1
  202. package/dist/chunk-7HZCFG2A.js.map +0 -1
  203. package/dist/chunk-7KKOFMLD.js.map +0 -1
  204. package/dist/chunk-FENBDSIW.js.map +0 -1
  205. package/dist/chunk-LQYIBL3G.js.map +0 -1
  206. /package/dist/{DesignCanvas-OW3W2QXW.js.map → DesignCanvas-L6J72JQ2.js.map} +0 -0
  207. /package/dist/{DesignCanvasEditor-TCHZF25W.js.map → DesignCanvasEditor-QFQD63MR.js.map} +0 -0
  208. /package/dist/{chunk-MY3EJJ6Y.js.map → chunk-4FEH6266.js.map} +0 -0
  209. /package/dist/{chunk-X556WVBG.js.map → chunk-4ZSLX3LY.js.map} +0 -0
  210. /package/dist/{chunk-VBKP2NLI.js.map → chunk-BTKI4XMM.js.map} +0 -0
  211. /package/dist/{chunk-63QAQP7I.js.map → chunk-CNBVWPQC.js.map} +0 -0
  212. /package/dist/{chunk-A3KPDLSF.js.map → chunk-EFPIHR6F.js.map} +0 -0
  213. /package/dist/{chunk-NMSAZFRL.js.map → chunk-H5GQMLHA.js.map} +0 -0
  214. /package/dist/{chunk-OQE6WMDP.js.map → chunk-HN6MZ2XL.js.map} +0 -0
  215. /package/dist/{chunk-TCGZFSN5.js.map → chunk-KH4QSBNI.js.map} +0 -0
  216. /package/dist/{chunk-JH3CKHF4.js.map → chunk-KJODHPWM.js.map} +0 -0
  217. /package/dist/{chunk-VBWYH7UZ.js.map → chunk-NHYRIM4I.js.map} +0 -0
  218. /package/dist/{chunk-EWOJATDS.js.map → chunk-PDD5A43Y.js.map} +0 -0
  219. /package/dist/{chunk-23JUSUUB.js.map → chunk-RZLCBWGG.js.map} +0 -0
  220. /package/dist/{chunk-Y4W6GK5X.js.map → chunk-UGFCLD32.js.map} +0 -0
  221. /package/dist/{chunk-ZGUXI5SI.js.map → chunk-VUBJZEZB.js.map} +0 -0
  222. /package/dist/{chunk-JK7R7BZQ.js.map → chunk-ZWJ3SZ2G.js.map} +0 -0
@@ -0,0 +1,653 @@
1
+ import {
2
+ withTimeout
3
+ } from "../chunk-6Z7TZVKZ.js";
4
+ import {
5
+ isBlockedFetchHostname
6
+ } from "../chunk-57XPEL7X.js";
7
+
8
+ // src/media/router-client.ts
9
+ var RouterHttpError = class extends Error {
10
+ status;
11
+ code;
12
+ constructor(status, message, code) {
13
+ super(message);
14
+ this.name = "RouterHttpError";
15
+ this.status = status;
16
+ this.code = code;
17
+ }
18
+ };
19
+ var NOT_CONFIGURED = "Media generation is not configured for this deployment.";
20
+ function routerV1Url(value) {
21
+ return `${routerRootUrl(value)}/v1`;
22
+ }
23
+ async function routerResponseError(response) {
24
+ const text3 = await response.text();
25
+ if (!text3) return { message: response.statusText };
26
+ try {
27
+ const json = JSON.parse(text3);
28
+ if (typeof json.error === "string") return { message: json.error };
29
+ const code = typeof json.error?.code === "string" ? json.error.code : void 0;
30
+ if (typeof json.error?.message === "string") return { message: json.error.message, code };
31
+ if (typeof json.message === "string") return { message: json.message, code };
32
+ } catch {
33
+ return { message: text3.slice(0, 500) };
34
+ }
35
+ return { message: text3.slice(0, 500) };
36
+ }
37
+ async function routerResponseErrorMessage(response) {
38
+ return (await routerResponseError(response)).message;
39
+ }
40
+ function createRouterMediaClient(config) {
41
+ const wrap = (headers) => config.headers?.(headers) ?? headers;
42
+ function requiredRouterApiKey(value) {
43
+ const apiKey = text(value ?? config.defaultApiKey?.());
44
+ if (!apiKey) throw new Error(NOT_CONFIGURED);
45
+ return apiKey;
46
+ }
47
+ function routerMediaUrl(path) {
48
+ return `${routerV1Url(config.baseUrl())}${path}`;
49
+ }
50
+ function routerHeaders(apiKey, extra = {}) {
51
+ return wrap({ Authorization: `Bearer ${requiredRouterApiKey(apiKey)}`, ...extra });
52
+ }
53
+ async function routerJson(path, body, signal, apiKey) {
54
+ const response = await fetch(routerMediaUrl(path), {
55
+ method: "POST",
56
+ headers: routerHeaders(apiKey, { "Content-Type": "application/json" }),
57
+ body: JSON.stringify(pruneUndefined(body)),
58
+ signal
59
+ });
60
+ if (!response.ok) {
61
+ const { message, code } = await routerResponseError(response);
62
+ throw new RouterHttpError(response.status, `Router media request failed: ${response.status} ${message}`, code);
63
+ }
64
+ return await response.json();
65
+ }
66
+ async function routerMediaStatus(id, signal, apiKey) {
67
+ const response = await fetch(routerMediaUrl(`/videos/${encodeURIComponent(id)}`), {
68
+ headers: routerHeaders(apiKey),
69
+ signal
70
+ });
71
+ if (!response.ok) {
72
+ throw new Error(`Router media poll failed: ${response.status} ${await routerResponseErrorMessage(response)}`);
73
+ }
74
+ return await response.json();
75
+ }
76
+ function resolveRouterMediaSource(value, apiKey) {
77
+ if (!value.startsWith("/") || value.startsWith("//")) return { url: value };
78
+ return {
79
+ url: `${routerRootUrl(config.baseUrl())}${value}`,
80
+ authorization: `Bearer ${requiredRouterApiKey(apiKey)}`
81
+ };
82
+ }
83
+ function validateRouterMediaSourceUrl(value) {
84
+ const expected = new URL(routerRootUrl(config.baseUrl())).origin;
85
+ const url = new URL(value);
86
+ if (url.origin !== expected) {
87
+ throw new Error(`Authorized media fetch must target the router origin ${expected}`);
88
+ }
89
+ return url.toString();
90
+ }
91
+ return {
92
+ requiredRouterApiKey,
93
+ routerMediaUrl,
94
+ routerHeaders,
95
+ routerJson,
96
+ routerMediaStatus,
97
+ resolveRouterMediaSource,
98
+ validateRouterMediaSourceUrl
99
+ };
100
+ }
101
+ function routerRootUrl(value) {
102
+ return value.replace(/\/+$/, "").replace(/\/v1$/, "");
103
+ }
104
+ function pruneUndefined(value) {
105
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
106
+ }
107
+ function text(value) {
108
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
109
+ }
110
+
111
+ // src/media/router-generation.ts
112
+ var MAX_TRANSCRIPTION_BYTES = 25 * 1024 * 1024;
113
+ var SUPPORTED_TRANSCRIPTION_FORMATS = /* @__PURE__ */ new Set(["wav", "mp3", "flac", "m4a", "ogg", "webm", "aac"]);
114
+ function validatePublicHttpUrl(value, field) {
115
+ let url;
116
+ try {
117
+ url = new URL(value);
118
+ } catch {
119
+ throw new Error(`${field} must be a valid public URL`);
120
+ }
121
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
122
+ throw new Error(`${field} must use http or https`);
123
+ }
124
+ if (isBlockedFetchHostname(url.hostname)) {
125
+ throw new Error(`${field} must be a public URL`);
126
+ }
127
+ return url.toString();
128
+ }
129
+ async function fetchBoundedAudio(url, options = {}) {
130
+ const safeUrl = validatePublicHttpUrl(url, "audioUrl");
131
+ const response = await fetch(safeUrl, { signal: options.signal, redirect: "manual" });
132
+ if (response.status >= 300 && response.status < 400) {
133
+ throw new Error("Audio URL redirects are not allowed");
134
+ }
135
+ if (!response.ok) {
136
+ throw new Error(`Audio fetch failed with ${response.status}`);
137
+ }
138
+ const contentLength = Number(response.headers.get("content-length") ?? "0");
139
+ if (contentLength > MAX_TRANSCRIPTION_BYTES) {
140
+ throw new Error("Audio file is too large");
141
+ }
142
+ const contentType = response.headers.get("content-type") ?? "application/octet-stream";
143
+ if (!contentType.startsWith("audio/") && contentType !== "application/octet-stream") {
144
+ throw new Error("Transcription URL must return audio");
145
+ }
146
+ const blob = await response.blob();
147
+ if (blob.size === 0) throw new Error("Transcription audio URL returned an empty file");
148
+ if (blob.size > MAX_TRANSCRIPTION_BYTES) {
149
+ throw new Error("Audio file is too large");
150
+ }
151
+ return blob;
152
+ }
153
+ function createRouterGeneration(client) {
154
+ async function generateVideoViaRouter({ model, prompt, duration, resolution, aspectRatio, referenceImageUrl, callbackUrl }, signal, apiKey) {
155
+ return await client.routerJson(
156
+ "/videos/generate",
157
+ {
158
+ model,
159
+ prompt,
160
+ duration,
161
+ resolution,
162
+ aspect_ratio: aspectRatio,
163
+ image_url: referenceImageUrl,
164
+ callback_url: callbackUrl
165
+ },
166
+ signal,
167
+ apiKey
168
+ );
169
+ }
170
+ async function generateAvatarViaRouter(body, signal, apiKey) {
171
+ return await client.routerJson("/videos/avatar", { ...body }, signal, apiKey);
172
+ }
173
+ async function transcribeViaRouter({
174
+ audioBlob,
175
+ audioUrl,
176
+ model,
177
+ language,
178
+ prompt,
179
+ responseFormat,
180
+ temperature,
181
+ signal,
182
+ apiKey
183
+ }) {
184
+ const format = transcriptionAudioFormat(audioUrl, audioBlob.type);
185
+ const responseFormatText = typeof responseFormat === "string" && responseFormat.trim() ? responseFormat.trim() : null;
186
+ const audioData = bytesToBase64(new Uint8Array(await audioBlob.arrayBuffer()));
187
+ const response = await fetch(client.routerMediaUrl("/audio/transcriptions"), {
188
+ method: "POST",
189
+ headers: client.routerHeaders(apiKey, { "Content-Type": "application/json" }),
190
+ body: JSON.stringify({
191
+ model,
192
+ input_audio: { data: audioData, format },
193
+ language,
194
+ prompt,
195
+ response_format: responseFormat,
196
+ temperature
197
+ }),
198
+ signal
199
+ });
200
+ if (!response.ok) {
201
+ throw new Error(`Transcription provider failed: ${response.status} ${await routerResponseErrorMessage(response)}`);
202
+ }
203
+ if (isRawTranscriptionResponseFormat(responseFormatText)) {
204
+ return { text: await response.text() };
205
+ }
206
+ return await response.json();
207
+ }
208
+ return { generateVideoViaRouter, generateAvatarViaRouter, transcribeViaRouter };
209
+ }
210
+ function isRawTranscriptionResponseFormat(value) {
211
+ const format = value?.toLowerCase();
212
+ return format === "text" || format === "srt" || format === "vtt";
213
+ }
214
+ function transcriptionAudioFormat(audioUrl, contentType) {
215
+ const fromType = contentTypeToAudioFormat(contentType);
216
+ if (fromType) return fromType;
217
+ const ext = new URL(audioUrl).pathname.split(".").pop()?.toLowerCase();
218
+ if (ext && SUPPORTED_TRANSCRIPTION_FORMATS.has(ext)) return ext;
219
+ throw new Error("Transcription audio must be wav, mp3, flac, m4a, ogg, webm, or aac");
220
+ }
221
+ function contentTypeToAudioFormat(contentType) {
222
+ const type = contentType.toLowerCase().split(";")[0]?.trim();
223
+ if (type === "audio/wav" || type === "audio/x-wav") return "wav";
224
+ if (type === "audio/mpeg" || type === "audio/mp3") return "mp3";
225
+ if (type === "audio/flac") return "flac";
226
+ if (type === "audio/mp4" || type === "audio/x-m4a") return "m4a";
227
+ if (type === "audio/ogg" || type === "application/ogg") return "ogg";
228
+ if (type === "audio/webm" || type === "video/webm") return "webm";
229
+ if (type === "audio/aac") return "aac";
230
+ return null;
231
+ }
232
+ function bytesToBase64(bytes) {
233
+ let binary = "";
234
+ for (let i = 0; i < bytes.length; i += 8192) {
235
+ binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
236
+ }
237
+ return btoa(binary);
238
+ }
239
+
240
+ // src/media/generate-request.ts
241
+ var MIN_IMAGE_COUNT = 1;
242
+ var MAX_IMAGE_COUNT = 4;
243
+ function requiredText(value) {
244
+ return typeof value === "string" && value.trim() ? value.trim() : null;
245
+ }
246
+ function validateGenerateRequest(type, body, prompt) {
247
+ if (type !== "transcription" && type !== "avatar" && !prompt) {
248
+ return { succeeded: false, error: "prompt is required" };
249
+ }
250
+ if (type === "avatar") {
251
+ const audioUrl = requiredHttpsUrl(body.audioUrl, "audioUrl");
252
+ if (!audioUrl.succeeded) return audioUrl;
253
+ const imageUrl = optionalHttpsUrl(body.imageUrl, "imageUrl");
254
+ if (!imageUrl.succeeded) return imageUrl;
255
+ return {
256
+ succeeded: true,
257
+ value: {
258
+ promptLabel: prompt || audioUrl.value,
259
+ audioUrl: audioUrl.value,
260
+ imageUrl: imageUrl.value,
261
+ avatarId: body.avatarId?.trim() || void 0
262
+ }
263
+ };
264
+ }
265
+ if (type === "transcription") {
266
+ const audioUrl = requiredHttpsUrl(body.audioUrl, "audioUrl");
267
+ if (!audioUrl.succeeded) return audioUrl;
268
+ return {
269
+ succeeded: true,
270
+ value: {
271
+ promptLabel: prompt || audioUrl.value,
272
+ audioUrl: audioUrl.value,
273
+ language: body.language?.trim() || void 0,
274
+ responseFormat: body.responseFormat?.trim() || void 0,
275
+ temperature: numberValue(body.temperature)
276
+ }
277
+ };
278
+ }
279
+ if (type === "video") {
280
+ const referenceImageUrl = optionalHttpsUrl(body.referenceImageUrl, "referenceImageUrl");
281
+ if (!referenceImageUrl.succeeded) return referenceImageUrl;
282
+ return {
283
+ succeeded: true,
284
+ value: {
285
+ promptLabel: prompt,
286
+ duration: body.duration,
287
+ resolution: body.resolution,
288
+ aspectRatio: body.aspectRatio?.trim() || void 0,
289
+ referenceImageUrl: referenceImageUrl.value
290
+ }
291
+ };
292
+ }
293
+ return {
294
+ succeeded: true,
295
+ value: {
296
+ promptLabel: prompt,
297
+ size: body.size,
298
+ quality: body.quality,
299
+ n: body.n,
300
+ duration: body.duration,
301
+ resolution: body.resolution,
302
+ voice: body.voice
303
+ }
304
+ };
305
+ }
306
+ function imageCountForRequest(value) {
307
+ if (value == null) return { succeeded: true, value: 1 };
308
+ const count = typeof value === "number" ? value : Number.NaN;
309
+ if (!Number.isInteger(count) || count < MIN_IMAGE_COUNT || count > MAX_IMAGE_COUNT) {
310
+ return { succeeded: false, error: `Images must be an integer between ${MIN_IMAGE_COUNT} and ${MAX_IMAGE_COUNT}` };
311
+ }
312
+ return { succeeded: true, value: count };
313
+ }
314
+ function modelForRequest(type, body, defaults) {
315
+ return body.model?.trim() || defaults[type];
316
+ }
317
+ function requiredHttpsUrl(value, field) {
318
+ const text3 = requiredText(value);
319
+ if (!text3) return { succeeded: false, error: `${field} is required` };
320
+ return validateExternalHttpsUrl(text3, field);
321
+ }
322
+ function optionalHttpsUrl(value, field) {
323
+ const text3 = requiredText(value);
324
+ if (!text3) return { succeeded: true, value: void 0 };
325
+ return validateExternalHttpsUrl(text3, field);
326
+ }
327
+ function validateExternalHttpsUrl(value, field) {
328
+ try {
329
+ const url = new URL(value);
330
+ if (url.protocol !== "https:") {
331
+ return { succeeded: false, error: `${field} must be an https URL` };
332
+ }
333
+ if (isBlockedFetchHostname(url.hostname)) {
334
+ return { succeeded: false, error: `${field} must not point to localhost or a private network address` };
335
+ }
336
+ return { succeeded: true, value };
337
+ } catch {
338
+ return { succeeded: false, error: `${field} must be a valid URL` };
339
+ }
340
+ }
341
+ function numberValue(value) {
342
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
343
+ }
344
+
345
+ // src/media/speech-script.ts
346
+ var DEFAULT_TIMEOUT_MS = 2e4;
347
+ var SYSTEM_PROMPT = "Convert Audio Studio prompts into the exact words a voice actor should speak. If the user gives a creative brief, write concise speakable copy matching it. Do not describe the audio. Do not include labels, markdown, quotes, bracketed directions, or explanations. Preserve requested tone, audience, duration, and constraints. Output only the spoken words.";
348
+ function createSpeechScriptResolver(config) {
349
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
350
+ const { inputUsdPerMtok, outputUsdPerMtok } = config.pricing;
351
+ async function generateSpeechScript(prompt, signal, apiKey) {
352
+ const response = await config.routerJson("/chat/completions", {
353
+ model: config.model(),
354
+ ...config.requestOptions,
355
+ messages: [
356
+ { role: "system", content: SYSTEM_PROMPT },
357
+ { role: "user", content: prompt }
358
+ ]
359
+ }, signal, apiKey);
360
+ const content = response.choices?.[0]?.message?.content;
361
+ const usage = response.usage;
362
+ return {
363
+ text: typeof content === "string" ? content : "",
364
+ ...Number.isSafeInteger(usage?.prompt_tokens) && Number.isSafeInteger(usage?.completion_tokens) ? { usage: { inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens } } : {}
365
+ };
366
+ }
367
+ function estimateCostUsd(prompt, script) {
368
+ const inputCost = estimateTextTokens(prompt) / 1e6 * inputUsdPerMtok;
369
+ const outputCost = estimateTextTokens(script) / 1e6 * outputUsdPerMtok;
370
+ return roundUsd(inputCost + outputCost);
371
+ }
372
+ return async function resolveSpeechInput(prompt, apiKey) {
373
+ const literalInput = exactSpeechInput(prompt);
374
+ if (literalInput) return { mode: "literal", input: literalInput, scriptCostUsd: 0 };
375
+ const script = await withTimeout(
376
+ (signal) => generateSpeechScript(prompt, signal, apiKey),
377
+ timeoutMs,
378
+ `Speech script generation timed out after ${timeoutMs / 1e3}s`
379
+ );
380
+ const input = normalizeSpeechScript(script.text);
381
+ if (!input) throw new Error("Speech script generation returned empty text");
382
+ const scriptCostUsd = script.usage ? roundUsd((script.usage.inputTokens * inputUsdPerMtok + script.usage.outputTokens * outputUsdPerMtok) / 1e6) : estimateCostUsd(prompt, input);
383
+ return { mode: "generated", input, scriptCostUsd };
384
+ };
385
+ }
386
+ function exactSpeechInput(prompt) {
387
+ const patterns = [
388
+ /^\s*(?:say|read|speak|narrate)\s+(?:exactly|verbatim)\s*:?\s*([\s\S]+)$/i,
389
+ /^\s*(?:read|say)\s+this\s+(?:exactly|verbatim)\s*:?\s*([\s\S]+)$/i,
390
+ /^\s*(?:exact|literal|verbatim)\s*(?:text|script)?\s*:\s*([\s\S]+)$/i
391
+ ];
392
+ for (const pattern of patterns) {
393
+ const match = prompt.match(pattern);
394
+ const text3 = normalizeSpeechScript(match?.[1] ?? "");
395
+ if (text3) return text3;
396
+ }
397
+ return null;
398
+ }
399
+ function normalizeSpeechScript(value) {
400
+ let text3 = value.trim();
401
+ text3 = text3.replace(/^```(?:text)?\s*/i, "").replace(/\s*```$/i, "").trim();
402
+ text3 = text3.replace(/^(?:script|voiceover|spoken words)\s*:\s*/i, "").trim();
403
+ const quoted = text3.match(/^["'“”‘’]([\s\S]+)["'“”‘’]$/);
404
+ if (quoted?.[1]) text3 = quoted[1].trim();
405
+ return text3;
406
+ }
407
+ function estimateTextTokens(value) {
408
+ return Math.ceil(value.trim().length / 4);
409
+ }
410
+ function roundUsd(value) {
411
+ return Math.round(value * 1e6) / 1e6;
412
+ }
413
+
414
+ // src/media/generation-record.ts
415
+ function metadataResultUrl(value) {
416
+ if (!value || value.startsWith("data:")) return void 0;
417
+ return value;
418
+ }
419
+ function generationMetadata({
420
+ status,
421
+ provider,
422
+ negativePrompt,
423
+ publishPackage,
424
+ resultUrl,
425
+ providerResultUrl,
426
+ ...fields
427
+ }) {
428
+ return {
429
+ generationStatus: status,
430
+ provider,
431
+ negativePrompt: negativePrompt || void 0,
432
+ ...publishPackage ? { publishPackage } : {},
433
+ ...fields,
434
+ resultUrl: metadataResultUrl(resultUrl),
435
+ providerResultUrl: metadataResultUrl(providerResultUrl)
436
+ };
437
+ }
438
+ function browserUsableSourceUrl(source) {
439
+ if (!source || source.authorization) return null;
440
+ return source.url;
441
+ }
442
+ function normalizeProviderJobStatus(value) {
443
+ const record = recordValue(value);
444
+ const rawStatus = text2(record.status) ?? "running";
445
+ const resultUrl = [record, recordValue(record.result), recordValue(record.output)].map((source) => text2(source.video_url) ?? text2(source.url) ?? text2(source.result_url) ?? text2(source.output_url)).find(Boolean);
446
+ const error = text2(record.error) ?? text2(record.message);
447
+ const lower = rawStatus.toLowerCase();
448
+ if (lower === "failed" || lower === "error" || lower === "cancelled") {
449
+ return { status: "failed", providerStatus: rawStatus, error: error ?? `Provider job ${rawStatus}` };
450
+ }
451
+ if (lower === "completed" || lower === "complete" || lower === "succeeded" || lower === "success") {
452
+ if (!resultUrl) {
453
+ return { status: "failed", providerStatus: rawStatus, error: "Provider job completed without a result URL" };
454
+ }
455
+ return { status: "succeeded", providerStatus: rawStatus, resultUrl };
456
+ }
457
+ if (resultUrl) return { status: "succeeded", providerStatus: rawStatus, resultUrl };
458
+ return { status: "running", providerStatus: rawStatus };
459
+ }
460
+ function validProviderImages(value) {
461
+ if (!Array.isArray(value)) return [];
462
+ return value.filter((image) => Boolean(requiredText(image.url) || requiredText(image.b64_json)));
463
+ }
464
+ function providerImageBytes(url, b64Json) {
465
+ const cleanUrl = requiredText(url);
466
+ return cleanUrl?.startsWith("data:") ? imageBytesFromDataUri(cleanUrl) : imageBytesFromBase64(requiredText(b64Json));
467
+ }
468
+ function imageBytesFromDataUri(value) {
469
+ const match = /^data:([^;,]+);base64,(.+)$/s.exec(value);
470
+ if (!match) throw new Error("Image provider returned an unsupported data URI");
471
+ return imageBytesFromBase64(match[2] ?? null, match[1]);
472
+ }
473
+ function imageBytesFromBase64(value, mimeType = "image/png") {
474
+ if (!value) return null;
475
+ try {
476
+ const binary = atob(value);
477
+ const bytes = new Uint8Array(binary.length);
478
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
479
+ return { bytes, mimeType };
480
+ } catch {
481
+ throw new Error("Image provider returned invalid image bytes");
482
+ }
483
+ }
484
+ function recordValue(value) {
485
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
486
+ }
487
+ function text2(value) {
488
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
489
+ }
490
+
491
+ // src/media/model-catalog.ts
492
+ var DEFAULT_CACHE_TTL_MS = 3e5;
493
+ var ENDPOINT_BY_TYPE = {
494
+ image: "images_generations",
495
+ speech: "audio_speech",
496
+ transcription: "audio_transcriptions"
497
+ };
498
+ function createMediaModelCatalog(config) {
499
+ let cache = null;
500
+ function modelFromRouteability(model, type, endpoint = ENDPOINT_BY_TYPE[type]) {
501
+ const id = stringValue(model.id);
502
+ if (!id) return null;
503
+ const endpointStatus = model.routeability?.endpoints?.[endpoint];
504
+ if (!endpointStatus) return null;
505
+ const admission = config.routeability(endpointStatus);
506
+ const inputModalities = stringArray(model.architecture?.input_modalities);
507
+ return {
508
+ id,
509
+ name: stringValue(model.name) ?? id,
510
+ provider: stringValue(model._provider) ?? stringValue(model.provider),
511
+ type,
512
+ status: admission.status,
513
+ reason: admission.reason,
514
+ routeable: endpointStatus.routeable === true,
515
+ inputModalities,
516
+ outputModalities: stringArray(model.architecture?.output_modalities),
517
+ supportedParameters: stringArray(model.supported_parameters),
518
+ source: "models",
519
+ ...config.extraFields?.(model, type, inputModalities)
520
+ };
521
+ }
522
+ function modelFromVideoCatalog(model, type) {
523
+ const id = stringValue(model.id);
524
+ if (!id) return null;
525
+ const admission = config.videoAdmission(model, type);
526
+ const inputModalities = stringArray(model.input_modalities);
527
+ return {
528
+ id,
529
+ name: stringValue(model.name) ?? id,
530
+ provider: stringValue(model.provider),
531
+ type,
532
+ status: admission.status,
533
+ reason: admission.reason,
534
+ routeable: admission.routeable,
535
+ configured: model.configured === true,
536
+ available: model.available === true,
537
+ supportedParameters: stringArray(model.supported_parameters),
538
+ inputModalities,
539
+ outputModalities: stringArray(model.output_modalities),
540
+ source: "videos",
541
+ ...config.extraFields?.(model, type, inputModalities)
542
+ };
543
+ }
544
+ async function buildMediaModelCatalog(routerBaseUrl = config.routerBaseUrl(), routerApiKey) {
545
+ const normalizedBaseUrl = routerBaseUrl.replace(/\/+$/, "").replace(/\/v1$/, "");
546
+ const now = Date.now();
547
+ if (!routerApiKey && cache && cache.routerBaseUrl === normalizedBaseUrl && cache.expiresAt > now) {
548
+ return cache.value;
549
+ }
550
+ const [generalModels, videoModels] = await Promise.all([
551
+ config.fetchRouterModels(normalizedBaseUrl, routerApiKey),
552
+ fetchVideoModels(normalizedBaseUrl)
553
+ ]);
554
+ const { defaults } = config;
555
+ const fromGeneral = (type) => sortMediaModels(
556
+ generalModels.map((model) => modelFromRouteability(model, type)).filter((model) => Boolean(model)),
557
+ defaults[type]
558
+ );
559
+ const fromVideo = (type, capability) => sortMediaModels(
560
+ videoModels.filter((model) => stringValue(model.capability) === capability).map((model) => modelFromVideoCatalog(model, type)).filter((model) => Boolean(model)),
561
+ defaults[type]
562
+ );
563
+ const catalog = {
564
+ defaults,
565
+ models: {
566
+ image: fromGeneral("image"),
567
+ speech: fromGeneral("speech"),
568
+ transcription: fromGeneral("transcription"),
569
+ video: fromVideo("video", "generate"),
570
+ avatar: fromVideo("avatar", "avatar")
571
+ }
572
+ };
573
+ if (!routerApiKey) {
574
+ cache = { routerBaseUrl: normalizedBaseUrl, expiresAt: now + (config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS), value: catalog };
575
+ }
576
+ return catalog;
577
+ }
578
+ async function validateMediaModelSelection(type, modelId, routerApiKey) {
579
+ return checkMediaModelSelection(modelId, `${type} generation`, async (id) => {
580
+ const catalog = await buildMediaModelCatalog(config.routerBaseUrl(), routerApiKey);
581
+ return catalog.models[type].find((option) => option.id === id);
582
+ });
583
+ }
584
+ return {
585
+ buildMediaModelCatalog,
586
+ validateMediaModelSelection,
587
+ modelFromRouteability,
588
+ clearMediaModelCatalogCache: () => {
589
+ cache = null;
590
+ }
591
+ };
592
+ }
593
+ async function checkMediaModelSelection(modelId, purpose, lookup) {
594
+ const id = modelId.trim();
595
+ if (!id) return { succeeded: false, error: `model is required for ${purpose}` };
596
+ const model = await lookup(id);
597
+ if (!model) return { succeeded: false, error: `Model "${id}" is not available for ${purpose}` };
598
+ if (model.status === "unavailable") {
599
+ return {
600
+ succeeded: false,
601
+ error: `Model "${id}" is unavailable for ${purpose}${model.reason ? `: ${model.reason}` : ""}`
602
+ };
603
+ }
604
+ return { succeeded: true, value: model };
605
+ }
606
+ async function fetchVideoModels(routerBaseUrl) {
607
+ const response = await fetch(`${routerV1Url(routerBaseUrl)}/videos/models`);
608
+ if (!response.ok) {
609
+ throw new Error(`Could not load video models: ${response.status} ${await routerResponseErrorMessage(response)}`);
610
+ }
611
+ const data = await response.json();
612
+ return Array.isArray(data.data) ? data.data : [];
613
+ }
614
+ function sortMediaModels(models, preferredId) {
615
+ const statusWeight = { available: 0, limited: 1, unavailable: 2 };
616
+ return [...models].sort((a, b) => {
617
+ if (a.id === preferredId) return -1;
618
+ if (b.id === preferredId) return 1;
619
+ const statusDiff = statusWeight[a.status] - statusWeight[b.status];
620
+ if (statusDiff !== 0) return statusDiff;
621
+ return a.id.localeCompare(b.id);
622
+ });
623
+ }
624
+ function stringArray(value) {
625
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string" && item.trim().length > 0) : [];
626
+ }
627
+ function stringValue(value) {
628
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
629
+ }
630
+ export {
631
+ RouterHttpError,
632
+ browserUsableSourceUrl,
633
+ checkMediaModelSelection,
634
+ createMediaModelCatalog,
635
+ createRouterGeneration,
636
+ createRouterMediaClient,
637
+ createSpeechScriptResolver,
638
+ fetchBoundedAudio,
639
+ generationMetadata,
640
+ imageCountForRequest,
641
+ metadataResultUrl,
642
+ modelForRequest,
643
+ normalizeProviderJobStatus,
644
+ optionalHttpsUrl,
645
+ providerImageBytes,
646
+ requiredText,
647
+ routerResponseErrorMessage,
648
+ routerV1Url,
649
+ validProviderImages,
650
+ validateGenerateRequest,
651
+ validatePublicHttpUrl
652
+ };
653
+ //# sourceMappingURL=index.js.map