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
@@ -1,100 +0,0 @@
1
- // 0.09.8 — upstream error classifier.
2
- // Pattern-match upstream OpenAI / OAuth / network errors into stable ImaErrorCode
3
- // values so the UI can surface localized, actionable messages with CTAs.
4
-
5
- /** @typedef {"REF_TOO_LARGE"|"REF_NOT_BASE64"|"REF_EMPTY"|"REF_TOO_MANY"|"MODERATION_REFUSED"|"UPSTREAM_5XX"|"AUTH_CHATGPT_EXPIRED"|"AUTH_API_KEY_INVALID"|"NETWORK_FAILED"|"OAUTH_UNAVAILABLE"|"INVALID_REQUEST"|"INVALID_MODERATION"|"APIKEY_DISABLED"|"SAFETY_REFUSAL"|"EMPTY_RESPONSE"|"STREAM_PARSE_FAILED"|"IMAGE_TOOL_NOT_CALLED"|"WEB_SEARCH_ONLY_RESPONSE"|"IMAGE_TOOL_FAILED"|"IMAGE_TOOL_COMPLETED_WITHOUT_RESULT"|"OAUTH_IMAGE_CAPABILITY_UNAVAILABLE"|"RESPONSES_STREAM_ERROR"|"OAUTH_UPSTREAM_ERROR"|"DB_ERROR"|"UNKNOWN"} ImaErrorCode */
6
-
7
- const INVALID_REQUEST_CODES = new Set([
8
- "bad_request",
9
- "invalid_request",
10
- "invalid_request_error",
11
- "invalid_value",
12
- "invalid_size",
13
- "invalid_type",
14
- "invalid_parameter",
15
- "missing_required_parameter",
16
- "unsupported_parameter",
17
- "unsupported_value",
18
- ]);
19
-
20
- /**
21
- * Normalize provider-specific request/validation codes into app codes.
22
- * @param {string | undefined | null} code
23
- * @returns {ImaErrorCode}
24
- */
25
- export function classifyUpstreamErrorCode(code: string | undefined | null) {
26
- const s = String(code || "").toLowerCase();
27
- if (!s) return "UNKNOWN";
28
- if (INVALID_REQUEST_CODES.has(s)) return "INVALID_REQUEST";
29
- if (s.includes("moderation_blocked") || s.includes("moderation refused")) return "MODERATION_REFUSED";
30
- return "UNKNOWN";
31
- }
32
-
33
- /**
34
- * Classify an upstream error message into an ImaErrorCode.
35
- * Order matters: auth session expiry must beat generic "token" matches,
36
- * and moderation must beat generic 5xx.
37
- * @param {string | undefined | null} msg
38
- * @returns {ImaErrorCode}
39
- */
40
- export function classifyUpstreamError(msg: string | undefined | null) {
41
- const s = String(msg || "").toLowerCase();
42
- if (!s) return "UNKNOWN";
43
-
44
- if (s.includes("moderation_blocked") || s.includes("moderation refused")) {
45
- return "MODERATION_REFUSED";
46
- }
47
-
48
- // ChatGPT sign-in session expiry must precede the generic api-key checks
49
- // so it is not misclassified when messages contain both "token" and "api".
50
- if (
51
- s.includes("token is expired") ||
52
- s.includes("sign in again") ||
53
- (s.includes("access token") && s.includes("expired")) ||
54
- (s.includes("token") && s.includes("expired") && !s.includes("api key"))
55
- ) {
56
- return "AUTH_CHATGPT_EXPIRED";
57
- }
58
-
59
- if (
60
- s.includes("incorrect api key") ||
61
- s.includes("invalid authentication") ||
62
- s.includes("exceeded your current quota") ||
63
- s.includes("incorrect organization")
64
- ) {
65
- return "AUTH_API_KEY_INVALID";
66
- }
67
-
68
- if (
69
- s.includes("failed to fetch") ||
70
- s.includes("econnrefused") ||
71
- s.includes("econnreset") ||
72
- s.includes("enotfound") ||
73
- s.includes("etimedout") ||
74
- s.includes("network error")
75
- ) {
76
- return "NETWORK_FAILED";
77
- }
78
-
79
- if (s.includes("oauth") && (s.includes("not running") || s.includes("unavailable") || s.includes("not ready"))) {
80
- return "OAUTH_UNAVAILABLE";
81
- }
82
-
83
- if (
84
- s.includes("invalid_request_error") ||
85
- s.includes("invalid_value") ||
86
- s.includes("invalid size") ||
87
- s.includes("invalid request") ||
88
- s.includes("requested resolution") ||
89
- s.includes("minimum pixel budget") ||
90
- s.includes("unsupported value")
91
- ) {
92
- return "INVALID_REQUEST";
93
- }
94
-
95
- if (s.includes("an error occurred while processing") || /\b5\d\d\b/.test(s)) {
96
- return "UPSTREAM_5XX";
97
- }
98
-
99
- return "UNKNOWN";
100
- }
@@ -1,28 +0,0 @@
1
- import { isJobCanceled } from "./inflight.js";
2
-
3
- export const GENERATION_CANCELED_CODE = "GENERATION_CANCELED";
4
-
5
- export interface GenerationCanceledError extends Error {
6
- status: number;
7
- code: typeof GENERATION_CANCELED_CODE;
8
- }
9
-
10
- export function makeGenerationCanceledError(): GenerationCanceledError {
11
- const err = new Error("Generation canceled") as GenerationCanceledError;
12
- err.status = 499;
13
- err.code = GENERATION_CANCELED_CODE;
14
- return err;
15
- }
16
-
17
- export function isGenerationCanceledError(value: unknown): value is GenerationCanceledError {
18
- return Boolean(
19
- value &&
20
- typeof value === "object" &&
21
- "code" in value &&
22
- (value as { code?: unknown }).code === GENERATION_CANCELED_CODE,
23
- );
24
- }
25
-
26
- export function throwIfJobCanceled(requestId: string | null | undefined) {
27
- if (isJobCanceled(requestId)) throw makeGenerationCanceledError();
28
- }
@@ -1,238 +0,0 @@
1
- import { classifyUpstreamError, classifyUpstreamErrorCode } from "./errorClassify.js";
2
- import { safeDiagnosticLabel } from "./responsesParse.js";
3
- import { RESPONSE_DIAGNOSTIC_CODES } from "./responsesErrors.js";
4
-
5
- const PASSTHROUGH_CODES = new Set([
6
- "OAUTH_UNAVAILABLE",
7
- "NETWORK_FAILED",
8
- "AUTH_CHATGPT_EXPIRED",
9
- "AUTH_API_KEY_INVALID",
10
- "UPSTREAM_5XX",
11
- "OAUTH_IMAGE_TIMEOUT",
12
- "API_KEY_REQUIRED",
13
- "INVALID_REQUEST",
14
- "OAUTH_UPSTREAM_ERROR",
15
- ]);
16
-
17
- const SAFETY_CODES = new Set(["SAFETY_REFUSAL", "MODERATION_REFUSED", "moderation_blocked"]);
18
-
19
- function has4kSize(size: unknown) {
20
- if (typeof size !== "string") return false;
21
- const [w, h] = size.split("x").map((part: string) => Number(part));
22
- return Number.isFinite(w) && Number.isFinite(h) && Math.max(w, h) >= 3840;
23
- }
24
-
25
- export interface UpstreamErr {
26
- diagnosticReason?: string;
27
- referenceMismatchCount?: number;
28
- size?: string;
29
- upstreamCode?: string;
30
- upstreamType?: string;
31
- upstreamParam?: string;
32
- code?: string;
33
- message?: string;
34
- status?: number;
35
- cause?: unknown;
36
- eventType?: string;
37
- eventCount?: number;
38
- eventTypes?: unknown;
39
- webSearchCalls?: number;
40
- responseDiagnostics?: unknown;
41
- webSearchEnabled?: boolean;
42
- toolTypes?: unknown;
43
- toolChoiceKind?: string;
44
- promptChars?: number;
45
- quality?: string;
46
- moderation?: string;
47
- model?: string;
48
- provider?: string;
49
- refsCount?: number;
50
- inputImageCount?: number;
51
- referenceDiagnostics?: unknown;
52
- retryKind?: string;
53
- initialEventCount?: number;
54
- initialEventTypes?: unknown;
55
- referencesDroppedOnRetry?: boolean;
56
- developerPromptDroppedOnRetry?: boolean;
57
- webSearchDroppedOnRetry?: boolean;
58
- fallbackEventCount?: number;
59
- fallbackEventTypes?: unknown;
60
- fallbackImageCallSeen?: boolean;
61
- fallbackImageResultCount?: number;
62
- name?: string;
63
- stack?: string;
64
- }
65
-
66
- function diagnosticReasonFrom(err: UpstreamErr | null | undefined) {
67
- if (typeof err?.diagnosticReason === "string" && err.diagnosticReason) return err.diagnosticReason;
68
- if (Number(err?.referenceMismatchCount) > 0) return "reference_mime_mismatch_candidate";
69
- const responseDiagnosticReason = responseDiagnosticReasonFrom(err);
70
- if (responseDiagnosticReason) return responseDiagnosticReason;
71
- if (has4kSize(err?.size)) return "experimental_4k_empty_response";
72
- return null;
73
- }
74
-
75
- function responseDiagnosticReasonFrom(err: UpstreamErr | null | undefined) {
76
- if (!err?.responseDiagnostics || typeof err.responseDiagnostics !== "object") return null;
77
- const diagnostics = err.responseDiagnostics as {
78
- imageCallSeen?: unknown;
79
- imageCallCompleted?: unknown;
80
- imageCallFailed?: unknown;
81
- imageResultCount?: unknown;
82
- messageOutputSeen?: unknown;
83
- streamStats?: { bytesRead?: unknown };
84
- };
85
- const bytesRead = Number(diagnostics.streamStats?.bytesRead);
86
- if (Number.isFinite(bytesRead) && bytesRead > 0 && Number(err.eventCount) === 0) return "stream_parse_failed";
87
- if (diagnostics.imageCallFailed === true) return "image_tool_failed";
88
- if (diagnostics.imageCallCompleted === true && Number(diagnostics.imageResultCount) === 0) return "image_tool_completed_without_result";
89
- if (diagnostics.imageCallSeen !== true && Number(err.webSearchCalls) > 0) return "web_search_only_response";
90
- if (diagnostics.imageCallSeen !== true && diagnostics.messageOutputSeen === true) return "image_tool_not_called";
91
- return null;
92
- }
93
-
94
- function responseDiagnosticCodeFrom(err: UpstreamErr | null | undefined) {
95
- const reason = responseDiagnosticReasonFrom(err);
96
- if (reason === "stream_parse_failed") return "STREAM_PARSE_FAILED";
97
- if (reason === "web_search_only_response") return "WEB_SEARCH_ONLY_RESPONSE";
98
- if (reason === "image_tool_not_called") return "IMAGE_TOOL_NOT_CALLED";
99
- if (reason === "image_tool_failed") return "IMAGE_TOOL_FAILED";
100
- if (reason === "image_tool_completed_without_result") return "IMAGE_TOOL_COMPLETED_WITHOUT_RESULT";
101
- return null;
102
- }
103
-
104
- export function errorCodeFrom(err: UpstreamErr | null | undefined): string {
105
- if (!err) return "UNKNOWN";
106
- const appCode = err.code as string;
107
- if (RESPONSE_DIAGNOSTIC_CODES.has(appCode) || appCode === "EMPTY_RESPONSE") return appCode;
108
- const upstreamCode = classifyUpstreamErrorCode(err.upstreamCode);
109
- if (upstreamCode !== "UNKNOWN") return upstreamCode;
110
- const upstreamType = classifyUpstreamErrorCode(err.upstreamType);
111
- if (upstreamType !== "UNKNOWN") return upstreamType;
112
- // Known app-level codes pass through directly (before message heuristic)
113
- if (PASSTHROUGH_CODES.has(appCode) || SAFETY_CODES.has(appCode)) return appCode;
114
- const rawCode = classifyUpstreamErrorCode(err.code);
115
- if (rawCode !== "UNKNOWN") return rawCode;
116
- const direct = classifyUpstreamError(err.message);
117
- if (direct !== "UNKNOWN") return direct;
118
- const responseDiagnosticCode = responseDiagnosticCodeFrom(err);
119
- if (responseDiagnosticCode) return responseDiagnosticCode;
120
- const status = Number(err.status);
121
- if (Number.isFinite(status) && status >= 400 && status < 500 && !SAFETY_CODES.has(err.code as string)) {
122
- return "INVALID_REQUEST";
123
- }
124
- if (typeof err.code === "string" && err.code) return err.code;
125
- if (err.cause) return errorCodeFrom(err.cause as UpstreamErr);
126
- return "UNKNOWN";
127
- }
128
-
129
- export function isNonRetryableGenerationError(err: UpstreamErr | null | undefined) {
130
- const code = errorCodeFrom(err);
131
- if (SAFETY_CODES.has(code)) return false;
132
- const status = Number(err?.status);
133
- return code === "INVALID_REQUEST" || code === "OAUTH_IMAGE_TIMEOUT" || (Number.isFinite(status) && status >= 400 && status < 500);
134
- }
135
-
136
- export function statusForErrorCode(code: string, fallback = 500) {
137
- if (code === "OAUTH_UNAVAILABLE" || code === "NETWORK_FAILED") return 503;
138
- if (code === "AUTH_CHATGPT_EXPIRED" || code === "AUTH_API_KEY_INVALID") return 401;
139
- if (code === "API_KEY_REQUIRED") return 401;
140
- if (code === "UPSTREAM_5XX") return 502;
141
- if (code === "RESPONSES_STREAM_ERROR") return 502;
142
- if (code === "OAUTH_IMAGE_TIMEOUT") return 504;
143
- if (code === "INVALID_REQUEST") return 400;
144
- if (RESPONSE_DIAGNOSTIC_CODES.has(code)) return 422;
145
- if (code === "SAFETY_REFUSAL" || code === "MODERATION_REFUSED" || code === "moderation_blocked") return 422;
146
- return fallback;
147
- }
148
-
149
- function copyEmptyResponseMetadata(target: any, source: UpstreamErr | null | undefined) {
150
- if (!source) return;
151
- if (typeof source.eventCount === "number") target.eventCount = source.eventCount;
152
- if (source.eventTypes) target.eventTypes = source.eventTypes;
153
- if (typeof source.webSearchCalls === "number") target.webSearchCalls = source.webSearchCalls;
154
- if (source.responseDiagnostics) target.responseDiagnostics = source.responseDiagnostics;
155
- if (typeof source.webSearchEnabled === "boolean") target.webSearchEnabled = source.webSearchEnabled;
156
- if (Array.isArray(source.toolTypes)) target.toolTypes = source.toolTypes;
157
- if (source.toolChoiceKind) target.toolChoiceKind = source.toolChoiceKind;
158
- if (typeof source.promptChars === "number") target.promptChars = source.promptChars;
159
- if (typeof source.refsCount === "number") target.refsCount = source.refsCount;
160
- if (typeof source.inputImageCount === "number") target.inputImageCount = source.inputImageCount;
161
- if (Array.isArray(source.referenceDiagnostics)) target.referenceDiagnostics = source.referenceDiagnostics;
162
- if (typeof source.referenceMismatchCount === "number") target.referenceMismatchCount = source.referenceMismatchCount;
163
- if (source.retryKind) target.retryKind = source.retryKind;
164
- if (typeof source.initialEventCount === "number") target.initialEventCount = source.initialEventCount;
165
- if (source.initialEventTypes) target.initialEventTypes = source.initialEventTypes;
166
- if (typeof source.referencesDroppedOnRetry === "boolean") target.referencesDroppedOnRetry = source.referencesDroppedOnRetry;
167
- if (typeof source.developerPromptDroppedOnRetry === "boolean") target.developerPromptDroppedOnRetry = source.developerPromptDroppedOnRetry;
168
- if (typeof source.webSearchDroppedOnRetry === "boolean") target.webSearchDroppedOnRetry = source.webSearchDroppedOnRetry;
169
- if (typeof source.fallbackEventCount === "number") target.fallbackEventCount = source.fallbackEventCount;
170
- if (source.fallbackEventTypes) target.fallbackEventTypes = source.fallbackEventTypes;
171
- if (typeof source.fallbackImageCallSeen === "boolean") target.fallbackImageCallSeen = source.fallbackImageCallSeen;
172
- if (typeof source.fallbackImageResultCount === "number") target.fallbackImageResultCount = source.fallbackImageResultCount;
173
- }
174
-
175
- export function normalizeGenerationFailure(lastErr: UpstreamErr | null | undefined, options: any = {}) {
176
- const code = errorCodeFrom(lastErr);
177
- if (PASSTHROUGH_CODES.has(code)) {
178
- const err: any = new Error(lastErr?.message || options.proxyMessage || "GPT OAuth proxy/network failure");
179
- err.code = code;
180
- err.status = lastErr?.status || statusForErrorCode(code);
181
- err.cause = lastErr;
182
- if (lastErr?.upstreamCode) err.upstreamCode = safeDiagnosticLabel(lastErr.upstreamCode);
183
- if (lastErr?.upstreamType) err.upstreamType = safeDiagnosticLabel(lastErr.upstreamType);
184
- if (lastErr?.upstreamParam) err.upstreamParam = safeDiagnosticLabel(lastErr.upstreamParam);
185
- if (lastErr?.eventType) err.eventType = lastErr.eventType;
186
- if (typeof lastErr?.eventCount === "number") err.eventCount = lastErr.eventCount;
187
- return err;
188
- }
189
- if (SAFETY_CODES.has(code)) {
190
- const err: any = new Error(options.safetyMessage || lastErr?.message || "Content generation refused after retries");
191
- err.code = "SAFETY_REFUSAL";
192
- err.status = 422;
193
- err.cause = lastErr;
194
- return err;
195
- }
196
- if (RESPONSE_DIAGNOSTIC_CODES.has(code)) {
197
- const err: any = new Error(lastErr?.message || "Image generation did not return image data");
198
- err.code = code;
199
- err.status = lastErr?.status || statusForErrorCode(code, 422);
200
- err.cause = lastErr;
201
- if (lastErr?.upstreamCode) err.upstreamCode = safeDiagnosticLabel(lastErr.upstreamCode);
202
- if (lastErr?.upstreamType) err.upstreamType = safeDiagnosticLabel(lastErr.upstreamType);
203
- if (lastErr?.upstreamParam) err.upstreamParam = safeDiagnosticLabel(lastErr.upstreamParam);
204
- if (lastErr?.eventType) err.eventType = lastErr.eventType;
205
- copyEmptyResponseMetadata(err, lastErr);
206
- err.diagnosticReason = diagnosticReasonFrom(lastErr) || code.toLowerCase();
207
- return err;
208
- }
209
- // Empty response with metadata → likely a technical limitation (unsupported size/quality/model)
210
- if (typeof lastErr?.eventCount === "number") {
211
- const meta: string[] = [];
212
- if (lastErr.size) meta.push(`size=${lastErr.size}`);
213
- if (lastErr.quality) meta.push(`quality=${lastErr.quality}`);
214
- if (lastErr.model) meta.push(`model=${lastErr.model}`);
215
- const msg = meta.length
216
- ? `No image data returned. This may be an unsupported ${meta.join(", ")} combination. Try a different size or model.`
217
- : "No image data returned from the image backend. Try a different size, quality, or prompt.";
218
- const err: any = new Error(msg);
219
- err.code = "EMPTY_RESPONSE";
220
- err.status = 422;
221
- err.cause = lastErr;
222
- if (lastErr.size) err.size = lastErr.size;
223
- if (lastErr.quality) err.quality = lastErr.quality;
224
- if (lastErr.model) err.model = lastErr.model;
225
- if (lastErr.provider) err.provider = lastErr.provider;
226
- if (lastErr.moderation) err.moderation = lastErr.moderation;
227
- copyEmptyResponseMetadata(err, lastErr);
228
- const diagnosticReason = diagnosticReasonFrom(lastErr);
229
- if (diagnosticReason) err.diagnosticReason = diagnosticReason;
230
- return err;
231
- }
232
- // Unrecognized errors → UNKNOWN (do not pretend they are safety refusals)
233
- const err: any = new Error(lastErr?.message || options.proxyMessage || "Image generation failed");
234
- err.code = "UNKNOWN";
235
- err.status = lastErr?.status || 500;
236
- err.cause = lastErr;
237
- return err;
238
- }