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
package/lib/inflight.ts DELETED
@@ -1,281 +0,0 @@
1
- import { config } from "../config.js";
2
- import { getDb } from "./db.js";
3
- import { logEvent } from "./logger.js";
4
-
5
- // SQLite-backed inflight job registry.
6
- // Tracks generation requests that are currently running on the server so clients
7
- // can reconcile optimistic UI state after a reload or across tabs.
8
- //
9
- // A restarted process cannot continue the original upstream fetch, but keeping
10
- // metadata durable lets the UI reconcile requestIds and eventually prune stale
11
- // work without losing the recovery breadcrumb.
12
-
13
- interface InflightRow {
14
- request_id: string;
15
- kind: string;
16
- prompt?: string | null;
17
- meta?: string | null;
18
- session_id?: string | null;
19
- parent_node_id?: string | null;
20
- client_node_id?: string | null;
21
- started_at: number;
22
- phase?: string | null;
23
- phase_at?: number | null;
24
- }
25
-
26
- interface InflightJob {
27
- requestId: string;
28
- kind: string;
29
- prompt: string;
30
- meta: Record<string, unknown>;
31
- startedAt: number;
32
- phase: string;
33
- phaseAt: number;
34
- }
35
-
36
- interface TerminalJob {
37
- requestId: string;
38
- kind: string;
39
- status: string;
40
- startedAt: number;
41
- finishedAt: number;
42
- durationMs: number;
43
- phase: string;
44
- phaseAt: number;
45
- httpStatus?: number | undefined;
46
- errorCode?: string | undefined;
47
- prompt?: string | null;
48
- meta: Record<string, unknown>;
49
- }
50
-
51
- const terminalJobs = new Map<string, TerminalJob>(); // requestId -> terminal snapshot, active-only API stays default
52
- const abortControllers = new Map<string, AbortController>();
53
-
54
- // Phases: "queued" → "streaming" (upstream connection open, waiting for image)
55
- // → "decoding" (b64 received, writing to disk)
56
- export function startJob({ requestId, kind, prompt, meta = {} }: {
57
- requestId: string;
58
- kind: string;
59
- prompt?: string | null;
60
- meta?: Record<string, unknown>;
61
- }) {
62
- if (!requestId) return;
63
- const startedAt = Date.now();
64
- const normalizedPrompt = typeof prompt === "string" ? prompt.slice(0, 500) : "";
65
- const normalizedMeta = normalizeMeta(meta);
66
- getDb()
67
- .prepare(`
68
- INSERT OR REPLACE INTO inflight (
69
- request_id,
70
- kind,
71
- prompt,
72
- meta,
73
- session_id,
74
- parent_node_id,
75
- client_node_id,
76
- started_at,
77
- phase,
78
- phase_at
79
- )
80
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
81
- `)
82
- .run(
83
- requestId,
84
- kind,
85
- normalizedPrompt,
86
- JSON.stringify(normalizedMeta),
87
- stringOrNull(normalizedMeta.sessionId),
88
- stringOrNull(normalizedMeta.parentNodeId),
89
- stringOrNull(normalizedMeta.clientNodeId),
90
- startedAt,
91
- "queued",
92
- startedAt,
93
- );
94
- terminalJobs.delete(requestId);
95
- abortControllers.delete(requestId);
96
- logEvent("inflight", "start", {
97
- requestId,
98
- kind,
99
- sessionId: normalizedMeta.sessionId || null,
100
- parentNodeId: normalizedMeta.parentNodeId || null,
101
- clientNodeId: normalizedMeta.clientNodeId || null,
102
- promptChars: typeof prompt === "string" ? prompt.length : 0,
103
- });
104
- }
105
-
106
- export function registerJobAbortController(
107
- requestId: string | null | undefined,
108
- controller: AbortController,
109
- ) {
110
- if (!requestId) return;
111
- abortControllers.set(requestId, controller);
112
- }
113
-
114
- export function abortJob(requestId: string | null | undefined) {
115
- if (!requestId) return { requestId: "", active: false, aborted: false };
116
- const controller = abortControllers.get(requestId);
117
- const active = Boolean(getJob(requestId));
118
- let aborted = false;
119
- if (controller && !controller.signal.aborted) {
120
- controller.abort();
121
- aborted = true;
122
- }
123
- finishJob(requestId, {
124
- canceled: true,
125
- httpStatus: 499,
126
- errorCode: "GENERATION_CANCELED",
127
- });
128
- return { requestId, active, aborted };
129
- }
130
-
131
- export function isJobCanceled(requestId: string | null | undefined): boolean {
132
- if (!requestId) return false;
133
- return terminalJobs.get(requestId)?.status === "canceled";
134
- }
135
-
136
- export function setJobPhase(requestId: string | null | undefined, phase: string) {
137
- if (!requestId) return;
138
- const j = getJob(requestId);
139
- if (!j) return;
140
- getDb()
141
- .prepare("UPDATE inflight SET phase = ?, phase_at = ? WHERE request_id = ?")
142
- .run(phase, Date.now(), requestId);
143
- logEvent("inflight", "phase", { requestId, kind: j.kind, phase });
144
- }
145
-
146
- export function finishJob(requestId: string | null | undefined, options: any = {}) {
147
- if (!requestId) return;
148
- const j = getJob(requestId);
149
- if (j) {
150
- const finishedAt = Date.now();
151
- const status = options.canceled ? "canceled" : options.status || "completed";
152
- terminalJobs.set(requestId, {
153
- requestId,
154
- kind: j.kind,
155
- status,
156
- startedAt: j.startedAt,
157
- finishedAt,
158
- durationMs: finishedAt - j.startedAt,
159
- phase: j.phase,
160
- phaseAt: j.phaseAt,
161
- httpStatus: options.httpStatus,
162
- errorCode: options.errorCode,
163
- meta: {
164
- ...j.meta,
165
- ...(options.meta || {}),
166
- },
167
- });
168
- logEvent("inflight", "finish", {
169
- requestId,
170
- kind: j.kind,
171
- status,
172
- durationMs: finishedAt - j.startedAt,
173
- httpStatus: options.httpStatus,
174
- errorCode: options.errorCode,
175
- });
176
- }
177
- getDb().prepare("DELETE FROM inflight WHERE request_id = ?").run(requestId);
178
- abortControllers.delete(requestId);
179
- reapTerminalJobs();
180
- }
181
-
182
- function reapTerminalJobs() {
183
- const now = Date.now();
184
- for (const [id, j] of terminalJobs) {
185
- if (now - j.finishedAt > config.inflight.terminalTtlMs) terminalJobs.delete(id);
186
- }
187
- }
188
-
189
- export function listJobs(filters: any = {}) {
190
- purgeStaleJobs();
191
- const { kind, sessionId } = filters;
192
- const clauses: string[] = [];
193
- const params: unknown[] = [];
194
- if (kind) {
195
- clauses.push("kind = ?");
196
- params.push(kind);
197
- }
198
- if (sessionId) {
199
- clauses.push("session_id = ?");
200
- params.push(sessionId);
201
- }
202
- const where = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
203
- return getDb()
204
- .prepare(`SELECT * FROM inflight${where} ORDER BY started_at ASC`)
205
- .all(...params)
206
- .map((row) => rowToJob(row as InflightRow));
207
- }
208
-
209
- export function listTerminalJobs(filters: any = {}) {
210
- reapTerminalJobs();
211
- const { kind, sessionId } = filters;
212
- return Array.from(terminalJobs.values())
213
- .filter((j) => {
214
- if (kind && j.kind !== kind) return false;
215
- if (sessionId && j.meta?.sessionId !== sessionId) return false;
216
- return true;
217
- })
218
- .sort((a, b) => b.finishedAt - a.finishedAt);
219
- }
220
-
221
- export function _resetForTests() {
222
- getDb().prepare("DELETE FROM inflight").run();
223
- terminalJobs.clear();
224
- abortControllers.clear();
225
- }
226
-
227
- export function purgeStaleJobs(now = Date.now()) {
228
- getDb()
229
- .prepare("DELETE FROM inflight WHERE started_at < ?")
230
- .run(now - config.inflight.ttlMs);
231
- }
232
-
233
- function getJob(requestId: string): InflightJob | null {
234
- const row = getDb()
235
- .prepare("SELECT * FROM inflight WHERE request_id = ?")
236
- .get(requestId) as InflightRow | undefined;
237
- return row ? rowToJob(row) : null;
238
- }
239
-
240
- function rowToJob(row: InflightRow): InflightJob {
241
- const meta = normalizeMeta(parseMeta(row.meta));
242
- const sessionId = stringOrNull(row.session_id) ?? stringOrNull(meta.sessionId);
243
- const parentNodeId =
244
- stringOrNull(row.parent_node_id) ?? stringOrNull(meta.parentNodeId);
245
- const clientNodeId =
246
- stringOrNull(row.client_node_id) ?? stringOrNull(meta.clientNodeId);
247
- return {
248
- requestId: row.request_id,
249
- kind: row.kind,
250
- prompt: row.prompt || "",
251
- meta: {
252
- ...meta,
253
- ...(sessionId ? { sessionId } : {}),
254
- ...(parentNodeId ? { parentNodeId } : {}),
255
- ...(clientNodeId ? { clientNodeId } : {}),
256
- },
257
- startedAt: Number(row.started_at),
258
- phase: row.phase || "queued",
259
- phaseAt: Number(row.phase_at || row.started_at),
260
- };
261
- }
262
-
263
- function parseMeta(raw: unknown): Record<string, unknown> {
264
- if (typeof raw !== "string" || !raw) return {};
265
- try {
266
- const parsed: unknown = JSON.parse(raw);
267
- return parsed && typeof parsed === "object" && !Array.isArray(parsed)
268
- ? (parsed as Record<string, unknown>)
269
- : {};
270
- } catch {
271
- return {};
272
- }
273
- }
274
-
275
- function normalizeMeta(meta: unknown): Record<string, unknown> {
276
- return meta && typeof meta === "object" && !Array.isArray(meta) ? (meta as Record<string, unknown>) : {};
277
- }
278
-
279
- function stringOrNull(value: unknown): string | null {
280
- return typeof value === "string" && value.length > 0 ? value : null;
281
- }
@@ -1,114 +0,0 @@
1
- import type { RuntimeContext } from "./runtimeContext.js";
2
- import { mkdir, writeFile } from "fs/promises";
3
- import { basename, join, normalize } from "path";
4
- import { randomBytes } from "crypto";
5
- import { embedImageMetadataBestEffort } from "./imageMetadataStore.js";
6
- import { invalidateHistoryIndex } from "./historyIndex.js";
7
-
8
- const PNG_SIGNATURE_HEX = "89504e470d0a1a0a";
9
- const JPEG_SIGNATURE_HEX = "ffd8ff";
10
- const WEBP_RIFF_HEAD = "52494646";
11
- const WEBP_VP_TAIL = "57454250";
12
-
13
- function detectFormat(buffer: Buffer) {
14
- if (!Buffer.isBuffer(buffer) || buffer.length < 12) return null;
15
- const head8 = buffer.subarray(0, 8).toString("hex");
16
- if (head8 === PNG_SIGNATURE_HEX) return "png";
17
- if (head8.startsWith(JPEG_SIGNATURE_HEX)) return "jpeg";
18
- if (
19
- buffer.subarray(0, 4).toString("hex") === WEBP_RIFF_HEAD &&
20
- buffer.subarray(8, 12).toString("hex") === WEBP_VP_TAIL
21
- ) {
22
- return "webp";
23
- }
24
- return null;
25
- }
26
-
27
- function ensureInsideGeneratedDir(generatedDir: string, filename: string) {
28
- const full = normalize(join(generatedDir, filename));
29
- const root = normalize(generatedDir);
30
- if (!full.startsWith(root)) {
31
- const err: any = new Error("Imported path escapes generated directory");
32
- err.status = 400;
33
- err.code = "IMPORT_PATH_ESCAPE";
34
- throw err;
35
- }
36
- return full;
37
- }
38
-
39
- function makeImportedFilename(format: string) {
40
- const stamp = new Date().toISOString().slice(0, 19).replace(/[-:T]/g, "");
41
- const rand = randomBytes(3).toString("hex");
42
- return `imported-${stamp}-${rand}.${format}`;
43
- }
44
-
45
- function safeOriginalName(input: unknown) {
46
- if (typeof input !== "string" || !input) return null;
47
- const trimmed = input.slice(0, 200);
48
- return basename(trimmed);
49
- }
50
-
51
- export async function createLocalImport(ctx: RuntimeContext, { buffer, originalFilename }: { buffer: Buffer; originalFilename?: string | null }) {
52
- if (!Buffer.isBuffer(buffer) || buffer.length === 0) {
53
- const err: any = new Error("Image body is required");
54
- err.status = 400;
55
- err.code = "EMPTY_IMPORT";
56
- throw err;
57
- }
58
- const format = detectFormat(buffer);
59
- if (!format) {
60
- const err: any = new Error("Only PNG, JPEG, or WebP is supported");
61
- err.status = 400;
62
- err.code = "IMPORT_BAD_FORMAT";
63
- throw err;
64
- }
65
- const filename = makeImportedFilename(format);
66
- const fullPath = ensureInsideGeneratedDir(ctx.config.storage.generatedDir, filename);
67
- await mkdir(ctx.config.storage.generatedDir, { recursive: true });
68
-
69
- const meta = {
70
- schema: "ima2.generation.v1",
71
- app: "ima2-gen",
72
- version: ctx.packageVersion,
73
- createdAt: Date.now(),
74
- kind: "imported",
75
- canvasVersion: false,
76
- originalFilename: safeOriginalName(originalFilename),
77
- format,
78
- };
79
- const embedded = await embedImageMetadataBestEffort(buffer, format, meta, {
80
- version: ctx.packageVersion,
81
- });
82
- await writeFile(fullPath, embedded.buffer);
83
- await writeFile(`${fullPath}.json`, JSON.stringify(meta)).catch(() => {});
84
- invalidateHistoryIndex();
85
-
86
- const url = `/generated/${encodeURIComponent(filename)}`;
87
- return {
88
- filename,
89
- url,
90
- image: url,
91
- thumb: url,
92
- createdAt: meta.createdAt,
93
- format,
94
- kind: "imported",
95
- canvasVersion: false,
96
- canvasSourceFilename: null,
97
- canvasEditableFilename: null,
98
- prompt: null,
99
- userPrompt: null,
100
- revisedPrompt: null,
101
- promptMode: null,
102
- quality: null,
103
- size: null,
104
- model: null,
105
- provider: null,
106
- usage: null,
107
- webSearchCalls: 0,
108
- sessionId: null,
109
- nodeId: null,
110
- parentNodeId: null,
111
- refsCount: 0,
112
- isFavorite: false,
113
- };
114
- }
package/lib/logger.ts DELETED
@@ -1,161 +0,0 @@
1
- const REDACTED = "[redacted]";
2
- const MAX_VALUE_LEN = 240;
3
- const LOG_LEVELS = {
4
- debug: 10,
5
- info: 20,
6
- warn: 30,
7
- error: 40,
8
- silent: 50,
9
- };
10
-
11
- const SECRET_KEYS = new Set([
12
- "authorization",
13
- "cookie",
14
- "headers",
15
- "apiKey",
16
- "token",
17
- "password",
18
- "secret",
19
- "body",
20
- "prompt",
21
- "effectivePrompt",
22
- "userPrompt",
23
- "revisedPrompt",
24
- "textPrompt",
25
- "styleSheet",
26
- "style_sheet",
27
- "image",
28
- "imageB64",
29
- "image_url",
30
- "references",
31
- "rawResponse",
32
- ]);
33
-
34
- const ALLOWED_PROMPT_METRICS = new Set(["promptChars", "promptMode"]);
35
-
36
- type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
37
- type LogSink = {
38
- log?: (line: string) => void;
39
- debug?: (line: string) => void;
40
- info?: (line: string) => void;
41
- warn?: (line: string) => void;
42
- error?: (line: string) => void;
43
- };
44
-
45
- let activeLevel: LogLevel = "info";
46
- let activeSink: LogSink = console;
47
-
48
- function shouldRedactKey(key: string) {
49
- if (ALLOWED_PROMPT_METRICS.has(key)) return false;
50
- if (SECRET_KEYS.has(key)) return true;
51
- const lower = key.toLowerCase();
52
- return (
53
- lower.includes("token") ||
54
- lower.includes("authorization") ||
55
- lower.includes("cookie") ||
56
- lower.includes("apikey") ||
57
- lower.includes("api_key") ||
58
- lower.includes("secret") ||
59
- lower.includes("b64") ||
60
- lower.includes("base64") ||
61
- lower.includes("dataurl")
62
- );
63
- }
64
-
65
- function sanitizeValue(value: unknown): unknown {
66
- if (value == null) return value;
67
- if (value instanceof Error) return sanitizeError(value);
68
- if (Array.isArray(value)) return `[array:${value.length}]`;
69
- if (Buffer.isBuffer(value)) return `[buffer:${value.length}]`;
70
- if (typeof value === "object") return "[object]";
71
- if (typeof value === "string") {
72
- const oneLine = value
73
- .replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [redacted]")
74
- .replace(/data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi, "data:image/[redacted]")
75
- .replace(/\s+/g, " ")
76
- .trim();
77
- return oneLine.length > MAX_VALUE_LEN ? `${oneLine.slice(0, MAX_VALUE_LEN)}...` : oneLine;
78
- }
79
- return value;
80
- }
81
-
82
- export function sanitizeError(err: unknown) {
83
- if (!err) return { message: "Unknown error" };
84
- const e = err as { name?: string; code?: string; status?: number; message?: string };
85
- return {
86
- name: e.name || "Error",
87
- code: e.code || undefined,
88
- status: e.status || undefined,
89
- message: sanitizeValue(e.message || "Unknown error"),
90
- };
91
- }
92
-
93
- export function sanitizeFields(fields: Record<string, unknown> = {}) {
94
- const out: Record<string, unknown> = {};
95
- for (const [key, value] of Object.entries(fields)) {
96
- out[key] = shouldRedactKey(key) ? REDACTED : sanitizeValue(value);
97
- }
98
- return out;
99
- }
100
-
101
- function formatValue(value: unknown): string | undefined {
102
- if (value === undefined) return undefined;
103
- if (value === null) return "null";
104
- if (typeof value === "boolean" || typeof value === "number") return String(value);
105
- return JSON.stringify(String(value));
106
- }
107
-
108
- export function formatLog(scope: string, event: string, fields: Record<string, unknown> = {}) {
109
- const safeFields = sanitizeFields(fields);
110
- const parts = Object.entries(safeFields)
111
- .map(([key, value]) => {
112
- const formatted = formatValue(value);
113
- return formatted === undefined ? null : `${key}=${formatted}`;
114
- })
115
- .filter(Boolean);
116
- return `[${scope}.${event}]${parts.length ? ` ${parts.join(" ")}` : ""}`;
117
- }
118
-
119
- export function normalizeLogLevel(level: unknown): LogLevel {
120
- return typeof level === "string" && Object.hasOwn(LOG_LEVELS, level) ? (level as LogLevel) : "info";
121
- }
122
-
123
- export function configureLogger(options: { level?: unknown; sink?: LogSink } = {}) {
124
- activeLevel = normalizeLogLevel(options.level);
125
- activeSink = options.sink || console;
126
- }
127
-
128
- export function shouldLog(level: unknown) {
129
- const normalized = normalizeLogLevel(level);
130
- return LOG_LEVELS[normalized] >= LOG_LEVELS[activeLevel] && activeLevel !== "silent";
131
- }
132
-
133
- function writeLog(level: LogLevel, line: string) {
134
- if (!shouldLog(level)) return;
135
- const sink = activeSink as Record<string, ((line: string) => void) | undefined>;
136
- const writer = sink[level] || sink.log || console.log;
137
- writer.call(activeSink, line);
138
- }
139
-
140
- export function logDebug(scope: string, event: string, fields: Record<string, unknown> = {}) {
141
- writeLog("debug", formatLog(scope, event, fields));
142
- }
143
-
144
- export function logEvent(scope: string, event: string, fields: Record<string, unknown> = {}) {
145
- writeLog("info", formatLog(scope, event, fields));
146
- }
147
-
148
- export function logWarn(scope: string, event: string, fields: Record<string, unknown> = {}) {
149
- writeLog("warn", formatLog(scope, event, fields));
150
- }
151
-
152
- export function logError(scope: string, event: string, err: unknown, fields: Record<string, unknown> = {}) {
153
- const safe = sanitizeError(err);
154
- writeLog("error", formatLog(scope, event, {
155
- ...fields,
156
- errorName: safe.name,
157
- errorCode: safe.code,
158
- errorStatus: safe.status,
159
- errorMessage: safe.message,
160
- }));
161
- }
package/lib/nodeStore.ts DELETED
@@ -1,91 +0,0 @@
1
- import { writeFile, readFile, access, mkdir } from "fs/promises";
2
- import { join, resolve, sep } from "path";
3
- import { randomBytes } from "crypto";
4
- import { config } from "../config.js";
5
- import { embedImageMetadataBestEffort } from "./imageMetadataStore.js";
6
- import { invalidateHistoryIndex } from "./historyIndex.js";
7
-
8
- export function newNodeId() {
9
- return "n_" + randomBytes(config.ids.nodeHexBytes).toString("hex");
10
- }
11
-
12
- interface SaveNodeOptions {
13
- nodeId: string;
14
- b64: string;
15
- meta: Record<string, unknown>;
16
- ext?: string;
17
- generatedDir?: string;
18
- }
19
-
20
- export async function saveNode(rootDir: string, { nodeId, b64, meta, ext = "png", generatedDir = config.storage.generatedDir }: SaveNodeOptions) {
21
- void rootDir;
22
- const filename = `${nodeId}.${ext}`;
23
- await mkdir(generatedDir, { recursive: true });
24
- const imageMeta = {
25
- ...meta,
26
- kind: meta?.kind || "node",
27
- nodeId: meta?.nodeId || nodeId,
28
- format: meta?.format || ext,
29
- };
30
- const rawBuffer = Buffer.from(b64, "base64");
31
- const embedded = await embedImageMetadataBestEffort(rawBuffer, ext, imageMeta) as { embedded: boolean; warning?: string; buffer: Buffer };
32
- if (!embedded.embedded) {
33
- console.warn("[nodeStore] metadata embed skipped:", embedded.warning);
34
- }
35
- await writeFile(join(generatedDir, filename), embedded.buffer);
36
- await writeFile(join(generatedDir, filename + ".json"), JSON.stringify(meta, null, 2));
37
- invalidateHistoryIndex();
38
- return { filename };
39
- }
40
-
41
- export async function loadNodeB64(rootDir: string, filename: string, generatedDir = config.storage.generatedDir) {
42
- const p = resolveGeneratedPath(rootDir, filename, generatedDir);
43
- try { await access(p); } catch {
44
- const err = new Error(`Node file not found: ${filename}`) as Error & { code?: string; status?: number };
45
- err.code = "NODE_NOT_FOUND";
46
- err.status = 404;
47
- throw err;
48
- }
49
- const buf = await readFile(p);
50
- return buf.toString("base64");
51
- }
52
-
53
- export async function loadNodeMeta(rootDir: string, nodeId: string, ext = "png", generatedDir = config.storage.generatedDir) {
54
- void rootDir;
55
- try {
56
- return JSON.parse(await readFile(join(generatedDir, `${nodeId}.${ext}.json`), "utf-8"));
57
- } catch {
58
- return null;
59
- }
60
- }
61
-
62
- export async function loadAssetB64(rootDir: string, externalSrc: string, generatedDir = config.storage.generatedDir) {
63
- const p = resolveGeneratedPath(rootDir, externalSrc, generatedDir);
64
- try { await access(p); } catch {
65
- const err = new Error(`Asset file not found: ${externalSrc}`) as Error & { code?: string; status?: number };
66
- err.code = "NODE_NOT_FOUND";
67
- err.status = 404;
68
- throw err;
69
- }
70
- const buf = await readFile(p);
71
- return buf.toString("base64");
72
- }
73
-
74
- function resolveGeneratedPath(rootDir: string, relPath: string, generatedDir = config.storage.generatedDir) {
75
- void rootDir;
76
- if (typeof relPath !== "string" || relPath.length === 0) {
77
- const err = new Error("Asset path is required") as Error & { code?: string; status?: number };
78
- err.code = "NODE_SOURCE_INVALID";
79
- err.status = 400;
80
- throw err;
81
- }
82
- const baseDir = resolve(generatedDir);
83
- const target = resolve(baseDir, relPath);
84
- if (target !== baseDir && !target.startsWith(baseDir + sep)) {
85
- const err = new Error(`Asset path escapes generated/: ${relPath}`) as Error & { code?: string; status?: number };
86
- err.code = "NODE_SOURCE_INVALID";
87
- err.status = 400;
88
- throw err;
89
- }
90
- return target;
91
- }