dsh-image-gen 0.8.5 → 0.8.7

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.
package/lib/index.js CHANGED
@@ -5581,6 +5581,111 @@ function toolAbortedBeforeDispatchResult(prior) {
5581
5581
  };
5582
5582
  }
5583
5583
  //#endregion
5584
+ //#region lib/types/watermark.js
5585
+ const WATERMARK_OPTIONS = [
5586
+ {
5587
+ value: "default",
5588
+ label: "渠道默认"
5589
+ },
5590
+ {
5591
+ value: "off",
5592
+ label: "关闭"
5593
+ },
5594
+ {
5595
+ value: "on",
5596
+ label: "开启"
5597
+ }
5598
+ ];
5599
+ function configuredField(extra) {
5600
+ if (typeof extra?.watermark === "boolean") return "watermark";
5601
+ if (typeof extra?.watermark_enabled === "boolean") return "watermark_enabled";
5602
+ const parameters = extra?.parameters;
5603
+ if (parameters && typeof parameters === "object" && !Array.isArray(parameters) && typeof parameters.watermark === "boolean") return "parameters.watermark";
5604
+ }
5605
+ /** Model names alone do not establish the protocol of an unknown relay. */
5606
+ function officialContract(config, mode) {
5607
+ const model = (mode === "generate" ? config.openaiCompatExtraBody : config.openaiCompatEditExtra)?.model ?? config.openaiCompatModel;
5608
+ if (typeof model !== "string") return void 0;
5609
+ try {
5610
+ const url = new URL(config.openaiCompatBaseURL ?? "");
5611
+ if (url.protocol !== "https:" || url.port || url.search || url.hash) return void 0;
5612
+ const path = url.pathname.replace(/\/+$/, "");
5613
+ if (url.hostname === "token.sensenova.cn" && path === "/v1" && model === "sensenova-u1.5-lite") return "sensenova";
5614
+ if (/^[a-z0-9-]+\.(?:cn-beijing|ap-southeast-1|us-east-1|eu-central-1|ap-northeast-1|cn-hongkong)\.maas\.aliyuncs\.com$/.test(url.hostname) && path === "/compatible-mode/v1" && /^qwen-image-(?:3\.0(?:-pro)?|2\.1-(?:pro|turbo))$/.test(model)) return "qwen";
5615
+ } catch {}
5616
+ }
5617
+ /** Known official edit contracts take precedence over relay-specific format settings. */
5618
+ function compatEditFormat(config) {
5619
+ const contract = officialContract(config, "edit");
5620
+ if (contract === "sensenova") return "jsonImageUrlArray";
5621
+ if (contract === "qwen") return "qwenJson";
5622
+ return config.openaiCompatEditFormat ?? "multipart";
5623
+ }
5624
+ function compatWatermarkField(config, mode = "generate") {
5625
+ if (officialContract(config, mode) !== void 0) return "watermark";
5626
+ if (mode === "generate") return configuredField(config.openaiCompatExtraBody);
5627
+ return compatEditFormat(config) === "jsonImageUrlArray" ? configuredField(config.openaiCompatEditExtra) : void 0;
5628
+ }
5629
+ function overrideField(extra, field, selected) {
5630
+ const watermark = selected === "on";
5631
+ return field === "parameters.watermark" ? {
5632
+ ...extra,
5633
+ parameters: {
5634
+ ...extra?.parameters,
5635
+ watermark
5636
+ }
5637
+ } : {
5638
+ ...extra,
5639
+ [field]: watermark
5640
+ };
5641
+ }
5642
+ /** Preserve all advanced fields; only an explicit workbench choice overrides its own watermark. */
5643
+ function compatGenerationExtraBody(config, selected) {
5644
+ const extra = config.openaiCompatExtraBody;
5645
+ if (selected === void 0 || selected === "default") return extra;
5646
+ const field = compatWatermarkField(config);
5647
+ if (field === void 0) throw new Error("该渠道尚未确认文生图水印支持,请刷新工作台");
5648
+ return overrideField(extra, field, selected);
5649
+ }
5650
+ function compatEditExtraBody(config, selected) {
5651
+ if (selected === void 0 || selected === "default") return void 0;
5652
+ const field = compatWatermarkField(config, "edit");
5653
+ if (field === void 0) throw new Error("该渠道尚未确认图生图水印支持,请刷新工作台");
5654
+ return overrideField(config.openaiCompatEditExtra, field, selected);
5655
+ }
5656
+ function selectedWatermark(selected, channelDefault) {
5657
+ return selected === "off" ? false : selected === "on" ? true : channelDefault;
5658
+ }
5659
+ function watermarkProfile(config, provider, model) {
5660
+ const capability = (mode) => {
5661
+ if (provider === "seedream" || provider === "dashscope" && /^qwen-image(?:$|-)/.test(model)) return { status: "supported" };
5662
+ if (provider === "openai-compat") return compatWatermarkField(config, mode) === void 0 ? {
5663
+ status: "unknown",
5664
+ reason: mode === "edit" && configuredField(config.openaiCompatEditExtra) !== void 0 ? "edit-format" : "channel-unconfirmed"
5665
+ } : { status: "supported" };
5666
+ if (provider === "zhipu") return {
5667
+ status: "unknown",
5668
+ reason: "account-unconfirmed"
5669
+ };
5670
+ if (provider === "dashscope") return {
5671
+ status: "unknown",
5672
+ reason: "model-unconfirmed"
5673
+ };
5674
+ return {
5675
+ status: "unavailable",
5676
+ reason: "no-api-control"
5677
+ };
5678
+ };
5679
+ const generate = capability("generate");
5680
+ return {
5681
+ watermarkCapabilities: {
5682
+ generate,
5683
+ edit: capability("edit")
5684
+ },
5685
+ ...generate.status === "supported" ? { watermarkOptions: WATERMARK_OPTIONS } : {}
5686
+ };
5687
+ }
5688
+ //#endregion
5584
5689
  //#region lib/types/shared.js
5585
5690
  /** Browser route used by the generated-image card. */
5586
5691
  const IMAGE_ROUTE = "/plugins/dsh-image-gen/image";
@@ -5596,6 +5701,8 @@ const INSPIRATION_ROUTE = "/plugins/dsh-image-gen/inspiration";
5596
5701
  const SAVE_WORKSPACE_ROUTE = "/plugins/dsh-image-gen/save-workspace";
5597
5702
  /** Browser route the settings card probes provider connectivity through. */
5598
5703
  const TEST_CONNECTION_ROUTE = "/plugins/dsh-image-gen/test";
5704
+ /** Non-secret settings capability probe, available even when the host cannot serve a form. */
5705
+ const SETTINGS_HEALTH_ROUTE = "/plugins/dsh-image-gen/settings-health";
5599
5706
  /** Browser route the workbench infinite canvas pushes live state through. */
5600
5707
  const CANVAS_STATE_ROUTE = "/plugins/dsh-image-gen/canvas-state";
5601
5708
  /** Upload a selected canvas original to the host attachment store. */
@@ -5715,6 +5822,17 @@ const SUBSCRIPTION_PROVIDER_DISPLAY_NAMES = {
5715
5822
  "grok-sub": "Grok 订阅",
5716
5823
  "google-sub": "Google 订阅"
5717
5824
  };
5825
+ const STUDIO_WATERMARK_VALUES = [
5826
+ "default",
5827
+ "off",
5828
+ "on"
5829
+ ];
5830
+ function studioWatermarkCapability(profile, mode) {
5831
+ return profile?.watermarkCapabilities?.[mode] ?? (mode === "generate" && profile?.watermarkOptions?.length ? { status: "supported" } : {
5832
+ status: "unknown",
5833
+ reason: "channel-unconfirmed"
5834
+ });
5835
+ }
5718
5836
  /** Default endpoints and base URLs. */
5719
5837
  const DEFAULT_GOOGLE_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/interactions";
5720
5838
  const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1";
@@ -5839,8 +5957,18 @@ const Config = z.object({
5839
5957
  googleEndpoint: volatile(z.string().default(DEFAULT_GOOGLE_ENDPOINT)),
5840
5958
  openaiBaseURL: volatile(z.string().default(DEFAULT_OPENAI_BASE_URL)),
5841
5959
  openaiModel: volatile(z.string().default(DEFAULT_OPENAI_MODEL)),
5960
+ openaiSizes: volatile(z.dict(z.dict(z.string())).default({})),
5842
5961
  openaiCompatBaseURL: volatile(z.string().default("")),
5843
5962
  openaiCompatModel: volatile(z.string().default("")),
5963
+ openaiCompatQuality: volatile(z.string().default("")),
5964
+ openaiCompatQualityOptions: volatile(z.array(z.string()).default([
5965
+ "auto",
5966
+ "low",
5967
+ "medium",
5968
+ "high"
5969
+ ])),
5970
+ openaiCompatExtraBody: volatile(z.dict(z.any()).default({})),
5971
+ openaiCompatEditSizeMode: volatile(z.union(["auto", "selected"]).default("auto")),
5844
5972
  openaiCompatEditFormat: volatile(z.union([
5845
5973
  z.const("multipart"),
5846
5974
  z.const("jsonImageUrlArray"),
@@ -5894,7 +6022,7 @@ function resolveProvider(config) {
5894
6022
  model,
5895
6023
  baseURL,
5896
6024
  imageSize: "1024x1024",
5897
- editFormat: config.openaiCompatEditFormat ?? "multipart",
6025
+ editFormat: compatEditFormat(config),
5898
6026
  editExtra: config.openaiCompatEditExtra ?? {}
5899
6027
  };
5900
6028
  }
@@ -7266,7 +7394,10 @@ async function generateDashScopeImage(options) {
7266
7394
  role: "user",
7267
7395
  content: [{ text: options.prompt }]
7268
7396
  }] },
7269
- parameters: { ...formattedSize === void 0 ? {} : { size: formattedSize } }
7397
+ parameters: {
7398
+ ...formattedSize === void 0 ? {} : { size: formattedSize },
7399
+ ...options.watermark === void 0 ? {} : { watermark: options.watermark }
7400
+ }
7270
7401
  },
7271
7402
  operation: "generation"
7272
7403
  });
@@ -7285,7 +7416,8 @@ async function editDashScopeImage(options) {
7285
7416
  }] },
7286
7417
  parameters: {
7287
7418
  prompt_extend: true,
7288
- ...formattedSize === void 0 ? {} : { size: formattedSize }
7419
+ ...formattedSize === void 0 ? {} : { size: formattedSize },
7420
+ ...options.watermark === void 0 ? {} : { watermark: options.watermark }
7289
7421
  }
7290
7422
  },
7291
7423
  operation: "editing"
@@ -7991,6 +8123,24 @@ async function generateOpenAICompatibleImage(input) {
7991
8123
  }), input.provider, input);
7992
8124
  }
7993
8125
  async function editOpenAICompatibleImage(input) {
8126
+ if (input.editFormat === "qwenJson") return parseImageResponse(await fetch(imageEndpoint$1(input.baseURL, "generations"), {
8127
+ method: "POST",
8128
+ redirect: "error",
8129
+ signal: input.signal,
8130
+ headers: {
8131
+ authorization: `Bearer ${input.apiKey}`,
8132
+ "content-type": "application/json"
8133
+ },
8134
+ body: JSON.stringify({
8135
+ model: input.model,
8136
+ prompt: input.prompt,
8137
+ image: input.sourceImages.map(toDataUrl$2),
8138
+ ...input.size === void 0 ? {} : { size: input.size },
8139
+ ...input.quality === void 0 ? {} : { quality: input.quality },
8140
+ ...input.editExtra ?? {},
8141
+ ...input.extraBody ?? {}
8142
+ })
8143
+ }), "openai-compat", input);
7994
8144
  if (input.editFormat === "xaiJson") {
7995
8145
  const references = input.sourceImages.map((image) => ({
7996
8146
  type: "image_url",
@@ -8019,7 +8169,7 @@ async function editOpenAICompatibleImage(input) {
8019
8169
  images: input.sourceImages.map((sourceImage) => ({ image_url: toDataUrl$2(sourceImage) })),
8020
8170
  prompt: input.prompt,
8021
8171
  n: 1,
8022
- size: "auto",
8172
+ size: input.editSizeMode === "selected" ? input.size ?? "auto" : "auto",
8023
8173
  response_format: "url",
8024
8174
  ...input.quality === void 0 ? {} : { quality: input.quality },
8025
8175
  ...input.editExtra ?? {},
@@ -8747,19 +8897,22 @@ const ANTIGRAVITY_CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.ap
8747
8897
  const ANTIGRAVITY_CLIENT_SECRET = "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";
8748
8898
  const ANTIGRAVITY_REDIRECT_URI = "http://localhost:51121/oauth-callback";
8749
8899
  /**
8750
- * Endpoint fallback order for generation, mirroring the reference (daily
8751
- * sandbox first, then autopush, then prod).
8900
+ * Preserve the working sandbox routes, then try ordinary daily (consumer
8901
+ * accounts) before the production compatibility fallback. A Gmail address
8902
+ * alone does not establish which backend an account can use.
8752
8903
  */
8753
8904
  const ANTIGRAVITY_ENDPOINTS = [
8754
8905
  "https://daily-cloudcode-pa.sandbox.googleapis.com",
8755
8906
  "https://autopush-cloudcode-pa.sandbox.googleapis.com",
8907
+ "https://daily-cloudcode-pa.googleapis.com",
8756
8908
  "https://cloudcode-pa.googleapis.com"
8757
8909
  ];
8758
8910
  /** loadCodeAssist is best supported on prod; discovery tries prod first. */
8759
8911
  const LOAD_ENDPOINTS = [
8760
8912
  "https://cloudcode-pa.googleapis.com",
8761
8913
  "https://daily-cloudcode-pa.sandbox.googleapis.com",
8762
- "https://autopush-cloudcode-pa.sandbox.googleapis.com"
8914
+ "https://autopush-cloudcode-pa.sandbox.googleapis.com",
8915
+ "https://daily-cloudcode-pa.googleapis.com"
8763
8916
  ];
8764
8917
  /** The image model served through this channel: Nano Banana 2. */
8765
8918
  const ANTIGRAVITY_IMAGE_MODEL = DEFAULT_SUBSCRIPTION_MODELS["google-sub"];
@@ -8801,7 +8954,7 @@ async function fetchVersionText(url, maxChars) {
8801
8954
  return;
8802
8955
  }
8803
8956
  }
8804
- /** Hardcoded fallback project when Antigravity returns none (workspace accounts). */
8957
+ /** Legacy compatibility project: not an account project or proof of entitlement. */
8805
8958
  const DEFAULT_PROJECT_ID = "rising-fact-p41fc";
8806
8959
  /** Generation timeout mirroring the reference implementation. */
8807
8960
  const IMAGE_TIMEOUT_MS = 12e4;
@@ -8867,16 +9020,10 @@ function antigravityAuthorizeUrl(cfg, pkce) {
8867
9020
  * plain SDK identity here, mirroring its project.js loadHeaders.
8868
9021
  */
8869
9022
  function loadHeaders(projectId) {
8870
- const platform = process.platform === "win32" ? "WINDOWS" : process.platform === "darwin" ? "MACOS" : "LINUX";
8871
9023
  return {
8872
9024
  "User-Agent": "google-api-nodejs-client/9.15.1",
8873
9025
  "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
8874
- "Client-Metadata": JSON.stringify({
8875
- ideType: "ANTIGRAVITY",
8876
- platform,
8877
- pluginType: "GEMINI",
8878
- ...projectId.length > 0 ? { duetProject: projectId } : {}
8879
- })
9026
+ "Client-Metadata": JSON.stringify(clientMetadata(projectId))
8880
9027
  };
8881
9028
  }
8882
9029
  /**
@@ -8886,17 +9033,10 @@ function loadHeaders(projectId) {
8886
9033
  * SDK UA here is what produced 403 #3501 on personal accounts.
8887
9034
  */
8888
9035
  function contentHeaders(projectId) {
8889
- const uaPlatform = process.platform === "darwin" ? "Macintosh; Intel Mac OS X 10_15_7" : "Windows NT 10.0; Win64; x64";
8890
- const platform = process.platform === "win32" ? "WINDOWS" : process.platform === "darwin" ? "MACOS" : "LINUX";
8891
9036
  return {
8892
- "User-Agent": `Mozilla/5.0 (${uaPlatform}) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${getAntigravityVersion()} Chrome/138.0.7204.235 Electron/37.3.1 Safari/537.36`,
9037
+ "User-Agent": `Mozilla/5.0 (${process.platform === "darwin" ? "Macintosh; Intel Mac OS X 10_15_7" : "Windows NT 10.0; Win64; x64"}) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${getAntigravityVersion()} Chrome/138.0.7204.235 Electron/37.3.1 Safari/537.36`,
8893
9038
  "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
8894
- "Client-Metadata": JSON.stringify({
8895
- ideType: "ANTIGRAVITY",
8896
- platform,
8897
- pluginType: "GEMINI",
8898
- ...projectId.length > 0 ? { duetProject: projectId } : {}
8899
- })
9039
+ "Client-Metadata": JSON.stringify(clientMetadata(projectId))
8900
9040
  };
8901
9041
  }
8902
9042
  function tokenBlobFromOAuth(json) {
@@ -8951,41 +9091,113 @@ async function antigravityRefresh(blob) {
8951
9091
  };
8952
9092
  }
8953
9093
  /**
8954
- * Resolve the managed project id for the logged-in account. Most accounts
8955
- * have one; when loadCodeAssist reports none, the hardcoded fallback keeps
8956
- * generation working (mirrors the reference's ensureProjectContext).
8957
- * Returns '' only when every endpoint fails, letting generate() throw then.
9094
+ * Discover an actual account project, preserving HTTP and eligibility failures.
9095
+ * Keep the legacy fallback for accounts whose image route still accepts it;
9096
+ * UNSUPPORTED_CLIENT here describes Code Assist, not a universal image ban.
9097
+ * Do not invoke onboarding or accept account terms during image generation.
8958
9098
  */
8959
- async function antigravityResolveProject(blob) {
8960
- const metadata = {
9099
+ async function antigravityResolveProjectContext(blob, signal) {
9100
+ signal?.throwIfAborted();
9101
+ const metadata = clientMetadata("");
9102
+ const diagnostics = [];
9103
+ for (const base of LOAD_ENDPOINTS) {
9104
+ const label = `loadCodeAssist ${new URL(base).hostname}`;
9105
+ try {
9106
+ const response = await fetch(`${base}/v1internal:loadCodeAssist`, {
9107
+ method: "POST",
9108
+ headers: {
9109
+ "Content-Type": "application/json",
9110
+ Authorization: `Bearer ${blob.accessToken}`,
9111
+ ...loadHeaders("")
9112
+ },
9113
+ body: JSON.stringify({ metadata }),
9114
+ signal: signal === void 0 ? AbortSignal.timeout(25e3) : AbortSignal.any([signal, AbortSignal.timeout(25e3)])
9115
+ });
9116
+ if (!response.ok) {
9117
+ diagnostics.push(`${label}: ${httpDiagnostic(response.status, await response.text().catch(() => ""), blob)}`);
9118
+ continue;
9119
+ }
9120
+ const payload = recordOf(await response.json().catch(() => null));
9121
+ if (payload === void 0) {
9122
+ diagnostics.push(`${label}: HTTP ${String(response.status)}, invalid response`);
9123
+ continue;
9124
+ }
9125
+ const project = payload.cloudaicompanionProject;
9126
+ const projectRecord = recordOf(project);
9127
+ const id = typeof project === "string" ? project : typeof projectRecord?.id === "string" ? projectRecord.id : "";
9128
+ if (id.trim().length > 0) return {
9129
+ projectId: id.trim(),
9130
+ source: "account",
9131
+ diagnostics
9132
+ };
9133
+ diagnostics.push(`${label}: HTTP ${String(response.status)}, ${missingProjectDiagnostic(payload, blob)}`);
9134
+ } catch (error) {
9135
+ if (signal?.aborted === true) throw error;
9136
+ diagnostics.push(`${label}: ${diagnosticText(error instanceof Error ? error.message : "request failed", blob)}`);
9137
+ }
9138
+ }
9139
+ return {
9140
+ projectId: DEFAULT_PROJECT_ID,
9141
+ source: "fallback",
9142
+ diagnostics
9143
+ };
9144
+ }
9145
+ /** Google ClientMetadata.Platform enum, shared by request body and headers. */
9146
+ function platformOf() {
9147
+ if (process.platform === "win32" && process.arch === "x64") return "WINDOWS_AMD64";
9148
+ if (process.platform === "darwin" && process.arch === "x64") return "DARWIN_AMD64";
9149
+ if (process.platform === "darwin" && process.arch === "arm64") return "DARWIN_ARM64";
9150
+ if (process.platform === "linux" && process.arch === "x64") return "LINUX_AMD64";
9151
+ if (process.platform === "linux" && process.arch === "arm64") return "LINUX_ARM64";
9152
+ return "PLATFORM_UNSPECIFIED";
9153
+ }
9154
+ function clientMetadata(projectId) {
9155
+ return {
8961
9156
  ideType: "ANTIGRAVITY",
8962
9157
  platform: platformOf(),
8963
- pluginType: "GEMINI"
9158
+ pluginType: "GEMINI",
9159
+ ...projectId.length > 0 ? { duetProject: projectId } : {}
8964
9160
  };
8965
- for (const base of LOAD_ENDPOINTS) try {
8966
- const response = await fetch(`${base}/v1internal:loadCodeAssist`, {
8967
- method: "POST",
8968
- headers: {
8969
- "Content-Type": "application/json",
8970
- Authorization: `Bearer ${blob.accessToken}`,
8971
- ...loadHeaders("")
8972
- },
8973
- body: JSON.stringify({ metadata }),
8974
- signal: AbortSignal.timeout(25e3)
8975
- });
8976
- if (!response.ok) continue;
8977
- const payload = await response.json().catch(() => null);
8978
- if (payload === null) continue;
8979
- const project = payload.cloudaicompanionProject;
8980
- const id = typeof project === "string" ? project : typeof project === "object" && project !== null && typeof project.id === "string" ? project.id : "";
8981
- if (id.length > 0) return id;
8982
- } catch {}
8983
- return DEFAULT_PROJECT_ID;
8984
9161
  }
8985
- function platformOf() {
8986
- if (process.platform === "win32") return "WINDOWS";
8987
- if (process.platform === "darwin") return "MACOS";
8988
- return "LINUX";
9162
+ function recordOf(value) {
9163
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
9164
+ }
9165
+ /** Upstream errors may echo request identity; redact before bounding the text. */
9166
+ function diagnosticText(value, blob) {
9167
+ let text = typeof value === "string" ? value : "";
9168
+ for (const secret of [
9169
+ blob.accessToken,
9170
+ blob.refreshToken,
9171
+ blob.accountId,
9172
+ blob.email
9173
+ ]) if (secret.length > 0) text = text.replaceAll(secret, "[redacted]");
9174
+ return text.replace(/Bearer\s+\S+/gi, "Bearer [redacted]").replace(/\s+/g, " ").trim().slice(0, 200);
9175
+ }
9176
+ function httpDiagnostic(status, text, blob) {
9177
+ let detail = text;
9178
+ try {
9179
+ const error = recordOf(recordOf(JSON.parse(text))?.error);
9180
+ if (typeof error?.message === "string") detail = `${typeof error.status === "string" ? `${error.status}: ` : ""}${error.message}`;
9181
+ } catch {}
9182
+ const safe = diagnosticText(detail, blob);
9183
+ return `HTTP ${String(status)}${safe.length > 0 ? `: ${safe}` : ""}`;
9184
+ }
9185
+ function missingProjectDiagnostic(payload, blob) {
9186
+ const reasons = Array.isArray(payload.ineligibleTiers) ? payload.ineligibleTiers.flatMap((value) => {
9187
+ const tier = recordOf(value);
9188
+ return typeof tier?.reasonCode === "string" ? [`${tier.reasonCode}${typeof tier.reasonMessage === "string" ? `: ${tier.reasonMessage}` : ""}`] : [];
9189
+ }) : [];
9190
+ const allowed = Array.isArray(payload.allowedTiers) ? payload.allowedTiers.flatMap((value) => {
9191
+ const tier = recordOf(value);
9192
+ return typeof tier?.id === "string" ? [tier.id] : [];
9193
+ }) : [];
9194
+ const current = recordOf(payload.paidTier)?.id ?? recordOf(payload.currentTier)?.id;
9195
+ const detail = [
9196
+ ...reasons,
9197
+ ...typeof current === "string" ? [`tier=${current}`] : [],
9198
+ ...allowed.length > 0 ? [`allowedTiers=${allowed.join(",")}`] : []
9199
+ ];
9200
+ return `未返回账号项目${detail.length > 0 ? `; ${diagnosticText(detail.join("; "), blob)}` : ""}`;
8989
9201
  }
8990
9202
  /**
8991
9203
  * Build the streamGenerateContent request body for one image generation.
@@ -9037,6 +9249,7 @@ function antigravityEnvelope(projectId, request) {
9037
9249
  * parse the SSE stream for the inlineData image part.
9038
9250
  */
9039
9251
  async function antigravityGenerateImage(options) {
9252
+ options.signal?.throwIfAborted();
9040
9253
  await initAntigravityVersion();
9041
9254
  const inner = antigravityImageBody({
9042
9255
  prompt: options.prompt,
@@ -9045,7 +9258,7 @@ async function antigravityGenerateImage(options) {
9045
9258
  ...options.referenceImages !== void 0 ? { referenceImages: options.referenceImages } : {}
9046
9259
  });
9047
9260
  const body = antigravityEnvelope(options.projectId, inner);
9048
- let lastError = "no endpoint succeeded";
9261
+ const failures = [];
9049
9262
  for (const base of ANTIGRAVITY_ENDPOINTS) {
9050
9263
  const url = `${base}/v1internal:streamGenerateContent?alt=sse`;
9051
9264
  const timeoutSignal = AbortSignal.timeout(IMAGE_TIMEOUT_MS);
@@ -9064,23 +9277,23 @@ async function antigravityGenerateImage(options) {
9064
9277
  });
9065
9278
  if (!response.ok) {
9066
9279
  const text = await response.text().catch(() => "");
9067
- lastError = `HTTP ${String(response.status)}: ${text.slice(0, 200)}`;
9068
- if (response.status === 403 || response.status === 404 || response.status === 429 || response.status >= 500) continue;
9069
- throw new Error(`antigravity ${lastError}`);
9280
+ failures.push(`${new URL(base).hostname}: ${httpDiagnostic(response.status, text, options.blob)}`);
9281
+ continue;
9070
9282
  }
9071
9283
  const text = await response.text();
9072
9284
  const parsed = parseSseImage(text);
9073
9285
  if (parsed !== void 0) return parsed;
9074
9286
  const reason = parseSseError(text);
9075
- lastError = reason !== void 0 ? reason : "response contained no image";
9287
+ failures.push(`${new URL(base).hostname}: ${diagnosticText(reason ?? "response contained no image", options.blob)}`);
9076
9288
  continue;
9077
9289
  } catch (error) {
9078
9290
  if (options.signal?.aborted === true) throw error;
9079
- lastError = error instanceof Error ? error.message : String(error);
9291
+ failures.push(`${new URL(base).hostname}: ${diagnosticText(error instanceof Error ? error.message : "request failed", options.blob)}`);
9080
9292
  continue;
9081
9293
  }
9082
9294
  }
9083
- throw new Error(`antigravity image generation failed: ${lastError}`);
9295
+ const discovery = options.projectContext?.source === "fallback" ? ["项目发现未返回账号项目,已尝试兼容项目。", ...options.projectContext.diagnostics] : [];
9296
+ throw new Error(`antigravity image generation failed: ${[...discovery, ...failures].join(" | ")}`);
9084
9297
  }
9085
9298
  /** Scan an SSE body for the first image part in any data: line. */
9086
9299
  function parseSseImage(text) {
@@ -9308,11 +9521,12 @@ var SubscriptionManager = class {
9308
9521
  const references = options.referenceImages ?? [];
9309
9522
  if (references.length > 5) throw new Error(`订阅生图最多支持 ${String(5)} 张参考图,当前 ${String(references.length)} 张`);
9310
9523
  if (vendor === "antigravity") {
9311
- const projectId = await this.ensureAntigravityProject(session);
9524
+ const projectContext = await this.ensureAntigravityProject(session, options.signal);
9312
9525
  const aspectRatio = antigravityAspectRatioOf(options.size);
9313
9526
  return [{ b64_json: (await antigravityGenerateImage({
9314
9527
  blob: session,
9315
- projectId,
9528
+ projectId: projectContext.projectId,
9529
+ projectContext,
9316
9530
  prompt: text,
9317
9531
  ...aspectRatio !== void 0 ? { aspectRatio } : {},
9318
9532
  hd: options.quality === "hd" || options.quality === "high",
@@ -9374,13 +9588,13 @@ var SubscriptionManager = class {
9374
9588
  * Antigravity generation envelope needs. Re-resolved when the account
9375
9589
  * signs out or a different account logs in.
9376
9590
  */
9377
- async ensureAntigravityProject(blob) {
9591
+ async ensureAntigravityProject(blob, signal) {
9378
9592
  const cacheKey = blob.refreshToken.length > 0 ? blob.refreshToken : blob.accessToken.slice(0, 32);
9379
9593
  const cached = this.projectCache.get(cacheKey);
9380
9594
  if (cached !== void 0) return cached;
9381
- const projectId = await antigravityResolveProject(blob);
9382
- this.projectCache.set(cacheKey, projectId);
9383
- return projectId;
9595
+ const context = await antigravityResolveProjectContext(blob, signal);
9596
+ if (context.source === "account") this.projectCache.set(cacheKey, context);
9597
+ return context;
9384
9598
  }
9385
9599
  };
9386
9600
  /** The private Codex backend can ignore size while following a canvas ratio in
@@ -27185,6 +27399,103 @@ async function clearDiskCache() {
27185
27399
  } catch {}
27186
27400
  }
27187
27401
  //#endregion
27402
+ //#region lib/types/openai-output.js
27403
+ const PROVIDER_DEFAULT_QUALITY = "__default__";
27404
+ const DEFAULT_COMPAT_QUALITIES = [
27405
+ "auto",
27406
+ "low",
27407
+ "medium",
27408
+ "high"
27409
+ ];
27410
+ const LEGACY_SIZES = [
27411
+ "1024x1024",
27412
+ "1536x1024",
27413
+ "1024x1536"
27414
+ ];
27415
+ const OPENAI_SIZES = {
27416
+ "1:1": {
27417
+ "1K": "1024x1024",
27418
+ "2K": "2048x2048"
27419
+ },
27420
+ "3:2": {
27421
+ "1K": "1536x1024",
27422
+ "2K": "2304x1536"
27423
+ },
27424
+ "2:3": {
27425
+ "1K": "1024x1536",
27426
+ "2K": "1536x2304"
27427
+ },
27428
+ "4:3": {
27429
+ "1K": "1152x864",
27430
+ "2K": "2048x1536"
27431
+ },
27432
+ "3:4": {
27433
+ "1K": "864x1152",
27434
+ "2K": "1536x2048"
27435
+ },
27436
+ "16:9": {
27437
+ "1K": "1536x864",
27438
+ "2K": "2048x1152",
27439
+ "4K": "3840x2160"
27440
+ },
27441
+ "9:16": {
27442
+ "1K": "864x1536",
27443
+ "2K": "1152x2048",
27444
+ "4K": "2160x3840"
27445
+ }
27446
+ };
27447
+ function flexibleSizeModel(model) {
27448
+ return /^gpt-image-2(?:$|[-.])/.test(model);
27449
+ }
27450
+ function officialSizeTable(config, model) {
27451
+ if (config.openaiSizes && Object.keys(config.openaiSizes).length > 0) return config.openaiSizes;
27452
+ if (flexibleSizeModel(model)) return OPENAI_SIZES;
27453
+ return {
27454
+ "1:1": { "1K": LEGACY_SIZES[0] },
27455
+ "3:2": { "1K": LEGACY_SIZES[1] },
27456
+ "2:3": { "1K": LEGACY_SIZES[2] }
27457
+ };
27458
+ }
27459
+ /** Check the official model contract before spending a request. Relays own their size contract. */
27460
+ function validateOfficialSize(model, size) {
27461
+ if (size === "auto") return;
27462
+ if (!flexibleSizeModel(model)) {
27463
+ if (!LEGACY_SIZES.includes(size)) throw new Error(`模型 ${model} 不支持尺寸 ${size};请使用 1024x1024、1536x1024 或 1024x1536`);
27464
+ return;
27465
+ }
27466
+ const match = /^(\d+)x(\d+)$/.exec(size);
27467
+ const width = Number(match?.[1]);
27468
+ const height = Number(match?.[2]);
27469
+ const pixels = width * height;
27470
+ if (!match || width % 16 !== 0 || height % 16 !== 0 || Math.max(width, height) > 3840 || pixels < 655360 || pixels > 8294400 || Math.max(width, height) > 3 * Math.min(width, height)) throw new Error(`OpenAI 尺寸 ${size} 无效:边长须为 16 的倍数且不超过 3840,比例在 1:3 到 3:1,像素数在 655360 到 8294400`);
27471
+ }
27472
+ function officialQualityOptions(model) {
27473
+ return [
27474
+ "auto",
27475
+ "low",
27476
+ "medium",
27477
+ "high",
27478
+ .../^gpt-image-2\.5-(sunburst|flare)(?:$|-)/.test(model) ? ["xhigh", "max"] : []
27479
+ ].map((value) => ({
27480
+ value,
27481
+ label: value === "auto" ? "自动" : value
27482
+ }));
27483
+ }
27484
+ function compatQualityOptions(config) {
27485
+ const values = [...new Set([...config.openaiCompatQualityOptions ?? DEFAULT_COMPAT_QUALITIES, config.openaiCompatQuality ?? ""].map((value) => value.trim()).filter((value) => value && value !== "__default__"))];
27486
+ return [{
27487
+ value: PROVIDER_DEFAULT_QUALITY,
27488
+ label: "渠道默认(不发送)"
27489
+ }, ...values.map((value) => ({
27490
+ value,
27491
+ label: value
27492
+ }))];
27493
+ }
27494
+ function compatRequestQuality(config, selected) {
27495
+ const value = (selected ?? config.openaiCompatQuality)?.trim();
27496
+ return value && value !== "__default__" ? value : void 0;
27497
+ }
27498
+ //#endregion
27188
27499
  //#region lib/types/studio.js
27189
27500
  const LEGACY_OPENAI_TABLE = {
27190
27501
  "1:1": { "1K": "1024x1024" },
@@ -27331,7 +27642,8 @@ function subscriptionStudioProfile(provider, signedIn) {
27331
27642
  ratioOptions: cap.ratioOptions,
27332
27643
  qualityOptions: cap.qualityOptions,
27333
27644
  defaultRatio: cap.defaultRatio,
27334
- defaultQuality: cap.defaultQuality
27645
+ defaultQuality: cap.defaultQuality,
27646
+ ...watermarkProfile({}, provider, DEFAULT_SUBSCRIPTION_MODELS[provider])
27335
27647
  };
27336
27648
  }
27337
27649
  /** Short display names for the workbench subscription rows. */
@@ -27350,6 +27662,7 @@ async function generateFromStudio(ctx, config, input, signal, fallbackWorkspaceR
27350
27662
  assertAllowed(studioProfile(config, input.provider, true), input);
27351
27663
  const active = resolveProvider(withProviderOverrides(config, input.provider, input.model));
27352
27664
  if (active.provider === "comfyui") throw new Error("ComfyUI 暂未接入工作台");
27665
+ if (isSubscriptionProvider(active.provider)) throw new Error("订阅生图应通过订阅渠道执行");
27353
27666
  const wired = active;
27354
27667
  const credential = await requireApiKey(ctx, input.provider);
27355
27668
  const rawRefs = input.references ?? (input.reference ? [input.reference] : []);
@@ -27386,12 +27699,16 @@ async function generateFromStudio(ctx, config, input, signal, fallbackWorkspaceR
27386
27699
  output = `${aspectRatio}, ${imageSize}`;
27387
27700
  } else if (wired.provider === "openai" || wired.provider === "openai-compat" || wired.provider === "xai" || wired.provider === "zhipu") {
27388
27701
  const p = wired.provider;
27389
- const size = p === "openai-compat" ? openAIRequestSize(config, input.ratio, input.quality) : p === "xai" ? void 0 : CLOUD_CAPABILITIES[p].sizeFor?.(input.ratio, input.quality);
27390
- const quality = p === "openai" ? input.quality === "auto" ? void 0 : input.quality : p === "zhipu" ? "hd" : void 0;
27702
+ const officialTable = p === "openai" ? officialSizeTable(config, wired.model) : void 0;
27703
+ const officialResolution = input.resolution ?? (officialTable ? openAICompatTable({ openaiCompatSizes: officialTable }).find((group) => group.ratio === input.ratio)?.tiers[0]?.tier : void 0) ?? "1K";
27704
+ const size = p === "openai-compat" ? openAIRequestSize(config, input.ratio, input.resolution ?? input.quality) : p === "openai" ? openAIRequestSize({ openaiCompatSizes: officialTable }, input.ratio, officialResolution) : p === "xai" ? void 0 : CLOUD_CAPABILITIES[p].sizeFor?.(input.ratio, input.quality);
27705
+ if (p === "openai" && size !== void 0) validateOfficialSize(wired.model, size);
27706
+ const requestedQuality = input.generationQuality ?? input.quality;
27707
+ const quality = p === "openai" ? requestedQuality === "auto" ? void 0 : requestedQuality : p === "openai-compat" ? compatRequestQuality(config, input.generationQuality) : p === "zhipu" ? "hd" : void 0;
27391
27708
  const extraBody = p === "xai" ? {
27392
27709
  aspect_ratio: input.ratio,
27393
27710
  resolution: input.quality
27394
- } : void 0;
27711
+ } : p === "openai-compat" ? input.mode === "generate" ? compatGenerationExtraBody(config, input.watermark) : compatEditExtraBody(config, input.watermark) : void 0;
27395
27712
  generated = input.mode === "edit" ? await editOpenAICompatibleImage({
27396
27713
  apiKey: credential,
27397
27714
  baseURL: wired.baseURL,
@@ -27405,7 +27722,8 @@ async function generateFromStudio(ctx, config, input, signal, fallbackWorkspaceR
27405
27722
  ...extraBody === void 0 ? {} : { extraBody },
27406
27723
  ...p === "openai-compat" ? {
27407
27724
  editFormat: wired.editFormat,
27408
- editExtra: wired.editExtra
27725
+ editExtra: wired.editExtra,
27726
+ editSizeMode: config.openaiCompatEditSizeMode ?? "auto"
27409
27727
  } : p === "xai" ? { editFormat: "xaiJson" } : {}
27410
27728
  }) : await generateOpenAICompatibleImage({
27411
27729
  provider: p,
@@ -27422,6 +27740,10 @@ async function generateFromStudio(ctx, config, input, signal, fallbackWorkspaceR
27422
27740
  output = size ?? `${input.ratio}, ${input.quality}`;
27423
27741
  } else if (wired.provider === "seedream") {
27424
27742
  const size = CLOUD_CAPABILITIES.seedream.sizeFor?.(input.ratio, input.quality) ?? input.quality;
27743
+ const arkOptions = {
27744
+ ...wired.arkOptions,
27745
+ watermark: selectedWatermark(input.watermark, wired.arkOptions.watermark)
27746
+ };
27425
27747
  generated = input.mode === "edit" ? await editSeedreamImage({
27426
27748
  apiKey: credential,
27427
27749
  baseURL: wired.baseURL,
@@ -27431,7 +27753,7 @@ async function generateFromStudio(ctx, config, input, signal, fallbackWorkspaceR
27431
27753
  size,
27432
27754
  maxBytes: ctx.attachments.imageLimits.maxImageBytes,
27433
27755
  signal,
27434
- arkOptions: wired.arkOptions
27756
+ arkOptions
27435
27757
  }) : await generateOpenAICompatibleImage({
27436
27758
  provider: "seedream",
27437
27759
  apiKey: credential,
@@ -27441,12 +27763,13 @@ async function generateFromStudio(ctx, config, input, signal, fallbackWorkspaceR
27441
27763
  size,
27442
27764
  maxBytes: ctx.attachments.imageLimits.maxImageBytes,
27443
27765
  signal,
27444
- arkOptions: wired.arkOptions
27766
+ arkOptions
27445
27767
  });
27446
27768
  output = size;
27447
- } else {
27769
+ } else if (wired.provider === "dashscope") {
27448
27770
  if (input.mode === "edit" && sourceImages.length > 3) throw new Error("DashScope (通义万相) 图生图目前最多支持 3 张参考图,请精简后重试");
27449
27771
  const size = CLOUD_CAPABILITIES.dashscope.sizeFor?.(input.ratio, input.quality) ?? "1024x1024";
27772
+ const watermark = selectedWatermark(input.watermark);
27450
27773
  generated = input.mode === "edit" ? await editDashScopeImage({
27451
27774
  apiKey: credential,
27452
27775
  endpoint: wired.endpoint,
@@ -27455,7 +27778,8 @@ async function generateFromStudio(ctx, config, input, signal, fallbackWorkspaceR
27455
27778
  sourceImages,
27456
27779
  size,
27457
27780
  maxBytes: ctx.attachments.imageLimits.maxImageBytes,
27458
- signal
27781
+ signal,
27782
+ ...watermark === void 0 ? {} : { watermark }
27459
27783
  }) : await generateDashScopeImage({
27460
27784
  apiKey: credential,
27461
27785
  endpoint: wired.endpoint,
@@ -27463,10 +27787,11 @@ async function generateFromStudio(ctx, config, input, signal, fallbackWorkspaceR
27463
27787
  prompt: input.prompt,
27464
27788
  size,
27465
27789
  maxBytes: ctx.attachments.imageLimits.maxImageBytes,
27466
- signal
27790
+ signal,
27791
+ ...watermark === void 0 ? {} : { watermark }
27467
27792
  });
27468
27793
  output = size;
27469
- }
27794
+ } else throw new Error("当前渠道未接入 API 工作台");
27470
27795
  if (!ctx.attachments.imageLimits.mediaTypes.includes(generated.mediaType)) throw new Error(`当前 DSH 不支持保存 ${generated.mediaType} 图片`);
27471
27796
  return {
27472
27797
  attachment: await ctx.attachments.saveImage({
@@ -27637,18 +27962,19 @@ function subscriptionResponse(input, startedAt, requestedCount, failedCount, ite
27637
27962
  };
27638
27963
  }
27639
27964
  function studioProfile(config, provider, configured) {
27965
+ const result = cloudStudioProfile(config, provider, configured);
27966
+ return {
27967
+ ...result,
27968
+ ...watermarkProfile(config, provider, result.model)
27969
+ };
27970
+ }
27971
+ function cloudStudioProfile(config, provider, configured) {
27640
27972
  let active;
27641
27973
  try {
27642
27974
  active = resolveProvider(withProviderOverrides(config, provider));
27643
- } catch {
27644
- return profile(provider, "", configured, [
27645
- "1:1",
27646
- "3:2",
27647
- "2:3"
27648
- ].map(option), [{
27649
- value: "standard",
27650
- label: "标准(推荐)"
27651
- }], "1:1", "standard");
27975
+ } catch (cause) {
27976
+ if (provider !== "openai-compat") throw cause;
27977
+ return compatibleStudioProfile(config, "", false);
27652
27978
  }
27653
27979
  if (active.provider === "comfyui") throw new Error("Invalid cloud provider profile");
27654
27980
  const model = active.model;
@@ -27656,19 +27982,55 @@ function studioProfile(config, provider, configured) {
27656
27982
  const cap = CLOUD_CAPABILITIES.google;
27657
27983
  return profile(provider, model, configured, cap.ratioOptions, cap.qualityOptions, cap.defaultRatio, cap.defaultQuality);
27658
27984
  }
27659
- if (provider === "openai-compat") {
27660
- if (config.openaiCompatSizes === void 0 || Object.keys(config.openaiCompatSizes).length === 0) return profile(provider, model, configured, [
27985
+ if (provider === "openai-compat") return compatibleStudioProfile(config, model, configured);
27986
+ if (provider === "openai") {
27987
+ const table = officialSizeTable(config, model);
27988
+ const order = Object.keys(table);
27989
+ const groups = openAICompatTable({ openaiCompatSizes: table }).sort((a, b) => order.indexOf(a.ratio) - order.indexOf(b.ratio));
27990
+ const resolutionOptions = Object.fromEntries(groups.map((group) => [group.ratio, group.tiers.map((entry) => ({
27991
+ value: entry.tier,
27992
+ label: `${entry.tier} · ${entry.size}`
27993
+ }))]));
27994
+ const defaultRatio = groups.some((group) => group.ratio === "1:1") ? "1:1" : groups[0]?.ratio ?? "1:1";
27995
+ return {
27996
+ ...profile(provider, model, configured, groups.map((group) => option(group.ratio)), officialQualityOptions(model), defaultRatio, "auto"),
27997
+ resolutionOptions,
27998
+ defaultResolution: resolutionOptions[defaultRatio]?.[0]?.value ?? "1K"
27999
+ };
28000
+ }
28001
+ const cap = CLOUD_CAPABILITIES[provider];
28002
+ return profile(provider, model, configured, cap.ratioOptions, cap.qualityOptions, cap.defaultRatio, cap.defaultQuality);
28003
+ }
28004
+ /** Output capabilities remain visible before credentials, address or model are configured. */
28005
+ function compatibleStudioProfile(config, model, configured) {
28006
+ const groups = openAICompatTable(config);
28007
+ const qualityProfile = {
28008
+ generationQualityOptions: compatQualityOptions(config),
28009
+ defaultGenerationQuality: compatRequestQuality(config) ?? "__default__",
28010
+ resolutionOptions: Object.fromEntries(groups.map((group) => [group.ratio, group.tiers.map((entry) => ({
28011
+ value: entry.tier,
28012
+ label: `${entry.tier} · ${entry.size}`
28013
+ }))]))
28014
+ };
28015
+ if (config.openaiCompatSizes === void 0 || Object.keys(config.openaiCompatSizes).length === 0) return {
28016
+ ...profile("openai-compat", model, configured, [
27661
28017
  "1:1",
27662
28018
  "3:2",
27663
28019
  "2:3"
27664
28020
  ].map(option), [{
27665
28021
  value: "standard",
27666
28022
  label: "标准(推荐)"
27667
- }], "1:1", "standard");
27668
- return openAICompatStudioProfile(config, model, configured);
27669
- }
27670
- const cap = CLOUD_CAPABILITIES[provider];
27671
- return profile(provider, model, configured, cap.ratioOptions, cap.qualityOptions, cap.defaultRatio, cap.defaultQuality);
28023
+ }], "1:1", "standard"),
28024
+ ...qualityProfile,
28025
+ resolutionOptions: Object.fromEntries(groups.map((group) => [group.ratio, [{
28026
+ value: "standard",
28027
+ label: `标准 · ${group.tiers[0].size}`
28028
+ }]]))
28029
+ };
28030
+ return {
28031
+ ...openAICompatStudioProfile(config, model, configured),
28032
+ ...qualityProfile
28033
+ };
27672
28034
  }
27673
28035
  function profile(provider, model, configured, ratioOptions, qualityOptions, defaultRatio, defaultQuality) {
27674
28036
  return {
@@ -27702,7 +28064,12 @@ function option(value) {
27702
28064
  function assertAllowed(profile, input) {
27703
28065
  if (input.model !== profile.model) throw new Error("模型配置已变化,请刷新工作台后重试");
27704
28066
  if (!profile.ratioOptions.some((option) => option.value === input.ratio)) throw new Error("该 Provider 不支持所选比例");
27705
- if (!profile.qualityOptions.some((option) => option.value === input.quality)) throw new Error("该 Provider 不支持所选清晰度");
28067
+ const selectedQuality = input.provider === "openai" ? input.generationQuality ?? input.quality : input.resolution ?? input.quality;
28068
+ if (!profile.qualityOptions.some((option) => option.value === selectedQuality)) throw new Error("该 Provider 不支持所选清晰度");
28069
+ if (input.resolution !== void 0 && profile.resolutionOptions !== void 0 && !profile.resolutionOptions[input.ratio]?.some((option) => option.value === input.resolution)) throw new Error("该比例不支持所选分辨率");
28070
+ if (input.generationQuality !== void 0 && input.provider === "openai-compat" && !profile.generationQualityOptions?.some((option) => option.value === input.generationQuality)) throw new Error("该 Provider 不支持所选生成质量");
28071
+ if ((input.resolution !== void 0 || input.generationQuality !== void 0) && input.provider !== "openai" && input.provider !== "openai-compat") throw new Error("该 Provider 不支持独立的 OpenAI 输出参数");
28072
+ if (input.watermark !== void 0 && input.watermark !== "default" && studioWatermarkCapability(profile, input.mode).status !== "supported") throw new Error("该渠道尚未确认当前操作的水印控制,请刷新工作台");
27706
28073
  if (input.mode === "edit" && !profile.supportsEditing) throw new Error("该 Provider 暂不支持图生图");
27707
28074
  }
27708
28075
  async function readStudioReference(ctx, reference, signal) {
@@ -27806,6 +28173,10 @@ function parseStudioGenerateRequest(value) {
27806
28173
  const model = requiredText(input.model, "请选择模型", 200);
27807
28174
  const ratio = requiredText(input.ratio, "请选择比例", 32);
27808
28175
  const quality = requiredText(input.quality, "请选择清晰度", 32);
28176
+ const resolution = input.resolution === void 0 ? void 0 : requiredText(input.resolution, "请选择分辨率", 32);
28177
+ const generationQuality = input.generationQuality === void 0 ? void 0 : requiredText(input.generationQuality, "请选择生成质量", 100);
28178
+ const watermark = input.watermark === void 0 ? void 0 : STUDIO_WATERMARK_VALUES.find((value) => value === input.watermark);
28179
+ if (input.watermark !== void 0 && watermark === void 0) throw new Error("请选择有效的水印选项");
27809
28180
  const references = (Array.isArray(input.references) ? input.references : input.reference !== void 0 ? [input.reference] : []).map(parseReference);
27810
28181
  if (input.mode === "edit" && references.length === 0) throw new Error("图生图需要至少一张参考图");
27811
28182
  if (references.length > 5) throw new Error("最多支持上传 5 张参考图");
@@ -27822,6 +28193,9 @@ function parseStudioGenerateRequest(value) {
27822
28193
  prompt,
27823
28194
  ratio,
27824
28195
  quality,
28196
+ ...resolution === void 0 ? {} : { resolution },
28197
+ ...generationQuality === void 0 ? {} : { generationQuality },
28198
+ ...watermark === void 0 ? {} : { watermark },
27825
28199
  ...count !== void 0 ? { count } : {},
27826
28200
  ...references.length > 0 ? {
27827
28201
  references,
@@ -28245,6 +28619,27 @@ function jsonError(res, status, code) {
28245
28619
  json(res, status, { error: code });
28246
28620
  }
28247
28621
  //#endregion
28622
+ //#region lib/types/settings-health.js
28623
+ function describeSettingsHealth(settings, schema) {
28624
+ const service = settings;
28625
+ const fields = Object.values(schema.dict ?? {});
28626
+ return {
28627
+ settings: typeof service?.installSection === "function" ? "legacy" : typeof service?.describe === "function" ? "live" : "unavailable",
28628
+ liveSchema: fields.length > 0 && fields.every((field) => field.meta.volatile === true)
28629
+ };
28630
+ }
28631
+ function serveSettingsHealth(req, res, health) {
28632
+ res.setHeader("cache-control", "no-store");
28633
+ if (req.method !== "GET") {
28634
+ res.statusCode = 405;
28635
+ res.setHeader("allow", "GET");
28636
+ res.end();
28637
+ return;
28638
+ }
28639
+ res.setHeader("content-type", "application/json; charset=utf-8");
28640
+ res.end(JSON.stringify(health));
28641
+ }
28642
+ //#endregion
28248
28643
  //#region lib/types/index.js
28249
28644
  const name = "dsh-image-gen";
28250
28645
  const inject = [
@@ -28270,12 +28665,17 @@ function apply(ctx, config = {}) {
28270
28665
  const canvasMirror = new CanvasMirror();
28271
28666
  const subscriptionManager = new SubscriptionManager(ctx);
28272
28667
  registerSubscriptionRoutes(ctx, subscriptionManager);
28273
- installImageSettings(ctx, current(), {
28668
+ const settingsHealth = installImageSettings(ctx, current(), {
28274
28669
  setSource: (source) => {
28275
28670
  current = () => migrateOpenAICompatConfig(plainConfig(source()));
28276
28671
  },
28277
28672
  onChange: () => {}
28278
28673
  });
28674
+ ctx.effect(() => ctx.webServer.register({
28675
+ kind: "exact",
28676
+ path: SETTINGS_HEALTH_ROUTE,
28677
+ handler: (req, res) => serveSettingsHealth(req, res, settingsHealth())
28678
+ }), "dsh-image-gen: settings health");
28279
28679
  ctx.effect(() => ctx.webServer.register({
28280
28680
  kind: "exact",
28281
28681
  path: IMAGE_ROUTE,
@@ -28473,6 +28873,9 @@ function apply(ctx, config = {}) {
28473
28873
  }
28474
28874
  const size = args.size ?? active.imageSize;
28475
28875
  const arkOptions = active.provider === "seedream" ? active.arkOptions : void 0;
28876
+ if (active.provider === "openai") validateOfficialSize(active.model, size);
28877
+ const quality = active.provider === "openai-compat" ? compatRequestQuality(current(), args.quality) : active.provider === "openai" ? args.quality : void 0;
28878
+ if (active.provider === "openai" && quality !== void 0 && !officialQualityOptions(active.model).some((option) => option.value === quality)) throw new Error("该 OpenAI 模型不支持所选生成质量");
28476
28879
  return saveGenerated(ctx, await generateOpenAICompatibleImage({
28477
28880
  provider: active.provider,
28478
28881
  apiKey: credential,
@@ -28482,8 +28885,10 @@ function apply(ctx, config = {}) {
28482
28885
  size,
28483
28886
  maxBytes: ctx.attachments.imageLimits.maxImageBytes,
28484
28887
  signal: exec.signal,
28888
+ ...quality === void 0 ? {} : { quality },
28889
+ ...active.provider === "openai-compat" ? { extraBody: current().openaiCompatExtraBody ?? {} } : {},
28485
28890
  ...arkOptions === void 0 ? {} : { arkOptions }
28486
- }), active.provider, active.model, size, current(), exec, knownWorkspaceRoots);
28891
+ }), active.provider, active.model, quality === void 0 ? size : `${size}, quality=${quality}`, current(), exec, knownWorkspaceRoots);
28487
28892
  };
28488
28893
  ctx.tools.register(defineTool({
28489
28894
  name: "generate_image",
@@ -28544,6 +28949,10 @@ function apply(ctx, config = {}) {
28544
28949
  type: "string",
28545
28950
  description: "Optional dimensions or size tier for OpenAI, Seedream, or DashScope; WIDTHxHEIGHT maps to aspect_ratio for xAI Grok."
28546
28951
  },
28952
+ quality: {
28953
+ type: "string",
28954
+ description: "Optional generation quality for OpenAI or compatible APIs, independent of pixel size (e.g. auto, low, medium, high). Omit to use the configured default."
28955
+ },
28547
28956
  workflow: {
28548
28957
  type: "string",
28549
28958
  description: "Optional name of the ComfyUI workflow to run; omit to use the active workflow from settings. Only meaningful when the ComfyUI provider is selected."
@@ -28615,6 +29024,10 @@ function apply(ctx, config = {}) {
28615
29024
  type: "string",
28616
29025
  description: "Optional dimensions or size tier for OpenAI, Seedream, or DashScope; WIDTHxHEIGHT maps to aspect_ratio for xAI Grok."
28617
29026
  },
29027
+ quality: {
29028
+ type: "string",
29029
+ description: "Optional OpenAI or compatible generation quality, applied to every item independently of size."
29030
+ },
28618
29031
  workflow: {
28619
29032
  type: "string",
28620
29033
  description: "Optional name of the ComfyUI workflow to run; omit to use the active workflow from settings."
@@ -28752,6 +29165,7 @@ function apply(ctx, config = {}) {
28752
29165
  ...args.aspect_ratio !== void 0 ? { aspect_ratio: args.aspect_ratio } : {},
28753
29166
  ...args.image_size !== void 0 ? { image_size: args.image_size } : {},
28754
29167
  ...args.size !== void 0 ? { size: args.size } : {},
29168
+ ...args.quality !== void 0 ? { quality: args.quality } : {},
28755
29169
  ...args.workflow !== void 0 ? { workflow: args.workflow } : {}
28756
29170
  }, exec);
28757
29171
  images.push({
@@ -28855,6 +29269,10 @@ function apply(ctx, config = {}) {
28855
29269
  type: "string",
28856
29270
  description: "Optional output size for OpenAI, Seedream, or DashScope; WIDTHxHEIGHT maps to aspect_ratio for xAI Grok."
28857
29271
  },
29272
+ quality: {
29273
+ type: "string",
29274
+ description: "Optional generation quality for OpenAI or compatible edits, independent of size."
29275
+ },
28858
29276
  workflow: {
28859
29277
  type: "string",
28860
29278
  description: "Optional name of the ComfyUI workflow to run; omit to use the active workflow from settings. Only meaningful when the ComfyUI provider is selected."
@@ -28934,6 +29352,9 @@ function apply(ctx, config = {}) {
28934
29352
  }
28935
29353
  const size = args.size ?? active.imageSize;
28936
29354
  if (active.provider === "openai" || active.provider === "openai-compat" || active.provider === "xai" || active.provider === "zhipu") {
29355
+ if (active.provider === "openai") validateOfficialSize(active.model, size);
29356
+ const quality = active.provider === "openai-compat" ? compatRequestQuality(current(), args.quality) : active.provider === "openai" ? args.quality : void 0;
29357
+ if (active.provider === "openai" && quality !== void 0 && !officialQualityOptions(active.model).some((option) => option.value === quality)) throw new Error("该 OpenAI 模型不支持所选生成质量");
28937
29358
  const xaiExtraBody = active.provider === "xai" ? xaiToolParameters({
28938
29359
  ...args.aspect_ratio !== void 0 ? { aspectRatio: args.aspect_ratio } : {},
28939
29360
  ...args.image_size !== void 0 ? { imageSize: args.image_size } : {},
@@ -28946,16 +29367,18 @@ function apply(ctx, config = {}) {
28946
29367
  prompt: args.prompt,
28947
29368
  sourceImages,
28948
29369
  ...active.provider === "xai" ? {} : { size },
29370
+ ...quality === void 0 ? {} : { quality },
28949
29371
  maxBytes: ctx.attachments.imageLimits.maxImageBytes,
28950
29372
  signal: exec.signal,
28951
29373
  ...active.provider === "openai-compat" ? {
28952
29374
  editFormat: active.editFormat,
28953
- editExtra: active.editExtra
29375
+ editExtra: active.editExtra,
29376
+ editSizeMode: current().openaiCompatEditSizeMode ?? "auto"
28954
29377
  } : active.provider === "xai" ? {
28955
29378
  editFormat: "xaiJson",
28956
29379
  ...xaiExtraBody === void 0 ? {} : { extraBody: xaiExtraBody }
28957
29380
  } : {}
28958
- }), active.provider, active.model, active.provider === "xai" ? xaiExtraBody?.aspect_ratio ?? "auto" : size, current(), exec, knownWorkspaceRoots);
29381
+ }), active.provider, active.model, active.provider === "xai" ? xaiExtraBody?.aspect_ratio ?? "auto" : quality === void 0 ? size : `${size}, quality=${quality}`, current(), exec, knownWorkspaceRoots);
28959
29382
  }
28960
29383
  if (active.provider === "seedream") return saveGenerated(ctx, await editSeedreamImage({
28961
29384
  apiKey: credential,
@@ -29240,14 +29663,22 @@ function imagePresentation(result) {
29240
29663
  * on the service, so the namespace registers through it; DSH 0.1.7 replaced it
29241
29664
  * with schema-derived forms served by the loader itself (keyed by entry id),
29242
29665
  * so its service carries no installer and a host without any settings service
29243
- * simply never runs the callback — both stay silent instead of warning.
29666
+ * simply never runs the callback. A modern host with an unmarked schema is
29667
+ * incompatible and must be diagnosed, while old hosts keep their installer.
29244
29668
  */
29245
29669
  function installImageSettings(ctx, config, hooks) {
29670
+ let service;
29246
29671
  ctx.inject(["settings"], (settingsCtx) => {
29247
29672
  const settings = settingsCtx.settings;
29248
- if (typeof settings.installSection !== "function") return;
29249
- settings.installSection(ctx, IMAGE_GENERATION_NAMESPACE, Config, config, hooks);
29673
+ service = settings;
29674
+ const health = describeSettingsHealth(settings, Config);
29675
+ if (health.settings === "live" && !health.liveSchema) ctx.logger.warn("dsh-image-gen: the loaded schema lacks volatile fields required by this DSH settings service. Install @deepseek-ai/schemastery >=3.18.4 <4 in the plugin profile and check which copy the plugin resolves; settings cannot be saved with this schema.");
29676
+ if (typeof settings.installSection === "function") settings.installSection(ctx, IMAGE_GENERATION_NAMESPACE, Config, config, hooks);
29677
+ return () => {
29678
+ service = void 0;
29679
+ };
29250
29680
  });
29681
+ return () => describeSettingsHealth(service, Config);
29251
29682
  }
29252
29683
  //#endregion
29253
29684
  export { CANVAS_STATE_ROUTE, Config, DELETE_ROUTE, IMAGE_ROUTE, IMPORT_ROUTE, INSPIRATION_ROUTE, SAVE_WORKSPACE_ROUTE, STUDIO_ROUTE, TEST_CONNECTION_ROUTE, apply, imageAttachmentFromMeta, inject, name };