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