@dickpy/dsh-imagegen 1.2.3 → 1.4.0

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 (45) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +203 -181
  3. package/cordis.patch.yml +8 -8
  4. package/docs/images/multi-model-comparison.png +0 -0
  5. package/lib/client.js +2711 -1318
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +830 -155
  8. package/package.json +70 -68
  9. package/src/agent-image-tools.ts +418 -316
  10. package/src/client/ImageGenPanel.tsx +1703 -1476
  11. package/src/client/SettingsCard.tsx +936 -648
  12. package/src/client/TemplateLibrary.tsx +336 -336
  13. package/src/client/api.ts +193 -193
  14. package/src/client/channels-form.ts +263 -0
  15. package/src/client/controller.ts +46 -46
  16. package/src/client/conversation-sync.ts +14 -0
  17. package/src/client/css-modules.d.ts +5 -5
  18. package/src/client/helpers.ts +33 -33
  19. package/src/client/image-toolview.module.css +73 -73
  20. package/src/client/image-toolview.tsx +170 -152
  21. package/src/client/index.ts +32 -22
  22. package/src/client/locales.ts +610 -484
  23. package/src/client/mount.tsx +185 -96
  24. package/src/client/panel.module.css +1713 -1445
  25. package/src/client/settings-card.module.css +1023 -536
  26. package/src/client/settings-form.ts +336 -336
  27. package/src/client/settings-scope.ts +298 -250
  28. package/src/client/sidebar-entry.ts +148 -102
  29. package/src/client/templates.module.css +453 -453
  30. package/src/engine.ts +520 -464
  31. package/src/gallery-store.ts +286 -280
  32. package/src/generation-runtime.ts +79 -48
  33. package/src/history-store.ts +250 -238
  34. package/src/image-format.ts +11 -0
  35. package/src/image-models.ts +19 -19
  36. package/src/index.ts +318 -212
  37. package/src/model-catalog.ts +115 -0
  38. package/src/presets.ts +71 -0
  39. package/src/prompt-enhancer.ts +137 -79
  40. package/src/protocol.ts +338 -253
  41. package/src/routes.ts +916 -738
  42. package/src/task-queue.ts +113 -103
  43. package/src/templates/cases.json +10196 -10196
  44. package/src/templates-store.ts +278 -278
  45. package/src/updater.ts +117 -117
@@ -1,19 +1,19 @@
1
- /**
2
- * Image-model configuration shared by the host, panel, and Agent tools.
3
- * `/models` exposes candidates only: the configured list is the explicit
4
- * allow-list because OpenAI-compatible gateways rarely advertise modalities.
5
- */
6
-
7
- export const DEFAULT_IMAGE_MODELS = ['gpt-image-2', 'grok-imagine-image', 'nanobanana2', 'nanobanana2-lite', 'nanobanana-pro', 'seedream-5.0-pro'] as const
8
-
9
- /** Normalize user-entered model identifiers and retain a usable legacy default. */
10
- export function normalizeImageModels(value: unknown): string[] {
11
- const candidates = Array.isArray(value) ? value : []
12
- const unique = new Set<string>()
13
- for (const candidate of candidates) {
14
- if (typeof candidate !== 'string') continue
15
- const model = candidate.trim()
16
- if (model !== '') unique.add(model)
17
- }
18
- return unique.size > 0 ? [...unique] : [...DEFAULT_IMAGE_MODELS]
19
- }
1
+ /**
2
+ * Image-model configuration shared by the host, panel, and Agent tools.
3
+ * `/models` exposes candidates only: the configured list is the explicit
4
+ * allow-list because OpenAI-compatible gateways rarely advertise modalities.
5
+ */
6
+
7
+ export const DEFAULT_IMAGE_MODELS = ['gpt-image-2', 'grok-imagine-image', 'nanobanana2', 'nanobanana2-lite', 'nanobanana-pro', 'seedream-5.0-pro', 'glm-image'] as const
8
+
9
+ /** Normalize user-entered model identifiers and retain a usable legacy default. */
10
+ export function normalizeImageModels(value: unknown): string[] {
11
+ const candidates = Array.isArray(value) ? value : []
12
+ const unique = new Set<string>()
13
+ for (const candidate of candidates) {
14
+ if (typeof candidate !== 'string') continue
15
+ const model = candidate.trim()
16
+ if (model !== '') unique.add(model)
17
+ }
18
+ return unique.size > 0 ? [...unique] : [...DEFAULT_IMAGE_MODELS]
19
+ }
package/src/index.ts CHANGED
@@ -1,212 +1,318 @@
1
- /**
2
- * dsh-imagegen — host half. Mounts the plugin's settings section (api_url /
3
- * api_key on the host settings seam), the /api/dsh-imagegen route family
4
- * (loopback-only settings bridge + image-generation proxy that keeps the API
5
- * key host-side), and a system-prompt announcement. The browser half
6
- * (./client) renders the sidebar entry and the split-pane generation studio.
7
- */
8
-
9
- import type { Context } from '@deepseek-ai/cordis'
10
- import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings'
11
- import z from 'schemastery'
12
- // Type-only: pulls the webServer Context merge (route registration).
13
- import type {} from '@deepseek-ai/dsh-host-webserver'
14
- // Type-only: pulls the systemPrompt Context merge (announcement section).
15
- import type {} from '@deepseek-ai/dsh-system-prompt'
16
- import type {} from '@deepseek-ai/dsh-tools'
17
- import type {} from '@deepseek-ai/dsh-attachment'
18
- import { IMAGEGEN_SETTINGS_NAMESPACE } from './protocol.ts'
19
- import { makeRoutes, type SettingsSeam } from './routes.ts'
20
- import { ImageGenerationRuntime } from './generation-runtime.ts'
21
- import { registerAgentImageTools } from './agent-image-tools.ts'
22
- import { DEFAULT_IMAGE_MODELS, normalizeImageModels } from './image-models.ts'
23
-
24
- /** Stable cordis plugin name. */
25
- export const name = 'imagegen'
26
-
27
- /** Services required before the surfaces can mount. */
28
- export const inject = ['webServer', 'systemPrompt']
29
-
30
- // Internals re-exported for smoke tests and host-side debugging; the plugin
31
- // contract only requires name / inject / Config / apply.
32
- export { makeRoutes } from './routes.ts'
33
- export { generateImage, ImageGenError } from './engine.ts'
34
- export { ImageGenerationRuntime } from './generation-runtime.ts'
35
- export { registerAgentImageTools } from './agent-image-tools.ts'
36
- export { appendGallery, clearGallery, listGallery, readGalleryImage, removeGallery, updateGalleryTags } from './gallery-store.ts'
37
- export { listTemplates, readTemplateImage, refreshTemplates, clearTemplateMemo } from './templates-store.ts'
38
- export { checkForUpdate, clearUpdateCache, compareVersions, CURRENT_VERSION, installUpdate, profileFromProcess } from './updater.ts'
39
-
40
- /** The branded settings namespace of this plugin (the card edits it). */
41
- export const ImageGenSettingsNamespace = settingsNamespace(IMAGEGEN_SETTINGS_NAMESPACE)
42
-
43
- /** Plugin config, validated by the same-named schemastery schema. */
44
- export interface Config {
45
- /** Master switch for the plugin (routes, prompt section). */
46
- enabled?: boolean
47
- /** Announce the plugin in every agent's system prompt. */
48
- announceToAgent?: boolean
49
- /** Allow Agents to submit and retrieve image-generation tasks. */
50
- allowAgentImageGeneration?: boolean
51
- /** Base URL of the OpenAI-compatible endpoint, e.g. https://api.openai.com/v1 */
52
- apiUrl?: string
53
- /** Bearer API key (stored as a secret field on the settings seam). */
54
- apiKey?: string
55
- /** Explicit allow-list of image models selected for this API endpoint. */
56
- imageModels?: string[]
57
- /** Optional OpenAI-compatible chat endpoint for prompt enhancement. */
58
- promptApiUrl?: string
59
- /** Optional secret for the prompt enhancement endpoint. */
60
- promptApiKey?: string
61
- /** Chat model used to expand short image prompts. */
62
- promptModel?: string
63
- }
64
-
65
- export const Config: z<Config> = z.object({
66
- enabled: z.boolean().default(true),
67
- announceToAgent: z.boolean().default(true),
68
- allowAgentImageGeneration: z.boolean().default(true),
69
- apiUrl: z.string().default(''),
70
- apiKey: z.string().role('secret').default(''),
71
- imageModels: z.array(z.string()).default([...DEFAULT_IMAGE_MODELS]),
72
- promptApiUrl: z.string().default(''),
73
- promptApiKey: z.string().role('secret').default(''),
74
- promptModel: z.string().default(''),
75
- })
76
-
77
- /** Schema defaults, re-read for hand-built contexts (the loader applies them normally). */
78
- const DEFAULT_ENABLED = true
79
- const DEFAULT_ANNOUNCE = true
80
- const DEFAULT_ALLOW_AGENT_IMAGE_GENERATION = true
81
-
82
- /** Order of the announcement section within the tool-guidance band. */
83
- const SECTION_ORDER = 150
84
-
85
- /** Model-facing announcement: plugin presence, capabilities, and limits. */
86
- export const IMAGEGEN_GUIDANCE = '本机已安装 dsh-imagegen 插件(DSH AI 生图):侧边栏「AI 生图」入口。能力:对接 OpenAI 兼容图像生成 API,模型由用户在「设置 → 插件 → AI 生图」中检测或手动配置的生图模型列表决定;支持文生图(/images/generations)与图生图(/images/edits,上传参考图,grok-imagine 模型按官方 JSON image_url 协议发送,nanobanana 系列按 aspect_ratio / image_size 参数协议发送;seedream 系列统一走 /images/generations,参考图以 JSON image 数组发送)。API 地址与密钥在 GUI 设置中配置,密钥仅存于本机设置文档;生成请求由本地宿主代理转发,结果以 base64 返回面板,可预览与下载。模型只能使用已配置的生图模型;模型出现在 /models 中不等于其网关原生支持生图协议,遇到 Qwen、Gemini 等非 OpenAI 生图协议时应如实说明上游兼容性。可一键把满意的图片加入「画廊」。内置「提示词模板库」(面板提示词框左下角「模板库」按钮):打包 awesome-gpt-image-2 的数百条提示词案例,可搜索、筛选与复用。Agent 可直接调用 `generate_image` 提交文生图,也可用 `edit_image` 图生图;默认保持工具调用等待直到任务完成,完成图片直接作为工具结果附件返回,不会额外伪造用户消息。若明确需要后台执行,可传 `wait_for_completion: false`,之后再用 `get_image_generation_task` 查询;不要反复轮询。限制:生成消耗上游 API 额度;图片内容由上游模型生成,可能不符合预期或包含不适宜内容;api_key 以明文存储在设置文档中;参考图会发送至所配置的 API 服务;模板库在线刷新与参考图首次加载需要访问 vibeui.top。用户提到「生图 / 绘画 / 生成图片 / 文生图 / 图生图 / 画廊 / 提示词模板」时即指本插件,请据此协作。'
87
-
88
- /** Add the live allow-list so an Agent can honor a user's model choice. */
89
- function guidanceFor(imageModels: string[]): string {
90
- return `${IMAGEGEN_GUIDANCE} 当前允许调用的生图模型:${imageModels.join('、')}。用户指定其中某个模型时,工具参数 model 必须使用该精确名称;未指定时使用列表中的第一个。`
91
- }
92
-
93
- /** Effective config (schema defaults applied). */
94
- interface EffectiveConfig {
95
- enabled: boolean
96
- announceToAgent: boolean
97
- allowAgentImageGeneration: boolean
98
- apiUrl: string
99
- apiKey: string
100
- imageModels: string[]
101
- promptApiUrl: string
102
- promptApiKey: string
103
- promptModel: string
104
- }
105
-
106
- /**
107
- * Mount the settings section, routes, and announcement.
108
- * @param ctx - host plugin context carrying webServer/systemPrompt.
109
- * @param config - resolved plugin config (schema defaults applied by the loader).
110
- */
111
- export function apply(ctx: Context, config?: Config): void {
112
- // The live source the surfaces read: the settings section once the settings
113
- // service is attached, the composition entry otherwise.
114
- let current: () => Config = () => config ?? {}
115
- const resolve = (): EffectiveConfig => {
116
- const value = current()
117
- return {
118
- enabled: value.enabled ?? DEFAULT_ENABLED,
119
- announceToAgent: value.announceToAgent ?? DEFAULT_ANNOUNCE,
120
- allowAgentImageGeneration: value.allowAgentImageGeneration ?? DEFAULT_ALLOW_AGENT_IMAGE_GENERATION,
121
- apiUrl: value.apiUrl ?? '',
122
- apiKey: value.apiKey ?? '',
123
- imageModels: normalizeImageModels(value.imageModels),
124
- promptApiUrl: value.promptApiUrl ?? '',
125
- promptApiKey: value.promptApiKey ?? '',
126
- promptModel: value.promptModel ?? '',
127
- }
128
- }
129
-
130
- // Browser endpoints and Agent tools share the exact same serial queue. This
131
- // keeps image persistence, cancellation, and retries coherent across both
132
- // entry points; Agent tools wait for their task result by default and render
133
- // images in the tool result instead of injecting a synthetic user message.
134
- const runtime = new ImageGenerationRuntime(() => {
135
- const value = resolve()
136
- return { apiUrl: value.apiUrl, apiKey: value.apiKey }
137
- })
138
-
139
- // The route family mounts once, gated on the settings seam (the bridge
140
- // serves it; without the seam there is nothing to expose). Route handlers
141
- // read resolve() per request, so config edits apply live. The settings
142
- // bridge deliberately keeps serving while the plugin is disabled — it is
143
- // how the user re-enables the plugin from the settings card.
144
- ctx.inject(['settings'], (sctx) => {
145
- const seam = sctx.get('settings') as unknown as SettingsSeam
146
- sctx.effect(
147
- () => {
148
- const routes = makeRoutes({
149
- settings: seam,
150
- resolve: () => {
151
- const value = resolve()
152
- return { apiUrl: value.apiUrl, apiKey: value.apiKey }
153
- },
154
- resolvePrompt: () => {
155
- const value = resolve()
156
- return {
157
- apiUrl: value.promptApiUrl.trim() || value.apiUrl,
158
- apiKey: value.promptApiKey.trim() || value.apiKey,
159
- model: value.promptModel,
160
- }
161
- },
162
- resolveImageModels: () => resolve().imageModels,
163
- runtime,
164
- })
165
- const disposers = routes.map(route => ctx.webServer.register(route))
166
- return () => { for (const dispose of disposers) dispose() }
167
- },
168
- 'dsh-imagegen: routes',
169
- )
170
- })
171
-
172
- ctx.inject(['tools', 'attachments'], (tctx) => {
173
- tctx.effect(() => registerAgentImageTools(tctx, runtime, () => {
174
- const value = resolve()
175
- return {
176
- enabled: value.enabled,
177
- allowAgentImageGeneration: value.allowAgentImageGeneration,
178
- apiUrl: value.apiUrl,
179
- apiKey: value.apiKey,
180
- imageModels: value.imageModels,
181
- }
182
- }), 'dsh-imagegen: agent image tools')
183
- })
184
-
185
- // System-prompt announcement (toggled by settings changes).
186
- let disposeSection: (() => void) | undefined
187
- const sync = (): void => {
188
- if (disposeSection !== undefined) {
189
- disposeSection()
190
- disposeSection = undefined
191
- }
192
- const value = resolve()
193
- if (!value.enabled || !value.announceToAgent) return
194
- disposeSection = ctx.systemPrompt.section({
195
- name: 'plugin:dsh-imagegen',
196
- order: SECTION_ORDER,
197
- text: guidanceFor(value.imageModels),
198
- })
199
- }
200
-
201
- installSettingsSection(ctx, ImageGenSettingsNamespace, Config, config ?? {}, {
202
- setSource: (source) => {
203
- current = source
204
- sync()
205
- },
206
- onChange: sync,
207
- })
208
-
209
- // Initial registration from the composition entry (covers deployments with
210
- // no settings service, whose installSettingsSection never fires its hooks).
211
- sync()
212
- }
1
+ /**
2
+ * dsh-imagegen — host half. Mounts the plugin's settings section (channels
3
+ * with per-channel model catalogs on the host settings seam), the
4
+ * /api/dsh-imagegen route family (loopback-only settings bridge + presets /
5
+ * usage / image-generation proxy that keeps every API key host-side), and a
6
+ * system-prompt announcement. The browser half (./client) renders the sidebar
7
+ * entry and the split-pane generation studio.
8
+ */
9
+
10
+ import type { Context } from '@deepseek-ai/cordis'
11
+ import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings'
12
+ import z from 'schemastery'
13
+ // Type-only: pulls the webServer Context merge (route registration).
14
+ import type {} from '@deepseek-ai/dsh-host-webserver'
15
+ // Type-only: pulls the systemPrompt Context merge (announcement section).
16
+ import type {} from '@deepseek-ai/dsh-system-prompt'
17
+ import type {} from '@deepseek-ai/dsh-tools'
18
+ import type {} from '@deepseek-ai/dsh-attachment'
19
+ import { IMAGEGEN_SETTINGS_NAMESPACE, type ChannelConfig, type ModelMapping } from './protocol.ts'
20
+ import { makeRoutes, type SettingsSeam } from './routes.ts'
21
+ import { ImageGenerationRuntime, type ChannelsView, type RuntimeChannel } from './generation-runtime.ts'
22
+ import { registerAgentImageTools } from './agent-image-tools.ts'
23
+ import { presetById } from './presets.ts'
24
+
25
+ /** Stable cordis plugin name. */
26
+ export const name = 'imagegen'
27
+
28
+ /** Services required before the surfaces can mount. */
29
+ export const inject = ['webServer', 'systemPrompt']
30
+
31
+ // Internals re-exported for smoke tests and host-side debugging; the plugin
32
+ // contract only requires name / inject / Config / apply.
33
+ export { makeRoutes } from './routes.ts'
34
+ export { generateImage, ImageGenError } from './engine.ts'
35
+ export { ImageGenerationRuntime } from './generation-runtime.ts'
36
+ export { registerAgentImageTools } from './agent-image-tools.ts'
37
+ export { appendGallery, clearGallery, listGallery, readGalleryImage, removeGallery, updateGalleryTags } from './gallery-store.ts'
38
+ export { listTemplates, readTemplateImage, refreshTemplates, clearTemplateMemo } from './templates-store.ts'
39
+ export { checkForUpdate, clearUpdateCache, compareVersions, CURRENT_VERSION, installUpdate, profileFromProcess } from './updater.ts'
40
+
41
+ /** The branded settings namespace of this plugin (the card edits it). */
42
+ export const ImageGenSettingsNamespace = settingsNamespace(IMAGEGEN_SETTINGS_NAMESPACE)
43
+
44
+ /**
45
+ * Plugin config, validated by the same-named schemastery schema.
46
+ *
47
+ * Channels own the endpoint + model catalog. The API key of each channel lives
48
+ * in `channelSecrets` (a secret dict keyed by channel id) instead of inside the
49
+ * channel objects dsh-settings redaction supports dict/array containers, but
50
+ * path ops cannot reach inside arrays, so a whole-array write must never carry
51
+ * secrets it would clobber.
52
+ */
53
+ export interface Config {
54
+ /** Master switch for the plugin (routes, prompt section). */
55
+ enabled?: boolean
56
+ /** Announce the plugin in every agent's system prompt. */
57
+ announceToAgent?: boolean
58
+ /** Allow Agents to submit and retrieve image-generation tasks. */
59
+ allowAgentImageGeneration?: boolean
60
+ /** Configured channels (each: name, endpoint, model catalog). */
61
+ channels?: ChannelConfig[]
62
+ /** Per-channel API keys, keyed by channel id. */
63
+ channelSecrets?: Record<string, string>
64
+ /** Channel used when a request does not name one. */
65
+ defaultChannelId?: string
66
+ /** Optional OpenAI-compatible chat endpoint for prompt enhancement. */
67
+ promptApiUrl?: string
68
+ /** Optional secret for the prompt enhancement endpoint. */
69
+ promptApiKey?: string
70
+ /** Chat model used to expand short image prompts. */
71
+ promptModel?: string
72
+ /* ----- deprecated legacy single-endpoint fields (migrated to channels) ----- */
73
+ /** Legacy base URL; synthesized into the default channel on upgrade. */
74
+ apiUrl?: string
75
+ /** Legacy secret; migrated into channelSecrets on upgrade. */
76
+ apiKey?: string
77
+ /** Legacy allow-list; migrated into the default channel's catalog. */
78
+ imageModels?: string[]
79
+ }
80
+
81
+ export const Config: z<Config> = z.object({
82
+ enabled: z.boolean().default(true),
83
+ announceToAgent: z.boolean().default(true),
84
+ allowAgentImageGeneration: z.boolean().default(true),
85
+ channels: z.array(z.object({
86
+ id: z.string(),
87
+ preset: z.string().default(''),
88
+ name: z.string().default(''),
89
+ apiUrl: z.string().default(''),
90
+ models: z.array(z.object({
91
+ alias: z.string(),
92
+ id: z.string(),
93
+ })).default([]),
94
+ })).default([]),
95
+ channelSecrets: z.dict(z.string().role('secret')).default({}),
96
+ defaultChannelId: z.string().default(''),
97
+ promptApiUrl: z.string().default(''),
98
+ promptApiKey: z.string().role('secret').default(''),
99
+ promptModel: z.string().default(''),
100
+ apiUrl: z.string().default(''),
101
+ apiKey: z.string().role('secret').default(''),
102
+ imageModels: z.array(z.string()).default([]),
103
+ })
104
+
105
+ /** Schema defaults, re-read for hand-built contexts (the loader applies them normally). */
106
+ const DEFAULT_ENABLED = true
107
+ const DEFAULT_ANNOUNCE = true
108
+ const DEFAULT_ALLOW_AGENT_IMAGE_GENERATION = true
109
+
110
+ /** Order of the announcement section within the tool-guidance band. */
111
+ const SECTION_ORDER = 150
112
+
113
+ /** Model-facing announcement: plugin presence, capabilities, and limits. */
114
+ export const IMAGEGEN_GUIDANCE = '本机已安装 dsh-imagegen 插件(DSH AI 生图):侧边栏「AI 生图」入口。能力:通过「渠道」对接 OpenAI 兼容图像生成 API(每个渠道 = 一个 API 端点 + 各自的模型目录),支持文生图(/images/generations)与图生图(/images/edits,上传参考图,grok-imagine 模型按官方 JSON image_url 协议发送,nanobanana 系列按 aspect_ratio / image_size 参数协议发送;seedream 系列统一走 /images/generations,参考图以 JSON image 数组发送;智谱 `glm-image` 使用官方 `/api/paas/v4/images/generations`,当前仅支持文生图)。API 地址与密钥在 GUI 设置中按渠道配置,密钥仅存于本机设置文档;生成请求由本地宿主代理转发,结果以 base64 返回面板,可预览与下载。模型只能使用用户在各渠道配置目录中的模型;检测模型时会过滤聊天、Embedding 等非图片模型,但模型出现在 /models 中仍不等于其网关原生支持生图协议,遇到 Qwen、Gemini 等非 OpenAI 生图协议时应如实说明上游兼容性。可一键把满意的图片加入「画廊」。内置「提示词模板库」(面板提示词框左下角「模板库」按钮):打包 awesome-gpt-image-2 的数百条提示词案例,可搜索、筛选与复用。Agent 可直接调用 `generate_image` 提交文生图,也可用 `edit_image` 图生图;默认保持工具调用等待直到任务完成,完成图片显示在工具调用对应的左侧结果区域,模型收到状态和附件引用,不会额外伪造用户消息。若明确需要后台执行,可传 `wait_for_completion: false`,之后再用 `get_image_generation_task` 查询;不要反复轮询。限制:生成消耗上游 API 额度;图片内容由上游模型生成,可能不符合预期或包含不适宜内容;api_key 以明文存储在设置文档中;参考图会发送至所配置的 API 服务;模板库在线刷新与参考图首次加载需要访问 vibeui.top。用户提到「生图 / 绘画 / 生成图片 / 文生图 / 图生图 / 画廊 / 提示词模板」时即指本插件,请据此协作。'
115
+
116
+ /** Append the live channel × model table so an Agent can honor user choices. */
117
+ function guidanceFor(channels: RuntimeChannel[], defaultChannelId: string): string {
118
+ if (channels.length === 0) {
119
+ return `${IMAGEGEN_GUIDANCE} 尚未配置任何渠道:请先在「设置 → 插件 → AI 生图」添加渠道并填写 API 地址与密钥。`
120
+ }
121
+ const table = channels.map(channel => {
122
+ const aliases = channel.models.map(model => model.alias).join('')
123
+ const mark = channel.id === defaultChannelId ? '(默认渠道)' : ''
124
+ const key = channel.apiKey === '' ? '(未填密钥)' : ''
125
+ const models = channel.models.length === 0 ? '未配置模型' : `可用模型:${aliases}`
126
+ return `渠道「${channel.name}」${mark}[${channel.apiUrl}] ${models}${key}`
127
+ }).join(';')
128
+ return `${IMAGEGEN_GUIDANCE} 当前渠道与模型:${table}。用户指定模型名时取该模型所属渠道(多渠道同名用默认渠道);未指定模型时若仅一个可用模型可直接生成,若有多个应先询问用户选择「渠道 + 模型」。`
129
+ }
130
+
131
+ /** Normalize raw channel entries into the wire shape (schema-adjacent guard). */
132
+ function normalizeChannels(value: unknown): ChannelConfig[] {
133
+ if (!Array.isArray(value)) return []
134
+ const out: ChannelConfig[] = []
135
+ for (const item of value) {
136
+ if (item === null || typeof item !== 'object') continue
137
+ const raw = item as Record<string, unknown>
138
+ const id = typeof raw.id === 'string' ? raw.id.trim() : ''
139
+ if (id === '') continue
140
+ const models: ModelMapping[] = []
141
+ if (Array.isArray(raw.models)) {
142
+ for (const entry of raw.models) {
143
+ if (entry === null || typeof entry !== 'object') continue
144
+ const record = entry as Record<string, unknown>
145
+ const alias = typeof record.alias === 'string' ? record.alias.trim() : ''
146
+ const upstream = typeof record.id === 'string' ? record.id.trim() : ''
147
+ if (alias === '') continue
148
+ models.push({ alias, id: upstream === '' ? alias : upstream })
149
+ }
150
+ }
151
+ out.push({
152
+ id,
153
+ preset: typeof raw.preset === 'string' ? raw.preset : '',
154
+ name: typeof raw.name === 'string' ? raw.name.trim() : '',
155
+ apiUrl: typeof raw.apiUrl === 'string' ? raw.apiUrl.trim() : '',
156
+ models,
157
+ })
158
+ }
159
+ return out
160
+ }
161
+
162
+ /** Effective config (schema defaults applied + legacy migration). */
163
+ export interface EffectiveConfig {
164
+ enabled: boolean
165
+ announceToAgent: boolean
166
+ allowAgentImageGeneration: boolean
167
+ channels: RuntimeChannel[]
168
+ defaultChannelId: string
169
+ promptApiUrl: string
170
+ promptApiKey: string
171
+ promptModel: string
172
+ }
173
+
174
+ /**
175
+ * Mount the settings section, routes, and announcement.
176
+ * @param ctx - host plugin context carrying webServer/systemPrompt.
177
+ * @param config - resolved plugin config (schema defaults applied by the loader).
178
+ */
179
+ export function apply(ctx: Context, config?: Config): void {
180
+ // The live source the surfaces read: the settings section once the settings
181
+ // service is attached, the composition entry otherwise.
182
+ let current: () => Config = () => config ?? {}
183
+ const resolve = (): EffectiveConfig => {
184
+ const value = current() ?? {}
185
+ let channels = normalizeChannels(value.channels)
186
+ // Settings scopes are deep-frozen by the host. Legacy migration adds the
187
+ // synthesized default-channel secret, so always work on a detached copy.
188
+ const secrets: Record<string, string> = { ...(value.channelSecrets ?? {}) }
189
+ // Legacy single-endpoint migration: no channels yet → synthesize the
190
+ // default channel from the old flat fields so upgrades never break.
191
+ if (channels.length === 0) {
192
+ const legacyUrl = typeof value.apiUrl === 'string' ? value.apiUrl.trim() : ''
193
+ const legacyModels: ModelMapping[] = Array.isArray(value.imageModels)
194
+ ? value.imageModels
195
+ .filter((model): model is string => typeof model === 'string' && model.trim() !== '')
196
+ .map(model => ({ alias: model.trim(), id: model.trim() }))
197
+ : []
198
+ if (legacyUrl !== '' || legacyModels.length > 0) {
199
+ channels = [{ id: 'default', preset: '', name: '默认渠道', apiUrl: legacyUrl, models: legacyModels }]
200
+ const legacyKey = typeof value.apiKey === 'string' ? value.apiKey.trim() : ''
201
+ if (legacyKey !== '') secrets['default'] = legacyKey
202
+ }
203
+ }
204
+ const named = channels.map(channel => ({
205
+ ...channel,
206
+ name: channel.name === '' ? (presetById(channel.preset)?.name ?? '未命名渠道') : channel.name,
207
+ }))
208
+ const defaultChannelId = typeof value.defaultChannelId === 'string' && named.some(channel => channel.id === value.defaultChannelId)
209
+ ? value.defaultChannelId
210
+ : named[0]?.id ?? ''
211
+ return {
212
+ enabled: value.enabled ?? DEFAULT_ENABLED,
213
+ announceToAgent: value.announceToAgent ?? DEFAULT_ANNOUNCE,
214
+ allowAgentImageGeneration: value.allowAgentImageGeneration ?? DEFAULT_ALLOW_AGENT_IMAGE_GENERATION,
215
+ channels: named.map(channel => ({
216
+ ...channel,
217
+ apiKey: typeof secrets[channel.id] === 'string' ? secrets[channel.id] : '',
218
+ })),
219
+ defaultChannelId,
220
+ promptApiUrl: typeof value.promptApiUrl === 'string' ? value.promptApiUrl.trim() : '',
221
+ promptApiKey: typeof value.promptApiKey === 'string' ? value.promptApiKey.trim() : '',
222
+ promptModel: typeof value.promptModel === 'string' ? value.promptModel.trim() : '',
223
+ }
224
+ }
225
+
226
+ // Transient helper used by several mount points below: resolve the shared
227
+ // channel view once per access; the runtime then picks per-request creds.
228
+ const channelsView = (): ChannelsView => {
229
+ const value = resolve()
230
+ return { channels: value.channels, defaultChannelId: value.defaultChannelId }
231
+ }
232
+
233
+ // Browser endpoints and Agent tools share the exact same serial queue. This
234
+ // keeps image persistence, cancellation, and retries coherent across both
235
+ // entry points; Agent tools wait for their task result by default and render
236
+ // images in the tool result instead of injecting a synthetic user message.
237
+ const runtime = new ImageGenerationRuntime(channelsView)
238
+
239
+ // The route family mounts once, gated on the settings seam (the bridge
240
+ // serves it; without the seam there is nothing to expose). Route handlers
241
+ // read resolve() per request, so config edits apply live. The settings
242
+ // bridge deliberately keeps serving while the plugin is disabled — it is
243
+ // how the user re-enables the plugin from the settings card.
244
+ ctx.inject(['settings', 'attachments'], (sctx) => {
245
+ const seam = sctx.get('settings') as unknown as SettingsSeam
246
+ sctx.effect(
247
+ () => {
248
+ const routes = makeRoutes({
249
+ settings: seam,
250
+ resolve: () => {
251
+ const value = resolve()
252
+ const channel = value.channels.find(candidate => candidate.id === value.defaultChannelId) ?? value.channels[0]
253
+ return { apiUrl: channel?.apiUrl ?? '', apiKey: channel?.apiKey ?? '' }
254
+ },
255
+ resolveChannels: channelsView,
256
+ resolvePrompt: () => {
257
+ const value = resolve()
258
+ const channel = value.channels.find(candidate => candidate.id === value.defaultChannelId) ?? value.channels[0]
259
+ return {
260
+ apiUrl: value.promptApiUrl !== '' ? value.promptApiUrl : (channel?.apiUrl ?? ''),
261
+ apiKey: value.promptApiKey !== '' ? value.promptApiKey : (channel?.apiKey ?? ''),
262
+ model: value.promptModel,
263
+ }
264
+ },
265
+ resolveImageModels: () => {
266
+ const value = resolve()
267
+ return [...new Set(value.channels.flatMap(channel => channel.models.map(model => model.alias)))]
268
+ },
269
+ attachments: sctx.attachments,
270
+ runtime,
271
+ })
272
+ const disposers = routes.map(route => ctx.webServer.register(route))
273
+ return () => { for (const dispose of disposers) dispose() }
274
+ },
275
+ 'dsh-imagegen: routes',
276
+ )
277
+ })
278
+
279
+ ctx.inject(['tools', 'attachments'], (tctx) => {
280
+ tctx.effect(() => registerAgentImageTools(tctx, runtime, () => {
281
+ const value = resolve()
282
+ return {
283
+ enabled: value.enabled,
284
+ allowAgentImageGeneration: value.allowAgentImageGeneration,
285
+ channels: value.channels,
286
+ defaultChannelId: value.defaultChannelId,
287
+ }
288
+ }), 'dsh-imagegen: agent image tools')
289
+ })
290
+
291
+ // System-prompt announcement (toggled by settings changes).
292
+ let disposeSection: (() => void) | undefined
293
+ const sync = (): void => {
294
+ if (disposeSection !== undefined) {
295
+ disposeSection()
296
+ disposeSection = undefined
297
+ }
298
+ const value = resolve()
299
+ if (!value.enabled || !value.announceToAgent) return
300
+ disposeSection = ctx.systemPrompt.section({
301
+ name: 'plugin:dsh-imagegen',
302
+ order: SECTION_ORDER,
303
+ text: guidanceFor(value.channels, value.defaultChannelId),
304
+ })
305
+ }
306
+
307
+ installSettingsSection(ctx, ImageGenSettingsNamespace, Config, config ?? {}, {
308
+ setSource: (source) => {
309
+ current = source
310
+ sync()
311
+ },
312
+ onChange: sync,
313
+ })
314
+
315
+ // Initial registration from the composition entry (covers deployments with
316
+ // no settings service, whose installSettingsSection never fires its hooks).
317
+ sync()
318
+ }