ima2-gen 1.1.21 → 1.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +30 -4
  2. package/bin/ima2.js +14 -4
  3. package/bin/lib/platform.js +34 -5
  4. package/docs/README.ko.md +31 -0
  5. package/lib/agentQueueWorker.js +6 -0
  6. package/lib/agentRuntime.js +3 -2
  7. package/lib/atomicWrite.js +14 -0
  8. package/lib/grokProxyLauncher.js +5 -3
  9. package/lib/inflight.js +1 -1
  10. package/lib/oauthLauncher.js +5 -0
  11. package/lib/videoFrameExtract.js +3 -3
  12. package/package.json +5 -7
  13. package/routes/edit.js +2 -1
  14. package/routes/generate.js +4 -3
  15. package/routes/health.js +4 -3
  16. package/routes/multimode.js +2 -1
  17. package/routes/video.js +4 -2
  18. package/server.js +29 -2
  19. package/ui/dist/.vite/manifest.json +12 -12
  20. package/ui/dist/assets/{AgentWorkspace-B_hq9CLg.js → AgentWorkspace-COxQ5TjU.js} +1 -1
  21. package/ui/dist/assets/{CardNewsWorkspace-wD12J7qk.js → CardNewsWorkspace-B0OkcuVz.js} +1 -1
  22. package/ui/dist/assets/{NodeCanvas-CI_wuPMf.js → NodeCanvas-BSsclEBh.js} +1 -1
  23. package/ui/dist/assets/{PromptBuilderPanel-CUTujJUV.js → PromptBuilderPanel-DpC9A5Rz.js} +1 -1
  24. package/ui/dist/assets/{PromptImportDialog-CUi66jPK.js → PromptImportDialog-CVwT0rLd.js} +2 -2
  25. package/ui/dist/assets/{PromptImportDiscoverySection-Cm3vrjY4.js → PromptImportDiscoverySection-BDCkRCRs.js} +1 -1
  26. package/ui/dist/assets/{PromptImportFolderSection-DOtWTD9n.js → PromptImportFolderSection-QoKbZD83.js} +1 -1
  27. package/ui/dist/assets/{PromptLibraryPanel-BMjQegRa.js → PromptLibraryPanel-BhFgeKnY.js} +2 -2
  28. package/ui/dist/assets/SettingsWorkspace-CfjrlH5R.js +1 -0
  29. package/ui/dist/assets/index-C-mur7pa.css +1 -0
  30. package/ui/dist/assets/index-CCP5nUOj.js +42 -0
  31. package/ui/dist/assets/{index-31uVIdt4.js → index-Cxhzi3bs.js} +1 -1
  32. package/ui/dist/index.html +2 -2
  33. package/bin/commands/annotate.ts +0 -119
  34. package/bin/commands/cancel.ts +0 -48
  35. package/bin/commands/canvas-versions.ts +0 -80
  36. package/bin/commands/capabilities.ts +0 -110
  37. package/bin/commands/cardnews.ts +0 -249
  38. package/bin/commands/comfy.ts +0 -54
  39. package/bin/commands/config.ts +0 -186
  40. package/bin/commands/defaults.ts +0 -192
  41. package/bin/commands/doctor.ts +0 -202
  42. package/bin/commands/edit.ts +0 -150
  43. package/bin/commands/gen.ts +0 -214
  44. package/bin/commands/grok.ts +0 -90
  45. package/bin/commands/history.ts +0 -146
  46. package/bin/commands/ls.ts +0 -64
  47. package/bin/commands/metadata.ts +0 -39
  48. package/bin/commands/multimode.ts +0 -196
  49. package/bin/commands/node.ts +0 -166
  50. package/bin/commands/observability.ts +0 -176
  51. package/bin/commands/ping.ts +0 -31
  52. package/bin/commands/prompt-sub/build.ts +0 -101
  53. package/bin/commands/prompt.ts +0 -492
  54. package/bin/commands/ps.ts +0 -81
  55. package/bin/commands/session.ts +0 -266
  56. package/bin/commands/show.ts +0 -72
  57. package/bin/commands/skill.ts +0 -70
  58. package/bin/commands/video.ts +0 -442
  59. package/bin/ima2.ts +0 -430
  60. package/bin/lib/args.ts +0 -92
  61. package/bin/lib/browser-id.ts +0 -16
  62. package/bin/lib/client.ts +0 -122
  63. package/bin/lib/config-store.ts +0 -120
  64. package/bin/lib/destructive-confirm.ts +0 -19
  65. package/bin/lib/doctor-checks.ts +0 -91
  66. package/bin/lib/error-hints.ts +0 -23
  67. package/bin/lib/files.ts +0 -39
  68. package/bin/lib/output.ts +0 -73
  69. package/bin/lib/platform.ts +0 -99
  70. package/bin/lib/recover-output.ts +0 -139
  71. package/bin/lib/sse.ts +0 -73
  72. package/bin/lib/star-prompt.ts +0 -97
  73. package/bin/lib/storage-doctor.ts +0 -39
  74. package/bin/lib/ui-build.ts +0 -85
  75. package/config.ts +0 -354
  76. package/lib/agentCommandParser.ts +0 -69
  77. package/lib/agentGenerationPlanner.ts +0 -273
  78. package/lib/agentQuestionResponder.ts +0 -266
  79. package/lib/agentQueueStore.ts +0 -270
  80. package/lib/agentQueueWorker.ts +0 -89
  81. package/lib/agentRuntime.ts +0 -604
  82. package/lib/agentSettings.ts +0 -72
  83. package/lib/agentStore.ts +0 -422
  84. package/lib/agentStoreRows.ts +0 -136
  85. package/lib/agentTypes.ts +0 -154
  86. package/lib/apiCachePolicy.ts +0 -11
  87. package/lib/assetLifecycle.ts +0 -146
  88. package/lib/canvasVersionStore.ts +0 -223
  89. package/lib/capabilities.ts +0 -126
  90. package/lib/cardNewsGenerator.ts +0 -271
  91. package/lib/cardNewsJobStore.ts +0 -142
  92. package/lib/cardNewsManifestStore.ts +0 -154
  93. package/lib/cardNewsPlanner.ts +0 -236
  94. package/lib/cardNewsPlannerClient.ts +0 -155
  95. package/lib/cardNewsPlannerPrompt.ts +0 -62
  96. package/lib/cardNewsPlannerSchema.ts +0 -321
  97. package/lib/cardNewsRoleTemplateStore.ts +0 -47
  98. package/lib/cardNewsTemplateStore.ts +0 -252
  99. package/lib/codexDetect.ts +0 -71
  100. package/lib/comfyBridge.ts +0 -235
  101. package/lib/composerSnapshot.ts +0 -33
  102. package/lib/configKeys.ts +0 -62
  103. package/lib/db.ts +0 -295
  104. package/lib/errInfo.ts +0 -43
  105. package/lib/errorClassify.ts +0 -100
  106. package/lib/generationCancel.ts +0 -28
  107. package/lib/generationErrors.ts +0 -238
  108. package/lib/grokImageAdapter.ts +0 -513
  109. package/lib/grokMultimodeAdapter.ts +0 -84
  110. package/lib/grokProxyLauncher.ts +0 -153
  111. package/lib/grokRuntime.ts +0 -23
  112. package/lib/grokSizeMapper.ts +0 -71
  113. package/lib/grokVideoAdapter.ts +0 -458
  114. package/lib/grokVideoCanvas.ts +0 -26
  115. package/lib/grokVideoDownload.ts +0 -59
  116. package/lib/grokVideoPlannerPrompt.ts +0 -67
  117. package/lib/historyIndex.ts +0 -51
  118. package/lib/historyList.ts +0 -181
  119. package/lib/imageMetadata.ts +0 -113
  120. package/lib/imageMetadataStore.ts +0 -67
  121. package/lib/imageModels.ts +0 -165
  122. package/lib/inflight.ts +0 -281
  123. package/lib/localImportStore.ts +0 -114
  124. package/lib/logger.ts +0 -161
  125. package/lib/nodeStore.ts +0 -91
  126. package/lib/oauthLauncher.ts +0 -94
  127. package/lib/oauthNormalize.ts +0 -30
  128. package/lib/oauthProxy/errors.ts +0 -128
  129. package/lib/oauthProxy/generators.ts +0 -494
  130. package/lib/oauthProxy/index.ts +0 -28
  131. package/lib/oauthProxy/prompts.ts +0 -123
  132. package/lib/oauthProxy/references.ts +0 -45
  133. package/lib/oauthProxy/runtime.ts +0 -115
  134. package/lib/oauthProxy/streams.ts +0 -232
  135. package/lib/oauthProxy/types.ts +0 -9
  136. package/lib/oauthProxy.ts +0 -3
  137. package/lib/openDirectory.ts +0 -47
  138. package/lib/pngInfo.ts +0 -26
  139. package/lib/promptBuilder/attachments.ts +0 -74
  140. package/lib/promptBuilder/client.ts +0 -130
  141. package/lib/promptBuilder/constants.ts +0 -9
  142. package/lib/promptBuilder/context.ts +0 -36
  143. package/lib/promptBuilder/errors.ts +0 -12
  144. package/lib/promptBuilder/requestSchema.ts +0 -56
  145. package/lib/promptBuilder/responseParser.ts +0 -219
  146. package/lib/promptBuilder/systemPrompt.ts +0 -135
  147. package/lib/promptBuilder/transport.ts +0 -94
  148. package/lib/promptBuilder/types.ts +0 -109
  149. package/lib/promptImport/curatedSources.ts +0 -141
  150. package/lib/promptImport/discoveryRegistry.ts +0 -329
  151. package/lib/promptImport/errors.ts +0 -18
  152. package/lib/promptImport/githubDiscovery.ts +0 -309
  153. package/lib/promptImport/githubFolder.ts +0 -397
  154. package/lib/promptImport/githubSource.ts +0 -257
  155. package/lib/promptImport/gptImageHints.ts +0 -70
  156. package/lib/promptImport/parsePromptCandidates.ts +0 -179
  157. package/lib/promptImport/promptIndex.ts +0 -326
  158. package/lib/promptImport/rankPromptCandidates.ts +0 -65
  159. package/lib/promptImport/types.ts +0 -103
  160. package/lib/promptSafetyPolicy.ts +0 -5
  161. package/lib/providerOptions.ts +0 -56
  162. package/lib/referenceImageCompress.ts +0 -84
  163. package/lib/refs.ts +0 -133
  164. package/lib/requestLogger.ts +0 -49
  165. package/lib/responsesDoctor.ts +0 -456
  166. package/lib/responsesErrors.ts +0 -83
  167. package/lib/responsesFallback.ts +0 -114
  168. package/lib/responsesImageAdapter.ts +0 -466
  169. package/lib/responsesParse.ts +0 -452
  170. package/lib/responsesTools.ts +0 -28
  171. package/lib/runtimeContext.ts +0 -146
  172. package/lib/runtimePorts.ts +0 -105
  173. package/lib/sessionStore.ts +0 -308
  174. package/lib/storageMigration.ts +0 -310
  175. package/lib/styleSheet.ts +0 -139
  176. package/lib/systemTrash.ts +0 -20
  177. package/lib/videoContinuity.ts +0 -180
  178. package/lib/videoFrameExtract.ts +0 -78
  179. package/lib/videoSeriesChain.ts +0 -29
  180. package/lib/visibleTextLanguagePolicy.ts +0 -7
  181. package/routes/agent.ts +0 -308
  182. package/routes/annotations.ts +0 -118
  183. package/routes/canvasVersions.ts +0 -69
  184. package/routes/capabilities.ts +0 -18
  185. package/routes/cardNews.ts +0 -211
  186. package/routes/comfy.ts +0 -43
  187. package/routes/edit.ts +0 -352
  188. package/routes/generate.ts +0 -492
  189. package/routes/grok.ts +0 -24
  190. package/routes/health.ts +0 -123
  191. package/routes/history.ts +0 -221
  192. package/routes/imageImport.ts +0 -37
  193. package/routes/index.ts +0 -52
  194. package/routes/metadata.ts +0 -77
  195. package/routes/multimode.ts +0 -499
  196. package/routes/nodes.ts +0 -578
  197. package/routes/promptBuilder.ts +0 -37
  198. package/routes/promptImport.ts +0 -379
  199. package/routes/prompts.ts +0 -428
  200. package/routes/quota.ts +0 -89
  201. package/routes/sessions.ts +0 -317
  202. package/routes/storage.ts +0 -47
  203. package/routes/video.ts +0 -300
  204. package/routes/videoExtended.ts +0 -284
  205. package/server.ts +0 -293
  206. package/ui/dist/assets/SettingsWorkspace-PiaVnsdA.js +0 -1
  207. package/ui/dist/assets/index-CjgnNtgt.css +0 -1
  208. package/ui/dist/assets/index-Da2s4_-5.js +0 -36
@@ -1,321 +0,0 @@
1
- export const CARD_NEWS_TEXT_KINDS = ["headline", "body", "caption", "cta", "badge", "number"];
2
- export const CARD_NEWS_RENDER_MODES = ["in-image", "ui-only"];
3
- export const CARD_NEWS_PLACEMENTS = [
4
- "top-left",
5
- "top-center",
6
- "top-right",
7
- "center-left",
8
- "center",
9
- "center-right",
10
- "bottom-left",
11
- "bottom-center",
12
- "bottom-right",
13
- "free",
14
- ];
15
- export const CARD_NEWS_HIERARCHIES = ["primary", "secondary", "supporting"];
16
- export const CARD_NEWS_TEXT_SOURCES = ["planner", "user"];
17
-
18
- const TEXT_FIELD_SCHEMA = {
19
- type: "object",
20
- additionalProperties: false,
21
- required: [
22
- "id",
23
- "kind",
24
- "text",
25
- "renderMode",
26
- "placement",
27
- "slotId",
28
- "hierarchy",
29
- "maxChars",
30
- "language",
31
- "source",
32
- ],
33
- properties: {
34
- id: { type: "string" },
35
- kind: { type: "string", enum: CARD_NEWS_TEXT_KINDS },
36
- text: { type: "string" },
37
- renderMode: { type: "string", enum: CARD_NEWS_RENDER_MODES },
38
- placement: { type: "string", enum: CARD_NEWS_PLACEMENTS },
39
- slotId: { type: ["string", "null"] },
40
- hierarchy: { type: "string", enum: CARD_NEWS_HIERARCHIES },
41
- maxChars: { type: ["integer", "null"] },
42
- language: { type: ["string", "null"] },
43
- source: { type: "string", enum: CARD_NEWS_TEXT_SOURCES },
44
- },
45
- };
46
-
47
- export const CARD_NEWS_PLANNER_SCHEMA = {
48
- type: "object",
49
- additionalProperties: false,
50
- required: ["title", "topic", "cards"],
51
- properties: {
52
- title: { type: "string" },
53
- topic: { type: "string" },
54
- audience: { type: "string" },
55
- goal: { type: "string" },
56
- cards: {
57
- type: "array",
58
- items: {
59
- type: "object",
60
- additionalProperties: false,
61
- required: ["order", "role", "headline", "body", "visualPrompt", "textFields", "references", "locked"],
62
- properties: {
63
- order: { type: "integer" },
64
- role: { type: "string" },
65
- headline: { type: "string" },
66
- body: { type: "string" },
67
- visualPrompt: { type: "string" },
68
- textFields: { type: "array", items: TEXT_FIELD_SCHEMA },
69
- references: { type: "array", items: { type: "string" } },
70
- locked: { type: "boolean" },
71
- },
72
- },
73
- },
74
- },
75
- };
76
-
77
- interface TextFieldRecord {
78
- id?: unknown;
79
- kind?: unknown;
80
- text?: unknown;
81
- renderMode?: unknown;
82
- placement?: unknown;
83
- slotId?: unknown;
84
- hierarchy?: unknown;
85
- maxChars?: unknown;
86
- language?: unknown;
87
- source?: unknown;
88
- }
89
-
90
- interface NormalizedTextField {
91
- id: string;
92
- kind: string;
93
- text: string;
94
- renderMode: string;
95
- placement: string;
96
- slotId: string | null;
97
- hierarchy: string;
98
- maxChars: number | null;
99
- language: string | null;
100
- source: string;
101
- }
102
-
103
- interface CardRecord {
104
- order?: unknown;
105
- role?: unknown;
106
- headline?: unknown;
107
- body?: unknown;
108
- visualPrompt?: unknown;
109
- textFields?: unknown;
110
- references?: unknown;
111
- locked?: unknown;
112
- }
113
-
114
- interface RoleEntry {
115
- role: string;
116
- promptHint?: string;
117
- }
118
-
119
- interface RoleTemplate {
120
- roles: RoleEntry[];
121
- }
122
-
123
- interface BriefInput {
124
- topic?: string;
125
- title?: string;
126
- audience?: string;
127
- goal?: string;
128
- contentBrief?: string;
129
- roleTemplate?: RoleTemplate;
130
- }
131
-
132
- function asText(value: unknown, fallback = ""): string {
133
- return typeof value === "string" && value.trim() ? value.trim() : fallback;
134
- }
135
-
136
- function detectBriefLanguage(input: BriefInput = {}): "ko" | "en" | "und" {
137
- const text = [input.topic, input.audience, input.goal, input.contentBrief].filter(Boolean).join(" ");
138
- if (/[가-힣]/.test(text)) return "ko";
139
- if (/[A-Za-z]/.test(text)) return "en";
140
- return "und";
141
- }
142
-
143
- function fallbackCopy(input: BriefInput = {}, kind = "body"): string {
144
- const lang = detectBriefLanguage(input);
145
- const topic = asText(input.topic, asText(input.title, "Card news"));
146
- const goal = asText(input.goal, topic);
147
- const brief = asText(input.contentBrief, goal);
148
- if (kind === "headline") return topic;
149
- if (lang === "ko") return brief || `${topic} 핵심 내용을 정리합니다.`;
150
- if (lang === "en") return brief || `Summarize the key point for ${topic}.`;
151
- return brief || topic;
152
- }
153
-
154
- function normalizeTextField(field: unknown, index: number): NormalizedTextField | null {
155
- if (!field || typeof field !== "object") return null;
156
- const f = field as TextFieldRecord;
157
- const text = asText(f.text);
158
- if (!text) return null;
159
- return {
160
- id: asText(f.id, `tf_${index + 1}`),
161
- kind: typeof f.kind === "string" && CARD_NEWS_TEXT_KINDS.includes(f.kind) ? f.kind : "body",
162
- text,
163
- renderMode: typeof f.renderMode === "string" && CARD_NEWS_RENDER_MODES.includes(f.renderMode) ? f.renderMode : "in-image",
164
- placement: typeof f.placement === "string" && CARD_NEWS_PLACEMENTS.includes(f.placement) ? f.placement : "free",
165
- slotId: typeof f.slotId === "string" && f.slotId.trim() ? f.slotId.trim() : null,
166
- hierarchy: typeof f.hierarchy === "string" && CARD_NEWS_HIERARCHIES.includes(f.hierarchy) ? f.hierarchy : "supporting",
167
- maxChars: Number.isInteger(f.maxChars) ? (f.maxChars as number) : null,
168
- language: typeof f.language === "string" && f.language.trim() ? f.language.trim() : null,
169
- source: typeof f.source === "string" && CARD_NEWS_TEXT_SOURCES.includes(f.source) ? f.source : "planner",
170
- };
171
- }
172
-
173
- function normalizeTextFields(value: unknown): NormalizedTextField[] {
174
- if (!Array.isArray(value)) return [];
175
- return value.map((item, idx) => normalizeTextField(item, idx)).filter((field): field is NormalizedTextField => field !== null);
176
- }
177
-
178
- function stripExactVisibleText(visualPrompt: unknown, textFields: NormalizedTextField[]): string {
179
- let next = asText(visualPrompt);
180
- for (const field of textFields) {
181
- const text = asText(field.text);
182
- if (text.length >= 4 && next.includes(text)) {
183
- next = next.split(text).join("visible text box");
184
- }
185
- }
186
- return next.trim();
187
- }
188
-
189
- function normalizeCard(card: CardRecord | null | undefined, role: RoleEntry, index: number, input: BriefInput) {
190
- const topic = asText(input.topic, "Card news");
191
- const textFields = normalizeTextFields(card?.textFields);
192
- return {
193
- order: index + 1,
194
- role: role.role,
195
- headline: asText(card?.headline, index === 0 ? topic : fallbackCopy(input, "headline")),
196
- body: asText(card?.body, fallbackCopy(input, "body")),
197
- visualPrompt: stripExactVisibleText(
198
- asText(card?.visualPrompt, `${asText(role.promptHint, role.role)}, ${topic}`),
199
- textFields,
200
- ),
201
- textFields,
202
- references: Array.isArray(card?.references)
203
- ? (card.references as unknown[]).filter((ref): ref is string => typeof ref === "string")
204
- : [],
205
- locked: false,
206
- };
207
- }
208
-
209
- export function repairPlannerOutput(output: unknown, input: BriefInput = {}) {
210
- const roles = input.roleTemplate?.roles || [];
211
- const outputCards = (output && typeof output === "object" && Array.isArray((output as { cards?: unknown }).cards))
212
- ? (output as { cards: CardRecord[] }).cards
213
- : null;
214
- const cards = roles.map((role, index) => {
215
- const original = outputCards ? outputCards[index] : null;
216
- return normalizeCard(original, role, index, input);
217
- });
218
- const out = (output ?? {}) as Record<string, unknown>;
219
- return {
220
- ok: true,
221
- repaired: true,
222
- errors: [] as string[],
223
- plan: {
224
- title: asText(out.title, asText(input.topic, "Untitled card news")),
225
- topic: asText(out.topic, asText(input.topic, "Untitled card news")),
226
- audience: asText(out.audience, asText(input.audience)),
227
- goal: asText(out.goal, asText(input.goal)),
228
- cards,
229
- },
230
- };
231
- }
232
-
233
- function validateTextField(field: unknown, path: string, errors: string[]): void {
234
- if (!field || typeof field !== "object") {
235
- errors.push(`${path} must be object`);
236
- return;
237
- }
238
- const f = field as TextFieldRecord;
239
- if (typeof f.id !== "string") errors.push(`${path}.id must be string`);
240
- if (typeof f.kind !== "string" || !CARD_NEWS_TEXT_KINDS.includes(f.kind)) errors.push(`${path}.kind invalid`);
241
- if (typeof f.text !== "string") errors.push(`${path}.text must be string`);
242
- if (typeof f.text === "string" && !f.text.trim()) errors.push(`${path}.text must not be empty`);
243
- if (typeof f.renderMode !== "string" || !CARD_NEWS_RENDER_MODES.includes(f.renderMode)) errors.push(`${path}.renderMode invalid`);
244
- if (typeof f.placement !== "string" || !CARD_NEWS_PLACEMENTS.includes(f.placement)) errors.push(`${path}.placement invalid`);
245
- if (!(typeof f.slotId === "string" || f.slotId === null)) errors.push(`${path}.slotId invalid`);
246
- if (typeof f.hierarchy !== "string" || !CARD_NEWS_HIERARCHIES.includes(f.hierarchy)) errors.push(`${path}.hierarchy invalid`);
247
- if (!(Number.isInteger(f.maxChars) || f.maxChars === null)) errors.push(`${path}.maxChars invalid`);
248
- if (!(typeof f.language === "string" || f.language === null)) errors.push(`${path}.language invalid`);
249
- if (typeof f.source !== "string" || !CARD_NEWS_TEXT_SOURCES.includes(f.source)) errors.push(`${path}.source invalid`);
250
- }
251
-
252
- export function validatePlannerOutput(output: unknown, roleTemplate: RoleTemplate | null | undefined) {
253
- const errors: string[] = [];
254
- if (!output || typeof output !== "object" || Array.isArray(output)) {
255
- return { ok: false, repaired: false, errors: ["output must be an object"] };
256
- }
257
- const out = output as { title?: unknown; topic?: unknown; cards?: unknown; audience?: unknown; goal?: unknown };
258
- if (typeof out.title !== "string") errors.push("title must be a string");
259
- if (typeof out.topic !== "string") errors.push("topic must be a string");
260
- if (!Array.isArray(out.cards)) errors.push("cards must be an array");
261
-
262
- const roles = roleTemplate?.roles || [];
263
- if (Array.isArray(out.cards) && out.cards.length !== roles.length) {
264
- errors.push("cards length must match role template");
265
- }
266
-
267
- const cards: CardRecord[] = Array.isArray(out.cards) ? (out.cards as CardRecord[]) : [];
268
- cards.forEach((card, index) => {
269
- const expected = roles[index];
270
- if (!card || typeof card !== "object") {
271
- errors.push(`card ${index + 1} must be an object`);
272
- return;
273
- }
274
- if (card.order !== index + 1) errors.push(`card ${index + 1} order mismatch`);
275
- if (expected && card.role !== expected.role) errors.push(`card ${index + 1} role mismatch`);
276
- for (const key of ["headline", "body", "visualPrompt"] as const) {
277
- if (typeof card[key] !== "string") errors.push(`card ${index + 1} ${key} must be string`);
278
- }
279
- if (!Array.isArray(card.textFields)) errors.push(`card ${index + 1} textFields must be array`);
280
- if (Array.isArray(card.textFields)) {
281
- card.textFields.forEach((field, fieldIndex) =>
282
- validateTextField(field, `card ${index + 1} textFields ${fieldIndex + 1}`, errors));
283
- for (const field of card.textFields as TextFieldRecord[]) {
284
- if (
285
- field?.renderMode === "in-image" &&
286
- typeof field.text === "string" &&
287
- field.text.trim().length >= 4 &&
288
- typeof card.visualPrompt === "string" &&
289
- card.visualPrompt.includes(field.text.trim())
290
- ) {
291
- errors.push(`card ${index + 1} visualPrompt must not duplicate exact visible text`);
292
- }
293
- }
294
- }
295
- if (!Array.isArray(card.references)) errors.push(`card ${index + 1} references must be array`);
296
- if (card.locked !== false) errors.push(`card ${index + 1} locked must be false`);
297
- });
298
-
299
- if (errors.length) return { ok: false, repaired: false, errors };
300
- return {
301
- ok: true,
302
- repaired: false,
303
- errors: [] as string[],
304
- plan: {
305
- title: (out.title as string).trim(),
306
- topic: (out.topic as string).trim(),
307
- audience: asText(out.audience),
308
- goal: asText(out.goal),
309
- cards: cards.map((card) => ({
310
- order: card.order as number,
311
- role: card.role as string,
312
- headline: (card.headline as string).trim(),
313
- body: (card.body as string).trim(),
314
- visualPrompt: (card.visualPrompt as string).trim(),
315
- textFields: normalizeTextFields(card.textFields),
316
- references: (card.references as unknown[]).filter((ref): ref is string => typeof ref === "string"),
317
- locked: false,
318
- })),
319
- },
320
- };
321
- }
@@ -1,47 +0,0 @@
1
- const ROLE_TEMPLATES = [
2
- {
3
- id: "short-3",
4
- name: "Short 3",
5
- defaultCount: 3,
6
- roles: [
7
- { role: "hook", required: true, promptHint: "strong opening card", preferredSlots: ["title", "visual"] },
8
- { role: "core", required: true, promptHint: "main explanation card", preferredSlots: ["visual", "body"] },
9
- { role: "cta", required: true, promptHint: "clear call to action card", preferredSlots: ["cta"] },
10
- ],
11
- },
12
- {
13
- id: "mid-5",
14
- name: "Mid 5",
15
- defaultCount: 5,
16
- roles: [
17
- { role: "cover", required: true, promptHint: "cover card with strong headline", preferredSlots: ["title", "visual"] },
18
- { role: "problem", required: true, promptHint: "problem framing card", preferredSlots: ["title", "body"] },
19
- { role: "insight", required: true, promptHint: "insight or solution card", preferredSlots: ["visual", "body"] },
20
- { role: "example", required: true, promptHint: "example or proof card", preferredSlots: ["visual", "body"] },
21
- { role: "cta", required: true, promptHint: "closing call to action card", preferredSlots: ["cta"] },
22
- ],
23
- },
24
- {
25
- id: "long-8",
26
- name: "Long 8",
27
- defaultCount: 8,
28
- roles: [
29
- { role: "cover", required: true, promptHint: "cover card", preferredSlots: ["title"] },
30
- { role: "problem", required: true, promptHint: "problem card", preferredSlots: ["body"] },
31
- { role: "data", required: true, promptHint: "data card", preferredSlots: ["visual"] },
32
- { role: "tip1", required: true, promptHint: "first tip card", preferredSlots: ["body"] },
33
- { role: "tip2", required: true, promptHint: "second tip card", preferredSlots: ["body"] },
34
- { role: "example", required: true, promptHint: "example card", preferredSlots: ["visual"] },
35
- { role: "summary", required: true, promptHint: "summary card", preferredSlots: ["body"] },
36
- { role: "cta", required: true, promptHint: "call to action card", preferredSlots: ["cta"] },
37
- ],
38
- },
39
- ];
40
-
41
- export function listRoleTemplates() {
42
- return ROLE_TEMPLATES;
43
- }
44
-
45
- export function getRoleTemplate(roleTemplateId = "mid-5") {
46
- return ROLE_TEMPLATES.find((t) => t.id === roleTemplateId) || ROLE_TEMPLATES[1];
47
- }
@@ -1,252 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import { existsSync } from "node:fs";
3
- import { basename, join, normalize, sep } from "node:path";
4
-
5
- interface TemplateCtx {
6
- rootDir?: string;
7
- }
8
-
9
- interface SlotInput {
10
- id?: unknown;
11
- kind?: unknown;
12
- textKind?: unknown;
13
- label?: unknown;
14
- placement?: unknown;
15
- x?: unknown;
16
- y?: unknown;
17
- w?: unknown;
18
- h?: unknown;
19
- required?: unknown;
20
- maxChars?: unknown;
21
- safeArea?: unknown;
22
- [k: string]: unknown;
23
- }
24
-
25
- interface NormalizedSlot {
26
- id: string;
27
- kind: string;
28
- textKind: string | null;
29
- label: string;
30
- placement: string;
31
- x: number;
32
- y: number;
33
- w: number;
34
- h: number;
35
- required: boolean;
36
- maxChars: number | null;
37
- safeArea: boolean;
38
- [k: string]: unknown;
39
- }
40
-
41
- interface TemplateRecord {
42
- id?: string;
43
- name?: string;
44
- description?: string;
45
- size?: string;
46
- stylePrompt?: string;
47
- negativePrompt?: string;
48
- slots?: SlotInput[];
49
- palette?: unknown[];
50
- typography?: unknown;
51
- recommendedOutputSizes?: string[];
52
- authoringLabel?: string;
53
- recommendedRoleNodeIds?: string[];
54
- createdBy?: string;
55
- previewFilename?: string;
56
- baseFilename?: string;
57
- [k: string]: unknown;
58
- }
59
-
60
- type TypedError = Error & { status?: number; code?: string };
61
- function makeError(msg: string, status: number, code: string): TypedError {
62
- const err = new Error(msg) as TypedError;
63
- err.status = status;
64
- err.code = code;
65
- return err;
66
- }
67
-
68
- const TEMPLATE_ROOT = ["assets", "card-news", "templates"];
69
- const IMAGE_TEMPLATE_REGISTRY = [
70
- {
71
- id: "clean-report-square",
72
- label: "Clean editorial report",
73
- recommendedOutputSizes: ["1024x1024", "2048x2048"],
74
- },
75
- {
76
- id: "academy-lesson-square",
77
- label: "Academy lesson carousel",
78
- recommendedOutputSizes: ["1024x1024", "2048x2048"],
79
- },
80
- ];
81
- const OUTPUT_SIZE_RE = /^(1024|2048|[1-3][0-9]{3})x(1024|2048|[1-3][0-9]{3})$/;
82
- const PLACEMENTS = new Set([
83
- "top-left",
84
- "top-center",
85
- "top-right",
86
- "center-left",
87
- "center",
88
- "center-right",
89
- "bottom-left",
90
- "bottom-center",
91
- "bottom-right",
92
- "free",
93
- ]);
94
-
95
- function assertSafeId(id: unknown): asserts id is string {
96
- if (typeof id !== "string" || !/^[a-z0-9][a-z0-9-]{1,80}$/.test(id)) {
97
- throw makeError("Invalid template id", 400, "CARD_NEWS_BAD_TEMPLATE_ID");
98
- }
99
- }
100
-
101
- function templateDir(ctx: TemplateCtx, templateId: string): string {
102
- assertSafeId(templateId);
103
- const root = join(ctx.rootDir ?? process.cwd(), ...TEMPLATE_ROOT);
104
- const dir = join(root, templateId);
105
- const normalizedRoot = normalize(root + sep);
106
- const normalizedDir = normalize(dir + sep);
107
- if (!normalizedDir.startsWith(normalizedRoot)) {
108
- throw makeError("Template path escapes root", 400, "CARD_NEWS_BAD_TEMPLATE_PATH");
109
- }
110
- return dir;
111
- }
112
-
113
- function publicTemplate(t: TemplateRecord) {
114
- return {
115
- id: t.id,
116
- name: t.name,
117
- description: t.description || "",
118
- size: t.size,
119
- previewUrl: `/api/cardnews/image-templates/${encodeURIComponent(t.id ?? "")}/preview`,
120
- stylePrompt: t.stylePrompt,
121
- negativePrompt: t.negativePrompt || "",
122
- slots: normalizeSlots(t.slots),
123
- palette: t.palette || [],
124
- typography: t.typography || null,
125
- recommendedOutputSizes: Array.isArray(t.recommendedOutputSizes) ? t.recommendedOutputSizes : [],
126
- authoringLabel: t.authoringLabel || t.name,
127
- recommendedRoleNodeIds: t.recommendedRoleNodeIds || [],
128
- createdBy: t.createdBy || "system",
129
- };
130
- }
131
-
132
- function normalizeLegacySlotKind(kind: unknown): { kind: string; textKind: string | null } {
133
- if (kind === "title") return { kind: "text", textKind: "headline" };
134
- if (kind === "body") return { kind: "text", textKind: "body" };
135
- if (kind === "cta") return { kind: "text", textKind: "cta" };
136
- if (kind === "image") return { kind: "image", textKind: null };
137
- if (kind === "text" || kind === "mixed" || kind === "safe-area") return { kind: kind as string, textKind: null };
138
- return { kind: "mixed", textKind: null };
139
- }
140
-
141
- function normalizeSlot(slot: SlotInput = {}): NormalizedSlot {
142
- const legacy = normalizeLegacySlotKind(slot.kind);
143
- return {
144
- ...slot,
145
- id: typeof slot.id === "string" && slot.id ? slot.id : "slot",
146
- kind: legacy.kind,
147
- textKind: typeof slot.textKind === "string" && slot.textKind ? slot.textKind : (legacy.textKind || null),
148
- label: typeof slot.label === "string" && slot.label ? slot.label : (typeof slot.id === "string" && slot.id ? slot.id : "slot"),
149
- placement: typeof slot.placement === "string" && PLACEMENTS.has(slot.placement) ? slot.placement : "free",
150
- x: Number.isFinite(slot.x) ? (slot.x as number) : 0,
151
- y: Number.isFinite(slot.y) ? (slot.y as number) : 0,
152
- w: Number.isFinite(slot.w) ? (slot.w as number) : 100,
153
- h: Number.isFinite(slot.h) ? (slot.h as number) : 100,
154
- required: Boolean(slot.required),
155
- maxChars: Number.isFinite(slot.maxChars) ? (slot.maxChars as number) : null,
156
- safeArea: Boolean(slot.safeArea),
157
- };
158
- }
159
-
160
- function normalizeSlots(slots: unknown): NormalizedSlot[] {
161
- return Array.isArray(slots) ? slots.map((s) => normalizeSlot(s as SlotInput)) : [];
162
- }
163
-
164
- function registryEntry(templateId: string) {
165
- return IMAGE_TEMPLATE_REGISTRY.find((entry) => entry.id === templateId);
166
- }
167
-
168
- function validateTemplateAuthoring(template: TemplateRecord): void {
169
- const problems: string[] = [];
170
- if (typeof template.name !== "string" || !template.name.trim()) problems.push("name");
171
- if (typeof template.size !== "string" || !OUTPUT_SIZE_RE.test(template.size)) problems.push("size");
172
- if (typeof template.stylePrompt !== "string" || !template.stylePrompt.trim()) problems.push("stylePrompt");
173
- if (!Array.isArray(template.slots) || template.slots.length === 0) problems.push("slots");
174
- const ids = new Set<string>();
175
- for (const slot of normalizeSlots(template.slots)) {
176
- if (ids.has(slot.id)) problems.push(`duplicate slot ${slot.id}`);
177
- ids.add(slot.id);
178
- if (!PLACEMENTS.has(slot.placement)) problems.push(`slot ${slot.id} placement`);
179
- if ((slot.kind === "text" || slot.textKind) && !slot.maxChars) problems.push(`slot ${slot.id} maxChars`);
180
- }
181
- if (
182
- template.recommendedOutputSizes &&
183
- (!Array.isArray(template.recommendedOutputSizes) ||
184
- template.recommendedOutputSizes.some((size) => typeof size !== "string" || !OUTPUT_SIZE_RE.test(size)))
185
- ) {
186
- problems.push("recommendedOutputSizes");
187
- }
188
- if (problems.length) {
189
- throw makeError(`Template authoring metadata invalid: ${problems.join(", ")}`, 500, "CARD_NEWS_TEMPLATE_AUTHORING_INVALID");
190
- }
191
- }
192
-
193
- async function readTemplate(ctx: TemplateCtx, templateId: string): Promise<TemplateRecord> {
194
- const dir = templateDir(ctx, templateId);
195
- const raw = await readFile(join(dir, "template.json"), "utf8");
196
- const parsed = JSON.parse(raw) as TemplateRecord;
197
- const id = parsed.id || templateId;
198
- if (id !== templateId) {
199
- throw makeError("Template id mismatch", 500, "CARD_NEWS_TEMPLATE_ID_MISMATCH");
200
- }
201
- const entry = registryEntry(templateId);
202
- if (!entry) {
203
- throw makeError("Template is not registered", 500, "CARD_NEWS_TEMPLATE_NOT_REGISTERED");
204
- }
205
- validateTemplateAuthoring(parsed);
206
- return {
207
- ...parsed,
208
- authoringLabel: parsed.authoringLabel || entry.label,
209
- recommendedOutputSizes: parsed.recommendedOutputSizes || entry.recommendedOutputSizes,
210
- slots: normalizeSlots(parsed.slots) as unknown as SlotInput[],
211
- previewFilename: parsed.previewFilename || "preview.png",
212
- baseFilename: parsed.baseFilename || "base.png",
213
- createdBy: "system",
214
- };
215
- }
216
-
217
- export async function listImageTemplates(ctx: TemplateCtx) {
218
- const templates: ReturnType<typeof publicTemplate>[] = [];
219
- for (const entry of IMAGE_TEMPLATE_REGISTRY) {
220
- templates.push(publicTemplate(await readTemplate(ctx, entry.id)));
221
- }
222
- return templates;
223
- }
224
-
225
- export async function getImageTemplate(ctx: TemplateCtx, templateId: string) {
226
- return readTemplate(ctx, templateId);
227
- }
228
-
229
- export async function readTemplatePreview(ctx: TemplateCtx, templateId: string) {
230
- const template = await readTemplate(ctx, templateId);
231
- const filename = basename(template.previewFilename || "preview.png");
232
- const path = join(templateDir(ctx, templateId), filename);
233
- if (!existsSync(path)) {
234
- throw makeError("Template preview not found", 404, "CARD_NEWS_TEMPLATE_PREVIEW_NOT_FOUND");
235
- }
236
- return readFile(path);
237
- }
238
-
239
- export async function readTemplateBaseB64(ctx: TemplateCtx, templateId: string) {
240
- const template = await readTemplate(ctx, templateId);
241
- const filename = basename(template.baseFilename || "base.png");
242
- const path = join(templateDir(ctx, templateId), filename);
243
- if (!existsSync(path)) {
244
- throw makeError("Template base image not found", 404, "CARD_NEWS_TEMPLATE_BASE_NOT_FOUND");
245
- }
246
- const buf = await readFile(path);
247
- return {
248
- template,
249
- templateBase: join(...TEMPLATE_ROOT, templateId, filename),
250
- b64: buf.toString("base64"),
251
- };
252
- }
@@ -1,71 +0,0 @@
1
- // Codex CLI / OAuth auth detection across platforms.
2
- // References:
3
- // - OpenAI Codex stores auth under CODEX_HOME (default ~/.codex/auth.json).
4
- // - Legacy chatgpt-local stores auth under ~/.chatgpt-local/auth.json.
5
- // - Auth may live in OS keyring instead of a file (file absence ≠ unauth).
6
- // - Windows has no documented native install path; WSL is the supported path.
7
- import { existsSync } from "node:fs";
8
- import { execFileSync } from "node:child_process";
9
- import { homedir } from "node:os";
10
- import { join } from "node:path";
11
-
12
- import { errInfo } from "./errInfo.js";
13
- const HOME = homedir();
14
-
15
- export function codexAuthPaths() {
16
- const codexHome = process.env.CODEX_HOME || join(HOME, ".codex");
17
- return {
18
- codex: join(codexHome, "auth.json"),
19
- chatgpt: join(HOME, ".chatgpt-local", "auth.json"),
20
- xdgCodex: join(HOME, ".config", "codex", "auth.json"),
21
- };
22
- }
23
-
24
- export function hasAuthFile() {
25
- const p = codexAuthPaths();
26
- return existsSync(p.codex) || existsSync(p.chatgpt) || existsSync(p.xdgCodex);
27
- }
28
-
29
- // Non-invasive probe: `codex login status` returns 0 when authed (file OR keyring).
30
- // Returns: "authed" | "unauthed" | "missing" (codex binary not found)
31
- export function codexLoginStatus(timeoutMs = 2000) {
32
- const candidates =
33
- process.platform === "win32"
34
- ? ["codex.cmd", "codex.exe", "codex"]
35
- : ["codex"];
36
- for (const bin of candidates) {
37
- try {
38
- execFileSync(bin, ["login", "status"], {
39
- stdio: "ignore",
40
- timeout: timeoutMs,
41
- windowsHide: true,
42
- });
43
- return "authed";
44
- } catch (e) {
45
- const err = errInfo(e);
46
- if (err.raw && err.code === "ENOENT") continue;
47
- // non-zero exit = binary exists but not authed
48
- if (err.raw && typeof err.status === "number") return "unauthed";
49
- }
50
- }
51
- return "missing";
52
- }
53
-
54
- export function detectCodexAuth() {
55
- const files = codexAuthPaths();
56
- const fileHits = {
57
- codex: existsSync(files.codex),
58
- chatgpt: existsSync(files.chatgpt),
59
- xdgCodex: existsSync(files.xdgCodex),
60
- };
61
- const probe = codexLoginStatus();
62
- const authed = probe === "authed" || fileHits.codex || fileHits.chatgpt || fileHits.xdgCodex;
63
- return {
64
- authed,
65
- probe,
66
- files,
67
- fileHits,
68
- platform: process.platform,
69
- wslHint: process.platform === "win32",
70
- };
71
- }