@kevlns/art-workshop 0.1.2 → 0.2.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/AGENTS.md +61 -11
- package/README.md +72 -93
- package/art-workshop.mjs +35 -9
- package/docs/commands.md +82 -0
- package/docs/configuration.md +166 -0
- package/docs/core-guidance.md +80 -13
- package/docs/data-formats.md +167 -0
- package/docs/modes.md +140 -0
- package/docs/troubleshooting.md +84 -0
- package/docs//351/227/256/351/242/230/346/212/245/345/221/212-2026-10-08.md +29 -0
- package/lib/agent.mjs +3 -2
- package/lib/backends.mjs +89 -0
- package/lib/comfyui.mjs +62 -0
- package/lib/design.mjs +29 -0
- package/lib/diagnostics.mjs +83 -0
- package/lib/executor.mjs +10 -6
- package/lib/generate.mjs +6 -4
- package/lib/plan.mjs +6 -3
- package/lib/presentation.mjs +2 -2
- package/lib/providers.mjs +25 -0
- package/lib/runtime.mjs +23 -0
- package/lib/service.mjs +96 -0
- package/lib/settings.mjs +3 -2
- package/lib/shared.mjs +12 -2
- package/lib/task-worker.mjs +58 -0
- package/lib/tasks.mjs +81 -0
- package/lib/workflows.mjs +19 -0
- package/package.json +7 -5
- package/skills/art-workshop/SKILL.md +59 -13
- package/v-cli.plugin.json +250 -15
- package/workflows/vant-builtin-qwen-image-2.1-Q4-8GB.api.json +116 -0
- package/workflows/vant-builtin-qwen-image-2.1-Q4-8GB.json +648 -0
package/lib/service.mjs
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import {spawn,execFileSync} from 'node:child_process';
|
|
2
|
+
import {openSync,closeSync,existsSync} from 'node:fs';
|
|
3
|
+
import {join,resolve} from 'node:path';
|
|
4
|
+
import {writeJson,hash} from './shared.mjs';
|
|
5
|
+
import {http,sleep,locked,stateRead,alive} from './runtime.mjs';
|
|
6
|
+
import {inspectEnvironment,workflowError} from './diagnostics.mjs';
|
|
7
|
+
|
|
8
|
+
export function processIdentity(pid) {
|
|
9
|
+
if(!Number.isSafeInteger(pid)||pid<1)return null;
|
|
10
|
+
try {
|
|
11
|
+
if(process.platform==='win32') {
|
|
12
|
+
const script=`$p=Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"; if($p){[pscustomobject]@{pid=$p.ProcessId;exe=$p.ExecutablePath;created=$p.CreationDate.ToUniversalTime().ToString('o');command=$p.CommandLine}|ConvertTo-Json -Compress}`;
|
|
13
|
+
const output=execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true}).trim();
|
|
14
|
+
return output?JSON.parse(output):null;
|
|
15
|
+
}
|
|
16
|
+
const created=execFileSync('ps',['-p',String(pid),'-o','lstart='],{encoding:'utf8'}).trim();
|
|
17
|
+
const command=execFileSync('ps',['-p',String(pid),'-o','args='],{encoding:'utf8'}).trim();
|
|
18
|
+
return created?{pid,created,command}:null;
|
|
19
|
+
}catch{return null;}
|
|
20
|
+
}
|
|
21
|
+
export async function stopIdentity(identity,{timeout=10000}={}) {
|
|
22
|
+
const current=processIdentity(identity.pid);
|
|
23
|
+
if(!current)return;
|
|
24
|
+
if(hash(current)!==hash(identity))throw new Error('服务进程身份已变化,拒绝终止复用的 PID');
|
|
25
|
+
if(process.platform==='win32')execFileSync('taskkill.exe',['/PID',String(identity.pid),'/T','/F'],{windowsHide:true});
|
|
26
|
+
else process.kill(identity.pid,'SIGTERM');
|
|
27
|
+
const deadline=Date.now()+timeout;
|
|
28
|
+
while(alive(identity.pid)){if(Date.now()>deadline)throw new Error('服务进程未停止');await sleep(100);}
|
|
29
|
+
}
|
|
30
|
+
export async function healthy(endpoint,backend) {
|
|
31
|
+
try {
|
|
32
|
+
const stats=await http(endpoint,'/system_stats',{timeout:2000});if(!stats.system?.comfyui_version)return false;
|
|
33
|
+
const [major,minor]=stats.system.comfyui_version.split('.').map(Number);
|
|
34
|
+
if(major===0&&minor<39)return false;
|
|
35
|
+
if(backend.template){const nodes=await http(endpoint,'/object_info',{timeout:4000});for(const n of Object.values(backend.template))if(!nodes[n.class_type])return false;}
|
|
36
|
+
return stats;
|
|
37
|
+
}catch{return false;}
|
|
38
|
+
}
|
|
39
|
+
function serviceFile(root,endpoint){return join(root,'services',hash(endpoint)+'.json');}
|
|
40
|
+
export function externalIdentity(endpoint,launch) {
|
|
41
|
+
if(process.platform!=='win32'||!launch)return null;
|
|
42
|
+
const port=Number(new URL(endpoint).port||80);
|
|
43
|
+
const script=`Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique | ConvertTo-Json -Compress`;
|
|
44
|
+
let pids;try{pids=JSON.parse(execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true}).trim()||'null');}catch{return null;}
|
|
45
|
+
for(const pid of [].concat(pids??[])) {
|
|
46
|
+
const p=processIdentity(pid);
|
|
47
|
+
if(!p?.exe||resolve(p.exe).toLowerCase()!==resolve(launch.executable).toLowerCase())continue;
|
|
48
|
+
// Require the configured entrypoint, not just a Python interpreter or an occupied port.
|
|
49
|
+
const entry=launch.args.find(x=>/main\.py$|\.mjs$|\.js$/.test(x));
|
|
50
|
+
if(!entry||!p.command.toLowerCase().includes(entry.toLowerCase()))continue;
|
|
51
|
+
return p;
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
export async function ensureService(backend,root,{cancelled=()=>false}={}) {
|
|
56
|
+
return locked(root,'services',async()=>{
|
|
57
|
+
if(stateRead(join(root,'shutdown.json')))throw new Error('服务正在 shutdown');
|
|
58
|
+
const incompatible=[];
|
|
59
|
+
for(const endpoint of backend.endpoints) {
|
|
60
|
+
let report;try{report=await inspectEnvironment(endpoint,backend);}catch{continue;}
|
|
61
|
+
if(!report.ok){incompatible.push(report);continue;}
|
|
62
|
+
const file=serviceFile(root,endpoint),previous=stateRead(file);
|
|
63
|
+
const identity=previous?.identity&&hash(processIdentity(previous.identity.pid))===hash(previous.identity)?previous.identity:externalIdentity(endpoint,backend.launch);
|
|
64
|
+
writeJson(file,{endpoint,backend:backend.id,identity,owned:previous?.owned??false,observedAt:new Date().toISOString()});
|
|
65
|
+
return endpoint;
|
|
66
|
+
}
|
|
67
|
+
if(incompatible.length){const error=workflowError('现有 ComfyUI 环境无法执行工作流',backend,{stage:'environment'});error.diagnostic.environments=incompatible;throw error;}
|
|
68
|
+
if(!backend.launch)throw new Error('没有可用 ComfyUI,也未配置 launch');
|
|
69
|
+
if(cancelled())throw new Error('任务已取消');
|
|
70
|
+
const endpoint=backend.endpoints[0],file=serviceFile(root,endpoint),previous=stateRead(file);
|
|
71
|
+
if(previous?.identity&&hash(processIdentity(previous.identity.pid))===hash(previous.identity))throw new Error('现有服务不健康,请先 shutdown;不重复启动');
|
|
72
|
+
const logPath=join(root,'comfyui-'+hash(endpoint).slice(0,8)+'.log'),fd=openSync(logPath,'a');
|
|
73
|
+
const child=spawn(backend.launch.executable,backend.launch.args,{cwd:backend.launch.cwd,detached:true,windowsHide:true,stdio:['ignore',fd,fd]});closeSync(fd);
|
|
74
|
+
let spawnError;child.once('error',error=>{spawnError=error;});child.unref();
|
|
75
|
+
await sleep(100);
|
|
76
|
+
if(spawnError||!child.pid)throw spawnError??new Error('服务启动失败');
|
|
77
|
+
const identity=processIdentity(child.pid);if(!identity)throw new Error('无法记录服务进程身份');
|
|
78
|
+
writeJson(file,{endpoint,backend:backend.id,identity,owned:true,logPath});
|
|
79
|
+
const deadline=Date.now()+(backend.launch.startupTimeoutSeconds??120)*1000;
|
|
80
|
+
try {
|
|
81
|
+
while(Date.now()<deadline){if(cancelled())throw new Error('任务已取消');let report;try{report=await inspectEnvironment(endpoint,backend);}catch{};if(report?.ok)return endpoint;if(report){const error=workflowError('启动后的 ComfyUI 环境无法执行工作流,查看 '+logPath,backend,{stage:'environment'});error.diagnostic.environments=[report];throw error;}if(!alive(child.pid))throw new Error('ComfyUI 进程提前退出,查看 '+logPath);await sleep(300);}
|
|
82
|
+
throw new Error('ComfyUI 启动超时,查看 '+logPath);
|
|
83
|
+
}catch(error){await stopIdentity(identity);throw error;}
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
export function rememberedService(root,endpoint){return stateRead(serviceFile(root,endpoint));}
|
|
87
|
+
export async function closeService(root,endpoint,backend) {
|
|
88
|
+
const remembered=rememberedService(root,endpoint);
|
|
89
|
+
const previous=remembered?.identity;
|
|
90
|
+
const identity=previous&&hash(processIdentity(previous.pid))===hash(previous)?previous:externalIdentity(endpoint,backend.launch);
|
|
91
|
+
if(!identity){if(await healthy(endpoint,backend))throw new Error('无法验证服务进程身份:'+endpoint);return {endpoint,stopped:false};}
|
|
92
|
+
await stopIdentity(identity);
|
|
93
|
+
if(await healthy(endpoint,backend))throw new Error('关闭进程后服务仍可访问:'+endpoint);
|
|
94
|
+
writeJson(serviceFile(root,endpoint),{endpoint,stopped:true,stoppedAt:new Date().toISOString()});
|
|
95
|
+
return {endpoint,stopped:true};
|
|
96
|
+
}
|
package/lib/settings.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import {dirname,basename,join,resolve,relative,isAbsolute} from 'node:path';
|
|
|
5
5
|
import {fileURLToPath} from 'node:url';
|
|
6
6
|
import {readJson,writeJson,keys,text,id} from './shared.mjs';
|
|
7
7
|
import {execution} from './plan.mjs';
|
|
8
|
+
import {generationConfig} from './backends.mjs';
|
|
8
9
|
export const TOOL_ROOT=dirname(dirname(fileURLToPath(import.meta.url)));
|
|
9
10
|
export function downloadsDirectory({platform=process.platform,home=homedir(),env=process.env,knownFolder}={}) {
|
|
10
11
|
if(platform==='win32') {
|
|
@@ -34,7 +35,7 @@ export function configFile(env=process.env,home=homedir(),platform=process.platf
|
|
|
34
35
|
export function loadSettings({file=configFile(),workspace,output,refs,cache}={}) {
|
|
35
36
|
const base=join(downloadsDirectory(),'image.g');
|
|
36
37
|
const local=existsSync(file)?readJson(file):{};
|
|
37
|
-
keys(local,['paths','execution','analysisModel','defaultProject','autoSyncSkills'],'config');
|
|
38
|
+
keys(local,['paths','execution','generation','analysisModel','defaultProject','autoSyncSkills'],'config');
|
|
38
39
|
keys(local.paths??{},['workspace','output','refs','cache'],'config.paths');
|
|
39
40
|
keys(local.execution??{},['model','size','promptExtend','perValue','watermark'],'config.execution');
|
|
40
41
|
execution({execution:{}},{},local.execution??{});
|
|
@@ -43,7 +44,7 @@ export function loadSettings({file=configFile(),workspace,output,refs,cache}={})
|
|
|
43
44
|
if(local.autoSyncSkills!==undefined&&typeof local.autoSyncSkills!=='boolean')throw new Error('autoSyncSkills 必须为布尔值');
|
|
44
45
|
const overrides={workspace,output,refs,cache},defaults={workspace:base,output:base,refs:join(base,'refs'),cache:join(base,'.cache')};
|
|
45
46
|
const paths=Object.fromEntries(Object.keys(defaults).map(key=>[key,externalPath(overrides[key]??local.paths?.[key]??defaults[key],key)]));
|
|
46
|
-
return {file:externalPath(file,'本地配置'),paths,execution:local.execution??{},analysisModel:local.analysisModel??null,defaultProject:local.defaultProject??null,autoSyncSkills:local.autoSyncSkills??true};
|
|
47
|
+
return {file:externalPath(file,'本地配置'),paths,execution:local.execution??{},generation:generationConfig(local.generation??{}),analysisModel:local.analysisModel??null,defaultProject:local.defaultProject??null,autoSyncSkills:local.autoSyncSkills??true};
|
|
47
48
|
}
|
|
48
49
|
export function initSettings(file=configFile()) {
|
|
49
50
|
externalPath(file,'本地配置');if(existsSync(file))return loadSettings({file});
|
package/lib/shared.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
-
import { readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs';
|
|
2
|
+
import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
|
|
3
3
|
import { dirname } from 'node:path';
|
|
4
4
|
|
|
5
5
|
export function hash(value) {
|
|
@@ -15,7 +15,17 @@ export function writeJson(path, data) {
|
|
|
15
15
|
mkdirSync(dirname(path), { recursive: true });
|
|
16
16
|
const temporary = path + '.tmp-' + randomUUID();
|
|
17
17
|
writeFileSync(temporary, JSON.stringify(data, null, 2) + '\n', 'utf8');
|
|
18
|
-
|
|
18
|
+
// Windows readers and antivirus can temporarily deny replacement of a state file.
|
|
19
|
+
// Keep the previous complete document until rename succeeds; never truncate it.
|
|
20
|
+
try {
|
|
21
|
+
for(let attempt=0;;attempt++) {
|
|
22
|
+
try {renameSync(temporary,path);break;}
|
|
23
|
+
catch(error) {
|
|
24
|
+
if(process.platform!=='win32'||!['EPERM','EACCES','EBUSY'].includes(error.code)||attempt>=50)throw error;
|
|
25
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
} finally {try{rmSync(temporary,{force:true});}catch{}}
|
|
19
29
|
}
|
|
20
30
|
export function keys(value, allowed, label) {
|
|
21
31
|
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} 必须为对象`);
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import {existsSync,readdirSync,renameSync,writeFileSync} from 'node:fs';
|
|
2
|
+
import {join} from 'node:path';
|
|
3
|
+
import {readJson,writeJson,hash} from './shared.mjs';
|
|
4
|
+
import {sha256File} from './bl.mjs';
|
|
5
|
+
import {validatePlan} from './plan.mjs';
|
|
6
|
+
import {externalPath} from './settings.mjs';
|
|
7
|
+
import {ensureService} from './service.mjs';
|
|
8
|
+
import {generate,generationRequest} from './providers.mjs';
|
|
9
|
+
import {cancelPrompt} from './comfyui.mjs';
|
|
10
|
+
|
|
11
|
+
const file=process.argv[2],task=readJson(file);
|
|
12
|
+
const cancelled=()=>existsSync(file+'.cancel')||existsSync(join(task.root,'shutdown.json'));
|
|
13
|
+
const persist=()=>{task.heartbeat=new Date().toISOString();writeJson(file,task);};
|
|
14
|
+
task.workerPid=process.pid;task.status='running';persist();
|
|
15
|
+
const heartbeat=setInterval(persist,1000);
|
|
16
|
+
let manifest,manifestPath;
|
|
17
|
+
function saveManifest(){if(!manifest)return;manifest.summary={expected:task.items.length,completed:manifest.items.filter(x=>x.status!=='running').length,ok:manifest.items.filter(x=>x.ok).length,failed:manifest.items.filter(x=>x.status==='failed').length,cancelled:manifest.items.filter(x=>x.status==='cancelled').length};writeJson(manifestPath,manifest);}
|
|
18
|
+
try {
|
|
19
|
+
validatePlan(task.plan);externalPath(task.outputRoot,'输出目录');
|
|
20
|
+
for(const ref of task.plan.refs)if(sha256File(externalPath(ref.path))!==ref.hash)throw new Error('原图/参考图已变化:'+ref.path);
|
|
21
|
+
const runDir=join(task.outputRoot,task.plan.job+'-'+task.taskId);
|
|
22
|
+
manifestPath=join(runDir,'manifest.json');
|
|
23
|
+
task.manifestPath=manifestPath;
|
|
24
|
+
manifest={schema:'art-workshop/run',runId:task.taskId,taskId:task.taskId,plan:task.plan,planHash:task.plan.planHash,provider:task.plan.backend?.provider??'bailian',startedAt:new Date().toISOString(),items:[],review:[],selections:{}};saveManifest();persist();
|
|
25
|
+
const backend=task.plan.backend;
|
|
26
|
+
if(backend?.provider==='comfyui')task.endpoint=await ensureService(backend,task.root,{cancelled});
|
|
27
|
+
for(const item of task.items) {
|
|
28
|
+
if(cancelled())break;
|
|
29
|
+
task.currentItem={itemId:item.itemId,variantId:item.variantId};persist();
|
|
30
|
+
const record={...structuredClone(item),ok:false,status:'running',files:[],urls:[],outputHashes:{}};
|
|
31
|
+
manifest.items.push(record);saveManifest();
|
|
32
|
+
try {
|
|
33
|
+
const before=new Set(readdirSync(runDir));
|
|
34
|
+
const request=generationRequest(task.plan,item);
|
|
35
|
+
record.request=request;saveManifest();
|
|
36
|
+
const result=await generate(task.plan,item,{endpoint:task.endpoint,root:task.root,outputDir:runDir,prefix:`${item.itemId}--${item.variantId}`,cancelled,onPrompt:promptId=>{task.promptId=promptId;persist();},onRemoteCancel:()=>{task.remoteCancellation='client-stopped; upstream execution cannot be confirmed';}});
|
|
37
|
+
if(result.files)record.files=result.files;
|
|
38
|
+
else {
|
|
39
|
+
record.urls=result.urls??[];
|
|
40
|
+
const fresh=readdirSync(runDir).filter(f=>!before.has(f)&&/\.(png|jpe?g|webp)$/i.test(f)).sort();
|
|
41
|
+
for(const [index,source] of fresh.entries()){const target=`${item.itemId}--${item.variantId}${index?'--'+(index+1):''}${source.slice(source.lastIndexOf('.'))}`;if(source!==target){if(existsSync(join(runDir,target)))throw new Error('产物已存在');renameSync(join(runDir,source),join(runDir,target));}record.files.push(target);}
|
|
42
|
+
}
|
|
43
|
+
if(record.files.length!==(item.execution??task.plan.execution).perValue)throw new Error('生成数量与计划不符');
|
|
44
|
+
for(const image of record.files)record.outputHashes[image]=sha256File(join(runDir,image));
|
|
45
|
+
record.ok=true;record.status='generated';
|
|
46
|
+
}catch(error){
|
|
47
|
+
if(backend?.provider==='comfyui'&&task.promptId)try{await cancelPrompt(task.endpoint,task.promptId);task.promptId=null;}catch(stopError){error.unsettled=true;error.message+=';无法确认后端停止:'+stopError.message;}
|
|
48
|
+
if(error.unsettled)task.unsettled=true;
|
|
49
|
+
record.status=cancelled()&&!error.unsettled?'cancelled':'failed';record.error=error.message;
|
|
50
|
+
if(record.status==='failed'){task.error=error.message;if(error.diagnostic){record.diagnostic=error.diagnostic;task.diagnostic=error.diagnostic;}}
|
|
51
|
+
}
|
|
52
|
+
saveManifest();
|
|
53
|
+
}
|
|
54
|
+
if(cancelled())for(const item of task.items)if(!manifest.items.some(x=>x.inputHash===item.inputHash))manifest.items.push({...structuredClone(item),ok:false,status:'cancelled',files:[],urls:[],outputHashes:{},error:'任务已取消,未执行'});
|
|
55
|
+
manifest.finishedAt=new Date().toISOString();saveManifest();
|
|
56
|
+
task.status=task.unsettled?'failed':cancelled()?'cancelled':manifest.summary.failed?'failed':'succeeded';
|
|
57
|
+
}catch(error){task.status=cancelled()?'cancelled':'failed';task.error=error.message;if(error.diagnostic)task.diagnostic=error.diagnostic;if(manifest){manifest.error=error.message;manifest.diagnostic=error.diagnostic;manifest.finishedAt=new Date().toISOString();saveManifest();}}
|
|
58
|
+
finally{clearInterval(heartbeat);task.finishedAt=new Date().toISOString();persist();}
|
package/lib/tasks.mjs
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import {spawn} from 'node:child_process';
|
|
2
|
+
import {mkdirSync,openSync,closeSync,existsSync,rmSync} from 'node:fs';
|
|
3
|
+
import {join} from 'node:path';
|
|
4
|
+
import {fileURLToPath} from 'node:url';
|
|
5
|
+
import {randomUUID} from 'node:crypto';
|
|
6
|
+
import {writeJson,hash} from './shared.mjs';
|
|
7
|
+
import {runtimeRoot,taskFile,tasks,stateRead,terminal,sleep,locked,alive,http} from './runtime.mjs';
|
|
8
|
+
import {closeService,healthy} from './service.mjs';
|
|
9
|
+
import {cancelPrompt} from './comfyui.mjs';
|
|
10
|
+
import {validatePlan} from './plan.mjs';
|
|
11
|
+
|
|
12
|
+
export function taskView(task) {
|
|
13
|
+
const {schema,taskId,status,createdAt,heartbeat,finishedAt,workerPid,endpoint,promptId,manifestPath,error,diagnostic,remoteCancellation,unsettled,currentItem,logPath}=task;
|
|
14
|
+
return {schema,taskId,status,createdAt,heartbeat,finishedAt,workerPid,endpoint,promptId,manifestPath,error,diagnostic,remoteCancellation,unsettled,currentItem,logPath,backend:task.plan?.backend?.id??'bailian'};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function taskStatus(root,taskId) {
|
|
18
|
+
const file=taskFile(root,taskId),task=stateRead(file);if(!task)throw new Error('任务不存在 '+taskId);
|
|
19
|
+
if(!terminal(task.status)&&Date.now()-Date.parse(task.heartbeat??task.createdAt)>10000&&!alive(task.workerPid)) {
|
|
20
|
+
task.status='lost';task.error='工作进程退出;后端任务可能仍在运行,请 task cancel 或 shutdown 清理';writeJson(file,task);
|
|
21
|
+
}
|
|
22
|
+
return task;
|
|
23
|
+
}
|
|
24
|
+
export async function startTask(plan,items,settings) {
|
|
25
|
+
validatePlan(plan);if(!items.length)throw new Error('没有选中任务');
|
|
26
|
+
for(const item of items)if(!plan.items.some(x=>hash(x)===hash(item)))throw new Error('执行项不属于计划');
|
|
27
|
+
const root=runtimeRoot(settings);
|
|
28
|
+
return locked(root,'control',async()=>{
|
|
29
|
+
const gate=stateRead(join(root,'shutdown.json'));
|
|
30
|
+
if(gate&&alive(gate.pid))throw new Error('shutdown 正在执行,不能启动任务');
|
|
31
|
+
if(gate)rmSync(join(root,'shutdown.json'),{force:true});
|
|
32
|
+
const taskId='task-'+randomUUID(),file=taskFile(root,taskId);
|
|
33
|
+
const logPath=join(root,'tasks',taskId+'.log');
|
|
34
|
+
const task={schema:'art-workshop/task',taskId,status:'queued',createdAt:new Date().toISOString(),plan,items,outputRoot:settings.paths.output,root,config:settings.file,logPath};
|
|
35
|
+
writeJson(file,task);
|
|
36
|
+
const fd=openSync(logPath,'a');
|
|
37
|
+
const child=spawn(process.execPath,[fileURLToPath(new URL('./task-worker.mjs',import.meta.url)),file],{detached:true,windowsHide:true,stdio:['ignore',fd,fd]});closeSync(fd);
|
|
38
|
+
await new Promise((resolve,reject)=>{child.once('spawn',resolve);child.once('error',reject);});
|
|
39
|
+
child.unref();
|
|
40
|
+
return {taskId,status:'queued',logPath};
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
export async function waitTask(root,taskId,{timeoutSeconds=3600}={}) {
|
|
44
|
+
const deadline=Date.now()+timeoutSeconds*1000;
|
|
45
|
+
while(true){const state=taskStatus(root,taskId);if(terminal(state.status))return state;if(Date.now()>deadline)throw new Error('等待超时;任务仍在后台运行');await sleep(250);}
|
|
46
|
+
}
|
|
47
|
+
export async function cancelTask(root,taskId,{wait=true}={}) {
|
|
48
|
+
const task=taskStatus(root,taskId);
|
|
49
|
+
if(terminal(task.status)) {
|
|
50
|
+
if(task.endpoint&&task.promptId){await cancelPrompt(task.endpoint,task.promptId);task.promptId=null;task.unsettled=false;if(task.status!=='succeeded')task.status='cancelled';writeJson(taskFile(root,taskId),task);}
|
|
51
|
+
return taskStatus(root,taskId);
|
|
52
|
+
}
|
|
53
|
+
writeJson(taskFile(root,taskId)+'.cancel',{requestedAt:new Date().toISOString()});
|
|
54
|
+
return wait?waitTask(root,taskId,{timeoutSeconds:60}):{taskId,status:'cancelling'};
|
|
55
|
+
}
|
|
56
|
+
export async function shutdown(settings) {
|
|
57
|
+
const root=runtimeRoot(settings);
|
|
58
|
+
return locked(root,'control',async()=>{
|
|
59
|
+
const gate=join(root,'shutdown.json');writeJson(gate,{pid:process.pid,startedAt:new Date().toISOString()});
|
|
60
|
+
const failures=[],stopped=[];
|
|
61
|
+
try {
|
|
62
|
+
const active=tasks(root).filter(t=>!terminal(taskStatus(root,t.taskId).status));
|
|
63
|
+
for(const task of active)await cancelTask(root,task.taskId,{wait:false});
|
|
64
|
+
const backends=Object.entries(settings.generation?.backends??{}).filter(([,b])=>b.provider==='comfyui').map(([id,b])=>({id,...b}));
|
|
65
|
+
// Frozen tasks may refer to backends removed from the current configuration.
|
|
66
|
+
for(const task of tasks(root))if(task.plan?.backend?.provider==='comfyui')backends.push(task.plan.backend);
|
|
67
|
+
const endpoints=new Map();for(const b of backends)for(const endpoint of b.endpoints)endpoints.set(endpoint,b);
|
|
68
|
+
for(const [endpoint,backend] of endpoints) {
|
|
69
|
+
try {if(await healthy(endpoint,backend))await cancelPrompt(endpoint,null,{all:true});}
|
|
70
|
+
catch(e){failures.push(endpoint+': '+e.message);}
|
|
71
|
+
}
|
|
72
|
+
for(const task of active)try{await waitTask(root,task.taskId,{timeoutSeconds:60});}catch(e){failures.push(task.taskId+': '+e.message);}
|
|
73
|
+
// Never close the service while a live art worker is still using it.
|
|
74
|
+
if(tasks(root).some(t=>!terminal(taskStatus(root,t.taskId).status)))throw new Error('任务尚未停止,保留服务:'+failures.join('; '));
|
|
75
|
+
if(failures.length)throw new Error('任务停止尚未确认,保留服务:'+failures.join('; '));
|
|
76
|
+
for(const [endpoint,backend] of endpoints)try{stopped.push(await closeService(root,endpoint,backend));}catch(e){failures.push(endpoint+': '+e.message);}
|
|
77
|
+
if(failures.length)throw new Error('shutdown 未完整完成:'+failures.join('; '));
|
|
78
|
+
return {ok:true,cancelledTasks:active.map(t=>t.taskId),remoteCancellationUnconfirmed:active.filter(t=>taskStatus(root,t.taskId).remoteCancellation).map(t=>t.taskId),services:stopped};
|
|
79
|
+
}finally{rmSync(gate,{force:true});}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import {readFileSync} from 'node:fs';
|
|
2
|
+
import {dirname,resolve} from 'node:path';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
export const BUILTIN_WORKFLOW='vant-builtin-qwen-image-2.1-Q4-8GB';
|
|
5
|
+
const root=dirname(dirname(fileURLToPath(import.meta.url)));
|
|
6
|
+
export const builtinBindings={model:{node:'1',input:'unet_name'},prompt:{node:'4',input:'prompt'},negativePrompt:{node:'4',input:'negative_prompt'},width:{node:'5',input:'width'},height:{node:'5',input:'height'},count:{node:'5',input:'batch_size'},seed:{node:'6',input:'seed'}};
|
|
7
|
+
export function loadBackend(settings,name) {
|
|
8
|
+
const backend=structuredClone(settings.generation.backends[name]);if(!backend)throw new Error('未知 backend '+name);
|
|
9
|
+
backend.id=name;
|
|
10
|
+
if(backend.provider!=='comfyui')return backend;
|
|
11
|
+
const builtin=backend.workflow===undefined||backend.workflow===BUILTIN_WORKFLOW;
|
|
12
|
+
backend.workflow=builtin?BUILTIN_WORKFLOW:resolve(dirname(settings.file),backend.workflow);
|
|
13
|
+
const path=builtin?resolve(root,'workflows',BUILTIN_WORKFLOW+'.api.json'):backend.workflow;
|
|
14
|
+
backend.template=JSON.parse(readFileSync(path,'utf8'));
|
|
15
|
+
backend.bindings=builtin?{...structuredClone(builtinBindings),...backend.bindings}:backend.bindings;
|
|
16
|
+
if(backend.launch){backend.launch.executable=resolve(dirname(settings.file),backend.launch.executable);backend.launch.cwd=resolve(dirname(settings.file),backend.launch.cwd);}
|
|
17
|
+
return backend;
|
|
18
|
+
}
|
|
19
|
+
export function workflowList(){return [{id:BUILTIN_WORKFLOW,default:true,mode:'generate',api:resolve(root,'workflows',BUILTIN_WORKFLOW+'.api.json'),ui:resolve(root,'workflows',BUILTIN_WORKFLOW+'.json'),models:['qwen-image-2.1-UC-Q4_K_M.gguf','qwen3vl_8b_int8_convrot.safetensors','qwen_image_2.1_vae_bf16.safetensors'],notes:'8GB 配置:文本编码器使用 CPU,512×512 默认画布;分辨率增大可能超出显存。'}];}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kevlns/art-workshop",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "美术工坊:统一风格的多工程图片生成与编辑工具",
|
|
6
6
|
"type": "module",
|
|
@@ -14,18 +14,20 @@
|
|
|
14
14
|
"skills/",
|
|
15
15
|
"scripts/sync-skill.mjs",
|
|
16
16
|
"README.md",
|
|
17
|
-
"docs/core-guidance.md",
|
|
18
17
|
"LICENSE",
|
|
19
18
|
"v-cli.plugin.json",
|
|
20
|
-
"AGENTS.md"
|
|
19
|
+
"AGENTS.md",
|
|
20
|
+
"workflows/",
|
|
21
|
+
"docs/"
|
|
21
22
|
],
|
|
22
23
|
"scripts": {
|
|
23
24
|
"postinstall": "node scripts/sync-skill.mjs",
|
|
24
25
|
"skill:sync": "node scripts/sync-skill.mjs",
|
|
25
26
|
"test": "node scripts/test.mjs",
|
|
26
27
|
"pack:guard": "node scripts/pack-guard.mjs",
|
|
27
|
-
"check": "npm test && npm run pack:guard",
|
|
28
|
-
"test:package": "node scripts/test-package-install.mjs"
|
|
28
|
+
"check": "npm run docs:check && npm test && npm run pack:guard",
|
|
29
|
+
"test:package": "node scripts/test-package-install.mjs",
|
|
30
|
+
"docs:check": "node scripts/check-docs.mjs"
|
|
29
31
|
},
|
|
30
32
|
"engines": {
|
|
31
33
|
"node": ">=20"
|
|
@@ -1,28 +1,74 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: art-workshop
|
|
3
|
-
description:
|
|
3
|
+
description: 使用美术工坊进行风格分析与核心冻结、远程或本地 ComfyUI 生图和编辑、工作流及环境检查、任务取消与服务关闭。任务提到美术工坊、art 工具、核心冻结、统一风格图片或其工作流时使用。
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# 美术工坊
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
随包规范是权威来源。已安装 v-cli 时调用 v-cli art;首次先运行 v-cli agent docs art 和 v-cli agent describe art --json。独立使用读取同目录 runtime.json,通过 node <entry> 调用;全局安装也可用 art-workshop。以下前缀使用 v-cli art。
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
## 发现与模式选择
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
先 config show、agent index、config validate,确认实际外部路径、后端、工程、任务、核心。完整规范用 agent docs 查看;generate/edit show 读取任务,不猜身份。
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
| 模式 | 执行前检查 |
|
|
15
|
+
|---|---|
|
|
16
|
+
| 远程生图 | 百炼真实入口及 bl auth status/config show;config validate;generate plan、run --dry |
|
|
17
|
+
| 远程编辑 | 远程检查加原图与 changes/preserve;edit plan、run --dry |
|
|
18
|
+
| 本地内置 | workflow list、config validate、doctor;generate plan、run --dry |
|
|
19
|
+
| 本地自定义 | API JSON/bindings、插件与模型、单张输出;config validate、doctor、plan、dry |
|
|
20
|
+
| 本地 Qwen 2.1 编辑 | 一张底图、image/vae 绑定与编码器、修改/保留不冲突;doctor、edit plan、dry |
|
|
21
|
+
| 分析与冻结 | 百炼 analysisModel、参考 scope;analyze --dry、报告 validate;用户采用后 freeze |
|
|
17
22
|
|
|
18
|
-
|
|
23
|
+
远程 doctor 只是配置检查,当前百炼 CLI 无 bl doctor。style analyze 仍使用远程百炼,不随本地生图后端切换。pure local run 不需要百炼凭证。
|
|
19
24
|
|
|
20
|
-
|
|
25
|
+
## 生图与编辑流程
|
|
21
26
|
|
|
22
|
-
|
|
27
|
+
```powershell
|
|
28
|
+
v-cli art config validate --backend local-qwen
|
|
29
|
+
v-cli art doctor --backend local-qwen
|
|
30
|
+
# 服务未运行时可按配置启动后检测,不采样。
|
|
31
|
+
v-cli art doctor --backend local-qwen --start
|
|
32
|
+
v-cli art generate show --project P --job J
|
|
33
|
+
v-cli art generate plan --project P --job J --backend local-qwen --out .cache/plan.json
|
|
34
|
+
v-cli art generate run --plan .cache/plan.json --item ITEM --dry
|
|
35
|
+
v-cli art generate run --plan .cache/plan.json --item ITEM --background
|
|
36
|
+
```
|
|
23
37
|
|
|
24
|
-
|
|
38
|
+
P/J/ITEM 为需替换的真实身份,local-qwen 须已声明。编辑用 edit show/plan/run,选择有编辑能力的后端。未传 --backend 时由 generation.defaultBackend 选择;都未声明则仍走百炼默认。comfyui 后端省略 workflow 时选择 vant-builtin-qwen-image-2.1-Q4-8GB 内置文生图模板,默认 CPU 文本编码、512×512;权重和插件需已安装。
|
|
25
39
|
|
|
26
|
-
|
|
40
|
+
新计划可以 --backend 选远程/本地 ID。冻结 --plan 不能同时传 backend/project/job/core/explore;只选 item/variant/offset/limit 等执行范围。修改需求、模板、参数或原图后重新 plan,不手改快照或哈希。
|
|
27
41
|
|
|
28
|
-
|
|
42
|
+
variants 是构图/seed 候选,perValue 是每个组合的张数,limit 按 item 数。run 默认 base;新来源调用 --explore 展开候选。--timeout 只用于 task wait。本地要求每边为 32 的倍数、扩写和水印关闭;不自动改变设计尺寸。UI design 基于 profile 分辨率和单体尺寸/倍率换算,每边实际输出 256~4096,检查每项 execution。
|
|
43
|
+
|
|
44
|
+
## 核心与原图
|
|
45
|
+
|
|
46
|
+
核心只定义可复用视觉语言;实体、数量、身份色、动作和关系属于需求;背景、构图许可、设计基准属于资产;模型和尺寸属于执行。
|
|
47
|
+
|
|
48
|
+
文生图核心依次选显式 --core、任务 core、工程 defaultCore。冲突需改任务,不跨工程回退。默认纯白背景,其他背景必须明确允许。编辑默认保留原图风格,不读 defaultCore;绑定 core 后不能重复声明 style 修改/保留。原图与分析参考图语义不同,不将参考图自动用作编辑底图。
|
|
49
|
+
|
|
50
|
+
style analyze 只生成报告,不自动冻结;style validate 检查结构与冲突,人工审阅后由用户采用,再 style freeze。已有核心不可覆写。用户既有执行授权持续有效,不重复询问;仅预演或生成报告不能自行扩大到付费执行或冻结。
|
|
51
|
+
|
|
52
|
+
## 任务、失败与验收
|
|
53
|
+
|
|
54
|
+
```powershell
|
|
55
|
+
v-cli art task status TASK
|
|
56
|
+
v-cli art task wait TASK --timeout 60
|
|
57
|
+
v-cli art task cancel TASK
|
|
58
|
+
v-cli art shutdown
|
|
59
|
+
v-cli art check RUN --out .cache/review.json
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
前台和后台都创建 task。wait 超时不会取消;cancel 仅停止指定任务,保留服务。shutdown 停止当前配置范围全部生图/编辑任务,清空关联 ComfyUI 队列、中断执行并核验身份后关闭服务,也影响同后端浏览器任务。同步分析不在队列内。远程 cancel 不保证云端停止或费用撤销。
|
|
63
|
+
|
|
64
|
+
失败读取 task status 的 diagnostic、error、manifest 与日志:环境/提交/执行阶段、workflow/backend、节点和原始错误、修复提示。failed/lost 不证明后端停止,unsettled 必须如实报告。不得擅自换模型、后端或设计尺寸;修复后重新 plan/dry。
|
|
65
|
+
|
|
66
|
+
check 只核对完整性并汇总 content/style/asset 人工验收;全部 pass 才可 select。环境检查、mock 测试、模型输出都不等于实际图像或生产资产通过。
|
|
67
|
+
|
|
68
|
+
## 路径与副作用
|
|
69
|
+
|
|
70
|
+
资源放在安装目录之外。相对 input/report/plan/out/review/source 基于 workspace,RUN 基于 output,参考图基于实际 refs,workflow/launch 路径基于配置目录。目录覆盖建议绝对路径。
|
|
71
|
+
|
|
72
|
+
plan/dry 不联网、启动服务、上传或采样;普通 CLI 仍可补 refs 分类,plan --out 写计划。config validate/doctor/workflow list 不补 refs;doctor --start 可启动并保留服务。检测通过不保证权重加载、显存或效果。
|
|
73
|
+
|
|
74
|
+
用 refs guide 查实际分类;输入显式指定参考 path/scope/note。随包 SKILL.md 是源,agent init 同步到已有技能目录并保留扩展,不写工作区 AGENTS.md;避免直接改同步副本。
|