@stackfactor/agent-utils 1.13.3 → 1.32.0

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 (253) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +667 -23
  3. package/dist/cjs/agentProto.d.ts +13 -3
  4. package/dist/cjs/agentProto.d.ts.map +1 -1
  5. package/dist/cjs/agentProto.js +25 -4
  6. package/dist/cjs/backoff.d.ts +17 -0
  7. package/dist/cjs/backoff.d.ts.map +1 -0
  8. package/dist/cjs/backoff.js +26 -0
  9. package/dist/cjs/cancellation.d.ts +22 -0
  10. package/dist/cjs/cancellation.d.ts.map +1 -0
  11. package/dist/cjs/cancellation.js +36 -0
  12. package/dist/cjs/cli.d.ts +3 -0
  13. package/dist/cjs/cli.d.ts.map +1 -0
  14. package/dist/cjs/cli.js +85 -0
  15. package/dist/cjs/client.d.ts +11 -0
  16. package/dist/cjs/client.d.ts.map +1 -1
  17. package/dist/cjs/client.js +27 -0
  18. package/dist/cjs/const.d.ts +23 -0
  19. package/dist/cjs/const.d.ts.map +1 -1
  20. package/dist/cjs/const.js +23 -0
  21. package/dist/cjs/daemon.d.ts +94 -0
  22. package/dist/cjs/daemon.d.ts.map +1 -0
  23. package/dist/cjs/daemon.js +507 -0
  24. package/dist/cjs/daemonConfig.d.ts +45 -0
  25. package/dist/cjs/daemonConfig.d.ts.map +1 -0
  26. package/dist/cjs/daemonConfig.js +148 -0
  27. package/dist/cjs/daemonEnv.d.ts +10 -0
  28. package/dist/cjs/daemonEnv.d.ts.map +1 -0
  29. package/dist/cjs/daemonEnv.js +12 -0
  30. package/dist/cjs/durable/clientTool.d.ts +39 -0
  31. package/dist/cjs/durable/clientTool.d.ts.map +1 -0
  32. package/dist/cjs/durable/clientTool.js +90 -0
  33. package/dist/cjs/durable/index.d.ts +9 -0
  34. package/dist/cjs/durable/index.d.ts.map +1 -0
  35. package/dist/cjs/durable/index.js +16 -0
  36. package/dist/cjs/durable/journal.d.ts +218 -0
  37. package/dist/cjs/durable/journal.d.ts.map +1 -0
  38. package/dist/cjs/durable/journal.js +392 -0
  39. package/dist/cjs/durable/pause.d.ts +84 -0
  40. package/dist/cjs/durable/pause.d.ts.map +1 -0
  41. package/dist/cjs/durable/pause.js +241 -0
  42. package/dist/cjs/durable/resume.d.ts +27 -0
  43. package/dist/cjs/durable/resume.d.ts.map +1 -0
  44. package/dist/cjs/durable/resume.js +80 -0
  45. package/dist/cjs/durable/snapshotSaver.d.ts +38 -0
  46. package/dist/cjs/durable/snapshotSaver.d.ts.map +1 -0
  47. package/dist/cjs/durable/snapshotSaver.js +81 -0
  48. package/dist/cjs/durable/step.d.ts +28 -0
  49. package/dist/cjs/durable/step.d.ts.map +1 -0
  50. package/dist/cjs/durable/step.js +43 -0
  51. package/dist/cjs/index.d.ts +30 -7
  52. package/dist/cjs/index.d.ts.map +1 -1
  53. package/dist/cjs/index.js +28 -1
  54. package/dist/cjs/infrastructure.d.ts +50 -0
  55. package/dist/cjs/infrastructure.d.ts.map +1 -0
  56. package/dist/cjs/infrastructure.js +163 -0
  57. package/dist/cjs/langChain.d.ts +15 -3
  58. package/dist/cjs/langChain.d.ts.map +1 -1
  59. package/dist/cjs/langChain.js +986 -180
  60. package/dist/cjs/learningActivityMedia.d.ts +196 -0
  61. package/dist/cjs/learningActivityMedia.d.ts.map +1 -0
  62. package/dist/cjs/learningActivityMedia.js +861 -0
  63. package/dist/cjs/learningContentPlan.d.ts +105 -0
  64. package/dist/cjs/learningContentPlan.d.ts.map +1 -0
  65. package/dist/cjs/learningContentPlan.js +305 -0
  66. package/dist/cjs/learningContentThread.d.ts +184 -0
  67. package/dist/cjs/learningContentThread.d.ts.map +1 -0
  68. package/dist/cjs/learningContentThread.js +407 -0
  69. package/dist/cjs/logger.d.ts +1 -0
  70. package/dist/cjs/logger.d.ts.map +1 -1
  71. package/dist/cjs/logger.js +17 -3
  72. package/dist/cjs/modelRates.d.ts +40 -0
  73. package/dist/cjs/modelRates.d.ts.map +1 -0
  74. package/dist/cjs/modelRates.js +76 -0
  75. package/dist/cjs/referenceContext.d.ts +4 -145
  76. package/dist/cjs/referenceContext.d.ts.map +1 -1
  77. package/dist/cjs/referenceContext.js +16 -251
  78. package/dist/cjs/retry.d.ts +64 -0
  79. package/dist/cjs/retry.d.ts.map +1 -0
  80. package/dist/cjs/retry.js +138 -0
  81. package/dist/cjs/runtimeContext.d.ts +8 -1
  82. package/dist/cjs/runtimeContext.d.ts.map +1 -1
  83. package/dist/cjs/runtimeContext.js +3 -1
  84. package/dist/cjs/serve.d.ts +3 -2
  85. package/dist/cjs/serve.d.ts.map +1 -1
  86. package/dist/cjs/serve.js +32 -2
  87. package/dist/cjs/sourceStore.d.ts +378 -0
  88. package/dist/cjs/sourceStore.d.ts.map +1 -0
  89. package/dist/cjs/sourceStore.js +872 -0
  90. package/dist/cjs/stackfactorKnowledge.d.ts +91 -7
  91. package/dist/cjs/stackfactorKnowledge.d.ts.map +1 -1
  92. package/dist/cjs/stackfactorKnowledge.js +108 -44
  93. package/dist/cjs/tavily.d.ts +108 -4
  94. package/dist/cjs/tavily.d.ts.map +1 -1
  95. package/dist/cjs/tavily.js +242 -21
  96. package/dist/cjs/usage.d.ts.map +1 -1
  97. package/dist/cjs/usage.js +9 -15
  98. package/dist/cjs/version.d.ts +3 -0
  99. package/dist/cjs/version.d.ts.map +1 -0
  100. package/dist/cjs/version.js +5 -0
  101. package/dist/cjs/workflow/bookkeeping.d.ts +78 -0
  102. package/dist/cjs/workflow/bookkeeping.d.ts.map +1 -0
  103. package/dist/cjs/workflow/bookkeeping.js +75 -0
  104. package/dist/cjs/workflow/index.d.ts +13 -0
  105. package/dist/cjs/workflow/index.d.ts.map +1 -0
  106. package/dist/cjs/workflow/index.js +51 -0
  107. package/dist/cjs/workflow/limits.d.ts +52 -0
  108. package/dist/cjs/workflow/limits.d.ts.map +1 -0
  109. package/dist/cjs/workflow/limits.js +62 -0
  110. package/dist/cjs/workflow/platformTransport.d.ts +39 -0
  111. package/dist/cjs/workflow/platformTransport.d.ts.map +1 -0
  112. package/dist/cjs/workflow/platformTransport.js +115 -0
  113. package/dist/cjs/workflow/retrying.d.ts +44 -0
  114. package/dist/cjs/workflow/retrying.d.ts.map +1 -0
  115. package/dist/cjs/workflow/retrying.js +82 -0
  116. package/dist/cjs/workflow/run.d.ts +195 -0
  117. package/dist/cjs/workflow/run.d.ts.map +1 -0
  118. package/dist/cjs/workflow/run.js +858 -0
  119. package/dist/cjs/workflow/testing/index.d.ts +3 -0
  120. package/dist/cjs/workflow/testing/index.d.ts.map +1 -0
  121. package/dist/cjs/workflow/testing/index.js +6 -0
  122. package/dist/cjs/workflow/testing/memoryTransport.d.ts +203 -0
  123. package/dist/cjs/workflow/testing/memoryTransport.d.ts.map +1 -0
  124. package/dist/cjs/workflow/testing/memoryTransport.js +1171 -0
  125. package/dist/cjs/workflow/transport.d.ts +219 -0
  126. package/dist/cjs/workflow/transport.d.ts.map +1 -0
  127. package/dist/cjs/workflow/transport.js +19 -0
  128. package/dist/esm/agentProto.d.ts +13 -3
  129. package/dist/esm/agentProto.d.ts.map +1 -1
  130. package/dist/esm/agentProto.js +23 -3
  131. package/dist/esm/backoff.d.ts +17 -0
  132. package/dist/esm/backoff.d.ts.map +1 -0
  133. package/dist/esm/backoff.js +22 -0
  134. package/dist/esm/cancellation.d.ts +22 -0
  135. package/dist/esm/cancellation.d.ts.map +1 -0
  136. package/dist/esm/cancellation.js +27 -0
  137. package/dist/esm/cli.d.ts +3 -0
  138. package/dist/esm/cli.d.ts.map +1 -0
  139. package/dist/esm/cli.js +80 -0
  140. package/dist/esm/client.d.ts +11 -0
  141. package/dist/esm/client.d.ts.map +1 -1
  142. package/dist/esm/client.js +25 -1
  143. package/dist/esm/const.d.ts +23 -0
  144. package/dist/esm/const.d.ts.map +1 -1
  145. package/dist/esm/const.js +23 -0
  146. package/dist/esm/daemon.d.ts +94 -0
  147. package/dist/esm/daemon.d.ts.map +1 -0
  148. package/dist/esm/daemon.js +499 -0
  149. package/dist/esm/daemonConfig.d.ts +45 -0
  150. package/dist/esm/daemonConfig.d.ts.map +1 -0
  151. package/dist/esm/daemonConfig.js +142 -0
  152. package/dist/esm/daemonEnv.d.ts +10 -0
  153. package/dist/esm/daemonEnv.d.ts.map +1 -0
  154. package/dist/esm/daemonEnv.js +9 -0
  155. package/dist/esm/durable/clientTool.d.ts +39 -0
  156. package/dist/esm/durable/clientTool.d.ts.map +1 -0
  157. package/dist/esm/durable/clientTool.js +82 -0
  158. package/dist/esm/durable/index.d.ts +9 -0
  159. package/dist/esm/durable/index.d.ts.map +1 -0
  160. package/dist/esm/durable/index.js +8 -0
  161. package/dist/esm/durable/journal.d.ts +218 -0
  162. package/dist/esm/durable/journal.d.ts.map +1 -0
  163. package/dist/esm/durable/journal.js +374 -0
  164. package/dist/esm/durable/pause.d.ts +84 -0
  165. package/dist/esm/durable/pause.d.ts.map +1 -0
  166. package/dist/esm/durable/pause.js +226 -0
  167. package/dist/esm/durable/resume.d.ts +27 -0
  168. package/dist/esm/durable/resume.d.ts.map +1 -0
  169. package/dist/esm/durable/resume.js +72 -0
  170. package/dist/esm/durable/snapshotSaver.d.ts +38 -0
  171. package/dist/esm/durable/snapshotSaver.d.ts.map +1 -0
  172. package/dist/esm/durable/snapshotSaver.js +77 -0
  173. package/dist/esm/durable/step.d.ts +28 -0
  174. package/dist/esm/durable/step.d.ts.map +1 -0
  175. package/dist/esm/durable/step.js +36 -0
  176. package/dist/esm/index.d.ts +30 -7
  177. package/dist/esm/index.d.ts.map +1 -1
  178. package/dist/esm/index.js +20 -4
  179. package/dist/esm/infrastructure.d.ts +50 -0
  180. package/dist/esm/infrastructure.d.ts.map +1 -0
  181. package/dist/esm/infrastructure.js +156 -0
  182. package/dist/esm/langChain.d.ts +15 -3
  183. package/dist/esm/langChain.d.ts.map +1 -1
  184. package/dist/esm/langChain.js +984 -179
  185. package/dist/esm/learningActivityMedia.d.ts +196 -0
  186. package/dist/esm/learningActivityMedia.d.ts.map +1 -0
  187. package/dist/esm/learningActivityMedia.js +807 -0
  188. package/dist/esm/learningContentPlan.d.ts +105 -0
  189. package/dist/esm/learningContentPlan.d.ts.map +1 -0
  190. package/dist/esm/learningContentPlan.js +299 -0
  191. package/dist/esm/learningContentThread.d.ts +184 -0
  192. package/dist/esm/learningContentThread.d.ts.map +1 -0
  193. package/dist/esm/learningContentThread.js +364 -0
  194. package/dist/esm/logger.d.ts +1 -0
  195. package/dist/esm/logger.d.ts.map +1 -1
  196. package/dist/esm/logger.js +17 -3
  197. package/dist/esm/modelRates.d.ts +40 -0
  198. package/dist/esm/modelRates.d.ts.map +1 -0
  199. package/dist/esm/modelRates.js +68 -0
  200. package/dist/esm/referenceContext.d.ts +4 -145
  201. package/dist/esm/referenceContext.d.ts.map +1 -1
  202. package/dist/esm/referenceContext.js +16 -243
  203. package/dist/esm/retry.d.ts +64 -0
  204. package/dist/esm/retry.d.ts.map +1 -0
  205. package/dist/esm/retry.js +127 -0
  206. package/dist/esm/runtimeContext.d.ts +8 -1
  207. package/dist/esm/runtimeContext.d.ts.map +1 -1
  208. package/dist/esm/runtimeContext.js +3 -1
  209. package/dist/esm/serve.d.ts +3 -2
  210. package/dist/esm/serve.d.ts.map +1 -1
  211. package/dist/esm/serve.js +33 -3
  212. package/dist/esm/sourceStore.d.ts +378 -0
  213. package/dist/esm/sourceStore.d.ts.map +1 -0
  214. package/dist/esm/sourceStore.js +855 -0
  215. package/dist/esm/stackfactorKnowledge.d.ts +91 -7
  216. package/dist/esm/stackfactorKnowledge.d.ts.map +1 -1
  217. package/dist/esm/stackfactorKnowledge.js +101 -41
  218. package/dist/esm/tavily.d.ts +108 -4
  219. package/dist/esm/tavily.d.ts.map +1 -1
  220. package/dist/esm/tavily.js +237 -20
  221. package/dist/esm/usage.d.ts.map +1 -1
  222. package/dist/esm/usage.js +9 -15
  223. package/dist/esm/version.d.ts +3 -0
  224. package/dist/esm/version.d.ts.map +1 -0
  225. package/dist/esm/version.js +2 -0
  226. package/dist/esm/workflow/bookkeeping.d.ts +78 -0
  227. package/dist/esm/workflow/bookkeeping.d.ts.map +1 -0
  228. package/dist/esm/workflow/bookkeeping.js +67 -0
  229. package/dist/esm/workflow/index.d.ts +13 -0
  230. package/dist/esm/workflow/index.d.ts.map +1 -0
  231. package/dist/esm/workflow/index.js +10 -0
  232. package/dist/esm/workflow/limits.d.ts +52 -0
  233. package/dist/esm/workflow/limits.d.ts.map +1 -0
  234. package/dist/esm/workflow/limits.js +59 -0
  235. package/dist/esm/workflow/platformTransport.d.ts +39 -0
  236. package/dist/esm/workflow/platformTransport.d.ts.map +1 -0
  237. package/dist/esm/workflow/platformTransport.js +110 -0
  238. package/dist/esm/workflow/retrying.d.ts +44 -0
  239. package/dist/esm/workflow/retrying.d.ts.map +1 -0
  240. package/dist/esm/workflow/retrying.js +73 -0
  241. package/dist/esm/workflow/run.d.ts +195 -0
  242. package/dist/esm/workflow/run.d.ts.map +1 -0
  243. package/dist/esm/workflow/run.js +850 -0
  244. package/dist/esm/workflow/testing/index.d.ts +3 -0
  245. package/dist/esm/workflow/testing/index.d.ts.map +1 -0
  246. package/dist/esm/workflow/testing/index.js +2 -0
  247. package/dist/esm/workflow/testing/memoryTransport.d.ts +203 -0
  248. package/dist/esm/workflow/testing/memoryTransport.d.ts.map +1 -0
  249. package/dist/esm/workflow/testing/memoryTransport.js +1167 -0
  250. package/dist/esm/workflow/transport.d.ts +219 -0
  251. package/dist/esm/workflow/transport.d.ts.map +1 -0
  252. package/dist/esm/workflow/transport.js +16 -0
  253. package/package.json +11 -9
@@ -0,0 +1,807 @@
1
+ // The media of a generated learning activity: a video, or a text page.
2
+ //
3
+ // An activity is written with prompts where its pictures, clips and films go,
4
+ // and, for a video, with a narration script per scene. `generateActivityMedia`
5
+ // makes each of them, stores it as media of the activity, and gives the element
6
+ // the id of what was stored (`{ _id, set: true }`): the content never carries a
7
+ // file. Whoever shows the activity downloads each file by that id.
8
+ //
9
+ // It is what the agent that writes an activity runs once the activity is
10
+ // written, when its caller named where the media belongs (`ActivityMediaTarget`).
11
+ // The caller is the editor, the learning content job, or another agent: none of
12
+ // them generates media itself.
13
+ //
14
+ // Every generation goes through the platform (`contentGenerator.generateContent`
15
+ // with the run's token), which picks the integration, configures it for the
16
+ // tenant and charges what it used. Every file is stored through the routes
17
+ // anyone stores an activity's media with, so the token's permissions decide
18
+ // whether it may be.
19
+ //
20
+ // Nothing here fails the activity. An element whose media could not be made
21
+ // keeps its prompt and shows its placeholder; a scene whose narration could not
22
+ // be prepared is synthesised when it is first played. What was not made is in
23
+ // the summary.
24
+ import { gzipSync } from "node:zlib";
25
+ import { randomBytes } from "node:crypto";
26
+ import { contentGenerator, learningContent, tenant } from "@stackfactor/client-api";
27
+ import logger from "./logger.js";
28
+ /** The choice that turns one kind of media off. */
29
+ export const NO_MEDIA_INTEGRATION = "NONE";
30
+ const PNG = "image/png";
31
+ const JPEG = "image/jpeg";
32
+ const JPEG_QUALITY = 85;
33
+ const MP4 = "video/mp4";
34
+ // A film is stored compressed and never as text/html: media is streamed back
35
+ // with the type it was saved with, and an HTML page served from the platform's
36
+ // own origin would run there. The player unpacks it into a sandboxed frame.
37
+ const GZIP = "application/gzip";
38
+ // A clip is asked for at one of the two lengths every video provider accepts,
39
+ // chosen from how much narration its scene carries. A clip that outruns its
40
+ // narration holds on a still frame; narration that outruns its clip plays over
41
+ // a loop. The first is cheaper and calmer, so a short line gets the short
42
+ // clip, and a scene that says nothing gets the long one.
43
+ const CLIP_SHORT_NARRATION_WORDS = 10;
44
+ const CLIP_SECONDS_SHORT = 4;
45
+ const CLIP_SECONDS_LONG = 8;
46
+ // A clip is a provider job that holds its slot for minutes, where an image
47
+ // answers in seconds.
48
+ const CLIP_CONCURRENCY = 2;
49
+ const IMAGE_CONCURRENCY = 10;
50
+ const NARRATION_CONCURRENCY = 3;
51
+ const DEFAULT_RETRIES = 1;
52
+ const DEFAULT_GENERATION_TIMEOUT_SECONDS = 900;
53
+ // How fast the narrator speaks, for timing a scene's film to its narration.
54
+ const NARRATION_WORDS_PER_SECOND = 2.5;
55
+ // The frame a film under its scene's title is laid out in: the space below a
56
+ // one-line title and subtitle, at the frame's full width (the player's titled
57
+ // stage). Without a title, the film fills the Full HD frame.
58
+ const TITLED_FRAME = { width: 1920, height: 903 };
59
+ const warn = (message) => logger.log(null, logger.levels.warn, message);
60
+ const messageOfError = (error) => {
61
+ const message = error?.message ?? error;
62
+ return typeof message === "string" ? message : JSON.stringify(message);
63
+ };
64
+ // ---------------------------------------------------------------------------
65
+ // Ids
66
+ // ---------------------------------------------------------------------------
67
+ // An id the platform stores as a MongoDB ObjectId: 4 bytes of time, 5 random
68
+ // bytes fixed for the process, and a 3-byte counter that starts at random. Ids
69
+ // are minted here because what is stored is keyed on them before the document
70
+ // that holds them is saved.
71
+ const processBytes = randomBytes(5).toString("hex");
72
+ let counter = randomBytes(3).readUIntBE(0, 3);
73
+ /** A new id, as 24 hexadecimal characters. */
74
+ export const newMediaId = () => {
75
+ counter = (counter + 1) % 0x1000000;
76
+ const seconds = Math.floor(Date.now() / 1000) % 0x100000000;
77
+ return (seconds.toString(16).padStart(8, "0") + processBytes + counter.toString(16).padStart(6, "0"));
78
+ };
79
+ // ---------------------------------------------------------------------------
80
+ // Scenes
81
+ // ---------------------------------------------------------------------------
82
+ /** A list, whatever form the collection arrived in (an array, or an object keyed by index). */
83
+ const toArray = (value) => {
84
+ if (Array.isArray(value))
85
+ return value;
86
+ if (value && typeof value === "object")
87
+ return Object.values(value);
88
+ return [];
89
+ };
90
+ /** What holds a video's scenes, or null when it has none. */
91
+ export const sceneContainerOf = (videoContent) => [videoContent?.videoContent, videoContent?.content, videoContent].find((container) => container?.scenes) ?? null;
92
+ /** The scenes of a video, in order. */
93
+ export const scenesOf = (videoContent) => toArray(sceneContainerOf(videoContent)?.scenes);
94
+ /** The lines a scene's narrator says. */
95
+ export const narrationOf = (scene) => toArray(scene?.audioScript?.items)
96
+ .map((item) => item?.text)
97
+ .filter((text) => typeof text === "string" && text.trim().length > 0);
98
+ const narrationWordsOf = (scene) => narrationOf(scene).join(" ").split(/\s+/).filter(Boolean).length;
99
+ // Every element of a tree that holds media, wherever it is nested. The walk
100
+ // goes through every property of every node: an image inside a layout element
101
+ // (a grid, columns) is stored under a shape a walk of `props.items` alone
102
+ // would miss. The ids are the ones client-api's `extractImagePrompts` gives.
103
+ const mediaElementsOf = (tree) => {
104
+ const found = [];
105
+ const walk = (node) => {
106
+ if (node === null || typeof node !== "object")
107
+ return;
108
+ if (Array.isArray(node)) {
109
+ node.forEach(walk);
110
+ return;
111
+ }
112
+ const type = typeof node.type === "string" ? node.type : "";
113
+ const id = typeof node.props?.id === "string" ? node.props.id : null;
114
+ if ((type === "Image" || type === "Orbit") && id) {
115
+ found.push({ id, kind: "image", holder: node.props, field: "image" });
116
+ }
117
+ if (type === "Video" && id) {
118
+ found.push({ id, kind: "videoClip", holder: node.props, field: "video" });
119
+ }
120
+ if (type === "FlippableCards" && Array.isArray(node.props?.items)) {
121
+ node.props.items.forEach((card, index) => {
122
+ if (!card || typeof card !== "object")
123
+ return;
124
+ found.push({
125
+ id: typeof card._id === "string" ? card._id : `${id}_item_${index}`,
126
+ kind: "image",
127
+ holder: card,
128
+ field: "image",
129
+ fixed: true,
130
+ });
131
+ });
132
+ }
133
+ Object.values(node).forEach(walk);
134
+ };
135
+ walk(tree);
136
+ return found;
137
+ };
138
+ /** Every prompt of a tree whose element has no media yet, once each. */
139
+ export const mediaPromptsOf = (tree) => {
140
+ const seen = new Set();
141
+ const prompts = [];
142
+ for (const { id, kind, holder, field } of mediaElementsOf(tree)) {
143
+ const prompt = typeof holder[field]?.prompt === "string" ? holder[field].prompt.trim() : "";
144
+ if (!prompt || holder[field]?.set || seen.has(id))
145
+ continue;
146
+ seen.add(id);
147
+ prompts.push({ id, prompt, kind });
148
+ }
149
+ return prompts;
150
+ };
151
+ /** Gives each element the id of the media stored for it; the tree is changed in place. */
152
+ export const applyStoredMedia = (tree, stored) => {
153
+ if (stored.length === 0)
154
+ return;
155
+ const mediaIds = new Map(stored.map(({ id, _id }) => [id, _id]));
156
+ for (const { id, holder, field, fixed } of mediaElementsOf(tree)) {
157
+ const mediaId = mediaIds.get(id);
158
+ if (!mediaId)
159
+ continue;
160
+ if (!holder[field]) {
161
+ if (fixed)
162
+ continue;
163
+ holder[field] = {};
164
+ }
165
+ holder[field]._id = mediaId;
166
+ holder[field].set = true;
167
+ }
168
+ };
169
+ /** How long the clip of each Video element is, by prompt id: it follows its scene's narration. */
170
+ export const clipSecondsOf = (videoContent) => {
171
+ const seconds = new Map();
172
+ for (const scene of scenesOf(videoContent)) {
173
+ const words = narrationWordsOf(scene);
174
+ const length = words > 0 && words <= CLIP_SHORT_NARRATION_WORDS ? CLIP_SECONDS_SHORT : CLIP_SECONDS_LONG;
175
+ mediaElementsOf(scene?.content)
176
+ .filter(({ kind }) => kind === "videoClip")
177
+ .forEach(({ id }) => seconds.set(id, length));
178
+ }
179
+ return seconds;
180
+ };
181
+ /** The bytes of what a generator answered with, whatever form they travelled in. */
182
+ export const bytesOf = (raw) => {
183
+ if (Buffer.isBuffer(raw))
184
+ return raw;
185
+ if (raw instanceof ArrayBuffer)
186
+ return Buffer.from(raw);
187
+ if (ArrayBuffer.isView(raw))
188
+ return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength);
189
+ if (raw?.type === "Buffer" && Array.isArray(raw.data))
190
+ return Buffer.from(raw.data);
191
+ throw new Error("The generator answered with something that is not a file");
192
+ };
193
+ // The image models answer in PNG, the wrong format for the photographs and
194
+ // illustrations they make: the same pixels as JPEG are typically ten times
195
+ // smaller, and the bytes are the wait. PNG is kept when JPEG would be wrong or
196
+ // pointless: an image that uses its transparency, one that cannot be decoded,
197
+ // one that does not come out smaller. `sharp` does the work and is the agent's
198
+ // own dependency: an agent without it stores images as they were generated.
199
+ const deliverImage = async (original) => {
200
+ try {
201
+ // Named through a variable so the package builds without sharp installed.
202
+ const name = "sharp";
203
+ const loaded = await import(name);
204
+ const sharp = loaded.default ?? loaded;
205
+ // Whether the alpha channel is used, not whether there is one: there almost always is.
206
+ if (!(await sharp(original).stats()).isOpaque)
207
+ return { buffer: original, mimeType: PNG };
208
+ const encoded = await sharp(original)
209
+ .jpeg({ quality: JPEG_QUALITY, mozjpeg: true })
210
+ .toBuffer();
211
+ return encoded.length < original.length
212
+ ? { buffer: encoded, mimeType: JPEG }
213
+ : { buffer: original, mimeType: PNG };
214
+ }
215
+ catch (error) {
216
+ warn(`Could not re-encode a generated image (${messageOfError(error)}); storing it as generated`);
217
+ return { buffer: original, mimeType: PNG };
218
+ }
219
+ };
220
+ /** Every Motion Graphic of a tree with a brief and no film yet, wherever it is nested. */
221
+ export const motionGraphicsOf = (tree) => {
222
+ const found = [];
223
+ const seen = new Set();
224
+ const walk = (node) => {
225
+ if (node === null || typeof node !== "object")
226
+ return;
227
+ if (Array.isArray(node)) {
228
+ node.forEach(walk);
229
+ return;
230
+ }
231
+ const props = node.props;
232
+ const motionGraphic = props?.motionGraphic;
233
+ const prompt = typeof motionGraphic?.prompt === "string" ? motionGraphic.prompt.trim() : "";
234
+ if (node.type === "MotionGraphic" &&
235
+ typeof props?.id === "string" &&
236
+ prompt &&
237
+ !motionGraphic.set &&
238
+ !seen.has(props.id)) {
239
+ seen.add(props.id);
240
+ found.push({ id: props.id, holder: props, prompt });
241
+ }
242
+ Object.values(node).forEach(walk);
243
+ };
244
+ walk(tree);
245
+ return found;
246
+ };
247
+ /**
248
+ * How long the film of each Motion Graphic of a video runs, by element id. It
249
+ * plays under its scene's narration, so it is timed to it; a scene that says
250
+ * nothing leaves the length to the generator.
251
+ */
252
+ export const filmSecondsOf = (videoContent) => {
253
+ const seconds = new Map();
254
+ for (const scene of scenesOf(videoContent)) {
255
+ const words = narrationWordsOf(scene);
256
+ if (words === 0)
257
+ continue;
258
+ const length = Math.ceil(words / NARRATION_WORDS_PER_SECOND);
259
+ motionGraphicsOf(scene?.content).forEach(({ id }) => seconds.set(id, length));
260
+ }
261
+ return seconds;
262
+ };
263
+ /** Whether a video scene shows its title around its film: it has a title or a subtitle. */
264
+ const titledScene = (scene) => [scene?.root?.props?.title, scene?.root?.props?.subTitle].some((text) => typeof text === "string" && text.trim() !== "");
265
+ /** The film's chapters, as the element keeps them; none for a generator that does not send them. */
266
+ const chaptersOf = (response) => Array.isArray(response?.chapters)
267
+ ? response.chapters.map((chapter, index) => ({
268
+ index,
269
+ name: chapter?.name || "",
270
+ narration: chapter?.narration || "",
271
+ startSeconds: Number(chapter?.startSeconds) || 0,
272
+ durationSeconds: Number(chapter?.durationSeconds) || 0,
273
+ }))
274
+ : [];
275
+ /** The frame the film was laid out in, or null for a generator that does not say. */
276
+ const frameOf = (response) => {
277
+ const width = Number(response?.frame?.width);
278
+ const height = Number(response?.frame?.height);
279
+ return width > 0 && height > 0 ? { width, height } : null;
280
+ };
281
+ /**
282
+ * Makes a film's narration its scene's: one line per chapter, each line's
283
+ * start action bound to the film. The scene keeps its audioScript's id.
284
+ */
285
+ const applyNarration = (scene, elementId, audioScript, newId) => {
286
+ const items = Array.isArray(audioScript?.items) ? audioScript.items : [];
287
+ if (!scene || items.length === 0)
288
+ return;
289
+ scene.audioScript = {
290
+ ...(scene.audioScript || {}),
291
+ _id: scene.audioScript?._id || newId(),
292
+ items: items.map((item) => ({
293
+ ...item,
294
+ startActions: (item.startActions || []).map((action) => ({ ...action, elementId })),
295
+ })),
296
+ };
297
+ };
298
+ /** The page of what the Motion Graphic generator answered, in whichever shape. */
299
+ export const htmlOf = (response) => {
300
+ const html = typeof response === "string" ? response : response?.html;
301
+ if (typeof html !== "string" || !html.trim()) {
302
+ throw new Error("The Motion Graphic generator answered without a page");
303
+ }
304
+ return html;
305
+ };
306
+ // The look a film is generated in: the colours and font of the content around
307
+ // it, so it reads as part of that video or page.
308
+ /** The app's own colours, for a tenant that has not set its own. */
309
+ const LOOK_DEFAULTS = {
310
+ paperColor: "#ffffff",
311
+ primaryColor: "#255583",
312
+ textPrimaryColor: "#0f172a",
313
+ textSecondaryColor: "#64748b",
314
+ };
315
+ /** Video scenes and text pages are set in Roboto. */
316
+ const CONTENT_FONT = "Roboto, Helvetica, Arial, sans-serif";
317
+ /** How many accents are sent; the most used come first. */
318
+ const MAX_ACCENTS = 6;
319
+ /** Props that hold an element's colour, on the element or on its items. */
320
+ const COLOR_PROPS = ["accentColor", "color"];
321
+ const HEX = /^#[0-9a-f]{3,8}$/i;
322
+ const brandColor = (lookNFeel, key) => {
323
+ const value = lookNFeel?.[key];
324
+ return typeof value === "string" && HEX.test(value.trim())
325
+ ? value.trim().toLowerCase()
326
+ : LOOK_DEFAULTS[key];
327
+ };
328
+ // Counts every explicit colour in a content tree. "default" is the tenant's
329
+ // primary; named colours an element resolves itself are left out.
330
+ const countColors = (node, primary, counts) => {
331
+ if (Array.isArray(node)) {
332
+ node.forEach((child) => countColors(child, primary, counts));
333
+ return;
334
+ }
335
+ if (!node || typeof node !== "object")
336
+ return;
337
+ for (const [key, value] of Object.entries(node)) {
338
+ if (COLOR_PROPS.includes(key)) {
339
+ const color = value === "default"
340
+ ? primary
341
+ : typeof value === "string" && HEX.test(value)
342
+ ? value.toLowerCase()
343
+ : null;
344
+ if (color)
345
+ counts.set(color, (counts.get(color) || 0) + 1);
346
+ }
347
+ else if (value && typeof value === "object") {
348
+ countColors(value, primary, counts);
349
+ }
350
+ }
351
+ };
352
+ /** The background most of a video's scenes are drawn on. */
353
+ const commonBackground = (scenes, paper) => {
354
+ const counts = new Map();
355
+ scenes.forEach((scene) => {
356
+ const color = scene?.root?.props?.backgroundColor || paper;
357
+ counts.set(color, (counts.get(color) || 0) + 1);
358
+ });
359
+ let best = paper;
360
+ let most = 0;
361
+ counts.forEach((count, color) => {
362
+ if (count > most)
363
+ [best, most] = [color, count];
364
+ });
365
+ return best;
366
+ };
367
+ /**
368
+ * The look to generate an activity's Motion Graphics in.
369
+ * @param lookNFeel The tenant's look and feel; null for the app's defaults
370
+ * @param content The activity's `videoContent` or `textContent`
371
+ * @param scenes A video's scenes; null for a text page
372
+ */
373
+ export const motionGraphicStyle = (lookNFeel, content, scenes) => {
374
+ const paper = brandColor(lookNFeel, "paperColor");
375
+ const primary = brandColor(lookNFeel, "primaryColor");
376
+ const counts = new Map();
377
+ countColors(content, primary, counts);
378
+ const accents = [primary, ...[...counts.entries()].sort((a, b) => b[1] - a[1]).map(([c]) => c)];
379
+ return {
380
+ background: scenes ? commonBackground(scenes, paper) : paper,
381
+ text: brandColor(lookNFeel, "textPrimaryColor"),
382
+ mutedText: brandColor(lookNFeel, "textSecondaryColor"),
383
+ primary,
384
+ accents: [...new Set(accents)].slice(0, MAX_ACCENTS),
385
+ fontFamily: CONTENT_FONT,
386
+ };
387
+ };
388
+ // ---------------------------------------------------------------------------
389
+ // The platform
390
+ // ---------------------------------------------------------------------------
391
+ /** Rejects when a call takes longer than it may: the realtime call has no time limit of its own. */
392
+ const within = (seconds, what, promise) => {
393
+ let timer;
394
+ const deadline = new Promise((_, reject) => {
395
+ timer = setTimeout(() => reject(new Error(`${what} did not answer in ${seconds} seconds`)), seconds * 1000);
396
+ });
397
+ return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
398
+ };
399
+ const defaultPlatform = (token, signal) => ({
400
+ generate: (data, contentType, integrationId, elementId) =>
401
+ // The client's later versions take the caller's signal as a seventh
402
+ // argument; an earlier one ignores it.
403
+ contentGenerator.generateContent(data, contentType,
404
+ // The client takes "no integration" as nothing at all.
405
+ integrationId || null, token, null, elementId ? String(elementId) : null, signal ? { signal } : {}),
406
+ storeMedia: (target, mediaId, media, mimeType) => learningContent.storeLearningContentMicroSkillLearningContentActivityMedia(target.learningContentId, target.microSkillId, target.learningActivityId, mediaId, media, mimeType, token),
407
+ storeSceneAudio: (target, sceneId, script) => learningContent.storeLearningContentMicroSkillLearningContentActivitySceneAudio(target.learningContentId, target.microSkillId, target.learningActivityId, sceneId, script, token),
408
+ readLookNFeel: async (tenantName) => {
409
+ if (!tenantName)
410
+ return null;
411
+ try {
412
+ const lookNFeel = await tenant.getTenantLookNFeel(tenantName);
413
+ return lookNFeel && typeof lookNFeel === "object" ? lookNFeel : null;
414
+ }
415
+ catch {
416
+ return null;
417
+ }
418
+ },
419
+ deliverImage,
420
+ newId: newMediaId,
421
+ });
422
+ const isCancelled = async (run) => {
423
+ if (run.summary.cancelled)
424
+ return true;
425
+ if (run.options.signal?.aborted || (await run.options.isCancelled?.())) {
426
+ run.summary.cancelled = true;
427
+ }
428
+ return run.summary.cancelled;
429
+ };
430
+ const note = (run, message) => {
431
+ try {
432
+ run.options.onNote?.("warning", message);
433
+ }
434
+ catch {
435
+ // Telling the person is best-effort.
436
+ }
437
+ };
438
+ const settled = (run, message) => {
439
+ run.done++;
440
+ try {
441
+ run.options.onProgress?.({ done: run.done, total: run.total, message });
442
+ }
443
+ catch {
444
+ // Progress is best-effort.
445
+ }
446
+ };
447
+ // Runs an operation, and again when it throws, up to `retries` more times.
448
+ // Resolves null once every attempt failed, or the run was cancelled.
449
+ const attempt = async (run, what, operation) => {
450
+ for (let failures = 0;;) {
451
+ try {
452
+ return await operation();
453
+ }
454
+ catch (error) {
455
+ failures++;
456
+ if (failures > run.retries || (await isCancelled(run))) {
457
+ warn(`${what} failed: ${messageOfError(error)}`);
458
+ return null;
459
+ }
460
+ warn(`${what} failed, attempt ${failures}: ${messageOfError(error)}`);
461
+ }
462
+ }
463
+ };
464
+ // Runs `work` over `items`, `limit` at a time, and stops starting new ones once
465
+ // the run is cancelled.
466
+ const pooled = async (run, limit, items, work) => {
467
+ let next = 0;
468
+ const worker = async () => {
469
+ while (next < items.length) {
470
+ if (await isCancelled(run))
471
+ return;
472
+ const item = items[next++];
473
+ await work(item);
474
+ }
475
+ };
476
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, worker));
477
+ };
478
+ const generate = (run, data, contentType, integrationId) => within(run.timeoutSeconds, `The ${contentType} generation`, run.platform.generate(data, contentType, integrationId, run.costElementId));
479
+ // Generates one image or clip and stores it. Resolves what was stored, or null
480
+ // when it could not be made: the caller moves on.
481
+ const generateAndStore = async (run, prompt, what) => {
482
+ const failed = (step) => {
483
+ run.summary.failed.push({ id: prompt.id, kind: prompt.kind });
484
+ note(run, `Failed to ${step} ${what.name} "${prompt.id}". Skipping...`);
485
+ return null;
486
+ };
487
+ const bytes = await attempt(run, `The ${what.name} "${prompt.id}"`, async () => bytesOf(await generate(run, what.request(prompt), what.capability, what.integrationId)));
488
+ if (!bytes)
489
+ return failed("generate");
490
+ // A run cancelled meanwhile stores nothing more.
491
+ if (await isCancelled(run))
492
+ return null;
493
+ const mediaId = run.platform.newId();
494
+ try {
495
+ const { buffer, mimeType } = await what.delivery(bytes);
496
+ await run.platform.storeMedia(run.target, mediaId, buffer, mimeType);
497
+ }
498
+ catch (error) {
499
+ warn(`The ${what.name} "${prompt.id}" was not stored: ${messageOfError(error)}`);
500
+ return failed("save");
501
+ }
502
+ what.count.stored++;
503
+ return { id: prompt.id, _id: mediaId };
504
+ };
505
+ // Generates and stores the films of an activity, one at a time: a film is
506
+ // minutes of the largest model, and an activity has one at most.
507
+ const generateMotionGraphics = async (run, content, elements, scenes, integrationId) => {
508
+ if (elements.length === 0)
509
+ return;
510
+ const seconds = scenes ? filmSecondsOf(content) : new Map();
511
+ const style = motionGraphicStyle(await run.platform.readLookNFeel(run.options.tenantName ?? null), content, scenes);
512
+ for (const element of elements) {
513
+ if (await isCancelled(run))
514
+ return;
515
+ const failed = (step) => {
516
+ run.summary.failed.push({ id: element.id, kind: "motionGraphic" });
517
+ note(run, `Failed to ${step} motion graphic "${element.id}". Skipping...`);
518
+ settled(run, "Generating motion graphics");
519
+ };
520
+ const durationSeconds = seconds.get(element.id);
521
+ const frame = titledScene(element.scene) ? TITLED_FRAME : null;
522
+ const response = await attempt(run, `The motion graphic "${element.id}"`, async () => {
523
+ const answer = await generate(run, {
524
+ prompt: element.prompt,
525
+ ...(durationSeconds ? { durationSeconds } : {}),
526
+ ...(frame ? { frame } : {}),
527
+ style,
528
+ }, "GENERATE_MOTION_GRAPHIC", integrationId);
529
+ htmlOf(answer);
530
+ return answer;
531
+ });
532
+ if (!response) {
533
+ failed("generate");
534
+ continue;
535
+ }
536
+ if (await isCancelled(run))
537
+ return;
538
+ // A new id every time: the player caches a film by its id.
539
+ const mediaId = run.platform.newId();
540
+ try {
541
+ await run.platform.storeMedia(run.target, mediaId, gzipSync(Buffer.from(htmlOf(response), "utf8")), GZIP);
542
+ }
543
+ catch (error) {
544
+ warn(`The motion graphic "${element.id}" was not stored: ${messageOfError(error)}`);
545
+ failed("save");
546
+ continue;
547
+ }
548
+ const madeFor = frameOf(response);
549
+ element.holder.motionGraphic = {
550
+ ...element.holder.motionGraphic,
551
+ _id: mediaId,
552
+ chapters: chaptersOf(response),
553
+ ...(madeFor ? { frame: madeFor } : {}),
554
+ set: true,
555
+ };
556
+ applyNarration(element.scene, element.id, response?.audioScript, run.platform.newId);
557
+ run.summary.motionGraphics.stored++;
558
+ settled(run, "Generating motion graphics");
559
+ }
560
+ };
561
+ // Prepares the narration of every scene of a video. The platform synthesises
562
+ // and stores it (it holds the voice provider and the storage). A scene's audio
563
+ // is stored under the scene's id, so a scene without one is given it here.
564
+ // The cost either replaces what is stored (a whole video prepared) or is added
565
+ // to it (some scenes prepared again).
566
+ const prepareNarration = async (run, videoContent, scenes, costIs = "replaced") => {
567
+ scenes.forEach((scene) => {
568
+ if (scene && !scene._id)
569
+ scene._id = run.platform.newId();
570
+ });
571
+ // What preparing the narration cost, by model. The voice is the tenant's
572
+ // choice per model, so the tenant's totals cannot say what one video cost.
573
+ const usage = { cost: 0, models: {} };
574
+ let usageKnown = false;
575
+ const spoken = scenes.filter((scene) => {
576
+ // A scene that says nothing is not a failure.
577
+ if (narrationOf(scene).length > 0)
578
+ return true;
579
+ run.summary.narration.silent++;
580
+ return false;
581
+ });
582
+ await pooled(run, NARRATION_CONCURRENCY, spoken, async (scene) => {
583
+ const stored = await attempt(run, `The audio of scene ${scene._id}`, async () => {
584
+ const answer = await run.platform.storeSceneAudio(run.target, String(scene._id), {
585
+ items: toArray(scene.audioScript.items).map((item) => ({
586
+ text: typeof item?.text === "string" ? item.text : "",
587
+ })),
588
+ });
589
+ if (!answer?.stored)
590
+ throw new Error("no audio was stored");
591
+ return answer;
592
+ });
593
+ settled(run, "Preparing the narration");
594
+ if (!stored) {
595
+ if (!run.summary.cancelled)
596
+ run.summary.narration.deferred++;
597
+ return;
598
+ }
599
+ run.summary.narration.prepared++;
600
+ if (typeof stored.usage?.cost === "number") {
601
+ usageKnown = true;
602
+ usage.cost += stored.usage.cost;
603
+ for (const [model, amount] of Object.entries(stored.usage.tokens ?? {})) {
604
+ if (typeof amount === "number")
605
+ usage.models[model] = (usage.models[model] || 0) + amount;
606
+ }
607
+ }
608
+ });
609
+ // Kept with the scenes, so it is stored with them.
610
+ if (usageKnown) {
611
+ const container = sceneContainerOf(videoContent);
612
+ const before = costIs === "added" ? container.audioUsage : null;
613
+ if (before && typeof before === "object" && !Array.isArray(before)) {
614
+ // The cost is added to what is stored, so `scenes` then stays the number of scenes of the last whole preparation.
615
+ const models = { ...(before.models ?? {}) };
616
+ for (const [model, amount] of Object.entries(usage.models))
617
+ models[model] = (models[model] || 0) + amount;
618
+ container.audioUsage = {
619
+ ...before,
620
+ cost: Math.round(((Number(before.cost) || 0) + usage.cost) * 1e6) / 1e6,
621
+ models,
622
+ };
623
+ }
624
+ else {
625
+ container.audioUsage = {
626
+ cost: Math.round(usage.cost * 1e6) / 1e6,
627
+ models: usage.models,
628
+ scenes: run.summary.narration.prepared,
629
+ };
630
+ }
631
+ }
632
+ if (run.summary.narration.deferred > 0) {
633
+ note(run, `Audio for ${run.summary.narration.deferred} scene(s) could not be prepared in advance and will be generated the first time the video is played.`);
634
+ }
635
+ };
636
+ /** The integration a kind of media is generated by, or false when it is not generated. */
637
+ const integrationFor = (choice, whenAbsent) => {
638
+ if (choice === NO_MEDIA_INTEGRATION)
639
+ return false;
640
+ if (typeof choice === "string" && choice.trim())
641
+ return choice;
642
+ return whenAbsent ? null : false;
643
+ };
644
+ const positive = (value, fallback) => {
645
+ const parsed = Math.floor(Number(value));
646
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
647
+ };
648
+ /**
649
+ * Whether what a caller handed over names where an activity's media belongs:
650
+ * the three ids, each a non-empty string.
651
+ */
652
+ export const isActivityMediaTarget = (value) => !!value &&
653
+ typeof value === "object" &&
654
+ ["learningContentId", "microSkillId", "learningActivityId"].every((key) => typeof value[key] === "string" && value[key].trim() !== "");
655
+ const emptySummary = () => ({
656
+ images: { asked: 0, stored: 0 },
657
+ videoClips: { asked: 0, stored: 0 },
658
+ motionGraphics: { asked: 0, stored: 0 },
659
+ narration: { prepared: 0, deferred: 0, silent: 0 },
660
+ failed: [],
661
+ cancelled: false,
662
+ });
663
+ // The run both entry points share: one place builds it from the options.
664
+ const mediaRunOf = (options, summary, total) => ({
665
+ options,
666
+ platform: { ...defaultPlatform(options.token, options.signal), ...(options.platform ?? {}) },
667
+ target: options.target,
668
+ costElementId: String(options.target.costElementId || options.target.microSkillId),
669
+ retries: Math.max(0, Math.floor(Number(options.retries ?? DEFAULT_RETRIES)) || 0),
670
+ timeoutSeconds: positive(options.generationTimeoutSeconds, DEFAULT_GENERATION_TIMEOUT_SECONDS),
671
+ summary,
672
+ total,
673
+ done: 0,
674
+ });
675
+ /**
676
+ * Generates and stores the media of an activity, and gives its elements what
677
+ * was stored: the films and images first, then the clips (they cost the most,
678
+ * so a run cancelled part-way has spent the least), then a video's narration.
679
+ * @param activity The activity (`{ videoContent }` or `{ textContent }`), changed in place
680
+ * @param options Where the media belongs, which media to make, and the run's token
681
+ * @returns What became of the media. It never rejects for a file that could not be made
682
+ */
683
+ export const generateActivityMedia = async (activity, options) => {
684
+ const summary = emptySummary();
685
+ const content = activity?.[options.field];
686
+ if (!content)
687
+ return summary;
688
+ if (!isActivityMediaTarget(options.target)) {
689
+ throw new Error("An activity's media needs the learning content, micro skill and activity it belongs to");
690
+ }
691
+ const choices = options.choices ?? {};
692
+ const isVideo = options.field === "videoContent";
693
+ const scenes = isVideo ? scenesOf(content) : null;
694
+ const imageIntegration = integrationFor(choices.imageIntegrationId, true);
695
+ // Without a clip generator the clips are left unset. A still in a clip's
696
+ // place is a picture pretending to be a video, and is charged for.
697
+ const clipIntegration = isVideo
698
+ ? integrationFor(choices.videoClipIntegrationId, !!choices.videoClipsEnabled)
699
+ : false;
700
+ const filmIntegration = integrationFor(choices.motionGraphicIntegrationId, !!choices.motionGraphicsEnabled);
701
+ const prompts = mediaPromptsOf(content);
702
+ const images = imageIntegration === false ? [] : prompts.filter(({ kind }) => kind === "image");
703
+ const clips = clipIntegration === false ? [] : prompts.filter(({ kind }) => kind === "videoClip");
704
+ // In a video, each film with its scene, for its frame and its narration.
705
+ const films = filmIntegration === false
706
+ ? []
707
+ : scenes
708
+ ? scenes.flatMap((scene) => motionGraphicsOf(scene?.content).map((element) => ({ ...element, scene })))
709
+ : motionGraphicsOf(content);
710
+ const narrated = isVideo && choices.narration !== false ? scenes : [];
711
+ summary.images.asked = images.length;
712
+ summary.videoClips.asked = clips.length;
713
+ summary.motionGraphics.asked = films.length;
714
+ const run = mediaRunOf(options, summary, images.length +
715
+ clips.length +
716
+ films.length +
717
+ narrated.filter((scene) => narrationOf(scene).length > 0).length);
718
+ if (await isCancelled(run))
719
+ return summary;
720
+ const stored = [];
721
+ const keep = (entry) => {
722
+ if (entry)
723
+ stored.push(entry);
724
+ };
725
+ // The films and the images together: neither needs what the other makes.
726
+ await Promise.all([
727
+ generateMotionGraphics(run, content, films, scenes, filmIntegration || null),
728
+ pooled(run, positive(choices.imageConcurrency, IMAGE_CONCURRENCY), images, async (prompt) => {
729
+ keep(await generateAndStore(run, prompt, {
730
+ capability: "GENERATE_IMAGE",
731
+ count: summary.images,
732
+ delivery: run.platform.deliverImage,
733
+ integrationId: imageIntegration || null,
734
+ name: "image",
735
+ request: ({ prompt: text }) => ({ prompt: text }),
736
+ }));
737
+ settled(run, "Generating images");
738
+ }),
739
+ ]);
740
+ // The clips after the films: a clip is timed to its scene's narration, which
741
+ // a film on the scene has just replaced.
742
+ const seconds = clips.length > 0 ? clipSecondsOf(content) : new Map();
743
+ await pooled(run, CLIP_CONCURRENCY, clips, async (prompt) => {
744
+ keep(await generateAndStore(run, { ...prompt, seconds: seconds.get(prompt.id) ?? CLIP_SECONDS_LONG }, {
745
+ capability: "GENERATE_VIDEO",
746
+ count: summary.videoClips,
747
+ // A generator answers in MP4, which is what is delivered.
748
+ delivery: async (buffer) => ({ buffer, mimeType: MP4 }),
749
+ integrationId: clipIntegration || null,
750
+ name: "video clip",
751
+ request: ({ prompt: text, seconds: durationSeconds }) => ({ prompt: text, durationSeconds }),
752
+ }));
753
+ settled(run, "Generating video clips");
754
+ });
755
+ applyStoredMedia(content, stored);
756
+ // Narration last: it is what the films' lines are part of. It is otherwise
757
+ // synthesised when a scene is first played, which makes whoever opens a new
758
+ // video first wait on every scene of it.
759
+ if (narrated.length > 0 && !(await isCancelled(run))) {
760
+ await prepareNarration(run, content, narrated);
761
+ }
762
+ const asked = images.length + clips.length + films.length;
763
+ if (summary.failed.length > 0) {
764
+ warn(`Media of activity ${options.target.learningActivityId} is incomplete: ${asked - summary.failed.length}/${asked} generated; without media: ${summary.failed.map(({ id }) => id).join(", ")}`);
765
+ }
766
+ return summary;
767
+ };
768
+ /**
769
+ * Prepares again the narration of some scenes of a video, after their lines
770
+ * changed: the audio of each is stored whole, from all its lines. Nothing else
771
+ * of the activity is generated.
772
+ * @returns The summary, with only `narration` and `cancelled` meaningful
773
+ */
774
+ export const prepareScenesNarration = async (activity, sceneIds, options) => {
775
+ const summary = emptySummary();
776
+ const content = options.field === "videoContent" ? activity?.videoContent : null;
777
+ if (!content)
778
+ return summary;
779
+ if (!isActivityMediaTarget(options.target)) {
780
+ throw new Error("An activity's media needs the learning content, micro skill and activity it belongs to");
781
+ }
782
+ const named = new Set(toArray(sceneIds).map(String));
783
+ const scenes = scenesOf(content).filter((scene) => scene?._id && named.has(String(scene._id)));
784
+ const run = mediaRunOf(options, summary, scenes.filter((scene) => narrationOf(scene).length > 0).length);
785
+ if (scenes.length > 0 && !(await isCancelled(run))) {
786
+ await prepareNarration(run, content, scenes, "added");
787
+ }
788
+ return summary;
789
+ };
790
+ export default {
791
+ NO_MEDIA_INTEGRATION,
792
+ applyStoredMedia,
793
+ bytesOf,
794
+ clipSecondsOf,
795
+ filmSecondsOf,
796
+ generateActivityMedia,
797
+ htmlOf,
798
+ isActivityMediaTarget,
799
+ mediaPromptsOf,
800
+ motionGraphicStyle,
801
+ motionGraphicsOf,
802
+ narrationOf,
803
+ newMediaId,
804
+ prepareScenesNarration,
805
+ sceneContainerOf,
806
+ scenesOf,
807
+ };