ima2-gen 1.1.21 → 1.1.23

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 (214) hide show
  1. package/README.md +44 -7
  2. package/bin/commands/video.js +14 -0
  3. package/bin/ima2.js +14 -4
  4. package/bin/lib/platform.js +34 -5
  5. package/docs/README.ko.md +43 -2
  6. package/lib/agentQueueWorker.js +6 -0
  7. package/lib/agentRuntime.js +3 -2
  8. package/lib/atomicWrite.js +14 -0
  9. package/lib/grokImageAdapter.js +6 -0
  10. package/lib/grokProxyLauncher.js +5 -3
  11. package/lib/grokVideoAdapter.js +1 -1
  12. package/lib/grokVideoPlannerPrompt.js +10 -0
  13. package/lib/inflight.js +1 -1
  14. package/lib/oauthLauncher.js +5 -0
  15. package/lib/videoFrameExtract.js +3 -3
  16. package/package.json +5 -7
  17. package/routes/capabilities.js +13 -0
  18. package/routes/edit.js +2 -1
  19. package/routes/generate.js +32 -6
  20. package/routes/health.js +4 -3
  21. package/routes/multimode.js +2 -1
  22. package/routes/video.js +35 -3
  23. package/server.js +29 -2
  24. package/skills/ima2/SKILL.md +48 -6
  25. package/ui/dist/.vite/manifest.json +12 -12
  26. package/ui/dist/assets/{AgentWorkspace-B_hq9CLg.js → AgentWorkspace-C21zqdTZ.js} +1 -1
  27. package/ui/dist/assets/{CardNewsWorkspace-wD12J7qk.js → CardNewsWorkspace-BN-ga1lG.js} +1 -1
  28. package/ui/dist/assets/{NodeCanvas-CI_wuPMf.js → NodeCanvas-BbMa4IhI.js} +1 -1
  29. package/ui/dist/assets/{PromptBuilderPanel-CUTujJUV.js → PromptBuilderPanel-DRwBJRDQ.js} +1 -1
  30. package/ui/dist/assets/{PromptImportDialog-CUi66jPK.js → PromptImportDialog-Dp85kHCq.js} +2 -2
  31. package/ui/dist/assets/{PromptImportDiscoverySection-Cm3vrjY4.js → PromptImportDiscoverySection-BE8Q8MLD.js} +1 -1
  32. package/ui/dist/assets/{PromptImportFolderSection-DOtWTD9n.js → PromptImportFolderSection-PtH5x0sc.js} +1 -1
  33. package/ui/dist/assets/{PromptLibraryPanel-BMjQegRa.js → PromptLibraryPanel-FnM9tHI9.js} +2 -2
  34. package/ui/dist/assets/SettingsWorkspace-MARPGyBL.js +1 -0
  35. package/ui/dist/assets/index-BAFI6htx.js +42 -0
  36. package/ui/dist/assets/{index-31uVIdt4.js → index-BSXxr_Bt.js} +1 -1
  37. package/ui/dist/assets/index-DS-ADE7U.css +1 -0
  38. package/ui/dist/index.html +2 -2
  39. package/bin/commands/annotate.ts +0 -119
  40. package/bin/commands/cancel.ts +0 -48
  41. package/bin/commands/canvas-versions.ts +0 -80
  42. package/bin/commands/capabilities.ts +0 -110
  43. package/bin/commands/cardnews.ts +0 -249
  44. package/bin/commands/comfy.ts +0 -54
  45. package/bin/commands/config.ts +0 -186
  46. package/bin/commands/defaults.ts +0 -192
  47. package/bin/commands/doctor.ts +0 -202
  48. package/bin/commands/edit.ts +0 -150
  49. package/bin/commands/gen.ts +0 -214
  50. package/bin/commands/grok.ts +0 -90
  51. package/bin/commands/history.ts +0 -146
  52. package/bin/commands/ls.ts +0 -64
  53. package/bin/commands/metadata.ts +0 -39
  54. package/bin/commands/multimode.ts +0 -196
  55. package/bin/commands/node.ts +0 -166
  56. package/bin/commands/observability.ts +0 -176
  57. package/bin/commands/ping.ts +0 -31
  58. package/bin/commands/prompt-sub/build.ts +0 -101
  59. package/bin/commands/prompt.ts +0 -492
  60. package/bin/commands/ps.ts +0 -81
  61. package/bin/commands/session.ts +0 -266
  62. package/bin/commands/show.ts +0 -72
  63. package/bin/commands/skill.ts +0 -70
  64. package/bin/commands/video.ts +0 -442
  65. package/bin/ima2.ts +0 -430
  66. package/bin/lib/args.ts +0 -92
  67. package/bin/lib/browser-id.ts +0 -16
  68. package/bin/lib/client.ts +0 -122
  69. package/bin/lib/config-store.ts +0 -120
  70. package/bin/lib/destructive-confirm.ts +0 -19
  71. package/bin/lib/doctor-checks.ts +0 -91
  72. package/bin/lib/error-hints.ts +0 -23
  73. package/bin/lib/files.ts +0 -39
  74. package/bin/lib/output.ts +0 -73
  75. package/bin/lib/platform.ts +0 -99
  76. package/bin/lib/recover-output.ts +0 -139
  77. package/bin/lib/sse.ts +0 -73
  78. package/bin/lib/star-prompt.ts +0 -97
  79. package/bin/lib/storage-doctor.ts +0 -39
  80. package/bin/lib/ui-build.ts +0 -85
  81. package/config.ts +0 -354
  82. package/lib/agentCommandParser.ts +0 -69
  83. package/lib/agentGenerationPlanner.ts +0 -273
  84. package/lib/agentQuestionResponder.ts +0 -266
  85. package/lib/agentQueueStore.ts +0 -270
  86. package/lib/agentQueueWorker.ts +0 -89
  87. package/lib/agentRuntime.ts +0 -604
  88. package/lib/agentSettings.ts +0 -72
  89. package/lib/agentStore.ts +0 -422
  90. package/lib/agentStoreRows.ts +0 -136
  91. package/lib/agentTypes.ts +0 -154
  92. package/lib/apiCachePolicy.ts +0 -11
  93. package/lib/assetLifecycle.ts +0 -146
  94. package/lib/canvasVersionStore.ts +0 -223
  95. package/lib/capabilities.ts +0 -126
  96. package/lib/cardNewsGenerator.ts +0 -271
  97. package/lib/cardNewsJobStore.ts +0 -142
  98. package/lib/cardNewsManifestStore.ts +0 -154
  99. package/lib/cardNewsPlanner.ts +0 -236
  100. package/lib/cardNewsPlannerClient.ts +0 -155
  101. package/lib/cardNewsPlannerPrompt.ts +0 -62
  102. package/lib/cardNewsPlannerSchema.ts +0 -321
  103. package/lib/cardNewsRoleTemplateStore.ts +0 -47
  104. package/lib/cardNewsTemplateStore.ts +0 -252
  105. package/lib/codexDetect.ts +0 -71
  106. package/lib/comfyBridge.ts +0 -235
  107. package/lib/composerSnapshot.ts +0 -33
  108. package/lib/configKeys.ts +0 -62
  109. package/lib/db.ts +0 -295
  110. package/lib/errInfo.ts +0 -43
  111. package/lib/errorClassify.ts +0 -100
  112. package/lib/generationCancel.ts +0 -28
  113. package/lib/generationErrors.ts +0 -238
  114. package/lib/grokImageAdapter.ts +0 -513
  115. package/lib/grokMultimodeAdapter.ts +0 -84
  116. package/lib/grokProxyLauncher.ts +0 -153
  117. package/lib/grokRuntime.ts +0 -23
  118. package/lib/grokSizeMapper.ts +0 -71
  119. package/lib/grokVideoAdapter.ts +0 -458
  120. package/lib/grokVideoCanvas.ts +0 -26
  121. package/lib/grokVideoDownload.ts +0 -59
  122. package/lib/grokVideoPlannerPrompt.ts +0 -67
  123. package/lib/historyIndex.ts +0 -51
  124. package/lib/historyList.ts +0 -181
  125. package/lib/imageMetadata.ts +0 -113
  126. package/lib/imageMetadataStore.ts +0 -67
  127. package/lib/imageModels.ts +0 -165
  128. package/lib/inflight.ts +0 -281
  129. package/lib/localImportStore.ts +0 -114
  130. package/lib/logger.ts +0 -161
  131. package/lib/nodeStore.ts +0 -91
  132. package/lib/oauthLauncher.ts +0 -94
  133. package/lib/oauthNormalize.ts +0 -30
  134. package/lib/oauthProxy/errors.ts +0 -128
  135. package/lib/oauthProxy/generators.ts +0 -494
  136. package/lib/oauthProxy/index.ts +0 -28
  137. package/lib/oauthProxy/prompts.ts +0 -123
  138. package/lib/oauthProxy/references.ts +0 -45
  139. package/lib/oauthProxy/runtime.ts +0 -115
  140. package/lib/oauthProxy/streams.ts +0 -232
  141. package/lib/oauthProxy/types.ts +0 -9
  142. package/lib/oauthProxy.ts +0 -3
  143. package/lib/openDirectory.ts +0 -47
  144. package/lib/pngInfo.ts +0 -26
  145. package/lib/promptBuilder/attachments.ts +0 -74
  146. package/lib/promptBuilder/client.ts +0 -130
  147. package/lib/promptBuilder/constants.ts +0 -9
  148. package/lib/promptBuilder/context.ts +0 -36
  149. package/lib/promptBuilder/errors.ts +0 -12
  150. package/lib/promptBuilder/requestSchema.ts +0 -56
  151. package/lib/promptBuilder/responseParser.ts +0 -219
  152. package/lib/promptBuilder/systemPrompt.ts +0 -135
  153. package/lib/promptBuilder/transport.ts +0 -94
  154. package/lib/promptBuilder/types.ts +0 -109
  155. package/lib/promptImport/curatedSources.ts +0 -141
  156. package/lib/promptImport/discoveryRegistry.ts +0 -329
  157. package/lib/promptImport/errors.ts +0 -18
  158. package/lib/promptImport/githubDiscovery.ts +0 -309
  159. package/lib/promptImport/githubFolder.ts +0 -397
  160. package/lib/promptImport/githubSource.ts +0 -257
  161. package/lib/promptImport/gptImageHints.ts +0 -70
  162. package/lib/promptImport/parsePromptCandidates.ts +0 -179
  163. package/lib/promptImport/promptIndex.ts +0 -326
  164. package/lib/promptImport/rankPromptCandidates.ts +0 -65
  165. package/lib/promptImport/types.ts +0 -103
  166. package/lib/promptSafetyPolicy.ts +0 -5
  167. package/lib/providerOptions.ts +0 -56
  168. package/lib/referenceImageCompress.ts +0 -84
  169. package/lib/refs.ts +0 -133
  170. package/lib/requestLogger.ts +0 -49
  171. package/lib/responsesDoctor.ts +0 -456
  172. package/lib/responsesErrors.ts +0 -83
  173. package/lib/responsesFallback.ts +0 -114
  174. package/lib/responsesImageAdapter.ts +0 -466
  175. package/lib/responsesParse.ts +0 -452
  176. package/lib/responsesTools.ts +0 -28
  177. package/lib/runtimeContext.ts +0 -146
  178. package/lib/runtimePorts.ts +0 -105
  179. package/lib/sessionStore.ts +0 -308
  180. package/lib/storageMigration.ts +0 -310
  181. package/lib/styleSheet.ts +0 -139
  182. package/lib/systemTrash.ts +0 -20
  183. package/lib/videoContinuity.ts +0 -180
  184. package/lib/videoFrameExtract.ts +0 -78
  185. package/lib/videoSeriesChain.ts +0 -29
  186. package/lib/visibleTextLanguagePolicy.ts +0 -7
  187. package/routes/agent.ts +0 -308
  188. package/routes/annotations.ts +0 -118
  189. package/routes/canvasVersions.ts +0 -69
  190. package/routes/capabilities.ts +0 -18
  191. package/routes/cardNews.ts +0 -211
  192. package/routes/comfy.ts +0 -43
  193. package/routes/edit.ts +0 -352
  194. package/routes/generate.ts +0 -492
  195. package/routes/grok.ts +0 -24
  196. package/routes/health.ts +0 -123
  197. package/routes/history.ts +0 -221
  198. package/routes/imageImport.ts +0 -37
  199. package/routes/index.ts +0 -52
  200. package/routes/metadata.ts +0 -77
  201. package/routes/multimode.ts +0 -499
  202. package/routes/nodes.ts +0 -578
  203. package/routes/promptBuilder.ts +0 -37
  204. package/routes/promptImport.ts +0 -379
  205. package/routes/prompts.ts +0 -428
  206. package/routes/quota.ts +0 -89
  207. package/routes/sessions.ts +0 -317
  208. package/routes/storage.ts +0 -47
  209. package/routes/video.ts +0 -300
  210. package/routes/videoExtended.ts +0 -284
  211. package/server.ts +0 -293
  212. package/ui/dist/assets/SettingsWorkspace-PiaVnsdA.js +0 -1
  213. package/ui/dist/assets/index-CjgnNtgt.css +0 -1
  214. package/ui/dist/assets/index-Da2s4_-5.js +0 -36
@@ -1,211 +0,0 @@
1
- import type { Express, Request, Response } from "express";
2
- import { listImageTemplates, readTemplatePreview } from "../lib/cardNewsTemplateStore.js";
3
- import { listRoleTemplates } from "../lib/cardNewsRoleTemplateStore.js";
4
- import { createCardNewsDraft } from "../lib/cardNewsPlanner.js";
5
- import { generateCardNewsSet } from "../lib/cardNewsGenerator.js";
6
- import {
7
- createCardNewsJob,
8
- finishCardNewsJob,
9
- getCardNewsJob,
10
- getCardNewsJobPlan,
11
- retryCardNewsJob,
12
- updateCardNewsJob,
13
- updateCardNewsJobCard,
14
- } from "../lib/cardNewsJobStore.js";
15
- import { listCardNewsSets, readCardNewsManifest, readCardNewsSetPlan } from "../lib/cardNewsManifestStore.js";
16
-
17
- import { errInfo } from "../lib/errInfo.js";
18
- import { requireRuntimeContext, type RouteRuntimeContext, type RuntimeContext } from "../lib/runtimeContext.js";
19
-
20
- interface CardLike {
21
- id?: string;
22
- cardId?: string;
23
- status?: string;
24
- error?: { message?: string } | string | null;
25
- headline?: string;
26
- body?: string;
27
- textFields?: unknown;
28
- imageFilename?: string | null;
29
- generatedAt?: string | number | null;
30
- setId?: string;
31
- }
32
-
33
- function sendError(res: Response, err: unknown) {
34
- const info = errInfo(err);
35
- const status = info.status || 500;
36
- res.status(status).json({
37
- error: {
38
- code: info.code || "CARD_NEWS_ERROR",
39
- message: info.message || "Card News request failed",
40
- },
41
- });
42
- }
43
-
44
- function runCardNewsJob(ctx: RuntimeContext, jobId: string, plan: unknown) {
45
- setImmediate(async () => {
46
- try {
47
- updateCardNewsJob(jobId, { status: "running" });
48
- await generateCardNewsSet(ctx, plan as Parameters<typeof generateCardNewsSet>[1], {
49
- onCardStart: (card: CardLike) => {
50
- updateCardNewsJobCard(jobId, card.cardId ?? "", { status: "generating", error: undefined });
51
- },
52
- onCardDone: (card: CardLike) => {
53
- const url = card.imageFilename && card.setId
54
- ? `/generated/cardnews/${encodeURIComponent(card.setId)}/${encodeURIComponent(card.imageFilename)}`
55
- : undefined;
56
- const errStr = card.error
57
- ? (typeof card.error === "object" && card.error && "message" in card.error
58
- ? card.error.message
59
- : (typeof card.error === "string" ? card.error : undefined))
60
- : undefined;
61
- updateCardNewsJobCard(jobId, card.cardId ?? "", {
62
- status: card.status || "generated",
63
- error: errStr,
64
- headline: card.headline,
65
- body: card.body,
66
- textFields: Array.isArray(card.textFields) ? card.textFields : [],
67
- imageFilename: card.imageFilename || undefined,
68
- generatedAt: card.generatedAt || undefined,
69
- url,
70
- });
71
- },
72
- });
73
- finishCardNewsJob(jobId);
74
- } catch (e) {
75
- const err = errInfo(e);
76
- updateCardNewsJob(jobId, {
77
- status: "error",
78
- error: err.message || "Card News job failed",
79
- });
80
- }
81
- });
82
- }
83
-
84
- export function registerCardNewsRoutes(app: Express, ctxRaw: RouteRuntimeContext) {
85
- const ctx = requireRuntimeContext(ctxRaw);
86
- app.get("/api/cardnews/image-templates", async (_req: Request, res: Response) => {
87
- try {
88
- res.json({ templates: await listImageTemplates(ctx) });
89
- } catch (err) {
90
- sendError(res, err);
91
- }
92
- });
93
-
94
- app.get("/api/cardnews/image-templates/:templateId/preview", async (req: Request<{ templateId: string }>, res: Response) => {
95
- try {
96
- const buf = await readTemplatePreview(ctx, req.params.templateId);
97
- res.type("image/png").send(buf);
98
- } catch (err) {
99
- sendError(res, err);
100
- }
101
- });
102
-
103
- app.get("/api/cardnews/role-templates", (_req: Request, res: Response) => {
104
- res.json({ templates: listRoleTemplates() });
105
- });
106
-
107
- app.get("/api/cardnews/sets", async (_req: Request, res: Response) => {
108
- try {
109
- res.json({ sets: await listCardNewsSets(ctx) });
110
- } catch (err) {
111
- sendError(res, err);
112
- }
113
- });
114
-
115
- app.get("/api/cardnews/sets/:setId", async (req: Request<{ setId: string }>, res: Response) => {
116
- try {
117
- res.json({ plan: await readCardNewsSetPlan(ctx, req.params.setId) });
118
- } catch (err) {
119
- sendError(res, err);
120
- }
121
- });
122
-
123
- app.get("/api/cardnews/sets/:setId/manifest", async (req: Request<{ setId: string }>, res: Response) => {
124
- try {
125
- const manifest = await readCardNewsManifest(ctx, req.params.setId);
126
- if (req.query.download === "1") {
127
- res.setHeader("Content-Disposition", `attachment; filename="${req.params.setId}-manifest.json"`);
128
- }
129
- res.type("application/json").send(JSON.stringify(manifest, null, 2));
130
- } catch (err) {
131
- sendError(res, err);
132
- }
133
- });
134
-
135
- app.post("/api/cardnews/draft", async (req: Request, res: Response) => {
136
- try {
137
- res.json(await createCardNewsDraft(ctx, (req.body ?? {}) as Parameters<typeof createCardNewsDraft>[1]));
138
- } catch (err) {
139
- sendError(res, err);
140
- }
141
- });
142
-
143
- app.post("/api/cardnews/generate", async (req: Request, res: Response) => {
144
- try {
145
- const result = await generateCardNewsSet(ctx, (req.body ?? {}) as Parameters<typeof generateCardNewsSet>[1]);
146
- res.json(result);
147
- } catch (err) {
148
- sendError(res, err);
149
- }
150
- });
151
-
152
- app.post("/api/cardnews/jobs", (req: Request, res: Response) => {
153
- try {
154
- const body = (req.body ?? {}) as Parameters<typeof createCardNewsJob>[0];
155
- const summary = createCardNewsJob(body);
156
- runCardNewsJob(ctx, summary.jobId, body);
157
- res.status(202).json(summary);
158
- } catch (err) {
159
- sendError(res, err);
160
- }
161
- });
162
-
163
- app.get("/api/cardnews/jobs/:jobId", (req: Request<{ jobId: string }>, res: Response) => {
164
- const job = getCardNewsJob(req.params.jobId);
165
- if (!job) {
166
- res.status(404).json({ error: { code: "CARD_NEWS_JOB_NOT_FOUND", message: "Job not found" } });
167
- return;
168
- }
169
- res.json(job);
170
- });
171
-
172
- app.post("/api/cardnews/jobs/:jobId/retry", (req: Request<{ jobId: string }>, res: Response) => {
173
- const plan = getCardNewsJobPlan(req.params.jobId);
174
- const body = (req.body ?? {}) as { cardIds?: string[] };
175
- const job = retryCardNewsJob(req.params.jobId, body.cardIds || []);
176
- if (!job) {
177
- res.status(404).json({ error: { code: "CARD_NEWS_JOB_NOT_FOUND", message: "Job not found" } });
178
- return;
179
- }
180
- if (plan) {
181
- const wanted = new Set(body.cardIds || []);
182
- const planObj = plan as { cards?: Array<{ id: string }> } & Record<string, unknown>;
183
- runCardNewsJob(ctx, req.params.jobId, {
184
- ...planObj,
185
- cards: (planObj.cards || []).filter((card: { id: string }) => wanted.has(card.id)),
186
- });
187
- }
188
- res.status(202).json(job);
189
- });
190
-
191
- app.post("/api/cardnews/cards/:cardId/regenerate", async (req: Request<{ cardId: string }>, res: Response) => {
192
- try {
193
- const body = (req.body ?? {}) as { cards?: CardLike[]; card?: CardLike } & Record<string, unknown>;
194
- const cards = Array.isArray(body.cards)
195
- ? body.cards.filter((card: CardLike) => card.id === req.params.cardId || card.cardId === req.params.cardId)
196
- : body.card ? [body.card] : [];
197
- const result = await generateCardNewsSet(ctx, { ...body, cards } as Parameters<typeof generateCardNewsSet>[1]);
198
- res.json(result);
199
- } catch (err) {
200
- sendError(res, err);
201
- }
202
- });
203
-
204
- app.post("/api/cardnews/export", (_req: Request, res: Response) => {
205
- res.status(202).json({
206
- ok: true,
207
- status: "planned",
208
- message: "Card News export is planned after the dev MVP generation slice.",
209
- });
210
- });
211
- }
package/routes/comfy.ts DELETED
@@ -1,43 +0,0 @@
1
- import type { Express, Request, Response } from "express";
2
- import { exportImageToComfy, isComfyBridgeError } from "../lib/comfyBridge.js";
3
- import { requireRuntimeContext, type RouteRuntimeContext } from "../lib/runtimeContext.js";
4
-
5
- const ALLOWED_BODY_KEYS = new Set(["filename"]);
6
-
7
- function hasExactBodyShape(body: unknown): body is { filename: string } {
8
- if (!body || typeof body !== "object" || Array.isArray(body)) return false;
9
- const obj = body as Record<string, unknown>;
10
- const keys = Object.keys(obj);
11
- return keys.length === 1 && ALLOWED_BODY_KEYS.has(keys[0]) && typeof obj.filename === "string";
12
- }
13
-
14
- function errorPayload(code: string, message: string) {
15
- return {
16
- ok: false,
17
- error: { code, message },
18
- };
19
- }
20
-
21
- export function registerComfyRoutes(app: Express, ctxRaw: RouteRuntimeContext) {
22
- const ctx = requireRuntimeContext(ctxRaw);
23
- app.post("/api/comfy/export-image", async (req: Request, res: Response) => {
24
- try {
25
- if (!hasExactBodyShape(req.body)) {
26
- return res.status(400).json(errorPayload(
27
- "COMFY_IMAGE_INVALID",
28
- "Request body must contain exactly one filename.",
29
- ));
30
- }
31
- const result = await exportImageToComfy(ctx, { filename: req.body.filename });
32
- return res.json(result);
33
- } catch (error) {
34
- if (isComfyBridgeError(error)) {
35
- return res.status((error as any).status).json(errorPayload((error as any).code, error.message));
36
- }
37
- return res.status(502).json(errorPayload(
38
- "COMFY_UPLOAD_FAILED",
39
- "Could not upload image to ComfyUI.",
40
- ));
41
- }
42
- });
43
- }
package/routes/edit.ts DELETED
@@ -1,352 +0,0 @@
1
- import { mkdir, writeFile } from "fs/promises";
2
- import { join } from "path";
3
- import { randomBytes } from "crypto";
4
- import type { Express, Request, Response } from "express";
5
- import { detectImageMimeFromB64 } from "../lib/refs.js";
6
- import { classifyUpstreamError } from "../lib/errorClassify.js";
7
- import { normalizeOAuthParams } from "../lib/oauthNormalize.js";
8
- import { resolveProviderOptions } from "../lib/providerOptions.js";
9
- import { editViaResponses } from "../lib/responsesImageAdapter.js";
10
- import { editViaGrok } from "../lib/grokImageAdapter.js";
11
- import { startJob, finishJob, registerJobAbortController, isJobCanceled } from "../lib/inflight.js";
12
- import {
13
- isGenerationCanceledError,
14
- makeGenerationCanceledError,
15
- throwIfJobCanceled,
16
- } from "../lib/generationCancel.js";
17
- import { logEvent, logError } from "../lib/logger.js";
18
- import { hasPngAlphaChannel, parsePngInfo } from "../lib/pngInfo.js";
19
- import { invalidateHistoryIndex } from "../lib/historyIndex.js";
20
-
21
- import { errInfo } from "../lib/errInfo.js";
22
- import { requireRuntimeContext, type RouteRuntimeContext, type RuntimeContext } from "../lib/runtimeContext.js";
23
- function validateModeration(ctx: RuntimeContext, moderation: unknown) {
24
- if (typeof moderation !== "string" || !ctx.config.oauth.validModeration.has(moderation)) {
25
- return { error: "moderation must be one of: auto, low" };
26
- }
27
- return { moderation };
28
- }
29
-
30
- function imageFormatFromMime(mime: string | null | undefined): "png" | "jpeg" | "webp" {
31
- if (mime === "image/jpeg") return "jpeg";
32
- if (mime === "image/webp") return "webp";
33
- return "png";
34
- }
35
-
36
- const MAX_EDIT_MASK_BYTES = 16 * 1024 * 1024;
37
- const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
38
-
39
- function stripPngDataUrl(value: unknown): string {
40
- if (typeof value !== "string") return "";
41
- return value.replace(/^data:image\/png;base64,/, "");
42
- }
43
-
44
- interface PngDecodeResult {
45
- b64?: string;
46
- buffer?: Buffer;
47
- info?: ReturnType<typeof parsePngInfo>;
48
- error?: string;
49
- code?: string;
50
- }
51
-
52
- function decodePngDataUrl(value: unknown, invalidCode: string, pngCode: string): PngDecodeResult {
53
- const b64 = stripPngDataUrl(value).replace(/\s+/g, "");
54
- if (!b64 || b64.length % 4 !== 0 || !BASE64_RE.test(b64)) {
55
- return { error: "image must be valid base64", code: invalidCode };
56
- }
57
- const buffer = Buffer.from(b64, "base64");
58
- if (buffer.length === 0 || buffer.toString("base64").replace(/=+$/, "") !== b64.replace(/=+$/, "")) {
59
- return { error: "image must be valid base64", code: invalidCode };
60
- }
61
- const info = parsePngInfo(buffer);
62
- if (info.error) return { error: "image must be a PNG image", code: pngCode };
63
- return { b64, buffer, info };
64
- }
65
-
66
- interface MaskValidationResult {
67
- mask?: string | null;
68
- maskBytes?: number;
69
- error?: string;
70
- code?: string;
71
- }
72
-
73
- function validateEditMask(imageB64: unknown, mask: unknown): MaskValidationResult {
74
- if (mask == null) return { mask: null, maskBytes: 0 };
75
- if (typeof mask !== "string" || mask.length === 0) {
76
- return { error: "mask must be a PNG data URL or base64 string", code: "INVALID_EDIT_MASK" };
77
- }
78
- const maskCheck = decodePngDataUrl(mask, "INVALID_EDIT_MASK_BASE64", "INVALID_EDIT_MASK_PNG");
79
- if (maskCheck.error || !maskCheck.buffer || !maskCheck.info) return maskCheck;
80
- if (maskCheck.buffer.length > MAX_EDIT_MASK_BYTES) {
81
- return { error: "mask is too large", code: "EDIT_MASK_TOO_LARGE" };
82
- }
83
- if (!hasPngAlphaChannel(maskCheck.info)) {
84
- return { error: "mask PNG must include an alpha channel", code: "EDIT_MASK_NO_ALPHA" };
85
- }
86
- const imageCheck = decodePngDataUrl(imageB64, "INVALID_EDIT_IMAGE_BASE64", "INVALID_EDIT_IMAGE_PNG");
87
- if (imageCheck.error || !imageCheck.info) return imageCheck;
88
- if (imageCheck.info.width !== maskCheck.info.width || imageCheck.info.height !== maskCheck.info.height) {
89
- return { error: "mask dimensions must match image dimensions", code: "EDIT_MASK_DIMENSION_MISMATCH" };
90
- }
91
- return { mask: maskCheck.b64, maskBytes: maskCheck.buffer.length };
92
- }
93
-
94
- export function registerEditRoutes(app: Express, ctxRaw: RouteRuntimeContext) {
95
- const ctx = requireRuntimeContext(ctxRaw);
96
- app.post("/api/edit", async (req: Request, res: Response) => {
97
- const requestId = typeof req.body?.requestId === "string" ? req.body.requestId : req.id;
98
- let finishStatus = "completed";
99
- let finishHttpStatus;
100
- let finishErrorCode;
101
- let finishMeta = {};
102
- let finishCanceled = false;
103
- const cancelController = new AbortController();
104
- try {
105
- const {
106
- prompt,
107
- image: imageB64,
108
- mask: rawMask,
109
- quality: rawQuality = "medium",
110
- size = "1024x1024",
111
- moderation = "low",
112
- provider = "oauth",
113
- mode: promptMode = "auto",
114
- model: rawModel,
115
- reasoningEffort: rawReasoningEffort,
116
- webSearchEnabled: rawWebSearchEnabled = true,
117
- } = req.body;
118
- const { quality, warnings: qualityWarnings } = normalizeOAuthParams({ provider, quality: rawQuality });
119
- const providerOptions = resolveProviderOptions(ctx, {
120
- provider,
121
- rawModel,
122
- rawReasoningEffort,
123
- rawSize: size,
124
- rawWebSearchEnabled,
125
- });
126
- if (providerOptions.error) {
127
- finishStatus = "error";
128
- finishHttpStatus = providerOptions.status;
129
- finishErrorCode = providerOptions.code;
130
- return res.status(providerOptions.status).json({ error: providerOptions.error, code: providerOptions.code });
131
- }
132
- const imageModel = providerOptions.model;
133
- const reasoningEffort = providerOptions.reasoningEffort;
134
- const effectiveSize = providerOptions.size;
135
- const webSearchEnabled = providerOptions.webSearchEnabled;
136
- const activeProvider = providerOptions.provider;
137
- const sessionId = typeof req.body?.sessionId === "string" ? req.body.sessionId : null;
138
- const normalizedPromptMode = promptMode === "direct" ? "direct" : "auto";
139
-
140
- startJob({
141
- requestId,
142
- kind: "classic",
143
- prompt,
144
- meta: {
145
- kind: "edit",
146
- sessionId,
147
- quality,
148
- model: imageModel,
149
- size: effectiveSize,
150
- },
151
- });
152
- registerJobAbortController(requestId, cancelController);
153
-
154
- if (!prompt || !imageB64) {
155
- finishStatus = "error";
156
- finishHttpStatus = 400;
157
- finishErrorCode = "INVALID_EDIT_INPUT";
158
- return res.status(400).json({ error: "Prompt and image are required" });
159
- }
160
- if (activeProvider === "grok" && rawMask) {
161
- finishStatus = "error";
162
- finishHttpStatus = 400;
163
- finishErrorCode = "GROK_MASK_UNSUPPORTED";
164
- return res.status(400).json({ error: "Grok provider does not support mask editing", code: "GROK_MASK_UNSUPPORTED" });
165
- }
166
- const maskCheck: any = validateEditMask(imageB64, rawMask);
167
- if (maskCheck.error) {
168
- finishStatus = "error";
169
- finishHttpStatus = 400;
170
- finishErrorCode = maskCheck.code;
171
- return res.status(400).json({ error: maskCheck.error, code: maskCheck.code });
172
- }
173
- const moderationCheck = validateModeration(ctx, moderation);
174
- if (moderationCheck.error) {
175
- finishStatus = "error";
176
- finishHttpStatus = 400;
177
- finishErrorCode = "INVALID_MODERATION";
178
- return res.status(400).json({ error: moderationCheck.error });
179
- }
180
-
181
- logEvent("edit", "request", {
182
- requestId,
183
- client: req.get("x-ima2-client") || "ui",
184
- provider: activeProvider,
185
- quality,
186
- model: imageModel,
187
- size: effectiveSize,
188
- moderation,
189
- sessionId,
190
- promptChars: typeof prompt === "string" ? prompt.length : 0,
191
- promptMode: normalizedPromptMode,
192
- webSearchEnabled,
193
- inputImageChars: typeof imageB64 === "string" ? imageB64.length : 0,
194
- maskPresent: Boolean(maskCheck.mask),
195
- maskBytes: maskCheck.maskBytes ?? 0,
196
- });
197
- const startTime = Date.now();
198
- let resultB64: string;
199
- let usage: Record<string, number> | null;
200
- let revisedPrompt: string | undefined;
201
- let webSearchCalls = 0;
202
- let resultMimeFromProvider: string | undefined;
203
-
204
- if (activeProvider === "grok") {
205
- const grokModel = quality === "high" ? "grok-imagine-image-quality" : imageModel;
206
- const r = await editViaGrok(prompt, imageB64, ctx, {
207
- model: grokModel,
208
- size: effectiveSize,
209
- signal: cancelController.signal,
210
- requestId,
211
- });
212
- resultB64 = r.b64;
213
- usage = r.usage;
214
- revisedPrompt = r.revisedPrompt;
215
- webSearchCalls = r.webSearchCalls;
216
- resultMimeFromProvider = r.mime;
217
- } else {
218
- const r = await editViaResponses(
219
- activeProvider,
220
- prompt,
221
- imageB64,
222
- quality,
223
- effectiveSize,
224
- moderation,
225
- normalizedPromptMode,
226
- ctx,
227
- requestId,
228
- {
229
- model: imageModel,
230
- reasoningEffort,
231
- webSearchEnabled,
232
- mask: maskCheck.mask,
233
- signal: cancelController.signal,
234
- },
235
- );
236
- resultB64 = r.b64;
237
- usage = r.usage ?? null;
238
- revisedPrompt = r.revisedPrompt ?? undefined;
239
- webSearchCalls = r.webSearchCalls ?? 0;
240
- }
241
- throwIfJobCanceled(requestId);
242
-
243
- const elapsed = +((Date.now() - startTime) / 1000).toFixed(1);
244
- await mkdir(ctx.config.storage.generatedDir, { recursive: true });
245
- throwIfJobCanceled(requestId);
246
- const editMime = activeProvider === "grok"
247
- ? (resultMimeFromProvider || detectImageMimeFromB64(resultB64) || "image/png")
248
- : "image/png";
249
- const editExt = activeProvider === "grok" ? imageFormatFromMime(editMime) : "png";
250
- const filename = `${Date.now()}_${randomBytes(ctx.config.ids.generatedHexBytes).toString("hex")}.${editExt}`;
251
- await writeFile(join(ctx.config.storage.generatedDir, filename), Buffer.from(resultB64, "base64"));
252
- const meta = {
253
- prompt,
254
- userPrompt: prompt,
255
- revisedPrompt: revisedPrompt || null,
256
- promptMode: normalizedPromptMode,
257
- quality,
258
- size: effectiveSize,
259
- moderation,
260
- model: imageModel,
261
- reasoningEffort,
262
- elapsed,
263
- format: editExt,
264
- provider: activeProvider,
265
- kind: "edit",
266
- requestId,
267
- createdAt: Date.now(),
268
- usage: usage || null,
269
- webSearchCalls,
270
- webSearchEnabled,
271
- };
272
- await writeFile(join(ctx.config.storage.generatedDir, filename + ".json"), JSON.stringify(meta)).catch(() => {});
273
- invalidateHistoryIndex();
274
- finishHttpStatus = 200;
275
- finishMeta = { filename, imageChars: resultB64.length };
276
- logEvent("edit", "saved", {
277
- requestId,
278
- filename,
279
- imageChars: resultB64.length,
280
- elapsedMs: Date.now() - startTime,
281
- });
282
-
283
- res.json({
284
- image: `data:${editMime};base64,${resultB64}`,
285
- elapsed,
286
- reasoningEffort,
287
- filename,
288
- usage,
289
- provider: activeProvider,
290
- model: activeProvider === "grok" ? (quality === "high" ? "grok-imagine-image-quality" : imageModel) : imageModel,
291
- moderation,
292
- warnings: qualityWarnings,
293
- revisedPrompt: revisedPrompt || null,
294
- promptMode: normalizedPromptMode,
295
- webSearchCalls,
296
- webSearchEnabled,
297
- });
298
- } catch (e) {
299
- const err = errInfo(e);
300
- const ext = (err.raw && typeof err.raw === "object" ? err.raw as Record<string, unknown> : {});
301
- const fallbackCode = err.code || classifyUpstreamError(err.message);
302
- if (isGenerationCanceledError(err.raw) || isJobCanceled(requestId)) {
303
- const canceled = makeGenerationCanceledError();
304
- finishCanceled = true;
305
- finishHttpStatus = canceled.status;
306
- finishErrorCode = canceled.code;
307
- return res.status(canceled.status).json({
308
- error: canceled.message,
309
- code: canceled.code,
310
- requestId,
311
- });
312
- }
313
- finishStatus = "error";
314
- finishHttpStatus = err.status || 500;
315
- finishErrorCode = fallbackCode || "EDIT_FAILED";
316
- logError("edit", "error", err.raw, { requestId, code: finishErrorCode });
317
- res.status(err.status || 500).json({
318
- error: err.message,
319
- code: fallbackCode,
320
- upstreamCode: ext.upstreamCode || null,
321
- upstreamType: ext.upstreamType || null,
322
- upstreamParam: ext.upstreamParam || null,
323
- diagnosticReason: ext.diagnosticReason || null,
324
- retryKind: ext.retryKind || null,
325
- initialEventCount: ext.initialEventCount ?? null,
326
- initialEventTypes: ext.initialEventTypes || null,
327
- referencesDroppedOnRetry: ext.referencesDroppedOnRetry ?? null,
328
- developerPromptDroppedOnRetry: ext.developerPromptDroppedOnRetry ?? null,
329
- webSearchDroppedOnRetry: ext.webSearchDroppedOnRetry ?? null,
330
- fallbackEventCount: ext.fallbackEventCount ?? null,
331
- fallbackEventTypes: ext.fallbackEventTypes || null,
332
- fallbackImageCallSeen: ext.fallbackImageCallSeen ?? null,
333
- fallbackImageResultCount: ext.fallbackImageResultCount ?? null,
334
- errorEventCount: ext.eventCount ?? null,
335
- eventTypes: ext.eventTypes || null,
336
- webSearchCalls: ext.webSearchCalls ?? null,
337
- responseDiagnostics: ext.responseDiagnostics || null,
338
- toolTypes: ext.toolTypes || null,
339
- toolChoiceKind: ext.toolChoiceKind || null,
340
- requestId,
341
- });
342
- } finally {
343
- finishJob(requestId, {
344
- canceled: finishCanceled,
345
- status: finishStatus,
346
- httpStatus: finishHttpStatus,
347
- errorCode: finishErrorCode,
348
- meta: finishMeta,
349
- });
350
- }
351
- });
352
- }