ima2-gen 1.1.21 → 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 (208) hide show
  1. package/README.md +30 -4
  2. package/bin/ima2.js +14 -4
  3. package/bin/lib/platform.js +34 -5
  4. package/docs/README.ko.md +31 -0
  5. package/lib/agentQueueWorker.js +6 -0
  6. package/lib/agentRuntime.js +3 -2
  7. package/lib/atomicWrite.js +14 -0
  8. package/lib/grokProxyLauncher.js +5 -3
  9. package/lib/inflight.js +1 -1
  10. package/lib/oauthLauncher.js +5 -0
  11. package/lib/videoFrameExtract.js +3 -3
  12. package/package.json +5 -7
  13. package/routes/edit.js +2 -1
  14. package/routes/generate.js +4 -3
  15. package/routes/health.js +4 -3
  16. package/routes/multimode.js +2 -1
  17. package/routes/video.js +4 -2
  18. package/server.js +29 -2
  19. package/ui/dist/.vite/manifest.json +12 -12
  20. package/ui/dist/assets/{AgentWorkspace-B_hq9CLg.js → AgentWorkspace-COxQ5TjU.js} +1 -1
  21. package/ui/dist/assets/{CardNewsWorkspace-wD12J7qk.js → CardNewsWorkspace-B0OkcuVz.js} +1 -1
  22. package/ui/dist/assets/{NodeCanvas-CI_wuPMf.js → NodeCanvas-BSsclEBh.js} +1 -1
  23. package/ui/dist/assets/{PromptBuilderPanel-CUTujJUV.js → PromptBuilderPanel-DpC9A5Rz.js} +1 -1
  24. package/ui/dist/assets/{PromptImportDialog-CUi66jPK.js → PromptImportDialog-CVwT0rLd.js} +2 -2
  25. package/ui/dist/assets/{PromptImportDiscoverySection-Cm3vrjY4.js → PromptImportDiscoverySection-BDCkRCRs.js} +1 -1
  26. package/ui/dist/assets/{PromptImportFolderSection-DOtWTD9n.js → PromptImportFolderSection-QoKbZD83.js} +1 -1
  27. package/ui/dist/assets/{PromptLibraryPanel-BMjQegRa.js → PromptLibraryPanel-BhFgeKnY.js} +2 -2
  28. package/ui/dist/assets/SettingsWorkspace-CfjrlH5R.js +1 -0
  29. package/ui/dist/assets/index-C-mur7pa.css +1 -0
  30. package/ui/dist/assets/index-CCP5nUOj.js +42 -0
  31. package/ui/dist/assets/{index-31uVIdt4.js → index-Cxhzi3bs.js} +1 -1
  32. package/ui/dist/index.html +2 -2
  33. package/bin/commands/annotate.ts +0 -119
  34. package/bin/commands/cancel.ts +0 -48
  35. package/bin/commands/canvas-versions.ts +0 -80
  36. package/bin/commands/capabilities.ts +0 -110
  37. package/bin/commands/cardnews.ts +0 -249
  38. package/bin/commands/comfy.ts +0 -54
  39. package/bin/commands/config.ts +0 -186
  40. package/bin/commands/defaults.ts +0 -192
  41. package/bin/commands/doctor.ts +0 -202
  42. package/bin/commands/edit.ts +0 -150
  43. package/bin/commands/gen.ts +0 -214
  44. package/bin/commands/grok.ts +0 -90
  45. package/bin/commands/history.ts +0 -146
  46. package/bin/commands/ls.ts +0 -64
  47. package/bin/commands/metadata.ts +0 -39
  48. package/bin/commands/multimode.ts +0 -196
  49. package/bin/commands/node.ts +0 -166
  50. package/bin/commands/observability.ts +0 -176
  51. package/bin/commands/ping.ts +0 -31
  52. package/bin/commands/prompt-sub/build.ts +0 -101
  53. package/bin/commands/prompt.ts +0 -492
  54. package/bin/commands/ps.ts +0 -81
  55. package/bin/commands/session.ts +0 -266
  56. package/bin/commands/show.ts +0 -72
  57. package/bin/commands/skill.ts +0 -70
  58. package/bin/commands/video.ts +0 -442
  59. package/bin/ima2.ts +0 -430
  60. package/bin/lib/args.ts +0 -92
  61. package/bin/lib/browser-id.ts +0 -16
  62. package/bin/lib/client.ts +0 -122
  63. package/bin/lib/config-store.ts +0 -120
  64. package/bin/lib/destructive-confirm.ts +0 -19
  65. package/bin/lib/doctor-checks.ts +0 -91
  66. package/bin/lib/error-hints.ts +0 -23
  67. package/bin/lib/files.ts +0 -39
  68. package/bin/lib/output.ts +0 -73
  69. package/bin/lib/platform.ts +0 -99
  70. package/bin/lib/recover-output.ts +0 -139
  71. package/bin/lib/sse.ts +0 -73
  72. package/bin/lib/star-prompt.ts +0 -97
  73. package/bin/lib/storage-doctor.ts +0 -39
  74. package/bin/lib/ui-build.ts +0 -85
  75. package/config.ts +0 -354
  76. package/lib/agentCommandParser.ts +0 -69
  77. package/lib/agentGenerationPlanner.ts +0 -273
  78. package/lib/agentQuestionResponder.ts +0 -266
  79. package/lib/agentQueueStore.ts +0 -270
  80. package/lib/agentQueueWorker.ts +0 -89
  81. package/lib/agentRuntime.ts +0 -604
  82. package/lib/agentSettings.ts +0 -72
  83. package/lib/agentStore.ts +0 -422
  84. package/lib/agentStoreRows.ts +0 -136
  85. package/lib/agentTypes.ts +0 -154
  86. package/lib/apiCachePolicy.ts +0 -11
  87. package/lib/assetLifecycle.ts +0 -146
  88. package/lib/canvasVersionStore.ts +0 -223
  89. package/lib/capabilities.ts +0 -126
  90. package/lib/cardNewsGenerator.ts +0 -271
  91. package/lib/cardNewsJobStore.ts +0 -142
  92. package/lib/cardNewsManifestStore.ts +0 -154
  93. package/lib/cardNewsPlanner.ts +0 -236
  94. package/lib/cardNewsPlannerClient.ts +0 -155
  95. package/lib/cardNewsPlannerPrompt.ts +0 -62
  96. package/lib/cardNewsPlannerSchema.ts +0 -321
  97. package/lib/cardNewsRoleTemplateStore.ts +0 -47
  98. package/lib/cardNewsTemplateStore.ts +0 -252
  99. package/lib/codexDetect.ts +0 -71
  100. package/lib/comfyBridge.ts +0 -235
  101. package/lib/composerSnapshot.ts +0 -33
  102. package/lib/configKeys.ts +0 -62
  103. package/lib/db.ts +0 -295
  104. package/lib/errInfo.ts +0 -43
  105. package/lib/errorClassify.ts +0 -100
  106. package/lib/generationCancel.ts +0 -28
  107. package/lib/generationErrors.ts +0 -238
  108. package/lib/grokImageAdapter.ts +0 -513
  109. package/lib/grokMultimodeAdapter.ts +0 -84
  110. package/lib/grokProxyLauncher.ts +0 -153
  111. package/lib/grokRuntime.ts +0 -23
  112. package/lib/grokSizeMapper.ts +0 -71
  113. package/lib/grokVideoAdapter.ts +0 -458
  114. package/lib/grokVideoCanvas.ts +0 -26
  115. package/lib/grokVideoDownload.ts +0 -59
  116. package/lib/grokVideoPlannerPrompt.ts +0 -67
  117. package/lib/historyIndex.ts +0 -51
  118. package/lib/historyList.ts +0 -181
  119. package/lib/imageMetadata.ts +0 -113
  120. package/lib/imageMetadataStore.ts +0 -67
  121. package/lib/imageModels.ts +0 -165
  122. package/lib/inflight.ts +0 -281
  123. package/lib/localImportStore.ts +0 -114
  124. package/lib/logger.ts +0 -161
  125. package/lib/nodeStore.ts +0 -91
  126. package/lib/oauthLauncher.ts +0 -94
  127. package/lib/oauthNormalize.ts +0 -30
  128. package/lib/oauthProxy/errors.ts +0 -128
  129. package/lib/oauthProxy/generators.ts +0 -494
  130. package/lib/oauthProxy/index.ts +0 -28
  131. package/lib/oauthProxy/prompts.ts +0 -123
  132. package/lib/oauthProxy/references.ts +0 -45
  133. package/lib/oauthProxy/runtime.ts +0 -115
  134. package/lib/oauthProxy/streams.ts +0 -232
  135. package/lib/oauthProxy/types.ts +0 -9
  136. package/lib/oauthProxy.ts +0 -3
  137. package/lib/openDirectory.ts +0 -47
  138. package/lib/pngInfo.ts +0 -26
  139. package/lib/promptBuilder/attachments.ts +0 -74
  140. package/lib/promptBuilder/client.ts +0 -130
  141. package/lib/promptBuilder/constants.ts +0 -9
  142. package/lib/promptBuilder/context.ts +0 -36
  143. package/lib/promptBuilder/errors.ts +0 -12
  144. package/lib/promptBuilder/requestSchema.ts +0 -56
  145. package/lib/promptBuilder/responseParser.ts +0 -219
  146. package/lib/promptBuilder/systemPrompt.ts +0 -135
  147. package/lib/promptBuilder/transport.ts +0 -94
  148. package/lib/promptBuilder/types.ts +0 -109
  149. package/lib/promptImport/curatedSources.ts +0 -141
  150. package/lib/promptImport/discoveryRegistry.ts +0 -329
  151. package/lib/promptImport/errors.ts +0 -18
  152. package/lib/promptImport/githubDiscovery.ts +0 -309
  153. package/lib/promptImport/githubFolder.ts +0 -397
  154. package/lib/promptImport/githubSource.ts +0 -257
  155. package/lib/promptImport/gptImageHints.ts +0 -70
  156. package/lib/promptImport/parsePromptCandidates.ts +0 -179
  157. package/lib/promptImport/promptIndex.ts +0 -326
  158. package/lib/promptImport/rankPromptCandidates.ts +0 -65
  159. package/lib/promptImport/types.ts +0 -103
  160. package/lib/promptSafetyPolicy.ts +0 -5
  161. package/lib/providerOptions.ts +0 -56
  162. package/lib/referenceImageCompress.ts +0 -84
  163. package/lib/refs.ts +0 -133
  164. package/lib/requestLogger.ts +0 -49
  165. package/lib/responsesDoctor.ts +0 -456
  166. package/lib/responsesErrors.ts +0 -83
  167. package/lib/responsesFallback.ts +0 -114
  168. package/lib/responsesImageAdapter.ts +0 -466
  169. package/lib/responsesParse.ts +0 -452
  170. package/lib/responsesTools.ts +0 -28
  171. package/lib/runtimeContext.ts +0 -146
  172. package/lib/runtimePorts.ts +0 -105
  173. package/lib/sessionStore.ts +0 -308
  174. package/lib/storageMigration.ts +0 -310
  175. package/lib/styleSheet.ts +0 -139
  176. package/lib/systemTrash.ts +0 -20
  177. package/lib/videoContinuity.ts +0 -180
  178. package/lib/videoFrameExtract.ts +0 -78
  179. package/lib/videoSeriesChain.ts +0 -29
  180. package/lib/visibleTextLanguagePolicy.ts +0 -7
  181. package/routes/agent.ts +0 -308
  182. package/routes/annotations.ts +0 -118
  183. package/routes/canvasVersions.ts +0 -69
  184. package/routes/capabilities.ts +0 -18
  185. package/routes/cardNews.ts +0 -211
  186. package/routes/comfy.ts +0 -43
  187. package/routes/edit.ts +0 -352
  188. package/routes/generate.ts +0 -492
  189. package/routes/grok.ts +0 -24
  190. package/routes/health.ts +0 -123
  191. package/routes/history.ts +0 -221
  192. package/routes/imageImport.ts +0 -37
  193. package/routes/index.ts +0 -52
  194. package/routes/metadata.ts +0 -77
  195. package/routes/multimode.ts +0 -499
  196. package/routes/nodes.ts +0 -578
  197. package/routes/promptBuilder.ts +0 -37
  198. package/routes/promptImport.ts +0 -379
  199. package/routes/prompts.ts +0 -428
  200. package/routes/quota.ts +0 -89
  201. package/routes/sessions.ts +0 -317
  202. package/routes/storage.ts +0 -47
  203. package/routes/video.ts +0 -300
  204. package/routes/videoExtended.ts +0 -284
  205. package/server.ts +0 -293
  206. package/ui/dist/assets/SettingsWorkspace-PiaVnsdA.js +0 -1
  207. package/ui/dist/assets/index-CjgnNtgt.css +0 -1
  208. package/ui/dist/assets/index-Da2s4_-5.js +0 -36
@@ -1,181 +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
- videoContinuity: meta?.videoContinuity || null,
41
- createdAt: meta?.createdAt || st?.mtimeMs || 0,
42
- prompt: meta?.prompt || null,
43
- userPrompt: meta?.userPrompt || meta?.prompt || null,
44
- revisedPrompt: meta?.revisedPrompt || null,
45
- promptMode: meta?.promptMode || null,
46
- composerPrompt: meta?.composerPrompt ?? null,
47
- composerInsertedPrompts: meta?.composerInsertedPrompts ?? null,
48
- quality: meta?.quality || null,
49
- size: meta?.size || null,
50
- format: meta?.format || name.split(".").pop(),
51
- model: meta?.model || null,
52
- reasoningEffort: meta?.reasoningEffort ?? null,
53
- elapsed: meta?.elapsed ?? null,
54
- provider: meta?.provider || "oauth",
55
- usage: meta?.usage || null,
56
- webSearchCalls: meta?.webSearchCalls || 0,
57
- sessionId: meta?.sessionId || null,
58
- nodeId: meta?.nodeId || null,
59
- parentNodeId: meta?.parentNodeId || null,
60
- clientNodeId: meta?.clientNodeId || null,
61
- requestId: meta?.requestId || null,
62
- kind: meta?.kind || null,
63
- canvasVersion: Boolean(meta?.canvasVersion),
64
- canvasSourceFilename: meta?.canvasSourceFilename || null,
65
- canvasEditableFilename: meta?.canvasEditableFilename || null,
66
- canvasMergedAt: Number.isFinite(meta?.canvasMergedAt) ? meta.canvasMergedAt : null,
67
- setId: meta?.setId || null,
68
- cardId: meta?.cardId || null,
69
- cardOrder: Number.isFinite(meta?.cardOrder) ? meta.cardOrder : null,
70
- headline: meta?.headline || null,
71
- body: meta?.body || null,
72
- cards: meta?.cards || null,
73
- refsCount: Number.isFinite(meta?.refsCount) ? meta.refsCount : 0,
74
- sequenceId: meta?.sequenceId || null,
75
- sequenceIndex: Number.isFinite(meta?.sequenceIndex) ? meta.sequenceIndex : null,
76
- sequenceTotalRequested: Number.isFinite(meta?.sequenceTotalRequested) ? meta.sequenceTotalRequested : null,
77
- sequenceTotalReturned: Number.isFinite(meta?.sequenceTotalReturned) ? meta.sequenceTotalReturned : null,
78
- sequenceStatus: meta?.sequenceStatus || null,
79
- };
80
- }));
81
-
82
- rows.push(...setRows);
83
- rows.sort((a, b) => {
84
- if (b.createdAt !== a.createdAt) return b.createdAt - a.createdAt;
85
- return b.filename < a.filename ? -1 : b.filename > a.filename ? 1 : 0;
86
- });
87
-
88
- return rows;
89
- }
90
-
91
- async function readImageSidecar(full: string, rel: string) {
92
- const sibling = full.replace(/\.(png|jpe?g|webp)$/i, ".json");
93
- const candidates = new Set([`${full}.json`]);
94
- if (sibling !== full) candidates.add(sibling);
95
- for (const candidate of candidates) {
96
- try {
97
- return JSON.parse(await readFile(candidate, "utf-8"));
98
- } catch (e) {
99
- const err = errInfo(e);
100
- if (err.code !== "ENOENT") console.warn("[history] sidecar parse fail:", rel, err.message);
101
- }
102
- }
103
- return null;
104
- }
105
-
106
- async function readImageMetadata(full: string, rel: string) {
107
- const sidecar = await readImageSidecar(full, rel);
108
- if (sidecar) return sidecar;
109
- if (/\.mp4$/i.test(full)) return null;
110
- try {
111
- const embedded = await readEmbeddedImageMetadataFromFile(full);
112
- return embedded.metadata;
113
- } catch (e) {
114
- const err = errInfo(e);
115
- if (err.code !== "ENOENT") console.warn("[history] embedded metadata read fail:", rel, err.message);
116
- return null;
117
- }
118
- }
119
-
120
- async function listCardNewsSetRows(baseDir: string) {
121
- const root = join(baseDir, "cardnews");
122
- const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
123
- const rows: any[] = [];
124
- for (const entry of entries) {
125
- if (!entry.isDirectory()) continue;
126
- try {
127
- const manifestPath = join(root, entry.name, "manifest.json");
128
- const manifest = JSON.parse(await readFile(manifestPath, "utf-8")) as any;
129
- const first = (manifest.cards || []).find((card: any) => card.imageFilename);
130
- const filename = `cardnews/${entry.name}/manifest.json`;
131
- rows.push({
132
- filename,
133
- url: first?.imageFilename
134
- ? `/generated/cardnews/${encodeURIComponent(entry.name)}/${encodeURIComponent(first.imageFilename)}`
135
- : "",
136
- createdAt: manifest.createdAt || 0,
137
- prompt: null,
138
- userPrompt: null,
139
- revisedPrompt: null,
140
- promptMode: null,
141
- composerPrompt: null,
142
- composerInsertedPrompts: null,
143
- quality: null,
144
- size: manifest.size || null,
145
- format: "card-news-set",
146
- model: null,
147
- provider: "oauth",
148
- usage: null,
149
- webSearchCalls: 0,
150
- sessionId: manifest.sessionId || null,
151
- nodeId: null,
152
- parentNodeId: null,
153
- clientNodeId: null,
154
- requestId: manifest.requestId || null,
155
- kind: "card-news-set",
156
- setId: manifest.setId || entry.name,
157
- cardId: null,
158
- cardOrder: null,
159
- title: manifest.title || "Untitled card news",
160
- headline: manifest.title || "Untitled card news",
161
- body: null,
162
- cards: (manifest.cards || []).map((card: any) => ({
163
- url: card.imageFilename
164
- ? `/generated/cardnews/${encodeURIComponent(entry.name)}/${encodeURIComponent(card.imageFilename)}`
165
- : "",
166
- headline: card.headline,
167
- body: card.body,
168
- cardOrder: card.cardOrder,
169
- imageFilename: card.imageFilename,
170
- status: card.status || "generated",
171
- })),
172
- refsCount: 0,
173
- dir: dirname(manifestPath),
174
- });
175
- } catch (e) {
176
- const err = errInfo(e);
177
- if (err.code !== "ENOENT") console.warn("[history] card-news manifest parse fail:", entry.name, err.message);
178
- }
179
- }
180
- return rows;
181
- }
@@ -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
- }