privateer-agent 0.15.4 → 0.15.6

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 (229) hide show
  1. package/README.md +11 -0
  2. package/bin/boot-bundle.d.mts +2 -0
  3. package/bin/boot-bundle.mjs +44 -0
  4. package/bin/fresh-supervisor.d.mts +5 -1
  5. package/bin/fresh-supervisor.mjs +47 -10
  6. package/bin/privateer-launch.mjs +27 -3
  7. package/bin/privateer-subagent.mjs +5 -2
  8. package/bin/privateer-verify.mjs +12 -0
  9. package/bin/session-recovery.d.mts +53 -0
  10. package/bin/session-recovery.mjs +240 -0
  11. package/bin/session-seal-preload.mjs +17 -0
  12. package/bin/session-seal.d.mts +25 -0
  13. package/bin/session-seal.mjs +242 -0
  14. package/dist-boot/boot.mjs +3 -0
  15. package/dist-boot/c-27JKSMWL.mjs +1460 -0
  16. package/dist-boot/c-2BMRFV24.mjs +269 -0
  17. package/dist-boot/c-2CTF6JA3.mjs +166 -0
  18. package/dist-boot/c-2G3BBHRJ.mjs +84 -0
  19. package/dist-boot/c-2IDLKXX6.mjs +250 -0
  20. package/dist-boot/c-2NJD5VYM.mjs +8 -0
  21. package/dist-boot/c-2S5EEQPW.mjs +1602 -0
  22. package/dist-boot/c-2WRDCUVI.mjs +25 -0
  23. package/dist-boot/c-2YN3M256.mjs +14 -0
  24. package/dist-boot/c-37GM3GMU.mjs +187 -0
  25. package/dist-boot/c-3STKRSVO.mjs +2480 -0
  26. package/dist-boot/c-3TPV6TQQ.mjs +2320 -0
  27. package/dist-boot/c-3UVHLQDJ.mjs +225 -0
  28. package/dist-boot/c-42PUUZYC.mjs +697 -0
  29. package/dist-boot/c-4D5UMWVW.mjs +683 -0
  30. package/dist-boot/c-4ETZRMTA.mjs +46 -0
  31. package/dist-boot/c-4QT25BD5.mjs +1482 -0
  32. package/dist-boot/c-4WVR32AP.mjs +2579 -0
  33. package/dist-boot/c-5EMM567G.mjs +152 -0
  34. package/dist-boot/c-5FA4CV63.mjs +145 -0
  35. package/dist-boot/c-5GV3X3RB.mjs +14 -0
  36. package/dist-boot/c-5JCEPRIY.mjs +52 -0
  37. package/dist-boot/c-5NDKIIWT.mjs +16 -0
  38. package/dist-boot/c-5QL3AR26.mjs +4665 -0
  39. package/dist-boot/c-5XY6MFKN.mjs +5142 -0
  40. package/dist-boot/c-65UZIZC7.mjs +2897 -0
  41. package/dist-boot/c-6FUXKHOK.mjs +1969 -0
  42. package/dist-boot/c-6JHWQE4V.mjs +18242 -0
  43. package/dist-boot/c-6LOBR4I6.mjs +5280 -0
  44. package/dist-boot/c-6QHOZXKQ.mjs +14394 -0
  45. package/dist-boot/c-6ZO2SADQ.mjs +178 -0
  46. package/dist-boot/c-6ZORVVZP.mjs +1449 -0
  47. package/dist-boot/c-76QH4UCP.mjs +2441 -0
  48. package/dist-boot/c-77GO5L5Y.mjs +20982 -0
  49. package/dist-boot/c-7M23XFTN.mjs +5052 -0
  50. package/dist-boot/c-7TC367E2.mjs +32 -0
  51. package/dist-boot/c-7UOG7POX.mjs +1524 -0
  52. package/dist-boot/c-7VHP3FLN.mjs +376 -0
  53. package/dist-boot/c-A73JHZP2.mjs +13207 -0
  54. package/dist-boot/c-ABXULAFL.mjs +71 -0
  55. package/dist-boot/c-ANDD2AQO.mjs +74 -0
  56. package/dist-boot/c-AOY77AZL.mjs +1430 -0
  57. package/dist-boot/c-AXEPZ22I.mjs +108 -0
  58. package/dist-boot/c-B2Y7VNHU.mjs +427 -0
  59. package/dist-boot/c-B7VJUH73.mjs +77 -0
  60. package/dist-boot/c-BFW6CDVL.mjs +24 -0
  61. package/dist-boot/c-BHNIF2AR.mjs +188 -0
  62. package/dist-boot/c-BKF2O6BL.mjs +23 -0
  63. package/dist-boot/c-BOZXFTZN.mjs +8 -0
  64. package/dist-boot/c-BRNYJWZL.mjs +28 -0
  65. package/dist-boot/c-C3N4Z2HO.mjs +93 -0
  66. package/dist-boot/c-C4IV7ZFG.mjs +717 -0
  67. package/dist-boot/c-C5NK6UYV.mjs +793 -0
  68. package/dist-boot/c-C67644MB.mjs +1659 -0
  69. package/dist-boot/c-C6S2YB53.mjs +620 -0
  70. package/dist-boot/c-CDBEJSBF.mjs +37 -0
  71. package/dist-boot/c-CG47HBKU.mjs +435 -0
  72. package/dist-boot/c-CKCTWCT5.mjs +51 -0
  73. package/dist-boot/c-CN77DCGF.mjs +60 -0
  74. package/dist-boot/c-CRBXNKFO.mjs +1795 -0
  75. package/dist-boot/c-CRIHASQ6.mjs +973 -0
  76. package/dist-boot/c-CU4NGAUO.mjs +3786 -0
  77. package/dist-boot/c-CWRFLGQU.mjs +1883 -0
  78. package/dist-boot/c-CYQB2USO.mjs +32 -0
  79. package/dist-boot/c-DEE67DJO.mjs +379 -0
  80. package/dist-boot/c-DIFDBYOP.mjs +1258 -0
  81. package/dist-boot/c-DOSGVXDZ.mjs +34879 -0
  82. package/dist-boot/c-DR7XQI32.mjs +381 -0
  83. package/dist-boot/c-DTGPSB46.mjs +14666 -0
  84. package/dist-boot/c-DTHDNA4P.mjs +320 -0
  85. package/dist-boot/c-E4Z3Y5B5.mjs +3864 -0
  86. package/dist-boot/c-E66Z2TI7.mjs +203 -0
  87. package/dist-boot/c-EBU6RLRV.mjs +1527 -0
  88. package/dist-boot/c-EBZZNGSF.mjs +432 -0
  89. package/dist-boot/c-EC3LJ2KF.mjs +1032 -0
  90. package/dist-boot/c-EQBKXWNX.mjs +15829 -0
  91. package/dist-boot/c-EUEPIW4S.mjs +574 -0
  92. package/dist-boot/c-EX4YVWAT.mjs +378 -0
  93. package/dist-boot/c-EYZGSAJU.mjs +98 -0
  94. package/dist-boot/c-F75VRKY4.mjs +172 -0
  95. package/dist-boot/c-FH4NXKHV.mjs +177 -0
  96. package/dist-boot/c-FHNUCTEM.mjs +140 -0
  97. package/dist-boot/c-FJ5T42DS.mjs +5349 -0
  98. package/dist-boot/c-FPCNRL7G.mjs +1728 -0
  99. package/dist-boot/c-G4DLN7Q4.mjs +8 -0
  100. package/dist-boot/c-G56GYQFZ.mjs +2507 -0
  101. package/dist-boot/c-GLIOERDQ.mjs +1200 -0
  102. package/dist-boot/c-GMJ5HUBM.mjs +14 -0
  103. package/dist-boot/c-H3HSGMAQ.mjs +461 -0
  104. package/dist-boot/c-HIKTO6P7.mjs +275 -0
  105. package/dist-boot/c-I2MCJ34O.mjs +464 -0
  106. package/dist-boot/c-I3C6LBW4.mjs +765 -0
  107. package/dist-boot/c-I54OKQHW.mjs +387 -0
  108. package/dist-boot/c-IFSP3R4D.mjs +80 -0
  109. package/dist-boot/c-IZK77VB7.mjs +171 -0
  110. package/dist-boot/c-J3Y25UGE.mjs +54 -0
  111. package/dist-boot/c-J5IESS7W.mjs +27750 -0
  112. package/dist-boot/c-JJWZBY7L.mjs +254 -0
  113. package/dist-boot/c-JKTFXTGF.mjs +463 -0
  114. package/dist-boot/c-JN57AXQ4.mjs +77 -0
  115. package/dist-boot/c-KFIO6LUW.mjs +1096 -0
  116. package/dist-boot/c-KIEMEFWW.mjs +478 -0
  117. package/dist-boot/c-KIVXWBYD.mjs +28 -0
  118. package/dist-boot/c-KP6CRIP4.mjs +580 -0
  119. package/dist-boot/c-L26VOJX4.mjs +11558 -0
  120. package/dist-boot/c-L5GHWG5G.mjs +5988 -0
  121. package/dist-boot/c-M7NSQAKK.mjs +353 -0
  122. package/dist-boot/c-MCEWOPBW.mjs +56 -0
  123. package/dist-boot/c-MGPIEG7I.mjs +20 -0
  124. package/dist-boot/c-NREXJV3M.mjs +393 -0
  125. package/dist-boot/c-O5PP6CTX.mjs +162 -0
  126. package/dist-boot/c-OBQDHSXM.mjs +1774 -0
  127. package/dist-boot/c-OLQHHDD4.mjs +21 -0
  128. package/dist-boot/c-OXW4JQQH.mjs +319 -0
  129. package/dist-boot/c-P3D7ZUWN.mjs +1288 -0
  130. package/dist-boot/c-P4PQZVV5.mjs +948 -0
  131. package/dist-boot/c-P63T3XL2.mjs +26373 -0
  132. package/dist-boot/c-P6N5DQGZ.mjs +194 -0
  133. package/dist-boot/c-P7MLKQFC.mjs +58 -0
  134. package/dist-boot/c-PB3PZJL5.mjs +1276 -0
  135. package/dist-boot/c-PTN4S6G2.mjs +1259 -0
  136. package/dist-boot/c-PYCE5J7U.mjs +1083 -0
  137. package/dist-boot/c-Q4HYCRLB.mjs +19410 -0
  138. package/dist-boot/c-QUXMETGG.mjs +68 -0
  139. package/dist-boot/c-RDMJZCOX.mjs +356 -0
  140. package/dist-boot/c-ROGJK76M.mjs +17 -0
  141. package/dist-boot/c-RQJJ26T4.mjs +708 -0
  142. package/dist-boot/c-RSKCUPJF.mjs +7559 -0
  143. package/dist-boot/c-RVJU4O6P.mjs +37 -0
  144. package/dist-boot/c-S2RVHR3M.mjs +165 -0
  145. package/dist-boot/c-SKMK3PEE.mjs +91120 -0
  146. package/dist-boot/c-TI7SM4EG.mjs +20 -0
  147. package/dist-boot/c-TILJ6GXD.mjs +1235 -0
  148. package/dist-boot/c-TT6BCUJD.mjs +114 -0
  149. package/dist-boot/c-U4ITOXAN.mjs +2107 -0
  150. package/dist-boot/c-UGERXVO2.mjs +7120 -0
  151. package/dist-boot/c-UPBH5AXY.mjs +1363 -0
  152. package/dist-boot/c-US2PUNZL.mjs +597 -0
  153. package/dist-boot/c-UU4WZPPE.mjs +20 -0
  154. package/dist-boot/c-UWVIYPQS.mjs +39 -0
  155. package/dist-boot/c-V4RHQBPQ.mjs +17683 -0
  156. package/dist-boot/c-V5MRVK47.mjs +351 -0
  157. package/dist-boot/c-V6CL266R.mjs +1755 -0
  158. package/dist-boot/c-VJTMFKYE.mjs +14975 -0
  159. package/dist-boot/c-VJTRUKIB.mjs +773 -0
  160. package/dist-boot/c-W4IFSHPW.mjs +43 -0
  161. package/dist-boot/c-WETGB2CF.mjs +113 -0
  162. package/dist-boot/c-WO3QSZUU.mjs +1337 -0
  163. package/dist-boot/c-WQLH73TY.mjs +242 -0
  164. package/dist-boot/c-XL735JW5.mjs +500 -0
  165. package/dist-boot/c-Y7HADL5B.mjs +1107 -0
  166. package/dist-boot/c-YGQHSVSK.mjs +41 -0
  167. package/dist-boot/c-YMP2AMEB.mjs +10350 -0
  168. package/dist-boot/c-YRDO2WEF.mjs +12012 -0
  169. package/dist-boot/c-YUSTRATJ.mjs +8 -0
  170. package/dist-boot/c-Z2262R22.mjs +2697 -0
  171. package/dist-boot/c-Z4ALQMJC.mjs +709 -0
  172. package/dist-boot/c-Z5ZUQVUY.mjs +62 -0
  173. package/dist-boot/c-ZDZUKXF7.mjs +874 -0
  174. package/dist-boot/c-ZJYLGIC3.mjs +32 -0
  175. package/dist-boot/c-ZNA5CDMI.mjs +77 -0
  176. package/dist-boot/c-ZSO6DI3M.mjs +204 -0
  177. package/dist-boot/c-ZWUVHKMK.mjs +100 -0
  178. package/dist-boot/c-ZY4MESEW.mjs +832 -0
  179. package/dist-boot/c-ZZ5REI4L.mjs +329 -0
  180. package/dist-boot/cli.mjs +51 -0
  181. package/dist-boot/ext-anthropic-attribution.mjs +207 -0
  182. package/dist-boot/ext-pi-background-tasks.mjs +7234 -0
  183. package/dist-boot/ext-pi-subagents.mjs +37 -0
  184. package/dist-boot/ext-privateer-account.mjs +4426 -0
  185. package/dist-boot/ext-privateer-brand.mjs +5274 -0
  186. package/dist-boot/ext-privateer-codemode.mjs +37 -0
  187. package/dist-boot/ext-privateer-computer.mjs +626 -0
  188. package/dist-boot/ext-privateer-connect.mjs +1862 -0
  189. package/dist-boot/ext-privateer-context.mjs +323 -0
  190. package/dist-boot/ext-privateer-desktop.mjs +92 -0
  191. package/dist-boot/ext-privateer-final-audit.mjs +48 -0
  192. package/dist-boot/ext-privateer-fresh.mjs +81 -0
  193. package/dist-boot/ext-privateer-gate.mjs +5959 -0
  194. package/dist-boot/ext-privateer-hints.mjs +236 -0
  195. package/dist-boot/ext-privateer-media.mjs +2626 -0
  196. package/dist-boot/ext-privateer-models.mjs +3397 -0
  197. package/dist-boot/ext-privateer-posture.mjs +3006 -0
  198. package/dist-boot/ext-privateer-privacy.mjs +4578 -0
  199. package/dist-boot/ext-privateer-recovery.mjs +287 -0
  200. package/dist-boot/ext-privateer-speak.mjs +4754 -0
  201. package/dist-boot/ext-privateer-terminals.mjs +725 -0
  202. package/dist-boot/ext-privateer-tools.mjs +528 -0
  203. package/dist-boot/ext-privateer-truncation.mjs +74 -0
  204. package/dist-boot/ext-privateer-update.mjs +210 -0
  205. package/dist-boot/ext-privateer-vision.mjs +148 -0
  206. package/dist-boot/ext-privateer-web.mjs +543 -0
  207. package/dist-boot/ext-rpiv-ask-user-question.mjs +710 -0
  208. package/dist-boot/manifest.json +9 -0
  209. package/extensions/privateer-brand.ts +3 -1
  210. package/extensions/privateer-context.ts +4 -2
  211. package/extensions/privateer-final-audit.ts +17 -0
  212. package/extensions/privateer-gate.ts +55 -9
  213. package/extensions/privateer-recovery.ts +175 -0
  214. package/extensions/privateer-web.ts +4 -4
  215. package/package.json +3 -1
  216. package/patches/@earendil-works+pi-coding-agent+1.3.0.patch +199 -2
  217. package/patches/pi-background-tasks+2.6.10.patch +91 -7
  218. package/src/cli/chat.ts +7 -1
  219. package/src/config/moatManifest.json +2 -0
  220. package/src/config/whatsNew.json +4 -4
  221. package/src/context.ts +33 -5
  222. package/src/engine/finalAudit.ts +38 -0
  223. package/src/engine/stallWatchdog.ts +8 -1
  224. package/src/providers/account.ts +34 -3
  225. package/src/remote/attentionPush.ts +40 -0
  226. package/src/remote/liveTaskSession.ts +7 -1
  227. package/src/remote/relayClient.ts +38 -4
  228. package/src/remote/remoteBridge.ts +17 -0
  229. package/src/remote/transcriptSnapshot.ts +104 -0
@@ -0,0 +1,2626 @@
1
+ import{createRequire as __pvCR}from"node:module";import{fileURLToPath as __pvF}from"node:url";import{dirname as __pvD}from"node:path";const require=__pvCR(import.meta.url);const __pvUrl=(r)=>new URL(r,import.meta.url).href;const __pvFile=(r)=>__pvF(new URL(r,import.meta.url));
2
+ import {
3
+ require_undici
4
+ } from "./c-P63T3XL2.mjs";
5
+ import "./c-4WVR32AP.mjs";
6
+ import {
7
+ typebox_exports
8
+ } from "./c-RQJJ26T4.mjs";
9
+ import "./c-L5GHWG5G.mjs";
10
+ import {
11
+ __name,
12
+ __toESM
13
+ } from "./c-CN77DCGF.mjs";
14
+
15
+ // src/tools/media.ts?ext=privateer-media
16
+ var import_undici = __toESM(require_undici());
17
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync4, unlinkSync as unlinkSync2, existsSync as existsSync2, statSync as statSync2, readdirSync } from "node:fs";
18
+ import { createDecipheriv, randomBytes as randomBytes2 } from "node:crypto";
19
+ import { dirname as dirname2, extname, isAbsolute, join as join3, relative, resolve, sep } from "node:path";
20
+ import { tmpdir } from "node:os";
21
+
22
+ // src/auth/privateer.ts?ext=privateer-media
23
+ import { existsSync, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2, chmodSync as chmodSync2, rmSync as rmSync2 } from "node:fs";
24
+ import { hostname, userInfo } from "node:os";
25
+
26
+ // src/config/paths.ts?ext=privateer-media
27
+ import { homedir } from "node:os";
28
+ import { join } from "node:path";
29
+ function globalDir() {
30
+ return process.env.PRIVATEER_HOME ?? join(homedir(), ".privateer");
31
+ }
32
+ __name(globalDir, "globalDir");
33
+ function credentialsPath() {
34
+ return join(globalDir(), "credentials.json");
35
+ }
36
+ __name(credentialsPath, "credentialsPath");
37
+ function configPath() {
38
+ return join(globalDir(), "config.json");
39
+ }
40
+ __name(configPath, "configPath");
41
+
42
+ // src/engine/errors.ts?ext=privateer-media
43
+ var CAP_CODE = /CAP|QUOTA|LIMIT_REACHED|INSUFFICIENT|TOP_?UP/i;
44
+ function isAccountCapCode(code) {
45
+ return typeof code === "string" && CAP_CODE.test(code);
46
+ }
47
+ __name(isAccountCapCode, "isAccountCapCode");
48
+
49
+ // src/crypto/accountTrust.ts?ext=privateer-media
50
+ import { readFileSync, writeFileSync, chmodSync, rmSync } from "node:fs";
51
+ import { join as join2 } from "node:path";
52
+ function trustPath() {
53
+ return join2(globalDir(), "account-trust.json");
54
+ }
55
+ __name(trustPath, "trustPath");
56
+ function clearAccountSignKey() {
57
+ try {
58
+ rmSync(trustPath(), { force: true });
59
+ } catch {
60
+ }
61
+ }
62
+ __name(clearAccountSignKey, "clearAccountSignKey");
63
+
64
+ // src/auth/privateer.ts?ext=privateer-media
65
+ var DEFAULT_SERVER_URL = "https://helix-server-m1ac.onrender.com";
66
+ function isSafeServerUrl(raw) {
67
+ let u;
68
+ try {
69
+ u = new URL(raw);
70
+ } catch {
71
+ return false;
72
+ }
73
+ if (u.protocol === "https:") return true;
74
+ if (u.protocol === "http:" && (u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "::1")) {
75
+ return true;
76
+ }
77
+ return false;
78
+ }
79
+ __name(isSafeServerUrl, "isSafeServerUrl");
80
+ function serverBaseUrl() {
81
+ const env = process.env.PRIVATEER_SERVER_URL?.replace(/\/$/, "");
82
+ if (env) {
83
+ if (!isSafeServerUrl(env)) {
84
+ throw new Error(
85
+ `Refusing PRIVATEER_SERVER_URL=${env}: must be https:// (http allowed only for localhost). This protects your account token from being sent over an insecure or attacker-controlled connection.`
86
+ );
87
+ }
88
+ return env;
89
+ }
90
+ const base = (loadCredentials()?.serverBaseUrl || DEFAULT_SERVER_URL).replace(/\/$/, "");
91
+ if (!isSafeServerUrl(base)) {
92
+ throw new Error(`Stored Privateer server URL is not https (${base}). Run /logout then /login again.`);
93
+ }
94
+ return base;
95
+ }
96
+ __name(serverBaseUrl, "serverBaseUrl");
97
+ function defaultDeviceLabel() {
98
+ try {
99
+ return `${userInfo().username}@${hostname()}`;
100
+ } catch {
101
+ return "terminal";
102
+ }
103
+ }
104
+ __name(defaultDeviceLabel, "defaultDeviceLabel");
105
+ var SHARED = /* @__PURE__ */ Symbol.for("privateer.auth.shared");
106
+ function shared() {
107
+ const g = globalThis;
108
+ return g[SHARED] ??= { cache: null, signedIn: /* @__PURE__ */ new Set(), expired: /* @__PURE__ */ new Set() };
109
+ }
110
+ __name(shared, "shared");
111
+ var _child = null;
112
+ var _spawnInFlight = null;
113
+ var _refreshInFlight = null;
114
+ var _account = null;
115
+ function loadCredentials() {
116
+ const state = shared();
117
+ if (state.cache) return state.cache;
118
+ const path = credentialsPath();
119
+ if (!existsSync(path)) return null;
120
+ try {
121
+ state.cache = JSON.parse(readFileSync2(path, "utf8"));
122
+ } catch {
123
+ return null;
124
+ }
125
+ return state.cache;
126
+ }
127
+ __name(loadCredentials, "loadCredentials");
128
+ var ARMED_SLOT = /* @__PURE__ */ Symbol.for("privateer.accountCredential");
129
+ function forgetArmedAccountCredential() {
130
+ const slot = globalThis[ARMED_SLOT];
131
+ if (slot) slot.cred = void 0;
132
+ }
133
+ __name(forgetArmedAccountCredential, "forgetArmedAccountCredential");
134
+ function clearCredentials() {
135
+ try {
136
+ rmSync2(credentialsPath(), { force: true });
137
+ } catch {
138
+ }
139
+ clearAccountSignKey();
140
+ shared().cache = null;
141
+ _child = null;
142
+ _account = null;
143
+ forgetArmedAccountCredential();
144
+ }
145
+ __name(clearCredentials, "clearCredentials");
146
+ function hasCredentials() {
147
+ return loadCredentials() !== null;
148
+ }
149
+ __name(hasCredentials, "hasCredentials");
150
+ function notifySessionExpired() {
151
+ for (const listener of shared().expired) {
152
+ try {
153
+ listener();
154
+ } catch {
155
+ }
156
+ }
157
+ }
158
+ __name(notifySessionExpired, "notifySessionExpired");
159
+ async function postJson(base, path, body, init = {}) {
160
+ return fetch(`${base}${path}`, {
161
+ ...init,
162
+ method: "POST",
163
+ headers: { "Content-Type": "application/json", ...init.headers || {} },
164
+ body: JSON.stringify(body)
165
+ });
166
+ }
167
+ __name(postJson, "postJson");
168
+ async function spawnFailure(res) {
169
+ if (res.status === 401) {
170
+ if (hasCredentials()) {
171
+ clearCredentials();
172
+ notifySessionExpired();
173
+ }
174
+ return new Error("Your Privateer session expired. Run /login to sign in again.");
175
+ }
176
+ let message;
177
+ try {
178
+ message = (await res.json()).message;
179
+ } catch {
180
+ }
181
+ return new Error(message?.trim() || `Couldn't start a Privateer session (HTTP ${res.status}).`);
182
+ }
183
+ __name(spawnFailure, "spawnFailure");
184
+ async function spawnChildSession() {
185
+ const parent = loadCredentials();
186
+ if (!parent) throw new Error("Not logged in to Privateer. Run /login.");
187
+ const res = await postJson(serverBaseUrl(), "/auth/session/spawn", {
188
+ refreshToken: parent.refreshToken,
189
+ deviceLabel: defaultDeviceLabel()
190
+ }, {
191
+ headers: { Authorization: `Bearer ${parent.accessToken}` }
192
+ });
193
+ if (!res.ok) throw await spawnFailure(res);
194
+ const { accessToken, refreshToken } = await res.json();
195
+ _child = { accessToken, refreshToken };
196
+ return _child;
197
+ }
198
+ __name(spawnChildSession, "spawnChildSession");
199
+ function ensureChildSession() {
200
+ if (_child) return Promise.resolve(_child);
201
+ if (!_spawnInFlight) {
202
+ _spawnInFlight = spawnChildSession().finally(() => {
203
+ _spawnInFlight = null;
204
+ });
205
+ }
206
+ return _spawnInFlight;
207
+ }
208
+ __name(ensureChildSession, "ensureChildSession");
209
+ function refreshChildSession() {
210
+ if (_refreshInFlight) return _refreshInFlight;
211
+ _refreshInFlight = (async () => {
212
+ if (_child) {
213
+ const res = await postJson(serverBaseUrl(), "/auth/refresh", { refreshToken: _child.refreshToken });
214
+ if (res.ok) {
215
+ const { accessToken, refreshToken } = await res.json();
216
+ _child = { accessToken, refreshToken };
217
+ return _child;
218
+ }
219
+ }
220
+ _child = null;
221
+ return spawnChildSession();
222
+ })().finally(() => {
223
+ _refreshInFlight = null;
224
+ });
225
+ return _refreshInFlight;
226
+ }
227
+ __name(refreshChildSession, "refreshChildSession");
228
+ async function authedFetch(input, init = {}) {
229
+ const bodyBuf = init.body;
230
+ const withAuth = /* @__PURE__ */ __name((token) => {
231
+ const headers = new Headers(init.headers);
232
+ headers.set("Authorization", `Bearer ${token}`);
233
+ return { ...init, headers };
234
+ }, "withAuth");
235
+ let child = await ensureChildSession();
236
+ let res = await fetch(input, withAuth(child.accessToken));
237
+ if (res.status === 401) {
238
+ child = await refreshChildSession();
239
+ res = await fetch(input, { ...withAuth(child.accessToken), body: bodyBuf });
240
+ }
241
+ return await defuseRetryableCap(res);
242
+ }
243
+ __name(authedFetch, "authedFetch");
244
+ async function defuseRetryableCap(res) {
245
+ if (res.status !== 429) return res;
246
+ const body = await res.text();
247
+ let code;
248
+ try {
249
+ const parsed = JSON.parse(body);
250
+ code = parsed.code ?? parsed.error?.code;
251
+ } catch {
252
+ }
253
+ const status = isAccountCapCode(typeof code === "string" ? code : void 0) ? 402 : 429;
254
+ return new Response(body, { status, statusText: res.statusText, headers: res.headers });
255
+ }
256
+ __name(defuseRetryableCap, "defuseRetryableCap");
257
+ async function apiRequest(path, init = {}) {
258
+ const base = serverBaseUrl();
259
+ return authedFetch(`${base}${path}`, init);
260
+ }
261
+ __name(apiRequest, "apiRequest");
262
+
263
+ // src/config/mediaModels.ts?ext=privateer-media
264
+ import { readFileSync as readFileSync3, mkdirSync as mkdirSync2 } from "node:fs";
265
+ import { dirname } from "node:path";
266
+
267
+ // src/util/atomicWrite.ts?ext=privateer-media
268
+ import { chmodSync as chmodSync3, realpathSync, renameSync, statSync, unlinkSync, writeFileSync as writeFileSync3 } from "node:fs";
269
+ import { randomBytes } from "node:crypto";
270
+ function writeFileAtomic(path, data, opts = {}) {
271
+ let target = path;
272
+ let mode = opts.mode ?? 384;
273
+ try {
274
+ target = realpathSync(path);
275
+ if (opts.mode === void 0) mode = statSync(target).mode & 511;
276
+ } catch {
277
+ }
278
+ const tmp = `${target}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
279
+ try {
280
+ writeFileSync3(tmp, data, { encoding: "utf8", mode });
281
+ try {
282
+ chmodSync3(tmp, mode);
283
+ } catch {
284
+ }
285
+ renameSync(tmp, target);
286
+ } catch (e) {
287
+ try {
288
+ unlinkSync(tmp);
289
+ } catch {
290
+ }
291
+ throw e;
292
+ }
293
+ }
294
+ __name(writeFileAtomic, "writeFileAtomic");
295
+
296
+ // src/config/mediaModels.ts?ext=privateer-media
297
+ var KEY = { image: "imageModel", video: "videoModel" };
298
+ function readConfig() {
299
+ try {
300
+ const cfg = JSON.parse(readFileSync3(configPath(), "utf8"));
301
+ return cfg && typeof cfg === "object" && !Array.isArray(cfg) ? cfg : {};
302
+ } catch {
303
+ return {};
304
+ }
305
+ }
306
+ __name(readConfig, "readConfig");
307
+ function mediaModelPref(kind) {
308
+ const media = readConfig().media;
309
+ const v = media?.[KEY[kind]];
310
+ return typeof v === "string" && v.trim() ? v.trim() : void 0;
311
+ }
312
+ __name(mediaModelPref, "mediaModelPref");
313
+ function setMediaModelPref(kind, id) {
314
+ const cfg = readConfig();
315
+ const media = { ...cfg.media ?? {} };
316
+ const clean = id?.trim();
317
+ if (clean) media[KEY[kind]] = clean;
318
+ else delete media[KEY[kind]];
319
+ const next = { ...cfg, media };
320
+ if (Object.keys(media).length === 0) delete next.media;
321
+ mkdirSync2(dirname(configPath()), { recursive: true });
322
+ writeFileAtomic(configPath(), JSON.stringify(next, null, 2) + "\n");
323
+ }
324
+ __name(setMediaModelPref, "setMediaModelPref");
325
+ function effectiveMediaModel(kind, requested) {
326
+ return typeof requested === "string" && requested.trim() ? requested.trim() : mediaModelPref(kind);
327
+ }
328
+ __name(effectiveMediaModel, "effectiveMediaModel");
329
+
330
+ // src/tools/media.ts?ext=privateer-media
331
+ var VIDEO_POLL_TIMEOUT_MS = Number(process.env.PRIVATEER_VIDEO_TIMEOUT_MS) || 25 * 6e4;
332
+ var VIDEO_POLL_INTERVAL_MS = 5e3;
333
+ var MESH_POLL_TIMEOUT_MS = Number(process.env.PRIVATEER_MESH_TIMEOUT_MS) || 10 * 6e4;
334
+ var SPRITE_POLL_TIMEOUT_MS = Number(process.env.PRIVATEER_SPRITE_TIMEOUT_MS) || 25 * 6e4;
335
+ var SPRITE_POLL_INTERVAL_MS = 6e3;
336
+ var MESH_POLL_INTERVAL_MS = 5e3;
337
+ var MAX_MESH_VIEWS = 4;
338
+ var MAX_MESH_INPUT_TOTAL_BYTES = 12 * 1024 * 1024;
339
+ var MAX_INPUT_IMAGE_BYTES = 8 * 1024 * 1024;
340
+ function text(t) {
341
+ return { content: [{ type: "text", text: t }], details: {} };
342
+ }
343
+ __name(text, "text");
344
+ var IMAGE_MIME = {
345
+ ".png": "image/png",
346
+ ".jpg": "image/jpeg",
347
+ ".jpeg": "image/jpeg",
348
+ ".webp": "image/webp",
349
+ ".gif": "image/gif"
350
+ };
351
+ function mimeForImage(path) {
352
+ return IMAGE_MIME[extname(path).toLowerCase()] ?? "image/jpeg";
353
+ }
354
+ __name(mimeForImage, "mimeForImage");
355
+ function extForMime(mimeType, fallback) {
356
+ const m = (mimeType || "").toLowerCase();
357
+ if (m.includes("png")) return ".png";
358
+ if (m.includes("jpeg") || m.includes("jpg")) return ".jpg";
359
+ if (m.includes("webp")) return ".webp";
360
+ if (m.includes("mp4")) return ".mp4";
361
+ if (m.includes("webm")) return ".webm";
362
+ if (m.includes("mpeg") || m.includes("mp3")) return ".mp3";
363
+ if (m.includes("wav")) return ".wav";
364
+ if (m.includes("ogg")) return ".ogg";
365
+ return fallback;
366
+ }
367
+ __name(extForMime, "extForMime");
368
+ function abs(cwd, p) {
369
+ return isAbsolute(p) ? p : resolve(cwd, p);
370
+ }
371
+ __name(abs, "abs");
372
+ function writeOut(target, bytes) {
373
+ mkdirSync3(dirname2(target), { recursive: true });
374
+ writeFileSync4(target, bytes);
375
+ const kb = bytes.length / 1024;
376
+ return `${target} (${kb >= 1024 ? `${(kb / 1024).toFixed(1)} MB` : `${Math.round(kb)} KB`})`;
377
+ }
378
+ __name(writeOut, "writeOut");
379
+ function readInputImage(cwd, p) {
380
+ const target = abs(cwd, p);
381
+ if (!existsSync2(target)) throw new Error(`input image not found: ${p}`);
382
+ const stat = statSync2(target);
383
+ if (stat.isDirectory()) throw new Error(`${p} is a directory, not an image`);
384
+ if (stat.size === 0) throw new Error(`${p} is empty`);
385
+ if (stat.size > MAX_INPUT_IMAGE_BYTES) {
386
+ throw new Error(`${p} is ${(stat.size / 1048576).toFixed(1)} MB; the limit for an input image is ${MAX_INPUT_IMAGE_BYTES / 1048576} MB`);
387
+ }
388
+ return { data: readFileSync4(target).toString("base64"), mimeType: mimeForImage(target) };
389
+ }
390
+ __name(readInputImage, "readInputImage");
391
+ var MEDIA_HTTP_TIMEOUT_MS = 20 * 6e4;
392
+ var _mediaDispatcher = null;
393
+ function mediaDispatcher() {
394
+ return _mediaDispatcher ??= new import_undici.Agent({
395
+ headersTimeout: MEDIA_HTTP_TIMEOUT_MS,
396
+ bodyTimeout: MEDIA_HTTP_TIMEOUT_MS,
397
+ connect: { autoSelectFamilyAttemptTimeout: 2e3 }
398
+ });
399
+ }
400
+ __name(mediaDispatcher, "mediaDispatcher");
401
+ function describeTransportFailure(e) {
402
+ if (e instanceof Error && e.name === "AbortError") return "the request was cancelled";
403
+ const top = e instanceof Error ? e.message : String(e);
404
+ const cause = e?.cause;
405
+ const code = String(cause?.code ?? e?.code ?? "");
406
+ const causeMsg = cause instanceof Error ? cause.message : "";
407
+ if (/^UND_ERR_(HEADERS|BODY)_TIMEOUT$/.test(code)) {
408
+ return `Privateer did not answer within ${Math.round(MEDIA_HTTP_TIMEOUT_MS / 6e4)} minutes (${code}). The generation may still have finished and been billed on the server, so check the output path before retrying, and retry once rather than in a loop`;
409
+ }
410
+ const detail = [code, causeMsg].filter(Boolean).join(": ");
411
+ return `could not reach Privateer: ${top}${detail && !top.includes(detail) ? ` (${detail})` : ""}`;
412
+ }
413
+ __name(describeTransportFailure, "describeTransportFailure");
414
+ async function callAccount(path, init) {
415
+ let res;
416
+ try {
417
+ res = await apiRequest(path, {
418
+ // npm undici's Agent vs the undici-types Dispatcher in RequestInit: same runtime
419
+ // contract (verified against both Node's bundled fetch and Pi's undici 8).
420
+ ...{ dispatcher: mediaDispatcher() },
421
+ method: init.method,
422
+ ...init.body === void 0 ? {} : { headers: { "Content-Type": "application/json" }, body: JSON.stringify(init.body) },
423
+ ...init.signal ? { signal: init.signal } : {}
424
+ });
425
+ } catch (e) {
426
+ return { ok: false, message: describeTransportFailure(e) };
427
+ }
428
+ return interpretAccountResponse(res);
429
+ }
430
+ __name(callAccount, "callAccount");
431
+ async function interpretAccountResponse(res) {
432
+ if (res.ok || res.status === 202) {
433
+ try {
434
+ return { ok: true, data: await res.json() };
435
+ } catch {
436
+ return { ok: false, message: "Privateer returned a malformed response" };
437
+ }
438
+ }
439
+ let code = "";
440
+ let serverMessage = "";
441
+ try {
442
+ const err = await res.json();
443
+ code = String(err?.code ?? err?.error?.code ?? "");
444
+ serverMessage = String(err?.message ?? err?.error?.message ?? "");
445
+ } catch {
446
+ }
447
+ if (code === "ZDR_MEDIA_BLOCKED") {
448
+ return {
449
+ ok: false,
450
+ status: res.status,
451
+ message: (serverMessage || "this account requires Zero Data Retention and the media model has no ZDR endpoint") + " \u2014 this is a privacy setting only the account owner can change (Settings \u2192 Privacy), so do not retry."
452
+ };
453
+ }
454
+ if (code === "ZDR_KEY_UNAVAILABLE") {
455
+ return { ok: false, status: res.status, message: serverMessage || "no zero-retention provider key is available right now \u2014 try again later" };
456
+ }
457
+ if (/DAILY_CAP|LIMIT_REACHED/i.test(code) || res.status === 429) {
458
+ return { ok: false, status: res.status, message: serverMessage || "the account's daily media allowance is used up \u2014 it resets tomorrow" };
459
+ }
460
+ if (res.status === 402 || /INSUFFICIENT|QUOTA|TOP_?UP/i.test(code)) {
461
+ return { ok: false, status: res.status, message: serverMessage || "the account is out of credit for media generation \u2014 top up or upgrade to continue" };
462
+ }
463
+ if (res.status === 401) {
464
+ return {
465
+ ok: false,
466
+ status: res.status,
467
+ message: serverMessage || "Privateer refused this agent's session (401) \u2014 running the command again opens a fresh one; if it keeps failing, check `privateer auth status`"
468
+ };
469
+ }
470
+ if (res.status === 403) {
471
+ return {
472
+ ok: false,
473
+ status: res.status,
474
+ message: serverMessage || "Privateer refused this media request (403) \u2014 the plan may not include it; this is not a sign-in problem"
475
+ };
476
+ }
477
+ if (res.status === 400 || res.status === 413) {
478
+ return { ok: false, status: res.status, message: serverMessage || `Privateer rejected the request${code ? ` (${code})` : ""}` };
479
+ }
480
+ if (res.status === 503 || res.status === 504) {
481
+ return {
482
+ ok: false,
483
+ status: res.status,
484
+ message: `${serverMessage || "that media service is temporarily unavailable"} \u2014 this is on Privateer's side, not the prompt's; try again in a few minutes`
485
+ };
486
+ }
487
+ return { ok: false, status: res.status, message: serverMessage || `media generation failed (HTTP ${res.status}${code ? ` ${code}` : ""})` };
488
+ }
489
+ __name(interpretAccountResponse, "interpretAccountResponse");
490
+ var DEFERRED_SYNC_PATH = {
491
+ image: "/api/agent/media/images",
492
+ speech: "/api/audio/speech",
493
+ music: "/api/audio/music",
494
+ sfx: "/api/audio/sfx"
495
+ };
496
+ var DEFERRED_TOOL = {
497
+ image: "generate_image",
498
+ speech: "generate_speech",
499
+ music: "generate_music",
500
+ sfx: "generate_sfx"
501
+ };
502
+ var DEFERRED_POLL_MS = 3e3;
503
+ var DEFERRED_KEY_TTL_MS = 2 * 60 * 6e4;
504
+ function deferredKeyDir() {
505
+ return join3(globalDir(), "media-jobs");
506
+ }
507
+ __name(deferredKeyDir, "deferredKeyDir");
508
+ function saveDeferredKey(jobId, kind, key) {
509
+ const dir = deferredKeyDir();
510
+ mkdirSync3(dir, { recursive: true, mode: 448 });
511
+ try {
512
+ for (const f of readdirSync(dir)) {
513
+ const p = join3(dir, f);
514
+ try {
515
+ const { createdAt } = JSON.parse(readFileSync4(p, "utf8"));
516
+ if (!createdAt || Date.now() - createdAt > DEFERRED_KEY_TTL_MS) unlinkSync2(p);
517
+ } catch {
518
+ }
519
+ }
520
+ } catch {
521
+ }
522
+ writeFileSync4(join3(dir, `${jobId}.json`), JSON.stringify({ kind, key: key.toString("base64"), createdAt: Date.now() }), { mode: 384 });
523
+ }
524
+ __name(saveDeferredKey, "saveDeferredKey");
525
+ function loadDeferredKey(jobId) {
526
+ if (!/^amj_[0-9a-f]+$/.test(jobId)) return null;
527
+ try {
528
+ const raw = JSON.parse(readFileSync4(join3(deferredKeyDir(), `${jobId}.json`), "utf8"));
529
+ return { kind: raw.kind, key: Buffer.from(raw.key, "base64") };
530
+ } catch {
531
+ return null;
532
+ }
533
+ }
534
+ __name(loadDeferredKey, "loadDeferredKey");
535
+ function forgetDeferredKey(jobId) {
536
+ try {
537
+ unlinkSync2(join3(deferredKeyDir(), `${jobId}.json`));
538
+ } catch {
539
+ }
540
+ }
541
+ __name(forgetDeferredKey, "forgetDeferredKey");
542
+ function openSealedResult(key, sealedB64) {
543
+ const buf = Buffer.from(sealedB64, "base64");
544
+ const d = createDecipheriv("aes-256-gcm", key, buf.subarray(0, 12));
545
+ d.setAuthTag(buf.subarray(12, 28));
546
+ return JSON.parse(Buffer.concat([d.update(buf.subarray(28)), d.final()]).toString("utf8"));
547
+ }
548
+ __name(openSealedResult, "openSealedResult");
549
+ function deferredResumeHint(kind, jobId) {
550
+ return `Collect it with ${DEFERRED_TOOL[kind]} { resumeJobId: "${jobId}", path: <same path> } \u2014 that waits on this same job and bills nothing further.`;
551
+ }
552
+ __name(deferredResumeHint, "deferredResumeHint");
553
+ async function callDeferred(kind, body, opts) {
554
+ let jobId = String(opts.resumeJobId ?? "").trim();
555
+ let key;
556
+ if (jobId) {
557
+ const held = loadDeferredKey(jobId);
558
+ if (!held) {
559
+ return { ok: false, message: `no key for job ${jobId} on this machine \u2014 it was started elsewhere, already collected, or is over two hours old. Its result cannot be opened here.` };
560
+ }
561
+ if (held.kind !== kind) {
562
+ return { ok: false, message: `job ${jobId} is a ${held.kind} job; collect it with ${DEFERRED_TOOL[held.kind]}.` };
563
+ }
564
+ key = held.key;
565
+ } else {
566
+ key = randomBytes2(32);
567
+ const submitted = await callAccount("/api/agent/media/jobs", {
568
+ method: "POST",
569
+ signal: opts.signal,
570
+ body: { kind, sealKey: key.toString("base64"), request: body }
571
+ });
572
+ if (!submitted.ok) {
573
+ if (submitted.status === 404 || submitted.status === 405) {
574
+ return callAccount(DEFERRED_SYNC_PATH[kind], { method: "POST", body, signal: opts.signal });
575
+ }
576
+ return submitted;
577
+ }
578
+ jobId = String(submitted.data.jobId ?? "");
579
+ if (!jobId) return { ok: false, message: "Privateer accepted the job but returned no job id" };
580
+ saveDeferredKey(jobId, kind, key);
581
+ if (opts.wait === false) return { ok: "started", jobId };
582
+ }
583
+ const hint = deferredResumeHint(kind, jobId);
584
+ const deadline = Date.now() + MEDIA_HTTP_TIMEOUT_MS;
585
+ let failures = 0;
586
+ while (Date.now() < deadline) {
587
+ if (opts.signal?.aborted) {
588
+ return { ok: false, message: `stopped waiting \u2014 job ${jobId} keeps running on the server. ${hint}` };
589
+ }
590
+ const poll = await callAccount(`/api/agent/media/jobs/${encodeURIComponent(jobId)}`, { method: "GET", signal: opts.signal });
591
+ if (!poll.ok) {
592
+ if (spritePollWorthRetrying(poll.status) && ++failures < SPRITE_POLL_FAILURE_BUDGET) {
593
+ await sleep(DEFERRED_POLL_MS * 2, opts.signal);
594
+ continue;
595
+ }
596
+ if (poll.status === 404) forgetDeferredKey(jobId);
597
+ return { ok: false, status: poll.status, message: `job ${jobId} could not be collected: ${poll.message}${poll.status === 404 ? "" : `. ${hint}`}` };
598
+ }
599
+ failures = 0;
600
+ const status = String(poll.data.status ?? "");
601
+ if (status === "failed") {
602
+ forgetDeferredKey(jobId);
603
+ return { ok: false, message: poll.data.message ?? `job ${jobId} failed on the server` };
604
+ }
605
+ if (status === "done" && poll.data.sealed) {
606
+ let opened;
607
+ try {
608
+ opened = openSealedResult(key, poll.data.sealed);
609
+ } catch {
610
+ return { ok: false, message: `job ${jobId}'s result could not be opened with this machine's key` };
611
+ }
612
+ forgetDeferredKey(jobId);
613
+ void callAccount(`/api/agent/media/jobs/${encodeURIComponent(jobId)}`, { method: "DELETE" }).catch(() => {
614
+ });
615
+ return interpretAccountResponse(new Response(opened.body, { status: opened.status, headers: { "Content-Type": "application/json" } }));
616
+ }
617
+ await sleep(DEFERRED_POLL_MS, opts.signal);
618
+ }
619
+ return { ok: false, message: `job ${jobId} is still running after ${Math.round(MEDIA_HTTP_TIMEOUT_MS / 6e4)} minutes. ${hint}` };
620
+ }
621
+ __name(callDeferred, "callDeferred");
622
+ var deferredParams = {
623
+ resumeJobId: typebox_exports.Optional(typebox_exports.String({
624
+ description: "Collect a job started earlier (with wait:false, or one that timed out) instead of starting a new one. Nothing is generated and nothing is billed: it only waits and saves. Other generation fields are ignored; `path` still says where to save."
625
+ })),
626
+ wait: typebox_exports.Optional(typebox_exports.Boolean({
627
+ description: "Default true. Set false to start the generation and return its job id immediately, so you can start several at once and collect each later with resumeJobId. The job runs on Privateer's servers either way."
628
+ }))
629
+ };
630
+ function startedText(kind, jobId) {
631
+ return `Started ${kind} job ${jobId}; it is generating on Privateer's servers (results are held for up to an hour, sealed to this machine). ${deferredResumeHint(kind, jobId)}`;
632
+ }
633
+ __name(startedText, "startedText");
634
+ var generateImageToolDefinition = {
635
+ name: "generate_image",
636
+ label: "Generate Image",
637
+ description: "Generate an image from a text prompt and save it to disk. Optionally pass `images` \u2014 paths to images already on disk \u2014 to EDIT or COMPOSE instead: one input means 'change this picture per the prompt', several means 'combine these into one'. Billed to the user's Privateer account and subject to its privacy settings; the prompt and any input images pass through Privateer's servers in plaintext. The finished result is held on the server for up to an hour, encrypted to a key only this machine holds, until it is collected \u2014 the only readable copy is the file you name. Use the resulting path as the first frame of generate_video, or as slideshow material for video_compose.",
638
+ parameters: typebox_exports.Object({
639
+ prompt: typebox_exports.String({ description: "What the image should show. Be specific about subject, style, lighting and framing." }),
640
+ path: typebox_exports.String({ description: "Where to write the image, relative to cwd or absolute (e.g. 'frames/opening.png')." }),
641
+ images: typebox_exports.Optional(
642
+ typebox_exports.Array(typebox_exports.String(), {
643
+ description: "Paths to existing images to edit or combine. One = edit that image; several = use the first as the base and incorporate the rest. Omit to generate from the prompt alone."
644
+ })
645
+ ),
646
+ count: typebox_exports.Optional(typebox_exports.Number({ description: "How many variations to produce, 1-4. Above 1, files are suffixed -1, -2, \u2026 Defaults to 1." })),
647
+ aspectRatio: typebox_exports.Optional(typebox_exports.String({ description: "Aspect ratio, e.g. '16:9', '9:16', '1:1'. Defaults to the model's own." })),
648
+ size: typebox_exports.Optional(typebox_exports.String({ description: "Explicit pixel size if the model supports one, e.g. '1024x1024'." })),
649
+ model: typebox_exports.Optional(typebox_exports.String({ description: "Override the image model (e.g. 'google/gemini-3.1-flash-image'). Leave unset to use the one the user chose with /image-model, or the account default." })),
650
+ ...deferredParams
651
+ }),
652
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
653
+ const cwd = ctx?.cwd ?? process.cwd();
654
+ const prompt = String(params.prompt ?? "").trim();
655
+ const resuming = Boolean(String(params.resumeJobId ?? "").trim());
656
+ if (!prompt && !resuming) return text("Error: prompt is required.");
657
+ if (!params.path) return text("Error: path is required \u2014 say where to save the image.");
658
+ let inputs;
659
+ try {
660
+ inputs = resuming ? [] : (params.images ?? []).map((p) => readInputImage(cwd, p));
661
+ } catch (e) {
662
+ return text(`Error: ${e instanceof Error ? e.message : String(e)}`);
663
+ }
664
+ const count = Math.min(Math.max(1, Math.round(params.count ?? 1)), 4);
665
+ const model = effectiveMediaModel("image", params.model);
666
+ const r = await callDeferred("image", {
667
+ prompt,
668
+ n: count,
669
+ ...inputs.length ? { images: inputs } : {},
670
+ ...params.aspectRatio ? { aspectRatio: params.aspectRatio } : {},
671
+ ...params.size ? { imageSize: params.size } : {},
672
+ ...model ? { model } : {}
673
+ }, { signal, resumeJobId: params.resumeJobId, wait: params.wait });
674
+ if (r.ok === "started") return text(startedText("image", r.jobId));
675
+ if (!r.ok) return text(`Image generation failed: ${r.message}`);
676
+ const images = r.data.images ?? [];
677
+ if (images.length === 0) return text("Image generation returned no images.");
678
+ const target = abs(cwd, params.path);
679
+ const ext = extname(target) || extForMime(images[0].mimeType ?? "", ".png");
680
+ const stem = target.slice(0, target.length - extname(target).length);
681
+ const written = [];
682
+ for (const [i, img] of images.entries()) {
683
+ if (!img.data) continue;
684
+ const out = images.length === 1 ? `${stem}${ext}` : `${stem}-${i + 1}${ext}`;
685
+ written.push(writeOut(out, Buffer.from(img.data, "base64")));
686
+ }
687
+ if (written.length === 0) return text("Image generation returned no usable image data.");
688
+ const verb = resuming ? "Collected" : inputs.length ? inputs.length === 1 ? "Edited" : "Composed" : "Generated";
689
+ return text(`${verb} ${written.length} image${written.length === 1 ? "" : "s"} with ${r.data.model ?? "the account image model"}:
690
+ ${written.map((w) => ` ${w}`).join("\n")}`);
691
+ }
692
+ };
693
+ var generateVideoToolDefinition = {
694
+ name: "generate_video",
695
+ label: "Generate Video",
696
+ description: "Generate a video clip from a text prompt and save it to disk. Give `firstFrame` (a path to an image) to animate an existing picture, and `lastFrame` as well to interpolate between two stills \u2014 that pairing is how you keep several clips visually continuous: end one clip on a frame you extracted with video_compose, then start the next from it. Generation takes minutes and this tool waits for it. Expensive (roughly $0.10-$1 a clip) and billed to the user's Privateer account, so plan the shot before calling. Clip lengths and aspect ratios are model-specific \u2014 check media_capabilities first if unsure. Stitch the finished clips with video_compose.\nIf a call comes back saying the job is still running, DO NOT call this again with the same prompt \u2014 that bills a second generation. Call it with `resumeJobId` set to the job id it reported (and the same `path`) to keep waiting on the clip the account has already paid for.",
697
+ parameters: typebox_exports.Object({
698
+ prompt: typebox_exports.String({ description: "What happens in the shot: subject, action, camera move, style." }),
699
+ path: typebox_exports.String({ description: "Where to write the video, relative to cwd or absolute (e.g. 'clips/01-opening.mp4')." }),
700
+ resumeJobId: typebox_exports.Optional(typebox_exports.String({
701
+ description: "Resume waiting on a job already submitted (from a previous call that timed out). Nothing is generated and nothing is billed: it only polls and saves. `prompt` is ignored."
702
+ })),
703
+ firstFrame: typebox_exports.Optional(typebox_exports.String({ description: "Path to an image to use as the opening frame (image-to-video)." })),
704
+ lastFrame: typebox_exports.Optional(typebox_exports.String({ description: "Path to an image to use as the closing frame. Requires firstFrame." })),
705
+ seconds: typebox_exports.Optional(typebox_exports.Number({ description: "Clip length in seconds. Only certain values are legal per model \u2014 see media_capabilities." })),
706
+ aspectRatio: typebox_exports.Optional(typebox_exports.String({ description: "Aspect ratio, e.g. '16:9', '9:16'. Model-specific." })),
707
+ resolution: typebox_exports.Optional(typebox_exports.String({ description: "Resolution, e.g. '720p' or '1080p'." })),
708
+ audio: typebox_exports.Optional(typebox_exports.Boolean({ description: "Ask the model to generate a soundtrack too, where it supports one. Costs more. Defaults to false." })),
709
+ model: typebox_exports.Optional(typebox_exports.String({ description: "Override the video model (e.g. 'google/veo-3.1-lite'). Leave unset to use the one the user chose with /video-model, or the account default." }))
710
+ }),
711
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
712
+ const cwd = ctx?.cwd ?? process.cwd();
713
+ if (!params.path) return text("Error: path is required \u2014 say where to save the video.");
714
+ const resumeJobId = String(params.resumeJobId ?? "").trim();
715
+ if (resumeJobId) {
716
+ return awaitVideoJob(resumeJobId, cwd, params.path, null, signal);
717
+ }
718
+ const prompt = String(params.prompt ?? "").trim();
719
+ if (!prompt) return text("Error: prompt is required.");
720
+ if (params.lastFrame && !params.firstFrame) return text("Error: lastFrame needs firstFrame alongside it.");
721
+ let firstFrame;
722
+ let lastFrame;
723
+ try {
724
+ if (params.firstFrame) firstFrame = readInputImage(cwd, params.firstFrame);
725
+ if (params.lastFrame) lastFrame = readInputImage(cwd, params.lastFrame);
726
+ } catch (e) {
727
+ return text(`Error: ${e instanceof Error ? e.message : String(e)}`);
728
+ }
729
+ const model = effectiveMediaModel("video", params.model);
730
+ const submitted = await callAccount("/api/agent/media/videos", {
731
+ method: "POST",
732
+ signal,
733
+ body: {
734
+ prompt,
735
+ ...params.seconds != null ? { seconds: params.seconds } : {},
736
+ ...params.aspectRatio ? { aspectRatio: params.aspectRatio } : {},
737
+ ...params.resolution ? { resolution: params.resolution } : {},
738
+ ...params.audio ? { generateAudio: true } : {},
739
+ ...model ? { model } : {},
740
+ ...firstFrame ? { firstFrame } : {},
741
+ ...lastFrame ? { lastFrame } : {}
742
+ }
743
+ });
744
+ if (!submitted.ok) return text(`Video generation failed: ${submitted.message}`);
745
+ const jobId = submitted.data.jobId;
746
+ if (!jobId) return text("Video generation failed: Privateer did not return a job id.");
747
+ return awaitVideoJob(jobId, cwd, params.path, submitted.data.model ?? null, signal);
748
+ }
749
+ };
750
+ async function awaitVideoJob(jobId, cwd, path, submittedModel, signal) {
751
+ const deadline = Date.now() + VIDEO_POLL_TIMEOUT_MS;
752
+ const resumeHint = `Resume it with generate_video { resumeJobId: "${jobId}", path: "${path}" } \u2014 that waits on this same clip and bills nothing further.`;
753
+ const cancelled = /* @__PURE__ */ __name(() => text(`Video job ${jobId} is still running and will still be billed; the wait was cancelled. ${resumeHint}`), "cancelled");
754
+ for (; ; ) {
755
+ if (signal?.aborted) return cancelled();
756
+ await sleep(VIDEO_POLL_INTERVAL_MS, signal);
757
+ if (signal?.aborted) return cancelled();
758
+ const poll = await callAccount(`/api/agent/media/videos/${encodeURIComponent(jobId)}`, {
759
+ method: "GET",
760
+ signal
761
+ });
762
+ if (!poll.ok) return text(`Video job ${jobId} could not be polled: ${poll.message}. ${resumeHint}`);
763
+ const status = String(poll.data.status ?? "").toLowerCase();
764
+ if (status === "failed") return text(`Video generation failed: ${poll.data.message ?? "the provider reported a failure"}.`);
765
+ if (status === "completed") {
766
+ if (!poll.data.data) {
767
+ return text(`Video job ${jobId} already delivered its bytes on an earlier poll; they were not saved. Generate again if the file is missing.`);
768
+ }
769
+ const target = abs(cwd, path);
770
+ const ext = extname(target) || extForMime(poll.data.mimeType ?? "", ".mp4");
771
+ const out = `${target.slice(0, target.length - extname(target).length)}${ext}`;
772
+ const summary = writeOut(out, Buffer.from(poll.data.data, "base64"));
773
+ return text(`Generated video with ${poll.data.model ?? submittedModel ?? "the account video model"}: ${summary}`);
774
+ }
775
+ if (Date.now() > deadline) {
776
+ return text(
777
+ `Video job ${jobId} is still ${status || "running"} after ${Math.round(VIDEO_POLL_TIMEOUT_MS / 6e4)} minutes. It will still complete and is already billed \u2014 do NOT generate it again. ${resumeHint}`
778
+ );
779
+ }
780
+ }
781
+ }
782
+ __name(awaitVideoJob, "awaitVideoJob");
783
+ function sleep(ms, signal) {
784
+ return new Promise((resolve_) => {
785
+ const t = setTimeout(resolve_, ms);
786
+ signal?.addEventListener("abort", () => {
787
+ clearTimeout(t);
788
+ resolve_();
789
+ }, { once: true });
790
+ });
791
+ }
792
+ __name(sleep, "sleep");
793
+ var generateModelToolDefinition = {
794
+ name: "generate_model",
795
+ label: "Generate 3D Model",
796
+ description: "Generate a 3D MESH \u2014 a .glb (or .obj) file for a game engine or DCC tool \u2014 from one or more reference images. (This makes 3D geometry; it has nothing to do with language models.) There is no text-to-mesh here: generate the concept art with generate_image first, look at it, and pass that path as `images` \u2014 which also means the shape is generated from a look someone approved rather than from a sentence. Supply up to four views (front, back, left, right) of the SAME object to stop the model inventing the sides it cannot see; on some models that costs more and it is usually worth it. Generation takes a minute or more and this tool waits for it. EXPENSIVE and billed to the user's Privateer account: $0.14 to $2.41 a mesh depending on WHICH model and which options, so plan the asset before calling and tell the user the total before batching dozens of them.\nThere are ten models from five vendors and they are not interchangeable \u2014 the dearest costs seventeen times the cheapest, and each takes DIFFERENT options. Call media_capabilities (with `model` set) to see a model's own options and price before choosing; pass what you picked as `axes`. Blocking out a shape is a job for the cheap end; a hero asset is not. PRIVACY: 3D generation runs on a provider with no zero-retention option, so it is gated \u2014 a ZDR account must have enabled non-ZDR media. Call media_capabilities first if unsure.",
797
+ parameters: typebox_exports.Object({
798
+ images: typebox_exports.Array(typebox_exports.String(), {
799
+ description: "Paths to reference images of one object, best view first. 1-4 of them, read as front, back, left, right. How many are actually USED is per-model \u2014 media_capabilities reports `maxViews`, and several models take a single view and will quietly ignore the rest, so check before generating four images to feed one. Where extra views are used they give the model the sides it would otherwise invent; on the Hunyuan models they add $0.15 in total (not each) and are free elsewhere."
800
+ }),
801
+ path: typebox_exports.String({
802
+ description: "Where to write the mesh, relative to cwd or absolute (e.g. 'assets/props/crate.glb'). The extension is corrected to whatever container is actually delivered."
803
+ }),
804
+ format: typebox_exports.Optional(
805
+ typebox_exports.String({
806
+ description: "Container: 'glb' (default) or 'obj'. Prefer glb \u2014 it is the only one that carries the materials, so an 'obj' of a textured mesh arrives as bare geometry, and 'obj' is not produced at all for generateType 'Geometry'. Falls back to glb whenever the provider doesn't render it."
807
+ })
808
+ ),
809
+ // `additionalProperties`, not Type.Record: TypeBox compiles a Record to
810
+ // `patternProperties`, which several providers' tool-schema validators
811
+ // reject outright — and a tool whose schema is refused fails at the provider
812
+ // with a message about JSON Schema rather than about 3D.
813
+ axes: typebox_exports.Optional(
814
+ typebox_exports.Object({}, {
815
+ additionalProperties: typebox_exports.Union([typebox_exports.String(), typebox_exports.Number(), typebox_exports.Boolean()]),
816
+ description: "The chosen model's own options, as {name: value} \u2014 the ONLY way to reach the options on any model except the Hunyuan ones, since no two endpoints share their levers (one takes `resolution`, another a `texture` ladder, another a `highPack` flag). Get the exact names and legal values from media_capabilities with the same `model`; an option this model does not have is REFUSED, not ignored, so do not guess. Omit an option to take the model's own default, which for a numeric budget means letting the provider choose \u2014 on some models setting it at all is what costs extra."
817
+ })
818
+ ),
819
+ generateType: typebox_exports.Optional(
820
+ typebox_exports.String({
821
+ description: "Hunyuan models only (prefer `axes` elsewhere). 'Normal' ($0.375, default) \u2014 textured mesh. 'LowPoly' ($0.45) \u2014 retopologised, best for a game asset that will deform or needs clean edges; dearer because it is more work, not less. 'Geometry' ($0.225) \u2014 untextured geometry only, for blockouts and greyboxing."
822
+ })
823
+ ),
824
+ polygonType: typebox_exports.Optional(
825
+ typebox_exports.String({
826
+ description: "Hunyuan models only (prefer `axes` elsewhere). 'triangle' (default) or 'quadrilateral'. Quads deform far better under animation, so choose them for anything that will be rigged; triangles are fine for static props."
827
+ })
828
+ ),
829
+ faceCount: typebox_exports.Optional(
830
+ typebox_exports.Number({
831
+ description: "Target face budget, honoured exactly; the legal range is per-model (media_capabilities reports it). On the Hunyuan models it ADDS $0.15 because the provider charges for a custom count, and leaving it unset uses their 500k default \u2014 measured at 8.6 MB untextured and 64 MB textured, against 15 MB for a textured 60k mesh. Free on most other models. Set it for anything going into a game."
832
+ })
833
+ ),
834
+ pbr: typebox_exports.Optional(
835
+ typebox_exports.Boolean({
836
+ description: "Generate PBR materials (base colour, normal, roughness/metallic) instead of a flat texture. Essential for anything lit by a modern engine. ADDS $0.15 on the Hunyuan models and is free on Tripo and Meshy \u2014 which is why the price comes from media_capabilities and not from here. Refused on any model generating untextured geometry."
837
+ })
838
+ ),
839
+ model: typebox_exports.Optional(
840
+ typebox_exports.String({
841
+ description: "Which 3D model to use, e.g. 'fal-ai/hyper3d/rodin/v2.5/fast' for a cheap blockout or 'meshy/v7/image-to-3d' for a game-ready hero asset. media_capabilities lists every id with its price. Leave unset to use the account default."
842
+ })
843
+ )
844
+ }),
845
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
846
+ const cwd = ctx?.cwd ?? process.cwd();
847
+ const paths = params.images ?? [];
848
+ if (paths.length === 0) return text("Error: at least one reference image is required \u2014 generate one with generate_image first.");
849
+ if (paths.length > MAX_MESH_VIEWS) {
850
+ return text(`Error: at most ${MAX_MESH_VIEWS} reference views (front, back, left, right); got ${paths.length}.`);
851
+ }
852
+ if (!params.path) return text("Error: path is required \u2014 say where to save the mesh.");
853
+ let images;
854
+ try {
855
+ images = paths.map((p) => readInputImage(cwd, p));
856
+ } catch (e) {
857
+ return text(`Error: ${e instanceof Error ? e.message : String(e)}`);
858
+ }
859
+ const totalBytes = images.reduce((sum, img) => sum + Math.floor(img.data.length * 3 / 4), 0);
860
+ if (totalBytes > MAX_MESH_INPUT_TOTAL_BYTES) {
861
+ return text(
862
+ `Error: the reference views total ${(totalBytes / 1048576).toFixed(1)} MB; the limit for one request is ${MAX_MESH_INPUT_TOTAL_BYTES / 1048576} MB. Use fewer views, or downscale them first.`
863
+ );
864
+ }
865
+ const submitted = await callAccount("/api/agent/media/models", {
866
+ method: "POST",
867
+ signal,
868
+ body: {
869
+ images,
870
+ ...params.format ? { format: params.format } : {},
871
+ // `axes` wins over the named fields server-side, so a model passing both
872
+ // gets what it spelled out per-axis. The named four are sent alongside
873
+ // rather than folded in here: which of them the chosen model actually
874
+ // has is the server's business, and duplicating that judgement in the
875
+ // tool is how the two get to disagree.
876
+ ...params.axes && typeof params.axes === "object" ? { axes: params.axes } : {},
877
+ ...params.generateType ? { generateType: params.generateType } : {},
878
+ ...params.polygonType ? { polygonType: params.polygonType } : {},
879
+ ...params.faceCount != null ? { faceCount: params.faceCount } : {},
880
+ ...params.pbr ? { pbr: true } : {},
881
+ ...params.model ? { model: params.model } : {}
882
+ }
883
+ });
884
+ if (!submitted.ok) return text(`3D generation failed: ${submitted.message}`);
885
+ const jobId = submitted.data.jobId;
886
+ if (!jobId) return text("3D generation failed: Privateer did not return a job id.");
887
+ const deadline = Date.now() + MESH_POLL_TIMEOUT_MS;
888
+ const cancelled = /* @__PURE__ */ __name(() => text(`3D job ${jobId} was submitted but the wait was cancelled. It is still running and will still be billed.`), "cancelled");
889
+ for (; ; ) {
890
+ if (signal?.aborted) return cancelled();
891
+ await sleep(MESH_POLL_INTERVAL_MS, signal);
892
+ if (signal?.aborted) return cancelled();
893
+ const poll = await callAccount(`/api/agent/media/models/${encodeURIComponent(jobId)}`, {
894
+ method: "GET",
895
+ signal
896
+ });
897
+ if (!poll.ok) return text(`3D job ${jobId} could not be polled: ${poll.message}`);
898
+ const status = String(poll.data.status ?? "").toLowerCase();
899
+ if (status === "failed") return text(`3D generation failed: ${poll.data.message ?? "the provider reported a failure"}.`);
900
+ if (status === "completed") {
901
+ if (!poll.data.data) {
902
+ return text(`3D job ${jobId} already delivered its bytes on an earlier poll; they were not saved. Generate again if the file is missing.`);
903
+ }
904
+ const delivered = String(poll.data.format || "glb").toLowerCase();
905
+ const target = abs(cwd, params.path);
906
+ const asked = extname(target).replace(/^\./, "").toLowerCase();
907
+ const out = `${target.slice(0, target.length - extname(target).length)}.${delivered}`;
908
+ const summary = writeOut(out, Buffer.from(poll.data.data, "base64"));
909
+ const note = asked && asked !== delivered ? `
910
+ (Asked for .${asked}; the provider returned ${delivered.toUpperCase()}, so the file was saved with that extension.)` : "";
911
+ return text(`Generated 3D model with ${poll.data.model ?? submitted.data.model ?? "the account 3D model"}: ${summary}${note}`);
912
+ }
913
+ if (Date.now() > deadline) {
914
+ return text(
915
+ `3D job ${jobId} is still ${status || "running"} after ${Math.round(MESH_POLL_TIMEOUT_MS / 6e4)} minutes. It will still complete and still be billed; nothing was saved here.`
916
+ );
917
+ }
918
+ }
919
+ }
920
+ };
921
+ var generateSpeechToolDefinition = {
922
+ name: "generate_speech",
923
+ label: "Generate Speech",
924
+ description: "Turn text into spoken audio and save it to disk. Use it to narrate a video you are assembling, or to produce a spoken version of a written answer. Billed to the user's Privateer account; the account's default voice model is a confidential-compute one, so the text is processed inside an enclave rather than by a retaining provider. Mux the result onto video with video_compose. Call media_capabilities first if you want to override `voice` or `model` \u2014 it lists the exact wire voice ids for the account's current TTS model (and any model you pass it), which is not the same as a spoken character or brand name.",
925
+ parameters: typebox_exports.Object({
926
+ text: typebox_exports.String({ description: "The words to speak. Write them as they should be read aloud." }),
927
+ path: typebox_exports.String({ description: "Where to write the audio, relative to cwd or absolute (e.g. 'audio/narration.mp3')." }),
928
+ voice: typebox_exports.Optional(typebox_exports.String({
929
+ description: "Voice id, if the account's TTS model offers a choice. Leave unset for its default. These are PROVIDER wire ids, not free text \u2014 e.g. Deepgram Aura-2 voices are 'aura-2-<name>-<lang>' ('aura-2-jupiter-en', not 'jupiter' or 'Jupiter'). Get the exact legal list for the model in play from media_capabilities' `speech.voices` before guessing one; an unrecognised id is refused with VOICE_UNSUPPORTED rather than silently served on a different voice."
930
+ })),
931
+ model: typebox_exports.Optional(typebox_exports.String({ description: "Override the account's text-to-speech model." })),
932
+ ...deferredParams
933
+ }),
934
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
935
+ const cwd = ctx?.cwd ?? process.cwd();
936
+ const body = String(params.text ?? "").trim();
937
+ if (!body && !String(params.resumeJobId ?? "").trim()) return text("Error: text is required.");
938
+ if (!params.path) return text("Error: path is required \u2014 say where to save the audio.");
939
+ const r = await callDeferred("speech", {
940
+ text: body,
941
+ ...params.voice ? { voice: params.voice } : {},
942
+ ...params.model ? { ttsModelId: params.model } : {}
943
+ }, { signal, resumeJobId: params.resumeJobId, wait: params.wait });
944
+ if (r.ok === "started") return text(startedText("speech", r.jobId));
945
+ if (!r.ok) return text(`Speech generation failed: ${r.message}`);
946
+ if (!r.data.audioBase64) return text("Speech generation returned no audio.");
947
+ const target = abs(cwd, params.path);
948
+ const ext = extname(target) || extForMime(r.data.mimeType ?? "", ".mp3");
949
+ const out = `${target.slice(0, target.length - extname(target).length)}${ext}`;
950
+ const via = [r.data.model, r.data.voice].filter(Boolean).join(" / ");
951
+ return text(
952
+ `Generated speech${via ? ` with ${via}` : ""}: ${writeOut(out, Buffer.from(r.data.audioBase64, "base64"))}`
953
+ );
954
+ }
955
+ };
956
+ var generateMusicToolDefinition = {
957
+ name: "generate_music",
958
+ label: "Generate Music",
959
+ description: "Generate an instrumental music clip from a text prompt and save it to disk \u2014 a soundtrack for a video you are assembling. PRIVACY: music is the one media type with no zero-retention or confidential option anywhere in the catalog, so the prompt reaches a provider that may retain it. Privateer sends it unattributed (no account id, no history), but it is not private the way the other media tools are. Do not put anything sensitive or personal in a music prompt, and say so if the user's own wording would carry something identifying.",
960
+ parameters: typebox_exports.Object({
961
+ prompt: typebox_exports.String({ description: "The music to generate: genre, mood, instrumentation, tempo. Keep it about the music, not about the user." }),
962
+ path: typebox_exports.String({ description: "Where to write the audio, relative to cwd or absolute (e.g. 'audio/score.mp3')." }),
963
+ model: typebox_exports.Optional(typebox_exports.String({ description: "Override the account's music model." })),
964
+ ...deferredParams
965
+ }),
966
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
967
+ const cwd = ctx?.cwd ?? process.cwd();
968
+ const prompt = String(params.prompt ?? "").trim();
969
+ if (!prompt && !String(params.resumeJobId ?? "").trim()) return text("Error: prompt is required.");
970
+ if (!params.path) return text("Error: path is required \u2014 say where to save the audio.");
971
+ const r = await callDeferred(
972
+ "music",
973
+ { prompt, ...params.model ? { musicModelId: params.model } : {} },
974
+ { signal, resumeJobId: params.resumeJobId, wait: params.wait }
975
+ );
976
+ if (r.ok === "started") return text(startedText("music", r.jobId));
977
+ if (!r.ok) return text(`Music generation failed: ${r.message}`);
978
+ if (!r.data.audioBase64) return text("Music generation returned no audio.");
979
+ const target = abs(cwd, params.path);
980
+ const ext = extname(target) || extForMime(r.data.mimeType ?? "", ".mp3");
981
+ const out = `${target.slice(0, target.length - extname(target).length)}${ext}`;
982
+ return text(
983
+ `Generated music with ${r.data.model ?? "the account music model"}: ${writeOut(out, Buffer.from(r.data.audioBase64, "base64"))}
984
+ (Reminder for the answer you give the user: music prompts are sent to a provider with no zero-retention option, unattributed.)`
985
+ );
986
+ }
987
+ };
988
+ var SFX_MIN_SECONDS = 1;
989
+ var SFX_MAX_SECONDS = 30;
990
+ var generateSfxToolDefinition = {
991
+ name: "generate_sfx",
992
+ label: "Generate Sound Effect",
993
+ description: "Generate a single sound effect from a text prompt and save it to disk \u2014 an impact, a whoosh, a UI click, a room ambience. Cheap (about $0.01-$0.02 a call) and quick. This is for ONE sound, not for a score: use generate_music for a bed and generate_speech for narration. Place the result in time with video_compose's mix_audio, which is what makes an effect land on the frame it belongs to.\nPRIVACY: every effect model is a non-zero-retention provider, so this is gated exactly like image and video generation \u2014 an account with Require ZDR on is REFUSED until its owner enables non-ZDR media. That is a setting only they can change, so do not retry a refusal. (Do not reach for generate_music instead on privacy grounds: music has no ZDR gate at all, which is looser, not safer.) Check media_capabilities if you need to know whether this account can use it before you plan a sequence around a dozen effects.",
994
+ parameters: typebox_exports.Object({
995
+ prompt: typebox_exports.String({
996
+ description: "The sound itself, described as a sound: 'heavy wooden door slamming shut, close mic, reverberant hall'. Effect models are tuned for one event, so keep it to one \u2014 a scene comes out muddy."
997
+ }),
998
+ path: typebox_exports.String({ description: "Where to write the audio, relative to cwd or absolute (e.g. 'audio/sfx/door-slam.mp3')." }),
999
+ seconds: typebox_exports.Optional(
1000
+ typebox_exports.Number({
1001
+ description: `How long the effect should be, ${SFX_MIN_SECONDS}-${SFX_MAX_SECONDS} whole seconds. Defaults to 5. One of the models is billed by the second, so ask for what you need.`
1002
+ })
1003
+ ),
1004
+ model: typebox_exports.Optional(
1005
+ typebox_exports.String({
1006
+ description: "Override the account's effect model. 'fal-ai/elevenlabs/sound-effects/v2' is the most convincing foley in the catalog; the default is a cheaper model tuned for single sounds."
1007
+ })
1008
+ ),
1009
+ ...deferredParams
1010
+ }),
1011
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
1012
+ const cwd = ctx?.cwd ?? process.cwd();
1013
+ const prompt = String(params.prompt ?? "").trim();
1014
+ if (!prompt && !String(params.resumeJobId ?? "").trim()) return text("Error: prompt is required.");
1015
+ if (!params.path) return text("Error: path is required \u2014 say where to save the audio.");
1016
+ let seconds;
1017
+ if (params.seconds != null) {
1018
+ seconds = Number(params.seconds);
1019
+ if (!Number.isFinite(seconds) || seconds < SFX_MIN_SECONDS || seconds > SFX_MAX_SECONDS) {
1020
+ return text(
1021
+ `Error: seconds must be between ${SFX_MIN_SECONDS} and ${SFX_MAX_SECONDS} (got ${params.seconds}). For anything longer, generate a few effects and place them with video_compose mix_audio, or use generate_music for a bed.`
1022
+ );
1023
+ }
1024
+ seconds = Math.round(seconds);
1025
+ }
1026
+ const r = await callDeferred("sfx", {
1027
+ prompt,
1028
+ ...seconds != null ? { duration: seconds } : {},
1029
+ ...params.model ? { sfxModelId: params.model } : {}
1030
+ }, { signal, resumeJobId: params.resumeJobId, wait: params.wait });
1031
+ if (r.ok === "started") return text(startedText("sfx", r.jobId));
1032
+ if (!r.ok) return text(`Sound-effect generation failed: ${r.message}`);
1033
+ if (!r.data.audioBase64) return text("Sound-effect generation returned no audio.");
1034
+ const target = abs(cwd, params.path);
1035
+ const ext = extname(target) || extForMime(r.data.mimeType ?? "", ".mp3");
1036
+ const out = `${target.slice(0, target.length - extname(target).length)}${ext}`;
1037
+ const length = r.data.durationSeconds ? `${r.data.durationSeconds}s ` : "";
1038
+ return text(
1039
+ `Generated a ${length}sound effect with ${r.data.model ?? "the account effect model"}: ` + writeOut(out, Buffer.from(r.data.audioBase64, "base64"))
1040
+ );
1041
+ }
1042
+ };
1043
+ function describeModel3d(model3d) {
1044
+ if (model3d?.configured === false) {
1045
+ return ["3D model generation: NOT AVAILABLE on this deployment (no provider key). Do not call generate_model."];
1046
+ }
1047
+ const lines = [
1048
+ `3D model: ${model3d?.model ?? "unknown"}${model3d?.blockedByZdr ? " [BLOCKED by this account's ZDR setting]" : ""}`,
1049
+ ` formats: ${model3d?.formats?.length ? model3d.formats.join(", ") : "glb"}; up to ${model3d?.maxViews ?? 4} reference view(s)`,
1050
+ ` cost: $${(model3d?.priceUsd?.min ?? 0).toFixed(2)}-$${(model3d?.priceUsd?.max ?? 0).toFixed(2)} charged per mesh, depending on the options below`
1051
+ ];
1052
+ if (model3d?.axes?.length) {
1053
+ lines.push(` options (pass as generate_model's \`axes\`, e.g. {"${model3d.axes[0].name}": ...}):`);
1054
+ for (const a of model3d.axes) lines.push(describeAxis(a));
1055
+ }
1056
+ for (const c of model3d?.conflicts ?? []) {
1057
+ lines.push(` NOTE: ${c.forbids} cannot be used when ${c.whenAxis} is ${JSON.stringify(c.is)}.`);
1058
+ }
1059
+ if (model3d?.catalog?.length) {
1060
+ lines.push(" every 3D model available (pass `model` to generate_model, or to this tool to see its options):");
1061
+ for (const m of model3d.catalog) {
1062
+ const p = m.priceUsd ? ` $${(m.priceUsd.min ?? 0).toFixed(2)}-$${(m.priceUsd.max ?? 0).toFixed(2)}` : "";
1063
+ lines.push(` ${m.id}${p}${m.id === model3d.model ? " [described above]" : ""}`);
1064
+ }
1065
+ }
1066
+ return lines;
1067
+ }
1068
+ __name(describeModel3d, "describeModel3d");
1069
+ function describeAxis(a) {
1070
+ const cost = a.priced ? " [affects price]" : "";
1071
+ if (a.kind === "int") return ` ${a.name}: number ${a.min ?? "?"}-${a.max ?? "?"}, omit to let the provider choose${cost}`;
1072
+ if (a.kind === "views") return ` ${a.name}: driven by how many images you pass${cost}`;
1073
+ if (a.kind === "bool") return ` ${a.name}: true | false (default ${a.default === true})${cost}`;
1074
+ return ` ${a.name}: ${(a.values ?? []).join(" | ")} (default ${String(a.default)})${cost}`;
1075
+ }
1076
+ __name(describeAxis, "describeAxis");
1077
+ var usd = /* @__PURE__ */ __name((n) => `$${(n ?? 0).toFixed(2)}`, "usd");
1078
+ function describeImageVideo(image, video) {
1079
+ const imagePrice = typeof image?.priceUsdEach === "number" ? `, about ${usd(image.priceUsdEach)} each` : ", price not reported";
1080
+ const lines = [
1081
+ `Image model: ${image?.model ?? "unknown"}${image?.blockedByZdr ? " [BLOCKED by this account's ZDR setting]" : ""}`,
1082
+ ` up to ${image?.maxPerCall ?? 1} image(s) per call${imagePrice}`,
1083
+ `Video model: ${video?.model ?? "unknown"}${video?.blockedByZdr ? " [BLOCKED by this account's ZDR setting]" : ""}`,
1084
+ ` clip lengths: ${video?.durations?.length ? `${video.durations.join(", ")}s` : "model default only"}`,
1085
+ ` aspect ratios: ${video?.aspectRatios?.length ? video.aspectRatios.join(", ") : "model default only"}`
1086
+ ];
1087
+ const table = video?.priceTable ?? [];
1088
+ if (video?.priceUsd && table.length) {
1089
+ const fallback = video.priceSource === "fallback" ? " (no price row for this model \u2014 a conservative estimate)" : "";
1090
+ lines.push(` cost: ${usd(video.priceUsd.min)}-${usd(video.priceUsd.max)} a clip${fallback}, reserved up front and settled at the real cost`);
1091
+ const plain = table.filter((r) => r.resolution === null && !r.audio && r.seconds !== null);
1092
+ if (plain.length) lines.push(` by length (default resolution, no audio): ${plain.map((r) => `${r.seconds}s ${usd(r.usd)}`).join(", ")}`);
1093
+ const resolutions = [...new Set(table.map((r) => r.resolution).filter((r) => !!r))];
1094
+ if (resolutions.length) lines.push(` resolution changes the price: ${resolutions.join(", ")} (pass generate_video's \`resolution\`)`);
1095
+ if (table.some((r) => r.audio)) lines.push(" audio: true costs more on this model");
1096
+ } else {
1097
+ lines.push(" cost: not reported by this server \u2014 roughly $0.10-$1 a clip, more for long or high-resolution clips");
1098
+ }
1099
+ return lines;
1100
+ }
1101
+ __name(describeImageVideo, "describeImageVideo");
1102
+ function describeSfx(sfx) {
1103
+ if (sfx?.configured === false) {
1104
+ return ["Sound effects: NOT AVAILABLE on this deployment (no provider key). Do not call generate_sfx."];
1105
+ }
1106
+ if (sfx?.blockedByZdr) {
1107
+ return [
1108
+ `Sound effects: ${sfx.model ?? "unknown"} [BLOCKED by this account's ZDR setting]`,
1109
+ " Every effect model is non-ZDR, so this account cannot generate one until its owner enables non-ZDR media (Settings \u2192 Privacy). Do not substitute generate_music for an effect \u2014 it is ungated, not more private."
1110
+ ];
1111
+ }
1112
+ return [
1113
+ `Sound effects: ${sfx?.model ?? "unknown"}`,
1114
+ ` up to ${sfx?.maxDurationSeconds ?? SFX_MAX_SECONDS}s per effect, one sound per call, ~$0.01-$0.02 each`
1115
+ ];
1116
+ }
1117
+ __name(describeSfx, "describeSfx");
1118
+ function describeSpeech(speech) {
1119
+ const blocked = speech?.blockedByZdr ? " [BLOCKED by this account's ZDR setting]" : "";
1120
+ const lines = [`Speech model: ${speech?.model ?? "unknown"}${blocked}`];
1121
+ if (speech?.blockedByZdr) {
1122
+ lines.push(
1123
+ " This voice model is non-ZDR, so this account cannot use it until its owner enables non-ZDR media (Settings \u2192 Privacy). Omit `model` to use the account's confidential-compute default instead of retrying this one."
1124
+ );
1125
+ }
1126
+ if (speech?.voices?.length) {
1127
+ lines.push(
1128
+ ` ${speech.voices.length} voice id(s) for this model \u2014 pass one of these EXACTLY as generate_speech's \`voice\`, never a guessed name: ${speech.voices.join(", ")}`
1129
+ );
1130
+ } else {
1131
+ lines.push(" No enumerable voice list for this model; omit `voice` to use its default.");
1132
+ }
1133
+ if (speech?.catalog?.length) {
1134
+ lines.push(" every TTS model available (pass `ttsModel` to this tool to see its voices):");
1135
+ for (const m of speech.catalog) {
1136
+ const tags = [m.isTee ? "confidential" : m.isZdr ? "ZDR" : "non-ZDR", `${m.voiceCount ?? 0} voice(s)`];
1137
+ if (m.blockedByZdr) tags.push("BLOCKED");
1138
+ lines.push(
1139
+ ` ${m.id} (${tags.join(", ")})${m.id === speech.model ? " [described above]" : ""}`
1140
+ );
1141
+ }
1142
+ }
1143
+ return lines;
1144
+ }
1145
+ __name(describeSpeech, "describeSpeech");
1146
+ var mediaCapabilitiesToolDefinition = {
1147
+ name: "media_capabilities",
1148
+ label: "Media Capabilities",
1149
+ description: "Report what this Privateer account can generate right now: which image and video models it resolves to, what an image and a clip cost, the clip lengths and aspect ratios that video model accepts, and whether the account's privacy settings currently block media generation. Free and instant. Call it before planning a multi-clip video so you pick a legal clip length instead of discovering it through a rejected \u2014 or worse, billed \u2014 call.\nIt is also the ONLY way to find out which 3D models exist and what options each one takes: they range from $0.14 to $2.41 a mesh and no two take the same options, so call this with `model` set to the id you are considering BEFORE generate_model, or you will pay the default model's price for a job a cheaper one could have done.\nIt is also the ONLY way to find a text-to-speech model's real voice ids \u2014 Deepgram Aura-2's are 'aura-2-<name>-<lang>', not a bare character name \u2014 so call this with `ttsModel` set BEFORE generate_speech whenever you plan to pass `voice`.",
1150
+ parameters: typebox_exports.Object({
1151
+ model: typebox_exports.Optional(
1152
+ typebox_exports.String({
1153
+ description: "A 3D model id to describe instead of the account default (e.g. 'fal-ai/trellis-2'). The response's 3D catalog lists every legal id; every field reported \u2014 the options, their legal values and the price \u2014 is per-model."
1154
+ })
1155
+ ),
1156
+ imageModel: typebox_exports.Optional(
1157
+ typebox_exports.String({
1158
+ description: "An image model id to describe instead of the default (e.g. 'google/gemini-3.1-flash-image'), so the price per image is the one generate_image will charge for it."
1159
+ })
1160
+ ),
1161
+ videoModel: typebox_exports.Optional(
1162
+ typebox_exports.String({
1163
+ description: "A video model id to describe instead of the default (e.g. 'bytedance/seedance-2.0'). Clip lengths, aspect ratios and the price per clip are all per-model \u2014 check the one you will pass as generate_video's `model` before you spend on it."
1164
+ })
1165
+ ),
1166
+ ttsModel: typebox_exports.Optional(
1167
+ typebox_exports.String({
1168
+ description: "A text-to-speech model id to describe instead of the account default (e.g. 'deepgram/aura-2'). The response's `speech.voices` lists every legal voice id for THIS model \u2014 voice ids are not shared across models."
1169
+ })
1170
+ )
1171
+ }),
1172
+ async execute(_toolCallId, params, signal) {
1173
+ const imageModel = effectiveMediaModel("image", params?.imageModel);
1174
+ const videoModel = effectiveMediaModel("video", params?.videoModel);
1175
+ const query = new URLSearchParams();
1176
+ if (params?.model) query.set("model", params.model);
1177
+ if (imageModel) query.set("imageModel", imageModel);
1178
+ if (videoModel) query.set("videoModel", videoModel);
1179
+ if (params?.ttsModel) query.set("ttsModel", params.ttsModel);
1180
+ const qs = query.toString();
1181
+ const r = await callAccount(
1182
+ `/api/agent/media/capabilities${qs ? `?${qs}` : ""}`,
1183
+ { method: "GET", signal }
1184
+ );
1185
+ if (!r.ok) return text(`Could not read media capabilities: ${r.message}`);
1186
+ const { image, video, model3d, sfx, speech, privacy } = r.data;
1187
+ const lines = describeImageVideo(image, video);
1188
+ if (imageModel && image?.model && image.model !== imageModel) {
1189
+ lines.push(` (generate_image will use ${imageModel}; this server described the account default instead)`);
1190
+ }
1191
+ lines.push(...describeModel3d(model3d));
1192
+ lines.push(...describeSfx(sfx));
1193
+ lines.push(...describeSpeech(speech));
1194
+ lines.push(`Privacy: requireZdr=${privacy?.requireZdr ?? "?"}, allowNonZdrMedia=${privacy?.allowNonZdrMedia ?? "?"}`);
1195
+ if (image?.blockedByZdr || video?.blockedByZdr || model3d?.blockedByZdr || sfx?.blockedByZdr || speech?.blockedByZdr) {
1196
+ lines.push(
1197
+ "A [BLOCKED] model means the account requires Zero Data Retention and that model has no ZDR endpoint. Only the account owner can change it (Settings \u2192 Privacy); do not keep retrying."
1198
+ );
1199
+ }
1200
+ lines.push(
1201
+ "Music is always available; sound effects and (per above) speech's CURRENT model may not be. Music has no ZDR gate at all; effects are gated like image and video, so a blocked effect must never be answered with music instead."
1202
+ );
1203
+ return text(lines.join("\n"));
1204
+ }
1205
+ };
1206
+ function pathInside(root, target) {
1207
+ const rel = relative(root, target);
1208
+ return rel === "" || !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep);
1209
+ }
1210
+ __name(pathInside, "pathInside");
1211
+ function archiveEntryPath(name, root) {
1212
+ const rel = name.split("\\").join("/");
1213
+ const traverses = rel.startsWith("/") || /^[A-Za-z]:/.test(rel) || rel.split("/").some((seg) => seg === "..");
1214
+ if (traverses || !pathInside(root, resolve(root, rel))) {
1215
+ throw new Error(`archive entry "${name}" escapes the destination directory ${root}`);
1216
+ }
1217
+ return rel;
1218
+ }
1219
+ __name(archiveEntryPath, "archiveEntryPath");
1220
+ function extractStoredZip(zip, destDir) {
1221
+ const written = [];
1222
+ const root = resolve(destDir);
1223
+ let at = 0;
1224
+ while (at + 30 <= zip.length && zip.readUInt32LE(at) === 67324752) {
1225
+ const method = zip.readUInt16LE(at + 8);
1226
+ const size = zip.readUInt32LE(at + 18);
1227
+ const nameLen = zip.readUInt16LE(at + 26);
1228
+ const extraLen = zip.readUInt16LE(at + 28);
1229
+ const name = zip.toString("utf8", at + 30, at + 30 + nameLen);
1230
+ const dataAt = at + 30 + nameLen + extraLen;
1231
+ if (method !== 0) throw new Error(`archive entry "${name}" is compressed; only stored entries are expected`);
1232
+ if (dataAt + size > zip.length) throw new Error(`archive entry "${name}" is truncated`);
1233
+ const target = resolve(root, archiveEntryPath(name, root));
1234
+ mkdirSync3(dirname2(target), { recursive: true });
1235
+ writeFileSync4(target, zip.subarray(dataAt, dataAt + size));
1236
+ written.push(name);
1237
+ at = dataAt + size;
1238
+ }
1239
+ if (!written.length) throw new Error("the archive contained no files");
1240
+ return written;
1241
+ }
1242
+ __name(extractStoredZip, "extractStoredZip");
1243
+ function guessResPath(cwd, dir) {
1244
+ const target = resolve(abs(cwd, dir));
1245
+ const root = resolve(cwd);
1246
+ if (target === root || !pathInside(root, target)) return void 0;
1247
+ return `res://${relative(root, target).split("\\").join("/")}/`;
1248
+ }
1249
+ __name(guessResPath, "guessResPath");
1250
+ var SPRITE_DIRECTION_SETS = {
1251
+ one: { animations: 1, billed: 1 },
1252
+ four: { animations: 4, billed: 3 },
1253
+ eight: { animations: 8, billed: 5 }
1254
+ };
1255
+ function spritePollWorthRetrying(status) {
1256
+ return status === void 0 || status === 429 || status >= 500;
1257
+ }
1258
+ __name(spritePollWorthRetrying, "spritePollWorthRetrying");
1259
+ var SPRITE_POLL_FAILURE_BUDGET = 10;
1260
+ function stashBundle(bundle, jobId) {
1261
+ try {
1262
+ const path = join3(tmpdir(), `privateer-sprite-${jobId.replace(/[^A-Za-z0-9_-]/g, "")}.zip`);
1263
+ writeFileSync4(path, bundle);
1264
+ return path;
1265
+ } catch {
1266
+ return null;
1267
+ }
1268
+ }
1269
+ __name(stashBundle, "stashBundle");
1270
+ async function awaitSpriteJob(jobId, cwd, dir, expectedAnimations, billed, signal) {
1271
+ const deadline = Date.now() + SPRITE_POLL_TIMEOUT_MS;
1272
+ const resumeHint = `Resume it with generate_sprite { resumeJobId: "${jobId}", dir: "${dir}" } \u2014 that waits on this same job and bills nothing further.`;
1273
+ const cancelled = /* @__PURE__ */ __name(() => text(
1274
+ `Sprite job ${jobId} was submitted but the wait was cancelled. Its ${billed ?? "queued"} clip(s) are still rendering and will still be billed. ` + resumeHint
1275
+ ), "cancelled");
1276
+ let consecutiveFailures = 0;
1277
+ for (; ; ) {
1278
+ if (signal?.aborted) return cancelled();
1279
+ await sleep(SPRITE_POLL_INTERVAL_MS, signal);
1280
+ if (signal?.aborted) return cancelled();
1281
+ const poll = await callAccount(
1282
+ `/api/agent/media/sprites/${encodeURIComponent(jobId)}`,
1283
+ { method: "GET", signal }
1284
+ );
1285
+ if (!poll.ok) {
1286
+ if (!spritePollWorthRetrying(poll.status)) {
1287
+ return text(`Sprite job ${jobId} could not be polled: ${poll.message}`);
1288
+ }
1289
+ if (++consecutiveFailures >= SPRITE_POLL_FAILURE_BUDGET || Date.now() > deadline) {
1290
+ return text(
1291
+ `Sprite job ${jobId} could not be polled ${consecutiveFailures} times in a row: ${poll.message}. The clips are still rendering and are still billed. ${resumeHint}`
1292
+ );
1293
+ }
1294
+ continue;
1295
+ }
1296
+ consecutiveFailures = 0;
1297
+ const status = String(poll.data.status ?? "").toLowerCase();
1298
+ if (status === "failed") {
1299
+ return text(`Sprite generation failed: ${poll.data.error?.message ?? poll.data.message ?? "the provider reported a failure"}.`);
1300
+ }
1301
+ if (status === "completed") {
1302
+ if (!poll.data.zip_base64) {
1303
+ return text(`Sprite job ${jobId} already delivered its bytes on an earlier poll; they were not saved. Generate again if the files are missing.`);
1304
+ }
1305
+ const destination = abs(cwd, dir);
1306
+ const bundle = Buffer.from(poll.data.zip_base64, "base64");
1307
+ const stash = stashBundle(bundle, jobId);
1308
+ let written;
1309
+ try {
1310
+ written = extractStoredZip(bundle, destination);
1311
+ } catch (e) {
1312
+ const why = e instanceof Error ? e.message : String(e);
1313
+ return text(
1314
+ `Sprite job ${jobId} rendered but the bundle could not be unpacked into ${destination}: ${why}. ` + (stash ? `The archive itself was saved to ${stash} \u2014 unzip it there; the clips are already paid for and will not be delivered again.` : "The archive could not be saved either, so the clips are lost.")
1315
+ );
1316
+ }
1317
+ if (stash) {
1318
+ try {
1319
+ unlinkSync2(stash);
1320
+ } catch {
1321
+ }
1322
+ }
1323
+ const tres = written.find((f) => f.endsWith(".tres"));
1324
+ const anims = poll.data.animations ?? [];
1325
+ const mirrored = anims.filter((a) => a.origin === "mirrored").length;
1326
+ const sheet = poll.data.sheet;
1327
+ const missing = expectedAnimations != null ? expectedAnimations - anims.length : 0;
1328
+ const lines = [
1329
+ `Generated sprite animation: ${written.length} files in ${destination}`,
1330
+ sheet ? `Sheet ${sheet.width}x${sheet.height}px, ${sheet.frame_width}x${sheet.frame_height} cells, ${sheet.columns}x${sheet.rows} grid.` : "",
1331
+ anims.length ? `Animations: ${anims.map((a) => a.name).join(", ")}${mirrored ? ` (${mirrored} mirrored, not billed)` : ""}.` : "",
1332
+ // Said out loud rather than left to be counted: a sheet short a facing is
1333
+ // not the sheet that was asked for, and the animation GDScript plays for
1334
+ // that direction is simply not in the resource.
1335
+ missing > 0 ? `WARNING: ${missing} of ${expectedAnimations} facings did not render and are NOT in the sheet or the .tres \u2014 playing them will fail in Godot. The facings that did land were billed. Re-run to try for the missing ones.` : "",
1336
+ tres ? `Set an AnimatedSprite2D's Sprite Frames to ${poll.data.res_path ?? "res://"}${tres.split("/").pop()}.` : "",
1337
+ "Set the sheet's texture Filter to Nearest in the Import dock, or the pixel art imports blurry.",
1338
+ // Surfaced rather than swallowed: the flat backdrop the clip was asked
1339
+ // for is a prompt the model can ignore, and when it does the key leaves
1340
+ // a rim. The caller can see it here instead of finding it in-game.
1341
+ poll.data.key_residue != null && poll.data.key_residue > 0.08 ? `NOTE: the background did not key cleanly (residue ${poll.data.key_residue.toFixed(2)}) \u2014 the frames may have a fringe. Re-run, or clean them up before shipping.` : ""
1342
+ ].filter(Boolean);
1343
+ return text(lines.join("\n"));
1344
+ }
1345
+ if (Date.now() > deadline) {
1346
+ return text(
1347
+ `Sprite job ${jobId} is still ${status || "running"} after ${Math.round(SPRITE_POLL_TIMEOUT_MS / 6e4)} minutes. It will still complete and still be billed; nothing was saved here. ${resumeHint}`
1348
+ );
1349
+ }
1350
+ }
1351
+ }
1352
+ __name(awaitSpriteJob, "awaitSpriteJob");
1353
+ var generateSpriteToolDefinition = {
1354
+ name: "generate_sprite",
1355
+ label: "Generate Sprite Animation",
1356
+ description: "Generate a 2D SPRITE ANIMATION for a game engine \u2014 a packed sprite sheet, the individual frame PNGs, and a Godot 4 SpriteFrames .tres resource \u2014 from ONE picture of a character plus a description of how it moves. The files are written straight into your project directory, so an AnimatedSprite2D can use them without any further conversion. There is no text-to-sprite here: generate or find the character art first (generate_image works), look at it, and pass that path as `image` \u2014 every facing is derived from that one picture, which is what stops the character changing between frames.\nHOW IT IS BILLED, because it is not one generation: the motion is rendered as a short video per FACING and then sampled into frames. `directions: 'one'` costs one video generation, 'four' costs THREE, and 'eight' costs FIVE \u2014 the left-facing animations are mirrored from the right-facing ones rather than rendered, which is why eight animations cost five clips and not eight. Each clip is charged at the account's video rate, so an eight-way set is genuinely expensive; say the total to the user before batching characters.\nTWO models are involved, which matters when one of them is down AND when you are quoting a price: an IMAGE model turns the picture to face each direction (only for `directions` 'four' and 'eight'), then a VIDEO model renders the motion per facing. `image_model` and `model` override them separately. The turns are billed too, at the image rate \u2014 one still per billed facing after the first, so 'four' draws two and 'eight' draws four. They are small beside a clip, but a total that counts only clips is short; media_capabilities reports both numbers per direction set (`billedClips` and `billedTurnStills`).\nIt takes several minutes \u2014 the picture is turned to face each direction one at a time before anything is billed, then the clips render together \u2014 and this tool waits. Frame count, cell size and frame rate are chosen here and cost nothing extra.\nIf a call comes back saying the job is still running, or that it could not be polled, DO NOT call this again with the same image and prompt \u2014 that bills a whole second fan-out. Call it with `resumeJobId` set to the job id it reported (and the same `dir`) to keep waiting on the clips the account has already paid for.\nAVAILABILITY: this needs a video decoder on the Privateer API and some deployments do not have one \u2014 call media_capabilities and check `sprites.available` before spending, or you will get a clear refusal instead of a sheet. PRIVACY: video and image models have no zero-retention option, so this is gated the way 3D is \u2014 a ZDR account must have enabled non-ZDR media.",
1357
+ parameters: typebox_exports.Object({
1358
+ image: typebox_exports.String({
1359
+ description: "Path to ONE picture of the character, ideally full-body, centred and facing the viewer. Every other facing is generated as an edit of this image, so its framing sets the framing of the whole sheet."
1360
+ }),
1361
+ prompt: typebox_exports.String({
1362
+ description: "How the character MOVES, not what it looks like \u2014 'walking at a steady pace', 'swinging a sword overhead', 'idle, breathing'. The appearance comes from `image`; describing it again here only competes with the picture."
1363
+ }),
1364
+ dir: typebox_exports.String({
1365
+ description: "Directory to write the sheet, frames and .tres into, relative to cwd or absolute (e.g. 'sprites/knight'). It is created if missing. When it sits inside cwd, the res:// path baked into the .tres is derived from it, so running at your Godot project root means the resource resolves with nothing to edit."
1366
+ }),
1367
+ resumeJobId: typebox_exports.Optional(typebox_exports.String({
1368
+ description: "Resume waiting on a job already submitted (from a previous call that timed out or lost its poll). Nothing is generated and nothing is billed: it only polls and unpacks. `image`, `prompt` and every other setting are ignored \u2014 pass the same `dir`."
1369
+ })),
1370
+ action: typebox_exports.Optional(
1371
+ typebox_exports.String({
1372
+ description: `The animation-name stem, e.g. 'walk' \u2014 GDScript will play "walk_down", "walk_left" and so on. Defaults to 'anim'. Keep it lowercase and ASCII; it ends up in game code.`
1373
+ })
1374
+ ),
1375
+ directions: typebox_exports.Optional(
1376
+ typebox_exports.Union(
1377
+ [typebox_exports.Literal("one"), typebox_exports.Literal("four"), typebox_exports.Literal("eight")],
1378
+ {
1379
+ description: "'one' (default, one animation, ONE clip billed), 'four' (down/right/up/left, THREE billed) or 'eight' (adds the diagonals, FIVE billed). Four is the usual choice for a top-down or 2.5D character; eight only if the game actually turns that finely. These three words are the only accepted values \u2014 not '4', not 'four-way'."
1380
+ }
1381
+ )
1382
+ ),
1383
+ frames: typebox_exports.Optional(
1384
+ typebox_exports.Number({
1385
+ description: "Frames per animation, 2-24 (default 8). Sampled out of the rendered clip, so this costs nothing extra and can be chosen for the look: 8 is a classic walk cycle, 12+ is smoother and makes a larger sheet."
1386
+ })
1387
+ ),
1388
+ frame_size: typebox_exports.Optional(
1389
+ typebox_exports.Number({
1390
+ description: "Cell size in pixels, 8-512 (default 64). Frames are downscaled with nearest-neighbour, so pixel art stays crisp. Pick the size the game actually draws at."
1391
+ })
1392
+ ),
1393
+ fps: typebox_exports.Optional(
1394
+ typebox_exports.Number({ description: "Playback rate written into the resource, 1-120 (default 12)." })
1395
+ ),
1396
+ loop: typebox_exports.Optional(
1397
+ typebox_exports.Boolean({ description: "Whether the animations loop (default true)." })
1398
+ ),
1399
+ name: typebox_exports.Optional(
1400
+ typebox_exports.String({ description: "Name for the sprite; sets the file names. Defaults to `action`." })
1401
+ ),
1402
+ res_path: typebox_exports.Optional(
1403
+ typebox_exports.String({
1404
+ description: "Override the res:// folder the .tres points at, e.g. 'res://art/mobs/'. Only needed when `dir` is not inside your Godot project root \u2014 otherwise it is derived from `dir`."
1405
+ })
1406
+ ),
1407
+ model: typebox_exports.Optional(
1408
+ typebox_exports.String({ description: "Video model id to render the motion with. Omit for the one chosen with /video-model, or the account default." })
1409
+ ),
1410
+ image_model: typebox_exports.Optional(
1411
+ typebox_exports.String({
1412
+ description: "Image model id used to TURN the picture to face each direction, e.g. 'google/gemini-3.1-flash-image'. Omit for the one chosen with /image-model, or the account default. Only used when `directions` is 'four' or 'eight' \u2014 'one' renders no turns and never touches an image model. Worth setting when a run fails with SPRITE_IMAGE_MODEL_UNAVAILABLE: that is the image provider being down, not the request being wrong, and naming another model here retries the whole run for nothing (the turns are drawn before any clip is billed). media_capabilities lists the account's current image model."
1413
+ })
1414
+ )
1415
+ }),
1416
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
1417
+ const cwd = ctx?.cwd ?? process.cwd();
1418
+ if (!params.dir) return text("Error: dir is required \u2014 say where to write the sheet and the .tres.");
1419
+ const resumeJobId = String(params.resumeJobId ?? "").trim();
1420
+ if (resumeJobId) return awaitSpriteJob(resumeJobId, cwd, params.dir, null, null, signal);
1421
+ if (!params.image) return text("Error: image is required \u2014 sprite generation derives every facing from one picture.");
1422
+ if (!params.prompt?.trim()) return text("Error: prompt is required \u2014 describe how the character moves.");
1423
+ const directions = params.directions ?? "one";
1424
+ if (!Object.prototype.hasOwnProperty.call(SPRITE_DIRECTION_SETS, directions)) {
1425
+ return text(`Error: directions must be 'one', 'four' or 'eight' \u2014 got ${JSON.stringify(params.directions)}.`);
1426
+ }
1427
+ const ranges = [
1428
+ ["frames", params.frames, 2, 24],
1429
+ ["frame_size", params.frame_size, 8, 512],
1430
+ ["fps", params.fps, 1, 120]
1431
+ ];
1432
+ for (const [label, value, min, max] of ranges) {
1433
+ if (value == null) continue;
1434
+ if (!Number.isFinite(value) || value < min || value > max) {
1435
+ return text(`Error: ${label} must be between ${min} and ${max} \u2014 got ${value}.`);
1436
+ }
1437
+ }
1438
+ let seed;
1439
+ try {
1440
+ seed = readInputImage(cwd, params.image);
1441
+ } catch (e) {
1442
+ return text(`Error: ${e instanceof Error ? e.message : String(e)}`);
1443
+ }
1444
+ const submitted = await callAccount("/api/agent/media/sprites", {
1445
+ method: "POST",
1446
+ signal,
1447
+ body: {
1448
+ image: seed.data,
1449
+ prompt: params.prompt,
1450
+ ...params.action ? { action: params.action } : {},
1451
+ ...params.name ? { name: params.name } : {},
1452
+ directions,
1453
+ ...params.frames != null ? { frames: params.frames } : {},
1454
+ ...params.frame_size != null ? { frame_size: params.frame_size } : {},
1455
+ ...params.fps != null ? { fps: params.fps } : {},
1456
+ ...params.loop != null ? { loop: params.loop } : {},
1457
+ // The caller's own res:// wins; otherwise derive it from where the files
1458
+ // are going, which is right whenever the agent runs at the project root.
1459
+ ...params.res_path ? { res_path: params.res_path } : (() => {
1460
+ const guessed = guessResPath(cwd, params.dir);
1461
+ return guessed ? { res_path: guessed } : {};
1462
+ })(),
1463
+ .../* @__PURE__ */ ((m) => m ? { model: m } : {})(effectiveMediaModel("video", params.model)),
1464
+ .../* @__PURE__ */ ((m) => m ? { image_model: m } : {})(effectiveMediaModel("image", params.image_model))
1465
+ }
1466
+ });
1467
+ if (!submitted.ok) return text(`Sprite generation failed: ${submitted.message}`);
1468
+ const jobId = submitted.data.id;
1469
+ if (!jobId) return text("Sprite generation failed: Privateer did not return a job id.");
1470
+ const expected = submitted.data.animations ?? SPRITE_DIRECTION_SETS[directions].animations;
1471
+ return awaitSpriteJob(jobId, cwd, params.dir, expected, submitted.data.billed_facings ?? null, signal);
1472
+ }
1473
+ };
1474
+ function makeMediaTools() {
1475
+ return (pi) => {
1476
+ pi.registerTool?.(generateImageToolDefinition);
1477
+ pi.registerTool?.(generateVideoToolDefinition);
1478
+ pi.registerTool?.(generateModelToolDefinition);
1479
+ pi.registerTool?.(generateSpriteToolDefinition);
1480
+ pi.registerTool?.(generateSpeechToolDefinition);
1481
+ pi.registerTool?.(generateMusicToolDefinition);
1482
+ pi.registerTool?.(generateSfxToolDefinition);
1483
+ pi.registerTool?.(mediaCapabilitiesToolDefinition);
1484
+ };
1485
+ }
1486
+ __name(makeMediaTools, "makeMediaTools");
1487
+
1488
+ // src/tools/videoCompose.ts?ext=privateer-media
1489
+ import { spawn } from "node:child_process";
1490
+ import { existsSync as existsSync3, mkdirSync as mkdirSync4, mkdtempSync, readFileSync as readFileSync5, rmSync as rmSync3, statSync as statSync3, writeFileSync as writeFileSync5 } from "node:fs";
1491
+ import { tmpdir as tmpdir2 } from "node:os";
1492
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join4, resolve as resolve2 } from "node:path";
1493
+ var FFMPEG_TIMEOUT_MS = Number(process.env.PRIVATEER_FFMPEG_TIMEOUT_MS) || 10 * 6e4;
1494
+ var STDERR_TAIL_CHARS = 1200;
1495
+ var OPERATIONS = [
1496
+ "probe",
1497
+ "concat",
1498
+ "slideshow",
1499
+ "mux_audio",
1500
+ "mix_audio",
1501
+ "overlay_text",
1502
+ "overlay_image",
1503
+ "burn_subtitles",
1504
+ "trim",
1505
+ "extract_frame",
1506
+ "gif"
1507
+ ];
1508
+ function text2(t) {
1509
+ return { content: [{ type: "text", text: t }], details: {} };
1510
+ }
1511
+ __name(text2, "text");
1512
+ function ffmpegBin() {
1513
+ return process.env.PRIVATEER_FFMPEG || "ffmpeg";
1514
+ }
1515
+ __name(ffmpegBin, "ffmpegBin");
1516
+ function ffprobeBin() {
1517
+ return process.env.PRIVATEER_FFPROBE || "ffprobe";
1518
+ }
1519
+ __name(ffprobeBin, "ffprobeBin");
1520
+ var INSTALL_HINT = process.platform === "darwin" ? "install it with `brew install ffmpeg`" : process.platform === "win32" ? "install it with `winget install Gyan.FFmpeg`" : "install it with your package manager (e.g. `sudo apt install ffmpeg`)";
1521
+ var ToolError = class extends Error {
1522
+ static {
1523
+ __name(this, "ToolError");
1524
+ }
1525
+ };
1526
+ function run(bin, args, signal) {
1527
+ return new Promise((resolvePromise, rejectPromise) => {
1528
+ let child;
1529
+ try {
1530
+ child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
1531
+ } catch (e) {
1532
+ return rejectPromise(e);
1533
+ }
1534
+ let stdout = "";
1535
+ let stderr = "";
1536
+ let settled = false;
1537
+ const timer = setTimeout(() => {
1538
+ if (!settled) {
1539
+ child.kill("SIGKILL");
1540
+ settled = true;
1541
+ rejectPromise(new ToolError(`${bin} timed out after ${Math.round(FFMPEG_TIMEOUT_MS / 1e3)}s`));
1542
+ }
1543
+ }, FFMPEG_TIMEOUT_MS);
1544
+ const onAbort = /* @__PURE__ */ __name(() => {
1545
+ child.kill("SIGKILL");
1546
+ }, "onAbort");
1547
+ signal?.addEventListener("abort", onAbort, { once: true });
1548
+ child.stdout?.on("data", (d) => {
1549
+ stdout += String(d);
1550
+ });
1551
+ child.stderr?.on("data", (d) => {
1552
+ stderr += String(d);
1553
+ if (stderr.length > STDERR_TAIL_CHARS * 4) stderr = stderr.slice(-STDERR_TAIL_CHARS * 2);
1554
+ });
1555
+ child.on("error", (err) => {
1556
+ clearTimeout(timer);
1557
+ signal?.removeEventListener("abort", onAbort);
1558
+ if (settled) return;
1559
+ settled = true;
1560
+ if (err.code === "ENOENT") {
1561
+ rejectPromise(new ToolError(`ffmpeg is not installed (or not on PATH) \u2014 ${INSTALL_HINT}. Set PRIVATEER_FFMPEG to point at a specific binary.`));
1562
+ } else {
1563
+ rejectPromise(err);
1564
+ }
1565
+ });
1566
+ child.on("close", (code) => {
1567
+ clearTimeout(timer);
1568
+ signal?.removeEventListener("abort", onAbort);
1569
+ if (settled) return;
1570
+ settled = true;
1571
+ resolvePromise({ code, stdout, stderr });
1572
+ });
1573
+ });
1574
+ }
1575
+ __name(run, "run");
1576
+ async function ffmpeg(args, signal) {
1577
+ const res = await run(ffmpegBin(), ["-hide_banner", "-nostdin", "-y", ...args], signal);
1578
+ if (res.code !== 0) {
1579
+ throw new ToolError(`ffmpeg failed (exit ${res.code}):
1580
+ ${res.stderr.slice(-STDERR_TAIL_CHARS).trim()}`);
1581
+ }
1582
+ }
1583
+ __name(ffmpeg, "ffmpeg");
1584
+ async function probe(path, signal) {
1585
+ const res = await run(
1586
+ ffprobeBin(),
1587
+ ["-v", "error", "-print_format", "json", "-show_format", "-show_streams", path],
1588
+ signal
1589
+ );
1590
+ if (res.code !== 0) {
1591
+ throw new ToolError(`could not read ${path}: ${res.stderr.slice(-400).trim() || `ffprobe exit ${res.code}`}`);
1592
+ }
1593
+ let parsed;
1594
+ try {
1595
+ parsed = JSON.parse(res.stdout);
1596
+ } catch {
1597
+ throw new ToolError(`could not parse media info for ${path}`);
1598
+ }
1599
+ const streams = parsed.streams ?? [];
1600
+ const video = streams.find((s) => s.codec_type === "video");
1601
+ const audio = streams.find((s) => s.codec_type === "audio");
1602
+ const duration = Number(parsed.format?.duration ?? video?.duration ?? 0);
1603
+ let fps = null;
1604
+ if (video?.avg_frame_rate && video.avg_frame_rate !== "0/0") {
1605
+ const [num, den] = video.avg_frame_rate.split("/").map(Number);
1606
+ if (num > 0 && den > 0) fps = num / den;
1607
+ }
1608
+ return {
1609
+ path,
1610
+ durationSec: Number.isFinite(duration) && duration > 0 ? duration : 0,
1611
+ width: video?.width ?? null,
1612
+ height: video?.height ?? null,
1613
+ hasVideo: !!video,
1614
+ hasAudio: !!audio,
1615
+ fps
1616
+ };
1617
+ }
1618
+ __name(probe, "probe");
1619
+ function absPath(cwd, p) {
1620
+ return isAbsolute2(p) ? p : resolve2(cwd, p);
1621
+ }
1622
+ __name(absPath, "absPath");
1623
+ function requireExisting(cwd, p, label) {
1624
+ const target = absPath(cwd, p);
1625
+ if (!existsSync3(target)) throw new ToolError(`${label} not found: ${p}`);
1626
+ if (statSync3(target).isDirectory()) throw new ToolError(`${label} is a directory, not a file: ${p}`);
1627
+ return target;
1628
+ }
1629
+ __name(requireExisting, "requireExisting");
1630
+ function prepareOutput(cwd, p, operation) {
1631
+ if (!p) throw new ToolError(`\`output\` is required for the ${operation} operation.`);
1632
+ const target = absPath(cwd, p);
1633
+ mkdirSync4(dirname3(target), { recursive: true });
1634
+ return target;
1635
+ }
1636
+ __name(prepareOutput, "prepareOutput");
1637
+ var VIDEO_ENCODE = ["-c:v", "libx264", "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p", "-movflags", "+faststart"];
1638
+ var AUDIO_ENCODE = ["-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2"];
1639
+ function evenSize(w, h) {
1640
+ return [Math.max(2, w - w % 2), Math.max(2, h - h % 2)];
1641
+ }
1642
+ __name(evenSize, "evenSize");
1643
+ function parseSize(size) {
1644
+ if (!size) return null;
1645
+ const m = /^(\d{2,5})\s*[x×:]\s*(\d{2,5})$/i.exec(size.trim());
1646
+ if (!m) throw new ToolError(`\`size\` must look like 1920x1080 (got "${size}")`);
1647
+ return evenSize(Number(m[1]), Number(m[2]));
1648
+ }
1649
+ __name(parseSize, "parseSize");
1650
+ function normalizeVideo(index, label, w, h, fps) {
1651
+ return `[${index}:v]scale=${w}:${h}:force_original_aspect_ratio=decrease,pad=${w}:${h}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps=${fps},format=yuv420p[${label}]`;
1652
+ }
1653
+ __name(normalizeVideo, "normalizeVideo");
1654
+ var AFORMAT = "aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo";
1655
+ function normalizeAudio(index, label) {
1656
+ return `[${index}:a]${AFORMAT},aresample=async=1[${label}]`;
1657
+ }
1658
+ __name(normalizeAudio, "normalizeAudio");
1659
+ function bounded(v, label, min, max, dflt) {
1660
+ if (v == null) return dflt;
1661
+ const n = Number(v);
1662
+ if (!Number.isFinite(n) || n < min || n > max) {
1663
+ throw new ToolError(`\`${label}\` must be a number between ${min} and ${max} (got ${JSON.stringify(v)}).`);
1664
+ }
1665
+ return n;
1666
+ }
1667
+ __name(bounded, "bounded");
1668
+ var COLOR_RE = /^(?:#[0-9a-fA-F]{6}(?:[0-9a-fA-F]{2})?|[a-zA-Z]{3,20})$/;
1669
+ function colorValue(v, dflt, label) {
1670
+ const c = String(v ?? dflt).trim();
1671
+ if (!COLOR_RE.test(c)) {
1672
+ throw new ToolError(`\`${label}\` must be a colour name (e.g. white) or #rrggbb (got ${JSON.stringify(v)}).`);
1673
+ }
1674
+ return c;
1675
+ }
1676
+ __name(colorValue, "colorValue");
1677
+ function filterPath(p) {
1678
+ return `'${p.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/:/g, "\\:")}'`;
1679
+ }
1680
+ __name(filterPath, "filterPath");
1681
+ async function opProbe(cwd, p, signal) {
1682
+ const list = p.inputs?.length ? p.inputs : p.input ? [p.input] : [];
1683
+ if (list.length === 0) throw new ToolError("`probe` needs `input` (or `inputs`).");
1684
+ const infos = await Promise.all(list.map((f) => probe(requireExisting(cwd, f, "input"), signal)));
1685
+ return infos.map((i, n) => {
1686
+ const dims = i.width && i.height ? `${i.width}x${i.height}` : "no video";
1687
+ const fps = i.fps ? `, ${i.fps.toFixed(2)} fps` : "";
1688
+ return `${list[n]}: ${i.durationSec.toFixed(2)}s, ${dims}${fps}, audio: ${i.hasAudio ? "yes" : "no"}`;
1689
+ }).join("\n");
1690
+ }
1691
+ __name(opProbe, "opProbe");
1692
+ async function opConcat(cwd, p, signal) {
1693
+ const list = p.inputs ?? [];
1694
+ if (list.length < 2) throw new ToolError("`concat` needs at least two paths in `inputs`.");
1695
+ const paths = list.map((f) => requireExisting(cwd, f, "input"));
1696
+ const output = prepareOutput(cwd, p.output, "concat");
1697
+ const infos = await Promise.all(paths.map((f) => probe(f, signal)));
1698
+ for (const [i, info] of infos.entries()) {
1699
+ if (!info.hasVideo) throw new ToolError(`${list[i]} has no video stream \u2014 use mux_audio for audio.`);
1700
+ }
1701
+ const [w, h] = parseSize(p.size) ?? evenSize(infos[0].width ?? 1280, infos[0].height ?? 720);
1702
+ const fps = p.fps && p.fps > 0 ? Math.round(p.fps) : Math.round(infos[0].fps ?? 24);
1703
+ const xfade = p.crossfadeSeconds ?? 0;
1704
+ if (xfade < 0) throw new ToolError("`crossfadeSeconds` cannot be negative.");
1705
+ if (xfade > 0) {
1706
+ for (const [i, info] of infos.entries()) {
1707
+ if (info.durationSec <= xfade) {
1708
+ throw new ToolError(`crossfade of ${xfade}s is longer than clip ${list[i]} (${info.durationSec.toFixed(2)}s).`);
1709
+ }
1710
+ }
1711
+ }
1712
+ const args = [];
1713
+ for (const f of paths) args.push("-i", f);
1714
+ const silenceInputIndex = infos.map(() => null);
1715
+ let nextIndex = paths.length;
1716
+ for (const [i, info] of infos.entries()) {
1717
+ if (!info.hasAudio) {
1718
+ args.push("-f", "lavfi", "-t", String(Math.max(0.1, info.durationSec)), "-i", "anullsrc=r=48000:cl=stereo");
1719
+ silenceInputIndex[i] = nextIndex++;
1720
+ }
1721
+ }
1722
+ const filters = [];
1723
+ for (const [i, info] of infos.entries()) {
1724
+ filters.push(normalizeVideo(i, `v${i}`, w, h, fps));
1725
+ filters.push(normalizeAudio(info.hasAudio ? i : silenceInputIndex[i], `a${i}`));
1726
+ }
1727
+ let vOut;
1728
+ let aOut;
1729
+ if (xfade > 0) {
1730
+ let vPrev = "v0";
1731
+ let aPrev = "a0";
1732
+ let offset = infos[0].durationSec - xfade;
1733
+ for (let i = 1; i < infos.length; i++) {
1734
+ const v = `vx${i}`;
1735
+ const a = `ax${i}`;
1736
+ filters.push(`[${vPrev}][v${i}]xfade=transition=fade:duration=${xfade}:offset=${offset.toFixed(3)}[${v}]`);
1737
+ filters.push(`[${aPrev}][a${i}]acrossfade=d=${xfade}[${a}]`);
1738
+ vPrev = v;
1739
+ aPrev = a;
1740
+ offset += infos[i].durationSec - xfade;
1741
+ }
1742
+ vOut = vPrev;
1743
+ aOut = aPrev;
1744
+ } else {
1745
+ const pairs = infos.map((_, i) => `[v${i}][a${i}]`).join("");
1746
+ filters.push(`${pairs}concat=n=${infos.length}:v=1:a=1[vcat][acat]`);
1747
+ vOut = "vcat";
1748
+ aOut = "acat";
1749
+ }
1750
+ args.push("-filter_complex", filters.join(";"), "-map", `[${vOut}]`, "-map", `[${aOut}]`, ...VIDEO_ENCODE, ...AUDIO_ENCODE, output);
1751
+ await ffmpeg(args, signal);
1752
+ const result = await probe(output, signal);
1753
+ return `Stitched ${paths.length} clips${xfade > 0 ? ` with ${xfade}s crossfades` : ""} \u2192 ${output} (${result.durationSec.toFixed(2)}s, ${w}x${h}, ${fps} fps)`;
1754
+ }
1755
+ __name(opConcat, "opConcat");
1756
+ async function opSlideshow(cwd, p, signal) {
1757
+ const list = p.inputs ?? [];
1758
+ if (list.length === 0) throw new ToolError("`slideshow` needs image paths in `inputs`.");
1759
+ const paths = list.map((f) => requireExisting(cwd, f, "image"));
1760
+ const output = prepareOutput(cwd, p.output, "slideshow");
1761
+ const hold = p.secondsPerImage && p.secondsPerImage > 0 ? p.secondsPerImage : 3;
1762
+ const fps = p.fps && p.fps > 0 ? Math.round(p.fps) : 30;
1763
+ const xfade = p.crossfadeSeconds ?? 0;
1764
+ if (xfade < 0) throw new ToolError("`crossfadeSeconds` cannot be negative.");
1765
+ if (xfade >= hold) throw new ToolError(`\`crossfadeSeconds\` (${xfade}) must be shorter than \`secondsPerImage\` (${hold}).`);
1766
+ const infos = await Promise.all(paths.map((f) => probe(f, signal)));
1767
+ const [w, h] = parseSize(p.size) ?? evenSize(infos[0].width ?? 1280, infos[0].height ?? 720);
1768
+ const args = [];
1769
+ for (const f of paths) args.push("-loop", "1", "-t", String(hold), "-i", f);
1770
+ const filters = [];
1771
+ for (let i = 0; i < paths.length; i++) filters.push(normalizeVideo(i, `v${i}`, w, h, fps));
1772
+ let vOut = "v0";
1773
+ if (paths.length > 1) {
1774
+ if (xfade > 0) {
1775
+ let prev = "v0";
1776
+ let offset = hold - xfade;
1777
+ for (let i = 1; i < paths.length; i++) {
1778
+ const v = `vx${i}`;
1779
+ filters.push(`[${prev}][v${i}]xfade=transition=fade:duration=${xfade}:offset=${offset.toFixed(3)}[${v}]`);
1780
+ prev = v;
1781
+ offset += hold - xfade;
1782
+ }
1783
+ vOut = prev;
1784
+ } else {
1785
+ filters.push(`${paths.map((_, i) => `[v${i}]`).join("")}concat=n=${paths.length}:v=1:a=0[vcat]`);
1786
+ vOut = "vcat";
1787
+ }
1788
+ }
1789
+ args.push("-filter_complex", filters.join(";"), "-map", `[${vOut}]`, ...VIDEO_ENCODE, output);
1790
+ await ffmpeg(args, signal);
1791
+ const result = await probe(output, signal);
1792
+ return `Built a ${result.durationSec.toFixed(2)}s slideshow from ${paths.length} image(s) \u2192 ${output} (${w}x${h}, ${fps} fps, no audio \u2014 add some with mux_audio)`;
1793
+ }
1794
+ __name(opSlideshow, "opSlideshow");
1795
+ async function opMuxAudio(cwd, p, signal) {
1796
+ if (!p.input) throw new ToolError("`mux_audio` needs `input` (the video).");
1797
+ if (!p.audio) throw new ToolError("`mux_audio` needs `audio` (the track to add).");
1798
+ const video = requireExisting(cwd, p.input, "video");
1799
+ const audio = requireExisting(cwd, p.audio, "audio");
1800
+ const output = prepareOutput(cwd, p.output, "mux_audio");
1801
+ const [vInfo, aInfo] = await Promise.all([probe(video, signal), probe(audio, signal)]);
1802
+ if (!vInfo.hasVideo) throw new ToolError(`${p.input} has no video stream.`);
1803
+ if (!aInfo.hasAudio) throw new ToolError(`${p.audio} has no audio stream.`);
1804
+ const volume = p.volume != null ? Number(p.volume) : 1;
1805
+ if (!Number.isFinite(volume) || volume < 0 || volume > 4) throw new ToolError("`volume` must be between 0 and 4.");
1806
+ const args = ["-i", video];
1807
+ if (p.loopAudio) args.push("-stream_loop", "-1");
1808
+ args.push("-i", audio);
1809
+ const filters = [`[1:a]aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo,volume=${volume}[anew]`];
1810
+ let aOut = "anew";
1811
+ if (p.keepOriginalAudio) {
1812
+ if (!vInfo.hasAudio) throw new ToolError(`\`keepOriginalAudio\` was set but ${p.input} has no audio to keep.`);
1813
+ filters.push("[0:a]aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo[aorig]");
1814
+ filters.push("[aorig][anew]amix=inputs=2:duration=first:dropout_transition=0,dynaudnorm[amix]");
1815
+ aOut = "amix";
1816
+ }
1817
+ args.push(
1818
+ "-filter_complex",
1819
+ filters.join(";"),
1820
+ "-map",
1821
+ "0:v",
1822
+ "-map",
1823
+ `[${aOut}]`,
1824
+ "-c:v",
1825
+ "copy",
1826
+ ...AUDIO_ENCODE,
1827
+ "-shortest",
1828
+ output
1829
+ );
1830
+ await ffmpeg(args, signal);
1831
+ const result = await probe(output, signal);
1832
+ return `Muxed ${p.audio} onto ${p.input}${p.loopAudio ? " (looped)" : ""}${p.keepOriginalAudio ? " (mixed with the original audio)" : ""} \u2192 ${output} (${result.durationSec.toFixed(2)}s)`;
1833
+ }
1834
+ __name(opMuxAudio, "opMuxAudio");
1835
+ var DUCK_FILTER = "sidechaincompress=threshold=0.03:ratio=12:attack=15:release=350:detection=rms";
1836
+ async function opMixAudio(cwd, p, signal) {
1837
+ if (!p.input) throw new ToolError("`mix_audio` needs `input` (the video the tracks go onto).");
1838
+ const raw = p.tracks ?? [];
1839
+ if (raw.length === 0) {
1840
+ throw new ToolError(
1841
+ "`mix_audio` needs at least one entry in `tracks`, each with a `path` (plus optional atSeconds, gain, loop, duck). For one track at one level over the whole video, mux_audio is simpler."
1842
+ );
1843
+ }
1844
+ const tracks = raw.map((t, i) => {
1845
+ const track = typeof t === "string" ? { path: t } : t ?? {};
1846
+ if (!track.path) throw new ToolError(`tracks[${i}] has no \`path\`.`);
1847
+ return track;
1848
+ });
1849
+ const voice = p.voiceTrack;
1850
+ if (voice != null && (!Number.isInteger(Number(voice)) || Number(voice) < 0 || Number(voice) >= tracks.length)) {
1851
+ throw new ToolError(
1852
+ `\`voiceTrack\` must be the index of one of the ${tracks.length} track(s) \u2014 0 to ${tracks.length - 1} \u2014 got ${JSON.stringify(p.voiceTrack)}.`
1853
+ );
1854
+ }
1855
+ const ducked = tracks.map((t, i) => t.duck && i !== voice ? i : -1).filter((i) => i >= 0);
1856
+ if (ducked.length > 0 && voice == null) {
1857
+ throw new ToolError(
1858
+ "`duck` needs `voiceTrack` set to the index of the track everything else ducks under (normally the narration) \u2014 there is nothing to duck under otherwise."
1859
+ );
1860
+ }
1861
+ const video = requireExisting(cwd, p.input, "video");
1862
+ const paths = tracks.map((t, i) => requireExisting(cwd, t.path, `tracks[${i}]`));
1863
+ const output = prepareOutput(cwd, p.output, "mix_audio");
1864
+ const [vInfo, ...tInfos] = await Promise.all([probe(video, signal), ...paths.map((f) => probe(f, signal))]);
1865
+ if (!vInfo.hasVideo) throw new ToolError(`${p.input} has no video stream.`);
1866
+ for (const [i, info] of tInfos.entries()) {
1867
+ if (!info.hasAudio) throw new ToolError(`tracks[${i}] (${tracks[i].path}) has no audio stream.`);
1868
+ }
1869
+ const args = ["-i", video];
1870
+ for (const [i, t] of tracks.entries()) {
1871
+ if (t.loop) {
1872
+ if (!(vInfo.durationSec > 0)) {
1873
+ throw new ToolError(`\`loop\` needs a video of known length, and ${p.input} reports none.`);
1874
+ }
1875
+ args.push("-stream_loop", "-1", "-t", vInfo.durationSec.toFixed(3));
1876
+ }
1877
+ args.push("-i", paths[i]);
1878
+ }
1879
+ const filters = [];
1880
+ const labels = [];
1881
+ if (p.keepOriginalAudio) {
1882
+ if (!vInfo.hasAudio) throw new ToolError(`\`keepOriginalAudio\` was set but ${p.input} has no audio to keep.`);
1883
+ filters.push(`[0:a]${AFORMAT}[aorig]`);
1884
+ labels.push("aorig");
1885
+ }
1886
+ for (const [i, t] of tracks.entries()) {
1887
+ const gain = bounded(t.gain, `tracks[${i}].gain`, 0, 4, 1);
1888
+ const at = bounded(t.atSeconds, `tracks[${i}].atSeconds`, 0, 86400, 0);
1889
+ let chain = `[${i + 1}:a]${AFORMAT}`;
1890
+ if (gain !== 1) chain += `,volume=${gain}`;
1891
+ if (at > 0) chain += `,adelay=${Math.round(at * 1e3)}:all=1`;
1892
+ filters.push(`${chain}[t${i}]`);
1893
+ }
1894
+ const mixLabel = new Map(tracks.map((_, i) => [i, `t${i}`]));
1895
+ if (ducked.length > 0) {
1896
+ filters.push(`[t${voice}]asplit=${ducked.length + 1}[vmix]${ducked.map((_, k) => `[key${k}]`).join("")}`);
1897
+ mixLabel.set(voice, "vmix");
1898
+ ducked.forEach((i, k) => {
1899
+ filters.push(`[t${i}][key${k}]${DUCK_FILTER}[d${i}]`);
1900
+ mixLabel.set(i, `d${i}`);
1901
+ });
1902
+ }
1903
+ labels.push(...tracks.map((_, i) => mixLabel.get(i)));
1904
+ if (labels.length > 1) {
1905
+ filters.push(
1906
+ `${labels.map((l) => `[${l}]`).join("")}amix=inputs=${labels.length}:duration=longest:dropout_transition=0:normalize=0[amixed]`
1907
+ );
1908
+ } else {
1909
+ filters.push(`[${labels[0]}]anull[amixed]`);
1910
+ }
1911
+ filters.push("[amixed]alimiter=limit=0.95[aout]");
1912
+ args.push(
1913
+ "-filter_complex",
1914
+ filters.join(";"),
1915
+ "-map",
1916
+ "0:v",
1917
+ "-map",
1918
+ "[aout]",
1919
+ // The picture is untouched, so it is copied: a mix must never be a reason to
1920
+ // re-encode video and lose a generation of quality.
1921
+ "-c:v",
1922
+ "copy",
1923
+ ...AUDIO_ENCODE,
1924
+ "-shortest",
1925
+ output
1926
+ );
1927
+ await ffmpeg(args, signal);
1928
+ const result = await probe(output, signal);
1929
+ const placed = tracks.map((t, i) => {
1930
+ const bits = [t.path];
1931
+ if (t.atSeconds) bits.push(`at ${Number(t.atSeconds)}s`);
1932
+ if (t.gain != null && Number(t.gain) !== 1) bits.push(`gain ${Number(t.gain)}`);
1933
+ if (t.loop) bits.push("looped");
1934
+ if (i === voice) bits.push("voice");
1935
+ else if (ducked.includes(i)) bits.push("ducked under the voice");
1936
+ return ` ${bits.join(", ")}`;
1937
+ }).join("\n");
1938
+ return `Mixed ${tracks.length} track(s) onto ${p.input}${p.keepOriginalAudio ? " over its own audio" : ""} \u2192 ${output} (${result.durationSec.toFixed(2)}s)
1939
+ ${placed}`;
1940
+ }
1941
+ __name(opMixAudio, "opMixAudio");
1942
+ async function opOverlayText(cwd, p, signal) {
1943
+ if (!p.input) throw new ToolError("`overlay_text` needs `input` (the video to draw on).");
1944
+ const cues = p.texts ?? [];
1945
+ if (cues.length === 0) {
1946
+ throw new ToolError(
1947
+ "`overlay_text` needs at least one entry in `texts`, each with `text` (plus optional fromSeconds, toSeconds, position, fontSize, color, box)."
1948
+ );
1949
+ }
1950
+ const input = requireExisting(cwd, p.input, "video");
1951
+ const output = prepareOutput(cwd, p.output, "overlay_text");
1952
+ const info = await probe(input, signal);
1953
+ if (!info.hasVideo) throw new ToolError(`${p.input} has no video stream.`);
1954
+ const font = resolveFont(cwd, p.fontFile);
1955
+ const tmp = mkdtempSync(join4(tmpdir2(), "pv-drawtext-"));
1956
+ try {
1957
+ const drawtexts = cues.map(
1958
+ (cue, i) => buildDrawtext({ cue: cue ?? {}, index: i, label: `texts[${i}]`, font, info, tmp })
1959
+ );
1960
+ await drawOnVideo(input, output, drawtexts, info, signal);
1961
+ const result = await probe(output, signal);
1962
+ return `Burned ${cues.length} text overlay(s) into ${p.input} \u2192 ${output} (${result.durationSec.toFixed(2)}s, ${result.width}x${result.height})`;
1963
+ } finally {
1964
+ rmSync3(tmp, { recursive: true, force: true });
1965
+ }
1966
+ }
1967
+ __name(opOverlayText, "opOverlayText");
1968
+ function buildDrawtext(args) {
1969
+ const { cue, index, label, font, info, tmp } = args;
1970
+ const body = String(cue.text ?? "");
1971
+ if (!body.trim()) throw new ToolError(`${label} has no \`text\`.`);
1972
+ const height = info.height ?? 1080;
1973
+ const fontSize = Math.round(bounded(cue.fontSize, `${label}.fontSize`, 8, 400, Math.max(16, Math.round(height / 20))));
1974
+ const margin = Math.round(bounded(cue.marginPx, `${label}.marginPx`, 0, 2e3, Math.round(fontSize * 0.8)));
1975
+ const { x, y } = positionExpr(cue.position ?? args.defaults?.position ?? "bottom", margin, label);
1976
+ const opts = [
1977
+ `fontfile=${filterPath(font)}`,
1978
+ `textfile=${filterPath(writeCueFile(tmp, index, body))}`,
1979
+ "expansion=none",
1980
+ `fontsize=${fontSize}`,
1981
+ `fontcolor=${colorValue(cue.color, "white", `${label}.color`)}`,
1982
+ `x=${x}`,
1983
+ `y=${y}`
1984
+ ];
1985
+ if (cue.box ?? args.defaults?.box) {
1986
+ const opacity = bounded(cue.boxOpacity, `${label}.boxOpacity`, 0, 1, 0.5);
1987
+ opts.push("box=1", `boxcolor=${colorValue(cue.boxColor, "black", `${label}.boxColor`)}@${opacity}`, `boxborderw=${Math.round(fontSize / 3)}`);
1988
+ } else {
1989
+ opts.push(`borderw=${Math.max(1, Math.round(fontSize / 16))}`, "bordercolor=black@0.85");
1990
+ }
1991
+ const from = cue.fromSeconds == null ? null : bounded(cue.fromSeconds, `${label}.fromSeconds`, 0, 86400, 0);
1992
+ const to = cue.toSeconds == null ? null : bounded(cue.toSeconds, `${label}.toSeconds`, 0, 86400, 0);
1993
+ if (from != null && to != null && to <= from) {
1994
+ throw new ToolError(`${label}: toSeconds (${to}) must be after fromSeconds (${from}).`);
1995
+ }
1996
+ if (from != null || to != null) {
1997
+ opts.push(`enable='between(t,${from ?? 0},${to ?? Math.max(from ?? 0, info.durationSec || 86400)})'`);
1998
+ }
1999
+ return `drawtext=${opts.join(":")}`;
2000
+ }
2001
+ __name(buildDrawtext, "buildDrawtext");
2002
+ async function drawOnVideo(input, output, filters, info, signal) {
2003
+ await ffmpeg(
2004
+ [
2005
+ "-i",
2006
+ input,
2007
+ "-filter_complex",
2008
+ `[0:v]${filters.join(",")}[vout]`,
2009
+ "-map",
2010
+ "[vout]",
2011
+ ...info.hasAudio ? ["-map", "0:a", "-c:a", "copy"] : [],
2012
+ ...VIDEO_ENCODE,
2013
+ output
2014
+ ],
2015
+ signal
2016
+ );
2017
+ }
2018
+ __name(drawOnVideo, "drawOnVideo");
2019
+ function writeCueFile(dir, index, body) {
2020
+ const file = join4(dir, `cue-${index}.txt`);
2021
+ writeFileSync5(file, body, "utf8");
2022
+ return file;
2023
+ }
2024
+ __name(writeCueFile, "writeCueFile");
2025
+ var POSITIONS = ["top-left", "top", "top-right", "left", "center", "right", "bottom-left", "bottom", "bottom-right"];
2026
+ var DRAWTEXT_VARS = { frameW: "w", frameH: "h", itemW: "text_w", itemH: "text_h" };
2027
+ var OVERLAY_VARS = { frameW: "W", frameH: "H", itemW: "w", itemH: "h" };
2028
+ function positionExpr(position, margin, label, vars = DRAWTEXT_VARS) {
2029
+ const name = String(position).trim().toLowerCase();
2030
+ if (!POSITIONS.includes(name)) {
2031
+ throw new ToolError(`${label}.position must be one of: ${POSITIONS.join(", ")} (got ${JSON.stringify(position)}).`);
2032
+ }
2033
+ const y = name.startsWith("top") ? String(margin) : name.startsWith("bottom") ? `${vars.frameH}-${vars.itemH}-${margin}` : `(${vars.frameH}-${vars.itemH})/2`;
2034
+ const x = name.endsWith("left") ? String(margin) : name.endsWith("right") ? `${vars.frameW}-${vars.itemW}-${margin}` : `(${vars.frameW}-${vars.itemW})/2`;
2035
+ return { x, y };
2036
+ }
2037
+ __name(positionExpr, "positionExpr");
2038
+ var FONT_CANDIDATES = {
2039
+ darwin: [
2040
+ "/System/Library/Fonts/Helvetica.ttc",
2041
+ "/System/Library/Fonts/Supplemental/Arial.ttf",
2042
+ "/Library/Fonts/Arial.ttf"
2043
+ ],
2044
+ linux: [
2045
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
2046
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
2047
+ "/usr/share/fonts/TTF/DejaVuSans.ttf",
2048
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
2049
+ "/usr/share/fonts/liberation-sans/LiberationSans-Bold.ttf"
2050
+ ],
2051
+ win32: ["C:\\Windows\\Fonts\\arialbd.ttf", "C:\\Windows\\Fonts\\arial.ttf", "C:\\Windows\\Fonts\\segoeui.ttf"]
2052
+ };
2053
+ function resolveFont(cwd, fontFile) {
2054
+ if (fontFile) return requireExisting(cwd, fontFile, "fontFile");
2055
+ for (const candidate of FONT_CANDIDATES[process.platform] ?? FONT_CANDIDATES.linux) {
2056
+ if (existsSync3(candidate)) return candidate;
2057
+ }
2058
+ throw new ToolError(
2059
+ `no system font found to draw with \u2014 pass \`fontFile\` with the path to a .ttf/.otf (looked for ${(FONT_CANDIDATES[process.platform] ?? FONT_CANDIDATES.linux).join(", ")}).`
2060
+ );
2061
+ }
2062
+ __name(resolveFont, "resolveFont");
2063
+ async function opOverlayImage(cwd, p, signal) {
2064
+ if (!p.input) throw new ToolError("`overlay_image` needs `input` (the video to draw on).");
2065
+ const raw = p.images ?? [];
2066
+ if (raw.length === 0) {
2067
+ throw new ToolError(
2068
+ "`overlay_image` needs at least one entry in `images`, each with a `path` (plus optional fromSeconds, toSeconds, position, widthPercent, opacity, marginPx)."
2069
+ );
2070
+ }
2071
+ const layers = raw.map((entry, i) => {
2072
+ const layer = typeof entry === "string" ? { path: entry } : entry ?? {};
2073
+ if (!layer.path) throw new ToolError(`images[${i}] has no \`path\`.`);
2074
+ return layer;
2075
+ });
2076
+ layers.forEach((layer, i) => {
2077
+ const label = `images[${i}]`;
2078
+ positionExpr(layer.position ?? "top-right", 0, label, OVERLAY_VARS);
2079
+ bounded(layer.opacity, `${label}.opacity`, 0, 1, 1);
2080
+ bounded(layer.widthPercent, `${label}.widthPercent`, 1, 100, 100);
2081
+ const from = bounded(layer.fromSeconds, `${label}.fromSeconds`, 0, 86400, 0);
2082
+ const to = layer.toSeconds == null ? null : bounded(layer.toSeconds, `${label}.toSeconds`, 0, 86400, 0);
2083
+ if (layer.fromSeconds != null && to != null && to <= from) {
2084
+ throw new ToolError(`${label}: toSeconds (${to}) must be after fromSeconds (${from}).`);
2085
+ }
2086
+ });
2087
+ const input = requireExisting(cwd, p.input, "video");
2088
+ const paths = layers.map((l, i) => requireExisting(cwd, l.path, `images[${i}]`));
2089
+ const output = prepareOutput(cwd, p.output, "overlay_image");
2090
+ const [info, ...layerInfos] = await Promise.all([probe(input, signal), ...paths.map((f) => probe(f, signal))]);
2091
+ if (!info.hasVideo) throw new ToolError(`${p.input} has no video stream.`);
2092
+ for (const [i, li] of layerInfos.entries()) {
2093
+ if (!li.hasVideo) throw new ToolError(`images[${i}] (${layers[i].path}) is not an image or video ffmpeg can read.`);
2094
+ }
2095
+ const frameW = info.width ?? 1280;
2096
+ const args = ["-i", input];
2097
+ for (const [i, li] of layerInfos.entries()) {
2098
+ if (li.durationSec === 0 && info.durationSec > 0) args.push("-loop", "1", "-t", info.durationSec.toFixed(3));
2099
+ args.push("-i", paths[i]);
2100
+ }
2101
+ const filters = [];
2102
+ const scaledTo = [];
2103
+ for (const [i, layer] of layers.entries()) {
2104
+ const label = `images[${i}]`;
2105
+ const pct = layer.widthPercent == null ? null : bounded(layer.widthPercent, `${label}.widthPercent`, 1, 100, 100);
2106
+ const nativeW = layerInfos[i].width ?? frameW;
2107
+ const targetW = pct != null ? Math.round(frameW * pct / 100) : nativeW > frameW ? frameW : null;
2108
+ scaledTo.push(targetW);
2109
+ const chain = [];
2110
+ if (targetW != null) chain.push(`scale=${Math.max(2, targetW - targetW % 2)}:-1`);
2111
+ const opacity = bounded(layer.opacity, `${label}.opacity`, 0, 1, 1);
2112
+ if (opacity < 1) chain.push("format=rgba", `colorchannelmixer=aa=${opacity}`);
2113
+ filters.push(`[${i + 1}:v]${chain.length > 0 ? chain.join(",") : "null"}[img${i}]`);
2114
+ }
2115
+ let vPrev = "0:v";
2116
+ layers.forEach((layer, i) => {
2117
+ const label = `images[${i}]`;
2118
+ const margin = Math.round(bounded(layer.marginPx, `${label}.marginPx`, 0, 2e3, Math.round(frameW * 0.03)));
2119
+ const { x, y } = positionExpr(layer.position ?? "top-right", margin, label, OVERLAY_VARS);
2120
+ const from = layer.fromSeconds == null ? null : bounded(layer.fromSeconds, `${label}.fromSeconds`, 0, 86400, 0);
2121
+ const to = layer.toSeconds == null ? null : bounded(layer.toSeconds, `${label}.toSeconds`, 0, 86400, 0);
2122
+ if (from != null && to != null && to <= from) {
2123
+ throw new ToolError(`${label}: toSeconds (${to}) must be after fromSeconds (${from}).`);
2124
+ }
2125
+ const opts = [`x=${x}`, `y=${y}`];
2126
+ if (from != null || to != null) {
2127
+ opts.push(`enable='between(t,${from ?? 0},${to ?? Math.max(from ?? 0, info.durationSec || 86400)})'`);
2128
+ }
2129
+ opts.push("eof_action=pass");
2130
+ const next = i === layers.length - 1 ? "vout" : `vo${i}`;
2131
+ filters.push(`[${vPrev}][img${i}]overlay=${opts.join(":")}[${next}]`);
2132
+ vPrev = next;
2133
+ });
2134
+ await ffmpeg(
2135
+ [
2136
+ ...args,
2137
+ "-filter_complex",
2138
+ filters.join(";"),
2139
+ "-map",
2140
+ "[vout]",
2141
+ ...info.hasAudio ? ["-map", "0:a", "-c:a", "copy"] : [],
2142
+ ...VIDEO_ENCODE,
2143
+ output
2144
+ ],
2145
+ signal
2146
+ );
2147
+ const result = await probe(output, signal);
2148
+ const placed = layers.map((l, i) => {
2149
+ const bits = [l.path, l.position ?? "top-right"];
2150
+ if (scaledTo[i] != null) bits.push(`${scaledTo[i]}px wide`);
2151
+ if (l.opacity != null && Number(l.opacity) < 1) bits.push(`opacity ${Number(l.opacity)}`);
2152
+ if (l.fromSeconds != null || l.toSeconds != null) bits.push(`${l.fromSeconds ?? 0}s-${l.toSeconds ?? "end"}`);
2153
+ return ` ${bits.join(", ")}`;
2154
+ }).join("\n");
2155
+ return `Composited ${layers.length} image(s) onto ${p.input} \u2192 ${output} (${result.durationSec.toFixed(2)}s, ${result.width}x${result.height})
2156
+ ${placed}`;
2157
+ }
2158
+ __name(opOverlayImage, "opOverlayImage");
2159
+ var MAX_SUBTITLE_CUES = 500;
2160
+ var DEFAULT_SUBTITLE_CHARS = 42;
2161
+ async function opBurnSubtitles(cwd, p, signal) {
2162
+ if (!p.input) throw new ToolError("`burn_subtitles` needs `input` (the video to draw on).");
2163
+ if (!p.subtitles) throw new ToolError("`burn_subtitles` needs `subtitles` (the path to an .srt or .vtt file).");
2164
+ const wrapAt = Math.round(bounded(p.maxCharsPerLine, "maxCharsPerLine", 10, 200, DEFAULT_SUBTITLE_CHARS));
2165
+ const input = requireExisting(cwd, p.input, "video");
2166
+ const subs = requireExisting(cwd, p.subtitles, "subtitles");
2167
+ const output = prepareOutput(cwd, p.output, "burn_subtitles");
2168
+ const info = await probe(input, signal);
2169
+ if (!info.hasVideo) throw new ToolError(`${p.input} has no video stream.`);
2170
+ const parsed = parseSubtitleCues(readFileSync5(subs, "utf8"));
2171
+ if (parsed.length === 0) {
2172
+ throw new ToolError(
2173
+ `no cues found in ${p.subtitles} \u2014 expected SubRip (.srt) or WebVTT (.vtt), where each cue is a \`00:00:01,000 --> 00:00:04,000\` line followed by its text.`
2174
+ );
2175
+ }
2176
+ if (parsed.length > MAX_SUBTITLE_CUES) {
2177
+ throw new ToolError(
2178
+ `${p.subtitles} has ${parsed.length} cues, over the ${MAX_SUBTITLE_CUES} this can burn in one pass. Trim the video and its subtitles into sections and burn each, or use fewer, longer cues.`
2179
+ );
2180
+ }
2181
+ const style = p.style ?? {};
2182
+ const font = resolveFont(cwd, p.fontFile);
2183
+ const tmp = mkdtempSync(join4(tmpdir2(), "pv-subtitles-"));
2184
+ try {
2185
+ const drawtexts = parsed.map(
2186
+ (cue, i) => buildDrawtext({
2187
+ cue: { ...style, text: wrapLines(cue.text, wrapAt), fromSeconds: cue.from, toSeconds: cue.to },
2188
+ index: i,
2189
+ label: "style",
2190
+ font,
2191
+ info,
2192
+ tmp,
2193
+ // Captions live at the bottom, and against generated footage they need a plate
2194
+ // more often than a title does — so a box is the default here where overlay_text
2195
+ // defaults to an outline. `style.box: false` turns it back off.
2196
+ defaults: { position: "bottom", box: true }
2197
+ })
2198
+ );
2199
+ await drawOnVideo(input, output, drawtexts, info, signal);
2200
+ const result = await probe(output, signal);
2201
+ const last = parsed[parsed.length - 1];
2202
+ return `Burned ${parsed.length} subtitle cue(s) from ${p.subtitles} into ${p.input} \u2192 ${output} (${result.durationSec.toFixed(2)}s, wrapped at ${wrapAt} characters, last cue ends at ${last.to.toFixed(2)}s)` + (last.to > info.durationSec + 0.5 ? `
2203
+ Note: the subtitles run ${(last.to - info.durationSec).toFixed(2)}s past the end of the video \u2014 those cues will never be seen.` : "");
2204
+ } finally {
2205
+ rmSync3(tmp, { recursive: true, force: true });
2206
+ }
2207
+ }
2208
+ __name(opBurnSubtitles, "opBurnSubtitles");
2209
+ function parseTimecode(raw) {
2210
+ const m = /^(?:(\d{1,3}):)?(\d{1,2}):(\d{1,2})(?:[.,](\d{1,3}))?$/.exec(raw.trim());
2211
+ if (!m) return null;
2212
+ const ms = m[4] ? Number(m[4].padEnd(3, "0")) : 0;
2213
+ return Number(m[1] ?? 0) * 3600 + Number(m[2]) * 60 + Number(m[3]) + ms / 1e3;
2214
+ }
2215
+ __name(parseTimecode, "parseTimecode");
2216
+ function stripMarkup(s) {
2217
+ return s.replace(/<[^>\n]*>/g, "").replace(/\{\\[^}\n]*\}/g, "");
2218
+ }
2219
+ __name(stripMarkup, "stripMarkup");
2220
+ function parseSubtitleCues(body) {
2221
+ const lines = body.replace(/^/, "").replace(/\r\n?/g, "\n").split("\n");
2222
+ const cues = [];
2223
+ for (let i = 0; i < lines.length; i++) {
2224
+ const arrow = lines[i].indexOf("-->");
2225
+ if (arrow === -1) continue;
2226
+ const from = parseTimecode(lines[i].slice(0, arrow));
2227
+ const to = parseTimecode(lines[i].slice(arrow + 3).trim().split(/\s+/)[0] ?? "");
2228
+ if (from == null || to == null || to <= from) continue;
2229
+ const text3 = [];
2230
+ let j = i + 1;
2231
+ for (; j < lines.length && lines[j].trim() !== ""; j++) text3.push(lines[j]);
2232
+ i = j;
2233
+ const clean = stripMarkup(text3.join("\n")).split("\n").map((l) => l.trim()).filter(Boolean).join("\n");
2234
+ if (clean) cues.push({ from, to, text: clean });
2235
+ }
2236
+ return cues;
2237
+ }
2238
+ __name(parseSubtitleCues, "parseSubtitleCues");
2239
+ function wrapLines(text3, max) {
2240
+ return text3.split("\n").map((line) => {
2241
+ const out = [];
2242
+ let current = "";
2243
+ for (const word of line.split(/\s+/).filter(Boolean)) {
2244
+ if (current === "") current = word;
2245
+ else if (current.length + 1 + word.length <= max) current += ` ${word}`;
2246
+ else {
2247
+ out.push(current);
2248
+ current = word;
2249
+ }
2250
+ }
2251
+ if (current) out.push(current);
2252
+ return out.join("\n");
2253
+ }).join("\n");
2254
+ }
2255
+ __name(wrapLines, "wrapLines");
2256
+ async function opTrim(cwd, p, signal) {
2257
+ if (!p.input) throw new ToolError("`trim` needs `input`.");
2258
+ const input = requireExisting(cwd, p.input, "input");
2259
+ const output = prepareOutput(cwd, p.output, "trim");
2260
+ const start = p.start != null ? Number(p.start) : 0;
2261
+ if (!Number.isFinite(start) || start < 0) throw new ToolError("`start` must be a number of seconds >= 0.");
2262
+ const info = await probe(input, signal);
2263
+ if (info.durationSec && start >= info.durationSec) {
2264
+ throw new ToolError(`\`start\` (${start}s) is at or past the end of ${p.input} (${info.durationSec.toFixed(2)}s).`);
2265
+ }
2266
+ const args = ["-ss", String(start), "-i", input];
2267
+ if (p.duration != null) {
2268
+ const d = Number(p.duration);
2269
+ if (!Number.isFinite(d) || d <= 0) throw new ToolError("`duration` must be a positive number of seconds.");
2270
+ args.push("-t", String(d));
2271
+ }
2272
+ args.push(...VIDEO_ENCODE, ...info.hasAudio ? AUDIO_ENCODE : ["-an"], output);
2273
+ await ffmpeg(args, signal);
2274
+ const result = await probe(output, signal);
2275
+ return `Trimmed ${p.input} from ${start}s${p.duration != null ? ` for ${p.duration}s` : " to the end"} \u2192 ${output} (${result.durationSec.toFixed(2)}s)`;
2276
+ }
2277
+ __name(opTrim, "opTrim");
2278
+ async function opExtractFrame(cwd, p, signal) {
2279
+ if (!p.input) throw new ToolError("`extract_frame` needs `input`.");
2280
+ const input = requireExisting(cwd, p.input, "input");
2281
+ const output = prepareOutput(cwd, p.output, "extract_frame");
2282
+ const info = await probe(input, signal);
2283
+ if (!info.hasVideo) throw new ToolError(`${p.input} has no video stream.`);
2284
+ let at;
2285
+ if (p.at === "last" || p.at === void 0) {
2286
+ at = p.at === void 0 ? 0 : Math.max(0, info.durationSec - 0.05);
2287
+ } else {
2288
+ at = Number(p.at);
2289
+ if (!Number.isFinite(at) || at < 0) throw new ToolError('`at` must be a number of seconds, or "last".');
2290
+ if (info.durationSec && at > info.durationSec) {
2291
+ throw new ToolError(`\`at\` (${at}s) is past the end of ${p.input} (${info.durationSec.toFixed(2)}s).`);
2292
+ }
2293
+ }
2294
+ await ffmpeg(["-ss", String(at), "-i", input, "-frames:v", "1", "-q:v", "2", output], signal);
2295
+ if (!existsSync3(output)) throw new ToolError(`ffmpeg produced no frame at ${at}s \u2014 try a slightly earlier timestamp.`);
2296
+ return `Extracted the frame at ${at.toFixed(2)}s of ${p.input} \u2192 ${output}`;
2297
+ }
2298
+ __name(opExtractFrame, "opExtractFrame");
2299
+ async function opGif(cwd, p, signal) {
2300
+ if (!p.input) throw new ToolError("`gif` needs `input`.");
2301
+ const input = requireExisting(cwd, p.input, "input");
2302
+ const output = prepareOutput(cwd, p.output, "gif");
2303
+ const fps = p.fps && p.fps > 0 ? Math.round(p.fps) : 12;
2304
+ const size = parseSize(p.size);
2305
+ const width = size ? size[0] : 640;
2306
+ const args = ["-i", input];
2307
+ if (p.start != null) args.splice(0, 0, "-ss", String(Number(p.start)));
2308
+ if (p.duration != null) args.push("-t", String(Number(p.duration)));
2309
+ args.push(
2310
+ "-filter_complex",
2311
+ `fps=${fps},scale=${width}:-2:flags=lanczos,split[s0][s1];[s0]palettegen=stats_mode=diff[p];[s1][p]paletteuse=dither=bayer:bayer_scale=3`,
2312
+ "-loop",
2313
+ "0",
2314
+ output
2315
+ );
2316
+ await ffmpeg(args, signal);
2317
+ return `Made a ${fps} fps GIF from ${p.input} \u2192 ${output}`;
2318
+ }
2319
+ __name(opGif, "opGif");
2320
+ var videoComposeToolDefinition = {
2321
+ name: "video_compose",
2322
+ label: "Compose Video",
2323
+ description: "Assemble and edit video and audio files on this machine with ffmpeg. Free, local, and instant \u2014 no account, no billing. This is the other half of a media workflow: generate_image and generate_video produce the raw material, and this turns it into a finished piece.\nOperations and the parameters each one uses:\n probe \u2014 input (or inputs): report duration, dimensions, fps and whether there is audio. Call this before planning any edit.\n concat \u2014 inputs (2+), output, optional crossfadeSeconds, size, fps: stitch clips end to end. Clips of different sizes/frame rates are normalized to the first one (or `size`), and clips with no audio get silence so the join doesn't fail.\n slideshow \u2014 inputs (images), output, optional secondsPerImage, crossfadeSeconds, size, fps: turn stills into a video. Output is silent; add sound with mux_audio.\n mux_audio \u2014 input (video), audio, output, optional loopAudio, volume, keepOriginalAudio: put ONE track onto a video at one level, trimmed to the video's length.\n mix_audio \u2014 input (video), tracks, output, optional voiceTrack, keepOriginalAudio: put SEVERAL tracks on at once, each placed and levelled. Every track takes `path` plus optional `atSeconds` (when it starts \u2014 this is how a sound effect lands on the frame it belongs to), `gain` (0-4), `loop` (repeat a short bed to the end) and `duck` (press this track down while the narration speaks). Set `voiceTrack` to the index of the narration for `duck` to key off. Use this rather than several mux_audio passes: each pass re-encodes the sound and mixes blind to what comes next.\n overlay_text \u2014 input (video), texts, output, optional fontFile: burn type into the picture. Each entry takes `text` plus optional `fromSeconds`/`toSeconds` (when it shows), `position` (one of top-left, top, top-right, left, center, right, bottom-left, bottom, bottom-right), `fontSize` (defaults to the frame height / 20), `color`, `box`, `boxColor`, `boxOpacity`, `marginPx`. Audio is copied through untouched.\n overlay_image \u2014 input (video), images, output: composite stills onto the picture \u2014 a logo bug, an end card, a lower-third plate. Each entry takes `path` plus optional `fromSeconds`/`toSeconds`, `position` (same nine names, defaults to top-right), `widthPercent` (of the frame width \u2014 the way to size a logo, since the art's own pixel size means nothing), `opacity` (0-1, for a watermark) and `marginPx`. Audio is copied through untouched.\n burn_subtitles \u2014 input (video), subtitles (.srt or .vtt), output, optional style, maxCharsPerLine, fontFile: burn a whole subtitle file in, timed from the file itself. Lines are wrapped to fit (42 characters by default) and drawn at the bottom on a plate; `style` takes the same fields as an overlay_text entry and applies to every cue. Needs no libass \u2014 italics and per-cue positioning in the file are dropped, everything else is honoured.\n trim \u2014 input, output, start, optional duration: cut a section out, frame-accurate.\n extract_frame \u2014 input, output, optional at (seconds, or \"last\"): pull one still. Extract the last frame of a clip and pass it to generate_video as `firstFrame` to keep consecutive clips visually continuous.\n gif \u2014 input, output, optional start, duration, fps, size: make an animated GIF.\nNeeds ffmpeg installed; every operation says so plainly if it isn't.",
2324
+ parameters: typebox_exports.Object({
2325
+ operation: typebox_exports.String({
2326
+ description: 'One of: "probe", "concat", "slideshow", "mux_audio", "mix_audio", "overlay_text", "overlay_image", "burn_subtitles", "trim", "extract_frame", "gif".'
2327
+ }),
2328
+ inputs: typebox_exports.Optional(typebox_exports.Array(typebox_exports.String(), { description: "Input paths, in order. Used by concat, slideshow, and probe." })),
2329
+ input: typebox_exports.Optional(typebox_exports.String({ description: "A single input path. Used by probe, mux_audio (the video), trim, extract_frame, gif." })),
2330
+ audio: typebox_exports.Optional(typebox_exports.String({ description: "Path to the audio track. mux_audio only." })),
2331
+ output: typebox_exports.Optional(typebox_exports.String({ description: "Where to write the result. Required by everything except probe." })),
2332
+ size: typebox_exports.Optional(typebox_exports.String({ description: `Target frame size, e.g. "1920x1080". Defaults to the first input's size (gif defaults to 640 wide).` })),
2333
+ fps: typebox_exports.Optional(typebox_exports.Number({ description: "Target frame rate. Defaults to the first input's (30 for slideshow, 12 for gif)." })),
2334
+ secondsPerImage: typebox_exports.Optional(typebox_exports.Number({ description: "How long each still is held. slideshow only; defaults to 3." })),
2335
+ crossfadeSeconds: typebox_exports.Optional(typebox_exports.Number({ description: "Cross-dissolve between clips/stills instead of a hard cut. concat and slideshow; defaults to 0 (hard cut)." })),
2336
+ start: typebox_exports.Optional(typebox_exports.Number({ description: "Start offset in seconds. trim and gif." })),
2337
+ duration: typebox_exports.Optional(typebox_exports.Number({ description: "Length in seconds from `start`. trim and gif; omit to run to the end." })),
2338
+ at: typebox_exports.Optional(typebox_exports.Union([typebox_exports.Number(), typebox_exports.String()], { description: 'Timestamp for extract_frame: seconds, or "last" for the final frame. Defaults to 0.' })),
2339
+ volume: typebox_exports.Optional(typebox_exports.Number({ description: "Volume multiplier for the added track, 0-4. mux_audio only; defaults to 1." })),
2340
+ loopAudio: typebox_exports.Optional(typebox_exports.Boolean({ description: "Repeat a short audio track until the video ends. mux_audio only." })),
2341
+ keepOriginalAudio: typebox_exports.Optional(typebox_exports.Boolean({ description: "Mix under the video's existing audio instead of replacing it. mux_audio and mix_audio." })),
2342
+ tracks: typebox_exports.Optional(
2343
+ typebox_exports.Array(
2344
+ typebox_exports.Object({
2345
+ path: typebox_exports.String({ description: "The audio file." }),
2346
+ atSeconds: typebox_exports.Optional(typebox_exports.Number({ description: "When it starts, in seconds from the beginning of the video. Defaults to 0." })),
2347
+ gain: typebox_exports.Optional(typebox_exports.Number({ description: "Volume multiplier, 0-4. Defaults to 1. A bed under narration usually wants 0.2-0.4." })),
2348
+ loop: typebox_exports.Optional(typebox_exports.Boolean({ description: "Repeat this track until the video ends \u2014 for a short music bed." })),
2349
+ duck: typebox_exports.Optional(typebox_exports.Boolean({ description: "Press this track down whenever the `voiceTrack` is speaking, and let it back up between lines." }))
2350
+ }),
2351
+ { description: "The tracks to place, in any order. mix_audio only." }
2352
+ )
2353
+ ),
2354
+ voiceTrack: typebox_exports.Optional(
2355
+ typebox_exports.Number({
2356
+ description: "Index into `tracks` of the narration everything else ducks under (0 = the first track). Required if any track sets `duck`. mix_audio only."
2357
+ })
2358
+ ),
2359
+ texts: typebox_exports.Optional(
2360
+ typebox_exports.Array(
2361
+ typebox_exports.Object({
2362
+ text: typebox_exports.String({ description: "The words to draw. Punctuation, colons and percent signs are all safe \u2014 the text never reaches the filter as syntax." }),
2363
+ fromSeconds: typebox_exports.Optional(typebox_exports.Number({ description: "When it appears. Omit for the whole video." })),
2364
+ toSeconds: typebox_exports.Optional(typebox_exports.Number({ description: "When it disappears. Omit to hold to the end." })),
2365
+ position: typebox_exports.Optional(typebox_exports.String({ description: "top-left, top, top-right, left, center, right, bottom-left, bottom, bottom-right. Defaults to bottom." })),
2366
+ fontSize: typebox_exports.Optional(typebox_exports.Number({ description: "In pixels, 8-400. Defaults to the frame height / 20." })),
2367
+ color: typebox_exports.Optional(typebox_exports.String({ description: "A colour name or #rrggbb. Defaults to white." })),
2368
+ box: typebox_exports.Optional(typebox_exports.Boolean({ description: "Draw a filled box behind the type. Without it the type gets a dark outline instead." })),
2369
+ boxColor: typebox_exports.Optional(typebox_exports.String({ description: "Box colour name or #rrggbb. Defaults to black." })),
2370
+ boxOpacity: typebox_exports.Optional(typebox_exports.Number({ description: "Box opacity, 0-1. Defaults to 0.5." })),
2371
+ marginPx: typebox_exports.Optional(typebox_exports.Number({ description: "Distance from the frame edge. Defaults to about 0.8 of the font size." }))
2372
+ }),
2373
+ { description: "The text to burn in. overlay_text only." }
2374
+ )
2375
+ ),
2376
+ fontFile: typebox_exports.Optional(
2377
+ typebox_exports.String({
2378
+ description: "Path to a .ttf/.otf to draw with. Omit to use a system font \u2014 pass one if the video needs the brand's typeface. overlay_text and burn_subtitles."
2379
+ })
2380
+ ),
2381
+ images: typebox_exports.Optional(
2382
+ typebox_exports.Array(
2383
+ typebox_exports.Object({
2384
+ path: typebox_exports.String({ description: "The image (or short video) to composite. PNG transparency is preserved." }),
2385
+ fromSeconds: typebox_exports.Optional(typebox_exports.Number({ description: "When it appears. Omit for the whole video." })),
2386
+ toSeconds: typebox_exports.Optional(typebox_exports.Number({ description: "When it disappears. Omit to hold to the end." })),
2387
+ position: typebox_exports.Optional(typebox_exports.String({ description: "top-left, top, top-right, left, center, right, bottom-left, bottom, bottom-right. Defaults to top-right." })),
2388
+ widthPercent: typebox_exports.Optional(typebox_exports.Number({ description: "Width as a percentage of the video's width, 1-100. The right way to size a logo. Omit to use the art at its own size (shrunk to fit if it is wider than the frame)." })),
2389
+ opacity: typebox_exports.Optional(typebox_exports.Number({ description: "0-1. Defaults to 1 (opaque); 0.3-0.6 is the range a watermark wants." })),
2390
+ marginPx: typebox_exports.Optional(typebox_exports.Number({ description: "Distance from the frame edge. Defaults to about 3% of the frame width." }))
2391
+ }),
2392
+ { description: "The images to composite, drawn in order (later entries sit on top). overlay_image only." }
2393
+ )
2394
+ ),
2395
+ subtitles: typebox_exports.Optional(
2396
+ typebox_exports.String({ description: "Path to a SubRip (.srt) or WebVTT (.vtt) file. Its own timings drive the cues. burn_subtitles only." })
2397
+ ),
2398
+ style: typebox_exports.Optional(
2399
+ typebox_exports.Object({
2400
+ position: typebox_exports.Optional(typebox_exports.String({ description: "Where every cue sits. Defaults to bottom." })),
2401
+ fontSize: typebox_exports.Optional(typebox_exports.Number({ description: "In pixels, 8-400. Defaults to the frame height / 20." })),
2402
+ color: typebox_exports.Optional(typebox_exports.String({ description: "A colour name or #rrggbb. Defaults to white." })),
2403
+ box: typebox_exports.Optional(typebox_exports.Boolean({ description: "Draw a plate behind the type. Defaults to TRUE for subtitles; set false for an outline instead." })),
2404
+ boxColor: typebox_exports.Optional(typebox_exports.String({ description: "Plate colour name or #rrggbb. Defaults to black." })),
2405
+ boxOpacity: typebox_exports.Optional(typebox_exports.Number({ description: "Plate opacity, 0-1. Defaults to 0.5." })),
2406
+ marginPx: typebox_exports.Optional(typebox_exports.Number({ description: "Distance from the frame edge. Defaults to about 0.8 of the font size." }))
2407
+ }, { description: "How every subtitle cue is drawn. burn_subtitles only." })
2408
+ ),
2409
+ maxCharsPerLine: typebox_exports.Optional(
2410
+ typebox_exports.Number({
2411
+ description: "Wrap subtitle lines longer than this, 10-200. Defaults to 42 (the broadcast convention). burn_subtitles only."
2412
+ })
2413
+ )
2414
+ }),
2415
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
2416
+ const cwd = ctx?.cwd ?? process.cwd();
2417
+ const operation = String(params.operation ?? "").trim().toLowerCase();
2418
+ if (!OPERATIONS.includes(operation)) {
2419
+ return text2(`Error: unknown operation "${params.operation}". Use one of: ${OPERATIONS.join(", ")}.`);
2420
+ }
2421
+ try {
2422
+ switch (operation) {
2423
+ case "probe":
2424
+ return text2(await opProbe(cwd, params, signal));
2425
+ case "concat":
2426
+ return text2(await opConcat(cwd, params, signal));
2427
+ case "slideshow":
2428
+ return text2(await opSlideshow(cwd, params, signal));
2429
+ case "mux_audio":
2430
+ return text2(await opMuxAudio(cwd, params, signal));
2431
+ case "mix_audio":
2432
+ return text2(await opMixAudio(cwd, params, signal));
2433
+ case "overlay_text":
2434
+ return text2(await opOverlayText(cwd, params, signal));
2435
+ case "overlay_image":
2436
+ return text2(await opOverlayImage(cwd, params, signal));
2437
+ case "burn_subtitles":
2438
+ return text2(await opBurnSubtitles(cwd, params, signal));
2439
+ case "trim":
2440
+ return text2(await opTrim(cwd, params, signal));
2441
+ case "extract_frame":
2442
+ return text2(await opExtractFrame(cwd, params, signal));
2443
+ case "gif":
2444
+ return text2(await opGif(cwd, params, signal));
2445
+ }
2446
+ } catch (e) {
2447
+ return text2(`video_compose ${operation} failed: ${e instanceof Error ? e.message : String(e)}`);
2448
+ }
2449
+ }
2450
+ };
2451
+ function makeComposeTools() {
2452
+ return (pi) => {
2453
+ pi.registerTool?.(videoComposeToolDefinition);
2454
+ };
2455
+ }
2456
+ __name(makeComposeTools, "makeComposeTools");
2457
+
2458
+ // src/config/hosted.ts?ext=privateer-media
2459
+ function isHosted() {
2460
+ return process.env.HARBOR_HOSTED === "1";
2461
+ }
2462
+ __name(isHosted, "isHosted");
2463
+ function mediaEnabled() {
2464
+ const flag = process.env.HARBOR_MEDIA;
2465
+ if (flag === "1") return hasCredentials();
2466
+ if (flag === "0") return false;
2467
+ if (isHosted()) return false;
2468
+ return hasCredentials();
2469
+ }
2470
+ __name(mediaEnabled, "mediaEnabled");
2471
+
2472
+ // src/remote/subagentChannel.ts?ext=privateer-media
2473
+ var DEFAULT_TIMEOUT_MS = 10 * 6e4;
2474
+
2475
+ // src/remote/subagentRelay.ts?ext=privateer-media
2476
+ function isSubagentChild() {
2477
+ return process.env.PI_SUBAGENT_CHILD === "1";
2478
+ }
2479
+ __name(isSubagentChild, "isSubagentChild");
2480
+
2481
+ // src/permissions/childSpend.ts?ext=privateer-media
2482
+ var CHILD_SPEND_ENV = "PRIVATEER_CHILD_SPEND";
2483
+ function inheritedChildSpend(env = process.env) {
2484
+ if (!isSubagentChild()) return /* @__PURE__ */ new Set();
2485
+ const raw = env[CHILD_SPEND_ENV];
2486
+ if (!raw) return /* @__PURE__ */ new Set();
2487
+ return new Set(
2488
+ raw.split(",").map((t) => t.trim()).filter(Boolean)
2489
+ );
2490
+ }
2491
+ __name(inheritedChildSpend, "inheritedChildSpend");
2492
+ function childHoldsSpendGrant() {
2493
+ return inheritedChildSpend().size > 0;
2494
+ }
2495
+ __name(childHoldsSpendGrant, "childHoldsSpendGrant");
2496
+
2497
+ // src/tools/mediaModelCommands.ts?ext=privateer-media
2498
+ var ACTION = { image: "imageGen", video: "videoGen" };
2499
+ var RESET = /* @__PURE__ */ new Set(["default", "reset", "clear", "none", "account"]);
2500
+ async function fetchMediaCatalog(kind) {
2501
+ let res;
2502
+ try {
2503
+ res = await apiRequest(`/api/models/openrouter?action=${ACTION[kind]}`, { method: "GET" });
2504
+ } catch (e) {
2505
+ return { ok: false, message: `could not reach Privateer: ${e instanceof Error ? e.message : String(e)}` };
2506
+ }
2507
+ if (!res.ok) {
2508
+ if (res.status === 401) return { ok: false, message: "not signed in \u2014 run /login first" };
2509
+ return { ok: false, message: `Privateer returned ${res.status}` };
2510
+ }
2511
+ try {
2512
+ const body = await res.json();
2513
+ const models = (body.models ?? []).filter(
2514
+ (m) => m && typeof m.id === "string" && m.id && !m.id.startsWith("openrouter/")
2515
+ );
2516
+ return { ok: true, models };
2517
+ } catch {
2518
+ return { ok: false, message: "Privateer returned a malformed model list" };
2519
+ }
2520
+ }
2521
+ __name(fetchMediaCatalog, "fetchMediaCatalog");
2522
+ function formatDurations(d) {
2523
+ const s = [...new Set(d)].sort((a, b) => a - b);
2524
+ const contiguous = s.length > 2 && s.every((v, i) => i === 0 || v === s[i - 1] + 1);
2525
+ return contiguous ? `${s[0]}-${s[s.length - 1]}s` : `${s.join("/")}s`;
2526
+ }
2527
+ __name(formatDurations, "formatDurations");
2528
+ function describeCatalogRow(m, kind, current) {
2529
+ const posture = m.isTee ? "confidential" : m.isZdr ? "ZDR" : "non-ZDR";
2530
+ const tags = [posture];
2531
+ if (kind === "video") {
2532
+ if (m.supportedDurations?.length) tags.push(formatDurations(m.supportedDurations));
2533
+ if (m.supportsImageToVideo) tags.push("first frame");
2534
+ if (m.generateAudio) tags.push("audio");
2535
+ }
2536
+ const name = m.name && m.name !== m.id ? `${m.name} ` : "";
2537
+ return `${m.id === current ? "\u25CF " : " "}${name}${m.id} (${tags.join(", ")})`;
2538
+ }
2539
+ __name(describeCatalogRow, "describeCatalogRow");
2540
+ var LABEL = { image: "Image", video: "Video" };
2541
+ function nonZdrWarning(m) {
2542
+ return m && !m.isZdr && !m.isTee ? " \u2014 non-ZDR: refused if this account requires Zero Data Retention for media (Settings \u2192 Privacy)" : "";
2543
+ }
2544
+ __name(nonZdrWarning, "nonZdrWarning");
2545
+ async function runMediaModelCommand(kind, args, ui, catalog = fetchMediaCatalog) {
2546
+ const say = /* @__PURE__ */ __name((msg, level = "info") => ui?.notify?.(msg, level), "say");
2547
+ const label = LABEL[kind];
2548
+ const current = mediaModelPref(kind);
2549
+ const arg = String(args ?? "").trim();
2550
+ if (RESET.has(arg.toLowerCase())) {
2551
+ setMediaModelPref(kind, null);
2552
+ say(`${label} model: account default${current ? ` (was ${current})` : ""}`);
2553
+ return;
2554
+ }
2555
+ const list = await catalog(kind);
2556
+ if (arg) {
2557
+ if (list.ok) {
2558
+ const hit = list.models.find((m) => m.id === arg) ?? list.models.find((m) => m.id.toLowerCase() === arg.toLowerCase());
2559
+ if (!hit) {
2560
+ const near = list.models.filter((m) => m.id.toLowerCase().includes(arg.toLowerCase())).slice(0, 5);
2561
+ say(
2562
+ `No ${kind} model "${arg}" on this account.` + (near.length ? ` Did you mean: ${near.map((m) => m.id).join(", ")}?` : ` Run /${kind}-model to browse.`),
2563
+ "warning"
2564
+ );
2565
+ return;
2566
+ }
2567
+ setMediaModelPref(kind, hit.id);
2568
+ say(`${label} model: ${hit.id}${nonZdrWarning(hit)}`);
2569
+ return;
2570
+ }
2571
+ setMediaModelPref(kind, arg);
2572
+ say(`${label} model: ${arg} (couldn't check it against the catalog: ${list.message})`, "warning");
2573
+ return;
2574
+ }
2575
+ if (!list.ok) {
2576
+ say(`Couldn't list ${kind} models: ${list.message}`, "error");
2577
+ return;
2578
+ }
2579
+ if (!list.models.length) {
2580
+ say(`This account has no ${kind} models available.`, "warning");
2581
+ return;
2582
+ }
2583
+ if (!ui?.select) {
2584
+ say(`${label} model: ${current ?? "account default"}. Set one with /${kind}-model <id>.`);
2585
+ return;
2586
+ }
2587
+ const DEFAULT_ROW = `${current ? " " : "\u25CF "}Account default`;
2588
+ const rows = list.models.map((m) => describeCatalogRow(m, kind, current));
2589
+ const picked = await ui.select(`${label} model for generate_${kind} \u2014 current: ${current ?? "account default"}`, [
2590
+ DEFAULT_ROW,
2591
+ ...rows
2592
+ ]);
2593
+ if (picked === void 0) return;
2594
+ if (picked === DEFAULT_ROW) {
2595
+ setMediaModelPref(kind, null);
2596
+ say(`${label} model: account default`);
2597
+ return;
2598
+ }
2599
+ const chosen = list.models[rows.indexOf(picked)];
2600
+ if (!chosen) return;
2601
+ setMediaModelPref(kind, chosen.id);
2602
+ say(`${label} model: ${chosen.id}${nonZdrWarning(chosen)}`);
2603
+ }
2604
+ __name(runMediaModelCommand, "runMediaModelCommand");
2605
+ function registerMediaModelCommands(pi) {
2606
+ for (const kind of ["image", "video"]) {
2607
+ pi.registerCommand?.(`${kind}-model`, {
2608
+ description: `Choose the model generate_${kind} uses on this machine (default = the account's)`,
2609
+ argumentHint: "[model id | default]",
2610
+ handler: /* @__PURE__ */ __name((args, ctx) => runMediaModelCommand(kind, args, ctx?.ui), "handler")
2611
+ });
2612
+ }
2613
+ }
2614
+ __name(registerMediaModelCommands, "registerMediaModelCommands");
2615
+
2616
+ // extensions/privateer-media.ts?ext=privateer-media
2617
+ function privateerMedia(pi) {
2618
+ const canSpend = !isSubagentChild() || childHoldsSpendGrant();
2619
+ if (mediaEnabled() && canSpend) makeMediaTools()(pi);
2620
+ makeComposeTools()(pi);
2621
+ registerMediaModelCommands(pi);
2622
+ }
2623
+ __name(privateerMedia, "privateerMedia");
2624
+ export {
2625
+ privateerMedia as default
2626
+ };