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,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
- }