ima2-gen 1.1.20 → 1.1.22

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 (239) hide show
  1. package/README.md +42 -26
  2. package/bin/commands/capabilities.js +2 -2
  3. package/bin/commands/defaults.js +2 -2
  4. package/bin/commands/doctor.js +3 -3
  5. package/bin/commands/edit.js +1 -1
  6. package/bin/commands/gen.js +1 -1
  7. package/bin/commands/grok.js +16 -11
  8. package/bin/commands/multimode.js +1 -1
  9. package/bin/commands/observability.js +2 -2
  10. package/bin/commands/video.js +335 -13
  11. package/bin/ima2.js +23 -13
  12. package/bin/lib/error-hints.js +2 -2
  13. package/bin/lib/platform.js +34 -5
  14. package/docs/API.md +112 -3
  15. package/docs/CLI.md +61 -7
  16. package/docs/FAQ.ko.md +15 -20
  17. package/docs/FAQ.md +14 -19
  18. package/docs/NPX_QUICKSTART.md +40 -0
  19. package/docs/PROMPT_STUDIO.ko.md +1 -1
  20. package/docs/PROMPT_STUDIO.md +1 -1
  21. package/docs/README.ja.md +6 -16
  22. package/docs/README.ko.md +35 -14
  23. package/docs/README.zh-CN.md +7 -17
  24. package/docs/migration/runtime-test-inventory.md +8 -1
  25. package/lib/agentQueueWorker.js +6 -0
  26. package/lib/agentRuntime.js +20 -5
  27. package/lib/atomicWrite.js +14 -0
  28. package/lib/capabilities.js +1 -1
  29. package/lib/generationErrors.js +1 -1
  30. package/lib/grokProxyLauncher.js +31 -6
  31. package/lib/grokVideoAdapter.js +18 -89
  32. package/lib/grokVideoCanvas.js +25 -0
  33. package/lib/grokVideoDownload.js +58 -0
  34. package/lib/grokVideoPlannerPrompt.js +64 -0
  35. package/lib/historyList.js +7 -1
  36. package/lib/inflight.js +1 -1
  37. package/lib/oauthLauncher.js +26 -6
  38. package/lib/videoContinuity.js +149 -0
  39. package/lib/videoFrameExtract.js +80 -0
  40. package/node_modules/progrok/dist/index.js +187 -88
  41. package/node_modules/progrok/dist/index.js.map +1 -1
  42. package/node_modules/progrok/package.json +1 -1
  43. package/node_modules/progrok/skills/progrok/SKILL.md +33 -4
  44. package/package.json +6 -8
  45. package/routes/edit.js +2 -1
  46. package/routes/generate.js +4 -3
  47. package/routes/health.js +4 -3
  48. package/routes/index.js +4 -0
  49. package/routes/multimode.js +2 -1
  50. package/routes/quota.js +66 -0
  51. package/routes/video.js +80 -16
  52. package/routes/videoExtended.js +293 -0
  53. package/server.js +35 -4
  54. package/skills/ima2/SKILL.md +320 -7
  55. package/ui/dist/.vite/manifest.json +12 -12
  56. package/ui/dist/assets/{AgentWorkspace-DS8uvoLI.js → AgentWorkspace-COxQ5TjU.js} +2 -2
  57. package/ui/dist/assets/{CardNewsWorkspace-CYxMsE67.js → CardNewsWorkspace-B0OkcuVz.js} +1 -1
  58. package/ui/dist/assets/{NodeCanvas-DccIc347.js → NodeCanvas-BSsclEBh.js} +1 -1
  59. package/ui/dist/assets/{PromptBuilderPanel-BvxxwSJp.js → PromptBuilderPanel-DpC9A5Rz.js} +1 -1
  60. package/ui/dist/assets/{PromptImportDialog-u1_BFDRd.js → PromptImportDialog-CVwT0rLd.js} +2 -2
  61. package/ui/dist/assets/{PromptImportDiscoverySection-C5uvkVSz.js → PromptImportDiscoverySection-BDCkRCRs.js} +1 -1
  62. package/ui/dist/assets/{PromptImportFolderSection-D3E_O1SD.js → PromptImportFolderSection-QoKbZD83.js} +1 -1
  63. package/ui/dist/assets/{PromptLibraryPanel-4gyf9CB9.js → PromptLibraryPanel-BhFgeKnY.js} +2 -2
  64. package/ui/dist/assets/SettingsWorkspace-CfjrlH5R.js +1 -0
  65. package/ui/dist/assets/index-C-mur7pa.css +1 -0
  66. package/ui/dist/assets/index-CCP5nUOj.js +42 -0
  67. package/ui/dist/assets/{index-DoKtXbod.js → index-Cxhzi3bs.js} +1 -1
  68. package/ui/dist/index.html +2 -2
  69. package/vendor/progrok-0.2.0.tgz +0 -0
  70. package/bin/commands/annotate.ts +0 -119
  71. package/bin/commands/cancel.ts +0 -48
  72. package/bin/commands/canvas-versions.ts +0 -80
  73. package/bin/commands/capabilities.ts +0 -110
  74. package/bin/commands/cardnews.ts +0 -249
  75. package/bin/commands/comfy.ts +0 -54
  76. package/bin/commands/config.ts +0 -186
  77. package/bin/commands/defaults.ts +0 -192
  78. package/bin/commands/doctor.ts +0 -202
  79. package/bin/commands/edit.ts +0 -150
  80. package/bin/commands/gen.ts +0 -214
  81. package/bin/commands/grok.ts +0 -85
  82. package/bin/commands/history.ts +0 -146
  83. package/bin/commands/ls.ts +0 -64
  84. package/bin/commands/metadata.ts +0 -39
  85. package/bin/commands/multimode.ts +0 -196
  86. package/bin/commands/node.ts +0 -166
  87. package/bin/commands/observability.ts +0 -176
  88. package/bin/commands/ping.ts +0 -31
  89. package/bin/commands/prompt-sub/build.ts +0 -101
  90. package/bin/commands/prompt.ts +0 -492
  91. package/bin/commands/ps.ts +0 -81
  92. package/bin/commands/session.ts +0 -266
  93. package/bin/commands/show.ts +0 -72
  94. package/bin/commands/skill.ts +0 -70
  95. package/bin/commands/video.ts +0 -205
  96. package/bin/ima2.ts +0 -430
  97. package/bin/lib/args.ts +0 -92
  98. package/bin/lib/browser-id.ts +0 -16
  99. package/bin/lib/client.ts +0 -122
  100. package/bin/lib/config-store.ts +0 -120
  101. package/bin/lib/destructive-confirm.ts +0 -19
  102. package/bin/lib/doctor-checks.ts +0 -91
  103. package/bin/lib/error-hints.ts +0 -23
  104. package/bin/lib/files.ts +0 -39
  105. package/bin/lib/output.ts +0 -73
  106. package/bin/lib/platform.ts +0 -99
  107. package/bin/lib/recover-output.ts +0 -139
  108. package/bin/lib/sse.ts +0 -73
  109. package/bin/lib/star-prompt.ts +0 -97
  110. package/bin/lib/storage-doctor.ts +0 -39
  111. package/bin/lib/ui-build.ts +0 -85
  112. package/config.ts +0 -354
  113. package/lib/agentCommandParser.ts +0 -69
  114. package/lib/agentGenerationPlanner.ts +0 -273
  115. package/lib/agentQuestionResponder.ts +0 -266
  116. package/lib/agentQueueStore.ts +0 -270
  117. package/lib/agentQueueWorker.ts +0 -89
  118. package/lib/agentRuntime.ts +0 -592
  119. package/lib/agentSettings.ts +0 -72
  120. package/lib/agentStore.ts +0 -422
  121. package/lib/agentStoreRows.ts +0 -136
  122. package/lib/agentTypes.ts +0 -154
  123. package/lib/apiCachePolicy.ts +0 -11
  124. package/lib/assetLifecycle.ts +0 -146
  125. package/lib/canvasVersionStore.ts +0 -223
  126. package/lib/capabilities.ts +0 -126
  127. package/lib/cardNewsGenerator.ts +0 -271
  128. package/lib/cardNewsJobStore.ts +0 -142
  129. package/lib/cardNewsManifestStore.ts +0 -154
  130. package/lib/cardNewsPlanner.ts +0 -236
  131. package/lib/cardNewsPlannerClient.ts +0 -155
  132. package/lib/cardNewsPlannerPrompt.ts +0 -62
  133. package/lib/cardNewsPlannerSchema.ts +0 -321
  134. package/lib/cardNewsRoleTemplateStore.ts +0 -47
  135. package/lib/cardNewsTemplateStore.ts +0 -252
  136. package/lib/codexDetect.ts +0 -71
  137. package/lib/comfyBridge.ts +0 -235
  138. package/lib/composerSnapshot.ts +0 -33
  139. package/lib/configKeys.ts +0 -62
  140. package/lib/db.ts +0 -295
  141. package/lib/errInfo.ts +0 -43
  142. package/lib/errorClassify.ts +0 -100
  143. package/lib/generationCancel.ts +0 -28
  144. package/lib/generationErrors.ts +0 -238
  145. package/lib/grokImageAdapter.ts +0 -513
  146. package/lib/grokMultimodeAdapter.ts +0 -84
  147. package/lib/grokProxyLauncher.ts +0 -129
  148. package/lib/grokRuntime.ts +0 -23
  149. package/lib/grokSizeMapper.ts +0 -71
  150. package/lib/grokVideoAdapter.ts +0 -519
  151. package/lib/historyIndex.ts +0 -51
  152. package/lib/historyList.ts +0 -177
  153. package/lib/imageMetadata.ts +0 -113
  154. package/lib/imageMetadataStore.ts +0 -67
  155. package/lib/imageModels.ts +0 -165
  156. package/lib/inflight.ts +0 -281
  157. package/lib/localImportStore.ts +0 -114
  158. package/lib/logger.ts +0 -161
  159. package/lib/nodeStore.ts +0 -91
  160. package/lib/oauthLauncher.ts +0 -78
  161. package/lib/oauthNormalize.ts +0 -30
  162. package/lib/oauthProxy/errors.ts +0 -128
  163. package/lib/oauthProxy/generators.ts +0 -494
  164. package/lib/oauthProxy/index.ts +0 -28
  165. package/lib/oauthProxy/prompts.ts +0 -123
  166. package/lib/oauthProxy/references.ts +0 -45
  167. package/lib/oauthProxy/runtime.ts +0 -115
  168. package/lib/oauthProxy/streams.ts +0 -232
  169. package/lib/oauthProxy/types.ts +0 -9
  170. package/lib/oauthProxy.ts +0 -3
  171. package/lib/openDirectory.ts +0 -47
  172. package/lib/pngInfo.ts +0 -26
  173. package/lib/promptBuilder/attachments.ts +0 -74
  174. package/lib/promptBuilder/client.ts +0 -130
  175. package/lib/promptBuilder/constants.ts +0 -9
  176. package/lib/promptBuilder/context.ts +0 -36
  177. package/lib/promptBuilder/errors.ts +0 -12
  178. package/lib/promptBuilder/requestSchema.ts +0 -56
  179. package/lib/promptBuilder/responseParser.ts +0 -219
  180. package/lib/promptBuilder/systemPrompt.ts +0 -135
  181. package/lib/promptBuilder/transport.ts +0 -94
  182. package/lib/promptBuilder/types.ts +0 -109
  183. package/lib/promptImport/curatedSources.ts +0 -141
  184. package/lib/promptImport/discoveryRegistry.ts +0 -329
  185. package/lib/promptImport/errors.ts +0 -18
  186. package/lib/promptImport/githubDiscovery.ts +0 -309
  187. package/lib/promptImport/githubFolder.ts +0 -397
  188. package/lib/promptImport/githubSource.ts +0 -257
  189. package/lib/promptImport/gptImageHints.ts +0 -70
  190. package/lib/promptImport/parsePromptCandidates.ts +0 -179
  191. package/lib/promptImport/promptIndex.ts +0 -326
  192. package/lib/promptImport/rankPromptCandidates.ts +0 -65
  193. package/lib/promptImport/types.ts +0 -103
  194. package/lib/promptSafetyPolicy.ts +0 -5
  195. package/lib/providerOptions.ts +0 -56
  196. package/lib/referenceImageCompress.ts +0 -84
  197. package/lib/refs.ts +0 -133
  198. package/lib/requestLogger.ts +0 -49
  199. package/lib/responsesDoctor.ts +0 -456
  200. package/lib/responsesErrors.ts +0 -83
  201. package/lib/responsesFallback.ts +0 -114
  202. package/lib/responsesImageAdapter.ts +0 -466
  203. package/lib/responsesParse.ts +0 -452
  204. package/lib/responsesTools.ts +0 -28
  205. package/lib/runtimeContext.ts +0 -146
  206. package/lib/runtimePorts.ts +0 -105
  207. package/lib/sessionStore.ts +0 -308
  208. package/lib/storageMigration.ts +0 -310
  209. package/lib/styleSheet.ts +0 -139
  210. package/lib/systemTrash.ts +0 -20
  211. package/lib/videoSeriesChain.ts +0 -29
  212. package/lib/visibleTextLanguagePolicy.ts +0 -7
  213. package/routes/agent.ts +0 -308
  214. package/routes/annotations.ts +0 -118
  215. package/routes/canvasVersions.ts +0 -69
  216. package/routes/capabilities.ts +0 -18
  217. package/routes/cardNews.ts +0 -211
  218. package/routes/comfy.ts +0 -43
  219. package/routes/edit.ts +0 -352
  220. package/routes/generate.ts +0 -492
  221. package/routes/grok.ts +0 -24
  222. package/routes/health.ts +0 -123
  223. package/routes/history.ts +0 -221
  224. package/routes/imageImport.ts +0 -37
  225. package/routes/index.ts +0 -48
  226. package/routes/metadata.ts +0 -77
  227. package/routes/multimode.ts +0 -499
  228. package/routes/nodes.ts +0 -578
  229. package/routes/promptBuilder.ts +0 -37
  230. package/routes/promptImport.ts +0 -379
  231. package/routes/prompts.ts +0 -428
  232. package/routes/sessions.ts +0 -317
  233. package/routes/storage.ts +0 -47
  234. package/routes/video.ts +0 -232
  235. package/server.ts +0 -290
  236. package/ui/dist/assets/SettingsWorkspace-F3eNu3mJ.js +0 -1
  237. package/ui/dist/assets/index-B6tcw_UF.css +0 -1
  238. package/ui/dist/assets/index-DYOh6gQD.js +0 -32
  239. package/vendor/progrok-0.1.1.tgz +0 -0
@@ -1,177 +0,0 @@
1
- import { mkdir, readFile, readdir, stat } from "fs/promises";
2
- import { dirname, join } from "path";
3
- import { config } from "../config.js";
4
- import { readEmbeddedImageMetadataFromFile } from "./imageMetadataStore.js";
5
-
6
- import { errInfo } from "./errInfo.js";
7
- async function listImageFiles(baseDir: string) {
8
- const out: Array<{ full: string; rel: string; name: string }> = [];
9
-
10
- async function walk(dir: string, depth: number) {
11
- const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
12
- for (const entry of entries) {
13
- if (entry.name === config.storage.trashDirName) continue;
14
- const full = join(dir, entry.name);
15
- if (entry.isDirectory() && depth > 0) {
16
- await walk(full, depth - 1);
17
- } else if (entry.isFile() && /\.(png|jpe?g|webp|mp4)$/i.test(entry.name)) {
18
- out.push({ full, rel: full.slice(baseDir.length + 1), name: entry.name });
19
- }
20
- }
21
- }
22
-
23
- await walk(baseDir, 2);
24
- return out;
25
- }
26
-
27
- export async function listHistoryRows(baseDir = config.storage.generatedDir) {
28
- await mkdir(baseDir, { recursive: true });
29
- const imgs = await listImageFiles(baseDir);
30
- const setRows = await listCardNewsSetRows(baseDir);
31
- const rows = await Promise.all(imgs.map(async ({ full, rel, name }) => {
32
- const st = await stat(full).catch(() => null);
33
- const meta = await readImageMetadata(full, rel);
34
- return {
35
- filename: rel,
36
- url: `/generated/${rel.split("/").map(encodeURIComponent).join("/")}`,
37
- mediaType: meta?.mediaType || (/\.mp4$/i.test(name) ? "video" : "image"),
38
- video: meta?.video || null,
39
- videoSeries: meta?.videoSeries || null,
40
- createdAt: meta?.createdAt || st?.mtimeMs || 0,
41
- prompt: meta?.prompt || null,
42
- userPrompt: meta?.userPrompt || meta?.prompt || null,
43
- revisedPrompt: meta?.revisedPrompt || null,
44
- promptMode: meta?.promptMode || null,
45
- composerPrompt: meta?.composerPrompt ?? null,
46
- composerInsertedPrompts: meta?.composerInsertedPrompts ?? null,
47
- quality: meta?.quality || null,
48
- size: meta?.size || null,
49
- format: meta?.format || name.split(".").pop(),
50
- model: meta?.model || null,
51
- reasoningEffort: meta?.reasoningEffort ?? null,
52
- elapsed: meta?.elapsed ?? null,
53
- provider: meta?.provider || "oauth",
54
- usage: meta?.usage || null,
55
- webSearchCalls: meta?.webSearchCalls || 0,
56
- sessionId: meta?.sessionId || null,
57
- nodeId: meta?.nodeId || null,
58
- parentNodeId: meta?.parentNodeId || null,
59
- clientNodeId: meta?.clientNodeId || null,
60
- requestId: meta?.requestId || null,
61
- kind: meta?.kind || null,
62
- canvasVersion: Boolean(meta?.canvasVersion),
63
- canvasSourceFilename: meta?.canvasSourceFilename || null,
64
- canvasEditableFilename: meta?.canvasEditableFilename || null,
65
- canvasMergedAt: Number.isFinite(meta?.canvasMergedAt) ? meta.canvasMergedAt : null,
66
- setId: meta?.setId || null,
67
- cardId: meta?.cardId || null,
68
- cardOrder: Number.isFinite(meta?.cardOrder) ? meta.cardOrder : null,
69
- headline: meta?.headline || null,
70
- body: meta?.body || null,
71
- cards: meta?.cards || null,
72
- refsCount: Number.isFinite(meta?.refsCount) ? meta.refsCount : 0,
73
- sequenceId: meta?.sequenceId || null,
74
- sequenceIndex: Number.isFinite(meta?.sequenceIndex) ? meta.sequenceIndex : null,
75
- sequenceTotalRequested: Number.isFinite(meta?.sequenceTotalRequested) ? meta.sequenceTotalRequested : null,
76
- sequenceTotalReturned: Number.isFinite(meta?.sequenceTotalReturned) ? meta.sequenceTotalReturned : null,
77
- sequenceStatus: meta?.sequenceStatus || null,
78
- };
79
- }));
80
-
81
- rows.push(...setRows);
82
- rows.sort((a, b) => {
83
- if (b.createdAt !== a.createdAt) return b.createdAt - a.createdAt;
84
- return b.filename < a.filename ? -1 : b.filename > a.filename ? 1 : 0;
85
- });
86
-
87
- return rows;
88
- }
89
-
90
- async function readImageSidecar(full: string, rel: string) {
91
- const sibling = full.replace(/\.(png|jpe?g|webp)$/i, ".json");
92
- for (const candidate of [`${full}.json`, sibling]) {
93
- try {
94
- return JSON.parse(await readFile(candidate, "utf-8"));
95
- } catch (e) {
96
- const err = errInfo(e);
97
- if (err.code !== "ENOENT") console.warn("[history] sidecar parse fail:", rel, err.message);
98
- }
99
- }
100
- return null;
101
- }
102
-
103
- async function readImageMetadata(full: string, rel: string) {
104
- const sidecar = await readImageSidecar(full, rel);
105
- if (sidecar) return sidecar;
106
- try {
107
- const embedded = await readEmbeddedImageMetadataFromFile(full);
108
- return embedded.metadata;
109
- } catch (e) {
110
- const err = errInfo(e);
111
- if (err.code !== "ENOENT") console.warn("[history] embedded metadata read fail:", rel, err.message);
112
- return null;
113
- }
114
- }
115
-
116
- async function listCardNewsSetRows(baseDir: string) {
117
- const root = join(baseDir, "cardnews");
118
- const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
119
- const rows: any[] = [];
120
- for (const entry of entries) {
121
- if (!entry.isDirectory()) continue;
122
- try {
123
- const manifestPath = join(root, entry.name, "manifest.json");
124
- const manifest = JSON.parse(await readFile(manifestPath, "utf-8")) as any;
125
- const first = (manifest.cards || []).find((card: any) => card.imageFilename);
126
- const filename = `cardnews/${entry.name}/manifest.json`;
127
- rows.push({
128
- filename,
129
- url: first?.imageFilename
130
- ? `/generated/cardnews/${encodeURIComponent(entry.name)}/${encodeURIComponent(first.imageFilename)}`
131
- : "",
132
- createdAt: manifest.createdAt || 0,
133
- prompt: null,
134
- userPrompt: null,
135
- revisedPrompt: null,
136
- promptMode: null,
137
- composerPrompt: null,
138
- composerInsertedPrompts: null,
139
- quality: null,
140
- size: manifest.size || null,
141
- format: "card-news-set",
142
- model: null,
143
- provider: "oauth",
144
- usage: null,
145
- webSearchCalls: 0,
146
- sessionId: manifest.sessionId || null,
147
- nodeId: null,
148
- parentNodeId: null,
149
- clientNodeId: null,
150
- requestId: manifest.requestId || null,
151
- kind: "card-news-set",
152
- setId: manifest.setId || entry.name,
153
- cardId: null,
154
- cardOrder: null,
155
- title: manifest.title || "Untitled card news",
156
- headline: manifest.title || "Untitled card news",
157
- body: null,
158
- cards: (manifest.cards || []).map((card: any) => ({
159
- url: card.imageFilename
160
- ? `/generated/cardnews/${encodeURIComponent(entry.name)}/${encodeURIComponent(card.imageFilename)}`
161
- : "",
162
- headline: card.headline,
163
- body: card.body,
164
- cardOrder: card.cardOrder,
165
- imageFilename: card.imageFilename,
166
- status: card.status || "generated",
167
- })),
168
- refsCount: 0,
169
- dir: dirname(manifestPath),
170
- });
171
- } catch (e) {
172
- const err = errInfo(e);
173
- if (err.code !== "ENOENT") console.warn("[history] card-news manifest parse fail:", entry.name, err.message);
174
- }
175
- }
176
- return rows;
177
- }
@@ -1,113 +0,0 @@
1
- export const IMA2_METADATA_SCHEMA = "ima2.generation.v1";
2
- export const IMA2_XMP_NAMESPACE = "https://github.com/lidge-jun/ima2-gen/ns/1.0/";
3
- export const IMA2_XMP_PROPERTY = "GenerationMetadata";
4
- export const MAX_EMBEDDED_METADATA_CHARS = 64 * 1024;
5
-
6
- function isPlainObject(value: unknown) {
7
- return value != null && typeof value === "object" && !Array.isArray(value);
8
- }
9
-
10
- function stringOrNull(value: unknown, max = 4000) {
11
- if (typeof value !== "string") return null;
12
- return value.slice(0, max);
13
- }
14
-
15
- function numberOrNull(value: unknown) {
16
- return typeof value === "number" && Number.isFinite(value) ? value : null;
17
- }
18
-
19
- function xmlEscape(value: unknown) {
20
- return String(value)
21
- .replace(/&/g, "&amp;")
22
- .replace(/"/g, "&quot;")
23
- .replace(/</g, "&lt;")
24
- .replace(/>/g, "&gt;");
25
- }
26
-
27
- function xmlUnescape(value: unknown) {
28
- return String(value)
29
- .replace(/&quot;/g, "\"")
30
- .replace(/&lt;/g, "<")
31
- .replace(/&gt;/g, ">")
32
- .replace(/&amp;/g, "&");
33
- }
34
-
35
- export function buildIma2MetadataPayload(meta: any = {}, context: any = {}) {
36
- const payload = {
37
- schema: IMA2_METADATA_SCHEMA,
38
- app: "ima2-gen",
39
- version: stringOrNull(context.version, 80) || null,
40
- createdAt: numberOrNull(meta.createdAt) || Date.now(),
41
- kind: stringOrNull(meta.kind, 80),
42
- canvasVersion: Boolean(meta.canvasVersion),
43
- canvasSourceFilename: stringOrNull(meta.canvasSourceFilename, 240),
44
- canvasEditableFilename: stringOrNull(meta.canvasEditableFilename, 240),
45
- canvasMergedAt: numberOrNull(meta.canvasMergedAt),
46
- prompt: stringOrNull(meta.prompt),
47
- userPrompt: stringOrNull(meta.userPrompt) || stringOrNull(meta.prompt),
48
- revisedPrompt: stringOrNull(meta.revisedPrompt),
49
- promptMode: meta.promptMode === "direct" ? "direct" : "auto",
50
- quality: stringOrNull(meta.quality, 40),
51
- size: stringOrNull(meta.size, 40),
52
- format: stringOrNull(meta.format, 20),
53
- moderation: stringOrNull(meta.moderation, 40),
54
- model: stringOrNull(meta.model, 80),
55
- reasoningEffort: stringOrNull(meta.reasoningEffort, 40),
56
- elapsed: numberOrNull(meta.elapsed),
57
- provider: stringOrNull(meta.provider, 40),
58
- sessionId: stringOrNull(meta.sessionId, 120),
59
- nodeId: stringOrNull(meta.nodeId, 120),
60
- parentNodeId: stringOrNull(meta.parentNodeId, 120),
61
- clientNodeId: stringOrNull(meta.clientNodeId, 120),
62
- requestId: stringOrNull(meta.requestId, 160),
63
- refsCount: Number.isFinite(meta.refsCount) ? meta.refsCount : 0,
64
- webSearchCalls: Number.isFinite(meta.webSearchCalls) ? meta.webSearchCalls : 0,
65
- styleSheetApplied: Boolean(meta.styleSheetApplied),
66
- };
67
- return Object.fromEntries(Object.entries(payload).filter(([, value]) => value !== undefined));
68
- }
69
-
70
- export function normalizeEmbeddedMetadata(value: any) {
71
- if (!isPlainObject(value)) return null;
72
- if (value.schema !== IMA2_METADATA_SCHEMA || value.app !== "ima2-gen") return null;
73
- return buildIma2MetadataPayload(value, { version: value.version });
74
- }
75
-
76
- export function buildIma2Xmp(metadataPayload: unknown) {
77
- const normalized = normalizeEmbeddedMetadata(metadataPayload);
78
- if (!normalized) {
79
- const err: any = new Error("Invalid ima2 metadata payload");
80
- err.code = "IMAGE_METADATA_INVALID";
81
- throw err;
82
- }
83
- const json = JSON.stringify(normalized);
84
- if (json.length > MAX_EMBEDDED_METADATA_CHARS) {
85
- const err: any = new Error("ima2 metadata payload is too large");
86
- err.code = "IMAGE_METADATA_TOO_LARGE";
87
- throw err;
88
- }
89
- const escaped = xmlEscape(json);
90
- return [
91
- "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>",
92
- "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">",
93
- "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">",
94
- `<rdf:Description xmlns:ima2="${IMA2_XMP_NAMESPACE}" ima2:${IMA2_XMP_PROPERTY}="${escaped}"/>`,
95
- "</rdf:RDF>",
96
- "</x:xmpmeta>",
97
- "<?xpacket end=\"w\"?>",
98
- ].join("");
99
- }
100
-
101
- export function parseIma2Xmp(xmpString: unknown) {
102
- if (typeof xmpString !== "string" || xmpString.length === 0) return null;
103
- const attrPattern = new RegExp(`ima2:${IMA2_XMP_PROPERTY}="([^"]*)"`);
104
- const attrMatch = attrPattern.exec(xmpString);
105
- const raw = attrMatch?.[1];
106
- if (!raw) return null;
107
- try {
108
- const parsed = JSON.parse(xmlUnescape(raw));
109
- return normalizeEmbeddedMetadata(parsed);
110
- } catch {
111
- return null;
112
- }
113
- }
@@ -1,67 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import sharp from "sharp";
3
- import { buildIma2MetadataPayload, buildIma2Xmp, parseIma2Xmp } from "./imageMetadata.js";
4
-
5
- const SUPPORTED_FORMATS = new Set(["png", "jpeg", "jpg", "webp"]);
6
-
7
- export function normalizeImageMetadataFormat(format: unknown) {
8
- const normalized = String(format || "").toLowerCase();
9
- if (normalized === "jpg") return "jpeg";
10
- return normalized;
11
- }
12
-
13
- export function isSupportedMetadataFormat(format: unknown) {
14
- return SUPPORTED_FORMATS.has(String(format || "").toLowerCase());
15
- }
16
-
17
- export async function embedImageMetadata(buffer: Buffer, format: unknown, metadata: unknown, context: any = {}) {
18
- const normalizedFormat = normalizeImageMetadataFormat(format);
19
- if (!isSupportedMetadataFormat(normalizedFormat)) {
20
- const err: any = new Error(`Unsupported image metadata format: ${format}`);
21
- err.code = "IMAGE_METADATA_UNSUPPORTED_FORMAT";
22
- throw err;
23
- }
24
- const payload = buildIma2MetadataPayload(metadata, context);
25
- const xmp = buildIma2Xmp(payload);
26
- const next = await sharp(buffer)
27
- .toFormat(normalizedFormat as any)
28
- .withXmp(xmp)
29
- .toBuffer();
30
- return { buffer: next, embedded: true, metadata: payload };
31
- }
32
-
33
- export async function embedImageMetadataBestEffort(buffer: Buffer, format: unknown, metadata: unknown, context: any = {}) {
34
- try {
35
- return await embedImageMetadata(buffer, format, metadata, context);
36
- } catch (error: any) {
37
- return {
38
- buffer,
39
- embedded: false,
40
- warning: error?.message || "metadata embedding failed",
41
- code: error?.code || "IMAGE_METADATA_EMBED_FAILED",
42
- };
43
- }
44
- }
45
-
46
- export async function readEmbeddedImageMetadata(buffer: Buffer) {
47
- const meta = await sharp(buffer, { failOn: "none" }).metadata();
48
- const xmpString = meta.xmpAsString || (meta.xmp ? meta.xmp.toString("utf8") : "");
49
- const xmp = parseIma2Xmp(xmpString);
50
- if (xmp) return { metadata: xmp, source: "xmp", warnings: [] };
51
-
52
- for (const comment of meta.comments || []) {
53
- const text = comment?.text || "";
54
- const parsed = parseIma2Xmp(text);
55
- if (parsed) return { metadata: parsed, source: "png-comment", warnings: [] };
56
- }
57
-
58
- return {
59
- metadata: null,
60
- source: null,
61
- warnings: ["No ima2 metadata found in this image."],
62
- };
63
- }
64
-
65
- export async function readEmbeddedImageMetadataFromFile(path: string) {
66
- return readEmbeddedImageMetadata(await readFile(path));
67
- }
@@ -1,165 +0,0 @@
1
- import type { RouteRuntimeContext } from "./runtimeContext.js";
2
-
3
- const FALLBACK_IMAGE_MODEL = "gpt-5.4-mini";
4
- const VALID_IMAGE_MODELS = new Set(["gpt-5.5", "gpt-5.4", "gpt-5.4-mini"]);
5
- const UNSUPPORTED_IMAGE_MODELS = new Set(["gpt-5.3-codex-spark"]);
6
- const FALLBACK_REASONING_EFFORT = "none";
7
- const VALID_REASONING_EFFORTS = new Set(["none", "low", "medium", "high", "xhigh"]);
8
-
9
- const GROK_FALLBACK_IMAGE_MODEL = "grok-imagine-image";
10
- const VALID_GROK_IMAGE_MODELS = new Set(["grok-imagine-image", "grok-imagine-image-quality"]);
11
-
12
- export function normalizeReasoningEffort(ctx: RouteRuntimeContext | null | undefined, rawEffort: unknown) {
13
- const configured = (ctx?.config as { imageModels?: { reasoningEffort?: string; validReasoningEfforts?: Set<string> } } | undefined)?.imageModels;
14
- const fallback = configured?.reasoningEffort ?? FALLBACK_REASONING_EFFORT;
15
- const valid = configured?.validReasoningEfforts ?? VALID_REASONING_EFFORTS;
16
-
17
- if (typeof rawEffort !== "string" || rawEffort.length === 0) {
18
- return { effort: valid.has(fallback) ? fallback : FALLBACK_REASONING_EFFORT };
19
- }
20
- if (!valid.has(rawEffort)) {
21
- return {
22
- error: "reasoningEffort must be one of: none, low, medium, high, xhigh",
23
- code: "INVALID_REASONING_EFFORT",
24
- status: 400,
25
- };
26
- }
27
- return { effort: rawEffort };
28
- }
29
-
30
- export function normalizeImageModel(ctx: RouteRuntimeContext | null | undefined, rawModel: unknown) {
31
- const configured = (ctx?.config as { imageModels?: { default?: string; valid?: Set<string>; unsupported?: Set<string> } } | undefined)?.imageModels;
32
- const fallback = configured?.default ?? FALLBACK_IMAGE_MODEL;
33
- const valid = configured?.valid ?? VALID_IMAGE_MODELS;
34
- const unsupported = configured?.unsupported ?? UNSUPPORTED_IMAGE_MODELS;
35
-
36
- if (typeof rawModel !== "string" || rawModel.length === 0) {
37
- return { model: valid.has(fallback) ? fallback : FALLBACK_IMAGE_MODEL };
38
- }
39
-
40
- if (unsupported.has(rawModel)) {
41
- return {
42
- error: "model is listed by OAuth but does not support image_generation: gpt-5.3-codex-spark",
43
- code: "IMAGE_MODEL_UNSUPPORTED",
44
- status: 400,
45
- };
46
- }
47
-
48
- if (!valid.has(rawModel)) {
49
- return {
50
- error: "model must be one of: gpt-5.5, gpt-5.4, gpt-5.4-mini",
51
- code: "INVALID_IMAGE_MODEL",
52
- status: 400,
53
- };
54
- }
55
-
56
- return { model: rawModel };
57
- }
58
-
59
- export function normalizeGrokImageModel(rawModel: unknown) {
60
- if (typeof rawModel !== "string" || rawModel.length === 0) {
61
- return { model: GROK_FALLBACK_IMAGE_MODEL };
62
- }
63
- if (!VALID_GROK_IMAGE_MODELS.has(rawModel)) {
64
- return {
65
- error: `Grok image model must be one of: ${[...VALID_GROK_IMAGE_MODELS].join(", ")}`,
66
- code: "INVALID_GROK_IMAGE_MODEL" as const,
67
- status: 400 as const,
68
- };
69
- }
70
- return { model: rawModel };
71
- }
72
-
73
- // ── Grok video (T2V/I2V) ─────────────────────────────────────────────────
74
- // Video is a separate generation kind, not an image model. Keep it out of the
75
- // image model unions/helpers above so `grok-` image classification is unaffected.
76
- const GROK_FALLBACK_VIDEO_MODEL = "grok-imagine-video";
77
- export const VALID_GROK_VIDEO_MODELS = new Set(["grok-imagine-video", "grok-imagine-video-1.5-preview"]);
78
- export const VALID_VIDEO_RESOLUTIONS = new Set(["480p", "720p"]);
79
- export const VALID_VIDEO_ASPECT_RATIOS = new Set([
80
- "1:1",
81
- "16:9",
82
- "9:16",
83
- "4:3",
84
- "3:4",
85
- "3:2",
86
- "2:3",
87
- "auto",
88
- ]);
89
- export const MIN_VIDEO_DURATION = 1;
90
- export const MAX_VIDEO_DURATION = 15;
91
- // reference-to-video (xAI): up to 7 reference images, max 10s duration.
92
- export const MAX_REF2V_REFERENCES = 7;
93
- export const MAX_REF2V_DURATION = 10;
94
-
95
- export type GrokVideoModel = "grok-imagine-video" | "grok-imagine-video-1.5-preview";
96
- export type VideoResolution = "480p" | "720p";
97
- export type VideoAspectRatio = "1:1" | "16:9" | "9:16" | "4:3" | "3:4" | "3:2" | "2:3" | "auto";
98
- export type VideoMode = "text-to-video" | "image-to-video" | "reference-to-video";
99
-
100
- // Mode is derived purely from the number of attached reference images.
101
- export function deriveVideoMode(refCount: number): VideoMode {
102
- if (refCount >= 2) return "reference-to-video";
103
- if (refCount === 1) return "image-to-video";
104
- return "text-to-video";
105
- }
106
-
107
- // Clamp duration to the reference-to-video ceiling; other modes keep their value.
108
- export function clampVideoDuration(duration: number, mode: VideoMode): number {
109
- return mode === "reference-to-video" ? Math.min(duration, MAX_REF2V_DURATION) : duration;
110
- }
111
-
112
- export function isGrokVideoModel(value: unknown): value is GrokVideoModel {
113
- return typeof value === "string" && VALID_GROK_VIDEO_MODELS.has(value);
114
- }
115
-
116
- export function normalizeGrokVideoModel(rawModel: unknown) {
117
- if (typeof rawModel !== "string" || rawModel.length === 0) {
118
- return { model: GROK_FALLBACK_VIDEO_MODEL };
119
- }
120
- if (!VALID_GROK_VIDEO_MODELS.has(rawModel)) {
121
- return {
122
- error: `Grok video model must be one of: ${[...VALID_GROK_VIDEO_MODELS].join(", ")}`,
123
- code: "INVALID_GROK_VIDEO_MODEL" as const,
124
- status: 400 as const,
125
- };
126
- }
127
- return { model: rawModel };
128
- }
129
-
130
- export function normalizeVideoResolution(raw: unknown) {
131
- if (raw === undefined || raw === null || raw === "") return { resolution: "480p" as const };
132
- if (typeof raw !== "string" || !VALID_VIDEO_RESOLUTIONS.has(raw)) {
133
- return {
134
- error: `resolution must be one of: ${[...VALID_VIDEO_RESOLUTIONS].join(", ")}`,
135
- code: "INVALID_VIDEO_RESOLUTION" as const,
136
- status: 400 as const,
137
- };
138
- }
139
- return { resolution: raw as VideoResolution };
140
- }
141
-
142
- export function normalizeVideoAspectRatio(raw: unknown) {
143
- if (raw === undefined || raw === null || raw === "") return { aspectRatio: "auto" as const };
144
- if (typeof raw !== "string" || !VALID_VIDEO_ASPECT_RATIOS.has(raw)) {
145
- return {
146
- error: `aspectRatio must be one of: ${[...VALID_VIDEO_ASPECT_RATIOS].join(", ")}`,
147
- code: "INVALID_VIDEO_ASPECT_RATIO" as const,
148
- status: 400 as const,
149
- };
150
- }
151
- return { aspectRatio: raw as VideoAspectRatio };
152
- }
153
-
154
- export function normalizeVideoDuration(raw: unknown) {
155
- if (raw === undefined || raw === null || raw === "") return { duration: 5 };
156
- const n = typeof raw === "number" ? raw : Number(raw);
157
- if (!Number.isInteger(n) || n < MIN_VIDEO_DURATION || n > MAX_VIDEO_DURATION) {
158
- return {
159
- error: `duration must be an integer between ${MIN_VIDEO_DURATION} and ${MAX_VIDEO_DURATION} seconds`,
160
- code: "INVALID_VIDEO_DURATION" as const,
161
- status: 400 as const,
162
- };
163
- }
164
- return { duration: n };
165
- }