ima2-gen 1.1.21 → 1.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +30 -4
  2. package/bin/ima2.js +14 -4
  3. package/bin/lib/platform.js +34 -5
  4. package/docs/README.ko.md +31 -0
  5. package/lib/agentQueueWorker.js +6 -0
  6. package/lib/agentRuntime.js +3 -2
  7. package/lib/atomicWrite.js +14 -0
  8. package/lib/grokProxyLauncher.js +5 -3
  9. package/lib/inflight.js +1 -1
  10. package/lib/oauthLauncher.js +5 -0
  11. package/lib/videoFrameExtract.js +3 -3
  12. package/package.json +5 -7
  13. package/routes/edit.js +2 -1
  14. package/routes/generate.js +4 -3
  15. package/routes/health.js +4 -3
  16. package/routes/multimode.js +2 -1
  17. package/routes/video.js +4 -2
  18. package/server.js +29 -2
  19. package/ui/dist/.vite/manifest.json +12 -12
  20. package/ui/dist/assets/{AgentWorkspace-B_hq9CLg.js → AgentWorkspace-COxQ5TjU.js} +1 -1
  21. package/ui/dist/assets/{CardNewsWorkspace-wD12J7qk.js → CardNewsWorkspace-B0OkcuVz.js} +1 -1
  22. package/ui/dist/assets/{NodeCanvas-CI_wuPMf.js → NodeCanvas-BSsclEBh.js} +1 -1
  23. package/ui/dist/assets/{PromptBuilderPanel-CUTujJUV.js → PromptBuilderPanel-DpC9A5Rz.js} +1 -1
  24. package/ui/dist/assets/{PromptImportDialog-CUi66jPK.js → PromptImportDialog-CVwT0rLd.js} +2 -2
  25. package/ui/dist/assets/{PromptImportDiscoverySection-Cm3vrjY4.js → PromptImportDiscoverySection-BDCkRCRs.js} +1 -1
  26. package/ui/dist/assets/{PromptImportFolderSection-DOtWTD9n.js → PromptImportFolderSection-QoKbZD83.js} +1 -1
  27. package/ui/dist/assets/{PromptLibraryPanel-BMjQegRa.js → PromptLibraryPanel-BhFgeKnY.js} +2 -2
  28. package/ui/dist/assets/SettingsWorkspace-CfjrlH5R.js +1 -0
  29. package/ui/dist/assets/index-C-mur7pa.css +1 -0
  30. package/ui/dist/assets/index-CCP5nUOj.js +42 -0
  31. package/ui/dist/assets/{index-31uVIdt4.js → index-Cxhzi3bs.js} +1 -1
  32. package/ui/dist/index.html +2 -2
  33. package/bin/commands/annotate.ts +0 -119
  34. package/bin/commands/cancel.ts +0 -48
  35. package/bin/commands/canvas-versions.ts +0 -80
  36. package/bin/commands/capabilities.ts +0 -110
  37. package/bin/commands/cardnews.ts +0 -249
  38. package/bin/commands/comfy.ts +0 -54
  39. package/bin/commands/config.ts +0 -186
  40. package/bin/commands/defaults.ts +0 -192
  41. package/bin/commands/doctor.ts +0 -202
  42. package/bin/commands/edit.ts +0 -150
  43. package/bin/commands/gen.ts +0 -214
  44. package/bin/commands/grok.ts +0 -90
  45. package/bin/commands/history.ts +0 -146
  46. package/bin/commands/ls.ts +0 -64
  47. package/bin/commands/metadata.ts +0 -39
  48. package/bin/commands/multimode.ts +0 -196
  49. package/bin/commands/node.ts +0 -166
  50. package/bin/commands/observability.ts +0 -176
  51. package/bin/commands/ping.ts +0 -31
  52. package/bin/commands/prompt-sub/build.ts +0 -101
  53. package/bin/commands/prompt.ts +0 -492
  54. package/bin/commands/ps.ts +0 -81
  55. package/bin/commands/session.ts +0 -266
  56. package/bin/commands/show.ts +0 -72
  57. package/bin/commands/skill.ts +0 -70
  58. package/bin/commands/video.ts +0 -442
  59. package/bin/ima2.ts +0 -430
  60. package/bin/lib/args.ts +0 -92
  61. package/bin/lib/browser-id.ts +0 -16
  62. package/bin/lib/client.ts +0 -122
  63. package/bin/lib/config-store.ts +0 -120
  64. package/bin/lib/destructive-confirm.ts +0 -19
  65. package/bin/lib/doctor-checks.ts +0 -91
  66. package/bin/lib/error-hints.ts +0 -23
  67. package/bin/lib/files.ts +0 -39
  68. package/bin/lib/output.ts +0 -73
  69. package/bin/lib/platform.ts +0 -99
  70. package/bin/lib/recover-output.ts +0 -139
  71. package/bin/lib/sse.ts +0 -73
  72. package/bin/lib/star-prompt.ts +0 -97
  73. package/bin/lib/storage-doctor.ts +0 -39
  74. package/bin/lib/ui-build.ts +0 -85
  75. package/config.ts +0 -354
  76. package/lib/agentCommandParser.ts +0 -69
  77. package/lib/agentGenerationPlanner.ts +0 -273
  78. package/lib/agentQuestionResponder.ts +0 -266
  79. package/lib/agentQueueStore.ts +0 -270
  80. package/lib/agentQueueWorker.ts +0 -89
  81. package/lib/agentRuntime.ts +0 -604
  82. package/lib/agentSettings.ts +0 -72
  83. package/lib/agentStore.ts +0 -422
  84. package/lib/agentStoreRows.ts +0 -136
  85. package/lib/agentTypes.ts +0 -154
  86. package/lib/apiCachePolicy.ts +0 -11
  87. package/lib/assetLifecycle.ts +0 -146
  88. package/lib/canvasVersionStore.ts +0 -223
  89. package/lib/capabilities.ts +0 -126
  90. package/lib/cardNewsGenerator.ts +0 -271
  91. package/lib/cardNewsJobStore.ts +0 -142
  92. package/lib/cardNewsManifestStore.ts +0 -154
  93. package/lib/cardNewsPlanner.ts +0 -236
  94. package/lib/cardNewsPlannerClient.ts +0 -155
  95. package/lib/cardNewsPlannerPrompt.ts +0 -62
  96. package/lib/cardNewsPlannerSchema.ts +0 -321
  97. package/lib/cardNewsRoleTemplateStore.ts +0 -47
  98. package/lib/cardNewsTemplateStore.ts +0 -252
  99. package/lib/codexDetect.ts +0 -71
  100. package/lib/comfyBridge.ts +0 -235
  101. package/lib/composerSnapshot.ts +0 -33
  102. package/lib/configKeys.ts +0 -62
  103. package/lib/db.ts +0 -295
  104. package/lib/errInfo.ts +0 -43
  105. package/lib/errorClassify.ts +0 -100
  106. package/lib/generationCancel.ts +0 -28
  107. package/lib/generationErrors.ts +0 -238
  108. package/lib/grokImageAdapter.ts +0 -513
  109. package/lib/grokMultimodeAdapter.ts +0 -84
  110. package/lib/grokProxyLauncher.ts +0 -153
  111. package/lib/grokRuntime.ts +0 -23
  112. package/lib/grokSizeMapper.ts +0 -71
  113. package/lib/grokVideoAdapter.ts +0 -458
  114. package/lib/grokVideoCanvas.ts +0 -26
  115. package/lib/grokVideoDownload.ts +0 -59
  116. package/lib/grokVideoPlannerPrompt.ts +0 -67
  117. package/lib/historyIndex.ts +0 -51
  118. package/lib/historyList.ts +0 -181
  119. package/lib/imageMetadata.ts +0 -113
  120. package/lib/imageMetadataStore.ts +0 -67
  121. package/lib/imageModels.ts +0 -165
  122. package/lib/inflight.ts +0 -281
  123. package/lib/localImportStore.ts +0 -114
  124. package/lib/logger.ts +0 -161
  125. package/lib/nodeStore.ts +0 -91
  126. package/lib/oauthLauncher.ts +0 -94
  127. package/lib/oauthNormalize.ts +0 -30
  128. package/lib/oauthProxy/errors.ts +0 -128
  129. package/lib/oauthProxy/generators.ts +0 -494
  130. package/lib/oauthProxy/index.ts +0 -28
  131. package/lib/oauthProxy/prompts.ts +0 -123
  132. package/lib/oauthProxy/references.ts +0 -45
  133. package/lib/oauthProxy/runtime.ts +0 -115
  134. package/lib/oauthProxy/streams.ts +0 -232
  135. package/lib/oauthProxy/types.ts +0 -9
  136. package/lib/oauthProxy.ts +0 -3
  137. package/lib/openDirectory.ts +0 -47
  138. package/lib/pngInfo.ts +0 -26
  139. package/lib/promptBuilder/attachments.ts +0 -74
  140. package/lib/promptBuilder/client.ts +0 -130
  141. package/lib/promptBuilder/constants.ts +0 -9
  142. package/lib/promptBuilder/context.ts +0 -36
  143. package/lib/promptBuilder/errors.ts +0 -12
  144. package/lib/promptBuilder/requestSchema.ts +0 -56
  145. package/lib/promptBuilder/responseParser.ts +0 -219
  146. package/lib/promptBuilder/systemPrompt.ts +0 -135
  147. package/lib/promptBuilder/transport.ts +0 -94
  148. package/lib/promptBuilder/types.ts +0 -109
  149. package/lib/promptImport/curatedSources.ts +0 -141
  150. package/lib/promptImport/discoveryRegistry.ts +0 -329
  151. package/lib/promptImport/errors.ts +0 -18
  152. package/lib/promptImport/githubDiscovery.ts +0 -309
  153. package/lib/promptImport/githubFolder.ts +0 -397
  154. package/lib/promptImport/githubSource.ts +0 -257
  155. package/lib/promptImport/gptImageHints.ts +0 -70
  156. package/lib/promptImport/parsePromptCandidates.ts +0 -179
  157. package/lib/promptImport/promptIndex.ts +0 -326
  158. package/lib/promptImport/rankPromptCandidates.ts +0 -65
  159. package/lib/promptImport/types.ts +0 -103
  160. package/lib/promptSafetyPolicy.ts +0 -5
  161. package/lib/providerOptions.ts +0 -56
  162. package/lib/referenceImageCompress.ts +0 -84
  163. package/lib/refs.ts +0 -133
  164. package/lib/requestLogger.ts +0 -49
  165. package/lib/responsesDoctor.ts +0 -456
  166. package/lib/responsesErrors.ts +0 -83
  167. package/lib/responsesFallback.ts +0 -114
  168. package/lib/responsesImageAdapter.ts +0 -466
  169. package/lib/responsesParse.ts +0 -452
  170. package/lib/responsesTools.ts +0 -28
  171. package/lib/runtimeContext.ts +0 -146
  172. package/lib/runtimePorts.ts +0 -105
  173. package/lib/sessionStore.ts +0 -308
  174. package/lib/storageMigration.ts +0 -310
  175. package/lib/styleSheet.ts +0 -139
  176. package/lib/systemTrash.ts +0 -20
  177. package/lib/videoContinuity.ts +0 -180
  178. package/lib/videoFrameExtract.ts +0 -78
  179. package/lib/videoSeriesChain.ts +0 -29
  180. package/lib/visibleTextLanguagePolicy.ts +0 -7
  181. package/routes/agent.ts +0 -308
  182. package/routes/annotations.ts +0 -118
  183. package/routes/canvasVersions.ts +0 -69
  184. package/routes/capabilities.ts +0 -18
  185. package/routes/cardNews.ts +0 -211
  186. package/routes/comfy.ts +0 -43
  187. package/routes/edit.ts +0 -352
  188. package/routes/generate.ts +0 -492
  189. package/routes/grok.ts +0 -24
  190. package/routes/health.ts +0 -123
  191. package/routes/history.ts +0 -221
  192. package/routes/imageImport.ts +0 -37
  193. package/routes/index.ts +0 -52
  194. package/routes/metadata.ts +0 -77
  195. package/routes/multimode.ts +0 -499
  196. package/routes/nodes.ts +0 -578
  197. package/routes/promptBuilder.ts +0 -37
  198. package/routes/promptImport.ts +0 -379
  199. package/routes/prompts.ts +0 -428
  200. package/routes/quota.ts +0 -89
  201. package/routes/sessions.ts +0 -317
  202. package/routes/storage.ts +0 -47
  203. package/routes/video.ts +0 -300
  204. package/routes/videoExtended.ts +0 -284
  205. package/server.ts +0 -293
  206. package/ui/dist/assets/SettingsWorkspace-PiaVnsdA.js +0 -1
  207. package/ui/dist/assets/index-CjgnNtgt.css +0 -1
  208. package/ui/dist/assets/index-Da2s4_-5.js +0 -36
package/lib/refs.ts DELETED
@@ -1,133 +0,0 @@
1
- // lib/refs.js — reference-image validator (0.09.7).
2
- // Extracted from server.js so unit tests can import without booting the app.
3
-
4
- import { config } from "../config.js";
5
-
6
- const BASE64_RE = /^[A-Za-z0-9+/]+=*$/;
7
- const DATA_URL_RE = /^data:([^;,]+);base64,/i;
8
-
9
- function approxBase64Bytes(b64: string) {
10
- try {
11
- return Buffer.from(b64, "base64").length;
12
- } catch {
13
- return Math.floor((b64.length * 3) / 4);
14
- }
15
- }
16
-
17
- export function detectImageMimeFromB64(b64: string | null | undefined) {
18
- if (!b64) return null;
19
- let buf: Buffer;
20
- try {
21
- buf = Buffer.from(b64, "base64");
22
- } catch {
23
- return null;
24
- }
25
- if (buf.length >= 4 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
26
- return "image/png";
27
- }
28
- if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
29
- return "image/jpeg";
30
- }
31
- if (
32
- buf.length >= 12 &&
33
- buf.toString("ascii", 0, 4) === "RIFF" &&
34
- buf.toString("ascii", 8, 12) === "WEBP"
35
- ) {
36
- return "image/webp";
37
- }
38
- return null;
39
- }
40
-
41
- export function safeReferenceDiagnostics(refDetails: any[] = []) {
42
- if (!Array.isArray(refDetails)) return [];
43
- return refDetails.map((ref: any) => ({
44
- index: ref.index,
45
- declaredMime: ref.declaredMime || null,
46
- detectedMime: ref.detectedMime || null,
47
- b64Chars: ref.b64Chars,
48
- approxBytes: ref.approxBytes,
49
- source: ref.source,
50
- warnings: ref.warnings || [],
51
- }));
52
- }
53
-
54
- export function summarizeReferencePayload(references: unknown) {
55
- if (!Array.isArray(references)) {
56
- return { refsCount: 0, referenceBytes: 0, referenceB64Chars: 0 };
57
- }
58
- let referenceBytes = 0;
59
- let referenceB64Chars = 0;
60
- for (const ref of references) {
61
- if (typeof ref !== "string") continue;
62
- const b64 = ref.replace(DATA_URL_RE, "");
63
- referenceB64Chars += b64.length;
64
- referenceBytes += approxBase64Bytes(b64);
65
- }
66
- return {
67
- refsCount: references.length,
68
- referenceBytes,
69
- referenceB64Chars,
70
- };
71
- }
72
-
73
- type RefDetail = {
74
- index: number;
75
- b64: string;
76
- declaredMime: string | null;
77
- detectedMime: string | null;
78
- b64Chars: number;
79
- approxBytes: number;
80
- source: string;
81
- warnings: string[];
82
- };
83
-
84
- type RefsValidationResult =
85
- | { error: string; code: string; refs?: undefined; refDetails?: undefined; referenceDiagnostics?: undefined }
86
- | { error?: undefined; code?: undefined; refs: string[]; refDetails: RefDetail[]; referenceDiagnostics: ReturnType<typeof safeReferenceDiagnostics> };
87
-
88
- export function validateAndNormalizeRefs(references: unknown, {
89
- maxCount = config.limits.maxRefCount,
90
- maxB64Bytes = config.limits.maxRefB64Bytes,
91
- } = {}): RefsValidationResult {
92
- if (!Array.isArray(references)) {
93
- return { error: "references must be an array", code: "REF_NOT_ARRAY" };
94
- }
95
- if (references.length > maxCount) {
96
- return { error: `references may not exceed ${maxCount} items`, code: "REF_TOO_MANY" };
97
- }
98
- const out: string[] = [];
99
- const refDetails: RefDetail[] = [];
100
- for (let i = 0; i < references.length; i++) {
101
- const r = references[i];
102
- if (typeof r !== "string") {
103
- return { error: `references[${i}] must be a string`, code: "REF_NOT_STRING" };
104
- }
105
- const dataUrlMatch = r.match(DATA_URL_RE);
106
- const declaredMime = dataUrlMatch?.[1]?.toLowerCase() || null;
107
- const b64 = r.replace(DATA_URL_RE, "");
108
- if (!b64) return { error: `references[${i}] is empty`, code: "REF_EMPTY" };
109
- if (b64.length > maxB64Bytes) {
110
- return { error: `references[${i}] exceeds ${maxB64Bytes} bytes`, code: "REF_TOO_LARGE" };
111
- }
112
- if (!BASE64_RE.test(b64)) {
113
- return { error: `references[${i}] is not valid base64`, code: "REF_NOT_BASE64" };
114
- }
115
- const detectedMime = detectImageMimeFromB64(b64);
116
- const warnings: string[] = [];
117
- if (declaredMime && detectedMime && declaredMime !== detectedMime) {
118
- warnings.push("mime_mismatch");
119
- }
120
- out.push(b64);
121
- refDetails.push({
122
- index: i,
123
- b64,
124
- declaredMime,
125
- detectedMime,
126
- b64Chars: b64.length,
127
- approxBytes: approxBase64Bytes(b64),
128
- source: declaredMime ? "dataUrl" : "rawBase64",
129
- warnings,
130
- });
131
- }
132
- return { refs: out, refDetails, referenceDiagnostics: safeReferenceDiagnostics(refDetails) };
133
- }
@@ -1,49 +0,0 @@
1
- import { randomUUID } from "crypto";
2
- import type { Request, Response, NextFunction } from "express";
3
- import { logEvent } from "./logger.js";
4
-
5
- const REQUEST_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
6
- const IGNORED_LOG_PATHS = new Set(["/api/health", "/api/inflight"]);
7
-
8
- export function normalizeRequestId(value: unknown) {
9
- return typeof value === "string" && REQUEST_ID_RE.test(value) ? value : `req_${randomUUID()}`;
10
- }
11
-
12
- function requestPath(req: Request) {
13
- return String(req.originalUrl || req.url || "").split("?")[0] || "/";
14
- }
15
-
16
- export function createRequestLogger() {
17
- return function requestLogger(req: Request, res: Response, next: NextFunction) {
18
- const path = requestPath(req);
19
- if (!path.startsWith("/api/")) return next();
20
-
21
- const requestId = normalizeRequestId(req.get("x-request-id"));
22
- const startedAt = Date.now();
23
- req.id = requestId;
24
- res.setHeader("X-Request-Id", requestId);
25
-
26
- const ignoreLog = IGNORED_LOG_PATHS.has(path);
27
- if (!ignoreLog) {
28
- logEvent("http", "request", {
29
- requestId,
30
- method: req.method,
31
- path,
32
- client: req.get("x-ima2-client") || "ui",
33
- });
34
- }
35
-
36
- res.on("finish", () => {
37
- if (ignoreLog) return;
38
- logEvent("http", "response", {
39
- requestId,
40
- method: req.method,
41
- path,
42
- status: res.statusCode,
43
- durationMs: Date.now() - startedAt,
44
- });
45
- });
46
-
47
- next();
48
- };
49
- }
@@ -1,456 +0,0 @@
1
- import { config as defaultConfig } from "../config.js";
2
- import { errInfo } from "./errInfo.js";
3
- import { parseJson, parseStream, safeDiagnosticLabel, type ResponseDiagnostics } from "./responsesParse.js";
4
- import type { RouteRuntimeContext } from "./runtimeContext.js";
5
- import {
6
- GENERATE_DEVELOPER_PROMPT,
7
- GENERATE_NO_SEARCH_DEVELOPER_PROMPT,
8
- buildUserTextPrompt,
9
- waitForOAuthReady,
10
- } from "./oauthProxy.js";
11
-
12
- type ToolChoiceSummary = "none" | "required" | "image_generation";
13
- type ProbeExpectation = "text" | "image";
14
-
15
- interface ProbeSpec {
16
- id: string;
17
- expectation: ProbeExpectation;
18
- promptId: string;
19
- promptChars: number;
20
- stream: boolean;
21
- toolTypes: string[];
22
- toolChoiceKind: ToolChoiceSummary;
23
- payload: Record<string, unknown>;
24
- }
25
-
26
- export interface ImageDoctorProbeOptions {
27
- provider?: string;
28
- apiKey?: string;
29
- oauthUrl?: string;
30
- model?: string;
31
- size?: string;
32
- quality?: string;
33
- moderation?: string;
34
- prompt?: string;
35
- matrix?: boolean;
36
- timeoutMs?: number;
37
- ctx?: RouteRuntimeContext;
38
- }
39
-
40
- export interface ImageDoctorProbeResult {
41
- id: string;
42
- ok: boolean;
43
- expectation: ProbeExpectation;
44
- diagnosticReason: string | null;
45
- request: {
46
- stream: boolean;
47
- toolTypes: string[];
48
- toolChoiceKind: ToolChoiceSummary;
49
- promptId: string;
50
- promptChars: number;
51
- };
52
- response: {
53
- httpStatus: number | null;
54
- contentType: string | null;
55
- upstreamRequestId: string | null;
56
- durationMs: number;
57
- eventCount: number;
58
- eventTypes: Record<string, number>;
59
- webSearchCalls: number;
60
- textOutputChars: number;
61
- imageResultCount: number;
62
- firstImageChars: number;
63
- diagnostics: ResponseDiagnostics | null;
64
- };
65
- error: {
66
- code: string | null;
67
- type: string | null;
68
- param: string | null;
69
- message: string;
70
- upstreamBodyChars?: number;
71
- } | null;
72
- }
73
-
74
- const BUILTIN_PROMPT_ID = "builtin_cat";
75
- const BUILTIN_CAT_PROMPT = "고양이";
76
- const TEXT_OK_PROMPT = "Reply with exactly OK.";
77
-
78
- function imageTool(size: string, quality: string, moderation: string) {
79
- return { type: "image_generation", size, quality, moderation, action: "generate" };
80
- }
81
-
82
- function createProbeSpecs({
83
- model,
84
- size,
85
- quality,
86
- moderation,
87
- prompt,
88
- matrix,
89
- }: Required<Pick<ImageDoctorProbeOptions, "model" | "size" | "quality" | "moderation" | "prompt">> & { matrix: boolean }): ProbeSpec[] {
90
- const imageOnlyTools = [imageTool(size, quality, moderation)];
91
- const webSearchImageTools = [{ type: "web_search" }, imageTool(size, quality, moderation)];
92
- const specs: ProbeSpec[] = [
93
- {
94
- id: "text_sanity",
95
- expectation: "text",
96
- promptId: "builtin_text_ok",
97
- promptChars: TEXT_OK_PROMPT.length,
98
- stream: false,
99
- toolTypes: [],
100
- toolChoiceKind: "none",
101
- payload: {
102
- model,
103
- input: [{ role: "user", content: TEXT_OK_PROMPT }],
104
- stream: false,
105
- },
106
- },
107
- {
108
- id: "minimal_image_non_stream",
109
- expectation: "image",
110
- promptId: BUILTIN_PROMPT_ID,
111
- promptChars: prompt.length,
112
- stream: false,
113
- toolTypes: ["image_generation"],
114
- toolChoiceKind: "image_generation",
115
- payload: {
116
- model,
117
- input: [{ role: "user", content: prompt }],
118
- tools: imageOnlyTools,
119
- tool_choice: { type: "image_generation" },
120
- stream: false,
121
- },
122
- },
123
- {
124
- id: "minimal_image_stream",
125
- expectation: "image",
126
- promptId: BUILTIN_PROMPT_ID,
127
- promptChars: prompt.length,
128
- stream: true,
129
- toolTypes: ["image_generation"],
130
- toolChoiceKind: "image_generation",
131
- payload: {
132
- model,
133
- input: [{ role: "user", content: prompt }],
134
- tools: imageOnlyTools,
135
- tool_choice: { type: "image_generation" },
136
- stream: true,
137
- },
138
- },
139
- ];
140
- if (!matrix) return specs;
141
- return [
142
- ...specs,
143
- {
144
- id: "current_payload_no_search_required",
145
- expectation: "image",
146
- promptId: BUILTIN_PROMPT_ID,
147
- promptChars: prompt.length,
148
- stream: true,
149
- toolTypes: ["image_generation"],
150
- toolChoiceKind: "required",
151
- payload: {
152
- model,
153
- input: [
154
- { role: "developer", content: GENERATE_NO_SEARCH_DEVELOPER_PROMPT },
155
- { role: "user", content: buildUserTextPrompt(prompt, "auto", { webSearchEnabled: false }) },
156
- ],
157
- tools: imageOnlyTools,
158
- tool_choice: "required",
159
- reasoning: { effort: "low" },
160
- stream: true,
161
- },
162
- },
163
- {
164
- id: "current_payload_web_search_required",
165
- expectation: "image",
166
- promptId: BUILTIN_PROMPT_ID,
167
- promptChars: prompt.length,
168
- stream: true,
169
- toolTypes: ["web_search", "image_generation"],
170
- toolChoiceKind: "required",
171
- payload: {
172
- model,
173
- input: [
174
- { role: "developer", content: GENERATE_DEVELOPER_PROMPT },
175
- { role: "user", content: buildUserTextPrompt(prompt, "auto", { webSearchEnabled: true }) },
176
- ],
177
- tools: webSearchImageTools,
178
- tool_choice: "required",
179
- reasoning: { effort: "low" },
180
- stream: true,
181
- },
182
- },
183
- {
184
- id: "current_payload_web_search_forced_image",
185
- expectation: "image",
186
- promptId: BUILTIN_PROMPT_ID,
187
- promptChars: prompt.length,
188
- stream: true,
189
- toolTypes: ["web_search", "image_generation"],
190
- toolChoiceKind: "image_generation",
191
- payload: {
192
- model,
193
- input: [
194
- { role: "developer", content: GENERATE_DEVELOPER_PROMPT },
195
- { role: "user", content: buildUserTextPrompt(prompt, "auto", { webSearchEnabled: true }) },
196
- ],
197
- tools: webSearchImageTools,
198
- tool_choice: { type: "image_generation" },
199
- reasoning: { effort: "low" },
200
- stream: true,
201
- },
202
- },
203
- ];
204
- }
205
-
206
- async function endpointFor(provider: string, options: ImageDoctorProbeOptions) {
207
- const ctx = options.ctx || { config: defaultConfig };
208
- if (provider === "api") {
209
- const headers: Record<string, string> = {
210
- "Content-Type": "application/json",
211
- Accept: "text/event-stream, application/json",
212
- Authorization: apiAuthorizationHeader(options.apiKey),
213
- };
214
- return {
215
- url: "https://api.openai.com/v1/responses",
216
- headers,
217
- };
218
- }
219
- await waitForOAuthReady(ctx);
220
- const port = ctx.config?.oauth?.proxyPort || defaultConfig.oauth.proxyPort;
221
- const baseUrl = safeOAuthBaseUrl(options.oauthUrl || `http://127.0.0.1:${port}`);
222
- const headers: Record<string, string> = {
223
- "Content-Type": "application/json",
224
- Accept: "text/event-stream, application/json",
225
- };
226
- return {
227
- url: `${baseUrl}/v1/responses`,
228
- headers,
229
- };
230
- }
231
-
232
- function apiAuthorizationHeader(apiKey: string | undefined) {
233
- const key = typeof apiKey === "string" ? apiKey.trim() : "";
234
- if (!key) {
235
- throw Object.assign(new Error("API key is required for API provider image probe"), {
236
- code: "API_KEY_REQUIRED",
237
- });
238
- }
239
- if (/[\u0000-\u001f\u007f]/.test(key)) {
240
- throw Object.assign(new Error("API key contains invalid characters."), {
241
- code: "AUTH_API_KEY_INVALID",
242
- });
243
- }
244
- return `Bearer ${key}`;
245
- }
246
-
247
- function safeOAuthBaseUrl(value: string) {
248
- try {
249
- const parsed = new URL(value);
250
- parsed.username = "";
251
- parsed.password = "";
252
- return parsed.toString().replace(/\/$/, "");
253
- } catch {
254
- return value.replace(/\/$/, "");
255
- }
256
- }
257
-
258
- function sanitizeProbeErrorMessage(value: string) {
259
- return value
260
- .replace(/([a-z][a-z0-9+.-]*:\/\/)([^/\s@]+)@/gi, "$1[redacted]@")
261
- .replace(/([?&](?:access_token|api_key|key|secret|token)=)[^&\s]+/gi, "$1[redacted]")
262
- .replace(/Bearer\s+[^"'\s]+/gi, "Bearer [redacted]")
263
- .replace(/sk-[A-Za-z0-9_-]+/g, "sk-[redacted]");
264
- }
265
-
266
- function safeUpstreamError(text: string) {
267
- try {
268
- const parsed = JSON.parse(text);
269
- const error = parsed?.error || {};
270
- return {
271
- code: safeDiagnosticLabel(error.code),
272
- type: safeDiagnosticLabel(error.type),
273
- param: safeDiagnosticLabel(error.param),
274
- };
275
- } catch {
276
- return { code: null, type: null, param: null };
277
- }
278
- }
279
-
280
- function reasonFrom(result: Omit<ImageDoctorProbeResult, "diagnosticReason">): string | null {
281
- const diagnostics = result.response.diagnostics;
282
- if (!result.error && result.ok) return null;
283
- if (result.error?.code) return result.error.code;
284
- if (!diagnostics) return "probe_failed";
285
- if (diagnostics.streamStats.bytesRead > 0 && result.response.eventCount === 0) return "stream_parse_failed";
286
- if (diagnostics.imageCallFailed) return "image_tool_failed";
287
- if (diagnostics.imageCallCompleted && diagnostics.imageResultCount === 0) return "image_tool_completed_without_result";
288
- if (!diagnostics.imageCallSeen && result.response.webSearchCalls > 0) return "web_search_only_response";
289
- if (!diagnostics.imageCallSeen && diagnostics.messageOutputSeen) return "image_tool_not_called";
290
- if (result.expectation === "text" && result.response.textOutputChars === 0) return "text_output_missing";
291
- if (result.expectation === "image" && result.response.imageResultCount === 0) return "image_output_missing";
292
- return "probe_failed";
293
- }
294
-
295
- async function runSingleProbe(provider: string, options: ImageDoctorProbeOptions, spec: ProbeSpec): Promise<ImageDoctorProbeResult> {
296
- const start = Date.now();
297
- let httpStatus: number | null = null;
298
- let contentType: string | null = null;
299
- let upstreamRequestId: string | null = null;
300
- try {
301
- const endpoint = await endpointFor(provider, options);
302
- const controller = new AbortController();
303
- const timer = setTimeout(() => controller.abort(), options.timeoutMs || defaultConfig.oauth.generationTimeoutMs);
304
- try {
305
- const res = await fetch(endpoint.url, {
306
- method: "POST",
307
- headers: endpoint.headers,
308
- signal: controller.signal,
309
- body: JSON.stringify(spec.payload),
310
- });
311
- httpStatus = res.status;
312
- contentType = res.headers.get("content-type");
313
- upstreamRequestId = res.headers.get("x-request-id") || res.headers.get("openai-request-id");
314
- if (!res.ok) {
315
- const body = await res.text();
316
- const upstream = safeUpstreamError(body);
317
- const partial = {
318
- id: spec.id,
319
- ok: false,
320
- expectation: spec.expectation,
321
- request: {
322
- stream: spec.stream,
323
- toolTypes: spec.toolTypes,
324
- toolChoiceKind: spec.toolChoiceKind,
325
- promptId: spec.promptId,
326
- promptChars: spec.promptChars,
327
- },
328
- response: {
329
- httpStatus,
330
- contentType,
331
- upstreamRequestId,
332
- durationMs: Date.now() - start,
333
- eventCount: 0,
334
- eventTypes: {},
335
- webSearchCalls: 0,
336
- textOutputChars: 0,
337
- imageResultCount: 0,
338
- firstImageChars: 0,
339
- diagnostics: null,
340
- },
341
- error: {
342
- ...upstream,
343
- message: "Upstream returned a non-2xx response",
344
- upstreamBodyChars: body.length,
345
- },
346
- };
347
- return { ...partial, diagnosticReason: reasonFrom(partial) };
348
- }
349
- const parsed = contentType?.includes("text/event-stream")
350
- ? await parseStream(res, { scope: "doctor-image-probe", maxImages: 1 })
351
- : await parseJson(res, 1);
352
- const ok = spec.expectation === "image"
353
- ? Boolean(parsed.images[0]?.b64)
354
- : Boolean(parsed.text && parsed.text.trim());
355
- const partial = {
356
- id: spec.id,
357
- ok,
358
- expectation: spec.expectation,
359
- request: {
360
- stream: spec.stream,
361
- toolTypes: spec.toolTypes,
362
- toolChoiceKind: spec.toolChoiceKind,
363
- promptId: spec.promptId,
364
- promptChars: spec.promptChars,
365
- },
366
- response: {
367
- httpStatus,
368
- contentType,
369
- upstreamRequestId,
370
- durationMs: Date.now() - start,
371
- eventCount: parsed.eventCount,
372
- eventTypes: parsed.eventTypes,
373
- webSearchCalls: parsed.webSearchCalls,
374
- textOutputChars: parsed.text?.length || 0,
375
- imageResultCount: parsed.images.length,
376
- firstImageChars: parsed.images[0]?.b64.length || 0,
377
- diagnostics: parsed.diagnostics,
378
- },
379
- error: null,
380
- };
381
- return { ...partial, diagnosticReason: reasonFrom(partial) };
382
- } finally {
383
- clearTimeout(timer);
384
- }
385
- } catch (e) {
386
- const err = errInfo(e);
387
- const partial = {
388
- id: spec.id,
389
- ok: false,
390
- expectation: spec.expectation,
391
- request: {
392
- stream: spec.stream,
393
- toolTypes: spec.toolTypes,
394
- toolChoiceKind: spec.toolChoiceKind,
395
- promptId: spec.promptId,
396
- promptChars: spec.promptChars,
397
- },
398
- response: {
399
- httpStatus,
400
- contentType,
401
- upstreamRequestId,
402
- durationMs: Date.now() - start,
403
- eventCount: Number((err.raw as { eventCount?: unknown })?.eventCount) || 0,
404
- eventTypes: {},
405
- webSearchCalls: 0,
406
- textOutputChars: 0,
407
- imageResultCount: 0,
408
- firstImageChars: 0,
409
- diagnostics: null,
410
- },
411
- error: {
412
- code: safeDiagnosticLabel(err.code),
413
- type: null,
414
- param: null,
415
- message: err.name === "AbortError" ? "Probe timed out" : sanitizeProbeErrorMessage(err.message),
416
- },
417
- };
418
- return { ...partial, diagnosticReason: reasonFrom(partial) };
419
- }
420
- }
421
-
422
- export async function runImageDoctorProbe(options: ImageDoctorProbeOptions = {}) {
423
- const provider = options.provider || "oauth";
424
- const model = options.model || defaultConfig.imageModels?.default || "gpt-5.4-mini";
425
- const size = options.size || "1024x1024";
426
- const quality = options.quality || "low";
427
- const moderation = options.moderation || "low";
428
- const prompt = options.prompt || BUILTIN_CAT_PROMPT;
429
- const specs = createProbeSpecs({
430
- model,
431
- size,
432
- quality,
433
- moderation,
434
- prompt,
435
- matrix: options.matrix === true,
436
- });
437
- const probes: ImageDoctorProbeResult[] = [];
438
- for (const spec of specs) probes.push(await runSingleProbe(provider, options, spec));
439
- return {
440
- provider,
441
- endpointKind: provider === "api" ? "api" : "oauth",
442
- model,
443
- size,
444
- quality,
445
- moderation,
446
- promptId: options.prompt ? "custom" : BUILTIN_PROMPT_ID,
447
- promptChars: prompt.length,
448
- matrix: options.matrix === true,
449
- probes,
450
- summary: {
451
- ok: probes.every((probe) => probe.ok),
452
- passed: probes.filter((probe) => probe.ok).length,
453
- failed: probes.filter((probe) => !probe.ok).length,
454
- },
455
- };
456
- }