koishi-plugin-p-draw 1.5.8 → 1.6.1

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/index.js CHANGED
@@ -25,6 +25,7 @@ exports.usage = `
25
25
  别名:部署诊断
26
26
  输出更详细的配置与连通性诊断。
27
27
  - **尺寸:** 支持 \`竖图\` \`横图\` \`方图\` \`长竖图\` \`宽屏\` 或在描述中写 \`1024x1536:描述\` / \`--尺寸 1216x832\`。
28
+ - **采样参数:** 描述里可写 \`--steps 40\` / \`--cfg 3.5\`(也可写 \`--步数\` / \`--强度\`)临时覆盖步数与 CFG,优先于 \`modelParams\` 与全局配置。
28
29
  - **原样模式:** 描述前加 \`无优化\` 直接提交写好的 tags。
29
30
  - **联网搜索:** 描述中带 \`联网\` / \`搜索\` / \`查一下\` 等词时,会先联网搜索补充角色设定(需配置 Tavily Key)。
30
31
  - **画师组:** \`创建画师组 名称=tags\` \`切换画师组 名称\` \`查看画师组\` \`删除画师组 名称\`
@@ -37,13 +38,24 @@ exports.Config = Schema.object({
37
38
  comfyuiBaseUrl: Schema.string().default('http://127.0.0.1:8188').description('ComfyUI 地址'),
38
39
  workflow: Schema.string().default('anima_t2i').description('工作流类型(内置 anima_t2i)'),
39
40
  customWorkflowEnabled: Schema.boolean().default(false).description('使用自定义 ComfyUI 工作流 JSON'),
40
- customWorkflowPath: Schema.string().default('').description('自定义工作流 JSON 路径(相对插件目录)'),
41
+ customWorkflowPath: Schema.string().default('').description('自定义工作流 JSON 路径(相对 Koishi 运行目录,例如 data/p-draw/workflows/anima-aesthetic-v1.1.json;插件目录作为回退)'),
41
42
  customWorkflowOverrideParameters: Schema.boolean().default(false).description('用插件参数覆盖自定义工作流参数'),
43
+ customWorkflowReloadOnChange: Schema.boolean().default(true).description('工作流 JSON 变化时自动重载(无需重启插件)'),
44
+ positivePromptNodeId: Schema.string().default('').description('自定义工作流中正面提示词节点 ID(留空自动识别;示例 6,以实际 JSON 为准)'),
45
+ negativePromptNodeId: Schema.string().default('').description('自定义工作流中负面提示词节点 ID(留空自动识别;示例 7,以实际 JSON 为准)'),
46
+ resolutionNodeId: Schema.string().default('').description('自定义工作流中尺寸节点 ID(EmptyLatentImage,可留空;示例 5)'),
47
+ seedNodeId: Schema.string().default('').description('自定义工作流中种子节点 ID(KSampler,可留空;示例 3)'),
48
+ stepsNodeId: Schema.string().default('').description('自定义工作流中步数节点 ID(KSampler,可留空;示例 3)'),
42
49
  timeout: Schema.number().default(300).description('单次生成超时(秒)'),
43
50
  pollInterval: Schema.number().default(2).description('生成状态查询间隔(秒)'),
44
51
 
45
52
  // 模型文件
46
- unetName: Schema.string().default('anima-base-v1.0.safetensors').description('主模型文件名(需与 ComfyUI models/diffusion_models 下的文件名完全一致,含连字符;默认 anima-base-v1.0.safetensors)'),
53
+ unetName: Schema.string().default('anima-aesthetic-v1.1.safetensors').description('主模型文件名(需与 ComfyUI models/diffusion_models 下的文件名完全一致,含连字符)。8G 显存推荐改为 GGUF Q8_0 版(如 anima-aesthetic-v1.1-Q8_0.gguf),插件会自动改用 UnetLoaderGGUF 加载'),
54
+ useGgufUnet: Schema.union([
55
+ Schema.const('auto').description('按模型文件名自动判断(.gguf 用 UnetLoaderGGUF)'),
56
+ Schema.const('true').description('强制使用 UnetLoaderGGUF(需安装 ComfyUI-GGUF)'),
57
+ Schema.const('false').description('强制使用原生 UNETLoader'),
58
+ ]).default('auto').description('主模型加载方式(auto / true / false)'),
47
59
  modelParams: Schema.dict(Schema.object({
48
60
  samplerName: Schema.string().description('采样器(如 er_sde / res_2s / dpmpp_2m)'),
49
61
  scheduler: Schema.string().description('调度器(如 simple / beta57 / normal)'),
@@ -60,13 +72,14 @@ exports.Config = Schema.object({
60
72
  height: Schema.number().default(1216).description('默认高度'),
61
73
  allowedSizes: Schema.array(Schema.string()).default(['832x1216', '896x1152', '1024x1024', '1152x896', '1216x832', '768x1344', '1344x768', '1024x1536']).description('可用尺寸列表(宽x高)'),
62
74
  steps: Schema.number().default(30).description('采样步数'),
63
- cfg: Schema.number().default(4.5).description('CFG 强度'),
75
+ cfg: Schema.number().default(4.0).description('CFG 强度(Aesthetic 1.1 推荐 4,用 3 也常能出更好效果)'),
64
76
  samplerName: Schema.string().default('er_sde').description('采样器'),
65
77
  scheduler: Schema.string().default('simple').description('调度器'),
66
78
 
67
- // 提示词
68
- qualityPrefix: Schema.string().default('masterpiece, best quality, score_7, safe,').description('质量词前缀'),
69
- negativePrompt: Schema.string().default('worst quality, low quality, score_1, score_2, score_3, artist name').description('负面提示词'),
79
+ // 提示词(默认值按 Design.md A4:Aesthetic 1.1 训练时已剥离质量标签,不需要质量前缀)
80
+ qualityPrefix: Schema.string().default('').description('质量词前缀(使用 Aesthetic 1.1 时建议留空;Base 模型可填 masterpiece, best quality, score_7)'),
81
+ skipQualityPrefixForCustomWorkflow: Schema.boolean().default(true).description('启用自定义工作流时自动跳过质量前缀注入(Aesthetic 模型不需要质量标签)'),
82
+ negativePrompt: Schema.string().default('worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts').description('负面提示词(Aesthetic 1.1 推荐值)'),
70
83
  promptOptimizeEnabled: Schema.boolean().default(false).description('启用自然语言优化(需要配置下方 LLM 接口)'),
71
84
  llmBaseUrl: Schema.string().default('').description('LLM 接口地址(OpenAI 兼容,例如 https://api.deepseek.com/v1)'),
72
85
  llmApiKey: Schema.string().role('secret').default('').description('LLM API Key'),
@@ -120,7 +133,7 @@ exports.Config = Schema.object({
120
133
  // 纯函数库已拆分到 lib/(解析 / tag 清洗 / 工作流 / Comfy 等待 / 多人规划 / HTTP 客户端)
121
134
  // ------------------------------------------------------------------
122
135
  const {
123
- normalizeBaseUrl, escapeRe, parseGenerationSize, parseBatchCount, parseSeed,
136
+ normalizeBaseUrl, escapeRe, parseGenerationSize, parseBatchCount, parseSeed, parseStepsCfg,
124
137
  stripRawPrefix, splitPositiveNegativePrompt, parseNameTags, parsePresetList, mergeTagText,
125
138
  } = require('./lib/parse')
126
139
  const {
@@ -128,7 +141,7 @@ const {
128
141
  NO_ARTIST_RE, NO_STYLE_RE,
129
142
  } = require('./lib/tags')
130
143
  const {
131
- buildWorkflow,
144
+ buildWorkflow, inspectCustomWorkflow, isGgufUnet,
132
145
  } = require('./lib/workflows')
133
146
  const { outputImages, waitComfyResult } = require('./lib/comfy')
134
147
  const { materializeImageSource } = require('./lib/media')
@@ -174,19 +187,59 @@ exports.apply = async function apply(ctx, cfg) {
174
187
  // 用户自选模型偏好(userid -> unet 文件名),持久化在 p_draw_config.user_models
175
188
  if (!cfg.userModels || typeof cfg.userModels !== 'object') cfg.userModels = {}
176
189
 
177
- // 启动时清理上次运行遗留的临时目录(先清理,再创建本次目录)
190
+ // 启动时清理上次运行遗留的临时目录(先清理,再创建本次目录)。
191
+ // 目录名带 PID:只清理「进程已退出」的目录,避免并行实例把自己的活跃临时目录删掉
192
+ // (旧版无 PID 后缀的 pdraw-* 视为历史遗留,直接清理)。
193
+ function cleanupStaleTempDirs() {
194
+ try {
195
+ for (const name of fs.readdirSync(os.tmpdir())) {
196
+ if (!name.startsWith('pdraw-')) continue
197
+ const owned = name.match(/^pdraw-(\d+)-/)
198
+ if (owned) {
199
+ const pid = parseInt(owned[1], 10)
200
+ if (pid === process.pid) continue
201
+ try {
202
+ process.kill(pid, 0)
203
+ continue // 进程仍存活,跳过
204
+ } catch (e) { /* 进程已退出,可清理 */ }
205
+ }
206
+ const dir = path.join(os.tmpdir(), name)
207
+ try {
208
+ for (const file of fs.readdirSync(dir)) fs.unlinkSync(path.join(dir, file))
209
+ fs.rmdirSync(dir)
210
+ } catch (e) { /* ignore */ }
211
+ }
212
+ } catch (e) { /* ignore */ }
213
+ }
214
+
215
+ cleanupStaleTempDirs()
216
+
217
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `pdraw-${process.pid}-`))
218
+
219
+ // 自定义工作流目录(Design.md A7:工作流文件由用户从 ComfyUI 导出后放入 data/p-draw/workflows/)
220
+ const workflowDir = path.join(ctx.baseDir || process.cwd(), 'data', 'p-draw', 'workflows')
178
221
  try {
179
- const leftovers = fs.readdirSync(os.tmpdir()).filter((n) => n.startsWith('pdraw-'))
180
- for (const name of leftovers) {
181
- const dir = path.join(os.tmpdir(), name)
182
- try {
183
- for (const file of fs.readdirSync(dir)) fs.unlinkSync(path.join(dir, file))
184
- fs.rmdirSync(dir)
185
- } catch (e) { /* ignore */ }
186
- }
187
- } catch (e) { /* ignore */ }
222
+ fs.mkdirSync(workflowDir, { recursive: true })
223
+ } catch (e) {
224
+ logger.warn(`创建自定义工作流目录失败(${workflowDir}):${e.message}`)
225
+ }
226
+
227
+ // 自定义工作流路径一律相对 Koishi 运行目录解析(见 lib/workflows.js)
228
+ const workflowOpts = () => ({ baseDir: ctx.baseDir || process.cwd() })
229
+
230
+ // A4:自定义工作流(Aesthetic 1.1)默认跳过质量前缀注入
231
+ function shouldSkipQualityPrefix() {
232
+ return Boolean(cfg.customWorkflowEnabled && cfg.skipQualityPrefixForCustomWorkflow)
233
+ }
188
234
 
189
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pdraw-'))
235
+ // A7:自定义工作流启用且质量前缀非空时,提示用户质量标签可能不适用于 Aesthetic 模型
236
+ function qualityPrefixWarning() {
237
+ if (!cfg.customWorkflowEnabled) return ''
238
+ if (!String(cfg.qualityPrefix || '').trim()) return ''
239
+ return shouldSkipQualityPrefix()
240
+ ? '检测到自定义工作流已启用,已自动跳过质量前缀注入;qualityPrefix 对 Aesthetic 模型不生效,建议手动置空。'
241
+ : '检测到自定义工作流已启用,qualityPrefix 可能不适用于 Aesthetic 模型,建议手动置空(或开启 skipQualityPrefixForCustomWorkflow)。'
242
+ }
190
243
 
191
244
  const baseUrl = () => normalizeBaseUrl(cfg.comfyuiBaseUrl)
192
245
 
@@ -259,14 +312,21 @@ exports.apply = async function apply(ctx, cfg) {
259
312
  payload.vram_total_mb = Math.round((device.vram_total || 0) / 1024 / 1024)
260
313
  payload.vram_free_mb = Math.round((device.vram_free || 0) / 1024 / 1024)
261
314
  if (objectInfo) {
262
- const unetList = availableModels(objectInfo, 'UNETLoader', 'unet_name')
315
+ // 主模型列表按实际使用的 loader 读取:GGUF 走 UnetLoaderGGUF,其余走 UNETLoader
316
+ const gguf = isGgufUnet(cfg)
317
+ const unetNode = gguf ? 'UnetLoaderGGUF' : 'UNETLoader'
318
+ const unetList = availableModels(objectInfo, unetNode, 'unet_name')
263
319
  const clipList = availableModels(objectInfo, 'CLIPLoader', 'clip_name')
264
320
  const vaeList = availableModels(objectInfo, 'VAELoader', 'vae_name')
321
+ payload.unet_loader = unetNode
322
+ payload.unet_loader_available = Boolean(objectInfo[unetNode])
265
323
  payload.unet_available = unetList.includes(cfg.unetName)
266
324
  payload.unet_models = unetList
267
325
  payload.clip_available = clipList.includes(cfg.clipName)
268
326
  payload.vae_available = vaeList.includes(cfg.vaeName)
269
327
  } else {
328
+ payload.unet_loader = isGgufUnet(cfg) ? 'UnetLoaderGGUF' : 'UNETLoader'
329
+ payload.unet_loader_available = undefined
270
330
  payload.unet_available = undefined
271
331
  payload.clip_available = undefined
272
332
  payload.vae_available = undefined
@@ -312,7 +372,7 @@ exports.apply = async function apply(ctx, cfg) {
312
372
  `ComfyUI 状态:在线`,
313
373
  `版本:${payload.comfyui_version || '未知'}`,
314
374
  `GPU:${payload.gpu || '未知'}(显存 ${payload.vram_total_mb}MB / 空闲 ${payload.vram_free_mb}MB)`,
315
- `主模型:${cfg.unetName} ${modelStatus(cfg.unetName, payload.unet_available)}`,
375
+ `主模型:${cfg.unetName} ${modelStatus(cfg.unetName, payload.unet_available)}(加载器 ${payload.unet_loader || (isGgufUnet(cfg) ? 'UnetLoaderGGUF' : 'UNETLoader')})`,
316
376
  `文本编码器:${cfg.clipName} ${modelStatus(cfg.clipName, payload.clip_available)}`,
317
377
  `VAE:${cfg.vaeName} ${modelStatus(cfg.vaeName, payload.vae_available)}`,
318
378
  `可用尺寸:${payload.allowed_sizes.join('、')}`,
@@ -323,14 +383,48 @@ exports.apply = async function apply(ctx, cfg) {
323
383
  return lines.join('\n')
324
384
  }
325
385
 
386
+ // 自定义工作流的诊断明细:来源路径 / mtime / 实际解析到的节点 ID / 定位方式
387
+ function customWorkflowDiagLines() {
388
+ const lines = []
389
+ const report = inspectCustomWorkflow(cfg, workflowOpts())
390
+ if (!report.ok && !report.path) {
391
+ lines.push(`自定义工作流:读取失败 — ${report.error}`)
392
+ return lines
393
+ }
394
+ lines.push(`自定义工作流:${report.path}`)
395
+ if (report.mtimeMs) {
396
+ const stamp = new Date(report.mtimeMs)
397
+ lines.push(`工作流更新时间:${stamp.toLocaleString('zh-CN')}(${cfg.customWorkflowReloadOnChange === false ? '变更不自动重载' : '变更自动重载'})`)
398
+ }
399
+ if (!report.ok) {
400
+ lines.push(`自定义工作流:解析失败 — ${report.error}`)
401
+ return lines
402
+ }
403
+ const t = report.targets
404
+ const how = (configured, found) => (configured ? '配置指定' : (found ? '自动识别' : '自动识别(未找到)'))
405
+ const fmt = (ids) => (ids && ids.length ? ids.map(id => `#${id}`).join('、') : '(无)')
406
+ lines.push(`正面提示词节点:${fmt(t.positive)}(${how(cfg.positivePromptNodeId, t.positive.length)})`)
407
+ lines.push(`负面提示词节点:${fmt(t.negative)}(${how(cfg.negativePromptNodeId, t.negative.length)})`)
408
+ lines.push(`尺寸节点:${fmt(t.resolutionIds)}(${how(cfg.resolutionNodeId, t.resolutionIds.length)})`)
409
+ lines.push(`步数节点:${fmt(t.stepsIds)}(${how(cfg.stepsNodeId, t.stepsIds.length)})`)
410
+ lines.push(`种子节点:${fmt(t.seedIds)}(${how(cfg.seedNodeId, t.seedIds.length)})`)
411
+ lines.push(`识别的文本编码节点:${fmt(t.textNodes)}`)
412
+ return lines
413
+ }
414
+
326
415
  async function diagnoseText(session) {
327
416
  const payload = await statusPayload()
328
417
  const lines = ['【p-draw 诊断】']
329
418
  lines.push(`插件版本:${require('./package.json').version || '未知'}`)
330
419
  lines.push(`ComfyUI 地址:${payload.base_url}`)
331
420
  lines.push(`工作流:${cfg.customWorkflowEnabled ? '自定义 ' + (cfg.customWorkflowPath || '(未填写路径)') : (cfg.workflow || 'anima_t2i')}`)
421
+ if (cfg.customWorkflowEnabled) {
422
+ lines.push(...customWorkflowDiagLines())
423
+ }
332
424
  lines.push(`模型:${cfg.unetName} / ${cfg.clipName} / ${cfg.vaeName}`)
425
+ lines.push(`主模型加载器:${payload.unet_loader || (isGgufUnet(cfg) ? 'UnetLoaderGGUF' : 'UNETLoader')}`)
333
426
  lines.push(`默认尺寸:${cfg.width}x${cfg.height},步数 ${cfg.steps},CFG ${cfg.cfg},采样器 ${cfg.samplerName}/${cfg.scheduler}`)
427
+ lines.push(`质量前缀:${String(cfg.qualityPrefix || '').trim() ? '已配置' + (shouldSkipQualityPrefix() ? '(自定义工作流下已跳过)' : '') : '未配置(空)'}`)
334
428
  lines.push(`队列:${cfg.queueEnabled ? '启用(上限 ' + (cfg.queueMaxRequests || '∞') + ')' : '关闭'}`)
335
429
  lines.push(`P 点价格:${cfg.price}`)
336
430
  lines.push(`权限:${cfg.adminOnly ? '仅管理员' : '开放'}`)
@@ -342,6 +436,9 @@ exports.apply = async function apply(ctx, cfg) {
342
436
  lines.push(`版本:${payload.comfyui_version || '未知'}`)
343
437
  lines.push(`GPU:${payload.gpu || '未知'}(显存 ${payload.vram_total_mb}MB / 空闲 ${payload.vram_free_mb}MB)`)
344
438
  lines.push(`模型可用性:主模型${payload.unet_available === undefined ? '(未获取)' : payload.unet_available ? '✓' : '✗'} / 编码器${payload.clip_available === undefined ? '(未获取)' : payload.clip_available ? '✓' : '✗'} / VAE${payload.vae_available === undefined ? '(未获取)' : payload.vae_available ? '✓' : '✗'}`)
439
+ if (payload.unet_loader_available === false) {
440
+ lines.push(`加载器提示:ComfyUI 中没有 ${payload.unet_loader} 节点,请安装 ComfyUI-GGUF 插件,或把 useGgufUnet 设为 false 使用 safetensors 模型。`)
441
+ }
345
442
  if (payload.unet_models && payload.unet_models.length) {
346
443
  lines.push(`可选模型:\n${payload.unet_models.join('\n')}`)
347
444
  }
@@ -352,6 +449,9 @@ exports.apply = async function apply(ctx, cfg) {
352
449
  if (payload.object_info_warning) {
353
450
  lines.push(`模型列表接口:${payload.object_info_warning}(不影响生图)`)
354
451
  }
452
+ // A7:自定义工作流 + 非空 qualityPrefix 的迁移提示
453
+ const warning = qualityPrefixWarning()
454
+ if (warning) lines.push(`⚠ ${warning}`)
355
455
  return lines.join('\n')
356
456
  }
357
457
 
@@ -477,35 +577,35 @@ exports.apply = async function apply(ctx, cfg) {
477
577
  const modelSeed = `当前模型:${unetName},--seed=${seeds.join(',')}`
478
578
  if (isAdmin) return modelSeed
479
579
  return `已扣除 ${totalPrice} P 点,${modelSeed}`
480
- }
481
-
482
- function buildGenerationReply(session, { successCount, count, failures, notes = [] }) {
580
+ }
581
+
582
+ function buildGenerationReply(session, { successCount, count, failures, notes = [] }) {
483
583
  const reply = []
484
584
  if (notes.length) reply.push(notes.join('\n'))
485
585
  if (failures.length) reply.push(session.text('.batch-partial', [successCount, count, failures.length, failures.join(';')]))
486
- return reply.filter(Boolean).join('\n')
487
- }
488
-
489
- function shouldOptimizePerImage({ count, enabled, admin }) {
490
- return count > 1 && (enabled || admin)
491
- }
492
-
493
- async function sendNotices(session, notices, opts = {}) {
494
- const content = notices.filter(Boolean).join('\n')
495
- if (!content) return
496
- try {
497
- const quoteId = session.event?.message?.id || session.messageId
498
- let message = content
499
- if (opts.quote && quoteId) {
500
- const quote = session.platform === 'onebot'
501
- ? h('reply', { id: quoteId })
502
- : h.quote(quoteId)
503
- message = quote + content
504
- }
505
- if (cfg.outputLogs && opts.quote) logger.info(`[p-draw] 发送扣费引用通知 platform=${session.platform || 'unknown'} messageId=${quoteId || 'missing'}`)
506
- await session.send(message)
507
- } catch (e) {
508
- logger.warn(`发送反馈消息失败:${e.message}`)
586
+ return reply.filter(Boolean).join('\n')
587
+ }
588
+
589
+ function shouldOptimizePerImage({ count, enabled, admin }) {
590
+ return count > 1 && (enabled || admin)
591
+ }
592
+
593
+ async function sendNotices(session, notices, opts = {}) {
594
+ const content = notices.filter(Boolean).join('\n')
595
+ if (!content) return
596
+ try {
597
+ const quoteId = session.event?.message?.id || session.messageId
598
+ let message = content
599
+ if (opts.quote && quoteId) {
600
+ const quote = session.platform === 'onebot'
601
+ ? h('reply', { id: quoteId })
602
+ : h.quote(quoteId)
603
+ message = quote + content
604
+ }
605
+ if (cfg.outputLogs && opts.quote) logger.info(`[p-draw] 发送扣费引用通知 platform=${session.platform || 'unknown'} messageId=${quoteId || 'missing'}`)
606
+ await session.send(message)
607
+ } catch (e) {
608
+ logger.warn(`发送反馈消息失败:${e.message}`)
509
609
  }
510
610
  }
511
611
 
@@ -549,6 +649,8 @@ exports.apply = async function apply(ctx, cfg) {
549
649
  const objectInfo = await getObjectInfoCached()
550
650
  const list = [
551
651
  ...availableModels(objectInfo, 'UNETLoader', 'unet_name'),
652
+ // GGUF 模型(ComfyUI-GGUF)同样可供用户选择
653
+ ...availableModels(objectInfo, 'UnetLoaderGGUF', 'unet_name'),
552
654
  ...availableModels(objectInfo, 'CheckpointLoaderSimple', 'ckpt_name')
553
655
  .filter(name => String(name).trim().toLowerCase().replace(/[-_]/g, '~') === 'animagine~xl~3.1.safetensors'),
554
656
  ]
@@ -623,7 +725,7 @@ exports.apply = async function apply(ctx, cfg) {
623
725
  const cfgVal = Number(overrides.cfg) || workCfg.cfg
624
726
  const seed = Number(overrides.seed) || crypto.randomInt(1, 2 ** 32 - 1)
625
727
  const negativePrompt = joinPromptParts([overrides.negativePrompt || cfg.negativePrompt || ''])
626
- const promptBody = buildWorkflow(workCfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, Boolean(size))
728
+ const promptBody = buildWorkflow(workCfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, Boolean(size), workflowOpts())
627
729
 
628
730
  const clientId = crypto.randomUUID()
629
731
  const submit = await comfyPost('/prompt', { prompt: promptBody, client_id: clientId }, 20000)
@@ -874,7 +976,7 @@ exports.apply = async function apply(ctx, cfg) {
874
976
  async function composePrompt(userPrompt, raw, fixedOverride) {
875
977
  if (raw) return { prompt: userPrompt, degraded: false }
876
978
  const parts = []
877
- if (cfg.qualityPrefix) parts.push(String(cfg.qualityPrefix).trim())
979
+ if (cfg.qualityPrefix && !shouldSkipQualityPrefix()) parts.push(String(cfg.qualityPrefix).trim())
878
980
  if (fixedOverride === 'skip') {
879
981
  // 不注入固定角色 tags
880
982
  } else if (typeof fixedOverride === 'string') {
@@ -1156,7 +1258,7 @@ exports.apply = async function apply(ctx, cfg) {
1156
1258
  // 组装最终提示词:质量词 + 画师组 + 主 tag 流(含角色外观)+ narrative 块(仅互动/站位)
1157
1259
  const contentClean = cleanContentTags(commonContent, 65, false, [], true)
1158
1260
  const parts = []
1159
- if (cfg.qualityPrefix) parts.push(String(cfg.qualityPrefix).trim())
1261
+ if (cfg.qualityPrefix && !shouldSkipQualityPrefix()) parts.push(String(cfg.qualityPrefix).trim())
1160
1262
  // 多人同样遵守 no artist 守卫(与单图一致):用户说「不要画师」时跳过画师 tags
1161
1263
  const artistTags = resolveArtistTags(prompt)
1162
1264
  if (artistTags) parts.push(artistTags)
@@ -1385,9 +1487,16 @@ exports.apply = async function apply(ctx, cfg) {
1385
1487
 
1386
1488
  // 批量张数解析(x3 / 3张 / --数量 3 等)
1387
1489
  const parsedBatch = parseBatchCount(parsedSize.prompt, cfg.batchMax)
1388
- const text = parsedBatch.prompt
1490
+ // 采样参数覆盖(--steps 40 / --cfg 3.5),并从描述中剥离,避免进入 LLM 规划
1491
+ const parsedTuning = parseStepsCfg(parsedBatch.prompt)
1492
+ const text = parsedTuning.prompt
1389
1493
  if (!text) return session.text('.multi-usage')
1390
1494
  const count = parsedBatch.count
1495
+ const tuningOverrides = Object.assign(
1496
+ {},
1497
+ parsedTuning.steps != null ? { steps: parsedTuning.steps } : {},
1498
+ parsedTuning.cfg != null ? { cfg: parsedTuning.cfg } : {},
1499
+ )
1391
1500
 
1392
1501
  // P 点校验(按总价 = 张数 × 单价)
1393
1502
  const pcheck = await precheckPoints(session, USERID, isAdmin, count * price)
@@ -1432,7 +1541,7 @@ exports.apply = async function apply(ctx, cfg) {
1432
1541
  }
1433
1542
 
1434
1543
  // 队列:预排队全部任务(先查容量再入队,占满整体退回总价)
1435
- const queued = await enqueueBatch(count, (i) => runComfyGenerate(finalPrompt, size, { negativePrompt: multiNegative, unet }), { USERID, isAdmin, totalPrice: count * price })
1544
+ const queued = await enqueueBatch(count, (i) => runComfyGenerate(finalPrompt, size, Object.assign({ negativePrompt: multiNegative, unet }, tuningOverrides)), { USERID, isAdmin, totalPrice: count * price })
1436
1545
  if (!queued.ok) return queued.message
1437
1546
  const queuedTasks = queued.tasks
1438
1547
  const firstPosition = queued.firstPosition
@@ -1450,7 +1559,7 @@ exports.apply = async function apply(ctx, cfg) {
1450
1559
  if (cfg.queueEnabled) {
1451
1560
  try { result = await queuedTasks[i] } catch (e) { result = { ok: false, message: `生成失败:${e.message}` } }
1452
1561
  } else {
1453
- try { result = await runComfyGenerate(finalPrompt, size, { negativePrompt: multiNegative, unet }) } catch (e) { result = { ok: false, message: `生成失败:${e.message}` } }
1562
+ try { result = await runComfyGenerate(finalPrompt, size, Object.assign({ negativePrompt: multiNegative, unet }, tuningOverrides)) } catch (e) { result = { ok: false, message: `生成失败:${e.message}` } }
1454
1563
  }
1455
1564
  if (!result.ok || !result.outputs || !result.outputs.length) return result
1456
1565
  if (!cfg.multiVerifyEnabled) {
@@ -1486,7 +1595,7 @@ exports.apply = async function apply(ctx, cfg) {
1486
1595
  unetName: unet,
1487
1596
  seeds,
1488
1597
  })
1489
- if (!allOutputs.length) {
1598
+ if (!allOutputs.length) {
1490
1599
  if (cfg.outputLogs) logger.warn(`多人生成全部失败(${USERID}),已按张退款`)
1491
1600
  return session.text('.generate-failed', ['全部失败(已按张退款)'])
1492
1601
  }
@@ -1501,7 +1610,7 @@ exports.apply = async function apply(ctx, cfg) {
1501
1610
  return buildGenerationReply(session, { successCount, count, failures, notes })
1502
1611
  }
1503
1612
 
1504
- // ---------------- 权限 ----------------
1613
+ // ---------------- 权限 ----------------
1505
1614
  function readableOptimizeReason(reason) {
1506
1615
  if (!reason) return ''
1507
1616
  if (reason === 'llm_not_configured') return '(未配置 LLM 模型名或接口地址)'
@@ -1838,9 +1947,20 @@ exports.apply = async function apply(ctx, cfg) {
1838
1947
  const parsedBatch = parseBatchCount(parsedSize.prompt, cfg.batchMax)
1839
1948
  // 固定种子解析(--seed:xxx / --seed xxx / --seed=xxx),并从提示词中剥离
1840
1949
  const parsedSeed = parseSeed(parsedBatch.prompt)
1841
- const text = parsedSeed.prompt
1950
+ // 采样参数覆盖(--steps 40 / --cfg 3.5),并从提示词中剥离
1951
+ const parsedTuning = parseStepsCfg(parsedSeed.prompt)
1952
+ const text = parsedTuning.prompt
1842
1953
  const seed = parsedSeed.seed
1843
1954
  const count = parsedBatch.count
1955
+ // 命令级参数优先于 modelParams 与全局配置(见 runComfyGenerate)
1956
+ const tuningOverrides = Object.assign(
1957
+ {},
1958
+ parsedTuning.steps != null ? { steps: parsedTuning.steps } : {},
1959
+ parsedTuning.cfg != null ? { cfg: parsedTuning.cfg } : {},
1960
+ )
1961
+ if (cfg.outputLogs && (parsedTuning.steps != null || parsedTuning.cfg != null)) {
1962
+ logger.info(`[p-draw] 命令级参数覆盖:steps=${parsedTuning.steps ?? '-'} cfg=${parsedTuning.cfg ?? '-'}`)
1963
+ }
1844
1964
 
1845
1965
  // P 点校验(按总价 = 张数 × 单价)
1846
1966
  // P 点校验(按总价 = 张数 × 单价)
@@ -1871,25 +1991,25 @@ exports.apply = async function apply(ctx, cfg) {
1871
1991
  if (!raw) {
1872
1992
  const globalOpt = cfg.promptOptimizeEnabled
1873
1993
  const adminOpt = !globalOpt && isAdmin && cfg.llmModel && cfg.llmBaseUrl
1874
- const tokenOpt = !globalOpt && !isAdmin && cfg.llmModel && cfg.llmBaseUrl
1875
- if (globalOpt) {
1876
- if (shouldOptimizePerImage({ count, enabled: true, admin: false })) {
1877
- perImageOptimize = true
1878
- } else {
1879
- const optimized = await optimizePrompt(session, userPrompt, false)
1880
- finalPrompt = optimized.prompt
1881
- degraded = !optimized.ok
1882
- optimizedReason = optimized.reason || ''
1883
- }
1884
- } else if (adminOpt) {
1885
- if (shouldOptimizePerImage({ count, enabled: false, admin: true })) {
1886
- perImageOptimize = true
1887
- } else {
1888
- const optimized = await optimizePrompt(session, userPrompt, true)
1889
- finalPrompt = optimized.prompt
1890
- degraded = !optimized.ok
1891
- optimizedReason = optimized.reason || ''
1892
- }
1994
+ const tokenOpt = !globalOpt && !isAdmin && cfg.llmModel && cfg.llmBaseUrl
1995
+ if (globalOpt) {
1996
+ if (shouldOptimizePerImage({ count, enabled: true, admin: false })) {
1997
+ perImageOptimize = true
1998
+ } else {
1999
+ const optimized = await optimizePrompt(session, userPrompt, false)
2000
+ finalPrompt = optimized.prompt
2001
+ degraded = !optimized.ok
2002
+ optimizedReason = optimized.reason || ''
2003
+ }
2004
+ } else if (adminOpt) {
2005
+ if (shouldOptimizePerImage({ count, enabled: false, admin: true })) {
2006
+ perImageOptimize = true
2007
+ } else {
2008
+ const optimized = await optimizePrompt(session, userPrompt, true)
2009
+ finalPrompt = optimized.prompt
2010
+ degraded = !optimized.ok
2011
+ optimizedReason = optimized.reason || ''
2012
+ }
1893
2013
  } else if (tokenOpt) {
1894
2014
  // 全局优化关闭:使用 p-shop 的「提示词优化券」(p_system.llmToken)。
1895
2015
  // 券一次性,按张数扣:x3 扣 3 张,每张图独立做一次 LLM 优化。
@@ -1941,6 +2061,7 @@ exports.apply = async function apply(ctx, cfg) {
1941
2061
  // 用户手写了 negative: 区块时,默认负面词仍保留;用户 tag 只补充未出现的部分。
1942
2062
  const generationOverrides = Object.assign(
1943
2063
  { unet, seed },
2064
+ tuningOverrides,
1944
2065
  userNegativePrompt ? { negativePrompt: mergeNegativePrompts(cfg.negativePrompt, userNegativePrompt) } : {},
1945
2066
  )
1946
2067
 
@@ -2022,7 +2143,7 @@ exports.apply = async function apply(ctx, cfg) {
2022
2143
  unetName: unet,
2023
2144
  seeds,
2024
2145
  })
2025
- if (!allOutputs.length) {
2146
+ if (!allOutputs.length) {
2026
2147
  if (cfg.outputLogs) logger.warn(`生成全部失败(${USERID}),已按张退款`)
2027
2148
  return session.text('.generate-failed', ['全部失败(已按张退款)'])
2028
2149
  }
@@ -2035,7 +2156,7 @@ exports.apply = async function apply(ctx, cfg) {
2035
2156
  await sendNotices(session, [chargeNotice])
2036
2157
 
2037
2158
  return buildGenerationReply(session, { successCount, count, failures })
2038
- }
2159
+ }
2039
2160
  // ---------------- 提示词优化券交互式确认 ----------------
2040
2161
  // 仅全局优化关闭 + 非管理员 + 已配置 LLM(tokenOpt 分支)时进入。
2041
2162
  // 返回:{ cancelled, tokenUsedCount, perImageOptimize, noOptimizeReason }
@@ -2180,5 +2301,5 @@ exports.apply = async function apply(ctx, cfg) {
2180
2301
  })
2181
2302
 
2182
2303
  // 暴露内部接口供自动化测试调用(Koishi 忽略 apply 返回值,不影响生产行为)
2183
- return { couponConfirmFlow, buyCouponsAndConsume, normalizeConfirm, resolveCouponPrice, buildChargeNotice, buildGenerationReply, shouldOptimizePerImage, sendNotices, sendImagesAsForward, executeBatch }
2184
- }
2304
+ return { couponConfirmFlow, buyCouponsAndConsume, normalizeConfirm, resolveCouponPrice, buildChargeNotice, buildGenerationReply, shouldOptimizePerImage, sendNotices, sendImagesAsForward, executeBatch, composePrompt, shouldSkipQualityPrefix, qualityPrefixWarning, customWorkflowDiagLines, diagnoseText, workflowDir }
2305
+ }
package/lib/i18n.js CHANGED
@@ -4,11 +4,18 @@ const zhCN = {
4
4
  comfyuiBaseUrl: { $description: 'ComfyUI 地址' },
5
5
  workflow: { $description: '工作流类型(内置 anima_t2i)' },
6
6
  customWorkflowEnabled: { $description: '使用自定义 ComfyUI 工作流 JSON' },
7
- customWorkflowPath: { $description: '自定义工作流 JSON 路径(相对插件目录)' },
7
+ customWorkflowPath: { $description: '自定义工作流 JSON 路径(相对 Koishi 运行目录,例如 data/p-draw/workflows/anima-aesthetic-v1.1.json;插件目录作为回退)' },
8
8
  customWorkflowOverrideParameters: { $description: '用插件参数覆盖自定义工作流参数' },
9
+ customWorkflowReloadOnChange: { $description: '工作流 JSON 变化时自动重载(无需重启插件)' },
10
+ positivePromptNodeId: { $description: '自定义工作流中正面提示词节点 ID(留空自动识别;示例 6,以实际 JSON 为准)' },
11
+ negativePromptNodeId: { $description: '自定义工作流中负面提示词节点 ID(留空自动识别;示例 7,以实际 JSON 为准)' },
12
+ resolutionNodeId: { $description: '自定义工作流中尺寸节点 ID(EmptyLatentImage,可留空;示例 5)' },
13
+ seedNodeId: { $description: '自定义工作流中种子节点 ID(KSampler,可留空;示例 3)' },
14
+ stepsNodeId: { $description: '自定义工作流中步数节点 ID(KSampler,可留空;示例 3)' },
9
15
  timeout: { $description: '单次生成超时(秒)' },
10
16
  pollInterval: { $description: '生成状态查询间隔(秒)' },
11
- unetName: { $description: '主模型文件名' },
17
+ unetName: { $description: '主模型文件名(8G 显存推荐 GGUF Q8_0 版,插件会自动改用 UnetLoaderGGUF 加载)' },
18
+ useGgufUnet: { $description: '主模型加载方式(auto 按文件名判断 / true 强制 GGUF / false 强制 safetensors)' },
12
19
  clipName: { $description: '文本编码器文件名' },
13
20
  vaeName: { $description: 'VAE 文件名' },
14
21
  width: { $description: '默认宽度' },
@@ -18,8 +25,9 @@ const zhCN = {
18
25
  cfg: { $description: 'CFG 强度' },
19
26
  samplerName: { $description: '采样器' },
20
27
  scheduler: { $description: '调度器' },
21
- qualityPrefix: { $description: '质量词前缀' },
22
- negativePrompt: { $description: '负面提示词' },
28
+ qualityPrefix: { $description: '质量词前缀(使用 Aesthetic 1.1 时建议留空;Base 模型可填 masterpiece, best quality, score_7)' },
29
+ skipQualityPrefixForCustomWorkflow: { $description: '启用自定义工作流时自动跳过质量前缀注入(Aesthetic 模型不需要质量标签)' },
30
+ negativePrompt: { $description: '负面提示词(Aesthetic 1.1 推荐值)' },
23
31
  promptOptimizeEnabled: { $description: '启用自然语言优化(需要配置下方 LLM 接口)' },
24
32
  llmBaseUrl: { $description: 'LLM 接口地址(OpenAI 兼容,例如 https://api.deepseek.com/v1)' },
25
33
  llmApiKey: { $description: 'LLM API Key' },
@@ -62,7 +70,7 @@ const zhCN = {
62
70
  description: '连接本地 ComfyUI 生图,消耗 P 点',
63
71
  messages: {
64
72
  'not-permitted': 'ComfyUI 助手已关闭,或当前用户没有使用权限。',
65
- usage: 'p-draw 帮助(本指令名可自行更换,如 /anm):\n\n【生成】\n p-draw <描述>\n 可加 --seed 数字、x3 / 3张、竖图 / 横图 / 方图\n 无优化 <tags> 可直接使用手写 tags\n\n【多人生成】\n p-draw 多人 <描述>(2-4 人画面,依赖 LLM 规划)\n\n【提示词优化】\n 配置 LLM 后可将自然语言转为 Danbooru tags;普通用户可使用提示词优化券\n\n【画师组】\n 创建 / 追加 / 切换 / 查看 / 删除画师组\n\n【固定角色】\n 添加角色 名称=tags\n\n【模型】\n p-draw 模型(查看) / p-draw 模型 <名称>(切换)/ p-draw 模型 默认(重置)\n\n【状态】\n p-draw 状态\n\n生成图片以合并转发发送,并附对应的 Positive / Negative 提示词;扣费提醒单独引用原指令。',
73
+ usage: 'p-draw 帮助(本指令名可自行更换,如 /anm):\n\n【生成】\n p-draw <描述>\n 可加 --seed 数字、x3 / 3张、竖图 / 横图 / 方图\n 临时覆盖采样参数:--steps 40 / --cfg 3.5\n 无优化 <tags> 可直接使用手写 tags\n\n【多人生成】\n p-draw 多人 <描述>(2-4 人画面,依赖 LLM 规划)\n\n【提示词优化】\n 配置 LLM 后可将自然语言转为 Danbooru tags;普通用户可使用提示词优化券\n\n【画师组】\n 创建 / 追加 / 切换 / 查看 / 删除画师组\n\n【固定角色】\n 添加角色 名称=tags\n\n【模型】\n p-draw 模型(查看) / p-draw 模型 <名称>(切换)/ p-draw 模型 默认(重置)\n\n【状态】\n p-draw 状态\n\n生成图片以合并转发发送,并附对应的 Positive / Negative 提示词;扣费提醒单独引用原指令。',
66
74
  'account-notExists': '君现在还没有 p 点,请先签到哦',
67
75
  'no-enough-p': '君的 p 点不够 {0}p 哦,先去签个到吧qwq',
68
76
  'no-prompt': '请提供画面描述,例如:p-draw 一个女孩,白色裙子',
package/lib/parse.js CHANGED
@@ -152,6 +152,45 @@ function parseSeed(text) {
152
152
  return { seed, prompt: cleaned }
153
153
  }
154
154
 
155
+ // 采样参数覆盖:--steps 40 / --步数 40 / --cfg 3.5 / --强度 3.5
156
+ // 从提示词里剥离并返回 { steps, cfg, prompt };缺失或越界的值返回 null(保持默认)。
157
+ const STEPS_LIMIT = { min: 1, max: 150 }
158
+ const CFG_LIMIT = { min: 0, max: 30 }
159
+
160
+ const STEPS_PATTERN = /(?<!\S)--(?:steps|步数)\s*(?:=|=|:|:)?\s*(\d+)/i
161
+ const CFG_PATTERN = /(?<!\S)--(?:cfg|强度)\s*(?:=|=|:|:)?\s*(\d+(?:\.\d+)?)/i
162
+
163
+ // 与 parseSeed 一致的剥离清理:去掉 token 后收拢多余分隔符与空白
164
+ function stripMatchedToken(prompt, match) {
165
+ return (prompt.slice(0, match.index) + ' ' + prompt.slice(match.index + match[0].length))
166
+ .trim()
167
+ .replace(/^[\s,,;;::]+|[\s,,;;::]+$/g, '')
168
+ .replace(/([,,;;])\s*[,,;;]+/g, '$1')
169
+ .replace(/\s+/g, ' ')
170
+ }
171
+
172
+ function parseStepsCfg(text) {
173
+ let prompt = String(text || '').trim()
174
+ let steps = null
175
+ let cfg = null
176
+
177
+ const stepsMatch = prompt.match(STEPS_PATTERN)
178
+ if (stepsMatch) {
179
+ const value = parseInt(stepsMatch[1], 10)
180
+ prompt = stripMatchedToken(prompt, stepsMatch)
181
+ if (Number.isFinite(value) && value >= STEPS_LIMIT.min) steps = Math.min(value, STEPS_LIMIT.max)
182
+ }
183
+
184
+ const cfgMatch = prompt.match(CFG_PATTERN)
185
+ if (cfgMatch) {
186
+ const value = Number(cfgMatch[1])
187
+ prompt = stripMatchedToken(prompt, cfgMatch)
188
+ if (Number.isFinite(value) && value >= CFG_LIMIT.min) cfg = Math.min(value, CFG_LIMIT.max)
189
+ }
190
+
191
+ return { steps, cfg, prompt }
192
+ }
193
+
155
194
  // ------------------------------------------------------------------
156
195
  // 提示词辅助(移植自 anima prompt_presets)
157
196
  // ------------------------------------------------------------------
@@ -257,6 +296,12 @@ module.exports = {
257
296
  cnNumValue,
258
297
  parseBatchCount,
259
298
  parseSeed,
299
+ STEPS_LIMIT,
300
+ CFG_LIMIT,
301
+ STEPS_PATTERN,
302
+ CFG_PATTERN,
303
+ stripMatchedToken,
304
+ parseStepsCfg,
260
305
  RAW_PREFIXES,
261
306
  stripRawPrefix,
262
307
  splitPositiveNegativePrompt,