@kevlns/art-workshop 0.1.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +33 -12
- package/README.md +33 -135
- package/art-workshop.mjs +95 -25
- package/docs/commands.md +915 -0
- package/docs/configuration.md +60 -0
- package/docs/core-guidance.md +80 -13
- package/docs/data-formats.md +29 -0
- package/docs/deployment.md +40 -0
- package/docs/model-architecture.md +52 -0
- package/docs/modes.md +39 -0
- package/docs/remote-models.md +42 -0
- package/docs/troubleshooting.md +46 -0
- package/lib/adapters/dashscope.mjs +234 -0
- package/lib/adapters/index.mjs +28 -0
- package/lib/agent.mjs +3 -2
- package/lib/analysis-worker.mjs +25 -0
- package/lib/analyze.mjs +8 -8
- package/lib/backends.mjs +365 -0
- package/lib/bl.mjs +3 -18
- package/lib/candidates.mjs +82 -0
- package/lib/comfyui.mjs +64 -0
- package/lib/contracts.d.ts +67 -0
- package/lib/deployment-worker.mjs +97 -0
- package/lib/deployment.mjs +72 -0
- package/lib/design.mjs +5 -5
- package/lib/diagnostics.mjs +83 -0
- package/lib/dimensions.mjs +22 -0
- package/lib/edit.mjs +6 -3
- package/lib/environments.mjs +67 -0
- package/lib/execution/remote.mjs +156 -0
- package/lib/executor.mjs +10 -24
- package/lib/generate.mjs +9 -5
- package/lib/generation-policy.mjs +198 -0
- package/lib/images.mjs +10 -0
- package/lib/lifecycle.mjs +40 -0
- package/lib/migration.mjs +154 -0
- package/lib/model-catalog.mjs +288 -0
- package/lib/model-registry.mjs +234 -0
- package/lib/plan.mjs +98 -28
- package/lib/project.mjs +13 -4
- package/lib/providers.mjs +30 -0
- package/lib/refs.mjs +12 -16
- package/lib/runtime.mjs +25 -0
- package/lib/service.mjs +137 -0
- package/lib/settings.mjs +5 -6
- package/lib/shared.mjs +12 -2
- package/lib/style-lifecycle.mjs +72 -0
- package/lib/task-references.mjs +35 -0
- package/lib/task-worker.mjs +233 -0
- package/lib/tasks.mjs +458 -0
- package/lib/templates.mjs +69 -0
- package/lib/transport/cli.mjs +69 -0
- package/lib/transport/http.mjs +82 -0
- package/lib/vision.mjs +46 -0
- package/lib/workflows.mjs +28 -0
- package/lib/workspace.mjs +190 -0
- package/package.json +14 -6
- package/skills/art-workshop/SKILL.md +27 -27
- package/v-cli.plugin.json +1484 -135
- 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
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import {environmentRoot,writeMarker} from './environments.mjs';
|
|
2
|
+
import {existsSync,mkdirSync,createReadStream,renameSync,rmSync,readFileSync} from 'node:fs';
|
|
3
|
+
import {join,dirname} from 'node:path';
|
|
4
|
+
import {spawn,execFileSync} from 'node:child_process';
|
|
5
|
+
import {createHash} from 'node:crypto';
|
|
6
|
+
import {readJson,writeJson,hash} from './shared.mjs';
|
|
7
|
+
import {loadSettings} from './settings.mjs';
|
|
8
|
+
import {ownedPath} from './workspace.mjs';
|
|
9
|
+
import {locked,sleep,stateRead} from './runtime.mjs';
|
|
10
|
+
import {processIdentity,stopIdentity,ensureService} from './service.mjs';
|
|
11
|
+
import {LOCAL_RECIPE,validateDeploymentPlan} from './deployment.mjs';
|
|
12
|
+
import {loadBackend,BUILTIN_WORKFLOW} from './workflows.mjs';
|
|
13
|
+
import {inspectEnvironment} from './diagnostics.mjs';
|
|
14
|
+
import {generate} from './providers.mjs';
|
|
15
|
+
import {cancelPrompt} from './comfyui.mjs';
|
|
16
|
+
import {finishPlan} from './plan.mjs';
|
|
17
|
+
import {bindBackend} from './backends.mjs';
|
|
18
|
+
import {validateImage} from './images.mjs';
|
|
19
|
+
|
|
20
|
+
const file=process.argv[2],state=readJson(file),plan=state.plan,settings=loadSettings({file:plan.settingsFile});
|
|
21
|
+
const persist=()=>{state.heartbeat=new Date().toISOString();writeJson(file,state);};
|
|
22
|
+
const cancelled=()=>existsSync(file+'.cancel');
|
|
23
|
+
const check=()=>{if(cancelled())throw new Error('部署已取消');};
|
|
24
|
+
const stage=value=>{state.stage=value;persist();check();};
|
|
25
|
+
state.workerPid=process.pid;state.status='running';persist();const heartbeat=setInterval(persist,1000);
|
|
26
|
+
let childIdentity,unsettled=false;
|
|
27
|
+
async function command(executable,args,cwd){
|
|
28
|
+
check();const child=spawn(executable,args,{cwd,windowsHide:true,stdio:['ignore','inherit','inherit']});
|
|
29
|
+
const completion=new Promise((resolve,reject)=>{child.once('error',reject);child.once('exit',(code)=>code===0?resolve():reject(new Error('部署命令失败,退出码 '+code)));});
|
|
30
|
+
// Attach rejection immediately while awaiting the process identity.
|
|
31
|
+
completion.catch(()=>{});await sleep(100);childIdentity=child.pid?processIdentity(child.pid):null;
|
|
32
|
+
let stopping;
|
|
33
|
+
const timer=setInterval(()=>{if(cancelled()&&childIdentity){clearInterval(timer);stopping=stopIdentity(childIdentity).catch(()=>{unsettled=true;});}},100);
|
|
34
|
+
try{await completion;check();}finally{clearInterval(timer);if(stopping)await stopping;if(childIdentity&&processIdentity(childIdentity.pid)){try{await stopIdentity(childIdentity);}catch{unsettled=true;}}childIdentity=null;}
|
|
35
|
+
}
|
|
36
|
+
async function sha256(path){const digest=createHash('sha256');let bytes=0;for await(const chunk of createReadStream(path)){check();digest.update(chunk);bytes+=chunk.length;state.processedBytes=bytes;}return digest.digest('hex');}
|
|
37
|
+
async function repository(path,source){
|
|
38
|
+
if(existsSync(path)){
|
|
39
|
+
const current=execFileSync('git',['-C',path,'rev-parse','HEAD'],{encoding:'utf8',windowsHide:true,timeout:10000}).trim();
|
|
40
|
+
const remote=execFileSync('git',['-C',path,'remote','get-url','origin'],{encoding:'utf8',windowsHide:true,timeout:10000}).trim().replace(/\.git$/,'');
|
|
41
|
+
const dirty=execFileSync('git',['-C',path,'status','--porcelain','--untracked-files=no'],{encoding:'utf8',windowsHide:true,timeout:10000}).trim();
|
|
42
|
+
if(current!==source.commit||remote!==source.repository||dirty)throw new Error('现有源码不是干净的固定部署版本,保留用户环境;请另选空目录');return;
|
|
43
|
+
}
|
|
44
|
+
mkdirSync(dirname(path),{recursive:true});
|
|
45
|
+
const staging=ownedPath(environmentRoot(plan.installRoot),'staging','source-'+hash(source).slice(0,16));
|
|
46
|
+
// Partial clones belong only to this fixed recipe's private staging area.
|
|
47
|
+
if(existsSync(staging))rmSync(staging,{recursive:true,force:true});
|
|
48
|
+
const network=['-c','http.lowSpeedLimit=1024','-c','http.lowSpeedTime=60'];
|
|
49
|
+
await command('git',[...network,'clone','--filter=blob:none','--no-checkout',source.repository,staging],dirname(staging));await command('git',[...network,'-C',staging,'checkout','--detach',source.commit],dirname(staging));check();if(existsSync(path))throw new Error('源码目标被其他操作创建,禁止覆盖');renameSync(staging,path);
|
|
50
|
+
}
|
|
51
|
+
try{
|
|
52
|
+
validateDeploymentPlan(plan,settings);
|
|
53
|
+
const control=environmentRoot(plan.installRoot),claim=ownedPath(control,'deployment.json');
|
|
54
|
+
await locked(control,'install',async()=>{
|
|
55
|
+
const old=stateRead(claim);if(old&&old.deploymentId!==state.deploymentId&&old.stopConfirmed!==true)throw new Error('该安装目录已有运行或停止未知的部署,禁止重复操作');
|
|
56
|
+
writeJson(claim,{deploymentId:state.deploymentId,workspace:plan.workspace,status:'running',stopConfirmed:false});
|
|
57
|
+
try{
|
|
58
|
+
stage('校验固定源码与节点');await repository(ownedPath(plan.installRoot,'ComfyUI'),LOCAL_RECIPE.comfy);
|
|
59
|
+
await repository(ownedPath(plan.installRoot,'ComfyUI/custom_nodes/ComfyUI-GGUF'),LOCAL_RECIPE.plugin);
|
|
60
|
+
const venvOwner=ownedPath(control,'venv-owned.json'),ownedVenv=stateRead(venvOwner);
|
|
61
|
+
const installPython=!plan.portable&&(!existsSync(plan.python)||ownedVenv?.recipeHash===hash(LOCAL_RECIPE));
|
|
62
|
+
if(installPython){
|
|
63
|
+
if(!existsSync(plan.python)){writeJson(venvOwner,{recipeHash:hash(LOCAL_RECIPE),python:plan.python});stage('创建独立 Python 环境');await command(plan.basePython,['-m','venv',ownedPath(plan.installRoot,'.venv')],plan.installRoot);}
|
|
64
|
+
stage('安装 CUDA 运行依赖');await command(plan.python,['-m','pip','install','torch=='+LOCAL_RECIPE.torch,'torchvision=='+LOCAL_RECIPE.torchvision,'--index-url',LOCAL_RECIPE.torchIndex],plan.installRoot);
|
|
65
|
+
await command(plan.python,['-m','pip','install','-r',ownedPath(plan.installRoot,'ComfyUI/requirements.txt'),'gguf=='+LOCAL_RECIPE.gguf,'sentencepiece','protobuf'],plan.installRoot);
|
|
66
|
+
}
|
|
67
|
+
stage('核验 Python 与 CUDA');await command(plan.python,['-c',`import torch,gguf; import importlib.metadata as m; assert torch.cuda.is_available(), 'NVIDIA CUDA unavailable'; assert torch.__version__.split('+')[0]=='${LOCAL_RECIPE.torch}', 'Torch version differs'; assert m.version('gguf')=='${LOCAL_RECIPE.gguf}', 'GGUF version differs'`],plan.installRoot);
|
|
68
|
+
for(const model of LOCAL_RECIPE.models){
|
|
69
|
+
const destination=ownedPath(plan.installRoot,'ComfyUI/models',model.path);stage('校验模型 '+model.path);state.processedBytes=0;
|
|
70
|
+
if(existsSync(destination)){if(await sha256(destination)!==model.sha256)throw new Error('现有模型哈希不匹配,保留原文件:'+model.path);continue;}
|
|
71
|
+
stage('下载模型 '+model.path);mkdirSync(dirname(destination),{recursive:true});const temporary=ownedPath(control,hash(model.path)+'.part');
|
|
72
|
+
try{await command('curl.exe',['--fail','--location','--retry','2','--connect-timeout','20','--max-time','7200','--output',temporary,model.url],plan.installRoot);if(await sha256(temporary)!==model.sha256)throw new Error('下载模型哈希校验失败');check();if(existsSync(destination))throw new Error('模型目标被其他操作创建,禁止覆盖');renameSync(temporary,destination);}finally{rmSync(temporary,{force:true});}
|
|
73
|
+
}
|
|
74
|
+
const configured={...settings,generation:{defaultBackend:'local-qwen',defaults:{},backends:{'local-qwen':{provider:'comfyui',model:LOCAL_RECIPE.models[0].path.split('/').at(-1),endpoints:[plan.endpoint],launch:{executable:plan.python,cwd:plan.installRoot,args:['-s','ComfyUI/main.py','--disable-dynamic-vram','--lowvram','--disable-auto-launch',...(new URL(plan.endpoint).port?['--port',new URL(plan.endpoint).port]:[])]}}}}};
|
|
75
|
+
stage('检测固定工作流与环境');const backend=loadBackend(configured,'local-qwen'),endpoint=await ensureService(backend,join(control,'runtime'),{cancelled});
|
|
76
|
+
const report=await inspectEnvironment(endpoint,backend);if(!report.ok)throw new Error('部署环境检查未通过');state.environment=report;
|
|
77
|
+
// Readiness is proved by generation and editing, rather than a listening port.
|
|
78
|
+
const {queue_running=[],queue_pending=[]}=await(await fetch(new URL('/queue',endpoint))).json();if(queue_running.length||queue_pending.length)throw new Error('现有服务正在执行其他任务,本次不插入验收采样;任务结束后重试部署验证');
|
|
79
|
+
const output=ownedPath(control,'verification',state.deploymentId);mkdirSync(output,{recursive:true});
|
|
80
|
+
let source;
|
|
81
|
+
for(const mode of ['generate','edit']){
|
|
82
|
+
stage(mode==='generate'?'单图生成验证':'底图编辑验证');
|
|
83
|
+
const base=finishPlan({module:mode,project:'deployment',job:'verification',execution:{model:LOCAL_RECIPE.models[0].path.split('/').at(-1),size:'512*512',perValue:1,promptExtend:false,watermark:false},sources:{recipe:LOCAL_RECIPE.id},snapshots:{},refs:[],items:[{itemId:'verification',variantId:'base',seed:7619,prompt:mode==='generate'?'一个圆润的青绿色科幻能量球,简洁轮廓,柔和高光,纯白背景。':'保持原图轮廓和构图,将主体颜色改成金黄色。',negativeBlock:'文字,水印',imageArgs:mode==='edit'?[source]:[],checks:{content:[],style:[],asset:[]}}]});
|
|
84
|
+
const modeOutput=ownedPath(output,mode);mkdirSync(modeOutput,{recursive:true});
|
|
85
|
+
const bound=bindBackend(base,configured,'local-qwen'),result=await generate(bound,bound.items[0],{endpoint,root:join(control,'runtime'),outputDir:modeOutput,prefix:mode,cancelled,onPrompt:promptId=>{state.promptId=promptId;persist();}});
|
|
86
|
+
state.promptId=null;const path=ownedPath(modeOutput,result.files[0]),info=await validateImage(readFileSync(path));if(info.width!==512||info.height!==512)throw new Error('部署验证图片尺寸不符');source=path;state.verification??=[];state.verification.push({mode,path,hash:await sha256(path),planHash:bound.planHash});persist();
|
|
87
|
+
}
|
|
88
|
+
stage('保存已验证部署配置');for(const evidence of state.verification)if(await sha256(evidence.path)!==evidence.hash)throw new Error('部署采样证据发生变化,不保存完成状态');const raw=readJson(settings.file);raw.generation={...raw.generation,defaultBackend:'local-qwen',backends:{...raw.generation?.backends,'local-qwen':configured.generation.backends['local-qwen']}};writeJson(settings.file,raw);
|
|
89
|
+
writeMarker(plan.installRoot,{python:plan.portable?'python_embeded/python.exe':'.venv/Scripts/python.exe',endpoint:plan.endpoint,recipe:LOCAL_RECIPE.id,verification:'generate-and-edit'});state.status='succeeded';state.stopConfirmed=true;state.workflow=BUILTIN_WORKFLOW;
|
|
90
|
+
}catch(error){
|
|
91
|
+
if(error.unsettled&&!state.promptId)unsettled=true;
|
|
92
|
+
if(state.promptId){try{await cancelPrompt(plan.endpoint,state.promptId);state.promptId=null;}catch{unsettled=true;}}
|
|
93
|
+
state.status=unsettled?'unknown':cancelled()?'cancelled':'failed';state.stopConfirmed=!unsettled;state.error=error.message;
|
|
94
|
+
}finally{writeJson(claim,{deploymentId:state.deploymentId,workspace:plan.workspace,status:state.status,stopConfirmed:state.stopConfirmed});}
|
|
95
|
+
});
|
|
96
|
+
}catch(error){if(error.unsettled)unsettled=true;state.status=unsettled?'unknown':cancelled()?'cancelled':'failed';state.stopConfirmed=!unsettled;state.error=error.message;}
|
|
97
|
+
finally{clearInterval(heartbeat);state.finishedAt=new Date().toISOString();persist();}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import {existsSync,openSync,closeSync,statfsSync} from 'node:fs';
|
|
2
|
+
import {join,resolve} from 'node:path';
|
|
3
|
+
import {spawn,execFileSync} from 'node:child_process';
|
|
4
|
+
import {fileURLToPath} from 'node:url';
|
|
5
|
+
import {randomUUID} from 'node:crypto';
|
|
6
|
+
import {hash,readJson,writeJson,keys,id} from './shared.mjs';
|
|
7
|
+
import {externalPath} from './settings.mjs';
|
|
8
|
+
import {ownedPath} from './workspace.mjs';
|
|
9
|
+
import {runtimeRoot,locked,alive} from './runtime.mjs';
|
|
10
|
+
|
|
11
|
+
// This recipe is the tested local installation, not a user-editable workflow.
|
|
12
|
+
export const LOCAL_RECIPE={
|
|
13
|
+
id:'qwen-image-2.1-Q4-cpu-text-v1',
|
|
14
|
+
comfy:{repository:'https://github.com/Comfy-Org/ComfyUI',commit:'b0b743566f65daafc423b4fea8a2fbda94b3384a'},
|
|
15
|
+
plugin:{repository:'https://github.com/leejet/ComfyUI-GGUF',commit:'373048b8403a7820620065210a691263d4da0a61'},
|
|
16
|
+
models:[
|
|
17
|
+
{path:'diffusion_models/qwen-image-2.1-UC-Q4_K_M.gguf',bytes:4_604_558_112,url:'https://huggingface.co/abenzerps/Qwen-Image-2.1-Uncensored-GGUF/resolve/main/qwen-image-2.1-UC-Q4_K_M.gguf',sha256:'e79c8a009f2ecbdb6c70fd663d9aea9ee304a0d91f347e4169a756b8ad141b41'},
|
|
18
|
+
{path:'text_encoders/qwen3vl_8b_int8_convrot.safetensors',bytes:9_350_798_360,url:'https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors',sha256:'8bfd0f6e12abf2d2d697ecc888e5e90b0d6741d6708f05799f53afa560452e8f'},
|
|
19
|
+
{path:'vae/qwen_image_2.1_vae_bf16.safetensors',bytes:675_509_688,url:'https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors',sha256:'bb21f7473051e1ac368515dd3f2e15cd44d7a11748ee8823e1ddca3e4876b7c9'},
|
|
20
|
+
],
|
|
21
|
+
torch:'2.14.0',torchvision:'0.29.0',torchIndex:'https://download.pytorch.org/whl/cu130',gguf:'0.19.0',
|
|
22
|
+
};
|
|
23
|
+
export function deploymentPlan(settings,{directory,endpoint='http://127.0.0.1:8188/'}={}){
|
|
24
|
+
if(process.platform!=='win32')throw new Error('固定自动部署方案目前仅适配 Windows NVIDIA 环境');
|
|
25
|
+
const target=ownedPath(externalPath(directory,'部署目录')),url=new URL(endpoint);
|
|
26
|
+
if(url.protocol!=='http:'||!['127.0.0.1','localhost'].includes(url.hostname)||url.pathname!=='/'||url.search||url.hash||url.username||url.password)throw new Error('部署服务地址必须为本机 HTTP 根地址');
|
|
27
|
+
let gpu;
|
|
28
|
+
try{gpu=execFileSync('nvidia-smi',['--query-gpu=name,memory.total,driver_version','--format=csv,noheader,nounits'],{encoding:'utf8',windowsHide:true,timeout:10000}).trim().split('\n').filter(Boolean).map(line=>{const [name,memoryMiB,driver]=line.split(',').map(value=>value.trim());return {name,memoryMiB:Number(memoryMiB),driver};});if(!gpu.length||gpu.some(device=>!device.name||!Number.isFinite(device.memoryMiB)))throw new Error('GPU 信息无效');}
|
|
29
|
+
catch{throw new Error('固定自动部署需要可检测的 NVIDIA GPU 与驱动,请先安装驱动');}
|
|
30
|
+
const portable=existsSync(ownedPath(target,'python_embeded/python.exe')),venv=ownedPath(target,'.venv/Scripts/python.exe');
|
|
31
|
+
let python=portable?ownedPath(target,'python_embeded/python.exe'):existsSync(venv)?venv:null,basePython=null;
|
|
32
|
+
if(!python){try{basePython=execFileSync('python',['-c','import sys; assert sys.version_info >= (3,12); print(sys.executable)'],{encoding:'utf8',windowsHide:true,timeout:10000}).trim();}catch{throw new Error('自动部署需要已安装的 Python 3.12 或以上;现有便携版可直接复用');}python=venv;}
|
|
33
|
+
const present=LOCAL_RECIPE.models.map(model=>({...model,present:existsSync(ownedPath(target,'ComfyUI/models',model.path))}));
|
|
34
|
+
let ancestor=target;while(!existsSync(ancestor)){const parent=resolve(ancestor,'..');if(parent===ancestor)break;ancestor=parent;}
|
|
35
|
+
const storage=statfsSync(ancestor),available=Number(storage.bavail)*Number(storage.bsize),required=present.filter(model=>!model.present).reduce((sum,model)=>sum+model.bytes,0)+(!portable&&!existsSync(venv)?8_000_000_000:1_000_000_000);
|
|
36
|
+
if(available<required)throw new Error('部署磁盘空间不足,需要至少 '+Math.ceil(required/1e9)+' GB');
|
|
37
|
+
const plan={schema:'art-workshop/deployment-plan',recipe:LOCAL_RECIPE,gpu,installRoot:target,endpoint:url.href,python,basePython,portable,models:present,requiredBytes:required,availableBytes:available,settingsFile:settings.file,workspace:settings.paths.workspace};
|
|
38
|
+
return {...plan,planHash:hash(plan)};
|
|
39
|
+
}
|
|
40
|
+
export function validateDeploymentPlan(plan,settings){
|
|
41
|
+
keys(plan,['schema','recipe','gpu','installRoot','endpoint','python','basePython','portable','models','requiredBytes','availableBytes','settingsFile','workspace','planHash'],'部署预案');
|
|
42
|
+
const {planHash,...body}=plan;if(plan.schema!=='art-workshop/deployment-plan'||hash(body)!==planHash||hash(plan.recipe)!==hash(LOCAL_RECIPE))throw new Error('部署预案或固定方案已变化');
|
|
43
|
+
if(plan.settingsFile!==settings.file||resolve(plan.workspace)!==resolve(settings.paths.workspace))throw new Error('部署预案不属于当前配置与工程');
|
|
44
|
+
const expected=deploymentPlan(settings,{directory:plan.installRoot,endpoint:plan.endpoint});
|
|
45
|
+
for(const key of ['gpu','python','basePython','portable','models'])if(hash(expected[key])!==hash(plan[key]))throw new Error('部署环境已变化,请重新预演');
|
|
46
|
+
return plan;
|
|
47
|
+
}
|
|
48
|
+
export function deploymentStatus(settings,deploymentId){
|
|
49
|
+
const state=readJson(ownedPath(runtimeRoot(settings),'deployments',id(deploymentId)+'.json'));
|
|
50
|
+
if(state.schema!=='art-workshop/deployment'||state.deploymentId!==deploymentId)throw new Error('部署身份不匹配');
|
|
51
|
+
if(!['succeeded','failed','cancelled','unknown'].includes(state.status)&&Date.now()-Date.parse(state.heartbeat??state.createdAt)>10000&&!alive(state.workerPid)){state.status='unknown';state.stopConfirmed=false;state.error='部署工作进程退出;禁止重复启动或清理,先核验原操作';writeJson(ownedPath(runtimeRoot(settings),'deployments',deploymentId+'.json'),state);}
|
|
52
|
+
return state;
|
|
53
|
+
}
|
|
54
|
+
export async function startDeployment(settings,plan,{operationId}={}){
|
|
55
|
+
if(typeof operationId!=='string'||!/^[a-z0-9-]{1,128}$/.test(operationId))throw new Error('部署需要稳定操作身份');
|
|
56
|
+
return locked(runtimeRoot(settings),'deployment',async()=>{
|
|
57
|
+
const {readdirSync}=await import('node:fs'),directory=ownedPath(runtimeRoot(settings),'deployments');
|
|
58
|
+
const previous=existsSync(directory)?readdirSync(directory).filter(file=>file.endsWith('.json')).map(file=>deploymentStatus(settings,file.slice(0,-5))):[];
|
|
59
|
+
const same=previous.find(state=>state.operationId===operationId);if(same){if(same.plan.planHash!==plan.planHash)throw new Error('部署操作身份已用于其他预案');return same;}
|
|
60
|
+
const deploymentId='deploy-'+randomUUID(),file=ownedPath(directory,deploymentId+'.json'),logPath=ownedPath(directory,deploymentId+'.log');
|
|
61
|
+
const state={schema:'art-workshop/deployment',deploymentId,operationId,status:'queued',stopConfirmed:false,createdAt:new Date().toISOString(),plan,logPath};writeJson(file,state);
|
|
62
|
+
// Record rejected requests too: a caller losing an error receipt can recover
|
|
63
|
+
// proof that this operation never started, without repeating the deployment.
|
|
64
|
+
try{validateDeploymentPlan(plan,settings);if(previous.some(state=>state.stopConfirmed!==true))throw new Error('已有部署运行或停止未知,先处理原操作');}
|
|
65
|
+
catch(error){state.status='failed';state.stopConfirmed=true;state.finishedAt=new Date().toISOString();state.error=error.message;writeJson(file,state);throw error;}
|
|
66
|
+
const fd=openSync(logPath,'a'),child=spawn(process.execPath,[fileURLToPath(new URL('./deployment-worker.mjs',import.meta.url)),file],{detached:true,windowsHide:true,stdio:['ignore',fd,fd],env:{...process.env,ART_VISION_KEY:'',DASHSCOPE_API_KEY:''}});closeSync(fd);
|
|
67
|
+
try{await new Promise((resolve,reject)=>{child.once('spawn',resolve);child.once('error',reject);});}catch(error){state.status='failed';state.stopConfirmed=true;state.error='部署进程启动失败';writeJson(file,state);throw error;}
|
|
68
|
+
child.unref();return {deploymentId,status:'queued',stopConfirmed:false};
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
export function cancelDeployment(settings,deploymentId){const state=deploymentStatus(settings,deploymentId);if(state.stopConfirmed===true)return state;writeJson(ownedPath(runtimeRoot(settings),'deployments',deploymentId+'.json.cancel'),{requestedAt:new Date().toISOString()});return {deploymentId,status:'cancelling',stopConfirmed:false};}
|
|
72
|
+
export async function recoverDeployment(settings,operationId){const {readdirSync}=await import('node:fs');const directory=ownedPath(runtimeRoot(settings),'deployments');const records=existsSync(directory)?readdirSync(directory).filter(file=>file.endsWith('.json')).map(file=>deploymentStatus(settings,file.slice(0,-5))).filter(state=>state.operationId===operationId):[];if(records.length!==1)throw new Error('没有唯一原部署记录,停止状态未知;禁止重新提交');return records[0];}
|
package/lib/design.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {resolveDimensions,DIMENSION_CAPABILITIES} from './dimensions.mjs';
|
|
1
2
|
import { keys, integer } from './shared.mjs';
|
|
2
3
|
|
|
3
4
|
// 设计基准归资产规格,单体尺寸与倍率归任务;出图尺寸由它们确定。
|
|
@@ -11,17 +12,16 @@ export function design(profile, override, explicitExecution = {}) {
|
|
|
11
12
|
keys(base.resolution, ['width', 'height'], 'design.resolution');
|
|
12
13
|
integer(base.resolution.width, 'design.resolution.width', 1, 16384);
|
|
13
14
|
integer(base.resolution.height, 'design.resolution.height', 1, 16384);
|
|
14
|
-
|
|
15
|
+
if(!Number.isFinite(base.outputScale)||base.outputScale<1||base.outputScale>4)throw new Error('预留缩放必须在 1 到 4 之间');
|
|
15
16
|
if (override !== undefined) keys(override, ['width', 'height', 'outputScale'], 'item.design');
|
|
16
17
|
const size = override === undefined ? base.resolution : override;
|
|
17
18
|
integer(size.width, 'design.width', 1, base.resolution.width);
|
|
18
19
|
integer(size.height, 'design.height', 1, base.resolution.height);
|
|
19
20
|
const outputScale = override?.outputScale ?? base.outputScale;
|
|
20
|
-
|
|
21
|
+
if(!Number.isFinite(outputScale)||outputScale<1||outputScale>4)throw new Error('预留缩放必须在 1 到 4 之间');
|
|
21
22
|
if (explicitExecution.size !== undefined) throw new Error('设计尺寸与任务 execution.size 不能同时指定');
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
return { resolution: { ...base.resolution }, size: { width: size.width, height: size.height }, outputScale, outputSize };
|
|
23
|
+
const requestedSize={ width: size.width * outputScale, height: size.height * outputScale },dimensions=resolveDimensions(requestedSize,DIMENSION_CAPABILITIES.bailian),outputSize=dimensions.actual;
|
|
24
|
+
return { resolution: { ...base.resolution }, size: { width: size.width, height: size.height }, outputScale, requestedSize,outputSize,dimensions };
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
export function designPrompt(value) {
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import {existsSync,statSync} from 'node:fs';
|
|
2
|
+
import {resolve} from 'node:path';
|
|
3
|
+
import {loadBackend} from './workflows.mjs';
|
|
4
|
+
import {http,runtimeRoot} from './runtime.mjs';
|
|
5
|
+
const issue=(code,message,extra={})=>({code,message,...extra});
|
|
6
|
+
export function templateIssues(backend) {
|
|
7
|
+
const graph=backend.template,issues=[];
|
|
8
|
+
if(!graph||graph.nodes||!Object.keys(graph).length||Object.values(graph).some(n=>!n?.class_type||!n.inputs||typeof n.inputs!=='object'))return [issue('workflow_format','需要非空 ComfyUI API 格式,而非 UI 导出的 nodes/links 格式')];
|
|
9
|
+
for(const [nodeId,node] of Object.entries(graph))for(const [input,value] of Object.entries(node.inputs))if(Array.isArray(value)&&value.length===2&&typeof value[0]==='string'&&Number.isInteger(value[1])) {
|
|
10
|
+
if(!graph[value[0]])issues.push(issue('workflow_link','连接指向不存在的节点',{nodeId,nodeType:node.class_type,input,sourceNode:value[0]}));
|
|
11
|
+
if(value[1]<0)issues.push(issue('workflow_link','输出索引不能为负数',{nodeId,input}));
|
|
12
|
+
}
|
|
13
|
+
for(const [field,b] of Object.entries(backend.bindings??{}))if(!(b.input in (graph[b.node]?.inputs??{})))issues.push(issue('workflow_binding','参数绑定指向不存在的节点输入',{field,nodeId:b.node,input:b.input}));
|
|
14
|
+
return issues;
|
|
15
|
+
}
|
|
16
|
+
export function environmentIssues(backend,info) {
|
|
17
|
+
const issues=[];
|
|
18
|
+
for(const [nodeId,node] of Object.entries(backend.template)) {
|
|
19
|
+
const schema=info[node.class_type];
|
|
20
|
+
if(!schema){issues.push(issue('missing_node','ComfyUI 未注册此节点,请安装或修复对应自定义节点',{nodeId,nodeType:node.class_type}));continue;}
|
|
21
|
+
const inputs={...schema.input?.required,...schema.input?.optional};
|
|
22
|
+
for(const [input,templateValue] of Object.entries(node.inputs)) {
|
|
23
|
+
const value=backend.bindings?.model?.node===nodeId&&backend.bindings.model.input===input?backend.model:templateValue;
|
|
24
|
+
const spec=inputs[input];
|
|
25
|
+
const uploadedImage=backend.bindings?.image?.node===nodeId&&backend.bindings.image.input===input;
|
|
26
|
+
if(!uploadedImage&&Array.isArray(spec?.[0])&&!Array.isArray(value)&&!spec[0].includes(value))issues.push(issue(input.endsWith('_name')?'missing_model':'invalid_node_value','节点输入值不在当前环境可选范围内',{nodeId,nodeType:node.class_type,input,value,available:spec[0]}));
|
|
27
|
+
if(Array.isArray(value)&&value.length===2&&typeof value[0]==='string'&&Number.isInteger(value[1])) {
|
|
28
|
+
const source=info[backend.template[value[0]]?.class_type];
|
|
29
|
+
if(source?.output&&value[1]>=source.output.length)issues.push(issue('workflow_link','连接输出索引超出节点输出范围',{nodeId,input,sourceNode:value[0],output:value[1]}));
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return issues;
|
|
34
|
+
}
|
|
35
|
+
export async function inspectEnvironment(endpoint,backend) {
|
|
36
|
+
const stats=await http(endpoint,'/system_stats',{timeout:2000});
|
|
37
|
+
const version=stats.system?.comfyui_version,parts=version?.split('.').map(Number),issues=[];
|
|
38
|
+
if(!version||!Number.isFinite(parts[0])||!Number.isFinite(parts[1])||(parts[0]===0&&parts[1]<39))issues.push(issue('comfyui_version','需要 ComfyUI 0.39.0 或更新版本,以支持按任务中断',{version}));
|
|
39
|
+
const nodes=await http(endpoint,'/object_info',{timeout:10000});
|
|
40
|
+
issues.push(...environmentIssues(backend,nodes));
|
|
41
|
+
return {endpoint,reachable:true,ok:!issues.length,version,devices:stats.devices??[],issues};
|
|
42
|
+
}
|
|
43
|
+
export function validateConfiguration(settings,{backend:selection}={}) {
|
|
44
|
+
const names=selection?[selection]:Object.keys(settings.generation.backends??{}),backends=[];
|
|
45
|
+
for(const name of names) {
|
|
46
|
+
try {
|
|
47
|
+
const b=loadBackend(settings,name),issues=b.provider==='comfyui'?templateIssues(b):[];
|
|
48
|
+
if(b.provider==='comfyui') {
|
|
49
|
+
const execution={...settings.generation.defaults,...b.execution,...settings.execution};
|
|
50
|
+
if(execution.promptExtend||execution.watermark)issues.push(issue('unsupported_option','本地后端不支持 promptExtend/watermark'));
|
|
51
|
+
if(execution.size&&execution.size.split('*').some(x=>Number(x)%32))issues.push(issue('local_dimensions','本地宽高必须为 32 的倍数',{size:execution.size}));
|
|
52
|
+
}
|
|
53
|
+
backends.push({backend:name,provider:b.provider,workflow:b.workflow,issues});
|
|
54
|
+
}
|
|
55
|
+
catch(error){backends.push({backend:name,issues:[issue('configuration',error.message)]});}
|
|
56
|
+
}
|
|
57
|
+
return {ok:backends.every(b=>!b.issues.length),config:settings.file,defaultBackend:settings.generation.defaultBackend??'bailian',backends};
|
|
58
|
+
}
|
|
59
|
+
export async function doctor(settings,{backend:selection,start=false}={}) {
|
|
60
|
+
const validation=validateConfiguration(settings,{backend:selection});if(!validation.ok)return {...validation,stage:'configuration'};
|
|
61
|
+
const reports=[];
|
|
62
|
+
for(const row of validation.backends) {
|
|
63
|
+
if(row.provider!=='comfyui'){reports.push({...row,ok:true,scope:'configuration-only',notes:'远程凭证与配置请核对 bl auth status 和 bl config show;本命令不验证云端连通性,也不发起付费调用'});continue;}
|
|
64
|
+
const b=loadBackend(settings,row.backend),issues=[];b.model=settings.execution.model??b.model;
|
|
65
|
+
if(b.launch) {
|
|
66
|
+
for(const [label,path,type] of [['launch.executable',b.launch.executable,'file'],['launch.cwd',b.launch.cwd,'directory']])if(!existsSync(path)||(type==='file'?!statSync(path).isFile():!statSync(path).isDirectory()))issues.push(issue('launch_path',label+' 不存在或类型不符',{path}));
|
|
67
|
+
const entry=b.launch.args.find(x=>/\.py$|\.mjs$|\.js$/.test(x));if(entry&&!existsSync(resolve(b.launch.cwd,entry)))issues.push(issue('launch_entry','启动入口文件不存在',{path:resolve(b.launch.cwd,entry)}));
|
|
68
|
+
}
|
|
69
|
+
if(start&&!issues.length)try{await (await import('./service.mjs')).ensureService(b,runtimeRoot(settings));}catch(error){issues.push(issue('startup',error.message,{diagnostic:error.diagnostic}));}
|
|
70
|
+
const endpoints=[];
|
|
71
|
+
for(const endpoint of b.endpoints)try{endpoints.push(await inspectEnvironment(endpoint,b));}catch(error){endpoints.push({endpoint,reachable:false,ok:false,issues:[issue('unreachable','无法读取 ComfyUI 环境:'+error.message)]});}
|
|
72
|
+
const available=endpoints.some(e=>e.ok);
|
|
73
|
+
reports.push({...row,ok:available&&!issues.length,issues,endpoints,notes:available?'未执行采样,显存容量和图像效果仍需实际任务验证':start||endpoints.some(e=>e.reachable)?'查看 issues:服务可达但环境不兼容,或启动配置有误':'服务未启动时不能确认插件和模型;使用 doctor --start 启动并检查'});
|
|
74
|
+
}
|
|
75
|
+
return {ok:reports.every(r=>r.ok),config:settings.file,startedOnDemand:start,backends:reports};
|
|
76
|
+
}
|
|
77
|
+
export function workflowError(message,backend,{stage='execution',promptId,nodeErrors={},messages=[],cause}={}) {
|
|
78
|
+
const nodes=Object.entries(nodeErrors).map(([nodeId,data])=>({nodeId,nodeType:data.class_type??backend.template[nodeId]?.class_type,title:backend.template[nodeId]?._meta?.title,errors:data.errors??[data]}));
|
|
79
|
+
for(const entry of messages)if(Array.isArray(entry)&&entry[0]==='execution_error') {const data=entry[1];nodes.push({nodeId:String(data.node_id),nodeType:data.node_type,exceptionType:data.exception_type,message:data.exception_message,traceback:data.traceback});}
|
|
80
|
+
const details=JSON.stringify({nodes,message});
|
|
81
|
+
const hint=/out of memory|OutOfMemory|allocation/i.test(details)?'显存或内存不足:降低出图尺寸,确认 lowvram 和文本编码器 CPU 配置':/not in list|not found|missing/i.test(details)?'运行 art doctor 检查模型文件、插件节点与输入选项':'检查指定节点的输入与连接;运行 art config validate 和 art doctor';
|
|
82
|
+
const error=new Error(message,{cause});error.diagnostic={kind:'workflow',stage,backend:backend.id,workflow:backend.workflow,promptId,nodes,messages,hint};return error;
|
|
83
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {keys,integer} from './shared.mjs';
|
|
2
|
+
export const DIMENSION_CAPABILITIES=Object.freeze({bailian:{min:256,max:4096,step:1,maxArea:4096*4096},comfyui:{min:256,max:4096,step:32,maxArea:4096*4096}});
|
|
3
|
+
/** Exhaustive finite grid; nearest pixel distance, then aspect ratio, then area/width. */
|
|
4
|
+
export function resolveDimensions(requested,capability){
|
|
5
|
+
keys(requested,['width','height'],'requested dimensions');
|
|
6
|
+
for(const axis of ['width','height'])if(!Number.isFinite(requested[axis])||requested[axis]<=0||requested[axis]>65536)throw new Error('请求尺寸超出有效范围');
|
|
7
|
+
const {min,max,step,maxArea,minArea=1}=capability;
|
|
8
|
+
integer(min,'min',1,16384);integer(max,'max',min,16384);integer(step,'step',1,512);integer(maxArea,'maxArea',1,16384*16384);
|
|
9
|
+
let best;
|
|
10
|
+
const ratio=requested.width/requested.height;
|
|
11
|
+
for(let width=Math.ceil(min/step)*step;width<=max;width+=step){
|
|
12
|
+
const upper=Math.min(max,Math.floor(maxArea/width),width/(capability.minRatio??Number.MIN_VALUE)),low=Math.ceil(Math.max(min,minArea/width,width/(capability.maxRatio??Infinity))/step)*step,high=Math.floor(upper/step)*step;if(high<low)continue;
|
|
13
|
+
// Convex pixel-distance objective: only adjacent heights to the requested height can win.
|
|
14
|
+
const nearest=requested.height/step;
|
|
15
|
+
for(const height of new Set([Math.max(low,Math.min(high,Math.floor(nearest)*step)),Math.max(low,Math.min(high,Math.ceil(nearest)*step))])){
|
|
16
|
+
const score=[(width-requested.width)**2+(height-requested.height)**2,Math.abs(width/height-ratio),width*height,width,height];
|
|
17
|
+
if(!best||score.some((v,i)=>v<best.score[i]&&score.slice(0,i).every((p,k)=>p===best.score[k])))best={width,height,score};
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if(!best)throw new Error('后端没有合法分辨率');
|
|
21
|
+
return {requested:{...requested},actual:{width:best.width,height:best.height},clamped:best.width!==requested.width||best.height!==requested.height,capability:{...capability}};
|
|
22
|
+
}
|
package/lib/edit.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import {taskReferencePrompt} from './task-references.mjs';
|
|
2
|
+
import {readObject,verifyReferences} from './workspace.mjs';
|
|
1
3
|
import {keys,id,text,texts,integer,hash} from './shared.mjs';
|
|
2
4
|
import {ROOT,loadProject,loadJob,sourcePath} from './project.mjs';
|
|
3
5
|
import {loadCore,corePrompt,coreNegative} from './core.mjs';
|
|
@@ -6,10 +8,11 @@ import {background} from './presentation.mjs';
|
|
|
6
8
|
import {sha256File} from './bl.mjs';
|
|
7
9
|
const targets=['background','style','shape','color','composition','content','detail','text'];
|
|
8
10
|
export function compileEdit({projectId,jobId,coreId,root=ROOT,localExecution={}}) {
|
|
11
|
+
const taskRecord=readObject(root,projectId,'task',jobId);const dynamicRefs=verifyReferences(root,taskRecord),referencePrompt=taskReferencePrompt(taskRecord);
|
|
9
12
|
const project=loadProject(projectId,root),job=loadJob(projectId,jobId,'edit',root);
|
|
10
13
|
keys(job,['project','kind','core','execution','items'],'edit job');
|
|
11
14
|
if(coreId&&job.core&&coreId!==job.core) throw new Error('核心与编辑任务绑定冲突');
|
|
12
|
-
const selected=coreId??job.core,core=selected?loadCore(projectId,selected,root):null,refs=
|
|
15
|
+
const selected=coreId??job.core,core=selected?loadCore(projectId,selected,root):null,refs=dynamicRefs.map(r=>({path:r.path,hash:r.hash})),items=[],ids=new Set();
|
|
13
16
|
if(!Array.isArray(job.items)||!job.items.length) throw new Error('编辑 items 必须非空');
|
|
14
17
|
for(const source of job.items) {
|
|
15
18
|
keys(source,['id','source','changes','preserve','mustRead','seed'],'edit item');id(source.id);
|
|
@@ -26,7 +29,7 @@ export function compileEdit({projectId,jobId,coreId,root=ROOT,localExecution={}}
|
|
|
26
29
|
if([...changed].some(x=>preserved.has(x))) throw new Error('修改与保留范围冲突');
|
|
27
30
|
if(core&&(changed.has('style')||preserved.has('style'))) throw new Error('绑定核心时,风格由核心负责,不能再声明修改或保留原风格');
|
|
28
31
|
texts(source.mustRead,'mustRead');const seed=source.seed??parseInt(hash([projectId,jobId,source.id]).slice(0,7),16);integer(seed,'seed');
|
|
29
|
-
items.push({itemId:source.id,variantId:'base',seed,brief:source,prompt:`基于输入原图编辑。未声明修改的部分保持原样。\n【修改】\n${changes.join('\n')}\n【保留】\n${preserve.join('\n')}${core?'\n【目标风格核心】\n'+corePrompt(core):''}`,negativeBlock:core?coreNegative(core):'',imageArgs:[path],checks:{content:source.mustRead,style:core?[corePrompt(core)]:['原图风格保持一致'],asset:changes.concat(preserve)}});
|
|
32
|
+
items.push({itemId:source.id,variantId:'base',seed,brief:source,prompt:`基于输入原图编辑。未声明修改的部分保持原样。\n【修改】\n${changes.join('\n')}\n【保留】\n${preserve.join('\n')}${core?'\n【目标风格核心】\n'+corePrompt(core):''}${referencePrompt}`,negativeBlock:core?coreNegative(core):'',imageArgs:[path],checks:{content:source.mustRead,style:core?[corePrompt(core)]:['原图风格保持一致'],asset:changes.concat(preserve)}});
|
|
30
33
|
}
|
|
31
|
-
return finishPlan({module:'edit',project:projectId,job:jobId,execution:execution(project,job.execution,localExecution),sources:{core:core?.id??null,coreHash:core?.coreHash??null,selection:selected?'编辑显式绑定':'保留原图'},snapshots:{project,core,job},refs,items});
|
|
34
|
+
return finishPlan({module:'edit',project:projectId,job:jobId,execution:execution(project,job.execution,localExecution),sources:{taskRevision:taskRecord.revision,taskConfigHash:hash(taskRecord.config),core:core?.id??null,coreHash:core?.coreHash??null,selection:selected?'编辑显式绑定':'保留原图'},snapshots:{project,core,job},refs,items});
|
|
32
35
|
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {existsSync,readFileSync,readdirSync,realpathSync,statSync,createReadStream} from 'node:fs';
|
|
3
|
+
import {homedir} from 'node:os';
|
|
4
|
+
import {join,resolve,dirname} from 'node:path';
|
|
5
|
+
import {hash,writeJson} from './shared.mjs';
|
|
6
|
+
import {loadBackend,BUILTIN_WORKFLOW} from './workflows.mjs';
|
|
7
|
+
import {inspectEnvironment} from './diagnostics.mjs';
|
|
8
|
+
import {LOCAL_RECIPE} from './deployment.mjs';
|
|
9
|
+
import {ensureService,externalIdentity} from './service.mjs';
|
|
10
|
+
export const MARKER='vant.art.config.json';
|
|
11
|
+
export const globalHome=()=>resolve(process.env.VANT_HOME??join(homedir(),'.vant'));
|
|
12
|
+
export const defaultInstallRoot=()=>join(globalHome(),'art-env');
|
|
13
|
+
export function environmentRoot(root){const canonical=existsSync(root)?realpathSync(root):resolve(root);return join(globalHome(),'state','art-environments',hash(process.platform==='win32'?canonical.toLowerCase():canonical));}
|
|
14
|
+
export function readMarker(root){
|
|
15
|
+
const file=join(root,MARKER);if(!existsSync(file))return null;
|
|
16
|
+
const value=JSON.parse(readFileSync(file,'utf8'));
|
|
17
|
+
let endpoint;try{endpoint=new URL(value.endpoint);}catch{throw new Error('环境标记缺少合法服务地址');}
|
|
18
|
+
if(endpoint.protocol!=='http:'||!['127.0.0.1','localhost'].includes(endpoint.hostname)||endpoint.pathname!=='/'||endpoint.search||endpoint.hash||endpoint.username||endpoint.password)throw new Error('环境标记只允许本机 HTTP 根地址');
|
|
19
|
+
if(value.schema!=='vant/art-environment-v1'||value.comfy!=='ComfyUI'||!['python_embeded/python.exe','.venv/Scripts/python.exe'].includes(value.python))throw new Error('美术环境标记无效:'+file);
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
export function writeMarker(root,{python,endpoint,recipe,verification='capabilities'}){
|
|
23
|
+
const value={schema:'vant/art-environment-v1',environmentId:hash(realpathSync(root).toLowerCase()),comfy:'ComfyUI',python,endpoint,workflow:BUILTIN_WORKFLOW,recipe,verification,verifiedAt:new Date().toISOString()};
|
|
24
|
+
writeJson(join(root,MARKER),value);
|
|
25
|
+
writeJson(join(environmentRoot(root),'environment.json'),{root:realpathSync(root),...value});return value;
|
|
26
|
+
}
|
|
27
|
+
export function backendFor(root,endpoint){
|
|
28
|
+
const python=existsSync(join(root,'python_embeded/python.exe'))?'python_embeded/python.exe':'.venv/Scripts/python.exe';
|
|
29
|
+
return {python,backend:loadBackend({file:join(root,'vant.art.config.json'),generation:{backends:{local:{provider:'comfyui',model:'qwen-image-2.1-UC-Q4_K_M.gguf',endpoints:[endpoint],launch:{executable:join(root,python),cwd:root,args:['-s','ComfyUI/main.py','--disable-dynamic-vram','--lowvram','--disable-auto-launch','--port',new URL(endpoint).port||'80']}}}}},'local')};
|
|
30
|
+
}
|
|
31
|
+
export async function inspectInstallation(root,endpoint){
|
|
32
|
+
root=resolve(root);let marker=null,markerError;try{marker=readMarker(root);}catch(e){markerError=e.message;}
|
|
33
|
+
const {python,backend}=backendFor(root,endpoint),missing=[];
|
|
34
|
+
if(!existsSync(join(root,python)))missing.push('Python 环境');
|
|
35
|
+
if(!existsSync(join(root,'ComfyUI/main.py')))missing.push('ComfyUI');
|
|
36
|
+
if(!existsSync(join(root,'ComfyUI/custom_nodes/ComfyUI-GGUF')))missing.push('ComfyUI-GGUF 节点');
|
|
37
|
+
for(const model of LOCAL_RECIPE.models){const file=join(root,'ComfyUI/models',model.path);if(!existsSync(file)||statSync(file).size!==model.bytes)missing.push(model.path+'(缺失或大小不符)');}
|
|
38
|
+
let service;try{service=await inspectEnvironment(endpoint,backend);if(service.ok){const edited=loadBackend({file:join(root,MARKER),generation:{backends:{local:{provider:'comfyui',model:backend.model,endpoints:[endpoint]}}}},'local','edit');const editReport=await inspectEnvironment(endpoint,edited);if(!editReport.ok)service=editReport;}}catch{}
|
|
39
|
+
let conflict;
|
|
40
|
+
if(service?.ok===true&&process.platform==='win32'&&!externalIdentity(endpoint,backend.launch))conflict='指定端口属于另一套环境';
|
|
41
|
+
if(marker?.endpoint&&marker.endpoint!==endpoint){try{const previous=await inspectEnvironment(marker.endpoint,backend);if(previous.ok)conflict='此环境已在 '+marker.endpoint+' 运行,请使用原端口或先关闭原服务';}catch{}}
|
|
42
|
+
const models=LOCAL_RECIPE.models.map(model=>({path:model.path,bytes:model.bytes,present:existsSync(join(root,'ComfyUI/models',model.path))&&statSync(join(root,'ComfyUI/models',model.path)).size===model.bytes}));
|
|
43
|
+
return {models,conflict,root,endpoint,managed:!!marker,markerError,python,missing,service,reusable:!markerError&&!missing.length,live:service?.ok===true};
|
|
44
|
+
}
|
|
45
|
+
export function discoverInstallations(){
|
|
46
|
+
const found=new Set(),index=join(globalHome(),'state','art-environments');
|
|
47
|
+
if(existsSync(index))for(const entry of readdirSync(index,{withFileTypes:true})){const file=join(index,entry.name,'environment.json');if(entry.isDirectory()&&existsSync(file)){try{const record=JSON.parse(readFileSync(file,'utf8'));if(typeof record.root==='string'&&existsSync(record.root))found.add(realpathSync(record.root));}catch{}}}
|
|
48
|
+
let budget=1500;
|
|
49
|
+
const scan=(root,depth)=>{if(--budget<0||!existsSync(root))return;try{if(existsSync(join(root,MARKER))||existsSync(join(root,'ComfyUI/main.py'))) {found.add(realpathSync(root));return;}if(depth===0)return;for(const entry of readdirSync(root,{withFileTypes:true})){if(entry.isDirectory()&&!entry.isSymbolicLink()&&!['node_modules','.git','AppData','Windows','models','python_embeded'].includes(entry.name))scan(join(root,entry.name),depth-1);}}catch{}};
|
|
50
|
+
for(const root of [join(globalHome(),'art-env'),join(homedir(),'AI'),...(process.platform==='win32'?['C:/AI','D:/AI','E:/AI']:[])])scan(root,3);
|
|
51
|
+
return [...found];
|
|
52
|
+
}
|
|
53
|
+
export async function adoptInstallation(root,endpoint,{cancelled=()=>false,onStage=()=>{}}={}){
|
|
54
|
+
const report=await inspectInstallation(root,endpoint);if(!report.reusable)throw new Error('现有环境需要补齐:'+report.missing.join('、'));
|
|
55
|
+
for(const model of LOCAL_RECIPE.models){
|
|
56
|
+
onStage('校验已有模型 '+model.path);const digest=createHash('sha256');
|
|
57
|
+
for await(const chunk of createReadStream(join(report.root,'ComfyUI/models',model.path))){if(cancelled())throw new Error('接入已取消');digest.update(chunk);}
|
|
58
|
+
if(digest.digest('hex')!==model.sha256)throw new Error('模型校验失败,保留原文件:'+model.path);
|
|
59
|
+
}
|
|
60
|
+
onStage('核验服务与工作流能力');
|
|
61
|
+
const {backend,python}=backendFor(report.root,endpoint);
|
|
62
|
+
if(report.live&&process.platform==='win32'&&!externalIdentity(endpoint,backend.launch))throw new Error('端口由其他环境占用,不能将其登记到指定目录');
|
|
63
|
+
await ensureService(backend,join(environmentRoot(report.root),'runtime'),{cancelled});
|
|
64
|
+
const current=await inspectInstallation(report.root,endpoint);if(!current.live)throw new Error('现有环境工作流能力检测未通过');
|
|
65
|
+
if(cancelled())throw new Error('接入已取消');
|
|
66
|
+
writeMarker(report.root,{python,endpoint,verification:'capabilities'});return current;
|
|
67
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { readFile, writeFile, mkdir, link, rm } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import sharp from "sharp";
|
|
5
|
+
import { hash } from "../shared.mjs";
|
|
6
|
+
import { boundedBody, RemoteError } from "../transport/http.mjs";
|
|
7
|
+
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
8
|
+
async function download(receipt, context) {
|
|
9
|
+
if (!context.outputDir) return { urls: receipt.urls };
|
|
10
|
+
if (!/^[a-zA-Z0-9_.-]+$/.test(context.prefix))
|
|
11
|
+
throw new Error("产物前缀无效");
|
|
12
|
+
await mkdir(context.outputDir, { recursive: true });
|
|
13
|
+
const files = [];
|
|
14
|
+
for (const [index, url] of receipt.urls.entries()) {
|
|
15
|
+
if (context.cancelled?.()) throw new Error("本地下载已取消,上游已完成");
|
|
16
|
+
// A pre-signed download receives no model credential, including on redirects.
|
|
17
|
+
const controller = new AbortController(),
|
|
18
|
+
timeout = setTimeout(() => controller.abort(), 60000),
|
|
19
|
+
timer = setInterval(() => {
|
|
20
|
+
if (context.cancelled?.()) controller.abort();
|
|
21
|
+
}, 100);
|
|
22
|
+
let buffer;
|
|
23
|
+
try {
|
|
24
|
+
const response = await (context.transport ?? fetch)(url, {
|
|
25
|
+
redirect: "follow",
|
|
26
|
+
signal: controller.signal,
|
|
27
|
+
});
|
|
28
|
+
if (!response.ok)
|
|
29
|
+
throw new Error("图片下载失败(HTTP " + response.status + ")");
|
|
30
|
+
buffer = await boundedBody(response, 64 * 1024 * 1024);
|
|
31
|
+
} finally {
|
|
32
|
+
clearTimeout(timeout);
|
|
33
|
+
clearInterval(timer);
|
|
34
|
+
}
|
|
35
|
+
const info = await sharp(buffer, {
|
|
36
|
+
limitInputPixels: 64 * 1024 * 1024,
|
|
37
|
+
}).metadata();
|
|
38
|
+
if (!["png", "jpeg", "webp"].includes(info.format))
|
|
39
|
+
throw new Error("生成产物不是可支持的图片格式");
|
|
40
|
+
const file =
|
|
41
|
+
context.prefix +
|
|
42
|
+
(index ? "--" + (index + 1) : "") +
|
|
43
|
+
"." +
|
|
44
|
+
(info.format === "jpeg" ? "jpg" : info.format),
|
|
45
|
+
path = join(context.outputDir, file);
|
|
46
|
+
const temporary = path + ".tmp-" + randomUUID();
|
|
47
|
+
try {
|
|
48
|
+
await writeFile(temporary, buffer, { flag: "wx" });
|
|
49
|
+
try {
|
|
50
|
+
await link(temporary, path);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (
|
|
53
|
+
error.code !== "EEXIST" ||
|
|
54
|
+
hash(await readFile(path)) !== hash(buffer)
|
|
55
|
+
)
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
} finally {
|
|
59
|
+
await rm(temporary, { force: true });
|
|
60
|
+
}
|
|
61
|
+
files.push(file);
|
|
62
|
+
}
|
|
63
|
+
return { files, urls: receipt.urls };
|
|
64
|
+
}
|
|
65
|
+
/** Provider-neutral lifecycle. Persist each transition before polling or downloading. */
|
|
66
|
+
export async function executeRemote(request, adapter, context = {}) {
|
|
67
|
+
const cancelled = context.cancelled ?? (() => false),
|
|
68
|
+
requestHash = hash(request);
|
|
69
|
+
let receipt = context.receipt,
|
|
70
|
+
baseUrl = context.baseUrl?.replace(/\/$/, "") ?? receipt?.baseUrl;
|
|
71
|
+
const persist = async (value) => {
|
|
72
|
+
receipt = { ...receipt, ...value };
|
|
73
|
+
await context.onReceipt?.(structuredClone(receipt));
|
|
74
|
+
};
|
|
75
|
+
if (request.transport.version !== adapter.version)
|
|
76
|
+
throw new Error("图片协议执行版本已变化,请重新预演");
|
|
77
|
+
if (
|
|
78
|
+
receipt &&
|
|
79
|
+
(receipt.requestHash !== requestHash ||
|
|
80
|
+
receipt.adapter !== adapter.id ||
|
|
81
|
+
receipt.adapterVersion !== adapter.version ||
|
|
82
|
+
receipt.baseUrl !== baseUrl)
|
|
83
|
+
)
|
|
84
|
+
throw new Error("上游任务与当前请求身份不一致;禁止重新提交");
|
|
85
|
+
if (receipt?.state === "dispatching")
|
|
86
|
+
throw new RemoteError("上次提交结果未知;禁止重复提交", {
|
|
87
|
+
unsettled: true,
|
|
88
|
+
});
|
|
89
|
+
try {
|
|
90
|
+
if (!receipt) {
|
|
91
|
+
if (cancelled()) throw new Error("任务已取消,尚未提交");
|
|
92
|
+
const prepared = await adapter.prepare(request, { ...context, baseUrl });
|
|
93
|
+
baseUrl = prepared.endpoint ?? baseUrl;
|
|
94
|
+
if (typeof baseUrl !== "string" || !baseUrl)
|
|
95
|
+
throw new Error("协议适配器未提供执行地址");
|
|
96
|
+
if (cancelled()) throw new Error("任务已取消,尚未提交");
|
|
97
|
+
await persist({
|
|
98
|
+
schema: "art/remote-receipt-v1",
|
|
99
|
+
adapter: adapter.id,
|
|
100
|
+
adapterVersion: adapter.version,
|
|
101
|
+
requestHash,
|
|
102
|
+
baseUrl,
|
|
103
|
+
state: "dispatching",
|
|
104
|
+
submittedAt: new Date().toISOString(),
|
|
105
|
+
});
|
|
106
|
+
if (cancelled()) {
|
|
107
|
+
await persist({ state: "cancelled", message: "请求尚未发出,已取消" });
|
|
108
|
+
throw new RemoteError("请求尚未发出,已取消", {
|
|
109
|
+
code: "upstream_cancelled",
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
const submitted = await adapter.submit(request, {
|
|
113
|
+
...context,
|
|
114
|
+
baseUrl,
|
|
115
|
+
prepared,
|
|
116
|
+
});
|
|
117
|
+
await persist(submitted);
|
|
118
|
+
}
|
|
119
|
+
while (receipt.state === "accepted") {
|
|
120
|
+
if (cancelled())
|
|
121
|
+
throw new RemoteError("本地等待已停止,上游停止未确认", {
|
|
122
|
+
unsettled: true,
|
|
123
|
+
});
|
|
124
|
+
const next = await adapter.query(receipt, { ...context, baseUrl });
|
|
125
|
+
await persist(next);
|
|
126
|
+
if (receipt.state === "accepted")
|
|
127
|
+
await pause(context.pollMilliseconds ?? 500);
|
|
128
|
+
}
|
|
129
|
+
if (receipt.state === "failed" || receipt.state === "cancelled")
|
|
130
|
+
throw new RemoteError(receipt.message ?? "上游执行未成功", {
|
|
131
|
+
code:
|
|
132
|
+
receipt.state === "cancelled"
|
|
133
|
+
? "upstream_cancelled"
|
|
134
|
+
: "upstream_failed",
|
|
135
|
+
});
|
|
136
|
+
if (
|
|
137
|
+
receipt.state !== "completed" ||
|
|
138
|
+
!Array.isArray(receipt.urls) ||
|
|
139
|
+
!receipt.urls.length
|
|
140
|
+
)
|
|
141
|
+
throw new RemoteError("协议适配器返回无效完成结果", { unsettled: true });
|
|
142
|
+
if (receipt.urls.length !== request.count)
|
|
143
|
+
throw new RemoteError("上游产物数量与冻结请求不同");
|
|
144
|
+
return await download(receipt, context);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (receipt?.state === "dispatching" && !error.unsettled)
|
|
147
|
+
await persist({ state: "failed", message: error.message });
|
|
148
|
+
if (receipt?.state === "accepted" || receipt?.state === "dispatching") {
|
|
149
|
+
error.unsettled = true;
|
|
150
|
+
context.onRemoteCancel?.();
|
|
151
|
+
}
|
|
152
|
+
// A completed upstream job stays settled even if downloading its result fails.
|
|
153
|
+
if (receipt?.state === "completed") error.unsettled = false;
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
}
|