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/routes/prompts.ts DELETED
@@ -1,428 +0,0 @@
1
- import type { Express, Request, Response } from "express";
2
- import { logError, logEvent } from "../lib/logger.js";
3
- import { getDb } from "../lib/db.js";
4
-
5
- import { errInfo } from "../lib/errInfo.js";
6
- import type { RouteRuntimeContext } from "../lib/runtimeContext.js";
7
-
8
- interface PromptRow {
9
- id: string;
10
- folder_id: string;
11
- name: string;
12
- text: string;
13
- tags: string | null;
14
- mode: string | null;
15
- is_favorite?: number;
16
- favorited_at?: number | null;
17
- created_at: number;
18
- updated_at: number;
19
- folder_name?: string | null;
20
- }
21
-
22
- interface FolderRow {
23
- id: string;
24
- parent_id: string;
25
- name: string;
26
- created_at: number;
27
- updated_at: number;
28
- }
29
-
30
- type IdParams = { id: string };
31
-
32
- function getPromptsDb() {
33
- return getDb();
34
- }
35
-
36
- function generateId() {
37
- return `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
38
- }
39
-
40
- export function registerPromptRoutes(app: Express, _ctx: RouteRuntimeContext) {
41
- // ── Prompts ───────────────────────────────────────────────────────────────
42
-
43
- app.get("/api/prompts", async (req: Request, res: Response) => {
44
- try {
45
- const db = getPromptsDb();
46
- const search = typeof req.query.search === "string" ? req.query.search.trim() : "";
47
- const folderId = typeof req.query.folderId === "string" ? req.query.folderId : null;
48
- const favoritesOnly = req.query.favoritesOnly === "1" || req.query.favoritesOnly === "true";
49
-
50
- let where = "WHERE 1=1";
51
- const params: unknown[] = [];
52
-
53
- if (folderId) {
54
- where += " AND p.folder_id = ?";
55
- params.push(folderId);
56
- } else {
57
- where += " AND p.folder_id != '__trash__'";
58
- }
59
-
60
- if (favoritesOnly) {
61
- where += " AND p.is_favorite = 1";
62
- }
63
-
64
- if (search) {
65
- where += " AND (p.name LIKE ? OR p.text LIKE ? OR p.tags LIKE ?)";
66
- const like = `%${search}%`;
67
- params.push(like, like, like);
68
- }
69
-
70
- const prompts = db
71
- .prepare(
72
- `SELECT p.*, f.name as folder_name
73
- FROM prompts p
74
- LEFT JOIN prompt_folders f ON p.folder_id = f.id
75
- ${where}
76
- ORDER BY p.updated_at DESC`
77
- )
78
- .all(...params) as PromptRow[];
79
-
80
- const folders = db
81
- .prepare("SELECT * FROM prompt_folders WHERE id NOT IN ('__root__', '__trash__') ORDER BY name COLLATE NOCASE")
82
- .all() as FolderRow[];
83
-
84
- res.json({ prompts: prompts.map(normalizePrompt), folders: folders.map(normalizeFolder) });
85
- } catch (e) {
86
- const err = errInfo(e);
87
- logError("prompts", "list_error", err.raw);
88
- res.status(500).json({ error: err.message });
89
- }
90
- });
91
-
92
- app.post("/api/prompts", async (req: Request, res: Response) => {
93
- try {
94
- const db = getPromptsDb();
95
- const body = (req.body ?? {}) as { name?: unknown; text?: unknown; tags?: unknown; folderId?: unknown; mode?: unknown };
96
- const { name, text, tags, folderId, mode } = body;
97
-
98
- if (!text || typeof text !== "string") {
99
- return res.status(400).json({ error: "text is required" });
100
- }
101
-
102
- const promptName = typeof name === "string" && name.trim() ? name.trim() : text.slice(0, 30);
103
- const folder_id = typeof folderId === "string" && folderId ? folderId : "__root__";
104
- const tagsJson = Array.isArray(tags) ? JSON.stringify(tags) : null;
105
- const id = generateId();
106
- const now = Math.floor(Date.now() / 1000);
107
-
108
- db.prepare(
109
- `INSERT INTO prompts (id, folder_id, name, text, tags, mode, created_at, updated_at)
110
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
111
- ).run(id, folder_id, promptName, text, tagsJson, (typeof mode === "string" ? mode : null), now, now);
112
-
113
- logEvent("prompts", "created", { id, folder_id });
114
- res.status(201).json({ prompt: normalizePrompt(db.prepare("SELECT * FROM prompts WHERE id = ?").get(id) as PromptRow) });
115
- } catch (e) {
116
- const err = errInfo(e);
117
- logError("prompts", "create_error", err.raw);
118
- res.status(500).json({ error: err.message });
119
- }
120
- });
121
-
122
- app.get("/api/prompts/:id", async (req: Request<IdParams>, res: Response) => {
123
- try {
124
- const db = getPromptsDb();
125
- const row = db.prepare("SELECT * FROM prompts WHERE id = ?").get(req.params.id) as PromptRow | undefined;
126
- if (!row) return res.status(404).json({ error: "Not found" });
127
- res.json({ prompt: normalizePrompt(row) });
128
- } catch (e) {
129
- const err = errInfo(e);
130
- logError("prompts", "get_error", err.raw);
131
- res.status(500).json({ error: err.message });
132
- }
133
- });
134
-
135
- app.patch("/api/prompts/:id", async (req: Request<IdParams>, res: Response) => {
136
- try {
137
- const db = getPromptsDb();
138
- const body = (req.body ?? {}) as { name?: unknown; text?: unknown; tags?: unknown; folderId?: unknown; mode?: unknown };
139
- const { name, text, tags, folderId, mode } = body;
140
- const sets: string[] = [];
141
- const params: unknown[] = [];
142
-
143
- if (typeof name === "string") { sets.push("name = ?"); params.push(name); }
144
- if (typeof text === "string") { sets.push("text = ?"); params.push(text); }
145
- if (Array.isArray(tags)) { sets.push("tags = ?"); params.push(JSON.stringify(tags)); }
146
- if (typeof folderId === "string") { sets.push("folder_id = ?"); params.push(folderId); }
147
- if (typeof mode === "string") { sets.push("mode = ?"); params.push(mode); }
148
-
149
- if (sets.length === 0) return res.status(400).json({ error: "No fields to update" });
150
-
151
- sets.push("updated_at = ?");
152
- params.push(Math.floor(Date.now() / 1000));
153
- params.push(req.params.id);
154
-
155
- db.prepare(`UPDATE prompts SET ${sets.join(", ")} WHERE id = ?`).run(...params);
156
-
157
- const row = db.prepare("SELECT * FROM prompts WHERE id = ?").get(req.params.id) as PromptRow | undefined;
158
- if (!row) return res.status(404).json({ error: "Not found" });
159
- res.json({ prompt: normalizePrompt(row) });
160
- } catch (e) {
161
- const err = errInfo(e);
162
- logError("prompts", "patch_error", err.raw);
163
- res.status(500).json({ error: err.message });
164
- }
165
- });
166
-
167
- app.delete("/api/prompts/:id", async (req: Request<IdParams>, res: Response) => {
168
- try {
169
- const db = getPromptsDb();
170
- db.prepare("UPDATE prompts SET folder_id = '__trash__', updated_at = ? WHERE id = ?").run(
171
- Math.floor(Date.now() / 1000),
172
- req.params.id,
173
- );
174
- logEvent("prompts", "soft_deleted", { id: req.params.id });
175
- res.json({ ok: true });
176
- } catch (e) {
177
- const err = errInfo(e);
178
- logError("prompts", "delete_error", err.raw);
179
- res.status(500).json({ error: err.message });
180
- }
181
- });
182
-
183
- app.post("/api/prompts/:id/favorite", async (req: Request<IdParams>, res: Response) => {
184
- try {
185
- const db = getPromptsDb();
186
- const row = db.prepare("SELECT is_favorite FROM prompts WHERE id = ?").get(req.params.id) as { is_favorite?: number } | undefined;
187
- if (!row) return res.status(404).json({ error: "Not found" });
188
-
189
- const newVal = row.is_favorite ? 0 : 1;
190
- const now = Math.floor(Date.now() / 1000);
191
- db.prepare("UPDATE prompts SET is_favorite = ?, favorited_at = ? WHERE id = ?").run(
192
- newVal,
193
- newVal ? now : null,
194
- req.params.id,
195
- );
196
-
197
- res.json({ isFavorite: !!newVal, favoritedAt: newVal ? now : null });
198
- } catch (e) {
199
- const err = errInfo(e);
200
- logError("prompts", "favorite_error", err.raw);
201
- res.status(500).json({ error: err.message });
202
- }
203
- });
204
-
205
- // ── Import / Export ───────────────────────────────────────────────────────
206
-
207
- app.post("/api/prompts/import", async (req: Request, res: Response) => {
208
- try {
209
- const db = getPromptsDb();
210
- const body = (req.body ?? {}) as { folders?: unknown; prompts?: unknown };
211
- const importFolders: Array<{ id?: string; name?: string; parentId?: string }> = Array.isArray(body.folders) ? body.folders : [];
212
- const importPrompts: Array<{ id?: string; name?: string; text?: string; tags?: unknown; folderId?: string; mode?: string; isFavorite?: boolean }> = Array.isArray(body.prompts) ? body.prompts : [];
213
-
214
- const result = { foldersCreated: 0, promptsImported: 0, duplicatesSkipped: 0 };
215
- const now = Math.floor(Date.now() / 1000);
216
-
217
- // Build name→id map for existing folders
218
- const existingFolders = db.prepare("SELECT * FROM prompt_folders").all() as FolderRow[];
219
- const folderMap = new Map<string, FolderRow>(existingFolders.map((f) => [f.id, f]));
220
- const namePathMap = new Map<string, string>();
221
- for (const f of existingFolders) {
222
- const parent = folderMap.get(f.parent_id);
223
- const path = parent && parent.id !== "__root__" ? `${parent.name}/${f.name}` : f.name;
224
- namePathMap.set(path.toLowerCase(), f.id);
225
- }
226
-
227
- // Import folders
228
- for (const f of importFolders) {
229
- if (!f.name) continue;
230
- const path = f.parentId && f.parentId !== "__root__"
231
- ? `${folderMap.get(f.parentId)?.name || ""}/${f.name}`
232
- : f.name;
233
- if (namePathMap.has(path.toLowerCase())) continue;
234
-
235
- const id = f.id || generateId();
236
- db.prepare(
237
- "INSERT INTO prompt_folders (id, parent_id, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)"
238
- ).run(id, f.parentId || "__root__", f.name, now, now);
239
- namePathMap.set(path.toLowerCase(), id);
240
- folderMap.set(id, { id, parent_id: f.parentId || "__root__", name: f.name, created_at: now, updated_at: now });
241
- result.foldersCreated++;
242
- }
243
-
244
- // Import prompts
245
- for (const p of importPrompts) {
246
- if (!p.text) continue;
247
- const folderId = p.folderId && folderMap.has(p.folderId) ? p.folderId : "__root__";
248
- // Check duplicate by text + folder
249
- const dup = db.prepare("SELECT 1 FROM prompts WHERE text = ? AND folder_id = ? LIMIT 1").get(p.text, folderId);
250
- if (dup) {
251
- result.duplicatesSkipped++;
252
- continue;
253
- }
254
- const id = p.id || generateId();
255
- const tagsJson = Array.isArray(p.tags) ? JSON.stringify(p.tags) : null;
256
- db.prepare(
257
- `INSERT INTO prompts (id, folder_id, name, text, tags, mode, is_favorite, created_at, updated_at)
258
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
259
- ).run(id, folderId, p.name || p.text.slice(0, 30), p.text, tagsJson, p.mode || null, p.isFavorite ? 1 : 0, now, now);
260
- result.promptsImported++;
261
- }
262
-
263
- logEvent("prompts", "imported", result);
264
- res.json(result);
265
- } catch (e) {
266
- const err = errInfo(e);
267
- logError("prompts", "import_error", err.raw);
268
- res.status(500).json({ error: err.message });
269
- }
270
- });
271
-
272
- app.get("/api/prompts/export", async (_req: Request, res: Response) => {
273
- try {
274
- const db = getPromptsDb();
275
- const prompts = db.prepare("SELECT * FROM prompts WHERE folder_id != '__trash__'").all() as PromptRow[];
276
- const folders = db.prepare("SELECT * FROM prompt_folders WHERE id NOT IN ('__root__', '__trash__')").all() as FolderRow[];
277
-
278
- res.json({
279
- version: 1,
280
- exportedAt: new Date().toISOString(),
281
- folders: folders.map((f) => ({ id: f.id, name: f.name, parentId: f.parent_id })),
282
- prompts: prompts.map((p) => ({
283
- id: p.id,
284
- name: p.name,
285
- text: p.text,
286
- tags: p.tags ? JSON.parse(p.tags) : [],
287
- folderId: p.folder_id,
288
- mode: p.mode,
289
- isFavorite: !!p.is_favorite,
290
- })),
291
- });
292
- } catch (e) {
293
- const err = errInfo(e);
294
- logError("prompts", "export_error", err.raw);
295
- res.status(500).json({ error: err.message });
296
- }
297
- });
298
-
299
- // ── Folders ───────────────────────────────────────────────────────────────
300
-
301
- app.get("/api/prompts/folders", async (_req: Request, res: Response) => {
302
- try {
303
- const db = getPromptsDb();
304
- const rows = db.prepare("SELECT * FROM prompt_folders WHERE id NOT IN ('__root__', '__trash__') ORDER BY name COLLATE NOCASE").all() as FolderRow[];
305
- res.json({ folders: rows.map(normalizeFolder) });
306
- } catch (e) {
307
- const err = errInfo(e);
308
- logError("prompts", "folders_list_error", err.raw);
309
- res.status(500).json({ error: err.message });
310
- }
311
- });
312
-
313
- app.post("/api/prompts/folders", async (req: Request, res: Response) => {
314
- try {
315
- const db = getPromptsDb();
316
- const body = (req.body ?? {}) as { name?: unknown; parentId?: unknown };
317
- const { name, parentId } = body;
318
- if (!name || typeof name !== "string" || !name.trim()) {
319
- return res.status(400).json({ error: "name is required" });
320
- }
321
-
322
- const parent_id = typeof parentId === "string" && parentId ? parentId : "__root__";
323
- const now = Math.floor(Date.now() / 1000);
324
- const id = generateId();
325
-
326
- try {
327
- db.prepare(
328
- "INSERT INTO prompt_folders (id, parent_id, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)"
329
- ).run(id, parent_id, name.trim(), now, now);
330
- } catch (e) {
331
- const err = errInfo(e);
332
- if (err.message && err.message.includes("UNIQUE constraint failed")) {
333
- return res.status(409).json({ error: "Folder name already exists in this parent" });
334
- }
335
- throw err.raw;
336
- }
337
-
338
- res.status(201).json({ folder: normalizeFolder(db.prepare("SELECT * FROM prompt_folders WHERE id = ?").get(id) as FolderRow) });
339
- } catch (e) {
340
- const err = errInfo(e);
341
- logError("prompts", "folder_create_error", err.raw);
342
- res.status(500).json({ error: err.message });
343
- }
344
- });
345
-
346
- app.patch("/api/prompts/folders/:id", async (req: Request<IdParams>, res: Response) => {
347
- try {
348
- const db = getPromptsDb();
349
- const body = (req.body ?? {}) as { name?: unknown; parentId?: unknown };
350
- const { name, parentId } = body;
351
- const sets: string[] = [];
352
- const params: unknown[] = [];
353
-
354
- if (typeof name === "string" && name.trim()) { sets.push("name = ?"); params.push(name.trim()); }
355
- if (typeof parentId === "string") { sets.push("parent_id = ?"); params.push(parentId); }
356
- if (sets.length === 0) return res.status(400).json({ error: "No fields to update" });
357
-
358
- sets.push("updated_at = ?");
359
- params.push(Math.floor(Date.now() / 1000));
360
- params.push(req.params.id);
361
-
362
- try {
363
- db.prepare(`UPDATE prompt_folders SET ${sets.join(", ")} WHERE id = ?`).run(...params);
364
- } catch (e) {
365
- const err = errInfo(e);
366
- if (err.message && err.message.includes("UNIQUE constraint failed")) {
367
- return res.status(409).json({ error: "Folder name already exists in this parent" });
368
- }
369
- throw err.raw;
370
- }
371
-
372
- const row = db.prepare("SELECT * FROM prompt_folders WHERE id = ?").get(req.params.id) as FolderRow | undefined;
373
- res.json({ folder: row ? normalizeFolder(row) : null });
374
- } catch (e) {
375
- const err = errInfo(e);
376
- logError("prompts", "folder_patch_error", err.raw);
377
- res.status(500).json({ error: err.message });
378
- }
379
- });
380
-
381
- app.delete("/api/prompts/folders/:id", async (req: Request<IdParams>, res: Response) => {
382
- try {
383
- const db = getPromptsDb();
384
- const strategy = req.query.strategy === "deleteItems" ? "deleteItems" : "moveToRoot";
385
-
386
- if (strategy === "moveToRoot") {
387
- db.prepare("UPDATE prompts SET folder_id = '__root__' WHERE folder_id = ?").run(req.params.id);
388
- } else {
389
- db.prepare("UPDATE prompts SET folder_id = '__trash__' WHERE folder_id = ?").run(req.params.id);
390
- }
391
-
392
- db.prepare("DELETE FROM prompt_folders WHERE id = ?").run(req.params.id);
393
- logEvent("prompts", "folder_deleted", { id: req.params.id, strategy });
394
- res.json({ ok: true });
395
- } catch (e) {
396
- const err = errInfo(e);
397
- logError("prompts", "folder_delete_error", err.raw);
398
- res.status(500).json({ error: err.message });
399
- }
400
- });
401
- }
402
-
403
- // ── Helpers ─────────────────────────────────────────────────────────────────
404
-
405
- function normalizePrompt(row: PromptRow) {
406
- return {
407
- id: row.id,
408
- folderId: row.folder_id,
409
- name: row.name,
410
- text: row.text,
411
- tags: row.tags ? JSON.parse(row.tags) : [],
412
- mode: row.mode,
413
- isFavorite: !!row.is_favorite,
414
- favoritedAt: row.favorited_at || null,
415
- createdAt: row.created_at,
416
- updatedAt: row.updated_at,
417
- };
418
- }
419
-
420
- function normalizeFolder(row: FolderRow) {
421
- return {
422
- id: row.id,
423
- parentId: row.parent_id,
424
- name: row.name,
425
- createdAt: row.created_at,
426
- updatedAt: row.updated_at,
427
- };
428
- }
package/routes/quota.ts DELETED
@@ -1,89 +0,0 @@
1
- import type { Express } from "express";
2
- import { readFileSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { join } from "node:path";
5
- import type { RouteRuntimeContext } from "../lib/runtimeContext.js";
6
-
7
- export interface QuotaWindow {
8
- label: string;
9
- percent: number;
10
- resetsAt: string | null;
11
- }
12
-
13
- export interface QuotaResult {
14
- provider: string;
15
- account?: { email: string | null; plan: string | null } | null;
16
- windows: QuotaWindow[];
17
- error?: boolean;
18
- authenticated?: boolean;
19
- }
20
-
21
- function readCodexTokens(): { access_token: string; account_id: string } | null {
22
- const codexHome = process.env.CODEX_HOME || join(homedir(), ".codex");
23
- try {
24
- const j = JSON.parse(readFileSync(join(codexHome, "auth.json"), "utf8"));
25
- if (j?.tokens?.access_token) {
26
- return { access_token: j.tokens.access_token, account_id: j.tokens.account_id ?? "" };
27
- }
28
- } catch {}
29
- return null;
30
- }
31
-
32
- async function fetchCodexUsage(tokens: { access_token: string; account_id: string }): Promise<QuotaResult> {
33
- try {
34
- const resp = await fetch("https://chatgpt.com/backend-api/wham/usage", {
35
- headers: {
36
- Authorization: `Bearer ${tokens.access_token}`,
37
- "ChatGPT-Account-Id": tokens.account_id,
38
- },
39
- signal: AbortSignal.timeout(8000),
40
- });
41
- if (!resp.ok) {
42
- if (resp.status === 401 || resp.status === 403) return { provider: "codex", authenticated: false, windows: [] };
43
- return { provider: "codex", error: true, windows: [] };
44
- }
45
- const data = await resp.json() as {
46
- email?: string | null;
47
- plan_type?: string | null;
48
- rate_limit?: {
49
- primary_window?: { used_percent?: number; reset_at?: number };
50
- secondary_window?: { used_percent?: number; reset_at?: number };
51
- };
52
- };
53
- const account = { email: data.email ?? null, plan: data.plan_type ?? null };
54
- const windows: QuotaWindow[] = [];
55
- if (data.rate_limit?.primary_window) {
56
- windows.push({
57
- label: "5h",
58
- percent: Math.round(data.rate_limit.primary_window.used_percent ?? 0),
59
- resetsAt: data.rate_limit.primary_window.reset_at
60
- ? new Date(data.rate_limit.primary_window.reset_at * 1000).toISOString()
61
- : null,
62
- });
63
- }
64
- if (data.rate_limit?.secondary_window) {
65
- windows.push({
66
- label: "7d",
67
- percent: Math.round(data.rate_limit.secondary_window.used_percent ?? 0),
68
- resetsAt: data.rate_limit.secondary_window.reset_at
69
- ? new Date(data.rate_limit.secondary_window.reset_at * 1000).toISOString()
70
- : null,
71
- });
72
- }
73
- return { provider: "codex", account, windows };
74
- } catch {
75
- return { provider: "codex", error: true, windows: [] };
76
- }
77
- }
78
-
79
- export function registerQuotaRoutes(app: Express, _ctx: RouteRuntimeContext) {
80
- app.get("/api/quota", async (_req, res) => {
81
- const tokens = readCodexTokens();
82
- if (!tokens) {
83
- res.json({ codex: { provider: "codex", authenticated: false, windows: [] } });
84
- return;
85
- }
86
- const codex = await fetchCodexUsage(tokens);
87
- res.json({ codex });
88
- });
89
- }