@fleox/agentphoto 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/LICENSE +143 -0
  2. package/README.md +229 -2
  3. package/changelog.json +17 -0
  4. package/dist/agent/agentphoto.mjs +3307 -0
  5. package/dist/agent/chunks/assets-CDQo3VqD.mjs +151 -0
  6. package/dist/agent/chunks/catalog-DIZ5dnH5.mjs +953 -0
  7. package/dist/agent/chunks/context-DoLoLF9f.mjs +75 -0
  8. package/dist/agent/chunks/doc-BjY_j4Su.mjs +773 -0
  9. package/dist/agent/chunks/export-CLmpFART.mjs +140 -0
  10. package/dist/agent/chunks/ids-DAmiNwd9.mjs +28 -0
  11. package/dist/agent/chunks/imageInfo-QxAfu8R6.mjs +173 -0
  12. package/dist/agent/chunks/jsonPath-B7vAPXsi.mjs +155 -0
  13. package/dist/agent/chunks/library-C_EXiphj.mjs +16 -0
  14. package/dist/agent/chunks/models-C4i_hicr.mjs +387 -0
  15. package/dist/agent/chunks/output-3F12IR9O.mjs +130 -0
  16. package/dist/agent/chunks/package-DSmAxrla.mjs +71 -0
  17. package/dist/agent/chunks/project-CUykGysG.mjs +198 -0
  18. package/dist/agent/chunks/rolldown-runtime-CMQPkI6i.mjs +18 -0
  19. package/dist/agent/chunks/server-I0trf5tM.mjs +241 -0
  20. package/dist/agent/chunks/templates--YGpGuHh.mjs +40 -0
  21. package/dist/agent/chunks/tools-Dnh8g6F9.mjs +1354 -0
  22. package/dist/agent/chunks/tree-DO7N0UDV.mjs +127 -0
  23. package/dist/agent/chunks/types-DOK7tAAu.mjs +30 -0
  24. package/dist/agent/chunks/validate-CXPFB-i6.mjs +936 -0
  25. package/dist/engine/agentphoto-engine.js +2777 -0
  26. package/dist/engine/chunks/transformers.web-D5Vsg6-A.js +18494 -0
  27. package/dist/engine/ort/ort-wasm-simd-threaded.asyncify.mjs +124 -0
  28. package/dist/engine/ort/ort-wasm-simd-threaded.asyncify.wasm +0 -0
  29. package/dist/studio/assets/index-Be8JnaFy.js +28 -0
  30. package/dist/studio/assets/index-DwPms2S5.css +1 -0
  31. package/dist/studio/assets/transformers.web-DgnCIB_X.js +38 -0
  32. package/dist/studio/index.html +15 -0
  33. package/dist/studio/library/LICENSES.md +57 -0
  34. package/dist/studio/library/fonts/OFL.txt +90 -0
  35. package/dist/studio/library/fonts/anton/anton-latin-400-normal.woff2 +0 -0
  36. package/dist/studio/library/fonts/anton/anton-latin-ext-400-normal.woff2 +0 -0
  37. package/dist/studio/library/fonts/archivo-black/archivo-black-latin-400-normal.woff2 +0 -0
  38. package/dist/studio/library/fonts/archivo-black/archivo-black-latin-ext-400-normal.woff2 +0 -0
  39. package/dist/studio/library/fonts/bebas-neue/bebas-neue-latin-400-normal.woff2 +0 -0
  40. package/dist/studio/library/fonts/bebas-neue/bebas-neue-latin-ext-400-normal.woff2 +0 -0
  41. package/dist/studio/library/fonts/caveat/caveat-latin-400-normal.woff2 +0 -0
  42. package/dist/studio/library/fonts/caveat/caveat-latin-700-normal.woff2 +0 -0
  43. package/dist/studio/library/fonts/caveat/caveat-latin-ext-400-normal.woff2 +0 -0
  44. package/dist/studio/library/fonts/caveat/caveat-latin-ext-700-normal.woff2 +0 -0
  45. package/dist/studio/library/fonts/dm-serif/dm-serif-display-latin-400-normal.woff2 +0 -0
  46. package/dist/studio/library/fonts/dm-serif/dm-serif-display-latin-ext-400-normal.woff2 +0 -0
  47. package/dist/studio/library/fonts/inter/inter-latin-400-normal.woff2 +0 -0
  48. package/dist/studio/library/fonts/inter/inter-latin-600-normal.woff2 +0 -0
  49. package/dist/studio/library/fonts/inter/inter-latin-700-normal.woff2 +0 -0
  50. package/dist/studio/library/fonts/inter/inter-latin-800-normal.woff2 +0 -0
  51. package/dist/studio/library/fonts/inter/inter-latin-ext-400-normal.woff2 +0 -0
  52. package/dist/studio/library/fonts/inter/inter-latin-ext-600-normal.woff2 +0 -0
  53. package/dist/studio/library/fonts/inter/inter-latin-ext-700-normal.woff2 +0 -0
  54. package/dist/studio/library/fonts/inter/inter-latin-ext-800-normal.woff2 +0 -0
  55. package/dist/studio/library/fonts/jetbrains-mono/jetbrains-mono-latin-400-normal.woff2 +0 -0
  56. package/dist/studio/library/fonts/jetbrains-mono/jetbrains-mono-latin-700-normal.woff2 +0 -0
  57. package/dist/studio/library/fonts/jetbrains-mono/jetbrains-mono-latin-ext-400-normal.woff2 +0 -0
  58. package/dist/studio/library/fonts/jetbrains-mono/jetbrains-mono-latin-ext-700-normal.woff2 +0 -0
  59. package/dist/studio/library/fonts/lobster/lobster-latin-400-normal.woff2 +0 -0
  60. package/dist/studio/library/fonts/lobster/lobster-latin-ext-400-normal.woff2 +0 -0
  61. package/dist/studio/library/fonts/montserrat/montserrat-latin-400-normal.woff2 +0 -0
  62. package/dist/studio/library/fonts/montserrat/montserrat-latin-700-normal.woff2 +0 -0
  63. package/dist/studio/library/fonts/montserrat/montserrat-latin-800-normal.woff2 +0 -0
  64. package/dist/studio/library/fonts/montserrat/montserrat-latin-ext-400-normal.woff2 +0 -0
  65. package/dist/studio/library/fonts/montserrat/montserrat-latin-ext-700-normal.woff2 +0 -0
  66. package/dist/studio/library/fonts/montserrat/montserrat-latin-ext-800-normal.woff2 +0 -0
  67. package/dist/studio/library/fonts/oswald/oswald-latin-400-normal.woff2 +0 -0
  68. package/dist/studio/library/fonts/oswald/oswald-latin-600-normal.woff2 +0 -0
  69. package/dist/studio/library/fonts/oswald/oswald-latin-ext-400-normal.woff2 +0 -0
  70. package/dist/studio/library/fonts/oswald/oswald-latin-ext-600-normal.woff2 +0 -0
  71. package/dist/studio/library/fonts/pacifico/pacifico-latin-400-normal.woff2 +0 -0
  72. package/dist/studio/library/fonts/pacifico/pacifico-latin-ext-400-normal.woff2 +0 -0
  73. package/dist/studio/library/fonts/playfair/playfair-display-latin-400-italic.woff2 +0 -0
  74. package/dist/studio/library/fonts/playfair/playfair-display-latin-400-normal.woff2 +0 -0
  75. package/dist/studio/library/fonts/playfair/playfair-display-latin-700-normal.woff2 +0 -0
  76. package/dist/studio/library/fonts/playfair/playfair-display-latin-ext-400-italic.woff2 +0 -0
  77. package/dist/studio/library/fonts/playfair/playfair-display-latin-ext-400-normal.woff2 +0 -0
  78. package/dist/studio/library/fonts/playfair/playfair-display-latin-ext-700-normal.woff2 +0 -0
  79. package/dist/studio/library/fonts/poppins/poppins-latin-400-normal.woff2 +0 -0
  80. package/dist/studio/library/fonts/poppins/poppins-latin-600-normal.woff2 +0 -0
  81. package/dist/studio/library/fonts/poppins/poppins-latin-700-normal.woff2 +0 -0
  82. package/dist/studio/library/fonts/poppins/poppins-latin-ext-400-normal.woff2 +0 -0
  83. package/dist/studio/library/fonts/poppins/poppins-latin-ext-600-normal.woff2 +0 -0
  84. package/dist/studio/library/fonts/poppins/poppins-latin-ext-700-normal.woff2 +0 -0
  85. package/dist/studio/library/fonts/roboto-slab/LICENSE.txt +202 -0
  86. package/dist/studio/library/fonts/roboto-slab/roboto-slab-latin-400-normal.woff2 +0 -0
  87. package/dist/studio/library/fonts/roboto-slab/roboto-slab-latin-700-normal.woff2 +0 -0
  88. package/dist/studio/library/fonts/roboto-slab/roboto-slab-latin-ext-400-normal.woff2 +0 -0
  89. package/dist/studio/library/fonts/roboto-slab/roboto-slab-latin-ext-700-normal.woff2 +0 -0
  90. package/dist/studio/library/fonts/space-grotesk/space-grotesk-latin-500-normal.woff2 +0 -0
  91. package/dist/studio/library/fonts/space-grotesk/space-grotesk-latin-700-normal.woff2 +0 -0
  92. package/dist/studio/library/fonts/space-grotesk/space-grotesk-latin-ext-500-normal.woff2 +0 -0
  93. package/dist/studio/library/fonts/space-grotesk/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  94. package/dist/studio/library/images/city.jpg +0 -0
  95. package/dist/studio/library/images/food.jpg +0 -0
  96. package/dist/studio/library/images/landscape.jpg +0 -0
  97. package/dist/studio/library/images/pet.jpg +0 -0
  98. package/dist/studio/library/images/portrait.jpg +0 -0
  99. package/dist/studio/library/images/product.jpg +0 -0
  100. package/dist/studio/library/index.json +752 -0
  101. package/dist/studio/templates/avatar-pro/assets/masks/photo-cutout.png +0 -0
  102. package/dist/studio/templates/avatar-pro/photo.json +13 -0
  103. package/dist/studio/templates/avatar-pro/preview.jpg +0 -0
  104. package/dist/studio/templates/avatar-pro/template.json +1 -0
  105. package/dist/studio/templates/index.json +1 -0
  106. package/dist/studio/templates/og-article/photo.json +13 -0
  107. package/dist/studio/templates/og-article/preview.jpg +0 -0
  108. package/dist/studio/templates/og-article/template.json +1 -0
  109. package/dist/studio/templates/polaroid/photo.json +13 -0
  110. package/dist/studio/templates/polaroid/preview.jpg +0 -0
  111. package/dist/studio/templates/polaroid/template.json +1 -0
  112. package/dist/studio/templates/product-white/assets/masks/photo-cutout.png +0 -0
  113. package/dist/studio/templates/product-white/photo.json +72 -0
  114. package/dist/studio/templates/product-white/preview.jpg +0 -0
  115. package/dist/studio/templates/product-white/template.json +1 -0
  116. package/dist/studio/templates/sale-banner/photo.json +125 -0
  117. package/dist/studio/templates/sale-banner/preview.jpg +0 -0
  118. package/dist/studio/templates/sale-banner/template.json +1 -0
  119. package/dist/studio/templates/social-quote/photo.json +13 -0
  120. package/dist/studio/templates/social-quote/preview.jpg +0 -0
  121. package/dist/studio/templates/social-quote/template.json +1 -0
  122. package/dist/studio/templates/story-promo/photo.json +13 -0
  123. package/dist/studio/templates/story-promo/preview.jpg +0 -0
  124. package/dist/studio/templates/story-promo/template.json +1 -0
  125. package/dist/studio/templates/youtube-thumbnail/photo.json +12 -0
  126. package/dist/studio/templates/youtube-thumbnail/preview.jpg +0 -0
  127. package/dist/studio/templates/youtube-thumbnail/template.json +1 -0
  128. package/library/LICENSES.md +57 -0
  129. package/library/fonts/OFL.txt +90 -0
  130. package/library/fonts/anton/anton-latin-400-normal.woff2 +0 -0
  131. package/library/fonts/anton/anton-latin-ext-400-normal.woff2 +0 -0
  132. package/library/fonts/archivo-black/archivo-black-latin-400-normal.woff2 +0 -0
  133. package/library/fonts/archivo-black/archivo-black-latin-ext-400-normal.woff2 +0 -0
  134. package/library/fonts/bebas-neue/bebas-neue-latin-400-normal.woff2 +0 -0
  135. package/library/fonts/bebas-neue/bebas-neue-latin-ext-400-normal.woff2 +0 -0
  136. package/library/fonts/caveat/caveat-latin-400-normal.woff2 +0 -0
  137. package/library/fonts/caveat/caveat-latin-700-normal.woff2 +0 -0
  138. package/library/fonts/caveat/caveat-latin-ext-400-normal.woff2 +0 -0
  139. package/library/fonts/caveat/caveat-latin-ext-700-normal.woff2 +0 -0
  140. package/library/fonts/dm-serif/dm-serif-display-latin-400-normal.woff2 +0 -0
  141. package/library/fonts/dm-serif/dm-serif-display-latin-ext-400-normal.woff2 +0 -0
  142. package/library/fonts/inter/inter-latin-400-normal.woff2 +0 -0
  143. package/library/fonts/inter/inter-latin-600-normal.woff2 +0 -0
  144. package/library/fonts/inter/inter-latin-700-normal.woff2 +0 -0
  145. package/library/fonts/inter/inter-latin-800-normal.woff2 +0 -0
  146. package/library/fonts/inter/inter-latin-ext-400-normal.woff2 +0 -0
  147. package/library/fonts/inter/inter-latin-ext-600-normal.woff2 +0 -0
  148. package/library/fonts/inter/inter-latin-ext-700-normal.woff2 +0 -0
  149. package/library/fonts/inter/inter-latin-ext-800-normal.woff2 +0 -0
  150. package/library/fonts/jetbrains-mono/jetbrains-mono-latin-400-normal.woff2 +0 -0
  151. package/library/fonts/jetbrains-mono/jetbrains-mono-latin-700-normal.woff2 +0 -0
  152. package/library/fonts/jetbrains-mono/jetbrains-mono-latin-ext-400-normal.woff2 +0 -0
  153. package/library/fonts/jetbrains-mono/jetbrains-mono-latin-ext-700-normal.woff2 +0 -0
  154. package/library/fonts/lobster/lobster-latin-400-normal.woff2 +0 -0
  155. package/library/fonts/lobster/lobster-latin-ext-400-normal.woff2 +0 -0
  156. package/library/fonts/montserrat/montserrat-latin-400-normal.woff2 +0 -0
  157. package/library/fonts/montserrat/montserrat-latin-700-normal.woff2 +0 -0
  158. package/library/fonts/montserrat/montserrat-latin-800-normal.woff2 +0 -0
  159. package/library/fonts/montserrat/montserrat-latin-ext-400-normal.woff2 +0 -0
  160. package/library/fonts/montserrat/montserrat-latin-ext-700-normal.woff2 +0 -0
  161. package/library/fonts/montserrat/montserrat-latin-ext-800-normal.woff2 +0 -0
  162. package/library/fonts/oswald/oswald-latin-400-normal.woff2 +0 -0
  163. package/library/fonts/oswald/oswald-latin-600-normal.woff2 +0 -0
  164. package/library/fonts/oswald/oswald-latin-ext-400-normal.woff2 +0 -0
  165. package/library/fonts/oswald/oswald-latin-ext-600-normal.woff2 +0 -0
  166. package/library/fonts/pacifico/pacifico-latin-400-normal.woff2 +0 -0
  167. package/library/fonts/pacifico/pacifico-latin-ext-400-normal.woff2 +0 -0
  168. package/library/fonts/playfair/playfair-display-latin-400-italic.woff2 +0 -0
  169. package/library/fonts/playfair/playfair-display-latin-400-normal.woff2 +0 -0
  170. package/library/fonts/playfair/playfair-display-latin-700-normal.woff2 +0 -0
  171. package/library/fonts/playfair/playfair-display-latin-ext-400-italic.woff2 +0 -0
  172. package/library/fonts/playfair/playfair-display-latin-ext-400-normal.woff2 +0 -0
  173. package/library/fonts/playfair/playfair-display-latin-ext-700-normal.woff2 +0 -0
  174. package/library/fonts/poppins/poppins-latin-400-normal.woff2 +0 -0
  175. package/library/fonts/poppins/poppins-latin-600-normal.woff2 +0 -0
  176. package/library/fonts/poppins/poppins-latin-700-normal.woff2 +0 -0
  177. package/library/fonts/poppins/poppins-latin-ext-400-normal.woff2 +0 -0
  178. package/library/fonts/poppins/poppins-latin-ext-600-normal.woff2 +0 -0
  179. package/library/fonts/poppins/poppins-latin-ext-700-normal.woff2 +0 -0
  180. package/library/fonts/roboto-slab/LICENSE.txt +202 -0
  181. package/library/fonts/roboto-slab/roboto-slab-latin-400-normal.woff2 +0 -0
  182. package/library/fonts/roboto-slab/roboto-slab-latin-700-normal.woff2 +0 -0
  183. package/library/fonts/roboto-slab/roboto-slab-latin-ext-400-normal.woff2 +0 -0
  184. package/library/fonts/roboto-slab/roboto-slab-latin-ext-700-normal.woff2 +0 -0
  185. package/library/fonts/space-grotesk/space-grotesk-latin-500-normal.woff2 +0 -0
  186. package/library/fonts/space-grotesk/space-grotesk-latin-700-normal.woff2 +0 -0
  187. package/library/fonts/space-grotesk/space-grotesk-latin-ext-500-normal.woff2 +0 -0
  188. package/library/fonts/space-grotesk/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  189. package/library/images/city.jpg +0 -0
  190. package/library/images/food.jpg +0 -0
  191. package/library/images/landscape.jpg +0 -0
  192. package/library/images/pet.jpg +0 -0
  193. package/library/images/portrait.jpg +0 -0
  194. package/library/images/product.jpg +0 -0
  195. package/library/index.json +752 -0
  196. package/package.json +65 -4
  197. package/plugin/.claude-plugin/plugin.json +19 -0
  198. package/plugin/skills/agentphoto-cutout/SKILL.md +132 -0
  199. package/plugin/skills/agentphoto-design/SKILL.md +104 -0
  200. package/plugin/skills/agentphoto-design/references/layouts.md +60 -0
  201. package/plugin/skills/agentphoto-publish/SKILL.md +79 -0
  202. package/plugin/skills/agentphoto-retouch/SKILL.md +144 -0
  203. package/plugin/skills/agentphoto-retouch/references/filters.md +51 -0
  204. package/plugin/skills/agentphoto-retouch/references/patch-ops.md +66 -0
  205. package/plugin/skills/agentphoto-retouch/references/recipes.md +129 -0
  206. package/templates/avatar-pro/assets/masks/photo-cutout.png +0 -0
  207. package/templates/avatar-pro/photo.json +13 -0
  208. package/templates/avatar-pro/preview.jpg +0 -0
  209. package/templates/avatar-pro/template.json +1 -0
  210. package/templates/og-article/photo.json +13 -0
  211. package/templates/og-article/preview.jpg +0 -0
  212. package/templates/og-article/template.json +1 -0
  213. package/templates/polaroid/photo.json +13 -0
  214. package/templates/polaroid/preview.jpg +0 -0
  215. package/templates/polaroid/template.json +1 -0
  216. package/templates/product-white/assets/masks/photo-cutout.png +0 -0
  217. package/templates/product-white/photo.json +72 -0
  218. package/templates/product-white/preview.jpg +0 -0
  219. package/templates/product-white/template.json +1 -0
  220. package/templates/sale-banner/photo.json +125 -0
  221. package/templates/sale-banner/preview.jpg +0 -0
  222. package/templates/sale-banner/template.json +1 -0
  223. package/templates/social-quote/photo.json +13 -0
  224. package/templates/social-quote/preview.jpg +0 -0
  225. package/templates/social-quote/template.json +1 -0
  226. package/templates/story-promo/photo.json +13 -0
  227. package/templates/story-promo/preview.jpg +0 -0
  228. package/templates/story-promo/template.json +1 -0
  229. package/templates/youtube-thumbnail/photo.json +12 -0
  230. package/templates/youtube-thumbnail/preview.jpg +0 -0
  231. package/templates/youtube-thumbnail/template.json +1 -0
@@ -0,0 +1,3307 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __apRequire } from "node:module";
3
+ import { fileURLToPath as __apPath } from "node:url";
4
+ import { dirname as __apDirname, basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ __apRequire(import.meta.url);
6
+ const __filename = __apPath(import.meta.url);
7
+ __apDirname(__filename);
8
+ import { t as __exportAll } from "./chunks/rolldown-runtime-CMQPkI6i.mjs";
9
+ import { a as routeConsoleToStderr, i as printResult, n as createIo, o as toCliError, r as printError, t as CliError } from "./chunks/output-3F12IR9O.mjs";
10
+ import { _ as packageRoot, a as mimeOf, b as templatesDir, c as sendJson, d as distRoot, f as engineBuilt, g as modelsDir, h as libraryDir, l as sendText, m as isBundled, n as modelCacheDir, o as readBody, p as engineDir, r as modelsRoute, s as resolveUnder, t as listCachedModels, u as startLocalServer, v as readVersionInfo, y as studioDir } from "./chunks/models-C4i_hicr.mjs";
11
+ import { d as normalizePath, u as FsError } from "./chunks/context-DoLoLF9f.mjs";
12
+ import { o as MODELS, t as CATALOG, u as modelDef } from "./chunks/catalog-DIZ5dnH5.mjs";
13
+ import { r as parseTemplateInfo } from "./chunks/templates--YGpGuHh.mjs";
14
+ import { s as referencedFiles } from "./chunks/tree-DO7N0UDV.mjs";
15
+ import { parseArgs } from "node:util";
16
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch } from "node:fs";
17
+ import { homedir, tmpdir } from "node:os";
18
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
19
+ import { execFile, spawn } from "node:child_process";
20
+ // agent/nodeFs.ts
21
+ var SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules"]);
22
+ var NodeFs = class {
23
+ root;
24
+ constructor(root) {
25
+ this.root = resolve(root);
26
+ }
27
+ resolve(path) {
28
+ const p = normalizePath(path);
29
+ const abs = resolve(this.root, p);
30
+ if (abs !== this.root && !abs.startsWith(this.root + sep)) throw new FsError("invalidPath", `Invalid project path: ${path}`);
31
+ let probe = abs;
32
+ while (probe !== this.root && !existsSync(probe)) probe = dirname(probe);
33
+ if (probe !== this.root && existsSync(this.root)) {
34
+ const realRoot = realpathSync(this.root);
35
+ const real = realpathSync(probe);
36
+ if (real !== realRoot && !real.startsWith(realRoot + sep)) throw new FsError("invalidPath", `Project path leaves the project through a symlink: ${path}`);
37
+ }
38
+ return abs;
39
+ }
40
+ async readText(path) {
41
+ return new TextDecoder().decode(await this.readBytes(path));
42
+ }
43
+ async readBytes(path) {
44
+ const abs = this.resolve(path);
45
+ try {
46
+ return new Uint8Array(await readFile(abs));
47
+ } catch (e) {
48
+ throw toFsError(e, path);
49
+ }
50
+ }
51
+ async writeText(path, text) {
52
+ await this.writeBytes(path, new TextEncoder().encode(text));
53
+ }
54
+ async writeBytes(path, bytes) {
55
+ const abs = this.resolve(path);
56
+ try {
57
+ await mkdir(dirname(abs), { recursive: true });
58
+ await writeFile(abs, bytes);
59
+ } catch (e) {
60
+ throw toFsError(e, path);
61
+ }
62
+ }
63
+ async exists(path) {
64
+ try {
65
+ return (await stat(this.resolve(path))).isFile();
66
+ } catch (e) {
67
+ if (e instanceof FsError) throw e;
68
+ return false;
69
+ }
70
+ }
71
+ async list(prefix = "") {
72
+ const p = prefix ? normalizePath(prefix).replace(/\/+$/, "") : "";
73
+ const start = p ? this.resolve(p) : this.root;
74
+ const out = [];
75
+ const walk = async (dir) => {
76
+ let entries;
77
+ try {
78
+ entries = await readdir(dir, { withFileTypes: true });
79
+ } catch {
80
+ return;
81
+ }
82
+ for (const e of entries) {
83
+ const abs = join(dir, e.name);
84
+ if (e.isDirectory()) {
85
+ if (!SKIP_DIRS.has(e.name)) await walk(abs);
86
+ } else if (e.isFile()) out.push(relative(this.root, abs).split(sep).join("/"));
87
+ }
88
+ };
89
+ await walk(start);
90
+ return out.sort();
91
+ }
92
+ async remove(path) {
93
+ try {
94
+ await rm(this.resolve(path), { force: true });
95
+ } catch (e) {
96
+ throw toFsError(e, path);
97
+ }
98
+ }
99
+ async size(path) {
100
+ try {
101
+ const s = await stat(this.resolve(path));
102
+ if (!s.isFile()) throw new FsError("notFound", `File not found: ${path}`);
103
+ return s.size;
104
+ } catch (e) {
105
+ throw toFsError(e, path);
106
+ }
107
+ }
108
+ };
109
+ function toFsError(e, path) {
110
+ if (e instanceof FsError) return e;
111
+ const code = e.code;
112
+ if (code === "ENOENT" || code === "EISDIR" || code === "ENOTDIR") return new FsError("notFound", `File not found: ${path}`);
113
+ return new FsError("io", `${path}: ${e.message}`);
114
+ }
115
+ // agent/commands/util.ts
116
+ function usage(message, hint) {
117
+ throw new CliError("usage", message, hint, 2);
118
+ }
119
+ function strOpt(options, name) {
120
+ const v = options[name];
121
+ if (Array.isArray(v)) return v.at(-1);
122
+ return typeof v === "string" ? v : void 0;
123
+ }
124
+ function multiOpt(options, name) {
125
+ const v = options[name];
126
+ if (v === void 0 || v === false) return [];
127
+ return Array.isArray(v) ? v : [String(v)];
128
+ }
129
+ function numOpt(options, name) {
130
+ const v = strOpt(options, name);
131
+ if (v === void 0) return void 0;
132
+ const n = Number(v);
133
+ if (!Number.isFinite(n)) usage(`--${name} must be a number, got "${v}".`);
134
+ return n;
135
+ }
136
+ function boolOpt(options, name) {
137
+ return options[name] === true;
138
+ }
139
+ var stdinText = null;
140
+ function readStdin() {
141
+ if (stdinText === null) stdinText = readFileSync(0, "utf8");
142
+ return stdinText;
143
+ }
144
+ function readTextValue(value, name) {
145
+ if (value === "-") return readStdin();
146
+ if (value.startsWith("@")) {
147
+ const file = value.slice(1);
148
+ if (!existsSync(file)) usage(`--${name}: ${file} does not exist.`);
149
+ return readFileSync(file, "utf8");
150
+ }
151
+ return value;
152
+ }
153
+ function parseJson(text, what, example) {
154
+ try {
155
+ return JSON.parse(text);
156
+ } catch (err) {
157
+ usage(`${what} is not valid JSON: ${err.message}`, `Example: ${example}`);
158
+ }
159
+ }
160
+ function jsonOpt(options, name, example = `--${name} '{"id":"title"}' or --${name} @file.json`) {
161
+ const v = strOpt(options, name);
162
+ if (v === void 0) return void 0;
163
+ return parseJson(readTextValue(v, name), `--${name}`, example);
164
+ }
165
+ function jsonObjectOpt(options, name) {
166
+ const v = jsonOpt(options, name);
167
+ if (v === void 0) return void 0;
168
+ if (!v || typeof v !== "object" || Array.isArray(v)) usage(`--${name} must be a JSON object.`);
169
+ return v;
170
+ }
171
+ function jsonInput(options, positionals, what, example) {
172
+ const file = strOpt(options, "file");
173
+ let text;
174
+ if (file !== void 0) {
175
+ if (file === "-") text = readStdin();
176
+ else {
177
+ const f = file.startsWith("@") ? file.slice(1) : file;
178
+ if (!existsSync(f)) usage(`--file: ${f} does not exist.`);
179
+ text = readFileSync(f, "utf8");
180
+ }
181
+ } else if (positionals.length) text = readTextValue(positionals[0], "file");
182
+ if (text === void 0) usage(`Missing ${what}.`, `Pass --file <path>, --file - (stdin), @file or inline JSON. ${example}`);
183
+ return parseJson(text, what, example);
184
+ }
185
+ function parseScalar(raw) {
186
+ const t = raw.trim();
187
+ if (t === "") return "";
188
+ try {
189
+ const v = JSON.parse(t);
190
+ if (typeof v === "string") return v;
191
+ if (typeof v === "number" && String(v) !== t) return raw;
192
+ return v;
193
+ } catch {
194
+ return raw;
195
+ }
196
+ }
197
+ var STRING_KEYS = /* @__PURE__ */ new Set([
198
+ "text",
199
+ "name",
200
+ "title",
201
+ "id",
202
+ "font",
203
+ "src",
204
+ "parent"
205
+ ]);
206
+ function setEntries(options) {
207
+ return multiOpt(options, "set").map((pair) => {
208
+ const i = pair.indexOf("=");
209
+ if (i <= 0) usage(`--set expects key=value, got "${pair}".`, "e.g. --set x=40 --set opacity=0.8 --set effects.dropShadow.blur=24 --set color=\"#ff3366\"");
210
+ const key = pair.slice(0, i).trim();
211
+ const raw = pair.slice(i + 1);
212
+ return [key, STRING_KEYS.has(key.split(".").at(-1)) ? raw : parseScalar(raw)];
213
+ });
214
+ }
215
+ function setPairs(options) {
216
+ const out = {};
217
+ for (const [key, value] of setEntries(options)) {
218
+ const keys = key.split(".");
219
+ let node = out;
220
+ for (const k of keys.slice(0, -1)) {
221
+ if (!node[k] || typeof node[k] !== "object" || Array.isArray(node[k])) node[k] = {};
222
+ node = node[k];
223
+ }
224
+ node[keys.at(-1)] = value;
225
+ }
226
+ return out;
227
+ }
228
+ function deepMerge(base, over) {
229
+ const out = { ...base };
230
+ for (const [k, v] of Object.entries(over)) {
231
+ const b = out[k];
232
+ out[k] = v && typeof v === "object" && !Array.isArray(v) && b && typeof b === "object" && !Array.isArray(b) ? deepMerge(b, v) : v;
233
+ }
234
+ return out;
235
+ }
236
+ var PLAN_FOOTER = "Nothing changed. Re-run with --yes to apply.";
237
+ function confirmOrPlan(io, options, plan, human) {
238
+ if (options.yes === true) return true;
239
+ printResult(io, {
240
+ needsConfirmation: true,
241
+ plan
242
+ }, () => `${human()}\n${PLAN_FOOTER}`);
243
+ return false;
244
+ }
245
+ function positional(positionals, index, what, usageLine) {
246
+ const v = positionals[index];
247
+ if (!v) usage(`Missing ${what}.`, `Usage: agentphoto ${usageLine}`);
248
+ return v;
249
+ }
250
+ function table(rows, columns) {
251
+ if (!rows.length) return "(none)";
252
+ const cell = (v) => (v === void 0 || v === null ? "" : typeof v === "object" ? JSON.stringify(v) : String(v)).replace(/\s+/g, " ").slice(0, 70);
253
+ const widths = columns.map((c) => Math.max(c.length, ...rows.map((r) => cell(r[c]).length)));
254
+ const line = (vals) => vals.map((v, i) => v.padEnd(widths[i])).join(" ").trimEnd();
255
+ return [
256
+ line(columns),
257
+ line(widths.map((w) => "-".repeat(w))),
258
+ ...rows.map((r) => line(columns.map((c) => cell(r[c]))))
259
+ ].join("\n");
260
+ }
261
+ var PROJECT_OPTION = {
262
+ name: "project",
263
+ type: "string",
264
+ description: "Project folder (default: the current directory)."
265
+ };
266
+ var YES_OPTION = {
267
+ name: "yes",
268
+ type: "boolean",
269
+ description: "Apply — only after the user confirmed the plan."
270
+ };
271
+ var DRY_RUN_OPTION = {
272
+ name: "dry-run",
273
+ type: "boolean",
274
+ description: "Compute the plan and the issues, write nothing."
275
+ };
276
+ var FILE_OPTION = {
277
+ name: "file",
278
+ type: "string",
279
+ description: "Read the JSON input from this file (`-` = stdin). A positional @file / - / inline JSON works too."
280
+ };
281
+ function projectDir(options) {
282
+ return resolve(strOpt(options, "project") ?? process.cwd());
283
+ }
284
+ function projectFs(options, { mustExist = true } = {}) {
285
+ const dir = projectDir(options);
286
+ if (mustExist && !existsSync(resolve(dir, "photo.json"))) throw new CliError("no-project", `No AgentPhoto project in ${dir} (photo.json not found).`, existsSync(dir) ? "Pass --project <dir>, or create one with `agentphoto new <dir> --image <photo>`." : `The folder does not exist. Create the project with \`agentphoto new ${dir}\`.`);
287
+ return new NodeFs(dir);
288
+ }
289
+ function paintValue(raw) {
290
+ if (raw === void 0) return void 0;
291
+ const t = raw.trim();
292
+ if (t === "null" || t === "none" || t === "transparent") return null;
293
+ if (t.startsWith("{") || t.startsWith("[")) return parseJson(readTextValue(t, "background"), "the paint", "{\"type\":\"linear\",\"angle\":90,\"stops\":[{\"offset\":0,\"color\":\"#000\"},{\"offset\":1,\"color\":\"#fff\"}]}");
294
+ if (t.startsWith("@")) return parseJson(readTextValue(t, "background"), "the paint", "@gradient.json");
295
+ return t;
296
+ }
297
+ async function tool(fs, name, input) {
298
+ const { callTool } = await Promise.resolve().then(() => aiHost_exports);
299
+ return await callTool(fs, name, input);
300
+ }
301
+ function issuesLine(issues) {
302
+ if (!issues?.length) return "No issues.";
303
+ return issues.map((i) => ` ${i.severity === "error" ? "✗" : i.severity === "warning" ? "!" : "·"} ${i.path ? `${i.path}: ` : ""}${i.message}${i.hint ? ` (${i.hint})` : ""}`).join("\n");
304
+ }
305
+ function refused(r) {
306
+ const first = r.issues.filter((i) => i.severity === "error")[0];
307
+ return new CliError("validation", `The change makes the document invalid: ${r.counts.errors} error${r.counts.errors > 1 ? "s" : ""}${first ? ` — ${first.path ? `${first.path}: ` : ""}${first.message.replace(/[.!?]+$/, "")}` : ""}. Nothing was written.`, first?.hint ?? "Fix the listed issues (details.issues: JSON path + message + hint) and retry; `agentphoto catalog <section> <id>` documents the parameters.", 2, {
308
+ issues: r.issues,
309
+ plan: r.plan
310
+ });
311
+ }
312
+ async function runMutation(io, options, fs, name, input, human, opts = {}) {
313
+ const dry = await tool(fs, name, {
314
+ ...input,
315
+ dryRun: true
316
+ });
317
+ if (dry.status === "refused") throw refused(dry);
318
+ if (dry.status === "unchanged") return printResult(io, dry, () => `${human}: no changes.`);
319
+ if (boolOpt(options, "dry-run")) return printResult(io, dry, () => `${human} (dry run): ${dry.plan.summary}\n${issuesLine(dry.issues)}`);
320
+ if ((opts.destructive ?? (dry.plan.layers?.removed.length ?? 0) > 0) && !confirmOrPlan(io, options, {
321
+ ...dry.plan,
322
+ tool: name,
323
+ input,
324
+ issues: dry.issues
325
+ }, () => `${human}: ${dry.plan.summary}`)) return;
326
+ const r = await tool(fs, name, input);
327
+ if (r.status === "refused") throw refused(r);
328
+ printResult(io, r, () => `${human}: ${r.plan.summary}\n${issuesLine(r.issues)}`);
329
+ }
330
+ function absPath(fs, path) {
331
+ return resolve(fs.root, path);
332
+ }
333
+ // agent/commands/assets.ts
334
+ var assetsCommand = {
335
+ name: "assets",
336
+ usage: "assets <list|add|remove|library> [--project <dir>]",
337
+ summary: "Project files (assets/images, masks, edits + manifest with sources and licences): list, add a local image or a URL (optionally as a layer), remove, and browse the built-in library (CC0 sample photos, fonts).",
338
+ subcommands: [
339
+ {
340
+ name: "list",
341
+ usage: "assets list",
342
+ summary: "The project's files with kind, size, source, licence and the layers using them."
343
+ },
344
+ {
345
+ name: "add",
346
+ usage: "assets add (<file> | --url <url>) [--name <file>] [--license <id>] [--author <name>] [--add-layer [--layer-id <id>]]",
347
+ summary: "Copy an image into assets/images/ (a URL is downloaded once). --add-layer also adds it as an image layer fitted inside the canvas.",
348
+ writes: true
349
+ },
350
+ {
351
+ name: "remove",
352
+ usage: "assets remove <path> [--force] [--yes]",
353
+ summary: "Delete a project file (plan + needsConfirmation unless --yes; refused while a layer uses it unless --force).",
354
+ writes: true,
355
+ destructive: true
356
+ },
357
+ {
358
+ name: "library",
359
+ usage: "assets library [--kind image|font] [--query <text>]",
360
+ summary: "Built-in assets: sample photos (use \"library:<id>\" as an image src) and fonts (use the id as a text font)."
361
+ }
362
+ ],
363
+ options: [
364
+ PROJECT_OPTION,
365
+ {
366
+ name: "url",
367
+ type: "string",
368
+ description: "add: http(s) URL of an image."
369
+ },
370
+ {
371
+ name: "name",
372
+ type: "string",
373
+ description: "add: file name to store it as."
374
+ },
375
+ {
376
+ name: "license",
377
+ type: "string",
378
+ description: "add: the image's licence (e.g. CC0-1.0, proprietary)."
379
+ },
380
+ {
381
+ name: "author",
382
+ type: "string",
383
+ description: "add: author / attribution."
384
+ },
385
+ {
386
+ name: "add-layer",
387
+ type: "boolean",
388
+ description: "add: also add it as an image layer."
389
+ },
390
+ {
391
+ name: "layer-id",
392
+ type: "string",
393
+ description: "add --add-layer: id of the new layer."
394
+ },
395
+ {
396
+ name: "force",
397
+ type: "boolean",
398
+ description: "remove: even when layers still use it."
399
+ },
400
+ {
401
+ name: "kind",
402
+ type: "string",
403
+ description: "library: image or font."
404
+ },
405
+ {
406
+ name: "query",
407
+ type: "string",
408
+ description: "library: words to look for."
409
+ },
410
+ YES_OPTION
411
+ ],
412
+ async run({ io, options, positionals }) {
413
+ const [action = "list", ...rest] = positionals;
414
+ if (action === "library") {
415
+ const kind = strOpt(options, "kind");
416
+ if (kind && kind !== "image" && kind !== "font") usage(`Unknown --kind "${kind}".`, "Use image or font.");
417
+ const r = await tool(new NodeFs(projectDir(options)), "library_list", {
418
+ ...kind ? { kind } : {},
419
+ ...strOpt(options, "query") ?? rest[0] ? { query: strOpt(options, "query") ?? rest.join(" ") } : {}
420
+ });
421
+ return printResult(io, r, () => `${table(r.assets, [
422
+ "ref",
423
+ "kind",
424
+ "size",
425
+ "license",
426
+ "description"
427
+ ])}\n${r.total} asset(s)`);
428
+ }
429
+ const fs = projectFs(options);
430
+ if (action === "list") {
431
+ const r = await tool(fs, "assets_list", {});
432
+ return printResult(io, r, () => `${table(r.assets.map((a) => ({
433
+ ...a,
434
+ usedBy: a.usedBy?.join(",")
435
+ })), [
436
+ "path",
437
+ "kind",
438
+ "bytes",
439
+ "source",
440
+ "license",
441
+ "usedBy"
442
+ ])}${r.untracked.length ? `\nUntracked: ${r.untracked.join(", ")}` : ""}\nTotal ${r.totalKb} KB`);
443
+ }
444
+ if (action === "add") {
445
+ const url = strOpt(options, "url");
446
+ const file = rest[0];
447
+ if (!url && !file) usage("assets add needs a file or --url.", "e.g. agentphoto assets add ~/Pictures/logo.png --add-layer");
448
+ const input = {};
449
+ if (url) input.url = url;
450
+ else if (/^https?:\/\//.test(file)) input.url = file;
451
+ else {
452
+ const abs = resolve(file);
453
+ if (!existsSync(abs) || !statSync(abs).isFile()) throw new CliError("notFound", `${file} does not exist.`, "Give the path of a local image file, or --url <http(s) URL>.");
454
+ input.file = abs;
455
+ }
456
+ for (const [opt, key] of [
457
+ ["name", "name"],
458
+ ["license", "license"],
459
+ ["author", "author"],
460
+ ["layer-id", "layerId"]
461
+ ]) if (strOpt(options, opt)) input[key] = strOpt(options, opt);
462
+ if (boolOpt(options, "add-layer")) input.addLayer = true;
463
+ const r = await tool(fs, "assets_add", input);
464
+ return printResult(io, r, () => `Added ${r.asset.path}${r.asset.width ? ` (${r.asset.width}×${r.asset.height})` : ""}${r.layer ? ` as layer "${r.layer}"` : ""}.`);
465
+ }
466
+ if (action === "remove") {
467
+ const path = positional(rest, 0, "asset path", "assets remove <path>");
468
+ const { assets } = await tool(fs, "assets_list", {});
469
+ const entry = assets.find((a) => a.path === path);
470
+ if (!entry && !await fs.exists(path)) throw new CliError("notFound", `No asset "${path}".`, "`agentphoto assets list` lists them.");
471
+ const force = boolOpt(options, "force");
472
+ if (entry?.usedBy?.length && !force) throw new CliError("conflict", `${path} is used by ${entry.usedBy.join(", ")}.`, "Remove or change those layers first, or pass --force (the layers will show a missing file).");
473
+ if (!confirmOrPlan(io, options, {
474
+ remove: [path],
475
+ entry: entry ?? null,
476
+ usedBy: entry?.usedBy ?? []
477
+ }, () => `Delete ${path}${entry ? ` (${entry.kind}${entry.license ? `, ${entry.license}` : ""})` : ""}`)) return;
478
+ const r = await tool(fs, "assets_remove", {
479
+ path,
480
+ ...force ? { force: true } : {}
481
+ });
482
+ return printResult(io, r, () => `Removed ${path}.${r.usedBy.length ? ` Still referenced by: ${r.usedBy.join(", ")} — fix those layers.` : ""}`);
483
+ }
484
+ usage(`Unknown assets action "${action}".`, "Use list, add, remove or library.");
485
+ }
486
+ };
487
+ // agent/host.ts
488
+ function walkFiles(root) {
489
+ const out = [];
490
+ const walk = (dir) => {
491
+ let entries;
492
+ try {
493
+ entries = readdirSync(dir, { withFileTypes: true });
494
+ } catch {
495
+ return;
496
+ }
497
+ for (const e of entries) {
498
+ const abs = join(dir, e.name);
499
+ if (e.isDirectory()) {
500
+ if (e.name !== "node_modules" && e.name !== ".git") walk(abs);
501
+ } else if (e.isFile()) out.push(relative(root, abs).split(sep).join("/"));
502
+ }
503
+ };
504
+ walk(root);
505
+ return out.sort();
506
+ }
507
+ var libraryCache = null;
508
+ function readLibraryIndex() {
509
+ const dir = libraryDir();
510
+ if (libraryCache?.dir === dir) return libraryCache.index;
511
+ const file = join(dir, "index.json");
512
+ let index = { assets: [] };
513
+ if (existsSync(file)) try {
514
+ const raw = JSON.parse(readFileSync(file, "utf8"));
515
+ index = Array.isArray(raw) ? { assets: raw } : {
516
+ ...raw,
517
+ assets: raw.assets ?? []
518
+ };
519
+ } catch {}
520
+ libraryCache = {
521
+ dir,
522
+ index
523
+ };
524
+ return index;
525
+ }
526
+ function libraryProvider() {
527
+ return {
528
+ index: readLibraryIndex(),
529
+ async read(path) {
530
+ const file = resolveUnder(libraryDir(), path);
531
+ if (!file || !existsSync(file)) throw new CliError("notFound", `No library file "${path}".`, "`agentphoto assets library` lists the built-in assets (reference images as \"library:<id>\").");
532
+ return new Uint8Array(readFileSync(file));
533
+ }
534
+ };
535
+ }
536
+ function readTemplatesIndex() {
537
+ const dir = templatesDir();
538
+ if (!existsSync(dir)) return [];
539
+ const out = [];
540
+ for (const name of readdirSync(dir).sort()) {
541
+ const meta = join(dir, name, "template.json");
542
+ if (!existsSync(meta) || !statSync(join(dir, name)).isDirectory()) continue;
543
+ try {
544
+ out.push(parseTemplateInfo(JSON.parse(readFileSync(meta, "utf8")), name));
545
+ } catch {}
546
+ }
547
+ return out;
548
+ }
549
+ function readTemplateFiles(id) {
550
+ const index = readTemplatesIndex();
551
+ if (!index.some((x) => x.id === id)) throw new CliError("notFound", `Unknown template "${id}".`, `\`agentphoto templates list\` lists them${index.length ? ` (${index.map((x) => x.id).join(", ")})` : " (none installed)"}.`);
552
+ const root = join(templatesDir(), folderOf(id));
553
+ const files = {};
554
+ for (const f of walkFiles(root)) if (!/^preview\.(png|jpe?g|webp)$/.test(f)) files[f] = new Uint8Array(readFileSync(join(root, f)));
555
+ return files;
556
+ }
557
+ function templatePreviewFile(id) {
558
+ if (!readTemplatesIndex().some((t) => t.id === id)) return null;
559
+ for (const ext of [
560
+ "jpg",
561
+ "jpeg",
562
+ "png",
563
+ "webp"
564
+ ]) {
565
+ const file = join(templatesDir(), folderOf(id), `preview.${ext}`);
566
+ if (existsSync(file)) return file;
567
+ }
568
+ return null;
569
+ }
570
+ function folderOf(id) {
571
+ const dir = templatesDir();
572
+ for (const name of readdirSync(dir)) {
573
+ const meta = join(dir, name, "template.json");
574
+ if (!existsSync(meta)) continue;
575
+ try {
576
+ if (JSON.parse(readFileSync(meta, "utf8")).id === id) return name;
577
+ } catch {}
578
+ if (name === id) return name;
579
+ }
580
+ return id;
581
+ }
582
+ // agent/commands/catalog.ts
583
+ var SECTIONS = Object.keys(CATALOG);
584
+ var idOf = (e) => typeof e === "string" ? e : e.id ?? "";
585
+ var catalogCommand = {
586
+ name: "catalog",
587
+ usage: "catalog [<section>] [<id>]",
588
+ summary: `What documents can use, with parameters: ${SECTIONS.join(", ")}. No section → an overview; a section → its entries; an id → the full entry (params, types, ranges, defaults).`,
589
+ options: [],
590
+ async run({ io, positionals }) {
591
+ const [section, id] = positionals;
592
+ if (section) {
593
+ if (!SECTIONS.find((s) => s.toLowerCase() === section.toLowerCase() || s.toLowerCase() === `${section.toLowerCase()}s`)) usage(`Unknown catalog section "${section}".`, `Sections: ${SECTIONS.join(", ")}.`);
594
+ }
595
+ const r = await tool(new NodeFs(projectDir({})), "catalog_get", {
596
+ ...section ? { section: SECTIONS.find((s) => s.toLowerCase() === section.toLowerCase() || s.toLowerCase() === `${section.toLowerCase()}s`) } : {},
597
+ ...id ? { id } : {}
598
+ });
599
+ if (!section) return printResult(io, r, () => Object.entries(r.sections).map(([k, v]) => `${k}:\n${v.map((x) => ` ${x}`).join("\n")}`).join("\n\n"));
600
+ if (!id) {
601
+ const entries = r.entries;
602
+ return printResult(io, r, () => table(entries.map((e) => ({
603
+ id: idOf(e),
604
+ description: typeof e === "string" ? "" : e.description
605
+ })), ["id", "description"]));
606
+ }
607
+ return printResult(io, r, () => JSON.stringify(r.entry, null, 2));
608
+ }
609
+ };
610
+ var templatesCommand = {
611
+ name: "templates",
612
+ usage: "templates <list|show> [<id>] [--category <c>] [--query <text>]",
613
+ summary: "Starter templates (`agentphoto new <dir> --template <id> [--image <photo>]`): list them, or show one (metadata, files and its document summary).",
614
+ subcommands: [{
615
+ name: "list",
616
+ usage: "templates list [--category <c>] [--query <text>]",
617
+ summary: "Templates with id, category, size, slot (the layer that receives your photo) and description."
618
+ }, {
619
+ name: "show",
620
+ usage: "templates show <id>",
621
+ summary: "A template's metadata, files and document summary."
622
+ }],
623
+ options: [{
624
+ name: "category",
625
+ type: "string",
626
+ description: "list: social, ad, thumbnail, product, portrait, print, web…"
627
+ }, {
628
+ name: "query",
629
+ type: "string",
630
+ description: "list: words to look for."
631
+ }],
632
+ async run({ io, options, positionals }) {
633
+ const [action = "list"] = positionals;
634
+ const fs = new NodeFs(projectDir({}));
635
+ if (action === "list") {
636
+ const r = await tool(fs, "templates_list", {
637
+ ...typeof options.category === "string" ? { category: options.category } : {},
638
+ ...typeof options.query === "string" ? { query: options.query } : {}
639
+ });
640
+ return printResult(io, r, () => table(r.templates.map((t) => ({
641
+ ...t,
642
+ size: `${t.width}×${t.height}`
643
+ })), [
644
+ "id",
645
+ "category",
646
+ "size",
647
+ "slot",
648
+ "title"
649
+ ]));
650
+ }
651
+ if (action === "show") {
652
+ const id = positional(positionals, 1, "template id", "templates show <id>");
653
+ const meta = readTemplatesIndex().find((t) => t.id === id);
654
+ const files = readTemplateFiles(id);
655
+ const raw = files["photo.json"];
656
+ if (!meta || !raw) throw new CliError("notFound", `Template "${id}" has no photo.json.`, "`agentphoto templates list` lists the templates.");
657
+ let summary = null;
658
+ try {
659
+ const { summarizeDoc } = await import("./chunks/doc-BjY_j4Su.mjs").then((n) => n.r);
660
+ const { normalizeDoc } = await import("./chunks/validate-CXPFB-i6.mjs").then((n) => n.a);
661
+ summary = summarizeDoc(normalizeDoc(JSON.parse(new TextDecoder().decode(raw))));
662
+ } catch {
663
+ summary = null;
664
+ }
665
+ return printResult(io, {
666
+ template: meta,
667
+ files: Object.keys(files),
668
+ summary
669
+ }, () => `${meta.title} (${id}, ${meta.width}×${meta.height}${meta.slot ? `, photo slot "${meta.slot}"` : ""})\n${meta.description}\nFiles: ${Object.keys(files).join(", ")}`);
670
+ }
671
+ usage(`Unknown templates action "${action}".`, "Use list or show.");
672
+ }
673
+ };
674
+ // agent/commands/doc.ts
675
+ var docCommand = {
676
+ name: "doc",
677
+ usage: "doc <get|summary|apply|patch|validate> [--project <dir>]",
678
+ summary: "Read, replace, patch and validate photo.json (the PhotoDoc). apply / patch are validated (nothing written on errors); removing layers needs --yes.",
679
+ subcommands: [
680
+ {
681
+ name: "get",
682
+ usage: "doc get [--path <json.path>]",
683
+ summary: "The full document, or the value at a path (\"canvas\", \"layers#title.size\")."
684
+ },
685
+ {
686
+ name: "summary",
687
+ usage: "doc summary",
688
+ summary: "Compact outline: canvas, layers top → bottom (id, type, detail, box, opacity, blend, mask, filters, effects), counts, sources."
689
+ },
690
+ {
691
+ name: "apply",
692
+ usage: "doc apply --file <photo.json|-> [--dry-run] [--yes]",
693
+ summary: "Replace the whole document (validated). Prints the plan + needsConfirmation when it removes layers, unless --yes.",
694
+ writes: true,
695
+ destructive: true
696
+ },
697
+ {
698
+ name: "patch",
699
+ usage: "doc patch --file <ops.json|-> [--dry-run] [--yes]",
700
+ summary: "Apply patch ops atomically ([{ \"op\": \"set\", \"path\": \"layers#title.size\", \"value\": 96 }, { \"op\": \"addFilter\", \"id\": \"photo\", \"filter\": {…} }, …] — `agentphoto tools list` documents doc_patch). Removing layers needs --yes.",
701
+ writes: true
702
+ },
703
+ {
704
+ name: "validate",
705
+ usage: "doc validate [--file <photo.json|->]",
706
+ summary: "Validate the project's document (or a candidate file): issues with JSON paths, messages and hints. Exit 2 on errors."
707
+ }
708
+ ],
709
+ options: [
710
+ PROJECT_OPTION,
711
+ FILE_OPTION,
712
+ {
713
+ name: "path",
714
+ type: "string",
715
+ description: "get: a JSON path into the document."
716
+ },
717
+ DRY_RUN_OPTION,
718
+ YES_OPTION
719
+ ],
720
+ async run({ io, options, positionals }) {
721
+ const [action = "summary", ...rest] = positionals;
722
+ if (action === "validate") {
723
+ const candidate = strOpt(options, "file") !== void 0 || rest.length ? jsonInput(options, rest, "the document", "--file photo.json") : void 0;
724
+ const r = await tool(candidate ? projectFs(options, { mustExist: false }) : projectFs(options), "doc_validate", candidate ? { doc: candidate } : {});
725
+ printResult(io, r, () => (r.valid ? "Valid.\n" : `${r.counts.errors} error(s):\n`) + issuesLine(r.issues));
726
+ return r.valid ? 0 : 2;
727
+ }
728
+ const fs = projectFs(options);
729
+ if (action === "get") {
730
+ const doc = await tool(fs, "doc_get", {});
731
+ const path = strOpt(options, "path");
732
+ if (!path) return printResult(io, doc, () => JSON.stringify(doc, null, 2));
733
+ const { getAt } = await import("./chunks/jsonPath-B7vAPXsi.mjs").then((n) => n.a);
734
+ const value = getAt(doc, path);
735
+ if (value === void 0) throw new CliError("notFound", `Nothing at "${path}".`, "`agentphoto doc summary` lists the layer ids; paths look like canvas.background or layers#title.color.");
736
+ return printResult(io, {
737
+ path,
738
+ value
739
+ }, () => JSON.stringify(value, null, 2));
740
+ }
741
+ if (action === "summary") {
742
+ const summary = await tool(fs, "doc_summary", {});
743
+ return printResult(io, summary, () => JSON.stringify(summary, null, 2));
744
+ }
745
+ if (action === "apply") {
746
+ const doc = jsonInput(options, rest, "the document", "--file photo.json");
747
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) usage("The document must be a JSON object (a PhotoDoc).");
748
+ return runMutation(io, options, fs, "doc_apply", { doc }, "Replace photo.json");
749
+ }
750
+ if (action === "patch") {
751
+ const raw = jsonInput(options, rest, "the patch ops", `--file ops.json with [{"op":"set","path":"canvas.background","value":"#101020"}]`);
752
+ const ops = Array.isArray(raw) ? raw : raw && typeof raw === "object" && Array.isArray(raw.ops) ? raw.ops : [raw];
753
+ if (!ops.length || ops.some((o) => !o || typeof o !== "object" || typeof o.op !== "string")) usage("The patch must be an array of ops with an \"op\" field.", "e.g. [{\"op\":\"set\",\"path\":\"canvas.background\",\"value\":\"#101020\"},{\"op\":\"removeLayer\",\"id\":\"old\"}]");
754
+ return runMutation(io, options, fs, "doc_patch", { ops }, `Patch (${ops.length} op${ops.length > 1 ? "s" : ""})`);
755
+ }
756
+ usage(`Unknown doc action "${action}".`, "Use get, summary, apply, patch or validate.");
757
+ }
758
+ };
759
+ var POSITION_OPTIONS = [
760
+ {
761
+ name: "above",
762
+ type: "string",
763
+ description: "add / move: place it just above this layer id."
764
+ },
765
+ {
766
+ name: "below",
767
+ type: "string",
768
+ description: "add / move: place it just below this layer id."
769
+ },
770
+ {
771
+ name: "parent",
772
+ type: "string",
773
+ description: "add / move: group id to put it in (\"root\" = the top level)."
774
+ },
775
+ {
776
+ name: "index",
777
+ type: "string",
778
+ description: "add / move: position in the parent, 0 = bottom (default: top)."
779
+ }
780
+ ];
781
+ function position(options) {
782
+ const parent = strOpt(options, "parent");
783
+ const index = numOpt(options, "index");
784
+ return {
785
+ ...strOpt(options, "above") ? { above: strOpt(options, "above") } : {},
786
+ ...strOpt(options, "below") ? { below: strOpt(options, "below") } : {},
787
+ ...parent !== void 0 ? { parent: parent === "root" || parent === "null" ? null : parent } : {},
788
+ ...index !== void 0 ? { index } : {}
789
+ };
790
+ }
791
+ function layerDef(options) {
792
+ let def = { ...jsonObjectOpt(options, "layer") ?? {} };
793
+ for (const k of [
794
+ "id",
795
+ "type",
796
+ "text",
797
+ "src",
798
+ "name"
799
+ ]) {
800
+ const v = strOpt(options, k);
801
+ if (v !== void 0) def[k] = v;
802
+ }
803
+ if (def.text !== void 0 && !def.type) def.type = "text";
804
+ if (def.src !== void 0 && !def.type) def.type = "image";
805
+ def = deepMerge(def, setPairs(options));
806
+ return def;
807
+ }
808
+ var layerCommand = {
809
+ name: "layer",
810
+ usage: "layer <list|get|add|update|remove|move> [<id>] [--project <dir>]",
811
+ summary: "List, inspect, add, change, remove and reorder layers (image, text, shape, fill, adjustment, group).",
812
+ subcommands: [
813
+ {
814
+ name: "list",
815
+ usage: "layer list",
816
+ summary: "Every layer top → bottom (flat, with parent / depth): id, type, detail, box, opacity, blend, mask, filters (their index is what filter update / remove use), effects."
817
+ },
818
+ {
819
+ name: "get",
820
+ usage: "layer get <id>",
821
+ summary: "One layer's full definition."
822
+ },
823
+ {
824
+ name: "add",
825
+ usage: "layer add --layer <json|@file> | --id <id> --type text --text \"Hello\" [--set k=v …] [--above|--below <id>] [--parent <group>] [--index <n>]",
826
+ summary: "Add a layer (validated). Default position: top of the stack.",
827
+ writes: true
828
+ },
829
+ {
830
+ name: "update",
831
+ usage: "layer update <id> [--layer <json>] [--set k=v …]",
832
+ summary: "Change fields of a layer (deep merge; --set effects.dropShadow.blur=24 changes only that key; --set mask=null removes a field).",
833
+ writes: true
834
+ },
835
+ {
836
+ name: "remove",
837
+ usage: "layer remove <id> [--yes]",
838
+ summary: "Remove a layer (and its children for a group); its files stay in assets/. Plan + needsConfirmation unless --yes.",
839
+ writes: true,
840
+ destructive: true
841
+ },
842
+ {
843
+ name: "move",
844
+ usage: "layer move <id> (--above <id> | --below <id> | --parent <group> [--index <n>] | --index <n>)",
845
+ summary: "Reorder a layer or move it into a group.",
846
+ writes: true
847
+ }
848
+ ],
849
+ options: [
850
+ PROJECT_OPTION,
851
+ {
852
+ name: "layer",
853
+ type: "string",
854
+ description: "add: the layer as JSON (@file, - = stdin); update: the fields to change."
855
+ },
856
+ {
857
+ name: "set",
858
+ type: "string",
859
+ multiple: true,
860
+ description: "key=value (dotted keys, JSON values), repeated: --set x=40 --set color=\"#ff3366\" --set effects.dropShadow.blur=24."
861
+ },
862
+ {
863
+ name: "id",
864
+ type: "string",
865
+ description: "add: the new layer's id ([a-zA-Z][a-zA-Z0-9_-]*)."
866
+ },
867
+ {
868
+ name: "type",
869
+ type: "string",
870
+ description: "add: image, text, shape, fill, adjustment or group."
871
+ },
872
+ {
873
+ name: "text",
874
+ type: "string",
875
+ description: "add: the text (implies --type text)."
876
+ },
877
+ {
878
+ name: "src",
879
+ type: "string",
880
+ description: "add: image source, \"assets/…\" or \"library:<id>\" (implies --type image)."
881
+ },
882
+ {
883
+ name: "name",
884
+ type: "string",
885
+ description: "add: display name."
886
+ },
887
+ ...POSITION_OPTIONS,
888
+ DRY_RUN_OPTION,
889
+ YES_OPTION
890
+ ],
891
+ async run({ io, options, positionals }) {
892
+ const [action = "list"] = positionals;
893
+ const fs = projectFs(options);
894
+ if (action === "list") {
895
+ const { layers } = await tool(fs, "layer_list", {});
896
+ return printResult(io, { layers }, () => table(layers.map((l) => ({
897
+ ...l,
898
+ id: `${" ".repeat(l.depth)}${l.id}`,
899
+ filters: l.filters?.join(",")
900
+ })), [
901
+ "id",
902
+ "type",
903
+ "detail",
904
+ "box",
905
+ "mask",
906
+ "filters"
907
+ ]));
908
+ }
909
+ if (action === "get") {
910
+ const id = positional(positionals, 1, "layer id", "layer get <id>");
911
+ const doc = await tool(fs, "doc_get", {});
912
+ const { findLayer } = await import("./chunks/tree-DO7N0UDV.mjs").then((n) => n.c);
913
+ const hit = findLayer(doc.layers, id);
914
+ if (!hit) throw new CliError("notFound", `No layer "${id}".`, "`agentphoto layer list` lists the layer ids.");
915
+ return printResult(io, {
916
+ layer: hit.layer,
917
+ parent: hit.parent?.id ?? null,
918
+ index: hit.index,
919
+ depth: hit.depth
920
+ }, () => JSON.stringify(hit.layer, null, 2));
921
+ }
922
+ if (action === "add") {
923
+ const layer = layerDef(options);
924
+ if (!layer.id || !layer.type) usage("layer add needs an id and a type.", "e.g. --id title --text \"Summer sale\" --set x=80 --set y=80 --set size=96, or --layer '{\"id\":\"bg\",\"type\":\"fill\",\"fill\":\"#101820\"}'");
925
+ return runMutation(io, options, fs, "layer_add", {
926
+ layer,
927
+ ...position(options)
928
+ }, `Add ${String(layer.type)} layer "${String(layer.id)}"`);
929
+ }
930
+ if (action === "update") {
931
+ const id = positional(positionals, 1, "layer id", "layer update <id> --set k=v");
932
+ const set = deepMerge(jsonObjectOpt(options, "layer") ?? {}, setPairs(options));
933
+ if (!Object.keys(set).length) usage("Nothing to change.", "Pass --set key=value (repeated) and/or --layer '{…}'.");
934
+ return runMutation(io, options, fs, "layer_update", {
935
+ id,
936
+ set
937
+ }, `Update "${id}"`);
938
+ }
939
+ if (action === "remove") {
940
+ const id = positional(positionals, 1, "layer id", "layer remove <id>");
941
+ return runMutation(io, options, fs, "layer_remove", { id }, `Remove "${id}"`, { destructive: true });
942
+ }
943
+ if (action === "move") {
944
+ const id = positional(positionals, 1, "layer id", "layer move <id> --above <id>");
945
+ const pos = position(options);
946
+ if (!Object.keys(pos).length) usage("layer move needs --above, --below, --parent or --index.");
947
+ return runMutation(io, options, fs, "layer_move", {
948
+ id,
949
+ ...pos
950
+ }, `Move "${id}"`);
951
+ }
952
+ usage(`Unknown layer action "${action}".`, "Use list, get, add, update, remove or move.");
953
+ }
954
+ };
955
+ var filterCommand = {
956
+ name: "filter",
957
+ usage: "filter <add|update|remove> <layer> [<index>] [--project <dir>]",
958
+ summary: "Non-destructive filters on a layer (or on an adjustment layer — it affects everything below): add, change or remove one. `agentphoto catalog filters` lists them with their parameters.",
959
+ subcommands: [
960
+ {
961
+ name: "add",
962
+ usage: "filter add <layer> (--filter <json> | --type <filter> [--set k=v …]) [--index <n>]",
963
+ summary: "Add a filter, e.g. --type exposure --set exposure=0.3, or --filter '{\"type\":\"look\",\"look\":\"film\"}'.",
964
+ writes: true
965
+ },
966
+ {
967
+ name: "update",
968
+ usage: "filter update <layer> <index> (--set k=v … | --filter <json>)",
969
+ summary: "Change parameters of the filter at <index> (layer list shows the order).",
970
+ writes: true
971
+ },
972
+ {
973
+ name: "remove",
974
+ usage: "filter remove <layer> <index>",
975
+ summary: "Remove the filter at <index>.",
976
+ writes: true
977
+ }
978
+ ],
979
+ options: [
980
+ PROJECT_OPTION,
981
+ {
982
+ name: "filter",
983
+ type: "string",
984
+ description: "The filter as JSON ({ type, ...params, amount? }), @file or -."
985
+ },
986
+ {
987
+ name: "type",
988
+ type: "string",
989
+ description: "add: filter type (catalog id)."
990
+ },
991
+ {
992
+ name: "set",
993
+ type: "string",
994
+ multiple: true,
995
+ description: "Filter parameters as key=value (repeated)."
996
+ },
997
+ {
998
+ name: "index",
999
+ type: "string",
1000
+ description: "add: position in the layer's filter list (default: last)."
1001
+ },
1002
+ DRY_RUN_OPTION,
1003
+ YES_OPTION
1004
+ ],
1005
+ async run({ io, options, positionals }) {
1006
+ const [action, layer] = positionals;
1007
+ if (!action) usage("Missing action.", "Use filter add|update|remove <layer>.");
1008
+ const fs = projectFs(options);
1009
+ if (action === "add") {
1010
+ const id = positional(positionals, 1, "layer id", "filter add <layer> --type exposure --set exposure=0.3");
1011
+ const filter = deepMerge({
1012
+ ...jsonObjectOpt(options, "filter") ?? {},
1013
+ ...strOpt(options, "type") ? { type: strOpt(options, "type") } : {}
1014
+ }, setPairs(options));
1015
+ if (!filter.type) usage("filter add needs --type <filter> or --filter <json>.", "e.g. filter add photo --type exposure --set exposure=0.3 (`agentphoto catalog filters` lists them).");
1016
+ const index = numOpt(options, "index");
1017
+ return runMutation(io, options, fs, "filter_add", {
1018
+ id,
1019
+ filter,
1020
+ ...index !== void 0 ? { index } : {}
1021
+ }, `Add filter ${String(filter.type)} to "${id}"`);
1022
+ }
1023
+ if (action === "update" || action === "remove") {
1024
+ const id = positional(positionals, 1, "layer id", `filter ${action} <layer> <index>`);
1025
+ const raw = positionals[2] ?? strOpt(options, "index");
1026
+ const index = Number(raw);
1027
+ if (raw === void 0 || !Number.isInteger(index) || index < 0) usage(`filter ${action} needs the filter index (0 = first; \`agentphoto layer get ${id}\` shows them).`);
1028
+ if (action === "remove") return runMutation(io, options, fs, "doc_patch", { ops: [{
1029
+ op: "removeFilter",
1030
+ id,
1031
+ index
1032
+ }] }, `Remove filter ${index} of "${id}"`);
1033
+ const set = deepMerge(jsonObjectOpt(options, "filter") ?? {}, setPairs(options));
1034
+ if (!Object.keys(set).length) usage("Nothing to change.", "Pass --set key=value (repeated) or --filter '{…}'.");
1035
+ return runMutation(io, options, fs, "doc_patch", { ops: [{
1036
+ op: "updateFilter",
1037
+ id,
1038
+ index,
1039
+ set
1040
+ }] }, `Update filter ${index} of "${id}"`);
1041
+ }
1042
+ usage(`Unknown filter action "${action}".`, "Use add, update or remove.");
1043
+ }
1044
+ };
1045
+ function parseNumbers(raw, what, count) {
1046
+ const nums = raw.replace(/^\[|\]$/g, "").split(/[\s,]+/).filter(Boolean).map(Number);
1047
+ if (nums.length !== count || nums.some((n) => !Number.isFinite(n))) usage(`${what} must be ${count} numbers, got "${raw}".`);
1048
+ return nums;
1049
+ }
1050
+ var maskCommand = {
1051
+ name: "mask",
1052
+ usage: "mask <set|clear|generate> <layer> [--project <dir>]",
1053
+ summary: "Layer masks: set one (image / shape / gradient), clear it, or generate one from pixels with local AI or a colour range (subject, points, box, color) — non-destructive, the mask PNG goes to assets/masks/.",
1054
+ subcommands: [
1055
+ {
1056
+ name: "set",
1057
+ usage: "mask set <layer> --mask <json|@file>",
1058
+ summary: "Set a mask: {\"src\":\"assets/masks/x.png\"} | {\"shape\":\"ellipse\",\"x\":0,\"y\":0,\"width\":400,\"height\":300,\"feather\":20} | {\"gradient\":{…}} (+ invert, feather, density, enabled). Box layers: layer-local px.",
1059
+ writes: true
1060
+ },
1061
+ {
1062
+ name: "clear",
1063
+ usage: "mask clear <layer>",
1064
+ summary: "Remove the layer's mask (the file stays in assets/).",
1065
+ writes: true
1066
+ },
1067
+ {
1068
+ name: "generate",
1069
+ usage: "mask generate <layer> --method subject|points|box|color [--points <json>] [--box x1,y1,x2,y2] [--color <c>] [--tolerance <0-100>] [--invert] [--feather <px>] [--model <id>] [--target mask|copy]",
1070
+ summary: "Make a mask from pixels (needs Chrome; AI models download once): subject (main subject), points (Segment Anything, [[x,y,1|0],…] in layer px), box, color (colour range). --invert keeps the rest; --target copy masks a duplicate instead.",
1071
+ writes: true
1072
+ }
1073
+ ],
1074
+ options: [
1075
+ PROJECT_OPTION,
1076
+ {
1077
+ name: "mask",
1078
+ type: "string",
1079
+ description: "set: the mask as JSON, @file or -."
1080
+ },
1081
+ {
1082
+ name: "method",
1083
+ type: "string",
1084
+ description: "generate: subject, points, box or color."
1085
+ },
1086
+ {
1087
+ name: "points",
1088
+ type: "string",
1089
+ description: "generate --method points: [[x, y, 1 = include | 0 = exclude], …] in layer px."
1090
+ },
1091
+ {
1092
+ name: "box",
1093
+ type: "string",
1094
+ description: "generate --method box: x1,y1,x2,y2 in layer px."
1095
+ },
1096
+ {
1097
+ name: "color",
1098
+ type: "string",
1099
+ description: "generate --method color: the colour to select."
1100
+ },
1101
+ {
1102
+ name: "tolerance",
1103
+ type: "string",
1104
+ description: "generate --method color: 0..100 (default 32)."
1105
+ },
1106
+ {
1107
+ name: "invert",
1108
+ type: "boolean",
1109
+ description: "generate: keep everything except the selection."
1110
+ },
1111
+ {
1112
+ name: "feather",
1113
+ type: "string",
1114
+ description: "generate: soften the edge, px."
1115
+ },
1116
+ {
1117
+ name: "model",
1118
+ type: "string",
1119
+ description: "generate: AI model id (`agentphoto models list`)."
1120
+ },
1121
+ {
1122
+ name: "target",
1123
+ type: "string",
1124
+ description: "generate: mask (default, the layer itself) or copy (duplicate the layer and mask the copy)."
1125
+ },
1126
+ {
1127
+ name: "copy-id",
1128
+ type: "string",
1129
+ description: "generate --target copy: id of the copy."
1130
+ },
1131
+ DRY_RUN_OPTION,
1132
+ YES_OPTION
1133
+ ],
1134
+ async run({ io, options, positionals }) {
1135
+ const [action] = positionals;
1136
+ if (!action) usage("Missing action.", "Use mask set|clear|generate <layer>.");
1137
+ const fs = projectFs(options);
1138
+ if (action === "set") {
1139
+ const id = positional(positionals, 1, "layer id", "mask set <layer> --mask <json>");
1140
+ const mask = jsonOpt(options, "mask", `--mask '{"shape":"ellipse","x":0,"y":0,"width":400,"height":300,"feather":20}'`);
1141
+ if (mask === void 0) usage("mask set needs --mask <json>.", "Use `mask clear <layer>` to remove a mask.");
1142
+ return runMutation(io, options, fs, "mask_set", {
1143
+ id,
1144
+ mask
1145
+ }, `Set the mask of "${id}"`);
1146
+ }
1147
+ if (action === "clear") {
1148
+ const id = positional(positionals, 1, "layer id", "mask clear <layer>");
1149
+ return runMutation(io, options, fs, "mask_set", {
1150
+ id,
1151
+ mask: null
1152
+ }, `Clear the mask of "${id}"`);
1153
+ }
1154
+ if (action === "generate") {
1155
+ const id = positional(positionals, 1, "layer id", "mask generate <layer> --method subject");
1156
+ const method = strOpt(options, "method");
1157
+ if (!method || ![
1158
+ "subject",
1159
+ "points",
1160
+ "box",
1161
+ "color"
1162
+ ].includes(method)) usage("mask generate needs --method subject|points|box|color.", "e.g. mask generate photo --method points --points '[[640,420,1]]'");
1163
+ const input = {
1164
+ id,
1165
+ method
1166
+ };
1167
+ if (method === "points") {
1168
+ const points = jsonOpt(options, "points", `--points '[[640,420,1],[100,80,0]]'`);
1169
+ if (!Array.isArray(points) || !points.length || points.some((p) => !Array.isArray(p) || p.length < 2)) usage("--method points needs --points '[[x,y,1],…]' (layer px; 1 = include, 0 = exclude).");
1170
+ input.points = points;
1171
+ }
1172
+ if (method === "box") {
1173
+ const raw = strOpt(options, "box");
1174
+ if (!raw) usage("--method box needs --box x1,y1,x2,y2 (layer px).");
1175
+ input.box = parseNumbers(raw, "--box", 4);
1176
+ }
1177
+ if (method === "color") {
1178
+ const color = strOpt(options, "color");
1179
+ if (!color) usage("--method color needs --color \"<colour>\" (e.g. \"#3a7bd5\").");
1180
+ input.color = color;
1181
+ if (numOpt(options, "tolerance") !== void 0) input.tolerance = numOpt(options, "tolerance");
1182
+ }
1183
+ if (boolOpt(options, "invert")) input.invert = true;
1184
+ if (numOpt(options, "feather") !== void 0) input.feather = numOpt(options, "feather");
1185
+ if (strOpt(options, "model")) input.model = strOpt(options, "model");
1186
+ if (strOpt(options, "target")) input.target = strOpt(options, "target");
1187
+ if (strOpt(options, "copy-id")) input.copyId = strOpt(options, "copy-id");
1188
+ const r = await tool(fs, "mask_generate", input);
1189
+ if (r.status === "refused") throw new CliError("validation", "The generated mask could not be applied.", "See details.issues.", 2, { issues: r.issues });
1190
+ return printResult(io, {
1191
+ ...r,
1192
+ maskFile: `${fs.root}/${r.mask}`
1193
+ }, () => `Mask ${r.mask} (${String(r.size)}) set on "${r.layer ?? id}". ${r.plan.summary}\nLook at it: agentphoto render --project ${fs.root}`);
1194
+ }
1195
+ usage(`Unknown mask action "${action}".`, "Use set, clear or generate.");
1196
+ }
1197
+ };
1198
+ // agent/commands/image.ts
1199
+ var log$1 = (m) => void process.stderr.write(`${m}\n`);
1200
+ var removeBgCommand = {
1201
+ name: "remove-bg",
1202
+ usage: "remove-bg <layer> [--model rmbg-1.4|modnet] [--background <paint>] [--shadow] [--feather <px>] [--threshold <0-255>]",
1203
+ summary: "Remove the background of a photo layer with local AI (nothing is uploaded; the model downloads once): writes a mask to assets/masks/ and sets it on the layer — non-destructive (`mask clear` restores). --background adds a colour / gradient under the cut-out, --shadow a soft drop shadow.",
1204
+ writes: true,
1205
+ options: [
1206
+ PROJECT_OPTION,
1207
+ {
1208
+ name: "model",
1209
+ type: "string",
1210
+ description: "rmbg-1.4 (default: products, people, objects) or modnet (portraits)."
1211
+ },
1212
+ {
1213
+ name: "background",
1214
+ type: "string",
1215
+ description: "Colour or gradient JSON placed behind the subject (adds a fill layer), e.g. \"#ffffff\"."
1216
+ },
1217
+ {
1218
+ name: "shadow",
1219
+ type: "boolean",
1220
+ description: "Add a soft drop shadow under the subject."
1221
+ },
1222
+ {
1223
+ name: "feather",
1224
+ type: "string",
1225
+ description: "Soften the edge, px."
1226
+ },
1227
+ {
1228
+ name: "threshold",
1229
+ type: "string",
1230
+ description: "Hard edge: keep pixels with confidence ≥ threshold (0..255). Default: soft alpha (best for hair)."
1231
+ }
1232
+ ],
1233
+ async run({ io, options, positionals }) {
1234
+ const id = positional(positionals, 0, "layer id", "remove-bg <layer>");
1235
+ const fs = projectFs(options);
1236
+ const input = { id };
1237
+ if (strOpt(options, "model")) input.model = strOpt(options, "model");
1238
+ if (strOpt(options, "background") !== void 0) input.background = paintValue(strOpt(options, "background"));
1239
+ if (boolOpt(options, "shadow")) input.shadow = true;
1240
+ if (numOpt(options, "feather") !== void 0) input.feather = numOpt(options, "feather");
1241
+ if (numOpt(options, "threshold") !== void 0) input.threshold = numOpt(options, "threshold");
1242
+ const r = await tool(fs, "remove_background", input);
1243
+ if (r.status === "refused") throw new CliError("validation", "The cut-out could not be applied.", "See details.issues.", 2, { issues: r.issues });
1244
+ printResult(io, {
1245
+ ...r,
1246
+ maskFile: absPath(fs, r.mask)
1247
+ }, () => `Background removed from "${id}" (${r.model}): mask ${r.mask} (${r.size}). ${r.plan.summary}\nLook at it: agentphoto render --project ${fs.root}`);
1248
+ }
1249
+ };
1250
+ var analyzeCommand = {
1251
+ name: "analyze",
1252
+ usage: "analyze [--layer <id>]",
1253
+ summary: "Measure the picture (or one layer's own pixels): brightness, contrast, tonal range, clipping, colour cast, saturation, sharpness, dominant colours — with suggested filters ready for `filter add`.",
1254
+ options: [PROJECT_OPTION, {
1255
+ name: "layer",
1256
+ type: "string",
1257
+ description: "Analyse this layer alone (default: the whole render)."
1258
+ }],
1259
+ async run({ io, options }) {
1260
+ const fs = projectFs(options);
1261
+ const layer = strOpt(options, "layer");
1262
+ const r = await tool(fs, "image_analyze", layer ? { layer } : {});
1263
+ printResult(io, r, () => [
1264
+ `${layer ? `Layer "${layer}"` : "Image"} ${r.width}×${r.height}: brightness ${r.brightness}, contrast ${r.contrast}, saturation ${r.saturation}, sharpness ${r.sharpness}`,
1265
+ `Clipped: shadows ${r.clippedShadows} %, highlights ${r.clippedHighlights} % · cast warm ${r.cast.warm}, magenta ${r.cast.magenta}`,
1266
+ `Dominant: ${r.dominant.map((d) => `${d.color} (${d.share} %)`).join(", ")}`,
1267
+ ...r.suggestions.length ? ["Suggestions:", ...r.suggestions.map((s) => ` ${s.issue}: ${JSON.stringify(s.filter)}`)] : ["No correction suggested."]
1268
+ ].join("\n"));
1269
+ }
1270
+ };
1271
+ function parseZoom(raw) {
1272
+ const n = raw.split(/[\s,x]+/).filter(Boolean).map(Number);
1273
+ if (n.length !== 4 || n.some((v) => !Number.isFinite(v)) || n[2] <= 0 || n[3] <= 0) usage(`--zoom must be x,y,width,height (canvas px), got "${raw}".`, "e.g. --zoom 400,200,600,400");
1274
+ return {
1275
+ x: n[0],
1276
+ y: n[1],
1277
+ width: n[2],
1278
+ height: n[3]
1279
+ };
1280
+ }
1281
+ var renderCommand = {
1282
+ name: "render",
1283
+ usage: "render [--max-width <px>] [--compare] [--layer <id>] [--zoom x,y,w,h]",
1284
+ summary: "Render the document headless (Chrome) to renders/preview.png and print the image path(s) — LOOK at them after every visual change. --compare also renders the unedited 'before', --layer one layer alone, --zoom a canvas region at 1:1 (mask edges, text).",
1285
+ options: [
1286
+ PROJECT_OPTION,
1287
+ {
1288
+ name: "max-width",
1289
+ type: "string",
1290
+ description: "Preview width cap in px (default 1000)."
1291
+ },
1292
+ {
1293
+ name: "compare",
1294
+ type: "boolean",
1295
+ description: "Also render the version without filters / adjustments (before / after)."
1296
+ },
1297
+ {
1298
+ name: "layer",
1299
+ type: "string",
1300
+ description: "Render only this layer."
1301
+ },
1302
+ {
1303
+ name: "zoom",
1304
+ type: "string",
1305
+ description: "Canvas region x,y,width,height rendered at full resolution (max 1600 px)."
1306
+ },
1307
+ {
1308
+ name: "backdrop",
1309
+ type: "string",
1310
+ description: "Under transparent areas: \"checker\" (default for transparent canvases and --layer), a CSS colour, or \"none\"."
1311
+ }
1312
+ ],
1313
+ async run({ io, options }) {
1314
+ const fs = projectFs(options);
1315
+ const input = {};
1316
+ if (numOpt(options, "max-width") !== void 0) input.maxWidth = numOpt(options, "max-width");
1317
+ if (boolOpt(options, "compare")) input.compare = true;
1318
+ if (strOpt(options, "backdrop")) input.backdrop = strOpt(options, "backdrop");
1319
+ if (strOpt(options, "layer")) input.layer = strOpt(options, "layer");
1320
+ if (strOpt(options, "zoom")) input.zoom = parseZoom(strOpt(options, "zoom"));
1321
+ const r = await tool(fs, "render_preview", input);
1322
+ const files = r.images.map((p) => absPath(fs, p));
1323
+ printResult(io, {
1324
+ ...r,
1325
+ files
1326
+ }, () => [
1327
+ ...files,
1328
+ `${r.size} (canvas ${r.canvas})`,
1329
+ ...r.errors?.length ? [`Errors: ${JSON.stringify(r.errors)}`] : []
1330
+ ].join("\n"));
1331
+ }
1332
+ };
1333
+ var exportCommand = {
1334
+ name: "export",
1335
+ usage: "export [--format png|jpeg|webp|avif] [--quality <1-100>] [--preset <size>] [--width <px>] [--height <px>] [--scale <k>] [--fit cover|contain|stretch] [--background <colour>] [--name <file>] [--out <path>] [--variants <json>] [--yes]",
1336
+ summary: "Render the final image(s) into dist/ (headless Chrome): format, quality, size (a preset like og / square / story, or width / height / scale), fit (cover crops, contain pads) and background (flatten transparency). --variants exports several at once. Overwriting existing files needs --yes.",
1337
+ writes: true,
1338
+ options: [
1339
+ PROJECT_OPTION,
1340
+ {
1341
+ name: "format",
1342
+ type: "string",
1343
+ description: "png (default), jpeg, webp or avif."
1344
+ },
1345
+ {
1346
+ name: "quality",
1347
+ type: "string",
1348
+ description: "1..100 (jpeg 88, webp 86, avif 70 by default)."
1349
+ },
1350
+ {
1351
+ name: "preset",
1352
+ type: "string",
1353
+ description: "Size preset (`agentphoto catalog sizes`)."
1354
+ },
1355
+ {
1356
+ name: "width",
1357
+ type: "string",
1358
+ description: "Output width in px."
1359
+ },
1360
+ {
1361
+ name: "height",
1362
+ type: "string",
1363
+ description: "Output height in px."
1364
+ },
1365
+ {
1366
+ name: "scale",
1367
+ type: "string",
1368
+ description: "Output scale (2 = twice the canvas)."
1369
+ },
1370
+ {
1371
+ name: "fit",
1372
+ type: "string",
1373
+ description: "cover (crop, default), contain (pad) or stretch — when the output aspect differs."
1374
+ },
1375
+ {
1376
+ name: "background",
1377
+ type: "string",
1378
+ description: "Flatten transparency onto this colour (\"transparent\" keeps alpha; jpeg defaults to white)."
1379
+ },
1380
+ {
1381
+ name: "name",
1382
+ type: "string",
1383
+ description: "File name without extension (default: the document id)."
1384
+ },
1385
+ {
1386
+ name: "out",
1387
+ type: "string",
1388
+ description: "Output path inside the project (default dist/<name>[-<preset>].<ext>)."
1389
+ },
1390
+ {
1391
+ name: "variants",
1392
+ type: "string",
1393
+ description: "Several outputs: JSON array of { format, preset, width, height, quality, … } (e.g. '[{\"preset\":\"og\"},{\"preset\":\"story\",\"format\":\"webp\"}]')."
1394
+ },
1395
+ YES_OPTION
1396
+ ],
1397
+ async run({ io, options }) {
1398
+ const fs = projectFs(options);
1399
+ const input = {};
1400
+ for (const k of [
1401
+ "format",
1402
+ "preset",
1403
+ "fit",
1404
+ "name",
1405
+ "out"
1406
+ ]) if (strOpt(options, k)) input[k] = strOpt(options, k);
1407
+ for (const k of [
1408
+ "quality",
1409
+ "width",
1410
+ "height",
1411
+ "scale"
1412
+ ]) if (numOpt(options, k) !== void 0) input[k] = numOpt(options, k);
1413
+ const bg = strOpt(options, "background");
1414
+ if (bg !== void 0) input.background = paintValue(bg);
1415
+ if (input.background !== void 0 && input.background !== null && typeof input.background !== "string") usage("--background must be a colour for exports.");
1416
+ const variants = jsonOpt(options, "variants", `--variants '[{"preset":"og"},{"preset":"story","format":"webp"}]'`);
1417
+ if (variants !== void 0) {
1418
+ if (!Array.isArray(variants) || !variants.length || variants.some((v) => !v || typeof v !== "object" || Array.isArray(v))) usage("--variants must be a JSON array of objects.", `e.g. --variants '[{"preset":"og"},{"preset":"square","format":"jpeg"}]'`);
1419
+ input.variants = variants;
1420
+ }
1421
+ const [{ getDoc }, { planExport }] = await Promise.all([import("./chunks/doc-BjY_j4Su.mjs").then((n) => n.r), import("./chunks/export-CLmpFART.mjs").then((n) => n.n)]);
1422
+ const doc = await getDoc(fs);
1423
+ const { variants: _v, ...base } = input;
1424
+ const jobs = (Array.isArray(variants) ? variants.map((v) => ({
1425
+ ...base,
1426
+ out: void 0,
1427
+ ...v
1428
+ })) : [base]).map((r) => planExport(doc, r));
1429
+ const existing = [];
1430
+ for (const j of jobs) if (await fs.exists(j.file)) existing.push(j.file);
1431
+ if (existing.length) {
1432
+ if (!confirmOrPlan(io, options, {
1433
+ overwrite: existing,
1434
+ files: jobs.map((j) => ({
1435
+ path: j.file,
1436
+ format: j.format,
1437
+ width: j.width,
1438
+ height: j.height
1439
+ }))
1440
+ }, () => `Export would overwrite: ${existing.join(", ")}`)) return;
1441
+ }
1442
+ log$1(`Exporting ${jobs.length} file${jobs.length > 1 ? "s" : ""}…`);
1443
+ const r = await tool(fs, "export", input);
1444
+ const files = r.files.map((f) => ({
1445
+ ...f,
1446
+ file: absPath(fs, f.path)
1447
+ }));
1448
+ printResult(io, {
1449
+ ...r,
1450
+ files
1451
+ }, () => files.map((f) => `${f.file} (${f.format}, ${f.width}×${f.height}, ${f.kb} KB)${f.note ? ` ${f.note}` : ""}`).join("\n"));
1452
+ }
1453
+ };
1454
+ var checkCommand = {
1455
+ name: "check",
1456
+ usage: "check [--project <dir>]",
1457
+ summary: "Everything to fix before export: validation, missing files, layers off the canvas, upscaled (blurry) photos, text that may overflow, heavy filters, licences needing attribution. Exit 1 when not ok.",
1458
+ options: [PROJECT_OPTION],
1459
+ async run({ io, options }) {
1460
+ const r = await tool(projectFs(options), "check", {});
1461
+ printResult(io, r, () => [
1462
+ r.ok ? "Check passed." : "Check failed.",
1463
+ ...r.issues.map((i) => ` ${i.severity === "error" ? "✗" : i.severity === "warning" ? "!" : "·"} ${i.code} ${i.path ?? ""}: ${i.message}${i.hint ? ` (${i.hint})` : ""}`),
1464
+ `Canvas ${r.canvas.width}×${r.canvas.height} (${r.canvas.megapixels} MP), ${r.layers} layers, render cost ${r.cost}, assets ${r.assetsKb} KB`,
1465
+ ...r.licences.length ? ["Licences:", ...r.licences.map((l) => ` ${l.path}: ${l.license ?? "?"}${l.attribution ? ` — ${l.attribution}` : ""}`)] : []
1466
+ ].join("\n"));
1467
+ return r.ok ? 0 : 1;
1468
+ }
1469
+ };
1470
+ // agent/commands/meta.ts
1471
+ var versionCommand = {
1472
+ name: "version",
1473
+ usage: "version",
1474
+ summary: "Print the AgentPhoto version (CLI = engine = skills version).",
1475
+ options: [],
1476
+ async run({ io }) {
1477
+ const info = readVersionInfo();
1478
+ printResult(io, {
1479
+ ...info,
1480
+ bundled: isBundled(),
1481
+ node: process.versions.node
1482
+ }, () => info.version);
1483
+ }
1484
+ };
1485
+ var DOCTOR_DOC = {
1486
+ version: 1,
1487
+ id: "doctor",
1488
+ canvas: {
1489
+ width: 128,
1490
+ height: 96,
1491
+ background: "#1d2330"
1492
+ },
1493
+ layers: [{
1494
+ id: "dot",
1495
+ type: "shape",
1496
+ shape: "ellipse",
1497
+ x: 32,
1498
+ y: 16,
1499
+ width: 64,
1500
+ height: 64,
1501
+ fill: "#ff6a3d"
1502
+ }]
1503
+ };
1504
+ var BROWSER_CODES = /* @__PURE__ */ new Set([
1505
+ "browser-launch",
1506
+ "no-browser",
1507
+ "cdp-connect"
1508
+ ]);
1509
+ function renderFailure(e) {
1510
+ const err = e;
1511
+ const code = err instanceof CliError ? err.code : void 0;
1512
+ const hint = err.hint ?? (code && BROWSER_CODES.has(code) ? "Update Chrome, or point AGENTPHOTO_CHROME at Google Chrome / Chromium (`npx playwright install chromium`)." : "The browser started but the test render failed inside AgentPhoto: retry once, then report it with this output (`agentphoto version`).");
1513
+ return {
1514
+ id: "render",
1515
+ ok: false,
1516
+ message: `Test render failed${code ? ` (${code})` : ""}: ${err.message}`,
1517
+ hint,
1518
+ ...code ? { details: { code } } : {}
1519
+ };
1520
+ }
1521
+ var doctorCommand = {
1522
+ name: "doctor",
1523
+ usage: "doctor [--no-render]",
1524
+ summary: "Check the setup: Node version, installed Chrome (+ version), the engine / Studio builds, library, templates, the AI model cache, and a headless test render. A failed required check makes the command fail (exit 1, error code doctor-failed, one hint per failed check, every check in error.details.checks).",
1525
+ options: [{
1526
+ name: "no-render",
1527
+ type: "boolean",
1528
+ description: "Skip the test render."
1529
+ }],
1530
+ async run({ io, options }) {
1531
+ const checks = [];
1532
+ const major = Number(process.versions.node.split(".")[0]);
1533
+ checks.push({
1534
+ id: "node",
1535
+ ok: major >= 22,
1536
+ message: `Node ${process.versions.node}${major >= 22 ? "" : " (AgentPhoto needs Node 22+)"}`,
1537
+ ...major < 22 ? { hint: "Install Node 22 or newer (https://nodejs.org)." } : {}
1538
+ });
1539
+ const { findBrowser, browserVersion, noBrowserError } = await Promise.resolve().then(() => browser_exports);
1540
+ const browser = findBrowser();
1541
+ if (browser) {
1542
+ const version = await browserVersion(browser.path);
1543
+ checks.push({
1544
+ id: "browser",
1545
+ ok: true,
1546
+ message: `${browser.name}${version ? ` — ${version}` : ""}`,
1547
+ details: {
1548
+ path: browser.path,
1549
+ source: browser.source,
1550
+ version
1551
+ }
1552
+ });
1553
+ } else {
1554
+ const e = noBrowserError();
1555
+ checks.push({
1556
+ id: "browser",
1557
+ ok: false,
1558
+ message: e.message,
1559
+ hint: e.hint
1560
+ });
1561
+ }
1562
+ checks.push(engineBuilt() ? {
1563
+ id: "engine",
1564
+ ok: true,
1565
+ message: `Engine build found (${engineDir()})`,
1566
+ details: { ai: existsSync(join(engineDir(), "ort")) }
1567
+ } : {
1568
+ id: "engine",
1569
+ ok: false,
1570
+ message: `Engine build missing (${engineDir()})`,
1571
+ hint: "Use the npm package, or run `npm run build:engine` in a clone (AGENTPHOTO_DIST overrides the dist folder)."
1572
+ });
1573
+ const studio = existsSync(join(studioDir(), "index.html"));
1574
+ checks.push({
1575
+ id: "studio",
1576
+ ok: studio,
1577
+ optional: true,
1578
+ message: studio ? `Studio build found (${studioDir()})` : `Studio build missing (${studioDir()}) — \`agentphoto studio\` needs it`,
1579
+ ...studio ? {} : { hint: "Run `npm run build:studio` in a clone (the npm package ships it)." }
1580
+ });
1581
+ const lib = existsSync(join(libraryDir(), "index.json"));
1582
+ checks.push({
1583
+ id: "library",
1584
+ ok: lib,
1585
+ optional: true,
1586
+ message: lib ? `Library found (${libraryDir()})` : `Library index missing (${join(libraryDir(), "index.json")})`
1587
+ });
1588
+ const tpl = existsSync(templatesDir());
1589
+ checks.push({
1590
+ id: "templates",
1591
+ ok: tpl,
1592
+ optional: true,
1593
+ message: tpl ? `Templates found (${templatesDir()})` : `Templates folder missing (${templatesDir()})`
1594
+ });
1595
+ const { listCachedModels } = await import("./chunks/models-C4i_hicr.mjs").then((n) => n.i);
1596
+ const cached = listCachedModels().filter((m) => m.cached);
1597
+ checks.push({
1598
+ id: "models",
1599
+ ok: true,
1600
+ optional: true,
1601
+ message: `AI model cache ${modelsDir()}: ${cached.length ? cached.map((m) => `${m.id} (${m.cachedMb} MB)`).join(", ") : "empty (models download once on first use, or `agentphoto models pull <id>`)"}`,
1602
+ details: {
1603
+ dir: modelsDir(),
1604
+ cached: cached.map((m) => m.id)
1605
+ }
1606
+ });
1607
+ if (!boolOpt(options, "no-render")) {
1608
+ if (!browser || !engineBuilt() || major < 22) checks.push({
1609
+ id: "render",
1610
+ ok: false,
1611
+ message: "Test render skipped (needs Chrome, the engine build and Node 22+).",
1612
+ hint: "Fix the checks above, then run `agentphoto doctor` again."
1613
+ });
1614
+ else {
1615
+ const dir = mkdtempSync(join(tmpdir(), "agentphoto-doctor-"));
1616
+ const { EngineSession, decodeImage } = await Promise.resolve().then(() => session_exports);
1617
+ const session = new EngineSession(dir);
1618
+ try {
1619
+ const t0 = Date.now();
1620
+ const img = decodeImage(await session.call("render", DOCTOR_DOC, { format: "png" }));
1621
+ const ok = img.bytes.byteLength > 100 && img.width === 128 && img.height === 96 && img.bytes[0] === 137;
1622
+ checks.push({
1623
+ id: "render",
1624
+ ok,
1625
+ message: ok ? `Headless render OK in ${Date.now() - t0} ms (${img.width}×${img.height} PNG, ${img.bytes.byteLength} bytes)` : "The test render returned an unexpected image.",
1626
+ ...ok ? {} : { hint: "Update Chrome, or point AGENTPHOTO_CHROME at Google Chrome / Chromium." }
1627
+ });
1628
+ } catch (e) {
1629
+ checks.push(renderFailure(e));
1630
+ } finally {
1631
+ await session.close();
1632
+ rmSync(dir, {
1633
+ recursive: true,
1634
+ force: true
1635
+ });
1636
+ }
1637
+ }
1638
+ }
1639
+ const ok = checks.every((c) => c.ok || c.optional);
1640
+ const info = readVersionInfo();
1641
+ const human = () => [
1642
+ `agentphoto ${info.version} doctor`,
1643
+ ...checks.map((c) => ` ${c.ok ? "✓" : c.optional ? "·" : "✗"} ${c.id.padEnd(9)} ${c.message}${c.hint && !c.ok ? `\n → ${c.hint}` : ""}`),
1644
+ "",
1645
+ ok ? "All good." : "Some checks failed."
1646
+ ].join("\n");
1647
+ if (!ok) {
1648
+ const failed = checks.filter((c) => !c.ok && !c.optional);
1649
+ if (!io.json) {
1650
+ io.out(human());
1651
+ return 1;
1652
+ }
1653
+ throw new CliError("doctor-failed", `${failed.length} required check(s) failed: ${failed.map((c) => `${c.id} (${c.message})`).join("; ")}`, failed.map((c) => `${c.id}: ${c.hint ?? "see details.checks"}`).join(" | "), 1, {
1654
+ version: info.version,
1655
+ packageRoot: packageRoot(),
1656
+ dist: distRoot(),
1657
+ failed: failed.map((c) => c.id),
1658
+ checks
1659
+ });
1660
+ }
1661
+ printResult(io, {
1662
+ ok,
1663
+ version: info.version,
1664
+ packageRoot: packageRoot(),
1665
+ dist: distRoot(),
1666
+ checks
1667
+ }, human);
1668
+ return 0;
1669
+ }
1670
+ };
1671
+ // agent/commands/models.ts
1672
+ var log = (m) => void process.stderr.write(`${m}\n`);
1673
+ function unknownModel(id) {
1674
+ throw new CliError("notFound", `Unknown model "${id}".`, `Models: ${MODELS.map((m) => m.id).join(", ")} (\`agentphoto models list\`).`, 2);
1675
+ }
1676
+ var modelsCommand = {
1677
+ name: "models",
1678
+ usage: "models <list|pull|remove> [<id>] [--yes]",
1679
+ summary: `Local AI models (background removal, Segment Anything): list them with their cache state, pre-download one (pull — otherwise the first remove-bg / mask generate downloads it), or delete its cache. Cache: ~/.cache/agentphoto/models ($AGENTPHOTO_MODELS overrides).`,
1680
+ subcommands: [
1681
+ {
1682
+ name: "list",
1683
+ usage: "models list",
1684
+ summary: "Every model: id, task, download size, licence, whether it is cached (and its size on disk)."
1685
+ },
1686
+ {
1687
+ name: "pull",
1688
+ usage: "models pull <id>",
1689
+ summary: "Download a model now by running it once on a sample photo (needs Chrome and the network)."
1690
+ },
1691
+ {
1692
+ name: "remove",
1693
+ usage: "models remove <id> [--yes]",
1694
+ summary: "Delete a model's cache folder (plan + needsConfirmation unless --yes).",
1695
+ destructive: true
1696
+ }
1697
+ ],
1698
+ options: [YES_OPTION],
1699
+ async run({ io, options, positionals }) {
1700
+ const [action = "list", id] = positionals;
1701
+ if (action === "list") {
1702
+ const models = listCachedModels();
1703
+ return printResult(io, {
1704
+ dir: modelsDir(),
1705
+ models
1706
+ }, () => `${table(models.map((m) => ({
1707
+ ...m,
1708
+ cached: m.cached ? `yes (${m.cachedMb} MB)` : "no"
1709
+ })), [
1710
+ "id",
1711
+ "task",
1712
+ "sizeMb",
1713
+ "cached",
1714
+ "license"
1715
+ ])}\nCache: ${modelsDir()}`);
1716
+ }
1717
+ if (action === "pull") {
1718
+ const mid = positional(positionals, 1, "model id", "models pull <id>");
1719
+ const def = modelDef(mid) ?? unknownModel(mid);
1720
+ const sample = readLibraryIndex().assets.find((a) => a.kind === "image" && a.width && a.height);
1721
+ if (!sample) throw new CliError("library-missing", "No sample photo in the library to run the model on.", "Reinstall the package (library/ ships the sample photos).");
1722
+ const W = sample.width;
1723
+ const H = sample.height;
1724
+ const doc = {
1725
+ version: 1,
1726
+ id: "pull",
1727
+ canvas: {
1728
+ width: W,
1729
+ height: H
1730
+ },
1731
+ layers: [{
1732
+ id: "photo",
1733
+ type: "image",
1734
+ src: `library:${sample.id}`,
1735
+ x: 0,
1736
+ y: 0,
1737
+ width: W,
1738
+ height: H
1739
+ }]
1740
+ };
1741
+ const dir = mkdtempSync(join(tmpdir(), "agentphoto-pull-"));
1742
+ const { EngineSession } = await Promise.resolve().then(() => session_exports);
1743
+ const session = new EngineSession(dir);
1744
+ const t0 = Date.now();
1745
+ try {
1746
+ log(`Pulling ${def.id} (${def.repo}, ~${def.sizeMb} MB)…`);
1747
+ if (def.task === "segmentation") await session.call("segmentMask", doc, "photo", { points: [[
1748
+ W / 2,
1749
+ H / 2,
1750
+ 1
1751
+ ]] }, { model: def.id });
1752
+ else await session.call("backgroundMask", doc, "photo", { model: def.id });
1753
+ } finally {
1754
+ await session.close();
1755
+ rmSync(dir, {
1756
+ recursive: true,
1757
+ force: true
1758
+ });
1759
+ }
1760
+ const m = listCachedModels().find((x) => x.id === def.id);
1761
+ return printResult(io, {
1762
+ model: m,
1763
+ seconds: Math.round((Date.now() - t0) / 100) / 10
1764
+ }, () => `${def.id} is ready (${m.cachedMb} MB in ${m.dir}).`);
1765
+ }
1766
+ if (action === "remove") {
1767
+ const mid = positional(positionals, 1, "model id", "models remove <id>");
1768
+ const def = modelDef(mid) ?? unknownModel(mid);
1769
+ const m = listCachedModels().find((x) => x.id === def.id);
1770
+ if (!m.cached) return printResult(io, {
1771
+ removed: false,
1772
+ model: m
1773
+ }, () => `${def.id} is not cached.`);
1774
+ if (!confirmOrPlan(io, options, {
1775
+ remove: modelCacheDir(def),
1776
+ model: def.id,
1777
+ mb: m.cachedMb
1778
+ }, () => `Delete ${modelCacheDir(def)} (${m.cachedMb} MB). It downloads again on next use.`)) return;
1779
+ rmSync(modelCacheDir(def), {
1780
+ recursive: true,
1781
+ force: true
1782
+ });
1783
+ return printResult(io, {
1784
+ removed: true,
1785
+ model: def.id,
1786
+ dir: modelCacheDir(def),
1787
+ freedMb: m.cachedMb
1788
+ }, () => `Removed ${def.id} (${m.cachedMb} MB freed).`);
1789
+ }
1790
+ usage(`Unknown models action "${action}".`, "Use list, pull or remove.");
1791
+ }
1792
+ };
1793
+ // agent/commands/project.ts
1794
+ var newCommand = {
1795
+ name: "new",
1796
+ usage: "new <dir> [--image <file|url>] [--size <preset>] [--width <px> --height <px>] [--background <paint>] [--template <id>] [--title <text>] [--force]",
1797
+ summary: "Create a project folder (agentphoto.json, photo.json, assets/): from a photo (it becomes the \"photo\" layer and sets the canvas size), blank (--size preset or --width / --height), and / or from a template (`templates list`).",
1798
+ writes: true,
1799
+ options: [
1800
+ {
1801
+ name: "image",
1802
+ type: "string",
1803
+ description: "Starting photo: a local file or an http(s) URL (copied into assets/images/)."
1804
+ },
1805
+ {
1806
+ name: "size",
1807
+ type: "string",
1808
+ description: "Canvas size preset (`agentphoto catalog sizes`: og, square, story, youtube…)."
1809
+ },
1810
+ {
1811
+ name: "width",
1812
+ type: "string",
1813
+ description: "Canvas width in px."
1814
+ },
1815
+ {
1816
+ name: "height",
1817
+ type: "string",
1818
+ description: "Canvas height in px."
1819
+ },
1820
+ {
1821
+ name: "background",
1822
+ type: "string",
1823
+ description: "Canvas background: a colour (\"#ffffff\"), a gradient as JSON, or \"transparent\"."
1824
+ },
1825
+ {
1826
+ name: "template",
1827
+ type: "string",
1828
+ description: "Start from this template (`agentphoto templates list`)."
1829
+ },
1830
+ {
1831
+ name: "title",
1832
+ type: "string",
1833
+ description: "Document title."
1834
+ },
1835
+ {
1836
+ name: "name",
1837
+ type: "string",
1838
+ description: "Project name (default: the folder name)."
1839
+ },
1840
+ {
1841
+ name: "force",
1842
+ type: "boolean",
1843
+ description: "Overwrite an existing project in the folder."
1844
+ }
1845
+ ],
1846
+ async run({ io, options, positionals }) {
1847
+ const dir = resolve(positional(positionals, 0, "project folder", "new <dir> [--image <photo>]"));
1848
+ const force = boolOpt(options, "force");
1849
+ if (!force && existsSync(resolve(dir, "photo.json"))) throw new CliError("conflict", `${dir} is already an AgentPhoto project (photo.json exists).`, "Work on it with `--project <dir>` (`agentphoto info --project …`), pick another folder, or pass --force to overwrite it.");
1850
+ if (!force && existsSync(dir) && readdirSync(dir).filter((f) => !f.startsWith(".")).length) throw new CliError("conflict", `${dir} exists and is not empty.`, "Pick a new or empty folder for the project (or --force).");
1851
+ const image = strOpt(options, "image");
1852
+ if (image && !/^https?:\/\//.test(image) && !existsSync(resolve(image))) throw new CliError("notFound", `${image} does not exist.`, "Give the path of a local image (JPEG, PNG, WebP…) or an http(s) URL.");
1853
+ const fs = new NodeFs(dir);
1854
+ const r = await tool(fs, "project_create", {
1855
+ name: strOpt(options, "name") ?? basename(dir),
1856
+ ...strOpt(options, "title") ? { title: strOpt(options, "title") } : {},
1857
+ ...image ? { image: /^https?:\/\//.test(image) ? image : resolve(image) } : {},
1858
+ ...strOpt(options, "size") ? { size: strOpt(options, "size") } : {},
1859
+ ...numOpt(options, "width") !== void 0 ? { width: numOpt(options, "width") } : {},
1860
+ ...numOpt(options, "height") !== void 0 ? { height: numOpt(options, "height") } : {},
1861
+ ...strOpt(options, "background") !== void 0 ? { background: paintValue(strOpt(options, "background")) } : {},
1862
+ ...strOpt(options, "template") ? { template: strOpt(options, "template") } : {},
1863
+ ...force ? { force: true } : {}
1864
+ });
1865
+ const files = await fs.list();
1866
+ const { canvas, layers } = r.summary;
1867
+ printResult(io, {
1868
+ dir,
1869
+ manifest: r.manifest,
1870
+ canvas,
1871
+ layers,
1872
+ files,
1873
+ issues: r.issues
1874
+ }, () => [`Created ${dir} (${canvas.width}×${canvas.height}${strOpt(options, "template") ? `, template ${strOpt(options, "template")}` : ""}; layers: ${layers.map((l) => l.id).join(", ") || "none"}).`, `Next: agentphoto render --project ${dir} · agentphoto analyze --project ${dir}`].join("\n"));
1875
+ }
1876
+ };
1877
+ var infoCommand = {
1878
+ name: "info",
1879
+ usage: "info [--project <dir>]",
1880
+ summary: "Project overview: manifest, document summary (canvas, layers top → bottom), issue counts, assets and the latest renders / exports.",
1881
+ options: [PROJECT_OPTION],
1882
+ async run({ io, options }) {
1883
+ const fs = projectFs(options);
1884
+ const r = await tool(fs, "project_info", {});
1885
+ const files = await fs.list();
1886
+ const data = {
1887
+ dir: fs.root,
1888
+ ...r,
1889
+ assets: files.filter((f) => f.startsWith("assets/") && f !== "assets/manifest.json").length,
1890
+ renders: files.filter((f) => f.startsWith("renders/")).map((f) => absPath(fs, f)),
1891
+ exports: files.filter((f) => f.startsWith("dist/")).map((f) => absPath(fs, f))
1892
+ };
1893
+ printResult(io, data, () => [
1894
+ `${r.manifest.title ?? r.manifest.name} (${r.manifest.name}) — ${fs.root}`,
1895
+ `Canvas ${r.summary.canvas.width}×${r.summary.canvas.height}, background ${r.summary.canvas.background} · ${r.counts.errors} errors, ${r.counts.warnings} warnings`,
1896
+ table(r.summary.layers, [
1897
+ "id",
1898
+ "type",
1899
+ "detail"
1900
+ ]),
1901
+ `Assets: ${data.assets} · Renders: ${data.renders.length} · Exports: ${data.exports.length}`
1902
+ ].join("\n"));
1903
+ }
1904
+ };
1905
+ // agent/render/browser.ts
1906
+ var browser_exports = /* @__PURE__ */ __exportAll({
1907
+ browserVersion: () => browserVersion,
1908
+ findBrowser: () => findBrowser,
1909
+ noBrowserError: () => noBrowserError
1910
+ });
1911
+ var realDeps = () => ({
1912
+ platform: process.platform,
1913
+ env: process.env,
1914
+ home: homedir(),
1915
+ exists: (p) => existsSync(p),
1916
+ readdir: (p) => {
1917
+ try {
1918
+ return readdirSync(p);
1919
+ } catch {
1920
+ return [];
1921
+ }
1922
+ }
1923
+ });
1924
+ function browserCandidates(deps) {
1925
+ const { platform, env, home } = deps;
1926
+ const out = [];
1927
+ const sys = (name, path) => out.push({
1928
+ name,
1929
+ path,
1930
+ source: "system"
1931
+ });
1932
+ if (platform === "darwin") for (const root of ["/Applications", join(home, "Applications")]) {
1933
+ sys("Google Chrome", `${root}/Google Chrome.app/Contents/MacOS/Google Chrome`);
1934
+ sys("Chromium", `${root}/Chromium.app/Contents/MacOS/Chromium`);
1935
+ sys("Google Chrome Canary", `${root}/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary`);
1936
+ sys("Microsoft Edge", `${root}/Microsoft Edge.app/Contents/MacOS/Microsoft Edge`);
1937
+ sys("Brave", `${root}/Brave Browser.app/Contents/MacOS/Brave Browser`);
1938
+ }
1939
+ else if (platform === "win32") {
1940
+ const roots = [
1941
+ env.PROGRAMFILES,
1942
+ env["PROGRAMFILES(X86)"],
1943
+ env.LOCALAPPDATA
1944
+ ].filter((r) => !!r);
1945
+ for (const r of roots) {
1946
+ sys("Google Chrome", join(r, "Google", "Chrome", "Application", "chrome.exe"));
1947
+ sys("Chromium", join(r, "Chromium", "Application", "chrome.exe"));
1948
+ sys("Microsoft Edge", join(r, "Microsoft", "Edge", "Application", "msedge.exe"));
1949
+ sys("Brave", join(r, "BraveSoftware", "Brave-Browser", "Application", "brave.exe"));
1950
+ }
1951
+ } else {
1952
+ const names = [
1953
+ ["google-chrome-stable", "Google Chrome"],
1954
+ ["google-chrome", "Google Chrome"],
1955
+ ["chromium", "Chromium"],
1956
+ ["chromium-browser", "Chromium"],
1957
+ ["microsoft-edge", "Microsoft Edge"],
1958
+ ["microsoft-edge-stable", "Microsoft Edge"],
1959
+ ["brave-browser", "Brave"]
1960
+ ];
1961
+ const dirs = [
1962
+ ...(env.PATH ?? "").split(delimiter).filter(Boolean),
1963
+ "/usr/bin",
1964
+ "/usr/local/bin",
1965
+ "/snap/bin",
1966
+ "/opt/google/chrome"
1967
+ ];
1968
+ const seen = /* @__PURE__ */ new Set();
1969
+ for (const [bin, name] of names) for (const d of dirs) {
1970
+ const p = join(d, bin);
1971
+ if (!seen.has(p)) {
1972
+ seen.add(p);
1973
+ sys(name, p);
1974
+ }
1975
+ }
1976
+ sys("Google Chrome", "/opt/google/chrome/chrome");
1977
+ }
1978
+ const pwRoot = env.PLAYWRIGHT_BROWSERS_PATH || (platform === "darwin" ? join(home, "Library", "Caches", "ms-playwright") : platform === "win32" ? join(env.LOCALAPPDATA ?? join(home, "AppData", "Local"), "ms-playwright") : join(home, ".cache", "ms-playwright"));
1979
+ const builds = deps.readdir(pwRoot).filter((d) => /^chromium-\d+$/.test(d)).sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]));
1980
+ for (const b of builds) {
1981
+ const base = join(pwRoot, b);
1982
+ const rel = platform === "darwin" ? [
1983
+ "chrome-mac/Chromium.app/Contents/MacOS/Chromium",
1984
+ "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
1985
+ "chrome-mac/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
1986
+ "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
1987
+ ] : platform === "win32" ? ["chrome-win/chrome.exe", "chrome-win64/chrome.exe"] : ["chrome-linux/chrome", "chrome-linux64/chrome"];
1988
+ for (const r of rel) out.push({
1989
+ name: "Playwright Chromium",
1990
+ path: join(base, ...r.split("/")),
1991
+ source: "playwright"
1992
+ });
1993
+ }
1994
+ return out;
1995
+ }
1996
+ function findBrowser(deps = realDeps()) {
1997
+ const override = deps.env.AGENTPHOTO_CHROME;
1998
+ if (override) return deps.exists(override) ? {
1999
+ name: "AGENTPHOTO_CHROME",
2000
+ path: override,
2001
+ source: "env"
2002
+ } : null;
2003
+ return browserCandidates(deps).find((c) => deps.exists(c.path)) ?? null;
2004
+ }
2005
+ function noBrowserError() {
2006
+ const override = process.env.AGENTPHOTO_CHROME;
2007
+ return new CliError("no-browser", override ? `AGENTPHOTO_CHROME points at ${override}, which does not exist.` : "No Chrome, Chromium, Edge or Brave found on this computer (needed for headless renders).", override ? "Fix AGENTPHOTO_CHROME (the browser executable), or unset it to auto-detect." : "Install Google Chrome (https://www.google.com/chrome/) or run `npx playwright install chromium`, or set AGENTPHOTO_CHROME to a Chromium-based browser executable. `agentphoto doctor` re-checks.");
2008
+ }
2009
+ function requireBrowser() {
2010
+ const b = findBrowser();
2011
+ if (!b) throw noBrowserError();
2012
+ return b;
2013
+ }
2014
+ function browserVersion(path) {
2015
+ if (process.platform === "win32") return Promise.resolve(null);
2016
+ return new Promise((resolve) => {
2017
+ execFile(path, ["--version"], { timeout: 1e4 }, (err, stdout) => resolve(err ? null : stdout.trim() || null));
2018
+ });
2019
+ }
2020
+ var HEADLESS_ARGS = [
2021
+ "--headless=new",
2022
+ "--use-angle=swiftshader",
2023
+ "--enable-unsafe-swiftshader",
2024
+ "--ignore-gpu-blocklist",
2025
+ "--remote-debugging-port=0",
2026
+ "--no-first-run",
2027
+ "--no-default-browser-check",
2028
+ "--hide-scrollbars",
2029
+ "--mute-audio",
2030
+ "--disable-extensions",
2031
+ "--disable-sync",
2032
+ "--disable-background-networking",
2033
+ "--disable-component-update",
2034
+ "--disable-default-apps",
2035
+ "--disable-background-timer-throttling",
2036
+ "--disable-renderer-backgrounding",
2037
+ "--disable-backgrounding-occluded-windows",
2038
+ "--autoplay-policy=no-user-gesture-required"
2039
+ ];
2040
+ function launchBrowser(info, opts = {}) {
2041
+ sweepStaleProfiles();
2042
+ const profileDir = mkdtempSync(join(tmpdir(), PROFILE_PREFIX));
2043
+ const args = [
2044
+ ...HEADLESS_ARGS,
2045
+ `--user-data-dir=${profileDir}`,
2046
+ ...isRoot() ? ["--no-sandbox"] : [],
2047
+ ...opts.extraArgs ?? [],
2048
+ "about:blank"
2049
+ ];
2050
+ const child = spawn(info.path, args, { stdio: [
2051
+ "ignore",
2052
+ "ignore",
2053
+ "pipe"
2054
+ ] });
2055
+ let closed = false;
2056
+ const close = async () => {
2057
+ if (closed) return;
2058
+ closed = true;
2059
+ process.off("exit", onExit);
2060
+ await killProcess(child);
2061
+ removeDir(profileDir);
2062
+ };
2063
+ const onExit = () => {
2064
+ child.kill("SIGKILL");
2065
+ removeDir(profileDir);
2066
+ };
2067
+ process.once("exit", onExit);
2068
+ return new Promise((resolve, reject) => {
2069
+ let stderr = "";
2070
+ const fail = (message) => {
2071
+ clearTimeout(timer);
2072
+ close().finally(() => reject(new CliError("browser-launch", message, `Could not start ${info.name} (${info.path}) headless. Check it opens normally, close crash dialogs, or point AGENTPHOTO_CHROME at another Chromium-based browser. Stderr tail: ${stderr.trim().split("\n").slice(-3).join(" | ") || "(empty)"}`)));
2073
+ };
2074
+ const timer = setTimeout(() => fail(`${info.name} did not report its DevTools endpoint within ${Math.round((opts.timeoutMs ?? 2e4) / 1e3)} s.`), opts.timeoutMs ?? 2e4);
2075
+ child.on("error", (e) => fail(`Failed to start the browser: ${e.message}`));
2076
+ child.on("exit", (code) => {
2077
+ if (!wsFound) fail(`${info.name} exited (code ${code}) before it was ready.`);
2078
+ });
2079
+ let wsFound = false;
2080
+ child.stderr.setEncoding("utf8");
2081
+ child.stderr.on("data", (chunk) => {
2082
+ if (wsFound) return;
2083
+ stderr += chunk;
2084
+ const m = /DevTools listening on (ws:\/\/\S+)/.exec(stderr);
2085
+ if (m) {
2086
+ wsFound = true;
2087
+ clearTimeout(timer);
2088
+ child.stderr.resume();
2089
+ resolve({
2090
+ info,
2091
+ wsUrl: m[1],
2092
+ process: child,
2093
+ profileDir,
2094
+ close
2095
+ });
2096
+ }
2097
+ });
2098
+ });
2099
+ }
2100
+ function isRoot() {
2101
+ return typeof process.getuid === "function" && process.getuid() === 0;
2102
+ }
2103
+ function killProcess(child) {
2104
+ return new Promise((resolve) => {
2105
+ if (child.exitCode !== null || child.signalCode !== null) return resolve();
2106
+ const done = () => {
2107
+ clearTimeout(hard);
2108
+ resolve();
2109
+ };
2110
+ child.once("exit", done);
2111
+ try {
2112
+ child.kill("SIGTERM");
2113
+ } catch {}
2114
+ const hard = setTimeout(() => {
2115
+ try {
2116
+ child.kill("SIGKILL");
2117
+ } catch {}
2118
+ setTimeout(resolve, 200);
2119
+ }, 2e3);
2120
+ });
2121
+ }
2122
+ var PROFILE_PREFIX = "agentphoto-chrome-";
2123
+ var STALE_PROFILE_MS = 864e5;
2124
+ function sweepStaleProfiles() {
2125
+ try {
2126
+ const now = Date.now();
2127
+ for (const name of readdirSync(tmpdir())) {
2128
+ if (!name.startsWith(PROFILE_PREFIX)) continue;
2129
+ const dir = join(tmpdir(), name);
2130
+ if (now - statSync(dir).mtimeMs > STALE_PROFILE_MS) removeDir(dir);
2131
+ }
2132
+ } catch {}
2133
+ }
2134
+ function removeDir(dir) {
2135
+ try {
2136
+ rmSync(dir, {
2137
+ recursive: true,
2138
+ force: true,
2139
+ maxRetries: 5,
2140
+ retryDelay: 100
2141
+ });
2142
+ } catch {}
2143
+ }
2144
+ // agent/render/cdp.ts
2145
+ var DEFAULT_TIMEOUT_MS = Number(process.env.AGENTPHOTO_CDP_TIMEOUT_MS) || 6e4;
2146
+ var CdpError = class extends Error {
2147
+ method;
2148
+ name = "CdpError";
2149
+ constructor(method, message) {
2150
+ super(`${method}: ${message}`);
2151
+ this.method = method;
2152
+ }
2153
+ };
2154
+ var CdpClient = class CdpClient {
2155
+ ws;
2156
+ nextId = 1;
2157
+ pending = /* @__PURE__ */ new Map();
2158
+ handlers = /* @__PURE__ */ new Map();
2159
+ closed = false;
2160
+ constructor(ws) {
2161
+ this.ws = ws;
2162
+ ws.addEventListener("message", (ev) => this.onMessage(String(ev.data)));
2163
+ ws.addEventListener("close", () => this.onClose());
2164
+ ws.addEventListener("error", () => this.onClose());
2165
+ }
2166
+ static connect(url, timeoutMs = 1e4) {
2167
+ const WS = globalThis.WebSocket;
2168
+ if (!WS) return Promise.reject(new CliError("node-too-old", `Headless renders need Node 22 or newer (global WebSocket); this is Node ${process.versions.node}.`, "Upgrade Node (https://nodejs.org) — `agentphoto doctor` checks it."));
2169
+ return new Promise((resolve, reject) => {
2170
+ const ws = new WS(url);
2171
+ const timer = setTimeout(() => {
2172
+ ws.close();
2173
+ reject(new CliError("cdp-connect", `Could not connect to the browser DevTools endpoint (${url}).`, "Retry; if it persists run `agentphoto doctor`."));
2174
+ }, timeoutMs);
2175
+ ws.addEventListener("open", () => {
2176
+ clearTimeout(timer);
2177
+ resolve(new CdpClient(ws));
2178
+ });
2179
+ ws.addEventListener("error", () => {
2180
+ clearTimeout(timer);
2181
+ reject(new CliError("cdp-connect", `Could not connect to the browser DevTools endpoint (${url}).`, "Retry; if it persists run `agentphoto doctor`."));
2182
+ });
2183
+ });
2184
+ }
2185
+ onMessage(text) {
2186
+ let msg;
2187
+ try {
2188
+ msg = JSON.parse(text);
2189
+ } catch {
2190
+ return;
2191
+ }
2192
+ if (typeof msg.id === "number") {
2193
+ const p = this.pending.get(msg.id);
2194
+ if (!p) return;
2195
+ this.pending.delete(msg.id);
2196
+ if (msg.error) p.reject(new CdpError(p.method, msg.error.message));
2197
+ else p.resolve(msg.result ?? {});
2198
+ return;
2199
+ }
2200
+ if (msg.method) {
2201
+ const key = msg.sessionId ? `${msg.sessionId}:${msg.method}` : msg.method;
2202
+ for (const h of this.handlers.get(key) ?? []) h(msg.params ?? {});
2203
+ }
2204
+ }
2205
+ onClose() {
2206
+ if (this.closed) return;
2207
+ this.closed = true;
2208
+ for (const p of this.pending.values()) p.reject(new CdpError(p.method, "connection closed"));
2209
+ this.pending.clear();
2210
+ }
2211
+ rawSend(method, params = {}, sessionId, timeoutMs = DEFAULT_TIMEOUT_MS) {
2212
+ if (this.closed) return Promise.reject(new CdpError(method, "connection closed"));
2213
+ const id = this.nextId++;
2214
+ return new Promise((resolve, reject) => {
2215
+ const timer = setTimeout(() => {
2216
+ this.pending.delete(id);
2217
+ reject(new CdpError(method, `no answer within ${Math.round(timeoutMs / 1e3)} s`));
2218
+ }, timeoutMs);
2219
+ this.pending.set(id, {
2220
+ method,
2221
+ resolve: (v) => {
2222
+ clearTimeout(timer);
2223
+ resolve(v);
2224
+ },
2225
+ reject: (e) => {
2226
+ clearTimeout(timer);
2227
+ reject(e);
2228
+ }
2229
+ });
2230
+ this.ws.send(JSON.stringify({
2231
+ id,
2232
+ method,
2233
+ params,
2234
+ ...sessionId ? { sessionId } : {}
2235
+ }));
2236
+ });
2237
+ }
2238
+ rawOn(key, handler) {
2239
+ let set = this.handlers.get(key);
2240
+ if (!set) this.handlers.set(key, set = /* @__PURE__ */ new Set());
2241
+ set.add(handler);
2242
+ return () => set.delete(handler);
2243
+ }
2244
+ send(method, params, timeoutMs) {
2245
+ return this.rawSend(method, params, void 0, timeoutMs);
2246
+ }
2247
+ on(event, handler) {
2248
+ return this.rawOn(event, handler);
2249
+ }
2250
+ waitFor(event, predicate, timeoutMs = 3e4) {
2251
+ return waitForEvent(this, event, predicate, timeoutMs);
2252
+ }
2253
+ session(sessionId) {
2254
+ return new CdpSession(this, sessionId);
2255
+ }
2256
+ async newPage() {
2257
+ const { targetId } = await this.send("Target.createTarget", { url: "about:blank" });
2258
+ const { sessionId } = await this.send("Target.attachToTarget", {
2259
+ targetId,
2260
+ flatten: true
2261
+ });
2262
+ const s = this.session(sessionId);
2263
+ s.targetId = targetId;
2264
+ return s;
2265
+ }
2266
+ close() {
2267
+ this.onClose();
2268
+ try {
2269
+ this.ws.close();
2270
+ } catch {}
2271
+ }
2272
+ };
2273
+ var CdpSession = class {
2274
+ client;
2275
+ sessionId;
2276
+ targetId;
2277
+ constructor(client, sessionId) {
2278
+ this.client = client;
2279
+ this.sessionId = sessionId;
2280
+ }
2281
+ send(method, params, timeoutMs) {
2282
+ return this.client.rawSend(method, params, this.sessionId, timeoutMs);
2283
+ }
2284
+ on(event, handler) {
2285
+ return this.client.rawOn(`${this.sessionId}:${event}`, handler);
2286
+ }
2287
+ waitFor(event, predicate, timeoutMs = 3e4) {
2288
+ return waitForEvent(this, event, predicate, timeoutMs);
2289
+ }
2290
+ async evaluate(expression, timeoutMs = DEFAULT_TIMEOUT_MS) {
2291
+ const r = await this.send("Runtime.evaluate", {
2292
+ expression,
2293
+ awaitPromise: true,
2294
+ returnByValue: true
2295
+ }, timeoutMs);
2296
+ if (r.exceptionDetails) throw new CdpError("Runtime.evaluate", r.exceptionDetails.exception?.description ?? r.exceptionDetails.text ?? "exception");
2297
+ return r.result.value;
2298
+ }
2299
+ };
2300
+ function waitForEvent(target, event, predicate, timeoutMs) {
2301
+ return new Promise((resolve, reject) => {
2302
+ const timer = setTimeout(() => {
2303
+ off();
2304
+ reject(new CdpError(event, `event not received within ${Math.round(timeoutMs / 1e3)} s`));
2305
+ }, timeoutMs);
2306
+ const off = target.on(event, (p) => {
2307
+ if (predicate && !predicate(p)) return;
2308
+ clearTimeout(timer);
2309
+ off();
2310
+ resolve(p);
2311
+ });
2312
+ });
2313
+ }
2314
+ // agent/render/page.ts
2315
+ var ENGINE_PAGE = "/__engine.html";
2316
+ var PROGRESS_TAG = "[agentphoto:progress]";
2317
+ function enginePageHtml(opts) {
2318
+ const json = (v) => JSON.stringify(v).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
2319
+ return `<!doctype html>
2320
+ <html><head><meta charset="utf-8"><title>AgentPhoto engine</title></head>
2321
+ <body><script type="module">
2322
+ try {
2323
+ await import(${json(opts.engineUrl ?? "/__engine/agentphoto-engine.js")});
2324
+ const ai = {
2325
+ remoteHost: location.origin + ${json(opts.modelsBase ?? "/__models/")},
2326
+ wasmPaths: ${json(opts.wasmPaths ?? "/__engine/ort/")},
2327
+ onProgress: (p) => console.log(${json(PROGRESS_TAG)} + " " + JSON.stringify(p)),
2328
+ };
2329
+ await window.agentphoto.init({ assetBase: ${json(opts.assetBase ?? "/project/")}, libraryBase: ${json(opts.libraryBase ?? "/__library/")}, library: ${json(opts.library)}, ai });
2330
+ window.__agentphotoReady = true;
2331
+ } catch (e) {
2332
+ window.__agentphotoError = String((e && e.stack) || e);
2333
+ }
2334
+ <\/script></body></html>
2335
+ `;
2336
+ }
2337
+ // agent/render/session.ts
2338
+ var session_exports = /* @__PURE__ */ __exportAll({
2339
+ EngineSession: () => EngineSession,
2340
+ closeEngineSessions: () => closeEngineSessions,
2341
+ decodeImage: () => decodeImage
2342
+ });
2343
+ var AI_METHODS = /* @__PURE__ */ new Set(["backgroundMask", "segmentMask"]);
2344
+ var CALL_TIMEOUT_MS = Number(process.env.AGENTPHOTO_CDP_TIMEOUT_MS) || 18e4;
2345
+ var AI_TIMEOUT_MS = Math.max(CALL_TIMEOUT_MS, 9e5);
2346
+ var READY_TIMEOUT_MS = 3e4;
2347
+ function decodeImage(r) {
2348
+ const { base64, errors, ...rest } = r;
2349
+ return {
2350
+ ...rest,
2351
+ bytes: new Uint8Array(Buffer.from(base64, "base64")),
2352
+ ...errors?.length ? { errors } : {}
2353
+ };
2354
+ }
2355
+ var EngineSession = class {
2356
+ projectDir;
2357
+ live = null;
2358
+ stamps = /* @__PURE__ */ new Map();
2359
+ log;
2360
+ consoleErrors = [];
2361
+ progress = {
2362
+ label: "",
2363
+ pct: -1,
2364
+ at: 0
2365
+ };
2366
+ constructor(projectDir, opts = {}) {
2367
+ this.projectDir = resolve(projectDir);
2368
+ this.log = opts.log ?? ((m) => void process.stderr.write(`${m}\n`));
2369
+ }
2370
+ get started() {
2371
+ return this.live !== null;
2372
+ }
2373
+ start() {
2374
+ if (!engineBuilt()) return Promise.reject(new CliError("engine-missing", `The engine build is missing (${join(engineDir(), "agentphoto-engine.js")}).`, "Use the npm package (it ships dist/engine), or run `npm run build:engine` in a clone. AGENTPHOTO_DIST can point at another dist/ folder."));
2375
+ let info;
2376
+ try {
2377
+ info = requireBrowser();
2378
+ } catch (e) {
2379
+ return Promise.reject(e);
2380
+ }
2381
+ return (async () => {
2382
+ const html = enginePageHtml({ library: readLibraryIndex() });
2383
+ const server = await startLocalServer({
2384
+ mounts: {
2385
+ "/__engine/": engineDir(),
2386
+ "/__library/": libraryDir(),
2387
+ "/project/": this.projectDir
2388
+ },
2389
+ routes: [(_req, res, url) => url.pathname === "/__engine.html" ? (sendText(res, 200, html, "text/html; charset=utf-8"), true) : false, modelsRoute({ log: this.log })]
2390
+ });
2391
+ let browser = null;
2392
+ try {
2393
+ browser = await launchBrowser(info);
2394
+ const client = await CdpClient.connect(browser.wsUrl);
2395
+ const page = await client.newPage();
2396
+ const live = {
2397
+ browser,
2398
+ client,
2399
+ page,
2400
+ server,
2401
+ dead: false
2402
+ };
2403
+ const kill = () => {
2404
+ live.dead = true;
2405
+ };
2406
+ browser.process.once("exit", kill);
2407
+ page.on("Inspector.targetCrashed", kill);
2408
+ page.on("Runtime.consoleAPICalled", (e) => this.onConsole(e));
2409
+ page.on("Runtime.exceptionThrown", (e) => this.remember(`exception: ${JSON.stringify(e.exceptionDetails ?? e).slice(0, 400)}`));
2410
+ await page.send("Runtime.enable");
2411
+ await page.send("Inspector.enable").catch(() => void 0);
2412
+ await page.send("Page.enable");
2413
+ await page.send("Page.navigate", { url: `${server.url}${ENGINE_PAGE}` });
2414
+ const t0 = Date.now();
2415
+ for (;;) {
2416
+ const state = await page.evaluate("window.__agentphotoReady ? 1 : window.__agentphotoError ? String(window.__agentphotoError) : 0", 1e4).catch(() => 0);
2417
+ if (state === 1) break;
2418
+ if (typeof state === "string") throw new CliError("engine-init", `The engine page failed to start: ${state.split("\n")[0]}`, "Rebuild the engine (`npm run build:engine` in a clone) or reinstall the package; `agentphoto doctor` checks the setup.");
2419
+ if (Date.now() - t0 > READY_TIMEOUT_MS) throw new CliError("engine-init", `The engine page did not start within ${READY_TIMEOUT_MS / 1e3} s.${this.consoleErrors.length ? ` Console: ${this.consoleErrors.slice(-3).join(" | ")}` : ""}`, "Retry once; then run `agentphoto doctor`.");
2420
+ await new Promise((r) => setTimeout(r, 100));
2421
+ }
2422
+ this.stamps.clear();
2423
+ return live;
2424
+ } catch (e) {
2425
+ await browser?.close().catch(() => void 0);
2426
+ await server.close().catch(() => void 0);
2427
+ throw e;
2428
+ }
2429
+ })();
2430
+ }
2431
+ remember(line) {
2432
+ this.consoleErrors.push(line);
2433
+ if (this.consoleErrors.length > 20) this.consoleErrors.shift();
2434
+ if (process.env.AGENTPHOTO_DEBUG) this.log(`[engine] ${line}`);
2435
+ }
2436
+ onConsole(e) {
2437
+ const text = (e.args ?? []).map((a) => typeof a.value === "string" ? a.value : a.value !== void 0 ? JSON.stringify(a.value) : a.description ?? "").join(" ");
2438
+ if (text.startsWith("[agentphoto:progress]")) {
2439
+ let p;
2440
+ try {
2441
+ p = JSON.parse(text.slice(PROGRESS_TAG.length));
2442
+ } catch {
2443
+ return;
2444
+ }
2445
+ this.onProgress(p);
2446
+ return;
2447
+ }
2448
+ if (e.type === "error" || e.type === "warning") this.remember(`${e.type}: ${text.slice(0, 400)}`);
2449
+ else if (process.env.AGENTPHOTO_DEBUG) this.log(`[engine] ${text.slice(0, 400)}`);
2450
+ }
2451
+ onProgress(p) {
2452
+ const label = p.label ?? "";
2453
+ const phase = label.replace(/\s*\(\d+\s*%\)$/, "");
2454
+ const pct = Math.round((p.progress ?? 0) * 100);
2455
+ const now = Date.now();
2456
+ const last = this.progress;
2457
+ const samePhase = last.label === phase;
2458
+ if (samePhase && pct < 100 && pct - last.pct < 10 && now - last.at < 2e3) return;
2459
+ if (samePhase && pct === last.pct) return;
2460
+ if (/ready$/.test(phase) && samePhase) return;
2461
+ this.progress = {
2462
+ label: phase,
2463
+ pct,
2464
+ at: now
2465
+ };
2466
+ this.log(label);
2467
+ }
2468
+ async ensure() {
2469
+ if (this.live) {
2470
+ const live = await this.live.catch(() => null);
2471
+ if (live && !live.dead) return live;
2472
+ if (live) await this.dispose(live);
2473
+ this.live = null;
2474
+ }
2475
+ this.live = this.start();
2476
+ this.live.catch(() => this.live = null);
2477
+ return this.live;
2478
+ }
2479
+ async dispose(live) {
2480
+ live.dead = true;
2481
+ live.client.close();
2482
+ await live.browser.close().catch(() => void 0);
2483
+ await live.server.close().catch(() => void 0);
2484
+ }
2485
+ async sync(live, doc) {
2486
+ if (!doc || typeof doc !== "object" || !Array.isArray(doc.layers)) return;
2487
+ const changed = [];
2488
+ for (const { path } of referencedFiles(doc)) {
2489
+ if (!path || path.startsWith("library:") || /^(blob:|data:)/.test(path)) continue;
2490
+ let stamp = "missing";
2491
+ try {
2492
+ const s = statSync(join(this.projectDir, path));
2493
+ stamp = `${s.size}:${s.mtimeMs}`;
2494
+ } catch {}
2495
+ const prev = this.stamps.get(path);
2496
+ if (prev !== void 0 && prev !== stamp) changed.push(path);
2497
+ this.stamps.set(path, stamp);
2498
+ }
2499
+ if (changed.length) await live.page.evaluate(`window.agentphoto.invalidate ? window.agentphoto.invalidate(${JSON.stringify(changed)}) : 0`, 1e4).catch(() => void 0);
2500
+ }
2501
+ async call(method, ...args) {
2502
+ for (let attempt = 0;; attempt++) {
2503
+ const live = await this.ensure();
2504
+ try {
2505
+ await this.sync(live, args[0]);
2506
+ const expr = `window.agentphoto.${method}(...${JSON.stringify(args)})`;
2507
+ return await live.page.evaluate(expr, AI_METHODS.has(method) ? AI_TIMEOUT_MS : CALL_TIMEOUT_MS);
2508
+ } catch (e) {
2509
+ if (live.dead || e instanceof CdpError && /connection closed|crashed|Target closed|No target|Session/i.test(e.message)) {
2510
+ await this.dispose(live);
2511
+ this.live = null;
2512
+ if (attempt === 0) {
2513
+ this.log("[engine] the headless browser stopped — restarting it");
2514
+ continue;
2515
+ }
2516
+ throw new CliError("engine-crashed", `The headless browser stopped during ${method}.`, "Retry; a very large image may exhaust memory (reduce the size), otherwise run `agentphoto doctor`.");
2517
+ }
2518
+ throw this.engineError(method, e);
2519
+ }
2520
+ }
2521
+ }
2522
+ engineError(method, e) {
2523
+ if (e instanceof CliError) return e;
2524
+ const raw = e instanceof Error ? e.message : String(e);
2525
+ const message = raw.replace(/^Runtime\.evaluate:\s*/, "").split("\n")[0].replace(/^(Uncaught\s+)?(Error:\s*)?/, "");
2526
+ if (/no answer within/.test(raw)) return new CliError("engine-timeout", `The engine did not answer ${method} in time.`, "Retry (a model download may be slow); AGENTPHOTO_CDP_TIMEOUT_MS raises the limit.");
2527
+ const ai = AI_METHODS.has(method);
2528
+ if (ai && /fetch|network|HTTP|Failed to load|download|onnx|wasm|protobuf/i.test(raw)) return new CliError("model-unavailable", `The AI model could not be loaded: ${message}`, "The first use downloads the model once from huggingface.co: check the network, then retry (`agentphoto models pull <id>` pre-downloads; `agentphoto models list` shows the cache).", 1, this.consoleErrors.length ? { console: this.consoleErrors.slice(-5) } : void 0);
2529
+ return new CliError("engine", `${method} failed in the engine: ${message}`, ai ? "Check the layer is an image with visible pixels; `agentphoto layer list` shows the layers." : "Check the document (`agentphoto check`): a missing file or an invalid layer is the usual cause.", 1, this.consoleErrors.length ? { console: this.consoleErrors.slice(-5) } : void 0);
2530
+ }
2531
+ async close() {
2532
+ const p = this.live;
2533
+ this.live = null;
2534
+ if (!p) return;
2535
+ const live = await p.catch(() => null);
2536
+ if (live) await this.dispose(live);
2537
+ }
2538
+ };
2539
+ var sessions = /* @__PURE__ */ new Map();
2540
+ function engineSession(projectDir) {
2541
+ const key = resolve(projectDir);
2542
+ let s = sessions.get(key);
2543
+ if (!s) sessions.set(key, s = new EngineSession(key));
2544
+ return s;
2545
+ }
2546
+ async function closeEngineSessions() {
2547
+ const all = [...sessions.values()];
2548
+ sessions.clear();
2549
+ await Promise.all(all.map((s) => s.close()));
2550
+ }
2551
+ function sessionEngineHost(session) {
2552
+ return {
2553
+ async render(doc, opts) {
2554
+ return decodeImage(await session().call("render", doc, opts));
2555
+ },
2556
+ async exportImage(doc, job) {
2557
+ return decodeImage(await session().call("exportImage", doc, job));
2558
+ },
2559
+ analyze(doc, opts) {
2560
+ return session().call("analyze", doc, opts);
2561
+ },
2562
+ async backgroundMask(doc, id, opts) {
2563
+ return decodeImage(await session().call("backgroundMask", doc, id, opts));
2564
+ },
2565
+ async segmentMask(doc, id, prompt, opts) {
2566
+ return decodeImage(await session().call("segmentMask", doc, id, prompt, opts));
2567
+ },
2568
+ async colorRangeMask(doc, id, opts) {
2569
+ return decodeImage(await session().call("colorRangeMask", doc, id, opts));
2570
+ },
2571
+ layerBoxes(doc) {
2572
+ return session().call("layerBoxes", doc);
2573
+ }
2574
+ };
2575
+ }
2576
+ // agent/aiHost.ts
2577
+ var aiHost_exports = /* @__PURE__ */ __exportAll({ callTool: () => callTool });
2578
+ function nodeHost(fs) {
2579
+ return {
2580
+ engine: sessionEngineHost(() => {
2581
+ if (!fs) throw new CliError("no-project", "Pixel tools need a project folder.", "Pass --project <dir>.");
2582
+ return engineSession(fs.root);
2583
+ }),
2584
+ library: libraryProvider(),
2585
+ templates: {
2586
+ index: readTemplatesIndex(),
2587
+ files: async (id) => readTemplateFiles(id)
2588
+ },
2589
+ async readLocalFile(path) {
2590
+ const abs = isAbsolute(path) ? path : resolve(path);
2591
+ try {
2592
+ return new Uint8Array(readFileSync(abs));
2593
+ } catch {
2594
+ throw new CliError("notFound", `Cannot read ${abs}.`, "Give the path of an existing local image file (absolute, or relative to the current directory).");
2595
+ }
2596
+ }
2597
+ };
2598
+ }
2599
+ function toolContext(fs) {
2600
+ return {
2601
+ fs,
2602
+ fetch,
2603
+ host: nodeHost(fs)
2604
+ };
2605
+ }
2606
+ async function listTools(opts = {}) {
2607
+ const { listAiTools } = await import("./chunks/tools-Dnh8g6F9.mjs");
2608
+ return listAiTools(nodeHost(null), opts).map((t) => ({
2609
+ name: t.name,
2610
+ description: t.description,
2611
+ inputSchema: t.inputSchema,
2612
+ mutating: !!t.mutating,
2613
+ needsEngine: !!t.needsEngine
2614
+ }));
2615
+ }
2616
+ async function callTool(fs, name, input) {
2617
+ const { callAiTool } = await import("./chunks/tools-Dnh8g6F9.mjs");
2618
+ return callAiTool(toolContext(fs), name, input);
2619
+ }
2620
+ async function previewImages(name, result, root) {
2621
+ const { resultImages } = await import("./chunks/tools-Dnh8g6F9.mjs");
2622
+ const out = [];
2623
+ for (const file of resultImages(name, result)) try {
2624
+ const mimeType = /\.jpe?g$/i.test(file) ? "image/jpeg" : /\.webp$/i.test(file) ? "image/webp" : "image/png";
2625
+ out.push({
2626
+ data: readFileSync(resolve(root, file)).toString("base64"),
2627
+ mimeType
2628
+ });
2629
+ } catch {}
2630
+ return out;
2631
+ }
2632
+ // agent/watch.ts
2633
+ var IGNORED = /^(renders|dist|node_modules|\.git)(\/|$)|(^|\/)\.DS_Store$|~$|\.swp$/;
2634
+ function watchProject(root, onChange, debounceMs = 120) {
2635
+ const pending = /* @__PURE__ */ new Set();
2636
+ const muted = /* @__PURE__ */ new Map();
2637
+ let timer = null;
2638
+ let watcher = null;
2639
+ const flush = () => {
2640
+ timer = null;
2641
+ const paths = [...pending].filter((p) => !isDir(`${root}/${p}`) && !(muted.has(p) && muted.get(p) === stamp(`${root}/${p}`)));
2642
+ pending.clear();
2643
+ if (paths.length) onChange(paths.sort());
2644
+ };
2645
+ try {
2646
+ watcher = watch(root, { recursive: true }, (_event, filename) => {
2647
+ if (!filename) return;
2648
+ const rel = (typeof filename === "string" ? filename : String(filename)).split(sep).join("/");
2649
+ if (IGNORED.test(rel) || rel.startsWith("..") || relative(root, `${root}/${rel}`).startsWith("..")) return;
2650
+ pending.add(rel);
2651
+ if (!timer) timer = setTimeout(flush, debounceMs);
2652
+ });
2653
+ watcher.on("error", () => void 0);
2654
+ } catch {
2655
+ watcher = null;
2656
+ }
2657
+ return {
2658
+ close() {
2659
+ if (timer) clearTimeout(timer);
2660
+ watcher?.close();
2661
+ },
2662
+ ignoreWritten(paths) {
2663
+ for (const p of paths) muted.set(p, stamp(`${root}/${p}`));
2664
+ }
2665
+ };
2666
+ }
2667
+ function isDir(path) {
2668
+ try {
2669
+ return statSync(path).isDirectory();
2670
+ } catch {
2671
+ return false;
2672
+ }
2673
+ }
2674
+ function stamp(path) {
2675
+ try {
2676
+ const s = statSync(path);
2677
+ return `${s.size}:${s.mtimeMs}`;
2678
+ } catch {
2679
+ return "missing";
2680
+ }
2681
+ }
2682
+ // agent/commands/serve.ts
2683
+ function openBrowser(url) {
2684
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", [
2685
+ "/c",
2686
+ "start",
2687
+ "",
2688
+ url
2689
+ ]] : ["xdg-open", [url]];
2690
+ try {
2691
+ spawn(cmd, args, {
2692
+ stdio: "ignore",
2693
+ detached: true
2694
+ }).on("error", () => void 0).unref();
2695
+ } catch {}
2696
+ }
2697
+ function localGuard(getPort) {
2698
+ return (req, res) => {
2699
+ const port = getPort();
2700
+ const host = (req.headers.host ?? "").toLowerCase();
2701
+ const okHosts = /* @__PURE__ */ new Set([
2702
+ `127.0.0.1:${port}`,
2703
+ `localhost:${port}`,
2704
+ `[::1]:${port}`
2705
+ ]);
2706
+ if (!okHosts.has(host)) {
2707
+ sendText(res, 403, "Forbidden host");
2708
+ return true;
2709
+ }
2710
+ const origin = req.headers.origin;
2711
+ if (origin && origin !== "null") {
2712
+ let o = null;
2713
+ try {
2714
+ o = new URL(origin);
2715
+ } catch {
2716
+ o = null;
2717
+ }
2718
+ if (!o || !okHosts.has(o.host.toLowerCase())) {
2719
+ sendText(res, 403, "Forbidden origin");
2720
+ return true;
2721
+ }
2722
+ }
2723
+ return false;
2724
+ };
2725
+ }
2726
+ function sseHub() {
2727
+ const clients = /* @__PURE__ */ new Set();
2728
+ const ping = setInterval(() => {
2729
+ for (const c of clients) c.write(": ping\n\n");
2730
+ }, 2e4);
2731
+ ping.unref();
2732
+ return {
2733
+ attach(req, res) {
2734
+ res.writeHead(200, {
2735
+ "content-type": "text/event-stream; charset=utf-8",
2736
+ "cache-control": "no-store",
2737
+ connection: "keep-alive",
2738
+ "x-accel-buffering": "no"
2739
+ });
2740
+ res.write("retry: 1000\n\n");
2741
+ clients.add(res);
2742
+ req.on("close", () => clients.delete(res));
2743
+ },
2744
+ send(event, data) {
2745
+ const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
2746
+ for (const c of clients) c.write(frame);
2747
+ },
2748
+ close() {
2749
+ clearInterval(ping);
2750
+ for (const c of clients) c.end();
2751
+ clients.clear();
2752
+ },
2753
+ get size() {
2754
+ return clients.size;
2755
+ }
2756
+ };
2757
+ }
2758
+ async function listen(start, first) {
2759
+ if (first === 0) return start(0);
2760
+ for (let port = first; port < first + 20 && port <= 65535; port++) try {
2761
+ return await start(port);
2762
+ } catch (e) {
2763
+ if (e.code !== "EADDRINUSE") throw e;
2764
+ }
2765
+ throw new CliError("port-busy", `Ports ${first}-${first + 19} are all in use.`, "Pass --port <n> (0 = any free port).");
2766
+ }
2767
+ function portOpt(options, def) {
2768
+ const raw = strOpt(options, "port");
2769
+ const port = raw === void 0 ? def : Number(raw);
2770
+ if (!Number.isInteger(port) || port < 0 || port > 65535) usage(`Invalid --port: ${raw}`);
2771
+ return port;
2772
+ }
2773
+ function waitForSignal() {
2774
+ return new Promise((r) => {
2775
+ process.once("SIGINT", () => r());
2776
+ process.once("SIGTERM", () => r());
2777
+ });
2778
+ }
2779
+ async function startStudioServer(opts) {
2780
+ const hub = sseHub();
2781
+ let actualPort = 0;
2782
+ const fs = opts.project ? new NodeFs(opts.project) : null;
2783
+ const watcher = opts.project ? watchProject(opts.project, (paths) => hub.send("change", { paths })) : null;
2784
+ const noProject = (res) => sendJson(res, 404, {
2785
+ ok: false,
2786
+ error: {
2787
+ code: "no-project",
2788
+ message: "The Studio was started without a project.",
2789
+ hint: "Restart with `agentphoto studio --project <dir>`."
2790
+ }
2791
+ });
2792
+ const fail = (res, err, status) => {
2793
+ const e = toCliError(err);
2794
+ const code = status ?? (e.code === "notFound" ? 404 : e.code === "invalid-path" ? 400 : e.exitCode === 2 ? 400 : 500);
2795
+ sendJson(res, code, {
2796
+ ok: false,
2797
+ error: {
2798
+ code: e.code,
2799
+ message: e.message,
2800
+ ...e.hint ? { hint: e.hint } : {},
2801
+ ...e.details !== void 0 ? { details: e.details } : {}
2802
+ }
2803
+ });
2804
+ };
2805
+ const api = async (req, res, url) => {
2806
+ if (!url.pathname.startsWith("/api/")) return false;
2807
+ const method = req.method ?? "GET";
2808
+ try {
2809
+ if (url.pathname === "/api/info" && method === "GET") {
2810
+ let manifest = null;
2811
+ if (fs && await fs.exists("agentphoto.json")) manifest = JSON.parse(await fs.readText("agentphoto.json"));
2812
+ sendJson(res, 200, {
2813
+ ok: true,
2814
+ data: {
2815
+ version: readVersionInfo().version,
2816
+ project: fs ? {
2817
+ dir: fs.root,
2818
+ manifest,
2819
+ exists: await fs.exists("photo.json")
2820
+ } : null,
2821
+ assetBase: "/project/",
2822
+ libraryBase: "/__library/",
2823
+ engineBase: "/__engine/",
2824
+ modelsBase: "/__models/"
2825
+ }
2826
+ });
2827
+ return true;
2828
+ }
2829
+ if (url.pathname === "/api/catalog" && method === "GET") return sendJson(res, 200, {
2830
+ ok: true,
2831
+ data: CATALOG
2832
+ }), true;
2833
+ if (url.pathname === "/api/library" && method === "GET") return sendJson(res, 200, {
2834
+ ok: true,
2835
+ data: readLibraryIndex()
2836
+ }), true;
2837
+ if (url.pathname === "/api/templates" && method === "GET") return sendJson(res, 200, {
2838
+ ok: true,
2839
+ data: { templates: readTemplatesIndex() }
2840
+ }), true;
2841
+ const preview = /^\/api\/templates\/([^/]+)\/preview\.(?:jpg|png)$/.exec(url.pathname);
2842
+ if (preview && (method === "GET" || method === "HEAD")) {
2843
+ let id = "";
2844
+ try {
2845
+ id = decodeURIComponent(preview[1]);
2846
+ } catch {}
2847
+ const file = id ? templatePreviewFile(id) : null;
2848
+ if (!file) return sendJson(res, 404, {
2849
+ ok: false,
2850
+ error: {
2851
+ code: "notFound",
2852
+ message: `No preview image for template "${id}".`,
2853
+ hint: "GET /api/templates lists the templates; not every template ships a preview.jpg."
2854
+ }
2855
+ }), true;
2856
+ const bytes = readFileSync(file);
2857
+ res.writeHead(200, {
2858
+ "content-type": mimeOf(file),
2859
+ "cache-control": "no-cache",
2860
+ "x-content-type-options": "nosniff",
2861
+ "content-length": String(bytes.byteLength)
2862
+ });
2863
+ res.end(method === "HEAD" ? void 0 : bytes);
2864
+ return true;
2865
+ }
2866
+ if (url.pathname === "/api/tools" && method === "GET") return sendJson(res, 200, {
2867
+ ok: true,
2868
+ data: { tools: await listTools() }
2869
+ }), true;
2870
+ if (url.pathname === "/api/events" && method === "GET") return hub.attach(req, res), true;
2871
+ if (url.pathname === "/api/tools/call" && method === "POST") {
2872
+ if (!fs) return noProject(res), true;
2873
+ let body;
2874
+ try {
2875
+ body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
2876
+ } catch {
2877
+ return fail(res, new CliError("usage", "The body must be JSON: { name, input }.", void 0, 2), 400), true;
2878
+ }
2879
+ if (typeof body.name !== "string") return fail(res, new CliError("usage", "\"name\" (a tool name) is required.", "GET /api/tools lists them.", 2), 400), true;
2880
+ const input = body.input && typeof body.input === "object" ? body.input : {};
2881
+ const before = stamps(opts.project);
2882
+ const result = await callTool(fs, body.name, input);
2883
+ const after = stamps(opts.project);
2884
+ watcher?.ignoreWritten([...after.keys()].filter((p) => before.get(p) !== after.get(p)));
2885
+ sendJson(res, 200, {
2886
+ ok: true,
2887
+ data: result
2888
+ });
2889
+ return true;
2890
+ }
2891
+ if (url.pathname === "/api/project" || url.pathname === "/api/project/") {
2892
+ if (!fs) return noProject(res), true;
2893
+ if (method !== "GET") return sendText(res, 405, "Method not allowed"), true;
2894
+ const files = await fs.list(url.searchParams.get("prefix") ?? "");
2895
+ const withSize = await Promise.all(files.map(async (path) => ({
2896
+ path,
2897
+ size: await fs.size(path)
2898
+ })));
2899
+ sendJson(res, 200, {
2900
+ ok: true,
2901
+ data: { files: withSize }
2902
+ });
2903
+ return true;
2904
+ }
2905
+ if (url.pathname.startsWith("/api/project/")) {
2906
+ if (!fs) return noProject(res), true;
2907
+ const raw = (req.url ?? "").split("?")[0].slice(13);
2908
+ let path;
2909
+ try {
2910
+ path = decodeURIComponent(raw);
2911
+ } catch {
2912
+ return fail(res, new CliError("invalid-path", "Bad path encoding.", void 0, 2), 400), true;
2913
+ }
2914
+ if (method === "GET" || method === "HEAD") {
2915
+ const bytes = await fs.readBytes(path);
2916
+ res.writeHead(200, {
2917
+ "content-type": mimeOf(path),
2918
+ "cache-control": "no-store",
2919
+ "x-content-type-options": "nosniff",
2920
+ "content-length": String(bytes.byteLength)
2921
+ });
2922
+ res.end(method === "HEAD" ? void 0 : Buffer.from(bytes));
2923
+ return true;
2924
+ }
2925
+ if (method === "PUT") {
2926
+ const body = await readBody(req);
2927
+ await fs.writeBytes(path, new Uint8Array(body));
2928
+ watcher?.ignoreWritten([path]);
2929
+ sendJson(res, 200, {
2930
+ ok: true,
2931
+ data: {
2932
+ path,
2933
+ bytes: body.byteLength
2934
+ }
2935
+ });
2936
+ return true;
2937
+ }
2938
+ if (method === "DELETE") {
2939
+ if (!await fs.exists(path)) return fail(res, new CliError("notFound", `No file ${path}.`), 404), true;
2940
+ await fs.remove(path);
2941
+ watcher?.ignoreWritten([path]);
2942
+ sendJson(res, 200, {
2943
+ ok: true,
2944
+ data: { removed: path }
2945
+ });
2946
+ return true;
2947
+ }
2948
+ sendText(res, 405, "Method not allowed");
2949
+ return true;
2950
+ }
2951
+ sendJson(res, 404, {
2952
+ ok: false,
2953
+ error: {
2954
+ code: "notFound",
2955
+ message: `No API route ${method} ${url.pathname}.`,
2956
+ hint: "See docs/studio-api.md."
2957
+ }
2958
+ });
2959
+ return true;
2960
+ } catch (err) {
2961
+ fail(res, err);
2962
+ return true;
2963
+ }
2964
+ };
2965
+ const models = modelsRoute({ log: (m) => void process.stderr.write(`${m}\n`) });
2966
+ const studioRoot = opts.studioRoot ?? studioDir();
2967
+ const server = await listen((p) => startLocalServer({
2968
+ port: p,
2969
+ mounts: {
2970
+ "/__engine/": engineDir(),
2971
+ "/__library/": libraryDir(),
2972
+ ...opts.project ? { "/project/": opts.project } : {}
2973
+ },
2974
+ routes: [
2975
+ localGuard(() => actualPort),
2976
+ api,
2977
+ models
2978
+ ],
2979
+ fallbackRoot: studioRoot
2980
+ }), opts.port ?? 0);
2981
+ actualPort = server.port;
2982
+ return {
2983
+ ...server,
2984
+ async stop() {
2985
+ watcher?.close();
2986
+ hub.close();
2987
+ await server.close();
2988
+ }
2989
+ };
2990
+ }
2991
+ var studioCommand = {
2992
+ name: "studio",
2993
+ usage: "studio [--port <n>] [--no-open] [--project <dir>]",
2994
+ summary: "Open the Studio (visual editor: canvas, layers, inspector, filters & looks, masks, AI cut-out, export, assistant) on this computer, editing the project folder through a local API (docs/studio-api.md). Runs until stopped (Ctrl+C).",
2995
+ options: [
2996
+ PROJECT_OPTION,
2997
+ {
2998
+ name: "port",
2999
+ type: "string",
3000
+ description: "First port to try (default 4330; 0 = any free port)."
3001
+ },
3002
+ {
3003
+ name: "no-open",
3004
+ type: "boolean",
3005
+ description: "Don't open a browser."
3006
+ }
3007
+ ],
3008
+ async run({ io, options }) {
3009
+ const studio = studioDir();
3010
+ const built = existsSync(join(studio, "index.html"));
3011
+ if (!built) process.stderr.write(`[agentphoto studio] The Studio build is missing (${studio}): only the API is served. Use the npm package, or run \`npm run build:studio\` in a clone.\n`);
3012
+ const dir = projectDir(options);
3013
+ if (!existsSync(dir)) throw new CliError("notFound", `The folder ${dir} does not exist.`, `Create it first (mkdir), or create a project with \`agentphoto new ${dir}\`.`);
3014
+ const exists = existsSync(join(dir, "photo.json"));
3015
+ const server = await startStudioServer({
3016
+ project: dir,
3017
+ port: portOpt(options, 4330)
3018
+ });
3019
+ const url = `http://localhost:${server.port}/`;
3020
+ printResult(io, {
3021
+ url,
3022
+ project: dir,
3023
+ exists,
3024
+ studio: built
3025
+ }, () => `AgentPhoto Studio — ${dir}${exists ? "" : " (no project yet: create one from the start screen)"}\n${url}\nPress Ctrl+C to stop.`);
3026
+ if (!boolOpt(options, "no-open")) openBrowser(url);
3027
+ await waitForSignal();
3028
+ await server.stop();
3029
+ const { closeEngineSessions } = await Promise.resolve().then(() => session_exports);
3030
+ await closeEngineSessions();
3031
+ }
3032
+ };
3033
+ function stamps(root) {
3034
+ const out = /* @__PURE__ */ new Map();
3035
+ const walk = (dir, rel) => {
3036
+ let entries;
3037
+ try {
3038
+ entries = readdirSync(dir, { withFileTypes: true });
3039
+ } catch {
3040
+ return;
3041
+ }
3042
+ for (const e of entries) {
3043
+ const r = rel ? `${rel}/${e.name}` : e.name;
3044
+ if (e.isDirectory()) {
3045
+ if (!/^(renders|dist|node_modules|\.git)$/.test(r)) walk(join(dir, e.name), r);
3046
+ } else if (e.isFile()) try {
3047
+ const st = statSync(join(dir, e.name));
3048
+ out.set(r, `${st.size}:${st.mtimeMs}`);
3049
+ } catch {}
3050
+ }
3051
+ };
3052
+ walk(root, "");
3053
+ return out;
3054
+ }
3055
+ // agent/commands/tools.ts
3056
+ var toolsCommand = {
3057
+ name: "tools",
3058
+ usage: "tools <list|call> [<name>] [--input <json|@file|->] [--project <dir>]",
3059
+ summary: "The AI tool catalog (src/ai/tools.ts) — exactly what the MCP server and the Studio assistant expose: list the tools with their JSON schemas, or call one with a JSON input.",
3060
+ subcommands: [{
3061
+ name: "list",
3062
+ usage: "tools list",
3063
+ summary: "Tools with description, input schema, whether they write and whether they need the engine (Chrome)."
3064
+ }, {
3065
+ name: "call",
3066
+ usage: "tools call <name> --input <json|@file|->",
3067
+ summary: "Run one tool against the project.",
3068
+ writes: true
3069
+ }],
3070
+ options: [PROJECT_OPTION, {
3071
+ name: "input",
3072
+ type: "string",
3073
+ description: "call: the tool input as a JSON object, @file or - (stdin)."
3074
+ }],
3075
+ async run({ io, options, positionals }) {
3076
+ const [action = "list"] = positionals;
3077
+ if (action === "list") {
3078
+ const tools = await listTools();
3079
+ return printResult(io, { tools }, () => table(tools, [
3080
+ "name",
3081
+ "mutating",
3082
+ "needsEngine",
3083
+ "description"
3084
+ ]));
3085
+ }
3086
+ if (action === "call") {
3087
+ const name = positional(positionals, 1, "tool name", "tools call <name> --input <json>");
3088
+ const tools = await listTools();
3089
+ if (!tools.some((t) => t.name === name)) usage(`Unknown tool "${name}".`, `\`agentphoto tools list\` lists them (${tools.map((t) => t.name).join(", ")}).`);
3090
+ const input = jsonObjectOpt(options, "input") ?? {};
3091
+ const result = await callTool(new NodeFs(projectDir(options)), name, input);
3092
+ return printResult(io, {
3093
+ tool: name,
3094
+ result
3095
+ }, () => JSON.stringify(result ?? null, null, 2), { raw: true });
3096
+ }
3097
+ usage(`Unknown tools action "${action}".`, "Use list or call.");
3098
+ }
3099
+ };
3100
+ var MCP_INSTRUCTIONS = (root) => `AgentPhoto — the photo studio you can run (project: ${root}). A picture is a JSON document (photo.json: canvas + a non-destructive layer stack — image, text, shape, fill, adjustment, group — with filters, masks and effects); source photos are never modified. Workflow: doc_summary (or project_info) first; image_analyze to measure the photo (exposure, contrast, cast, sharpness — it suggests filters); then edit with filter_add, layer_add / layer_update, remove_background (local AI cut-out; the model downloads once), mask_generate, doc_patch (atomic, validated; issues come back with JSON paths and hints) — catalog_get documents filters, looks, effects, fonts and size presets; after EVERY visual change call render_preview and LOOK at the returned image (compare: true for before / after, zoom for edges and text); check before export; export writes PNG / JPEG / WebP / AVIF into dist/ (variants for several sizes). Confirm destructive changes (doc_apply removing layers, layer_remove, assets_remove, export over existing files) with the user first.`;
3101
+ var mcpCommand = {
3102
+ name: "mcp",
3103
+ usage: "mcp [--project <dir>] [--read-only]",
3104
+ summary: "Run the MCP server on stdio (JSON-RPC 2.0, protocol 2025-06-18 / 2025-03-26 / 2024-11-05): tools = the AI catalog (render_preview returns the image), resources = photo://doc, photo://summary, photo://catalog. For Claude Desktop / Claude Code / Cursor.",
3105
+ options: [PROJECT_OPTION, {
3106
+ name: "read-only",
3107
+ type: "boolean",
3108
+ description: "Expose only the tools that don't write."
3109
+ }],
3110
+ async run({ options }) {
3111
+ const readOnly = boolOpt(options, "read-only");
3112
+ const dir = projectDir(options);
3113
+ const fs = new NodeFs(dir);
3114
+ const log = (msg) => void process.stderr.write(`${msg}\n`);
3115
+ const { createMcpServer, serveStdio } = await import("./chunks/server-I0trf5tM.mjs");
3116
+ const server = createMcpServer(mcpOptions(fs, readOnly, await listTools()));
3117
+ log(`[agentphoto mcp] project ${dir}${readOnly ? " (read-only)" : ""} on stdio — ${server.toolNames().length} tools`);
3118
+ await serveStdio(server, process.stdin, (line) => process.stdout.write(line + "\n"), log);
3119
+ const { closeEngineSessions } = await Promise.resolve().then(() => session_exports);
3120
+ await closeEngineSessions();
3121
+ return 0;
3122
+ }
3123
+ };
3124
+ function mcpOptions(fs, readOnly, tools) {
3125
+ return {
3126
+ readOnly,
3127
+ tools,
3128
+ serverName: "agentphoto",
3129
+ version: readVersionInfo().version,
3130
+ instructions: MCP_INSTRUCTIONS(fs.root),
3131
+ call: (name, input) => callTool(fs, name, input),
3132
+ images: (name, result) => previewImages(name, result, fs.root),
3133
+ resources: [
3134
+ {
3135
+ uri: "photo://doc",
3136
+ name: "doc",
3137
+ title: "Document",
3138
+ description: "The project's photo.json (PhotoDoc).",
3139
+ mimeType: "application/json",
3140
+ read: async () => JSON.parse(await fs.readText("photo.json"))
3141
+ },
3142
+ {
3143
+ uri: "photo://summary",
3144
+ name: "summary",
3145
+ title: "Document summary",
3146
+ description: "Compact outline: canvas, layers top → bottom with type, box, filters, masks, effects.",
3147
+ mimeType: "application/json",
3148
+ read: async () => {
3149
+ const { getDoc, summarizeDoc } = await import("./chunks/doc-BjY_j4Su.mjs").then((n) => n.r);
3150
+ return summarizeDoc(await getDoc(fs));
3151
+ }
3152
+ },
3153
+ {
3154
+ uri: "photo://catalog",
3155
+ name: "catalog",
3156
+ title: "Catalog",
3157
+ description: "Layer types, filters (+ params), looks, effects, blend modes, shapes, fonts, size presets, AI models.",
3158
+ mimeType: "application/json",
3159
+ read: async () => CATALOG
3160
+ }
3161
+ ]
3162
+ };
3163
+ }
3164
+ // agent/commands/index.ts
3165
+ var GLOBAL_OPTIONS = [{
3166
+ name: "json",
3167
+ type: "boolean",
3168
+ description: "Print one JSON object on stdout: { ok, data } or { ok: false, error: { code, message, hint } }."
3169
+ }, {
3170
+ name: "help",
3171
+ type: "boolean",
3172
+ description: "Show the command's usage and options instead of running it."
3173
+ }];
3174
+ var COMMANDS = [
3175
+ {
3176
+ name: "help",
3177
+ usage: "help [<command>]",
3178
+ summary: "List commands with their subcommands and options (--json gives a machine-readable list).",
3179
+ options: [],
3180
+ async run({ io, positionals }) {
3181
+ const wanted = positionals[0];
3182
+ const list = wanted ? COMMANDS.filter((c) => c.name === wanted) : COMMANDS;
3183
+ if (wanted && !list.length) throw new CliError("unknown-command", `Unknown command "${wanted}".`, `Available: ${COMMANDS.map((c) => c.name).join(", ")}.`, 2);
3184
+ const { version } = readVersionInfo();
3185
+ const data = {
3186
+ name: "agentphoto",
3187
+ version,
3188
+ globalOptions: GLOBAL_OPTIONS,
3189
+ commands: list.map(({ name, summary, usage, options, subcommands, writes }) => ({
3190
+ name,
3191
+ summary,
3192
+ usage,
3193
+ options,
3194
+ ...subcommands ? { subcommands } : {},
3195
+ ...writes ? { writes } : {}
3196
+ }))
3197
+ };
3198
+ printResult(io, data, () => [
3199
+ `agentphoto ${version} — the photo studio your AI agent can run.`,
3200
+ "",
3201
+ "Usage: agentphoto <command> [options] [--json]",
3202
+ "",
3203
+ ...list.flatMap((c) => [
3204
+ ` ${c.usage}`,
3205
+ ` ${c.summary}`,
3206
+ ...wanted ? (c.subcommands ?? []).map((s) => ` · ${s.usage}\n ${s.summary}`) : [],
3207
+ ...wanted ? c.options.map((o) => ` --${o.name}${o.type === "string" ? " <value>" : ""} ${o.description}`) : []
3208
+ ]),
3209
+ "",
3210
+ "Global options:",
3211
+ ...GLOBAL_OPTIONS.map((o) => ` --${o.name} ${o.description}`),
3212
+ ...wanted ? [] : ["", "`agentphoto help <command>` shows a command's actions and options."]
3213
+ ].join("\n"));
3214
+ }
3215
+ },
3216
+ versionCommand,
3217
+ doctorCommand,
3218
+ newCommand,
3219
+ infoCommand,
3220
+ docCommand,
3221
+ layerCommand,
3222
+ filterCommand,
3223
+ maskCommand,
3224
+ removeBgCommand,
3225
+ analyzeCommand,
3226
+ renderCommand,
3227
+ exportCommand,
3228
+ checkCommand,
3229
+ catalogCommand,
3230
+ templatesCommand,
3231
+ assetsCommand,
3232
+ modelsCommand,
3233
+ studioCommand,
3234
+ toolsCommand,
3235
+ mcpCommand
3236
+ ];
3237
+ function findCommand(name) {
3238
+ return COMMANDS.find((c) => c.name === name);
3239
+ }
3240
+ // agent/cli.ts
3241
+ async function main(argv, io) {
3242
+ const json = argv.includes("--json");
3243
+ const out = io ?? createIo(json);
3244
+ try {
3245
+ const args = argv.filter((a) => a !== "--json");
3246
+ const leading = [];
3247
+ while (args[0] && args[0].startsWith("--") && LEADING.has(args[0].split("=")[0])) {
3248
+ const flag = args.shift();
3249
+ leading.push(flag);
3250
+ if (LEADING_WITH_VALUE.has(flag) && args.length) leading.push(args.shift());
3251
+ }
3252
+ const [name = "help", ...rest] = args;
3253
+ rest.push(...leading);
3254
+ if (name === "--help" || name === "-h") return await run("help", rest, out) ?? 0;
3255
+ if (name === "--version" || name === "-v") return await run("version", rest, out) ?? 0;
3256
+ return await run(name, rest, out) ?? 0;
3257
+ } catch (error) {
3258
+ return printError(out, error);
3259
+ }
3260
+ }
3261
+ var LEADING_WITH_VALUE = /* @__PURE__ */ new Set(["--project"]);
3262
+ var LEADING = /* @__PURE__ */ new Set([...GLOBAL_OPTIONS.filter((o) => o.type === "boolean" && o.name !== "help").map((o) => `--${o.name}`), ...LEADING_WITH_VALUE]);
3263
+ async function run(name, args, io) {
3264
+ const command = findCommand(name);
3265
+ if (!command) throw new CliError("unknown-command", `Unknown command "${name}".`, `Available: ${COMMANDS.map((c) => c.name).join(", ")}. Run \`agentphoto help\`.`, 2);
3266
+ let parsed;
3267
+ try {
3268
+ parsed = parseArgs({
3269
+ args,
3270
+ allowPositionals: true,
3271
+ strict: true,
3272
+ options: Object.fromEntries([...command.options, ...GLOBAL_OPTIONS].map((o) => [o.name, {
3273
+ type: o.type,
3274
+ ...o.multiple ? { multiple: true } : {}
3275
+ }]))
3276
+ });
3277
+ } catch (e) {
3278
+ throw new CliError("usage", e.message, `Usage: agentphoto ${command.usage} (details: \`agentphoto help ${command.name}\`).`, 2);
3279
+ }
3280
+ if (parsed.values.help && command.name !== "help") return run("help", [command.name], io);
3281
+ try {
3282
+ return await command.run({
3283
+ io,
3284
+ options: parsed.values,
3285
+ positionals: parsed.positionals
3286
+ });
3287
+ } catch (e) {
3288
+ if (e instanceof CliError && !e.hint && e.exitCode === 2) throw new CliError(e.code, e.message, `Usage: agentphoto ${command.usage} (details: \`agentphoto help ${command.name}\`).`, e.exitCode, e.details);
3289
+ throw e;
3290
+ }
3291
+ }
3292
+ // agent/bin.ts
3293
+ function exitWhenFlushed(code) {
3294
+ let pending = 2;
3295
+ const done = () => {
3296
+ if (--pending === 0) process.exit(code);
3297
+ };
3298
+ process.stdout.write("", done);
3299
+ process.stderr.write("", done);
3300
+ }
3301
+ routeConsoleToStderr();
3302
+ var finish = (code) => void closeEngineSessions().catch(() => void 0).finally(() => exitWhenFlushed(code));
3303
+ main(process.argv.slice(2)).then(finish, (err) => {
3304
+ console.error(err);
3305
+ finish(1);
3306
+ });
3307
+ export {};