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/index.js +405 -179
- package/lib/i18n.js +16 -3
- package/lib/llm.js +153 -0
- package/lib/net.js +85 -0
- package/lib/parse.js +50 -0
- package/lib/workflows.js +100 -9
- package/package.json +1 -1
- package/readme.md +195 -15
package/index.js
CHANGED
|
@@ -26,6 +26,7 @@ exports.usage = `
|
|
|
26
26
|
输出更详细的配置与连通性诊断。
|
|
27
27
|
- **尺寸:** 支持 \`竖图\` \`横图\` \`方图\` \`长竖图\` \`宽屏\` 或在描述中写 \`1024x1536:描述\` / \`--尺寸 1216x832\`。
|
|
28
28
|
- **采样参数:** 描述里可写 \`--steps 40\` / \`--cfg 3.5\`(也可写 \`--步数\` / \`--强度\`)临时覆盖步数与 CFG,优先于 \`modelParams\` 与全局配置。
|
|
29
|
+
- **工作流预设:** 配置里可登记多套工作流 JSON,用 \`--工作流 名称:描述\` 或直接以名称/别名开头(如 \`极速:描述\`)切换;\`画图 工作流\` 可列出所有预设及是否可用。
|
|
29
30
|
- **原样模式:** 描述前加 \`无优化\` 直接提交写好的 tags。
|
|
30
31
|
- **联网搜索:** 描述中带 \`联网\` / \`搜索\` / \`查一下\` 等词时,会先联网搜索补充角色设定(需配置 Tavily Key)。
|
|
31
32
|
- **画师组:** \`创建画师组 名称=tags\` \`切换画师组 名称\` \`查看画师组\` \`删除画师组 名称\`
|
|
@@ -33,17 +34,76 @@ exports.usage = `
|
|
|
33
34
|
`;
|
|
34
35
|
|
|
35
36
|
const { zhCN } = require('./lib/i18n')
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
// 配置分组定义:组名 → 组内扁平键。
|
|
38
|
+
//
|
|
39
|
+
// 控制台里只有「嵌套 object 字段」才会渲染出折叠箭头(intersect 分支是平铺的),
|
|
40
|
+
// 所以这里用嵌套结构换折叠能力;运行时统一摊平成扁平 cfg,
|
|
41
|
+
// 并兼容老版本写在 koishi.yml 里的扁平键。
|
|
42
|
+
const CONFIG_GROUPS = {
|
|
43
|
+
connection: ['comfyuiBaseUrl', 'timeout', 'pollInterval'],
|
|
44
|
+
model: [
|
|
45
|
+
'unetName', 'useGgufUnet', 'clipName', 'vaeName', 'width', 'height',
|
|
46
|
+
'allowedSizes', 'steps', 'cfg', 'samplerName', 'scheduler', 'modelParams',
|
|
47
|
+
],
|
|
48
|
+
prompt: [
|
|
49
|
+
'qualityPrefix', 'negativePrompt', 'styleTags', 'defaultArtistTags',
|
|
50
|
+
'activeArtistPreset', 'artistPresets', 'fixedCharacters',
|
|
51
|
+
],
|
|
52
|
+
queue: ['queueEnabled', 'queueMaxRequests', 'batchMax'],
|
|
53
|
+
pricing: ['price', 'multiPrice', 'couponPrice', 'couponAskTimeout', 'adminUsers'],
|
|
54
|
+
access: ['adminOnly', 'allowedUserIds', 'blockedUserIds', 'allowedGroupIds', 'blockedGroupIds', 'outputLogs'],
|
|
55
|
+
workflow: [
|
|
56
|
+
'customWorkflowEnabled', 'customWorkflowPath', 'skipQualityPrefixForCustomWorkflow',
|
|
57
|
+
'customWorkflowOverrideParameters', 'customWorkflowReloadOnChange',
|
|
58
|
+
'positivePromptNodeId', 'negativePromptNodeId', 'resolutionNodeId', 'seedNodeId', 'stepsNodeId',
|
|
59
|
+
'workflowPresets', 'defaultWorkflowPreset',
|
|
60
|
+
],
|
|
61
|
+
llm: [
|
|
62
|
+
'promptOptimizeEnabled', 'llmBaseUrl', 'llmApiKey', 'llmProxy', 'llmModel', 'llmModels',
|
|
63
|
+
'llmChannels', 'llmChannelOrder', 'llmThinking', 'llmExtraBody', 'llmMaxTokens',
|
|
64
|
+
'promptOptimizeTemplate',
|
|
65
|
+
],
|
|
66
|
+
search: [
|
|
67
|
+
'webSearchEnabled', 'tavilyApiKey', 'tavilyProxy',
|
|
68
|
+
'webSearchMaxResults', 'webSearchDepth', 'webSearchQueryTemplate',
|
|
69
|
+
],
|
|
70
|
+
vision: [
|
|
71
|
+
'multiVerifyEnabled', 'multiVerifyPassScore', 'multiCandidateCount', 'multiSendDegradedCandidate',
|
|
72
|
+
'verifyLlmBaseUrl', 'verifyLlmApiKey', 'verifyLlmProxy', 'verifyLlmModel', 'verifyLlmModels',
|
|
73
|
+
'verifyLlmChannels', 'verifyLlmChannelOrder',
|
|
74
|
+
],
|
|
75
|
+
legacy: ['workflow'],
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 把嵌套配置摊平成扁平 cfg(就地写入,保持对象引用不变)。
|
|
79
|
+
// 优先级:顶层的旧扁平键 > 分组内的值。这样老 koishi.yml 直接可用,
|
|
80
|
+
// 而迁移到新结构后(顶层不再有同名键)就以分组值为准。
|
|
81
|
+
function normalizeConfig(raw) {
|
|
82
|
+
const src = raw && typeof raw === 'object' ? raw : {}
|
|
83
|
+
const known = Object.values(CONFIG_GROUPS).flat()
|
|
84
|
+
const legacy = known.filter(key => Object.prototype.hasOwnProperty.call(src, key))
|
|
85
|
+
|
|
86
|
+
for (const [group, keys] of Object.entries(CONFIG_GROUPS)) {
|
|
87
|
+
const node = src[group]
|
|
88
|
+
if (!node || typeof node !== 'object') continue
|
|
89
|
+
for (const key of keys) {
|
|
90
|
+
// 顶层扁平旧键优先,不被分组值覆盖
|
|
91
|
+
if (legacy.includes(key)) continue
|
|
92
|
+
if (key in node) src[key] = node[key]
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return { config: src, legacy }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// 控制台里每个分组是一个「可折叠小节」:嵌套 object 字段天生带折叠箭头,默认展开。
|
|
99
|
+
exports.Config = Schema.object({
|
|
100
|
+
connection: Schema.object({
|
|
41
101
|
comfyuiBaseUrl: Schema.string().default('http://127.0.0.1:8188').description('ComfyUI 地址'),
|
|
42
102
|
timeout: Schema.number().default(300).description('单次生成超时(秒)'),
|
|
43
103
|
pollInterval: Schema.number().default(2).description('生成状态查询间隔(秒)'),
|
|
44
104
|
}).description('① ComfyUI 连接'),
|
|
45
105
|
|
|
46
|
-
Schema.object({
|
|
106
|
+
model: Schema.object({
|
|
47
107
|
unetName: Schema.string().default('anima-aesthetic-v1.1.safetensors').description('主模型文件名,需与 ComfyUI models/diffusion_models 下的文件名完全一致;8G 显存可填 .gguf 版(插件自动改用 UnetLoaderGGUF)'),
|
|
48
108
|
useGgufUnet: Schema.union([
|
|
49
109
|
Schema.const('auto').description('按文件名自动判断(.gguf → UnetLoaderGGUF)'),
|
|
@@ -59,11 +119,19 @@ exports.Config = Schema.intersect([
|
|
|
59
119
|
cfg: Schema.number().default(4.0).description('CFG 强度(Aesthetic 1.1 推荐 4,用 3 也常更好)'),
|
|
60
120
|
samplerName: Schema.string().default('er_sde').description('采样器'),
|
|
61
121
|
scheduler: Schema.string().default('simple').description('调度器'),
|
|
122
|
+
modelParams: Schema.dict(Schema.object({
|
|
123
|
+
samplerName: Schema.string().description('采样器'),
|
|
124
|
+
scheduler: Schema.string().description('调度器'),
|
|
125
|
+
steps: Schema.number().description('采样步数'),
|
|
126
|
+
cfg: Schema.number().description('CFG 强度'),
|
|
127
|
+
width: Schema.number().description('默认宽度'),
|
|
128
|
+
height: Schema.number().description('默认高度'),
|
|
129
|
+
}).description('该模型的参数覆盖')).default({}).description('按模型覆盖参数:key=模型文件名,value 只填要覆盖的字段。显式写了的字段会覆盖工作流内取值'),
|
|
62
130
|
}).description('② 模型与采样参数'),
|
|
63
131
|
|
|
64
|
-
Schema.object({
|
|
132
|
+
prompt: Schema.object({
|
|
65
133
|
qualityPrefix: Schema.string().default('').description('质量词前缀(Aesthetic 1.1 建议留空;Base 模型可填 masterpiece, best quality, score_7)'),
|
|
66
|
-
negativePrompt: Schema.string().default('worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts').description('
|
|
134
|
+
negativePrompt: Schema.string().default('worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts').description('负面提示词。推荐值就是当前默认值:worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts(Aesthetic 1.1 适用)。若用 Base 模型,可再加 score_4, score_5, score_6'),
|
|
67
135
|
styleTags: Schema.string().default('').description('画风 tags'),
|
|
68
136
|
defaultArtistTags: Schema.string().default('').description('备用画师 tags'),
|
|
69
137
|
activeArtistPreset: Schema.string().default('').description('启用的画师组名称'),
|
|
@@ -71,13 +139,13 @@ exports.Config = Schema.intersect([
|
|
|
71
139
|
fixedCharacters: Schema.array(Schema.string()).default([]).description('固定角色(格式:角色名=tags;仅兼容旧配置,运行时以数据库为准)'),
|
|
72
140
|
}).description('③ 提示词与画师'),
|
|
73
141
|
|
|
74
|
-
Schema.object({
|
|
142
|
+
queue: Schema.object({
|
|
75
143
|
queueEnabled: Schema.boolean().default(true).description('启用生成队列(逐张顺序执行)'),
|
|
76
144
|
queueMaxRequests: Schema.number().default(5).description('队列最大任务数(0 表示不限制)'),
|
|
77
145
|
batchMax: Schema.number().default(4).description('单次指令最多生成的张数'),
|
|
78
146
|
}).description('④ 队列与批量'),
|
|
79
147
|
|
|
80
|
-
Schema.object({
|
|
148
|
+
pricing: Schema.object({
|
|
81
149
|
price: Schema.number().default(500).description('一张图消耗的 P 点'),
|
|
82
150
|
multiPrice: Schema.number().default(900).description('多人指令单张消耗的 P 点'),
|
|
83
151
|
couponPrice: Schema.number().default(3000).description('提示词优化券单价(可被 data/p-shop.json 覆盖)'),
|
|
@@ -85,7 +153,7 @@ exports.Config = Schema.intersect([
|
|
|
85
153
|
adminUsers: Schema.array(Schema.string()).default([]).description('免 P 点管理员用户 ID'),
|
|
86
154
|
}).description('⑤ P 点与优化券'),
|
|
87
155
|
|
|
88
|
-
Schema.object({
|
|
156
|
+
access: Schema.object({
|
|
89
157
|
adminOnly: Schema.boolean().default(false).description('仅管理员可用'),
|
|
90
158
|
allowedUserIds: Schema.array(Schema.string()).default([]).description('用户白名单(留空不限制)'),
|
|
91
159
|
blockedUserIds: Schema.array(Schema.string()).default([]).description('用户黑名单(优先于白名单)'),
|
|
@@ -94,8 +162,7 @@ exports.Config = Schema.intersect([
|
|
|
94
162
|
outputLogs: Schema.boolean().default(true).description('输出详细日志'),
|
|
95
163
|
}).description('⑥ 权限与日志'),
|
|
96
164
|
|
|
97
|
-
|
|
98
|
-
Schema.object({
|
|
165
|
+
workflow: Schema.object({
|
|
99
166
|
customWorkflowEnabled: Schema.boolean().default(false).description('使用自定义 ComfyUI 工作流 JSON'),
|
|
100
167
|
customWorkflowPath: Schema.string().default('').description('工作流 JSON 路径(相对 Koishi 运行目录,如 data/p-draw/workflows/anima-aesthetic-v1.1.json)'),
|
|
101
168
|
skipQualityPrefixForCustomWorkflow: Schema.boolean().default(true).description('启用自定义工作流时跳过质量前缀注入'),
|
|
@@ -103,61 +170,88 @@ exports.Config = Schema.intersect([
|
|
|
103
170
|
customWorkflowReloadOnChange: Schema.boolean().default(true).description('工作流文件变化时自动重载(无需重启)'),
|
|
104
171
|
positivePromptNodeId: Schema.string().default('').description('正面提示词节点 ID(留空自动识别;示例 6,以实际 JSON 为准)'),
|
|
105
172
|
negativePromptNodeId: Schema.string().default('').description('负面提示词节点 ID(留空自动识别;示例 7)'),
|
|
106
|
-
resolutionNodeId: Schema.string().default('').description('尺寸节点 ID
|
|
173
|
+
resolutionNodeId: Schema.string().default('').description('尺寸节点 ID(留空自动识别)'),
|
|
107
174
|
seedNodeId: Schema.string().default('').description('种子节点 ID(KSampler,可留空;示例 3)'),
|
|
108
175
|
stepsNodeId: Schema.string().default('').description('步数节点 ID(KSampler,可留空;示例 3)'),
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
176
|
+
workflowPresets: Schema.dict(Schema.object({
|
|
177
|
+
path: Schema.string().description('工作流 JSON 路径(相对 Koishi 运行目录)'),
|
|
178
|
+
aliases: Schema.array(Schema.string()).description('指令别名,例如 ["极速","fast"]'),
|
|
179
|
+
positivePromptNodeId: Schema.string().description('正面提示词节点 ID(留空自动识别)'),
|
|
180
|
+
negativePromptNodeId: Schema.string().description('负面提示词节点 ID(留空自动识别)'),
|
|
181
|
+
resolutionNodeId: Schema.string().description('尺寸节点 ID(留空自动识别)'),
|
|
182
|
+
seedNodeId: Schema.string().description('种子节点 ID(留空自动识别)'),
|
|
183
|
+
stepsNodeId: Schema.string().description('步数节点 ID(留空自动识别)'),
|
|
184
|
+
steps: Schema.number().description('该预设固定步数(如极速流 4)'),
|
|
185
|
+
cfg: Schema.number().description('该预设固定 CFG'),
|
|
186
|
+
samplerName: Schema.string().description('该预设固定采样器'),
|
|
187
|
+
scheduler: Schema.string().description('该预设固定调度器'),
|
|
188
|
+
overrideParameters: Schema.boolean().description('用上面的参数覆盖工作流内取值'),
|
|
189
|
+
}).description('预设')).default({}).description('工作流预设:key=预设名。指令里用 `--工作流 <名称>` 或名称/别名开头选择(如 `画图 极速:1girl`)'),
|
|
190
|
+
defaultWorkflowPreset: Schema.string().default('').description('默认预设名(留空则用上面的 customWorkflow* 那套)'),
|
|
191
|
+
}).description('⑦ 自定义工作流'),
|
|
192
|
+
|
|
193
|
+
llm: Schema.object({
|
|
123
194
|
promptOptimizeEnabled: Schema.boolean().default(false).description('启用自然语言优化(需配置下面的 LLM 接口)'),
|
|
124
195
|
llmBaseUrl: Schema.string().default('').description('LLM 接口地址(OpenAI 兼容,如 https://api.deepseek.com/v1)'),
|
|
125
196
|
llmApiKey: Schema.string().role('secret').default('').description('LLM API Key'),
|
|
126
|
-
|
|
197
|
+
llmProxy: Schema.string().default('').description('仅 LLM 使用代理(留空直连)。格式 http://127.0.0.1:7890 / socks5://127.0.0.1:7891,可省略 http://;通道内单独填了 proxy 则优先用通道的'),
|
|
198
|
+
llmModel: Schema.string().default('').description('LLM 模型名(旧版单模型;请在 llmModels 里配置,这里留空即可)'),
|
|
199
|
+
llmModels: Schema.array(Schema.string()).default([]).description('主通道的模型名列表,按顺序逐个尝试(如 ["deepseek-chat","gpt-4o-mini"])'),
|
|
200
|
+
llmChannels: Schema.dict(Schema.object({
|
|
201
|
+
baseUrl: Schema.string().description('接口地址(OpenAI 兼容)'),
|
|
202
|
+
apiKey: Schema.string().role('secret').description('API Key'),
|
|
203
|
+
models: Schema.array(Schema.string()).description('该通道的模型名列表,按顺序尝试'),
|
|
204
|
+
proxy: Schema.string().description('该通道专用代理(留空则用上面的 llmProxy)'),
|
|
205
|
+
}).description('通道')).default({}).description('附加通道(中转站/备用站):主通道全部模型都失败后,按顺序继续尝试这些通道'),
|
|
206
|
+
llmChannelOrder: Schema.array(Schema.string()).default([]).description('附加通道的尝试顺序(填通道名;留空则按配置里的先后顺序)'),
|
|
207
|
+
llmThinking: Schema.union([
|
|
208
|
+
Schema.const('auto').description('仅 DeepSeek 系接口发送 thinking(推荐)'),
|
|
209
|
+
Schema.const('always').description('总是发送 thinking'),
|
|
210
|
+
Schema.const('never').description('从不发送 thinking(部分中转站必须选这个)'),
|
|
211
|
+
]).default('auto').description('是否发送 DeepSeek 专有的 thinking 字段;非 DeepSeek 模型带了通常会被拒'),
|
|
212
|
+
llmExtraBody: Schema.string().role('textarea').default('{}').description('附加请求体 JSON(最后覆盖),用于中转站私有参数,如 {"enable_thinking":false}'),
|
|
127
213
|
llmMaxTokens: Schema.number().default(1000).description('LLM 输出上限'),
|
|
128
214
|
promptOptimizeTemplate: Schema.string().description('优化模板(支持 {theme} {search_block} {character_rule} 占位符)').default('你是为 Anima 图像生成模型编写正面提示词的 AI 画师。\n\n请根据用户的原始要求设计一幅完整、协调、具有视觉吸引力的画面,并将结果输出为英文 Danbooru-style tags。\n\n输出要求:\n- 只输出一行英文 tags,使用英文逗号分隔。\n- 不要输出解释、分析、标题、编号、Markdown、代码块或中文。\n- 不要输出 masterpiece、best quality、score 等质量前缀。\n- 不要输出画师 tags;质量词和画师组会由程序另行拼接。\n- 尽量使用模型容易理解的可见画面描述。\n- 保持用户明确指定的角色、主体、人数、关键服装、动作、表情和道具。\n- 除上述明确要求外,可以自由决定服装细节、姿态、构图、镜头、背景、环境、光影、色彩、氛围、前景和特效。\n- 以最终图像协调、精致、有表现力和好看为优先,不需要机械追求固定 Tag 数量。\n- 不要为了数量重复同义词;画面已经完整时即可停止。\n- 请自行解决明显冲突,直接输出你认为最适合生成最终画面的版本。\n\n角色和动态上下文:\n{character_rule}\n{search_block}\n\n用户原始要求:\n{theme}'),
|
|
129
|
-
}).description('
|
|
215
|
+
}).description('⑧ 提示词优化 / LLM'),
|
|
130
216
|
|
|
131
|
-
Schema.object({
|
|
217
|
+
search: Schema.object({
|
|
132
218
|
webSearchEnabled: Schema.boolean().default(false).description('启用联网搜索(指令里写「联网/搜索/查一下」触发)'),
|
|
133
219
|
tavilyApiKey: Schema.string().role('secret').default('').description('Tavily API Key(https://tavily.com)'),
|
|
220
|
+
tavilyProxy: Schema.string().default('').description('仅联网搜索(Tavily)使用代理(留空直连)。与 LLM / 视觉校验的代理互相独立'),
|
|
134
221
|
webSearchMaxResults: Schema.number().default(5).description('搜索结果数量'),
|
|
135
222
|
webSearchDepth: Schema.string().default('basic').description('搜索深度(basic / advanced)'),
|
|
136
223
|
webSearchQueryTemplate: Schema.string().default('{prompt} 角色 外观 立绘 服装 配色 武器 官方图 official art character design outfit appearance wiki fandom').description('搜索词模板({prompt} 代表用户需求)'),
|
|
137
|
-
}).description('
|
|
224
|
+
}).description('⑨ 联网搜索'),
|
|
138
225
|
|
|
139
|
-
Schema.object({
|
|
226
|
+
vision: Schema.object({
|
|
140
227
|
multiVerifyEnabled: Schema.boolean().default(true).description('多人图生成后启用视觉校验'),
|
|
141
228
|
multiVerifyPassScore: Schema.number().default(6).description('校验合格分数(0-10)'),
|
|
142
229
|
multiCandidateCount: Schema.number().default(2).description('候选采样数量(最多重试 候选数-1 次)'),
|
|
143
230
|
multiSendDegradedCandidate: Schema.boolean().default(true).description('全部候选不达标时仍发送最优候选'),
|
|
144
231
|
verifyLlmBaseUrl: Schema.string().default('').description('视觉校验接口地址(OpenAI 兼容;留空跳过校验)'),
|
|
145
232
|
verifyLlmApiKey: Schema.string().role('secret').default('').description('视觉校验 API Key'),
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
233
|
+
verifyLlmProxy: Schema.string().default('').description('仅视觉校验使用代理(留空直连)。通道内单独填了 proxy 则优先用通道的'),
|
|
234
|
+
verifyLlmModel: Schema.string().default('').description('视觉校验模型名(旧版单模型;请在 verifyLlmModels 里配置)'),
|
|
235
|
+
verifyLlmModels: Schema.array(Schema.string()).default([]).description('视觉通道的模型名列表,按顺序逐个尝试(需支持图片输入,如 qwen-vl)'),
|
|
236
|
+
verifyLlmChannels: Schema.dict(Schema.object({
|
|
237
|
+
baseUrl: Schema.string().description('接口地址(OpenAI 兼容)'),
|
|
238
|
+
apiKey: Schema.string().role('secret').description('API Key'),
|
|
239
|
+
models: Schema.array(Schema.string()).description('该通道的模型名列表,按顺序尝试'),
|
|
240
|
+
proxy: Schema.string().description('该通道专用代理(留空则用上面的 verifyLlmProxy)'),
|
|
241
|
+
}).description('通道')).default({}).description('视觉校验的附加通道:主通道全部失败后按顺序继续尝试'),
|
|
242
|
+
verifyLlmChannelOrder: Schema.array(Schema.string()).default([]).description('视觉附加通道的尝试顺序(填通道名;留空则按配置先后顺序)'),
|
|
243
|
+
}).description('⑩ 多人视觉校验'),
|
|
244
|
+
|
|
245
|
+
legacy: Schema.object({
|
|
150
246
|
workflow: Schema.string().default('anima_t2i').description('旧版工作流标识,仅用于状态/诊断显示,内置工作流固定 anima_t2i'),
|
|
151
|
-
}).description('
|
|
152
|
-
]).i18n({
|
|
153
|
-
'zh-CN': zhCN,
|
|
247
|
+
}).description('⑪ 兼容项(旧版,可忽略)'),
|
|
154
248
|
})
|
|
155
249
|
|
|
156
250
|
// ------------------------------------------------------------------
|
|
157
251
|
// 纯函数库已拆分到 lib/(解析 / tag 清洗 / 工作流 / Comfy 等待 / 多人规划 / HTTP 客户端)
|
|
158
252
|
// ------------------------------------------------------------------
|
|
159
253
|
const {
|
|
160
|
-
normalizeBaseUrl, escapeRe, parseGenerationSize, parseBatchCount, parseSeed, parseStepsCfg,
|
|
254
|
+
normalizeBaseUrl, escapeRe, parseGenerationSize, parseBatchCount, parseSeed, parseStepsCfg, parseWorkflowPreset,
|
|
161
255
|
stripRawPrefix, splitPositiveNegativePrompt, parseNameTags, parsePresetList, mergeTagText,
|
|
162
256
|
} = require('./lib/parse')
|
|
163
257
|
const {
|
|
@@ -165,7 +259,7 @@ const {
|
|
|
165
259
|
NO_ARTIST_RE, NO_STYLE_RE,
|
|
166
260
|
} = require('./lib/tags')
|
|
167
261
|
const {
|
|
168
|
-
buildWorkflow, inspectCustomWorkflow, isGgufUnet,
|
|
262
|
+
buildWorkflow, inspectCustomWorkflow, isGgufUnet, inspectWorkflowFile,
|
|
169
263
|
} = require('./lib/workflows')
|
|
170
264
|
const { outputImages, waitComfyResult } = require('./lib/comfy')
|
|
171
265
|
const { materializeImageSource } = require('./lib/media')
|
|
@@ -174,15 +268,27 @@ const {
|
|
|
174
268
|
renderMultiPersonCharacter, multiPersonAutoSize,
|
|
175
269
|
} = require('./lib/multi')
|
|
176
270
|
const { buildComfyClient } = require('./lib/http')
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
271
|
+
const { createOutboundFetch, normalizeProxyUrl, proxySupportAvailable } = require('./lib/net')
|
|
272
|
+
const { buildLlmChain, hasLlm, buildChatBody, runLlmChain } = require('./lib/llm')
|
|
273
|
+
exports.apply = async function apply(ctx, rawConfig) {
|
|
274
|
+
// 配置统一摊平成扁平 cfg:同时接受新的分组写法和老版本的扁平写法
|
|
275
|
+
const { config: cfg, legacy } = normalizeConfig(rawConfig)
|
|
180
276
|
|
|
181
277
|
const logger = ctx.logger('p-draw')
|
|
182
278
|
ctx.i18n.define('zh-CN', zhCN)
|
|
279
|
+
if (legacy.length) {
|
|
280
|
+
logger.warn(`[p-draw] koishi.yml 里仍有扁平旧配置键(${legacy.slice(0, 6).join('、')}${legacy.length > 6 ? ' 等' : ''}),本次已按它们生效;建议迁移到分组结构后删掉旧键,否则控制台里改同名项不会生效。`)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// 出站请求:代理按用途各自传入(联网搜索 / 文本 LLM / 视觉校验互不影响)
|
|
284
|
+
const outboundFetch = createOutboundFetch({
|
|
285
|
+
onWarn: (message) => logger.warn(message),
|
|
286
|
+
})
|
|
287
|
+
|
|
288
|
+
// 注意:不在此处 extend p_system 表 —— 该表由 p-qiandao 等 p 系插件创建。
|
|
289
|
+
// 重复声明同一张表可能导致 Koishi 的 schema 迁移冲突,拖垮签到插件。
|
|
183
290
|
|
|
184
|
-
// 运行时数据持久化到数据库,而不是调用 scope.update
|
|
185
|
-
// 写 koishi.yml:scope.update 会触发插件重载,导致正在生成的图被 dispose(Context has
|
|
291
|
+
// 运行时数据持久化到数据库,而不是调用 scope.update // 写 koishi.yml:scope.update 会触发插件重载,导致正在生成的图被 dispose(Context has
|
|
186
292
|
// been disposed),且重复写入时配置文件会被冲掉(曾出现配置整体恢复成默认)。
|
|
187
293
|
try {
|
|
188
294
|
ctx.model.extend('p_draw_config', {
|
|
@@ -251,6 +357,72 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
251
357
|
// 自定义工作流路径一律相对 Koishi 运行目录解析(见 lib/workflows.js)
|
|
252
358
|
const workflowOpts = () => ({ baseDir: ctx.baseDir || process.cwd() })
|
|
253
359
|
|
|
360
|
+
// ---------------- 工作流预设 ----------------
|
|
361
|
+
// 预设 = 一个 JSON 路径 + 可选的节点 ID / 采样参数覆盖,指令里按名字选用。
|
|
362
|
+
function presetList() {
|
|
363
|
+
const dict = cfg.workflowPresets
|
|
364
|
+
if (!dict || typeof dict !== 'object') return []
|
|
365
|
+
return Object.entries(dict)
|
|
366
|
+
.filter(([, value]) => value && typeof value === 'object')
|
|
367
|
+
.map(([name, value]) => ({ name, aliases: value.aliases || [], ...value }))
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function findPreset(name) {
|
|
371
|
+
if (!name) return null
|
|
372
|
+
return presetList().find(preset => preset.name === name) || null
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// 预设 → 生成用的配置补丁(工作流路径 + 节点 ID + 参数)
|
|
376
|
+
function presetCfgPatch(preset) {
|
|
377
|
+
if (!preset) return {}
|
|
378
|
+
const patch = {
|
|
379
|
+
customWorkflowEnabled: true,
|
|
380
|
+
customWorkflowPath: preset.path || '',
|
|
381
|
+
positivePromptNodeId: preset.positivePromptNodeId || '',
|
|
382
|
+
negativePromptNodeId: preset.negativePromptNodeId || '',
|
|
383
|
+
resolutionNodeId: preset.resolutionNodeId || '',
|
|
384
|
+
seedNodeId: preset.seedNodeId || '',
|
|
385
|
+
stepsNodeId: preset.stepsNodeId || '',
|
|
386
|
+
customWorkflowOverrideParameters: preset.overrideParameters != null
|
|
387
|
+
? Boolean(preset.overrideParameters)
|
|
388
|
+
: Boolean(cfg.customWorkflowOverrideParameters),
|
|
389
|
+
}
|
|
390
|
+
return patch
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// 预设里显式写死的参数,优先级高于 modelParams
|
|
394
|
+
function presetParams(preset) {
|
|
395
|
+
if (!preset) return {}
|
|
396
|
+
const out = {}
|
|
397
|
+
for (const key of ['steps', 'cfg', 'samplerName', 'scheduler', 'width', 'height']) {
|
|
398
|
+
if (preset[key] === undefined || preset[key] === null || preset[key] === '') continue
|
|
399
|
+
out[key] = key === 'samplerName' || key === 'scheduler' ? String(preset[key]).trim() : Number(preset[key])
|
|
400
|
+
}
|
|
401
|
+
return out
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// 体检:这个预设现在能不能真的跑(能否从纯文本启动)
|
|
405
|
+
function inspectPreset(preset) {
|
|
406
|
+
return inspectWorkflowFile(preset.path, {
|
|
407
|
+
positivePromptNodeId: preset.positivePromptNodeId || '',
|
|
408
|
+
negativePromptNodeId: preset.negativePromptNodeId || '',
|
|
409
|
+
resolutionNodeId: preset.resolutionNodeId || '',
|
|
410
|
+
seedNodeId: preset.seedNodeId || '',
|
|
411
|
+
stepsNodeId: preset.stepsNodeId || '',
|
|
412
|
+
customWorkflowReloadOnChange: cfg.customWorkflowReloadOnChange,
|
|
413
|
+
}, workflowOpts())
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// 指令里选了预设时先体检,不可用就给出人话原因
|
|
417
|
+
function checkPresetUsable(name) {
|
|
418
|
+
const preset = findPreset(name)
|
|
419
|
+
if (!preset) return { ok: false, message: `没有名为「${name}」的工作流预设。可用:${presetList().map(p => p.name).join('、') || '(未配置)'}` }
|
|
420
|
+
if (!String(preset.path || '').trim()) return { ok: false, message: `预设「${name}」没有填写 path。` }
|
|
421
|
+
const report = inspectPreset(preset)
|
|
422
|
+
if (!report.ok) return { ok: false, message: `预设「${name}」当前不可用:${report.error}` }
|
|
423
|
+
return { ok: true, preset }
|
|
424
|
+
}
|
|
425
|
+
|
|
254
426
|
// A4:自定义工作流(Aesthetic 1.1)默认跳过质量前缀注入
|
|
255
427
|
function shouldSkipQualityPrefix() {
|
|
256
428
|
return Boolean(cfg.customWorkflowEnabled && cfg.skipQualityPrefixForCustomWorkflow)
|
|
@@ -436,6 +608,44 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
436
608
|
return lines
|
|
437
609
|
}
|
|
438
610
|
|
|
611
|
+
// 预设总览:每个预设能不能跑、需要什么(不实际生图)
|
|
612
|
+
function presetOverviewText() {
|
|
613
|
+
const presets = presetList()
|
|
614
|
+
if (!presets.length) {
|
|
615
|
+
return '还没有配置工作流预设。\n在「⑦ 自定义工作流 → workflowPresets」里添加,key 用预设名,例如:\n workflowPresets:\n 极速4步:\n path: data/p-draw/workflows/03-dmdx.json\n aliases: [极速]'
|
|
616
|
+
}
|
|
617
|
+
const lines = ['工作流预设:']
|
|
618
|
+
for (const preset of presets) {
|
|
619
|
+
const report = inspectPreset(preset)
|
|
620
|
+
const aliases = (preset.aliases || []).length ? `(别名:${preset.aliases.join('、')})` : ''
|
|
621
|
+
lines.push(`${report.ok ? '✅' : '❌'} ${preset.name}${aliases}`)
|
|
622
|
+
if (report.ok) {
|
|
623
|
+
const analysis = report.analysis
|
|
624
|
+
const pos = report.targets.positive.map(id => `#${id}`).join('、')
|
|
625
|
+
const neg = report.targets.negative.map(id => `#${id}`).join('、')
|
|
626
|
+
lines.push(` 节点 ${analysis.nodeCount} 个 · 正面 ${pos} · 负面 ${neg} · 尺寸 ${report.targets.resolutionIds.map(id => `#${id}`).join('、') || '(无)'}`)
|
|
627
|
+
} else {
|
|
628
|
+
lines.push(` 不可用:${report.error}`)
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
const def = String(cfg.defaultWorkflowPreset || '').trim()
|
|
632
|
+
lines.push(`默认预设:${def ? `${def}${findPreset(def) ? '' : '(未找到此预设,已回落)'}` : '(未设置,使用内置/自定义工作流)'}`)
|
|
633
|
+
lines.push('用法:画图 --工作流 <名称>:描述 或 画图 <别名>:描述')
|
|
634
|
+
return lines.join('\n')
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// 诊断里附一段预设摘要
|
|
638
|
+
function presetDiagLines() {
|
|
639
|
+
const presets = presetList()
|
|
640
|
+
if (!presets.length) return []
|
|
641
|
+
const lines = [`工作流预设(${presets.length} 个):`]
|
|
642
|
+
for (const preset of presets) {
|
|
643
|
+
const report = inspectPreset(preset)
|
|
644
|
+
lines.push(` ${report.ok ? '✅' : '❌'} ${preset.name}${report.ok ? '' : ` — ${report.error}`}`)
|
|
645
|
+
}
|
|
646
|
+
return lines
|
|
647
|
+
}
|
|
648
|
+
|
|
439
649
|
async function diagnoseText(session) {
|
|
440
650
|
const payload = await statusPayload()
|
|
441
651
|
const lines = ['【p-draw 诊断】']
|
|
@@ -476,6 +686,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
476
686
|
// A7:自定义工作流 + 非空 qualityPrefix 的迁移提示
|
|
477
687
|
const warning = qualityPrefixWarning()
|
|
478
688
|
if (warning) lines.push(`⚠ ${warning}`)
|
|
689
|
+
lines.push(...presetDiagLines())
|
|
479
690
|
return lines.join('\n')
|
|
480
691
|
}
|
|
481
692
|
|
|
@@ -735,9 +946,15 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
735
946
|
async function runComfyGenerate(prompt, size, overrides) {
|
|
736
947
|
const sizes = parseAllowedSizes()
|
|
737
948
|
const unetName = overrides.unet || cfg.unetName
|
|
738
|
-
//
|
|
949
|
+
// 工作流预设:把路径 / 节点 ID 替换进配置,并取出预设写死的采样参数
|
|
950
|
+
const preset = overrides.preset || null
|
|
951
|
+
const presetExtra = presetParams(preset)
|
|
952
|
+
const baseCfg = preset ? Object.assign({}, cfg, presetCfgPatch(preset)) : cfg
|
|
953
|
+
// 应用该模型的独立参数覆盖(modelParams),再叠加预设参数与命令级 overrides
|
|
739
954
|
const modelSpecific = resolveModelParams(unetName)
|
|
740
|
-
const workCfg = Object.assign({},
|
|
955
|
+
const workCfg = Object.assign({}, baseCfg, modelSpecific, presetExtra, { unetName })
|
|
956
|
+
// 预设/modelParams 里显式配置的字段要覆盖自定义工作流内的取值
|
|
957
|
+
const overrideKeys = Object.assign({}, modelSpecific, presetExtra)
|
|
741
958
|
const requestedWidth = (size && size[0]) || overrides.width || workCfg.width
|
|
742
959
|
const requestedHeight = (size && size[1]) || overrides.height || workCfg.height
|
|
743
960
|
// 防御:sampler/scheduler 配置若带尾随空格会导致 ComfyUI 报 "Value not in list",统一 trim
|
|
@@ -749,7 +966,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
749
966
|
const cfgVal = Number(overrides.cfg) || workCfg.cfg
|
|
750
967
|
const seed = Number(overrides.seed) || crypto.randomInt(1, 2 ** 32 - 1)
|
|
751
968
|
const negativePrompt = joinPromptParts([overrides.negativePrompt || cfg.negativePrompt || ''])
|
|
752
|
-
const promptBody = buildWorkflow(workCfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, Boolean(size), workflowOpts())
|
|
969
|
+
const promptBody = buildWorkflow(workCfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, Boolean(size), Object.assign({}, workflowOpts(), { modelParams: overrideKeys }))
|
|
753
970
|
|
|
754
971
|
const clientId = crypto.randomUUID()
|
|
755
972
|
const submit = await comfyPost('/prompt', { prompt: promptBody, client_id: clientId }, 20000)
|
|
@@ -879,7 +1096,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
879
1096
|
const query = queryTemplate.includes('{prompt}')
|
|
880
1097
|
? queryTemplate.replace(/\{prompt\}/g, prompt).trim()
|
|
881
1098
|
: `${prompt} ${queryTemplate}`.trim()
|
|
882
|
-
const rawRes = await
|
|
1099
|
+
const rawRes = await outboundFetch('https://api.tavily.com/search', {
|
|
883
1100
|
method: 'POST',
|
|
884
1101
|
headers: { 'Content-Type': 'application/json' },
|
|
885
1102
|
body: JSON.stringify({
|
|
@@ -890,7 +1107,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
890
1107
|
topic: 'general',
|
|
891
1108
|
}),
|
|
892
1109
|
signal: controller.signal,
|
|
893
|
-
})
|
|
1110
|
+
}, cfg.tavilyProxy)
|
|
894
1111
|
if (!rawRes.ok) {
|
|
895
1112
|
const bodyText = await rawRes.text().catch(() => '')
|
|
896
1113
|
logger.warn(`联网搜索接口返回错误:HTTP ${rawRes.status} ${bodyText.slice(0, 200)}`)
|
|
@@ -921,12 +1138,77 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
921
1138
|
}
|
|
922
1139
|
}
|
|
923
1140
|
|
|
1141
|
+
// 统一调用 LLM:按「通道 × 模型」候选链逐个尝试,返回首个成功结果。
|
|
1142
|
+
// role='text' 用 llm* 配置,role='vision' 用 verifyLlm* 配置(需支持图片输入)。
|
|
1143
|
+
async function callLlm({ role = 'text', system, user, images, maxTokens = 700, timeout = 120000 }) {
|
|
1144
|
+
const chain = buildLlmChain(cfg, role)
|
|
1145
|
+
if (!chain.length) {
|
|
1146
|
+
return { ok: false, text: '', reason: 'llm_not_configured', candidate: null, errors: [] }
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
const messages = []
|
|
1150
|
+
if (system) messages.push({ role: 'system', content: system })
|
|
1151
|
+
if (images && images.length) {
|
|
1152
|
+
messages.push({
|
|
1153
|
+
role: 'user',
|
|
1154
|
+
content: [
|
|
1155
|
+
...(user ? [{ type: 'text', text: user }] : []),
|
|
1156
|
+
...images.map((src) => ({ type: 'image_url', image_url: { url: src } })),
|
|
1157
|
+
],
|
|
1158
|
+
})
|
|
1159
|
+
} else {
|
|
1160
|
+
messages.push({ role: 'user', content: user })
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
const result = await runLlmChain(chain, async (candidate) => {
|
|
1164
|
+
const controller = new AbortController()
|
|
1165
|
+
const timer = setTimeout(() => controller.abort(), timeout)
|
|
1166
|
+
try {
|
|
1167
|
+
const headers = { 'Content-Type': 'application/json' }
|
|
1168
|
+
if (candidate.apiKey) headers.Authorization = `Bearer ${candidate.apiKey}`
|
|
1169
|
+
const body = buildChatBody(cfg, { candidate, messages, maxTokens, defaultMaxTokens: maxTokens })
|
|
1170
|
+
// 代理按用途分开:通道自带 proxy 优先,否则用该用途的默认代理
|
|
1171
|
+
const purposeProxy = role === 'vision' ? cfg.verifyLlmProxy : cfg.llmProxy
|
|
1172
|
+
const proxy = candidate.proxy || purposeProxy || ''
|
|
1173
|
+
const rawRes = await outboundFetch(candidate.baseUrl + '/chat/completions', {
|
|
1174
|
+
method: 'POST',
|
|
1175
|
+
headers,
|
|
1176
|
+
body: JSON.stringify(body),
|
|
1177
|
+
signal: controller.signal,
|
|
1178
|
+
}, proxy)
|
|
1179
|
+
if (!rawRes.ok) {
|
|
1180
|
+
const detail = await rawRes.text().catch(() => '')
|
|
1181
|
+
throw new Error(`HTTP ${rawRes.status}${detail ? ' ' + detail.slice(0, 200) : ''}`)
|
|
1182
|
+
}
|
|
1183
|
+
const res = await rawRes.json()
|
|
1184
|
+
const text = extractLlmText(res)
|
|
1185
|
+
if (!text) throw new Error('接口未返回可用的文本内容')
|
|
1186
|
+
return text
|
|
1187
|
+
} finally {
|
|
1188
|
+
clearTimeout(timer)
|
|
1189
|
+
}
|
|
1190
|
+
}, {
|
|
1191
|
+
onError: (candidate, message) => {
|
|
1192
|
+
if (cfg.outputLogs) logger.warn(`[p-draw] LLM 候选失败(${candidate.label} / ${candidate.model}):${message}`)
|
|
1193
|
+
},
|
|
1194
|
+
})
|
|
1195
|
+
|
|
1196
|
+
if (!result.ok) {
|
|
1197
|
+
const last = result.errors.length ? result.errors[result.errors.length - 1].message : 'unknown'
|
|
1198
|
+
return { ok: false, text: '', reason: last, candidate: null, errors: result.errors }
|
|
1199
|
+
}
|
|
1200
|
+
if (cfg.outputLogs && (chain.length > 1 || result.errors.length)) {
|
|
1201
|
+
logger.info(`[p-draw] LLM 命中 ${result.candidate.label} / ${result.candidate.model}(前面失败 ${result.errors.length} 个)`)
|
|
1202
|
+
}
|
|
1203
|
+
return { ok: true, text: result.value, candidate: result.candidate, errors: result.errors }
|
|
1204
|
+
}
|
|
1205
|
+
|
|
924
1206
|
async function optimizePrompt(session, userPrompt, force = false, precomputedSearch = null) {
|
|
925
1207
|
if (!cfg.promptOptimizeEnabled && !force) {
|
|
926
1208
|
return { ok: true, prompt: userPrompt, reason: 'optimize_disabled' }
|
|
927
1209
|
}
|
|
928
|
-
if (!cfg
|
|
929
|
-
logger.warn('
|
|
1210
|
+
if (!hasLlm(cfg)) {
|
|
1211
|
+
logger.warn('提示词优化已开启但未配置任何 LLM 通道(llmBaseUrl + llmModels),跳过优化')
|
|
930
1212
|
return { ok: false, prompt: userPrompt, reason: 'llm_not_configured' }
|
|
931
1213
|
}
|
|
932
1214
|
let searchBlock = ''
|
|
@@ -949,50 +1231,17 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
949
1231
|
.replace(/[ \t]+\n/g, '\n')
|
|
950
1232
|
.replace(/\n{3,}/g, '\n\n')
|
|
951
1233
|
.trim()
|
|
952
|
-
const
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
headers,
|
|
962
|
-
body: JSON.stringify({
|
|
963
|
-
model: cfg.llmModel,
|
|
964
|
-
messages: [
|
|
965
|
-
{ role: 'system', content: rendered },
|
|
966
|
-
{ role: 'user', content: userPrompt },
|
|
967
|
-
],
|
|
968
|
-
max_tokens: Math.max(64, parseInt(cfg.llmMaxTokens) || 1000),
|
|
969
|
-
// DeepSeek V4 默认开启思考模式,改为关闭以保证 content 直接返回 tags
|
|
970
|
-
thinking: { type: 'disabled' },
|
|
971
|
-
}),
|
|
972
|
-
signal: controller.signal,
|
|
973
|
-
},
|
|
974
|
-
)
|
|
975
|
-
if (!rawRes.ok) {
|
|
976
|
-
const bodyText = await rawRes.text().catch(() => '')
|
|
977
|
-
const reason = `HTTP ${rawRes.status}${bodyText ? ' ' + bodyText.slice(0, 200) : ''}`
|
|
978
|
-
logger.warn(`提示词优化接口返回错误:${reason}`)
|
|
979
|
-
return { ok: false, prompt: userPrompt, reason }
|
|
980
|
-
}
|
|
981
|
-
const res = await rawRes.json()
|
|
982
|
-
const text = extractLlmText(res)
|
|
983
|
-
if (!text) {
|
|
984
|
-
const reason = '接口未返回可用的文本内容'
|
|
985
|
-
logger.warn(`提示词优化:${reason} 原始响应=${JSON.stringify(res).slice(0, 500)}`)
|
|
986
|
-
return { ok: false, prompt: userPrompt, reason }
|
|
987
|
-
}
|
|
988
|
-
return { ok: true, prompt: text }
|
|
989
|
-
} catch (e) {
|
|
990
|
-
const reason = String(e && e.message || e)
|
|
991
|
-
logger.warn(`提示词优化失败:${reason}`)
|
|
992
|
-
return { ok: false, prompt: userPrompt, reason }
|
|
993
|
-
} finally {
|
|
994
|
-
clearTimeout(timer)
|
|
1234
|
+
const outcome = await callLlm({
|
|
1235
|
+
role: 'text',
|
|
1236
|
+
system: rendered,
|
|
1237
|
+
user: userPrompt,
|
|
1238
|
+
maxTokens: cfg.llmMaxTokens,
|
|
1239
|
+
})
|
|
1240
|
+
if (!outcome.ok) {
|
|
1241
|
+
logger.warn(`提示词优化失败(已尝试 ${outcome.errors.length} 个候选):${outcome.reason}`)
|
|
1242
|
+
return { ok: false, prompt: userPrompt, reason: outcome.reason }
|
|
995
1243
|
}
|
|
1244
|
+
return { ok: true, prompt: outcome.text }
|
|
996
1245
|
}
|
|
997
1246
|
|
|
998
1247
|
// ---------------- 提示词组装 ----------------
|
|
@@ -1024,43 +1273,13 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1024
1273
|
// ---------------- 多人(移植自 anima /anm 多人) ----------------
|
|
1025
1274
|
|
|
1026
1275
|
// 通用 LLM 调用:system + user,返回文本;失败抛错由调用方捕获。
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
const
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
const timer = setTimeout(() => controller.abort(), timeout)
|
|
1033
|
-
try {
|
|
1034
|
-
const headers = { 'Content-Type': 'application/json' }
|
|
1035
|
-
if (resolvedKey) headers.Authorization = `Bearer ${resolvedKey}`
|
|
1036
|
-
const rawRes = await fetch(
|
|
1037
|
-
String(resolvedBase).replace(/\/+$/, '') + '/chat/completions',
|
|
1038
|
-
{
|
|
1039
|
-
method: 'POST',
|
|
1040
|
-
headers,
|
|
1041
|
-
body: JSON.stringify({
|
|
1042
|
-
model: resolvedModel,
|
|
1043
|
-
messages: [
|
|
1044
|
-
{ role: 'system', content: system },
|
|
1045
|
-
{ role: 'user', content: user },
|
|
1046
|
-
],
|
|
1047
|
-
max_tokens: Math.max(64, parseInt(maxTokens) || 700),
|
|
1048
|
-
thinking: { type: 'disabled' },
|
|
1049
|
-
}),
|
|
1050
|
-
signal: controller.signal,
|
|
1051
|
-
},
|
|
1052
|
-
)
|
|
1053
|
-
if (!rawRes.ok) {
|
|
1054
|
-
const bodyText = await rawRes.text().catch(() => '')
|
|
1055
|
-
throw new Error(`HTTP ${rawRes.status}${bodyText ? ' ' + bodyText.slice(0, 200) : ''}`)
|
|
1056
|
-
}
|
|
1057
|
-
const res = await rawRes.json()
|
|
1058
|
-
const text = extractLlmText(res)
|
|
1059
|
-
if (!text) throw new Error('接口未返回可用的文本内容')
|
|
1060
|
-
return text
|
|
1061
|
-
} finally {
|
|
1062
|
-
clearTimeout(timer)
|
|
1276
|
+
// 多人规划用的文本 LLM 调用:统一走「通道 × 模型」回退链,全部失败才抛错。
|
|
1277
|
+
async function llmChat({ system, user, maxTokens = 700, timeout = 120000 }) {
|
|
1278
|
+
const outcome = await callLlm({ role: 'text', system, user, maxTokens, timeout })
|
|
1279
|
+
if (!outcome.ok) {
|
|
1280
|
+
throw new Error(outcome.reason === 'llm_not_configured' ? '未配置任何 LLM 通道' : outcome.reason)
|
|
1063
1281
|
}
|
|
1282
|
+
return outcome.text
|
|
1064
1283
|
}
|
|
1065
1284
|
|
|
1066
1285
|
// 多人规划:让 LLM 输出结构化场景 JSON(2-4 人)。
|
|
@@ -1297,10 +1516,8 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1297
1516
|
|
|
1298
1517
|
// 视觉校验(anima_verify + generation_verifier 移植):对生成的图片跑视觉 LLM,
|
|
1299
1518
|
// 不合格则用相同提示词重试(最多 multiCandidateCount 张),按多候选规则挑选并返回结果。
|
|
1300
|
-
async function verifyGeneratedImages(session, images, userRequest, prompt, size, planCount, unet, negativePrompt) {
|
|
1301
|
-
|
|
1302
|
-
const verifyModel = String(cfg.verifyLlmModel || '').trim()
|
|
1303
|
-
if (!verifyBaseUrl || !verifyModel) {
|
|
1519
|
+
async function verifyGeneratedImages(session, images, userRequest, prompt, size, planCount, unet, negativePrompt, preset = null) {
|
|
1520
|
+
if (!hasLlm(cfg, 'vision')) {
|
|
1304
1521
|
return { ok: true, degraded: true, message: '', verdict: null, outputs: images, prompt, negativePrompt }
|
|
1305
1522
|
}
|
|
1306
1523
|
const passScore = Math.max(0, Math.min(10, parseInt(cfg.multiVerifyPassScore) || 6))
|
|
@@ -1314,38 +1531,17 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1314
1531
|
let currentPrompt = prompt
|
|
1315
1532
|
let currentNegativePrompt = negativePrompt
|
|
1316
1533
|
|
|
1534
|
+
// 视觉校验同样走「通道 × 模型」回退链(role='vision' 用 verifyLlm* 配置)
|
|
1317
1535
|
async function verifyOnce(imgs, userReq) {
|
|
1318
|
-
const
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
method: 'POST',
|
|
1328
|
-
headers,
|
|
1329
|
-
body: JSON.stringify({
|
|
1330
|
-
model: verifyModel,
|
|
1331
|
-
messages: [
|
|
1332
|
-
{ role: 'system', content: systemPrompt },
|
|
1333
|
-
{ role: 'user', content: [{ type: 'text', text: `用户的原始画图请求(中文):\n${userReq}\n\n请审查这张图片。` }, ...content] },
|
|
1334
|
-
],
|
|
1335
|
-
max_tokens: Math.max(256, parseInt(cfg.llmMaxTokens) || 700),
|
|
1336
|
-
}),
|
|
1337
|
-
signal: controller.signal,
|
|
1338
|
-
},
|
|
1339
|
-
)
|
|
1340
|
-
if (!rawRes.ok) {
|
|
1341
|
-
const bodyText = await rawRes.text().catch(() => '')
|
|
1342
|
-
throw new Error(`HTTP ${rawRes.status}${bodyText ? ' ' + bodyText.slice(0, 200) : ''}`)
|
|
1343
|
-
}
|
|
1344
|
-
const res = await rawRes.json()
|
|
1345
|
-
return extractLlmText(res)
|
|
1346
|
-
} finally {
|
|
1347
|
-
clearTimeout(timer)
|
|
1348
|
-
}
|
|
1536
|
+
const outcome = await callLlm({
|
|
1537
|
+
role: 'vision',
|
|
1538
|
+
system: systemPrompt,
|
|
1539
|
+
user: `用户的原始画图请求(中文):\n${userReq}\n\n请审查这张图片。`,
|
|
1540
|
+
images: imgs,
|
|
1541
|
+
maxTokens: Math.max(256, parseInt(cfg.llmMaxTokens) || 700),
|
|
1542
|
+
})
|
|
1543
|
+
if (!outcome.ok) throw new Error(outcome.reason)
|
|
1544
|
+
return outcome.text
|
|
1349
1545
|
}
|
|
1350
1546
|
|
|
1351
1547
|
function extractVerifyJson(text) {
|
|
@@ -1432,7 +1628,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1432
1628
|
if (hint) {
|
|
1433
1629
|
currentPrompt = `${userRequest}\n【上次问题,请修正】${hint}`
|
|
1434
1630
|
}
|
|
1435
|
-
const regen = await runComfyGenerate(currentPrompt, size, { unet, negativePrompt: currentNegativePrompt })
|
|
1631
|
+
const regen = await runComfyGenerate(currentPrompt, size, Object.assign({ unet, negativePrompt: currentNegativePrompt }, preset ? { preset } : {}))
|
|
1436
1632
|
if (!regen.ok) {
|
|
1437
1633
|
logger.warn(`多人校验重试生成失败:${regen.message}`)
|
|
1438
1634
|
break
|
|
@@ -1513,11 +1709,24 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1513
1709
|
const parsedBatch = parseBatchCount(parsedSize.prompt, cfg.batchMax)
|
|
1514
1710
|
// 采样参数覆盖(--steps 40 / --cfg 3.5),并从描述中剥离,避免进入 LLM 规划
|
|
1515
1711
|
const parsedTuning = parseStepsCfg(parsedBatch.prompt)
|
|
1516
|
-
|
|
1712
|
+
// 工作流预设(多人生图同样支持)
|
|
1713
|
+
const parsedPreset = parseWorkflowPreset(parsedTuning.prompt, presetList())
|
|
1714
|
+
if (parsedPreset.error) return parsedPreset.error
|
|
1715
|
+
let activePreset = null
|
|
1716
|
+
if (parsedPreset.preset) {
|
|
1717
|
+
const usable = checkPresetUsable(parsedPreset.preset)
|
|
1718
|
+
if (!usable.ok) return usable.message
|
|
1719
|
+
activePreset = usable.preset
|
|
1720
|
+
} else if (String(cfg.defaultWorkflowPreset || '').trim()) {
|
|
1721
|
+
const usable = checkPresetUsable(String(cfg.defaultWorkflowPreset).trim())
|
|
1722
|
+
if (usable.ok) activePreset = usable.preset
|
|
1723
|
+
else if (cfg.outputLogs) logger.warn(`[p-draw] 默认预设不可用,已回落:${usable.message}`)
|
|
1724
|
+
}
|
|
1725
|
+
const text = parsedPreset.prompt
|
|
1517
1726
|
if (!text) return session.text('.multi-usage')
|
|
1518
1727
|
const count = parsedBatch.count
|
|
1519
1728
|
const tuningOverrides = Object.assign(
|
|
1520
|
-
{},
|
|
1729
|
+
activePreset ? { preset: activePreset } : {},
|
|
1521
1730
|
parsedTuning.steps != null ? { steps: parsedTuning.steps } : {},
|
|
1522
1731
|
parsedTuning.cfg != null ? { cfg: parsedTuning.cfg } : {},
|
|
1523
1732
|
)
|
|
@@ -1537,7 +1746,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1537
1746
|
if (!ready.ok) return ready.message
|
|
1538
1747
|
|
|
1539
1748
|
// 多人规划(强制依赖 LLM)
|
|
1540
|
-
if (!cfg
|
|
1749
|
+
if (!hasLlm(cfg)) {
|
|
1541
1750
|
return session.text('.multi-no-llm')
|
|
1542
1751
|
}
|
|
1543
1752
|
|
|
@@ -1589,7 +1798,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1589
1798
|
if (!cfg.multiVerifyEnabled) {
|
|
1590
1799
|
return { ok: true, outputs: result.outputs, seed: result.seed, prompt: finalPrompt, negativePrompt: result.negativePrompt, note: session.text('.multi-degraded', ['(未启用校验或未配置视觉模型)']) }
|
|
1591
1800
|
}
|
|
1592
|
-
const verified = await verifyGeneratedImages(session, result.outputs, text, finalPrompt, size, plan.characters.length, unet, result.negativePrompt || multiNegative)
|
|
1801
|
+
const verified = await verifyGeneratedImages(session, result.outputs, text, finalPrompt, size, plan.characters.length, unet, result.negativePrompt || multiNegative, activePreset)
|
|
1593
1802
|
if (!verified.ok) return { ok: false, message: verified.message }
|
|
1594
1803
|
return { ok: true, outputs: verified.outputs, seed: result.seed, prompt: verified.prompt || finalPrompt, negativePrompt: verified.negativePrompt || result.negativePrompt || multiNegative, note: verified.message || '' }
|
|
1595
1804
|
}
|
|
@@ -1813,6 +2022,9 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1813
2022
|
if (lower === '诊断' || lower === 'diagnose' || lower === '部署诊断' || lower === 'debug' || lower === '调试' || lower === '调试状态') {
|
|
1814
2023
|
return await diagnoseText(session)
|
|
1815
2024
|
}
|
|
2025
|
+
if (lower === '工作流' || lower === '预设' || lower === 'workflow' || lower === 'workflows') {
|
|
2026
|
+
return presetOverviewText()
|
|
2027
|
+
}
|
|
1816
2028
|
|
|
1817
2029
|
// 多人指令:p-draw 多人 <描述>
|
|
1818
2030
|
const multiMatch = text.match(/^(?:多人|多人生图|双人|三人|群像)\s*(.*)$/)
|
|
@@ -1973,12 +2185,26 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1973
2185
|
const parsedSeed = parseSeed(parsedBatch.prompt)
|
|
1974
2186
|
// 采样参数覆盖(--steps 40 / --cfg 3.5),并从提示词中剥离
|
|
1975
2187
|
const parsedTuning = parseStepsCfg(parsedSeed.prompt)
|
|
1976
|
-
|
|
2188
|
+
// 工作流预设:--工作流 xxx 或开头裸写名称/别名
|
|
2189
|
+
const parsedPreset = parseWorkflowPreset(parsedTuning.prompt, presetList())
|
|
2190
|
+
if (parsedPreset.error) return parsedPreset.error
|
|
2191
|
+
let activePreset = null
|
|
2192
|
+
if (parsedPreset.preset) {
|
|
2193
|
+
const usable = checkPresetUsable(parsedPreset.preset)
|
|
2194
|
+
if (!usable.ok) return usable.message
|
|
2195
|
+
activePreset = usable.preset
|
|
2196
|
+
} else if (String(cfg.defaultWorkflowPreset || '').trim()) {
|
|
2197
|
+
// 默认预设不可用时不阻断生成,回落到 customWorkflow* / 内置工作流
|
|
2198
|
+
const usable = checkPresetUsable(String(cfg.defaultWorkflowPreset).trim())
|
|
2199
|
+
if (usable.ok) activePreset = usable.preset
|
|
2200
|
+
else if (cfg.outputLogs) logger.warn(`[p-draw] 默认预设不可用,已回落:${usable.message}`)
|
|
2201
|
+
}
|
|
2202
|
+
const text = parsedPreset.prompt
|
|
1977
2203
|
const seed = parsedSeed.seed
|
|
1978
2204
|
const count = parsedBatch.count
|
|
1979
|
-
//
|
|
2205
|
+
// 命令级参数优先于预设 / modelParams / 全局配置(见 runComfyGenerate)
|
|
1980
2206
|
const tuningOverrides = Object.assign(
|
|
1981
|
-
{},
|
|
2207
|
+
activePreset ? { preset: activePreset } : {},
|
|
1982
2208
|
parsedTuning.steps != null ? { steps: parsedTuning.steps } : {},
|
|
1983
2209
|
parsedTuning.cfg != null ? { cfg: parsedTuning.cfg } : {},
|
|
1984
2210
|
)
|
|
@@ -2014,8 +2240,8 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
2014
2240
|
let interactiveCoupon = false
|
|
2015
2241
|
if (!raw) {
|
|
2016
2242
|
const globalOpt = cfg.promptOptimizeEnabled
|
|
2017
|
-
const adminOpt = !globalOpt && isAdmin && cfg
|
|
2018
|
-
const tokenOpt = !globalOpt && !isAdmin && cfg
|
|
2243
|
+
const adminOpt = !globalOpt && isAdmin && hasLlm(cfg)
|
|
2244
|
+
const tokenOpt = !globalOpt && !isAdmin && hasLlm(cfg)
|
|
2019
2245
|
if (globalOpt) {
|
|
2020
2246
|
if (shouldOptimizePerImage({ count, enabled: true, admin: false })) {
|
|
2021
2247
|
perImageOptimize = true
|
|
@@ -2325,5 +2551,5 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
2325
2551
|
})
|
|
2326
2552
|
|
|
2327
2553
|
// 暴露内部接口供自动化测试调用(Koishi 忽略 apply 返回值,不影响生产行为)
|
|
2328
|
-
return { couponConfirmFlow, buyCouponsAndConsume, normalizeConfirm, resolveCouponPrice, buildChargeNotice, buildGenerationReply, shouldOptimizePerImage, sendNotices, sendImagesAsForward, executeBatch, composePrompt, shouldSkipQualityPrefix, qualityPrefixWarning, customWorkflowDiagLines, diagnoseText, workflowDir }
|
|
2554
|
+
return { couponConfirmFlow, buyCouponsAndConsume, normalizeConfirm, resolveCouponPrice, buildChargeNotice, buildGenerationReply, shouldOptimizePerImage, sendNotices, sendImagesAsForward, executeBatch, composePrompt, shouldSkipQualityPrefix, qualityPrefixWarning, customWorkflowDiagLines, diagnoseText, workflowDir, normalizeConfig, presetList, presetOverviewText }
|
|
2329
2555
|
}
|