ima2-gen 1.1.20 → 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 (239) hide show
  1. package/README.md +42 -26
  2. package/bin/commands/capabilities.js +2 -2
  3. package/bin/commands/defaults.js +2 -2
  4. package/bin/commands/doctor.js +3 -3
  5. package/bin/commands/edit.js +1 -1
  6. package/bin/commands/gen.js +1 -1
  7. package/bin/commands/grok.js +16 -11
  8. package/bin/commands/multimode.js +1 -1
  9. package/bin/commands/observability.js +2 -2
  10. package/bin/commands/video.js +335 -13
  11. package/bin/ima2.js +23 -13
  12. package/bin/lib/error-hints.js +2 -2
  13. package/bin/lib/platform.js +34 -5
  14. package/docs/API.md +112 -3
  15. package/docs/CLI.md +61 -7
  16. package/docs/FAQ.ko.md +15 -20
  17. package/docs/FAQ.md +14 -19
  18. package/docs/NPX_QUICKSTART.md +40 -0
  19. package/docs/PROMPT_STUDIO.ko.md +1 -1
  20. package/docs/PROMPT_STUDIO.md +1 -1
  21. package/docs/README.ja.md +6 -16
  22. package/docs/README.ko.md +35 -14
  23. package/docs/README.zh-CN.md +7 -17
  24. package/docs/migration/runtime-test-inventory.md +8 -1
  25. package/lib/agentQueueWorker.js +6 -0
  26. package/lib/agentRuntime.js +20 -5
  27. package/lib/atomicWrite.js +14 -0
  28. package/lib/capabilities.js +1 -1
  29. package/lib/generationErrors.js +1 -1
  30. package/lib/grokProxyLauncher.js +31 -6
  31. package/lib/grokVideoAdapter.js +18 -89
  32. package/lib/grokVideoCanvas.js +25 -0
  33. package/lib/grokVideoDownload.js +58 -0
  34. package/lib/grokVideoPlannerPrompt.js +64 -0
  35. package/lib/historyList.js +7 -1
  36. package/lib/inflight.js +1 -1
  37. package/lib/oauthLauncher.js +26 -6
  38. package/lib/videoContinuity.js +149 -0
  39. package/lib/videoFrameExtract.js +80 -0
  40. package/node_modules/progrok/dist/index.js +187 -88
  41. package/node_modules/progrok/dist/index.js.map +1 -1
  42. package/node_modules/progrok/package.json +1 -1
  43. package/node_modules/progrok/skills/progrok/SKILL.md +33 -4
  44. package/package.json +6 -8
  45. package/routes/edit.js +2 -1
  46. package/routes/generate.js +4 -3
  47. package/routes/health.js +4 -3
  48. package/routes/index.js +4 -0
  49. package/routes/multimode.js +2 -1
  50. package/routes/quota.js +66 -0
  51. package/routes/video.js +80 -16
  52. package/routes/videoExtended.js +293 -0
  53. package/server.js +35 -4
  54. package/skills/ima2/SKILL.md +320 -7
  55. package/ui/dist/.vite/manifest.json +12 -12
  56. package/ui/dist/assets/{AgentWorkspace-DS8uvoLI.js → AgentWorkspace-COxQ5TjU.js} +2 -2
  57. package/ui/dist/assets/{CardNewsWorkspace-CYxMsE67.js → CardNewsWorkspace-B0OkcuVz.js} +1 -1
  58. package/ui/dist/assets/{NodeCanvas-DccIc347.js → NodeCanvas-BSsclEBh.js} +1 -1
  59. package/ui/dist/assets/{PromptBuilderPanel-BvxxwSJp.js → PromptBuilderPanel-DpC9A5Rz.js} +1 -1
  60. package/ui/dist/assets/{PromptImportDialog-u1_BFDRd.js → PromptImportDialog-CVwT0rLd.js} +2 -2
  61. package/ui/dist/assets/{PromptImportDiscoverySection-C5uvkVSz.js → PromptImportDiscoverySection-BDCkRCRs.js} +1 -1
  62. package/ui/dist/assets/{PromptImportFolderSection-D3E_O1SD.js → PromptImportFolderSection-QoKbZD83.js} +1 -1
  63. package/ui/dist/assets/{PromptLibraryPanel-4gyf9CB9.js → PromptLibraryPanel-BhFgeKnY.js} +2 -2
  64. package/ui/dist/assets/SettingsWorkspace-CfjrlH5R.js +1 -0
  65. package/ui/dist/assets/index-C-mur7pa.css +1 -0
  66. package/ui/dist/assets/index-CCP5nUOj.js +42 -0
  67. package/ui/dist/assets/{index-DoKtXbod.js → index-Cxhzi3bs.js} +1 -1
  68. package/ui/dist/index.html +2 -2
  69. package/vendor/progrok-0.2.0.tgz +0 -0
  70. package/bin/commands/annotate.ts +0 -119
  71. package/bin/commands/cancel.ts +0 -48
  72. package/bin/commands/canvas-versions.ts +0 -80
  73. package/bin/commands/capabilities.ts +0 -110
  74. package/bin/commands/cardnews.ts +0 -249
  75. package/bin/commands/comfy.ts +0 -54
  76. package/bin/commands/config.ts +0 -186
  77. package/bin/commands/defaults.ts +0 -192
  78. package/bin/commands/doctor.ts +0 -202
  79. package/bin/commands/edit.ts +0 -150
  80. package/bin/commands/gen.ts +0 -214
  81. package/bin/commands/grok.ts +0 -85
  82. package/bin/commands/history.ts +0 -146
  83. package/bin/commands/ls.ts +0 -64
  84. package/bin/commands/metadata.ts +0 -39
  85. package/bin/commands/multimode.ts +0 -196
  86. package/bin/commands/node.ts +0 -166
  87. package/bin/commands/observability.ts +0 -176
  88. package/bin/commands/ping.ts +0 -31
  89. package/bin/commands/prompt-sub/build.ts +0 -101
  90. package/bin/commands/prompt.ts +0 -492
  91. package/bin/commands/ps.ts +0 -81
  92. package/bin/commands/session.ts +0 -266
  93. package/bin/commands/show.ts +0 -72
  94. package/bin/commands/skill.ts +0 -70
  95. package/bin/commands/video.ts +0 -205
  96. package/bin/ima2.ts +0 -430
  97. package/bin/lib/args.ts +0 -92
  98. package/bin/lib/browser-id.ts +0 -16
  99. package/bin/lib/client.ts +0 -122
  100. package/bin/lib/config-store.ts +0 -120
  101. package/bin/lib/destructive-confirm.ts +0 -19
  102. package/bin/lib/doctor-checks.ts +0 -91
  103. package/bin/lib/error-hints.ts +0 -23
  104. package/bin/lib/files.ts +0 -39
  105. package/bin/lib/output.ts +0 -73
  106. package/bin/lib/platform.ts +0 -99
  107. package/bin/lib/recover-output.ts +0 -139
  108. package/bin/lib/sse.ts +0 -73
  109. package/bin/lib/star-prompt.ts +0 -97
  110. package/bin/lib/storage-doctor.ts +0 -39
  111. package/bin/lib/ui-build.ts +0 -85
  112. package/config.ts +0 -354
  113. package/lib/agentCommandParser.ts +0 -69
  114. package/lib/agentGenerationPlanner.ts +0 -273
  115. package/lib/agentQuestionResponder.ts +0 -266
  116. package/lib/agentQueueStore.ts +0 -270
  117. package/lib/agentQueueWorker.ts +0 -89
  118. package/lib/agentRuntime.ts +0 -592
  119. package/lib/agentSettings.ts +0 -72
  120. package/lib/agentStore.ts +0 -422
  121. package/lib/agentStoreRows.ts +0 -136
  122. package/lib/agentTypes.ts +0 -154
  123. package/lib/apiCachePolicy.ts +0 -11
  124. package/lib/assetLifecycle.ts +0 -146
  125. package/lib/canvasVersionStore.ts +0 -223
  126. package/lib/capabilities.ts +0 -126
  127. package/lib/cardNewsGenerator.ts +0 -271
  128. package/lib/cardNewsJobStore.ts +0 -142
  129. package/lib/cardNewsManifestStore.ts +0 -154
  130. package/lib/cardNewsPlanner.ts +0 -236
  131. package/lib/cardNewsPlannerClient.ts +0 -155
  132. package/lib/cardNewsPlannerPrompt.ts +0 -62
  133. package/lib/cardNewsPlannerSchema.ts +0 -321
  134. package/lib/cardNewsRoleTemplateStore.ts +0 -47
  135. package/lib/cardNewsTemplateStore.ts +0 -252
  136. package/lib/codexDetect.ts +0 -71
  137. package/lib/comfyBridge.ts +0 -235
  138. package/lib/composerSnapshot.ts +0 -33
  139. package/lib/configKeys.ts +0 -62
  140. package/lib/db.ts +0 -295
  141. package/lib/errInfo.ts +0 -43
  142. package/lib/errorClassify.ts +0 -100
  143. package/lib/generationCancel.ts +0 -28
  144. package/lib/generationErrors.ts +0 -238
  145. package/lib/grokImageAdapter.ts +0 -513
  146. package/lib/grokMultimodeAdapter.ts +0 -84
  147. package/lib/grokProxyLauncher.ts +0 -129
  148. package/lib/grokRuntime.ts +0 -23
  149. package/lib/grokSizeMapper.ts +0 -71
  150. package/lib/grokVideoAdapter.ts +0 -519
  151. package/lib/historyIndex.ts +0 -51
  152. package/lib/historyList.ts +0 -177
  153. package/lib/imageMetadata.ts +0 -113
  154. package/lib/imageMetadataStore.ts +0 -67
  155. package/lib/imageModels.ts +0 -165
  156. package/lib/inflight.ts +0 -281
  157. package/lib/localImportStore.ts +0 -114
  158. package/lib/logger.ts +0 -161
  159. package/lib/nodeStore.ts +0 -91
  160. package/lib/oauthLauncher.ts +0 -78
  161. package/lib/oauthNormalize.ts +0 -30
  162. package/lib/oauthProxy/errors.ts +0 -128
  163. package/lib/oauthProxy/generators.ts +0 -494
  164. package/lib/oauthProxy/index.ts +0 -28
  165. package/lib/oauthProxy/prompts.ts +0 -123
  166. package/lib/oauthProxy/references.ts +0 -45
  167. package/lib/oauthProxy/runtime.ts +0 -115
  168. package/lib/oauthProxy/streams.ts +0 -232
  169. package/lib/oauthProxy/types.ts +0 -9
  170. package/lib/oauthProxy.ts +0 -3
  171. package/lib/openDirectory.ts +0 -47
  172. package/lib/pngInfo.ts +0 -26
  173. package/lib/promptBuilder/attachments.ts +0 -74
  174. package/lib/promptBuilder/client.ts +0 -130
  175. package/lib/promptBuilder/constants.ts +0 -9
  176. package/lib/promptBuilder/context.ts +0 -36
  177. package/lib/promptBuilder/errors.ts +0 -12
  178. package/lib/promptBuilder/requestSchema.ts +0 -56
  179. package/lib/promptBuilder/responseParser.ts +0 -219
  180. package/lib/promptBuilder/systemPrompt.ts +0 -135
  181. package/lib/promptBuilder/transport.ts +0 -94
  182. package/lib/promptBuilder/types.ts +0 -109
  183. package/lib/promptImport/curatedSources.ts +0 -141
  184. package/lib/promptImport/discoveryRegistry.ts +0 -329
  185. package/lib/promptImport/errors.ts +0 -18
  186. package/lib/promptImport/githubDiscovery.ts +0 -309
  187. package/lib/promptImport/githubFolder.ts +0 -397
  188. package/lib/promptImport/githubSource.ts +0 -257
  189. package/lib/promptImport/gptImageHints.ts +0 -70
  190. package/lib/promptImport/parsePromptCandidates.ts +0 -179
  191. package/lib/promptImport/promptIndex.ts +0 -326
  192. package/lib/promptImport/rankPromptCandidates.ts +0 -65
  193. package/lib/promptImport/types.ts +0 -103
  194. package/lib/promptSafetyPolicy.ts +0 -5
  195. package/lib/providerOptions.ts +0 -56
  196. package/lib/referenceImageCompress.ts +0 -84
  197. package/lib/refs.ts +0 -133
  198. package/lib/requestLogger.ts +0 -49
  199. package/lib/responsesDoctor.ts +0 -456
  200. package/lib/responsesErrors.ts +0 -83
  201. package/lib/responsesFallback.ts +0 -114
  202. package/lib/responsesImageAdapter.ts +0 -466
  203. package/lib/responsesParse.ts +0 -452
  204. package/lib/responsesTools.ts +0 -28
  205. package/lib/runtimeContext.ts +0 -146
  206. package/lib/runtimePorts.ts +0 -105
  207. package/lib/sessionStore.ts +0 -308
  208. package/lib/storageMigration.ts +0 -310
  209. package/lib/styleSheet.ts +0 -139
  210. package/lib/systemTrash.ts +0 -20
  211. package/lib/videoSeriesChain.ts +0 -29
  212. package/lib/visibleTextLanguagePolicy.ts +0 -7
  213. package/routes/agent.ts +0 -308
  214. package/routes/annotations.ts +0 -118
  215. package/routes/canvasVersions.ts +0 -69
  216. package/routes/capabilities.ts +0 -18
  217. package/routes/cardNews.ts +0 -211
  218. package/routes/comfy.ts +0 -43
  219. package/routes/edit.ts +0 -352
  220. package/routes/generate.ts +0 -492
  221. package/routes/grok.ts +0 -24
  222. package/routes/health.ts +0 -123
  223. package/routes/history.ts +0 -221
  224. package/routes/imageImport.ts +0 -37
  225. package/routes/index.ts +0 -48
  226. package/routes/metadata.ts +0 -77
  227. package/routes/multimode.ts +0 -499
  228. package/routes/nodes.ts +0 -578
  229. package/routes/promptBuilder.ts +0 -37
  230. package/routes/promptImport.ts +0 -379
  231. package/routes/prompts.ts +0 -428
  232. package/routes/sessions.ts +0 -317
  233. package/routes/storage.ts +0 -47
  234. package/routes/video.ts +0 -232
  235. package/server.ts +0 -290
  236. package/ui/dist/assets/SettingsWorkspace-F3eNu3mJ.js +0 -1
  237. package/ui/dist/assets/index-B6tcw_UF.css +0 -1
  238. package/ui/dist/assets/index-DYOh6gQD.js +0 -32
  239. package/vendor/progrok-0.1.1.tgz +0 -0
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
- }