@kevlns/art-workshop 0.5.0 → 0.5.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 +25 -109
- package/LICENSE +21 -21
- package/README.md +63 -63
- package/art-workshop.mjs +174 -168
- package/docs/commands.md +116 -8
- package/docs/configuration.md +82 -82
- package/docs/core-guidance.md +50 -50
- package/docs/data-formats.md +85 -85
- package/docs/deployment.md +32 -32
- package/docs/local-models/qwen-image-2.1.json +73 -73
- package/docs/local-models/qwen-image-2.1.md +33 -33
- package/docs/model-architecture.md +78 -78
- package/docs/modes.md +67 -67
- package/lib/agent.mjs +32 -47
- package/lib/analysis-worker.mjs +32 -29
- package/lib/analyze.mjs +85 -78
- package/lib/asset-profile.mjs +23 -21
- package/lib/candidates.mjs +103 -101
- package/lib/comfy-recovery.mjs +17 -17
- package/lib/conversation.mjs +77 -0
- package/lib/core.mjs +75 -89
- package/lib/deployment-guide.mjs +12 -12
- package/lib/design.mjs +29 -29
- package/lib/dimensions.mjs +22 -22
- package/lib/edit.mjs +41 -40
- package/lib/environment-operations.mjs +49 -49
- package/lib/environment-runtime.mjs +99 -99
- package/lib/environments.mjs +55 -55
- package/lib/errors.mjs +32 -0
- package/lib/executor.mjs +107 -107
- package/lib/generate.mjs +58 -57
- package/lib/heartbeat.mjs +16 -16
- package/lib/images.mjs +1 -1
- package/lib/lifecycle.mjs +53 -53
- package/lib/migration.mjs +154 -154
- package/lib/object-format.mjs +112 -0
- package/lib/process-identity.mjs +14 -14
- package/lib/project.mjs +39 -39
- package/lib/refs.mjs +26 -26
- package/lib/runtime.mjs +25 -25
- package/lib/service.mjs +126 -126
- package/lib/settings.mjs +50 -50
- package/lib/shared.mjs +67 -66
- package/lib/style-bundle.mjs +85 -85
- package/lib/style-contract.mjs +74 -35
- package/lib/style-evidence.mjs +39 -0
- package/lib/style-lifecycle.mjs +125 -120
- package/lib/style-report.mjs +201 -0
- package/lib/style-review.mjs +14 -75
- package/lib/task-contract.mjs +93 -91
- package/lib/tasks.mjs +497 -495
- package/lib/templates.mjs +80 -74
- package/lib/vision.mjs +56 -46
- package/lib/workspace.mjs +292 -238
- package/package.json +3 -5
- package/rules/core-guidance.json +22 -22
- package/skills/art-workshop/SKILL.md +17 -116
- package/skills/art-workshop/references/conversation.md +11 -0
- package/skills/art-workshop/references/expression.md +27 -0
- package/skills/art-workshop/references/getty.md +76 -0
- package/skills/art-workshop/references/project.md +109 -0
- package/skills/art-workshop/references/style-discussion.md +27 -0
- package/skills/art-workshop/scripts/getty.py +269 -0
- package/v-cli.plugin.json +2747 -2491
- package/scripts/sync-skill.mjs +0 -6
- /package/{skills/art-workshop → adapters/codex}/agents/openai.yaml +0 -0
|
@@ -1,99 +1,99 @@
|
|
|
1
|
-
import {createHash,randomUUID} from 'node:crypto';
|
|
2
|
-
import {existsSync, mkdirSync, renameSync, realpathSync, lstatSync, writeFileSync, readFileSync, readdirSync} from 'node:fs';
|
|
3
|
-
import {join, resolve, sep} from 'node:path';
|
|
4
|
-
import {spawnSync, spawn} from 'node:child_process';
|
|
5
|
-
import {deploymentGuide} from './deployment-guide.mjs';
|
|
6
|
-
import {locked} from './runtime.mjs';
|
|
7
|
-
import {environmentRoot} from './environments.mjs';
|
|
8
|
-
export function pythonVersion(executable, prefix=[], probe=spawnSync) {
|
|
9
|
-
const result=probe(executable,[...prefix,'-c','import sys,json;print(json.dumps(list(sys.version_info[:3])))'],{encoding:'utf8',timeout:10000,windowsHide:true});
|
|
10
|
-
if(result.status!==0)return null;
|
|
11
|
-
try {const value=JSON.parse(result.stdout.trim());return Array.isArray(value)&&value.length===3&&value.every(Number.isInteger)?value:null;}catch{return null;}
|
|
12
|
-
}
|
|
13
|
-
export function compatiblePython(version, contract) {
|
|
14
|
-
if(!version)return false;
|
|
15
|
-
const bounds=contract.python;if(!bounds)return true;
|
|
16
|
-
const key=v=>v[0]*100+v[1];return key(version)>=key(bounds.min)&&key(version)<key(bounds.maxExclusive);
|
|
17
|
-
}
|
|
18
|
-
export function inspectPython(root, contract, probe=pythonVersion) {
|
|
19
|
-
const candidates=contract.pythonCandidates.filter(path=>existsSync(join(root,path))).map(path=>({path,version:probe(join(root,path))}));
|
|
20
|
-
const selected=candidates.find(item=>compatiblePython(item.version,contract));
|
|
21
|
-
return {python:selected?.path??candidates[0]?.path??contract.pythonCandidates[0],version:selected?.version??candidates[0]?.version??null,compatible:!!selected,required:contract.python??null};
|
|
22
|
-
}
|
|
23
|
-
export async function prepareRuntime(directory,{guideId,signal}={}) {
|
|
24
|
-
signal?.throwIfAborted();
|
|
25
|
-
mkdirSync(directory,{recursive:true});const root=realpathSync(directory),contract=deploymentGuide(guideId).contract;
|
|
26
|
-
return locked(environmentRoot(root),'runtime',async()=>{
|
|
27
|
-
const current=inspectPython(root,contract);
|
|
28
|
-
if(current.compatible) { await ensurePip(root,join(root,current.python),contract,signal); return {root,...current,reused:true}; }
|
|
29
|
-
const preferred=contract.python?.preferred??'3.12';
|
|
30
|
-
const choices=process.platform==='win32'?[['py',['-'+preferred]],['py',['-3.11']],['python',[]]]:[['python'+preferred,[]],['python3.11',[]],['python3',[]]];
|
|
31
|
-
const selected=choices.find(([exe,args])=>compatiblePython(pythonVersion(exe,args),contract));
|
|
32
|
-
if(!selected && process.platform==='win32' && contract.python?.windowsPortable) return preparePortable(root,contract,signal);
|
|
33
|
-
if(!selected)throw new Error('未发现兼容 Python(需要 '+JSON.stringify(contract.python)+');请安装兼容运行时后重试,现有环境未改动');
|
|
34
|
-
const target=resolve(root,'.venv');if(!target.startsWith(root+sep))throw new Error('运行时目录越界');
|
|
35
|
-
let backup;
|
|
36
|
-
if(existsSync(target)) {
|
|
37
|
-
if(lstatSync(target).isSymbolicLink()||!realpathSync(target).startsWith(root+sep))throw new Error('虚拟环境是外部链接,不能替换');
|
|
38
|
-
backup=target+'.previous-'+Date.now();renameSync(target,backup);
|
|
39
|
-
}
|
|
40
|
-
signal?.throwIfAborted();
|
|
41
|
-
await new Promise((resolvePromise,reject)=>{
|
|
42
|
-
const child=spawn(selected[0],[...selected[1],'-m','venv',target],{windowsHide:true,signal,stdio:['ignore','pipe','pipe']});let log='';
|
|
43
|
-
child.stdout.on('data',chunk=>{log=(log+chunk).slice(-8000);});child.stderr.on('data',chunk=>{log=(log+chunk).slice(-8000);});
|
|
44
|
-
child.once('error',reject);child.once('close',code=>code===0?resolvePromise():reject(new Error('创建 Python 环境失败:'+log)));
|
|
45
|
-
});
|
|
46
|
-
const result=inspectPython(root,contract);if(!result.compatible)throw new Error('新环境未通过 Python 版本校验');
|
|
47
|
-
await ensurePip(root,join(root,result.python),contract,signal);
|
|
48
|
-
return {root,...result,reused:false,backup};
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
async function run(executable,args,signal,env=process.env) {
|
|
53
|
-
signal?.throwIfAborted();
|
|
54
|
-
await new Promise((done,reject)=>{
|
|
55
|
-
const child=spawn(executable,args,{windowsHide:true,signal,env,stdio:['ignore','pipe','pipe']});let log='';
|
|
56
|
-
child.stdout.on('data',chunk=>{log=(log+chunk).slice(-8000);});child.stderr.on('data',chunk=>{log=(log+chunk).slice(-8000);});
|
|
57
|
-
child.once('error',reject);child.once('close',code=>code===0?done():reject(new Error('运行时准备失败:'+log)));
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
export async function downloadChecked(url,sha256,file,signal) {
|
|
61
|
-
const bytes=existsSync(file)?readFileSync(file):null;
|
|
62
|
-
if(bytes&&createHash('sha256').update(bytes).digest('hex')===sha256)return;
|
|
63
|
-
const response=await fetch(url,{signal:signal?AbortSignal.any([signal,AbortSignal.timeout(300000)]):AbortSignal.timeout(300000)});
|
|
64
|
-
if(!response.ok)throw new Error('下载运行时失败:HTTP '+response.status);
|
|
65
|
-
const data=Buffer.from(await response.arrayBuffer());
|
|
66
|
-
if(createHash('sha256').update(data).digest('hex')!==sha256)throw new Error('运行时下载 SHA256 不匹配:'+url);
|
|
67
|
-
writeFileSync(file+'.part',data);renameSync(file+'.part',file);
|
|
68
|
-
}
|
|
69
|
-
async function preparePortable(root,contract,signal) {
|
|
70
|
-
const spec=contract.python.windowsPortable;
|
|
71
|
-
const cache=join(root,'.runtime-downloads');mkdirSync(cache,{recursive:true});
|
|
72
|
-
if(lstatSync(cache).isSymbolicLink()||!realpathSync(cache).startsWith(root+sep))throw new Error('下载目录不能指向目标外部');
|
|
73
|
-
const zip=join(cache,'python-'+spec.sha256+'.zip'),pip=join(cache,'get-pip-'+spec.pipSha256+'.py');
|
|
74
|
-
await downloadChecked(spec.url,spec.sha256,zip,signal);await downloadChecked(spec.pipUrl,spec.pipSha256,pip,signal);
|
|
75
|
-
const stage=join(root,'.python-preparing-'+randomUUID());mkdirSync(stage);
|
|
76
|
-
await run('powershell.exe',['-NoProfile','-NonInteractive','-Command',"Expand-Archive -LiteralPath $env:ART_RUNTIME_ZIP -DestinationPath $env:ART_RUNTIME_STAGE"],signal,{...process.env,ART_RUNTIME_ZIP:zip,ART_RUNTIME_STAGE:stage});
|
|
77
|
-
const pth=readdirSync(stage).find(name=>/^python[0-9]+\._pth$/.test(name));if(!pth)throw new Error('Python 便携包缺少路径配置');
|
|
78
|
-
const pathFile=join(stage,pth);writeFileSync(pathFile,readFileSync(pathFile,'utf8').replace('#import site','import site'));
|
|
79
|
-
const executable=join(stage,'python.exe');
|
|
80
|
-
if(!compatiblePython(pythonVersion(executable),contract))throw new Error('下载运行时版本不符合契约');
|
|
81
|
-
await run(executable,[pip,'pip=='+spec.pipVersion],signal);
|
|
82
|
-
await run(executable,['-m','pip','--version'],signal);
|
|
83
|
-
const target=join(root,'python_embeded');let backup;
|
|
84
|
-
if(existsSync(target)) {if(lstatSync(target).isSymbolicLink())throw new Error('已有 Python 是外部链接,不能替换');backup=target+'.previous-'+Date.now();renameSync(target,backup);}
|
|
85
|
-
signal?.throwIfAborted();renameSync(stage,target);
|
|
86
|
-
return {root,...inspectPython(root,contract),reused:false,downloaded:true,backup};
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
async function ensurePip(root,executable,contract,signal) {
|
|
90
|
-
if(spawnSync(executable,['-m','pip','--version'],{windowsHide:true,timeout:15000,stdio:'ignore'}).status===0)return;
|
|
91
|
-
try { await run(executable,['-m','ensurepip'],signal); }
|
|
92
|
-
catch(error) {
|
|
93
|
-
signal?.throwIfAborted();const spec=contract.python?.windowsPortable;if(!spec)throw error;
|
|
94
|
-
const cache=join(root,'.runtime-downloads');mkdirSync(cache,{recursive:true});
|
|
95
|
-
if(lstatSync(cache).isSymbolicLink()||!realpathSync(cache).startsWith(root+sep))throw new Error('下载目录越界');
|
|
96
|
-
const pip=join(cache,'get-pip-'+spec.pipSha256+'.py');await downloadChecked(spec.pipUrl,spec.pipSha256,pip,signal);await run(executable,[pip,'pip=='+spec.pipVersion],signal);
|
|
97
|
-
}
|
|
98
|
-
await run(executable,['-m','pip','--version'],signal);
|
|
99
|
-
}
|
|
1
|
+
import {createHash,randomUUID} from 'node:crypto';
|
|
2
|
+
import {existsSync, mkdirSync, renameSync, realpathSync, lstatSync, writeFileSync, readFileSync, readdirSync} from 'node:fs';
|
|
3
|
+
import {join, resolve, sep} from 'node:path';
|
|
4
|
+
import {spawnSync, spawn} from 'node:child_process';
|
|
5
|
+
import {deploymentGuide} from './deployment-guide.mjs';
|
|
6
|
+
import {locked} from './runtime.mjs';
|
|
7
|
+
import {environmentRoot} from './environments.mjs';
|
|
8
|
+
export function pythonVersion(executable, prefix=[], probe=spawnSync) {
|
|
9
|
+
const result=probe(executable,[...prefix,'-c','import sys,json;print(json.dumps(list(sys.version_info[:3])))'],{encoding:'utf8',timeout:10000,windowsHide:true});
|
|
10
|
+
if(result.status!==0)return null;
|
|
11
|
+
try {const value=JSON.parse(result.stdout.trim());return Array.isArray(value)&&value.length===3&&value.every(Number.isInteger)?value:null;}catch{return null;}
|
|
12
|
+
}
|
|
13
|
+
export function compatiblePython(version, contract) {
|
|
14
|
+
if(!version)return false;
|
|
15
|
+
const bounds=contract.python;if(!bounds)return true;
|
|
16
|
+
const key=v=>v[0]*100+v[1];return key(version)>=key(bounds.min)&&key(version)<key(bounds.maxExclusive);
|
|
17
|
+
}
|
|
18
|
+
export function inspectPython(root, contract, probe=pythonVersion) {
|
|
19
|
+
const candidates=contract.pythonCandidates.filter(path=>existsSync(join(root,path))).map(path=>({path,version:probe(join(root,path))}));
|
|
20
|
+
const selected=candidates.find(item=>compatiblePython(item.version,contract));
|
|
21
|
+
return {python:selected?.path??candidates[0]?.path??contract.pythonCandidates[0],version:selected?.version??candidates[0]?.version??null,compatible:!!selected,required:contract.python??null};
|
|
22
|
+
}
|
|
23
|
+
export async function prepareRuntime(directory,{guideId,signal}={}) {
|
|
24
|
+
signal?.throwIfAborted();
|
|
25
|
+
mkdirSync(directory,{recursive:true});const root=realpathSync(directory),contract=deploymentGuide(guideId).contract;
|
|
26
|
+
return locked(environmentRoot(root),'runtime',async()=>{
|
|
27
|
+
const current=inspectPython(root,contract);
|
|
28
|
+
if(current.compatible) { await ensurePip(root,join(root,current.python),contract,signal); return {root,...current,reused:true}; }
|
|
29
|
+
const preferred=contract.python?.preferred??'3.12';
|
|
30
|
+
const choices=process.platform==='win32'?[['py',['-'+preferred]],['py',['-3.11']],['python',[]]]:[['python'+preferred,[]],['python3.11',[]],['python3',[]]];
|
|
31
|
+
const selected=choices.find(([exe,args])=>compatiblePython(pythonVersion(exe,args),contract));
|
|
32
|
+
if(!selected && process.platform==='win32' && contract.python?.windowsPortable) return preparePortable(root,contract,signal);
|
|
33
|
+
if(!selected)throw new Error('未发现兼容 Python(需要 '+JSON.stringify(contract.python)+');请安装兼容运行时后重试,现有环境未改动');
|
|
34
|
+
const target=resolve(root,'.venv');if(!target.startsWith(root+sep))throw new Error('运行时目录越界');
|
|
35
|
+
let backup;
|
|
36
|
+
if(existsSync(target)) {
|
|
37
|
+
if(lstatSync(target).isSymbolicLink()||!realpathSync(target).startsWith(root+sep))throw new Error('虚拟环境是外部链接,不能替换');
|
|
38
|
+
backup=target+'.previous-'+Date.now();renameSync(target,backup);
|
|
39
|
+
}
|
|
40
|
+
signal?.throwIfAborted();
|
|
41
|
+
await new Promise((resolvePromise,reject)=>{
|
|
42
|
+
const child=spawn(selected[0],[...selected[1],'-m','venv',target],{windowsHide:true,signal,stdio:['ignore','pipe','pipe']});let log='';
|
|
43
|
+
child.stdout.on('data',chunk=>{log=(log+chunk).slice(-8000);});child.stderr.on('data',chunk=>{log=(log+chunk).slice(-8000);});
|
|
44
|
+
child.once('error',reject);child.once('close',code=>code===0?resolvePromise():reject(new Error('创建 Python 环境失败:'+log)));
|
|
45
|
+
});
|
|
46
|
+
const result=inspectPython(root,contract);if(!result.compatible)throw new Error('新环境未通过 Python 版本校验');
|
|
47
|
+
await ensurePip(root,join(root,result.python),contract,signal);
|
|
48
|
+
return {root,...result,reused:false,backup};
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function run(executable,args,signal,env=process.env) {
|
|
53
|
+
signal?.throwIfAborted();
|
|
54
|
+
await new Promise((done,reject)=>{
|
|
55
|
+
const child=spawn(executable,args,{windowsHide:true,signal,env,stdio:['ignore','pipe','pipe']});let log='';
|
|
56
|
+
child.stdout.on('data',chunk=>{log=(log+chunk).slice(-8000);});child.stderr.on('data',chunk=>{log=(log+chunk).slice(-8000);});
|
|
57
|
+
child.once('error',reject);child.once('close',code=>code===0?done():reject(new Error('运行时准备失败:'+log)));
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
export async function downloadChecked(url,sha256,file,signal) {
|
|
61
|
+
const bytes=existsSync(file)?readFileSync(file):null;
|
|
62
|
+
if(bytes&&createHash('sha256').update(bytes).digest('hex')===sha256)return;
|
|
63
|
+
const response=await fetch(url,{signal:signal?AbortSignal.any([signal,AbortSignal.timeout(300000)]):AbortSignal.timeout(300000)});
|
|
64
|
+
if(!response.ok)throw new Error('下载运行时失败:HTTP '+response.status);
|
|
65
|
+
const data=Buffer.from(await response.arrayBuffer());
|
|
66
|
+
if(createHash('sha256').update(data).digest('hex')!==sha256)throw new Error('运行时下载 SHA256 不匹配:'+url);
|
|
67
|
+
writeFileSync(file+'.part',data);renameSync(file+'.part',file);
|
|
68
|
+
}
|
|
69
|
+
async function preparePortable(root,contract,signal) {
|
|
70
|
+
const spec=contract.python.windowsPortable;
|
|
71
|
+
const cache=join(root,'.runtime-downloads');mkdirSync(cache,{recursive:true});
|
|
72
|
+
if(lstatSync(cache).isSymbolicLink()||!realpathSync(cache).startsWith(root+sep))throw new Error('下载目录不能指向目标外部');
|
|
73
|
+
const zip=join(cache,'python-'+spec.sha256+'.zip'),pip=join(cache,'get-pip-'+spec.pipSha256+'.py');
|
|
74
|
+
await downloadChecked(spec.url,spec.sha256,zip,signal);await downloadChecked(spec.pipUrl,spec.pipSha256,pip,signal);
|
|
75
|
+
const stage=join(root,'.python-preparing-'+randomUUID());mkdirSync(stage);
|
|
76
|
+
await run('powershell.exe',['-NoProfile','-NonInteractive','-Command',"Expand-Archive -LiteralPath $env:ART_RUNTIME_ZIP -DestinationPath $env:ART_RUNTIME_STAGE"],signal,{...process.env,ART_RUNTIME_ZIP:zip,ART_RUNTIME_STAGE:stage});
|
|
77
|
+
const pth=readdirSync(stage).find(name=>/^python[0-9]+\._pth$/.test(name));if(!pth)throw new Error('Python 便携包缺少路径配置');
|
|
78
|
+
const pathFile=join(stage,pth);writeFileSync(pathFile,readFileSync(pathFile,'utf8').replace('#import site','import site'));
|
|
79
|
+
const executable=join(stage,'python.exe');
|
|
80
|
+
if(!compatiblePython(pythonVersion(executable),contract))throw new Error('下载运行时版本不符合契约');
|
|
81
|
+
await run(executable,[pip,'pip=='+spec.pipVersion],signal);
|
|
82
|
+
await run(executable,['-m','pip','--version'],signal);
|
|
83
|
+
const target=join(root,'python_embeded');let backup;
|
|
84
|
+
if(existsSync(target)) {if(lstatSync(target).isSymbolicLink())throw new Error('已有 Python 是外部链接,不能替换');backup=target+'.previous-'+Date.now();renameSync(target,backup);}
|
|
85
|
+
signal?.throwIfAborted();renameSync(stage,target);
|
|
86
|
+
return {root,...inspectPython(root,contract),reused:false,downloaded:true,backup};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function ensurePip(root,executable,contract,signal) {
|
|
90
|
+
if(spawnSync(executable,['-m','pip','--version'],{windowsHide:true,timeout:15000,stdio:'ignore'}).status===0)return;
|
|
91
|
+
try { await run(executable,['-m','ensurepip'],signal); }
|
|
92
|
+
catch(error) {
|
|
93
|
+
signal?.throwIfAborted();const spec=contract.python?.windowsPortable;if(!spec)throw error;
|
|
94
|
+
const cache=join(root,'.runtime-downloads');mkdirSync(cache,{recursive:true});
|
|
95
|
+
if(lstatSync(cache).isSymbolicLink()||!realpathSync(cache).startsWith(root+sep))throw new Error('下载目录越界');
|
|
96
|
+
const pip=join(cache,'get-pip-'+spec.pipSha256+'.py');await downloadChecked(spec.pipUrl,spec.pipSha256,pip,signal);await run(executable,[pip,'pip=='+spec.pipVersion],signal);
|
|
97
|
+
}
|
|
98
|
+
await run(executable,['-m','pip','--version'],signal);
|
|
99
|
+
}
|
package/lib/environments.mjs
CHANGED
|
@@ -1,55 +1,55 @@
|
|
|
1
|
-
import {inspectPython} from './environment-runtime.mjs';
|
|
2
|
-
import {existsSync,readFileSync,readdirSync,realpathSync,statSync} from 'node:fs';
|
|
3
|
-
import {homedir} from 'node:os';
|
|
4
|
-
import {join,resolve} from 'node:path';
|
|
5
|
-
import {hash,writeJson} from './shared.mjs';
|
|
6
|
-
import {loadBackend} from './workflows.mjs';
|
|
7
|
-
import {inspectEnvironment} from './diagnostics.mjs';
|
|
8
|
-
import {deploymentGuide} from './deployment-guide.mjs';
|
|
9
|
-
import {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'||!deploymentGuide(value.recipe).contract.pythonCandidates.includes(value.python))throw new Error('美术环境标记无效:'+file);
|
|
20
|
-
return value;
|
|
21
|
-
}
|
|
22
|
-
export function writeMarker(root,{python,endpoint,recipe=deploymentGuide().id,verification='capabilities'}){
|
|
23
|
-
const value={schema:'vant/art-environment-v1',environmentId:hash(realpathSync(root).toLowerCase()),comfy:'ComfyUI',python,endpoint,workflow:deploymentGuide(recipe).contract.backend.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,guideId){
|
|
28
|
-
const profile=deploymentGuide(guideId??readMarker(root)?.recipe).contract;
|
|
29
|
-
const {python}=inspectPython(root,profile);
|
|
30
|
-
return {python,backend:loadBackend({file:join(root,MARKER),generation:{backends:{local:{...profile.backend,endpoints:[endpoint],launch:{executable:join(root,python),cwd:root,args:[...profile.launchArgs,'--port',new URL(endpoint).port||'80']}}}}},'local')};
|
|
31
|
-
}
|
|
32
|
-
export async function inspectInstallation(root,endpoint,guideId){
|
|
33
|
-
endpoint=new URL(endpoint).href;
|
|
34
|
-
root=resolve(root);let marker=null,markerError;try{marker=readMarker(root);}catch(e){markerError=e.message;}
|
|
35
|
-
const PROFILE=deploymentGuide(guideId??marker?.recipe).contract;
|
|
36
|
-
const {python,backend}=backendFor(root,endpoint,PROFILE.id),missing=[];
|
|
37
|
-
const runtime=inspectPython(root,PROFILE);
|
|
38
|
-
if(!runtime.compatible)missing.push('Python 环境缺失或版本不兼容:'+JSON.stringify(runtime));
|
|
39
|
-
for(const path of PROFILE.requiredPaths)if(!existsSync(join(root,path)))missing.push(path);
|
|
40
|
-
for(const model of PROFILE.models){const file=join(root,'ComfyUI/models',model.path);if(!existsSync(file)||statSync(file).size!==model.bytes)missing.push(model.path+'(缺失或大小不符)');}
|
|
41
|
-
let service;try{service=await inspectEnvironment(endpoint,backend);if(service.ok){const edited=loadBackend({file:join(root,MARKER),generation:{backends:{local:{...PROFILE.backend,endpoints:[endpoint]}}}},'local','edit');const editReport=await inspectEnvironment(endpoint,edited);if(!editReport.ok)service=editReport;}}catch{}
|
|
42
|
-
let conflict;
|
|
43
|
-
if(service?.ok===true&&process.platform==='win32'&&!externalIdentity(endpoint,backend.launch))conflict='指定端口属于另一套环境';
|
|
44
|
-
if(marker?.endpoint&&new URL(marker.endpoint).href!==endpoint){try{const previous=await inspectEnvironment(marker.endpoint,backend);if(previous.ok)conflict='此环境已在 '+marker.endpoint+' 运行,请使用原端口或先关闭原服务';}catch{}}
|
|
45
|
-
const models=PROFILE.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}));
|
|
46
|
-
return {guideId:PROFILE.id,models,conflict,root,endpoint,managed:!!marker,markerError,python,runtime,missing,service,reusable:!markerError&&!missing.length,live:service?.ok===true};
|
|
47
|
-
}
|
|
48
|
-
export function discoverInstallations(){
|
|
49
|
-
const found=new Set(),index=join(globalHome(),'state','art-environments');
|
|
50
|
-
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{}}}
|
|
51
|
-
let budget=1500;
|
|
52
|
-
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{}};
|
|
53
|
-
for(const root of [join(globalHome(),'art-env'),join(homedir(),'AI'),...(process.platform==='win32'?['C:/AI','D:/AI','E:/AI']:[])])scan(root,3);
|
|
54
|
-
return [...found];
|
|
55
|
-
}
|
|
1
|
+
import {inspectPython} from './environment-runtime.mjs';
|
|
2
|
+
import {existsSync,readFileSync,readdirSync,realpathSync,statSync} from 'node:fs';
|
|
3
|
+
import {homedir} from 'node:os';
|
|
4
|
+
import {join,resolve} from 'node:path';
|
|
5
|
+
import {hash,writeJson} from './shared.mjs';
|
|
6
|
+
import {loadBackend} from './workflows.mjs';
|
|
7
|
+
import {inspectEnvironment} from './diagnostics.mjs';
|
|
8
|
+
import {deploymentGuide} from './deployment-guide.mjs';
|
|
9
|
+
import {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'||!deploymentGuide(value.recipe).contract.pythonCandidates.includes(value.python))throw new Error('美术环境标记无效:'+file);
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
export function writeMarker(root,{python,endpoint,recipe=deploymentGuide().id,verification='capabilities'}){
|
|
23
|
+
const value={schema:'vant/art-environment-v1',environmentId:hash(realpathSync(root).toLowerCase()),comfy:'ComfyUI',python,endpoint,workflow:deploymentGuide(recipe).contract.backend.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,guideId){
|
|
28
|
+
const profile=deploymentGuide(guideId??readMarker(root)?.recipe).contract;
|
|
29
|
+
const {python}=inspectPython(root,profile);
|
|
30
|
+
return {python,backend:loadBackend({file:join(root,MARKER),generation:{backends:{local:{...profile.backend,endpoints:[endpoint],launch:{executable:join(root,python),cwd:root,args:[...profile.launchArgs,'--port',new URL(endpoint).port||'80']}}}}},'local')};
|
|
31
|
+
}
|
|
32
|
+
export async function inspectInstallation(root,endpoint,guideId){
|
|
33
|
+
endpoint=new URL(endpoint).href;
|
|
34
|
+
root=resolve(root);let marker=null,markerError;try{marker=readMarker(root);}catch(e){markerError=e.message;}
|
|
35
|
+
const PROFILE=deploymentGuide(guideId??marker?.recipe).contract;
|
|
36
|
+
const {python,backend}=backendFor(root,endpoint,PROFILE.id),missing=[];
|
|
37
|
+
const runtime=inspectPython(root,PROFILE);
|
|
38
|
+
if(!runtime.compatible)missing.push('Python 环境缺失或版本不兼容:'+JSON.stringify(runtime));
|
|
39
|
+
for(const path of PROFILE.requiredPaths)if(!existsSync(join(root,path)))missing.push(path);
|
|
40
|
+
for(const model of PROFILE.models){const file=join(root,'ComfyUI/models',model.path);if(!existsSync(file)||statSync(file).size!==model.bytes)missing.push(model.path+'(缺失或大小不符)');}
|
|
41
|
+
let service;try{service=await inspectEnvironment(endpoint,backend);if(service.ok){const edited=loadBackend({file:join(root,MARKER),generation:{backends:{local:{...PROFILE.backend,endpoints:[endpoint]}}}},'local','edit');const editReport=await inspectEnvironment(endpoint,edited);if(!editReport.ok)service=editReport;}}catch{}
|
|
42
|
+
let conflict;
|
|
43
|
+
if(service?.ok===true&&process.platform==='win32'&&!externalIdentity(endpoint,backend.launch))conflict='指定端口属于另一套环境';
|
|
44
|
+
if(marker?.endpoint&&new URL(marker.endpoint).href!==endpoint){try{const previous=await inspectEnvironment(marker.endpoint,backend);if(previous.ok)conflict='此环境已在 '+marker.endpoint+' 运行,请使用原端口或先关闭原服务';}catch{}}
|
|
45
|
+
const models=PROFILE.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}));
|
|
46
|
+
return {guideId:PROFILE.id,models,conflict,root,endpoint,managed:!!marker,markerError,python,runtime,missing,service,reusable:!markerError&&!missing.length,live:service?.ok===true};
|
|
47
|
+
}
|
|
48
|
+
export function discoverInstallations(){
|
|
49
|
+
const found=new Set(),index=join(globalHome(),'state','art-environments');
|
|
50
|
+
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{}}}
|
|
51
|
+
let budget=1500;
|
|
52
|
+
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{}};
|
|
53
|
+
for(const root of [join(globalHome(),'art-env'),join(homedir(),'AI'),...(process.platform==='win32'?['C:/AI','D:/AI','E:/AI']:[])])scan(root,3);
|
|
54
|
+
return [...found];
|
|
55
|
+
}
|
package/lib/errors.mjs
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Expected contract failures are distinct from transport and programming errors. */
|
|
2
|
+
export class ContractError extends Error {
|
|
3
|
+
constructor(message, { code = "INPUT_INVALID", fieldPath } = {}) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "ContractError";
|
|
6
|
+
this.code = code;
|
|
7
|
+
this.fieldPath = fieldPath;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export class AnalysisError extends Error {
|
|
11
|
+
constructor(code, message, detail = {}) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "AnalysisError";
|
|
14
|
+
this.code = code;
|
|
15
|
+
Object.assign(this, detail);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function errorDetail(error, stage) {
|
|
19
|
+
return {
|
|
20
|
+
code: error.code ?? "INTERNAL_ERROR",
|
|
21
|
+
stage,
|
|
22
|
+
message: error.message ?? String(error),
|
|
23
|
+
...(error.fieldPath ? { fieldPath: error.fieldPath } : {}),
|
|
24
|
+
...(error.upstream ? { upstream: error.upstream } : {}),
|
|
25
|
+
...(error.effectiveMaxTokens
|
|
26
|
+
? { effectiveMaxTokens: error.effectiveMaxTokens }
|
|
27
|
+
: {}),
|
|
28
|
+
recovery:
|
|
29
|
+
error.recovery ??
|
|
30
|
+
(error instanceof ContractError ? "fix-input" : "check-original-run"),
|
|
31
|
+
};
|
|
32
|
+
}
|
package/lib/executor.mjs
CHANGED
|
@@ -1,107 +1,107 @@
|
|
|
1
|
-
import {compileRemoteRequest} from './generation-policy.mjs';
|
|
2
|
-
import {adapters} from './adapters/index.mjs';
|
|
3
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from 'node:fs';
|
|
4
|
-
import { join, dirname, resolve, relative, isAbsolute } from 'node:path';
|
|
5
|
-
import { randomUUID } from 'node:crypto';
|
|
6
|
-
import { buildArgs, validatePlan } from './plan.mjs';
|
|
7
|
-
import { hash, writeJson } from './shared.mjs';
|
|
8
|
-
export { validatePlan } from './plan.mjs';
|
|
9
|
-
export { writeJson } from './shared.mjs';
|
|
10
|
-
import { runBl, sha256File, resolveBlEntry } from './bl.mjs';
|
|
11
|
-
import {ownedPath} from './workspace.mjs';
|
|
12
|
-
import {loadSettings,externalPath} from './settings.mjs';
|
|
13
|
-
import {assertExecutableStyle} from './style-contract.mjs';
|
|
14
|
-
|
|
15
|
-
function runtimeVersion() {
|
|
16
|
-
try { return JSON.parse(readFileSync(join(dirname(dirname(resolveBlEntry())), 'package.json'), 'utf8')).version ?? 'unknown'; }
|
|
17
|
-
catch { return 'unknown'; }
|
|
18
|
-
}
|
|
19
|
-
export function executePlan(plan, items, { outputRoot=loadSettings().paths.output, dry = false, runner, log = console.log } = {}) {
|
|
20
|
-
validatePlan(plan);
|
|
21
|
-
assertExecutableStyle(plan);
|
|
22
|
-
if (!items.length) throw new Error('没有选中任何计划项');
|
|
23
|
-
for (const item of items) {
|
|
24
|
-
const expected = plan.items.find(x => x.inputHash === item.inputHash);
|
|
25
|
-
if (!expected || hash(item) !== hash(expected)) throw new Error('执行项不属于该计划或内容已改变');
|
|
26
|
-
}
|
|
27
|
-
for (const ref of plan.refs) { externalPath(ref.path,'原图/参考图'); if (!existsSync(ref.path) || sha256File(ref.path) !== ref.hash) throw new Error(`参考图已变化:${ref.path}`); }
|
|
28
|
-
externalPath(outputRoot,'输出目录');
|
|
29
|
-
if (dry) {
|
|
30
|
-
const requests = items.map(item => ({ output:item.output, ...(item.design?{design:item.design,execution:item.execution}:{}),itemId: item.itemId, variantId: item.variantId, seed: item.seed,
|
|
31
|
-
inputHash: item.inputHash, ...(plan.backend?.provider!=='comfyui'?(()=>{const request=item.request??compileRemoteRequest(plan,item);return {request,wireRequest:adapters.get(request.adapter).preview?.(request)};})():{}), args: buildArgs(plan, item, join(outputRoot,'<runId>'), `${item.itemId}--${item.variantId}`) }));
|
|
32
|
-
log(JSON.stringify({ dry: true, remoteCalls: 0, planHash: plan.planHash, requests }, null, 2));
|
|
33
|
-
return { dry: true, requests };
|
|
34
|
-
}
|
|
35
|
-
if(!runner)throw new Error('真实执行必须使用受管 task 生命周期;executePlan 仅用于预演或注入测试');
|
|
36
|
-
const runId = `${plan.job.replaceAll('/', '-')}-${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID().slice(0, 8)}`;
|
|
37
|
-
const runDir = join(outputRoot, runId);
|
|
38
|
-
mkdirSync(runDir, { recursive: true });
|
|
39
|
-
const manifest = { schema: 'art-workshop/run', runId, plan, planHash: plan.planHash, blVersion: runner === runBl ? runtimeVersion() : 'injected',
|
|
40
|
-
startedAt: new Date().toISOString(), items: [] };
|
|
41
|
-
const manifestPath = join(runDir, 'manifest.json');
|
|
42
|
-
const persist = () => {
|
|
43
|
-
manifest.summary = { completed: manifest.items.filter(x => x.status !== 'running').length, expected: items.length,
|
|
44
|
-
ok: manifest.items.filter(x => x.ok).length, failed: manifest.items.filter(x => x.status === 'failed').length };
|
|
45
|
-
writeJson(manifestPath, manifest);
|
|
46
|
-
};
|
|
47
|
-
persist();
|
|
48
|
-
for (const item of items) {
|
|
49
|
-
const prefix = `${item.itemId}--${item.variantId}`;
|
|
50
|
-
const args = buildArgs(plan, item, runDir, prefix);
|
|
51
|
-
const record = { ...structuredClone(item), args, ok: false, status: 'running', files: [], urls: [], outputHashes: {} };
|
|
52
|
-
manifest.items.push(record); persist();
|
|
53
|
-
const before = new Set(readdirSync(runDir));
|
|
54
|
-
try {
|
|
55
|
-
const response = runner(args);
|
|
56
|
-
const fresh = readdirSync(runDir).filter(f => !before.has(f) && /\.(png|jpe?g|webp)$/i.test(f)).sort();
|
|
57
|
-
fresh.forEach((file, index) => {
|
|
58
|
-
const target = `${prefix}${index ? '--' + (index + 1) : ''}${file.slice(file.lastIndexOf('.'))}`;
|
|
59
|
-
if (file !== target) {
|
|
60
|
-
if (existsSync(join(runDir, target))) throw new Error(`输出文件已存在:${target}`);
|
|
61
|
-
renameSync(join(runDir, file), join(runDir, target));
|
|
62
|
-
}
|
|
63
|
-
record.files.push(target); record.outputHashes[target] = sha256File(join(runDir, target));
|
|
64
|
-
});
|
|
65
|
-
record.urls = response.urls ?? [];
|
|
66
|
-
const expectedCount = (item.execution??plan.execution).perValue;
|
|
67
|
-
if (record.files.length !== expectedCount) throw new Error(`期望 ${expectedCount} 张,实际 ${record.files.length} 张`);
|
|
68
|
-
record.ok = true; record.status = 'generated';
|
|
69
|
-
log(`✔ ${item.itemId}/${item.variantId} seed=${item.seed} → ${record.files.join(', ')}`);
|
|
70
|
-
} catch (e) {
|
|
71
|
-
record.status = 'failed'; record.error = String(e.message ?? e).slice(0, 1000);
|
|
72
|
-
log(`✗ ${item.itemId}/${item.variantId}:${record.error}`);
|
|
73
|
-
}
|
|
74
|
-
persist();
|
|
75
|
-
}
|
|
76
|
-
manifest.finishedAt = new Date().toISOString(); persist();
|
|
77
|
-
log(`manifest → ${manifestPath}`);
|
|
78
|
-
return { manifest, manifestPath, runDir };
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export function outputPath(manifestPath, file) {
|
|
82
|
-
const base = dirname(resolve(manifestPath));
|
|
83
|
-
const path = resolve(base, file);
|
|
84
|
-
const rel = relative(base, path);
|
|
85
|
-
if (isAbsolute(rel) || rel === '..' || rel.startsWith('..\\') || rel.startsWith('../')) throw new Error('输出路径越界');
|
|
86
|
-
return ownedPath(base,file);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export function checkRun(manifest, manifestPath) {
|
|
90
|
-
validatePlan(manifest.plan);
|
|
91
|
-
for (const item of manifest.items) {
|
|
92
|
-
const expected = manifest.plan.items.find(x => x.itemId === item.itemId && x.variantId === item.variantId);
|
|
93
|
-
if (!expected || expected.inputHash !== item.inputHash) throw new Error('执行记录不属于原始计划');
|
|
94
|
-
for (const key of ['prompt', 'seed', 'checks', 'negativeBlock', 'imageArgs', 'execution', 'design', 'output']) {
|
|
95
|
-
if (hash({value:item[key]}) !== hash({value:expected[key]})) throw new Error(`执行记录已改变:${item.itemId}.${key}`);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
return manifest.items.flatMap(item => item.files.length ? item.files.map(file => {
|
|
99
|
-
const path = outputPath(manifestPath, file);
|
|
100
|
-
const exists = existsSync(path), recordedHash = item.outputHashes[file];
|
|
101
|
-
const integrity = exists && sha256File(path) === recordedHash;
|
|
102
|
-
const editable = exists && !!manifest.finishedAt && !item.deleted &&
|
|
103
|
-
(integrity || (!recordedHash && !item.ok && item.status === 'failed'));
|
|
104
|
-
return { itemId: item.itemId, variantId: item.variantId, file, path, integrity, generated: item.ok,
|
|
105
|
-
editable, checks: item.checks, accepted: integrity && item.ok && !!manifest.finishedAt && !item.deleted };
|
|
106
|
-
}) : [{ itemId: item.itemId, variantId: item.variantId, file: null, generated: false, accepted: false, error: item.error }]);
|
|
107
|
-
}
|
|
1
|
+
import {compileRemoteRequest} from './generation-policy.mjs';
|
|
2
|
+
import {adapters} from './adapters/index.mjs';
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from 'node:fs';
|
|
4
|
+
import { join, dirname, resolve, relative, isAbsolute } from 'node:path';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { buildArgs, validatePlan } from './plan.mjs';
|
|
7
|
+
import { hash, writeJson } from './shared.mjs';
|
|
8
|
+
export { validatePlan } from './plan.mjs';
|
|
9
|
+
export { writeJson } from './shared.mjs';
|
|
10
|
+
import { runBl, sha256File, resolveBlEntry } from './bl.mjs';
|
|
11
|
+
import {ownedPath} from './workspace.mjs';
|
|
12
|
+
import {loadSettings,externalPath} from './settings.mjs';
|
|
13
|
+
import {assertExecutableStyle} from './style-contract.mjs';
|
|
14
|
+
|
|
15
|
+
function runtimeVersion() {
|
|
16
|
+
try { return JSON.parse(readFileSync(join(dirname(dirname(resolveBlEntry())), 'package.json'), 'utf8')).version ?? 'unknown'; }
|
|
17
|
+
catch { return 'unknown'; }
|
|
18
|
+
}
|
|
19
|
+
export function executePlan(plan, items, { outputRoot=loadSettings().paths.output, dry = false, runner, log = console.log } = {}) {
|
|
20
|
+
validatePlan(plan);
|
|
21
|
+
assertExecutableStyle(plan);
|
|
22
|
+
if (!items.length) throw new Error('没有选中任何计划项');
|
|
23
|
+
for (const item of items) {
|
|
24
|
+
const expected = plan.items.find(x => x.inputHash === item.inputHash);
|
|
25
|
+
if (!expected || hash(item) !== hash(expected)) throw new Error('执行项不属于该计划或内容已改变');
|
|
26
|
+
}
|
|
27
|
+
for (const ref of plan.refs) { externalPath(ref.path,'原图/参考图'); if (!existsSync(ref.path) || sha256File(ref.path) !== ref.hash) throw new Error(`参考图已变化:${ref.path}`); }
|
|
28
|
+
externalPath(outputRoot,'输出目录');
|
|
29
|
+
if (dry) {
|
|
30
|
+
const requests = items.map(item => ({ output:item.output, ...(item.design?{design:item.design,execution:item.execution}:{}),itemId: item.itemId, variantId: item.variantId, seed: item.seed,
|
|
31
|
+
inputHash: item.inputHash, ...(plan.backend?.provider!=='comfyui'?(()=>{const request=item.request??compileRemoteRequest(plan,item);return {request,wireRequest:adapters.get(request.adapter).preview?.(request)};})():{}), args: buildArgs(plan, item, join(outputRoot,'<runId>'), `${item.itemId}--${item.variantId}`) }));
|
|
32
|
+
log(JSON.stringify({ dry: true, remoteCalls: 0, planHash: plan.planHash, requests }, null, 2));
|
|
33
|
+
return { dry: true, requests };
|
|
34
|
+
}
|
|
35
|
+
if(!runner)throw new Error('真实执行必须使用受管 task 生命周期;executePlan 仅用于预演或注入测试');
|
|
36
|
+
const runId = `${plan.job.replaceAll('/', '-')}-${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID().slice(0, 8)}`;
|
|
37
|
+
const runDir = join(outputRoot, runId);
|
|
38
|
+
mkdirSync(runDir, { recursive: true });
|
|
39
|
+
const manifest = { schema: 'art-workshop/run', runId, plan, planHash: plan.planHash, blVersion: runner === runBl ? runtimeVersion() : 'injected',
|
|
40
|
+
startedAt: new Date().toISOString(), items: [] };
|
|
41
|
+
const manifestPath = join(runDir, 'manifest.json');
|
|
42
|
+
const persist = () => {
|
|
43
|
+
manifest.summary = { completed: manifest.items.filter(x => x.status !== 'running').length, expected: items.length,
|
|
44
|
+
ok: manifest.items.filter(x => x.ok).length, failed: manifest.items.filter(x => x.status === 'failed').length };
|
|
45
|
+
writeJson(manifestPath, manifest);
|
|
46
|
+
};
|
|
47
|
+
persist();
|
|
48
|
+
for (const item of items) {
|
|
49
|
+
const prefix = `${item.itemId}--${item.variantId}`;
|
|
50
|
+
const args = buildArgs(plan, item, runDir, prefix);
|
|
51
|
+
const record = { ...structuredClone(item), args, ok: false, status: 'running', files: [], urls: [], outputHashes: {} };
|
|
52
|
+
manifest.items.push(record); persist();
|
|
53
|
+
const before = new Set(readdirSync(runDir));
|
|
54
|
+
try {
|
|
55
|
+
const response = runner(args);
|
|
56
|
+
const fresh = readdirSync(runDir).filter(f => !before.has(f) && /\.(png|jpe?g|webp)$/i.test(f)).sort();
|
|
57
|
+
fresh.forEach((file, index) => {
|
|
58
|
+
const target = `${prefix}${index ? '--' + (index + 1) : ''}${file.slice(file.lastIndexOf('.'))}`;
|
|
59
|
+
if (file !== target) {
|
|
60
|
+
if (existsSync(join(runDir, target))) throw new Error(`输出文件已存在:${target}`);
|
|
61
|
+
renameSync(join(runDir, file), join(runDir, target));
|
|
62
|
+
}
|
|
63
|
+
record.files.push(target); record.outputHashes[target] = sha256File(join(runDir, target));
|
|
64
|
+
});
|
|
65
|
+
record.urls = response.urls ?? [];
|
|
66
|
+
const expectedCount = (item.execution??plan.execution).perValue;
|
|
67
|
+
if (record.files.length !== expectedCount) throw new Error(`期望 ${expectedCount} 张,实际 ${record.files.length} 张`);
|
|
68
|
+
record.ok = true; record.status = 'generated';
|
|
69
|
+
log(`✔ ${item.itemId}/${item.variantId} seed=${item.seed} → ${record.files.join(', ')}`);
|
|
70
|
+
} catch (e) {
|
|
71
|
+
record.status = 'failed'; record.error = String(e.message ?? e).slice(0, 1000);
|
|
72
|
+
log(`✗ ${item.itemId}/${item.variantId}:${record.error}`);
|
|
73
|
+
}
|
|
74
|
+
persist();
|
|
75
|
+
}
|
|
76
|
+
manifest.finishedAt = new Date().toISOString(); persist();
|
|
77
|
+
log(`manifest → ${manifestPath}`);
|
|
78
|
+
return { manifest, manifestPath, runDir };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function outputPath(manifestPath, file) {
|
|
82
|
+
const base = dirname(resolve(manifestPath));
|
|
83
|
+
const path = resolve(base, file);
|
|
84
|
+
const rel = relative(base, path);
|
|
85
|
+
if (isAbsolute(rel) || rel === '..' || rel.startsWith('..\\') || rel.startsWith('../')) throw new Error('输出路径越界');
|
|
86
|
+
return ownedPath(base,file);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function checkRun(manifest, manifestPath) {
|
|
90
|
+
validatePlan(manifest.plan);
|
|
91
|
+
for (const item of manifest.items) {
|
|
92
|
+
const expected = manifest.plan.items.find(x => x.itemId === item.itemId && x.variantId === item.variantId);
|
|
93
|
+
if (!expected || expected.inputHash !== item.inputHash) throw new Error('执行记录不属于原始计划');
|
|
94
|
+
for (const key of ['prompt', 'seed', 'checks', 'negativeBlock', 'imageArgs', 'execution', 'design', 'output']) {
|
|
95
|
+
if (hash({value:item[key]}) !== hash({value:expected[key]})) throw new Error(`执行记录已改变:${item.itemId}.${key}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return manifest.items.flatMap(item => item.files.length ? item.files.map(file => {
|
|
99
|
+
const path = outputPath(manifestPath, file);
|
|
100
|
+
const exists = existsSync(path), recordedHash = item.outputHashes[file];
|
|
101
|
+
const integrity = exists && sha256File(path) === recordedHash;
|
|
102
|
+
const editable = exists && !!manifest.finishedAt && !item.deleted &&
|
|
103
|
+
(integrity || (!recordedHash && !item.ok && item.status === 'failed'));
|
|
104
|
+
return { itemId: item.itemId, variantId: item.variantId, file, path, integrity, generated: item.ok,
|
|
105
|
+
editable, checks: item.checks, accepted: integrity && item.ok && !!manifest.finishedAt && !item.deleted };
|
|
106
|
+
}) : [{ itemId: item.itemId, variantId: item.variantId, file: null, generated: false, accepted: false, error: item.error }]);
|
|
107
|
+
}
|