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