koishi-plugin-p-draw 1.6.2 → 1.6.4

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/i18n.js CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  const zhCN = {
4
4
  comfyuiBaseUrl: { $description: 'ComfyUI 地址' },
5
+ tavilyProxy: { $description: '仅联网搜索(Tavily)使用代理(留空直连)。与 LLM / 视觉校验的代理互相独立' },
6
+ llmProxy: { $description: '仅 LLM 使用代理(留空直连)。通道内单独填了 proxy 则优先用通道的' },
7
+ verifyLlmProxy: { $description: '仅视觉校验使用代理(留空直连)。通道内单独填了 proxy 则优先用通道的' },
5
8
  workflow: { $description: '工作流类型(内置 anima_t2i)' },
6
9
  customWorkflowEnabled: { $description: '使用自定义 ComfyUI 工作流 JSON' },
7
10
  customWorkflowPath: { $description: '自定义工作流 JSON 路径(相对 Koishi 运行目录,例如 data/p-draw/workflows/anima-aesthetic-v1.1.json;插件目录作为回退)' },
@@ -12,6 +15,8 @@ const zhCN = {
12
15
  resolutionNodeId: { $description: '自定义工作流中尺寸节点 ID(EmptyLatentImage,可留空;示例 5)' },
13
16
  seedNodeId: { $description: '自定义工作流中种子节点 ID(KSampler,可留空;示例 3)' },
14
17
  stepsNodeId: { $description: '自定义工作流中步数节点 ID(KSampler,可留空;示例 3)' },
18
+ workflowPresets: { $description: '工作流预设:key=预设名。指令里用 --工作流 <名称> 或名称/别名开头选择' },
19
+ defaultWorkflowPreset: { $description: '默认预设名(留空则用 customWorkflow* 那套)' },
15
20
  timeout: { $description: '单次生成超时(秒)' },
16
21
  pollInterval: { $description: '生成状态查询间隔(秒)' },
17
22
  unetName: { $description: '主模型文件名(8G 显存推荐 GGUF Q8_0 版,插件会自动改用 UnetLoaderGGUF 加载)' },
@@ -27,11 +32,16 @@ const zhCN = {
27
32
  scheduler: { $description: '调度器' },
28
33
  qualityPrefix: { $description: '质量词前缀(使用 Aesthetic 1.1 时建议留空;Base 模型可填 masterpiece, best quality, score_7)' },
29
34
  skipQualityPrefixForCustomWorkflow: { $description: '启用自定义工作流时自动跳过质量前缀注入(Aesthetic 模型不需要质量标签)' },
30
- negativePrompt: { $description: '负面提示词(Aesthetic 1.1 推荐值)' },
35
+ negativePrompt: { $description: '负面提示词。推荐值即默认值:worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts' },
31
36
  promptOptimizeEnabled: { $description: '启用自然语言优化(需要配置下方 LLM 接口)' },
32
37
  llmBaseUrl: { $description: 'LLM 接口地址(OpenAI 兼容,例如 https://api.deepseek.com/v1)' },
33
38
  llmApiKey: { $description: 'LLM API Key' },
34
- llmModel: { $description: 'LLM 模型名(留空则不优化,原样生图)' },
39
+ llmModel: { $description: 'LLM 模型名(旧版单模型;请在 llmModels 里配置)' },
40
+ llmModels: { $description: '主通道的模型名列表,按顺序逐个尝试' },
41
+ llmChannels: { $description: '附加通道(中转站/备用站):主通道全部模型失败后按顺序继续尝试' },
42
+ llmChannelOrder: { $description: '附加通道的尝试顺序(填通道名;留空则按配置先后顺序)' },
43
+ llmThinking: { $description: '是否发送 DeepSeek 专有的 thinking 字段(auto / always / never)' },
44
+ llmExtraBody: { $description: '附加请求体 JSON(最后覆盖),用于中转站私有参数' },
35
45
  llmMaxTokens: { $description: 'LLM 输出上限' },
36
46
  webSearchEnabled: { $description: '启用联网搜索(指令里写“联网/搜索/查一下”等触发)' },
37
47
  tavilyApiKey: { $description: 'Tavily API Key(联网搜索用,https://tavily.com 申请)' },
@@ -59,7 +69,10 @@ const zhCN = {
59
69
  multiSendDegradedCandidate: { $description: '多人候选全部不达标时仍发送最优候选' },
60
70
  verifyLlmBaseUrl: { $description: '视觉校验 LLM 接口地址(OpenAI 兼容;留空则跳过校验)' },
61
71
  verifyLlmApiKey: { $description: '视觉校验 LLM API Key' },
62
- verifyLlmModel: { $description: '视觉校验 LLM 模型名(需支持图片输入,如 qwen-vl)' },
72
+ verifyLlmModel: { $description: '视觉校验模型名(旧版单模型;请在 verifyLlmModels 里配置)' },
73
+ verifyLlmModels: { $description: '视觉通道的模型名列表,按顺序逐个尝试(需支持图片输入)' },
74
+ verifyLlmChannels: { $description: '视觉校验的附加通道:主通道全部失败后按顺序继续尝试' },
75
+ verifyLlmChannelOrder: { $description: '视觉附加通道的尝试顺序(填通道名;留空则按配置先后顺序)' },
63
76
  adminOnly: { $description: '仅管理员可用(adminUsers 中的用户)' },
64
77
  allowedUserIds: { $description: '用户白名单(QQ 号,留空表示不限制)' },
65
78
  blockedUserIds: { $description: '用户黑名单(QQ 号,黑名单优先于白名单)' },
package/lib/llm.js ADDED
@@ -0,0 +1,153 @@
1
+ // LLM 通道与模型回退。
2
+ //
3
+ // 一个「通道」= 一组 baseUrl + apiKey;通道内可以填多个模型名。
4
+ // 调用顺序:主通道的模型逐个试 → 全挂 → 下一个通道的模型逐个试。
5
+ // 纯函数 + 一个 runner,不依赖 koishi,可独立单测。
6
+
7
+ const THINKING_MODES = new Set(['auto', 'always', 'never'])
8
+
9
+ // 支持数组或逗号/换行分隔的字符串
10
+ function splitModelList(value) {
11
+ const out = []
12
+ const push = (item) => {
13
+ const text = String(item == null ? '' : item).trim()
14
+ if (text && !out.includes(text)) out.push(text)
15
+ }
16
+ if (Array.isArray(value)) value.forEach(push)
17
+ else if (typeof value === 'string') value.split(/[,,\n]/).forEach(push)
18
+ return out
19
+ }
20
+
21
+ function normalizeBaseUrl(value) {
22
+ return String(value == null ? '' : value).trim().replace(/\/+$/, '')
23
+ }
24
+
25
+ // 通道的模型列表:models(数组)优先,兼容旧的单个 model 字段
26
+ function channelModels(channel) {
27
+ const models = splitModelList(channel && channel.models)
28
+ for (const model of splitModelList(channel && channel.model)) {
29
+ if (!models.includes(model)) models.push(model)
30
+ }
31
+ return models
32
+ }
33
+
34
+ // 附加通道,按 llmChannelOrder 排序;未列出的通道补在后面,避免漏配就丢通道
35
+ function collectChannels(cfg, role) {
36
+ const isVision = role === 'vision'
37
+ const dict = isVision ? cfg.verifyLlmChannels : cfg.llmChannels
38
+ if (!dict || typeof dict !== 'object') return []
39
+ const declared = splitModelList(isVision ? cfg.verifyLlmChannelOrder : cfg.llmChannelOrder)
40
+ const names = declared.filter(name => dict[name])
41
+ for (const name of Object.keys(dict)) {
42
+ if (!names.includes(name)) names.push(name)
43
+ }
44
+ return names.map(name => ({ name, channel: dict[name] }))
45
+ }
46
+
47
+ // 摊平成有序候选链:[{ baseUrl, apiKey, model, label }]
48
+ function buildLlmChain(cfg, role = 'text') {
49
+ const c = cfg || {}
50
+ const isVision = role === 'vision'
51
+ const primaryBase = normalizeBaseUrl(isVision ? c.verifyLlmBaseUrl : c.llmBaseUrl)
52
+ const primaryKey = String((isVision ? c.verifyLlmApiKey : c.llmApiKey) || '').trim()
53
+ const primaryModels = channelModels({
54
+ models: isVision ? c.verifyLlmModels : c.llmModels,
55
+ model: isVision ? c.verifyLlmModel : c.llmModel,
56
+ })
57
+
58
+ const candidates = []
59
+ const seen = new Set()
60
+ const add = (baseUrl, apiKey, model, label, proxy) => {
61
+ const base = normalizeBaseUrl(baseUrl)
62
+ if (!base || !model) return
63
+ const key = [base, String(apiKey || ''), model].join('\u0000')
64
+ if (seen.has(key)) return
65
+ seen.add(key)
66
+ candidates.push({ baseUrl: base, apiKey: String(apiKey || ''), model, label: label || base, proxy: String(proxy || '').trim() })
67
+ }
68
+
69
+ for (const model of primaryModels) add(primaryBase, primaryKey, model, '主通道', '')
70
+ for (const { name, channel } of collectChannels(c, role)) {
71
+ const base = channel && channel.baseUrl
72
+ const key = channel && channel.apiKey
73
+ // 通道可以单独指定代理;留空则用该用途的默认代理(由调用方决定)
74
+ const channelProxy = channel && channel.proxy
75
+ for (const model of channelModels(channel)) add(base, key, model, name, channelProxy)
76
+ }
77
+ return candidates
78
+ }
79
+
80
+ function hasLlm(cfg, role = 'text') {
81
+ return buildLlmChain(cfg, role).length > 0
82
+ }
83
+
84
+ function resolveThinkingMode(value) {
85
+ const mode = String(value == null ? '' : value).trim().toLowerCase()
86
+ return THINKING_MODES.has(mode) ? mode : 'auto'
87
+ }
88
+
89
+ // thinking 是 DeepSeek 专有字段,别的模型 / 中转站带上通常直接 400。
90
+ // auto:只有当 baseUrl 或模型名看起来是 DeepSeek 时才发。
91
+ function shouldSendThinking(cfg, candidate) {
92
+ const mode = resolveThinkingMode(cfg && cfg.llmThinking)
93
+ if (mode === 'always') return true
94
+ if (mode === 'never') return false
95
+ const haystack = `${(candidate && candidate.baseUrl) || ''} ${(candidate && candidate.model) || ''}`.toLowerCase()
96
+ return haystack.includes('deepseek')
97
+ }
98
+
99
+ function parseExtraBody(value) {
100
+ const raw = typeof value === 'string' ? value.trim() : ''
101
+ if (!raw) return {}
102
+ try {
103
+ const data = JSON.parse(raw)
104
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : {}
105
+ } catch (e) {
106
+ return {}
107
+ }
108
+ }
109
+
110
+ // 请求体:基础字段 + 条件性 thinking + 用户自定义附加参数(最后覆盖)
111
+ function buildChatBody(cfg, { candidate, messages, maxTokens, defaultMaxTokens = 700 }) {
112
+ const body = {
113
+ model: candidate.model,
114
+ messages,
115
+ max_tokens: Math.max(64, parseInt(maxTokens) || defaultMaxTokens),
116
+ }
117
+ if (shouldSendThinking(cfg, candidate)) body.thinking = { type: 'disabled' }
118
+ return Object.assign(body, parseExtraBody(cfg && cfg.llmExtraBody))
119
+ }
120
+
121
+ // 依次尝试候选;attempt 抛错即视为该候选失败,继续下一个。
122
+ // 返回 { ok, candidate, value, errors },errors 里保留每次失败原因便于诊断。
123
+ async function runLlmChain(candidates, attempt, { onError } = {}) {
124
+ const errors = []
125
+ for (const candidate of candidates) {
126
+ try {
127
+ const value = await attempt(candidate)
128
+ return { ok: true, candidate, value, errors }
129
+ } catch (e) {
130
+ const message = String((e && e.message) || e || 'unknown')
131
+ errors.push({ model: candidate.model, label: candidate.label, message })
132
+ if (typeof onError === 'function') {
133
+ try { onError(candidate, message) } catch (err) { /* ignore */ }
134
+ }
135
+ }
136
+ }
137
+ return { ok: false, candidate: null, value: null, errors }
138
+ }
139
+
140
+ module.exports = {
141
+ THINKING_MODES,
142
+ splitModelList,
143
+ normalizeBaseUrl,
144
+ channelModels,
145
+ collectChannels,
146
+ buildLlmChain,
147
+ hasLlm,
148
+ resolveThinkingMode,
149
+ shouldSendThinking,
150
+ parseExtraBody,
151
+ buildChatBody,
152
+ runLlmChain,
153
+ }
package/lib/net.js ADDED
@@ -0,0 +1,85 @@
1
+ // 出站 HTTP:可选代理(Tavily / LLM / 视觉校验共用)。
2
+ //
3
+ // Node 内置 fetch 不支持直接用代理,这里通过 undici 的 ProxyAgent 挂 dispatcher。
4
+ // undici 属于可选依赖:拿不到时降级为直连,并且只告警一次,不影响其他功能。
5
+
6
+ let undiciModule = null
7
+ let undiciLoaded = false
8
+
9
+ function loadUndici() {
10
+ if (undiciLoaded) return undiciModule
11
+ undiciLoaded = true
12
+ try {
13
+ // eslint-disable-next-line global-require
14
+ undiciModule = require('undici')
15
+ } catch (e) {
16
+ undiciModule = null
17
+ }
18
+ return undiciModule
19
+ }
20
+
21
+ // 允许省略协议:127.0.0.1:7890 → http://127.0.0.1:7890
22
+ function normalizeProxyUrl(value) {
23
+ const raw = String(value == null ? '' : value).trim()
24
+ if (!raw) return ''
25
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `http://${raw}`
26
+ }
27
+
28
+ // 是否能用上真实代理(undici 可用且 ProxyAgent 能构造)
29
+ const dispatcherCache = new Map()
30
+
31
+ function resolveDispatcher(proxyUrl) {
32
+ const url = normalizeProxyUrl(proxyUrl)
33
+ if (!url) return null
34
+ if (dispatcherCache.has(url)) return dispatcherCache.get(url)
35
+ const mod = loadUndici()
36
+ let dispatcher = null
37
+ if (mod && typeof mod.ProxyAgent === 'function') {
38
+ try {
39
+ dispatcher = new mod.ProxyAgent(url)
40
+ } catch (e) {
41
+ dispatcher = null
42
+ }
43
+ }
44
+ dispatcherCache.set(url, dispatcher)
45
+ return dispatcher
46
+ }
47
+
48
+ function proxySupportAvailable() {
49
+ const mod = loadUndici()
50
+ return Boolean(mod && typeof mod.ProxyAgent === 'function')
51
+ }
52
+
53
+ // 构造一个「按次指定代理」的 fetch:outboundFetch(url, options, proxyUrl)。
54
+ //
55
+ // 代理是分用途配置的(联网搜索 / 文本 LLM / 视觉校验各一套),所以这里不在工厂里
56
+ // 绑定代理,而是每次调用由调用方传入;proxyUrl 为空即直连。
57
+ function createOutboundFetch({ onWarn } = {}) {
58
+ const warned = new Set()
59
+ return async function outboundFetch(url, options = {}, proxyUrl = '') {
60
+ const proxy = normalizeProxyUrl(proxyUrl)
61
+ if (!proxy) return fetch(url, options)
62
+
63
+ const dispatcher = resolveDispatcher(proxy)
64
+ if (!dispatcher) {
65
+ if (!warned.has(proxy) && typeof onWarn === 'function') {
66
+ warned.add(proxy)
67
+ onWarn(`已配置代理 ${proxy},但无法启用(缺少 undici 依赖),该代理将被忽略,本次直连。`)
68
+ }
69
+ return fetch(url, options)
70
+ }
71
+ return fetch(url, { ...options, dispatcher })
72
+ }
73
+ }
74
+
75
+ function clearDispatcherCache() {
76
+ dispatcherCache.clear()
77
+ }
78
+
79
+ module.exports = {
80
+ normalizeProxyUrl,
81
+ resolveDispatcher,
82
+ proxySupportAvailable,
83
+ createOutboundFetch,
84
+ clearDispatcherCache,
85
+ }
package/lib/parse.js CHANGED
@@ -191,6 +191,54 @@ function parseStepsCfg(text) {
191
191
  return { steps, cfg, prompt }
192
192
  }
193
193
 
194
+ // 工作流预设选择:--工作流 名称 / --workflow 名称,或开头裸写名称/别名(如「极速:描述」)
195
+ // presets: [{ name, aliases: [] }]
196
+ function matchPreset(wanted, presets) {
197
+ const key = String(wanted || '').trim().toLowerCase()
198
+ if (!key) return null
199
+ for (const preset of presets) {
200
+ if (String(preset.name || '').toLowerCase() === key) return preset.name
201
+ if ((preset.aliases || []).some(alias => String(alias || '').toLowerCase() === key)) return preset.name
202
+ }
203
+ return null
204
+ }
205
+
206
+ function parseWorkflowPreset(text, presets = []) {
207
+ const original = String(text || '').trim()
208
+ const list = Array.isArray(presets) ? presets : []
209
+ if (!list.length) return { preset: null, prompt: original, error: null }
210
+
211
+ // 1) 显式开关:--工作流 xxx
212
+ const flag = original.match(/(?<!\S)--(?:工作流|预设|workflow|preset)\s*(?:=|=|:|:)?\s*([^\s,,::]+)/i)
213
+ if (flag) {
214
+ const hit = matchPreset(flag[1], list)
215
+ if (!hit) {
216
+ return {
217
+ preset: null,
218
+ prompt: original,
219
+ error: `没有名为「${flag[1]}」的工作流预设。可用:${list.map(p => p.name).join('、')}`,
220
+ }
221
+ }
222
+ return { preset: hit, prompt: stripMatchedToken(original, flag), error: null }
223
+ }
224
+
225
+ // 2) 开头裸写名称或别名(长的优先,避免「高清」抢了「高清重绘」)
226
+ const candidates = []
227
+ for (const preset of list) {
228
+ if (preset.name) candidates.push([String(preset.name), preset.name])
229
+ for (const alias of preset.aliases || []) if (alias) candidates.push([String(alias), preset.name])
230
+ }
231
+ candidates.sort((a, b) => b[0].length - a[0].length)
232
+ for (const [token, name] of candidates) {
233
+ const pattern = new RegExp(`^\\s*${escapeRe(token)}\\s*(?:[::,,]|\\s|$)`, 'i')
234
+ const matched = original.match(pattern)
235
+ if (matched) {
236
+ return { preset: name, prompt: original.slice(matched[0].length).trim(), error: null }
237
+ }
238
+ }
239
+ return { preset: null, prompt: original, error: null }
240
+ }
241
+
194
242
  // ------------------------------------------------------------------
195
243
  // 提示词辅助(移植自 anima prompt_presets)
196
244
  // ------------------------------------------------------------------
@@ -302,6 +350,8 @@ module.exports = {
302
350
  CFG_PATTERN,
303
351
  stripMatchedToken,
304
352
  parseStepsCfg,
353
+ matchPreset,
354
+ parseWorkflowPreset,
305
355
  RAW_PREFIXES,
306
356
  stripRawPrefix,
307
357
  splitPositiveNegativePrompt,
package/lib/workflows.js CHANGED
@@ -182,6 +182,22 @@ function findNodesByClass(workflow, classTypes) {
182
182
  return ids
183
183
  }
184
184
 
185
+ // 尺寸节点:凡是「类名带 Latent 且同时有 width/height 输入」的都算。
186
+ // 这样 EmptyLatentImage、EmptySD3LatentImage、EmptyHunyuanLatentVideo 等新老节点都能认。
187
+ function findResolutionNodeIds(workflow) {
188
+ const ids = []
189
+ for (const [nodeId, node] of Object.entries(workflow)) {
190
+ if (!node || typeof node !== 'object') continue
191
+ const classType = String(node.class_type || '')
192
+ const inputs = node.inputs
193
+ if (!inputs || typeof inputs !== 'object') continue
194
+ if (!/latent/i.test(classType)) continue
195
+ if (!('width' in inputs) || !('height' in inputs)) continue
196
+ ids.push(String(nodeId))
197
+ }
198
+ return ids
199
+ }
200
+
185
201
  // 从 KSampler 的 positive/negative 入口沿连线反查,找到真正的文本编码节点
186
202
  function conditioningTextNodeIds(workflow, inputName, textNodes) {
187
203
  const pending = []
@@ -254,12 +270,12 @@ function resolveCustomNodeTargets(workflow, cfg = {}) {
254
270
  let resolutionIds = []
255
271
  if (explicitResolution) {
256
272
  if (!workflow[explicitResolution]) {
257
- errors.push(`配置的尺寸节点 ID「${explicitResolution}」不存在于工作流中。可能是:\n ${findNodesByClass(workflow, ['EmptyLatentImage']).map(id => nodeLabel(workflow, id)).join('\n ') || '(无)'}`)
273
+ errors.push(`配置的尺寸节点 ID「${explicitResolution}」不存在于工作流中。可能是:\n ${findResolutionNodeIds(workflow).map(id => nodeLabel(workflow, id)).join('\n ') || '(无)'}`)
258
274
  } else {
259
275
  resolutionIds = [explicitResolution]
260
276
  }
261
277
  } else {
262
- resolutionIds = findNodesByClass(workflow, ['EmptyLatentImage'])
278
+ resolutionIds = findResolutionNodeIds(workflow)
263
279
  }
264
280
 
265
281
  // 采样节点:显式指定则只改该节点,否则改所有 KSampler
@@ -318,6 +334,11 @@ function customWorkflow(cfg, prompt, negativePrompt, width, height, steps, cfgVa
318
334
  }
319
335
 
320
336
  const override = Boolean(cfg.customWorkflowOverrideParameters)
337
+ // modelParams 里显式配置的字段永远覆盖工作流内取值(用户明确为这个模型指定的值),
338
+ // 其余字段才受 customWorkflowOverrideParameters 这个总开关控制。
339
+ const modelParams = (opts && opts.modelParams && typeof opts.modelParams === 'object') ? opts.modelParams : {}
340
+ const explicitlySet = (key) => Object.prototype.hasOwnProperty.call(modelParams, key)
341
+ const overwrite = (key) => override || explicitlySet(key)
321
342
  const resolutionSet = new Set(targets.resolutionIds)
322
343
  const stepsSet = new Set(targets.stepsIds)
323
344
  const seedSet = new Set(targets.seedIds)
@@ -330,16 +351,17 @@ function customWorkflow(cfg, prompt, negativePrompt, width, height, steps, cfgVa
330
351
  if (classType === 'SaveImage' && 'filename_prefix' in inputs) {
331
352
  inputs.filename_prefix = 'pdraw/anm'
332
353
  }
333
- // 尺寸:配置了 customWorkflowOverrideParameters,或用户显式指定了尺寸时覆盖
334
- if ((override || explicitSize) && resolutionSet.has(nodeId)) {
354
+ // 尺寸:总开关开、用户显式指定尺寸、或 modelParams 配了 width/height 时覆盖
355
+ const sizeOverride = override || explicitSize || overwrite('width') || overwrite('height')
356
+ if (sizeOverride && resolutionSet.has(nodeId)) {
335
357
  if ('width' in inputs) inputs.width = width
336
358
  if ('height' in inputs) inputs.height = height
337
359
  }
338
- if (override && stepsSet.has(nodeId)) {
339
- if ('steps' in inputs) inputs.steps = steps
340
- if ('cfg' in inputs) inputs.cfg = cfgVal
341
- if (cfg.samplerName && 'sampler_name' in inputs) inputs.sampler_name = cfg.samplerName
342
- if (cfg.scheduler && 'scheduler' in inputs) inputs.scheduler = cfg.scheduler
360
+ if (stepsSet.has(nodeId)) {
361
+ if ('steps' in inputs && overwrite('steps')) inputs.steps = steps
362
+ if ('cfg' in inputs && overwrite('cfg')) inputs.cfg = cfgVal
363
+ if (cfg.samplerName && 'sampler_name' in inputs && overwrite('samplerName')) inputs.sampler_name = cfg.samplerName
364
+ if (cfg.scheduler && 'scheduler' in inputs && overwrite('scheduler')) inputs.scheduler = cfg.scheduler
343
365
  }
344
366
  if (seedSet.has(nodeId)) {
345
367
  if ('seed' in inputs) inputs.seed = seed
@@ -373,6 +395,70 @@ function inspectCustomWorkflow(cfg, opts = {}) {
373
395
  }
374
396
  }
375
397
 
398
+ // 只有图像输入类节点才需要用户「喂图」;这些工作流在纯文生图模式下无法使用
399
+ const IMAGE_INPUT_RE = /^(LoadImage|LoadImageMask|LoadImageOutput|ImageInput|LoadImageFromUrl)$/i
400
+ const CONTROLNET_RE = /controlnet/i
401
+
402
+ // 体检:这个工作流能不能在「纯文本」模式下跑,需要什么额外输入
403
+ function analyzeWorkflow(workflow) {
404
+ const classes = Object.values(workflow).map(node => String((node && node.class_type) || ''))
405
+ const unique = (list) => [...new Set(list)]
406
+ const imageInputClasses = unique(classes.filter(type => IMAGE_INPUT_RE.test(type)))
407
+ const controlNetClasses = unique(classes.filter(type => CONTROLNET_RE.test(type)))
408
+ const resolutionIds = findResolutionNodeIds(workflow)
409
+ const textNodes = collectTextNodeIds(workflow)
410
+
411
+ const requires = []
412
+ if (imageInputClasses.length) requires.push(`图片输入(${imageInputClasses.join(' / ')})`)
413
+ if (controlNetClasses.length && !imageInputClasses.length) {
414
+ requires.push(`ControlNet 控制图(${controlNetClasses.join(' / ')})`)
415
+ }
416
+
417
+ return {
418
+ nodeCount: classes.length,
419
+ textNodes,
420
+ resolutionIds,
421
+ imageInputClasses,
422
+ controlNetClasses,
423
+ hasLatentStart: resolutionIds.length > 0,
424
+ requires,
425
+ // 纯文本可跑:有文生图起点,且没有任何需要外部图片的节点
426
+ canRunTextOnly: resolutionIds.length > 0 && imageInputClasses.length === 0,
427
+ }
428
+ }
429
+
430
+ // 体检任意一个工作流文件(预设用)。返回结构不抛错,便于诊断里逐条展示。
431
+ function inspectWorkflowFile(workflowPath, cfg = {}, opts = {}) {
432
+ const report = {
433
+ ok: false, path: '', mtimeMs: null, analysis: null, targets: null, error: '',
434
+ }
435
+ try {
436
+ const absPath = resolveCustomWorkflowPath({ customWorkflowPath: workflowPath }, opts)
437
+ report.path = absPath
438
+ try { report.mtimeMs = fs.statSync(absPath).mtimeMs } catch (e) { /* ignore */ }
439
+ const body = readCustomWorkflowBody(absPath, cfg.customWorkflowReloadOnChange !== false)
440
+ const workflow = JSON.parse(JSON.stringify(body))
441
+ report.analysis = analyzeWorkflow(workflow)
442
+ const targets = resolveCustomNodeTargets(workflow, cfg)
443
+ report.targets = targets
444
+ if (targets.errors.length) {
445
+ report.error = targets.errors.join(';')
446
+ return report
447
+ }
448
+ if (!report.analysis.canRunTextOnly) {
449
+ report.error = report.analysis.requires.length
450
+ ? `需要${report.analysis.requires.join('、')},当前版本不支持图生图`
451
+ : '工作流里找不到可写入尺寸的 latent 节点(缺少文生图起点)'
452
+ return report
453
+ }
454
+ report.ok = true
455
+ return report
456
+ } catch (e) {
457
+ report.error = String((e && e.message) || e)
458
+ return report
459
+ }
460
+ }
461
+
376
462
  function buildWorkflow(cfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, explicitSize, opts = {}) {
377
463
  if (cfg.customWorkflowEnabled && cfg.customWorkflowPath) {
378
464
  return customWorkflow(cfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, explicitSize, opts)
@@ -396,9 +482,14 @@ module.exports = {
396
482
  nodeLabel,
397
483
  collectTextNodeIds,
398
484
  findNodesByClass,
485
+ findResolutionNodeIds,
399
486
  buildWorkflow,
400
487
  customWorkflow,
401
488
  conditioningTextNodeIds,
402
489
  resolveCustomNodeTargets,
403
490
  inspectCustomWorkflow,
491
+ IMAGE_INPUT_RE,
492
+ CONTROLNET_RE,
493
+ analyzeWorkflow,
494
+ inspectWorkflowFile,
404
495
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-p-draw",
3
3
  "description": "p点-绘图,连接本地 ComfyUI 生图。支持自然语言优化、尺寸选择、画师组、固定角色、生成队列,需要配合 p-qiandao 使用",
4
- "version": "1.6.2",
4
+ "version": "1.6.4",
5
5
  "main": "index.js",
6
6
  "files": [
7
7
  "index.js",