@kevlns/art-workshop 0.5.1 → 0.5.2

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.
Files changed (57) hide show
  1. package/AGENTS.md +25 -25
  2. package/LICENSE +21 -21
  3. package/README.md +63 -63
  4. package/art-workshop.mjs +174 -174
  5. package/docs/configuration.md +82 -82
  6. package/docs/core-guidance.md +50 -50
  7. package/docs/data-formats.md +85 -85
  8. package/docs/deployment.md +32 -32
  9. package/docs/local-models/qwen-image-2.1.json +73 -73
  10. package/docs/local-models/qwen-image-2.1.md +33 -33
  11. package/docs/model-architecture.md +78 -78
  12. package/docs/modes.md +67 -67
  13. package/lib/agent.mjs +32 -32
  14. package/lib/analysis-worker.mjs +32 -32
  15. package/lib/analyze.mjs +85 -85
  16. package/lib/asset-profile.mjs +23 -23
  17. package/lib/candidates.mjs +103 -103
  18. package/lib/comfy-recovery.mjs +17 -17
  19. package/lib/conversation.mjs +77 -77
  20. package/lib/core.mjs +75 -75
  21. package/lib/deployment-guide.mjs +12 -12
  22. package/lib/design.mjs +29 -29
  23. package/lib/dimensions.mjs +22 -22
  24. package/lib/edit.mjs +41 -41
  25. package/lib/environment-operations.mjs +49 -49
  26. package/lib/environment-runtime.mjs +99 -99
  27. package/lib/environments.mjs +55 -55
  28. package/lib/executor.mjs +107 -107
  29. package/lib/generate.mjs +58 -58
  30. package/lib/heartbeat.mjs +16 -16
  31. package/lib/images.mjs +1 -1
  32. package/lib/lifecycle.mjs +53 -53
  33. package/lib/migration.mjs +154 -154
  34. package/lib/process-identity.mjs +22 -14
  35. package/lib/project.mjs +39 -39
  36. package/lib/refs.mjs +26 -26
  37. package/lib/runtime.mjs +25 -25
  38. package/lib/service.mjs +134 -126
  39. package/lib/settings.mjs +50 -50
  40. package/lib/shared.mjs +67 -67
  41. package/lib/style-bundle.mjs +85 -85
  42. package/lib/style-contract.mjs +74 -74
  43. package/lib/style-lifecycle.mjs +125 -125
  44. package/lib/style-review.mjs +14 -14
  45. package/lib/task-contract.mjs +93 -93
  46. package/lib/tasks.mjs +497 -497
  47. package/lib/templates.mjs +80 -80
  48. package/lib/vision.mjs +56 -56
  49. package/lib/worker-process.mjs +6 -6
  50. package/lib/workspace.mjs +292 -292
  51. package/package.json +1 -1
  52. package/rules/core-guidance.json +22 -22
  53. package/skills/art-workshop/SKILL.md +17 -17
  54. package/skills/art-workshop/references/conversation.md +11 -11
  55. package/skills/art-workshop/references/expression.md +27 -27
  56. package/skills/art-workshop/references/project.md +109 -109
  57. package/v-cli.plugin.json +2747 -2747
@@ -1,49 +1,49 @@
1
- import {createHash} from 'node:crypto';
2
- import {createReadStream,realpathSync,existsSync,readFileSync,rmSync} from 'node:fs';
3
- import {join} from 'node:path';
4
- import {deploymentGuide} from './deployment-guide.mjs';
5
- import {inspectInstallation,writeMarker,environmentRoot,MARKER} from './environments.mjs';
6
- import {locked} from './runtime.mjs';
7
-
8
- export async function verifyInstallation(directory,endpoint,{cancelled=()=>false,guideId}={}){
9
- const report=await inspectInstallation(directory,endpoint,guideId);
10
- const issues=[...report.missing,...(report.conflict?[report.conflict]:[])];
11
- if(report.markerError)issues.push(report.markerError);
12
- if(!report.live)issues.push('服务与工作流能力尚未通过');
13
- for(const model of deploymentGuide(report.guideId).contract.models){
14
- const file=join(report.root,'ComfyUI/models',model.path);
15
- if(!existsSync(file))continue;
16
- const digest=createHash('sha256');
17
- for await(const chunk of createReadStream(file)){
18
- if(cancelled())throw new Error('环境验收已取消');
19
- digest.update(chunk);
20
- }
21
- if(digest.digest('hex')!==model.sha256)issues.push('SHA256 不匹配:'+model.path);
22
- }
23
- return {...report,ok:issues.length===0,issues,verification:'capabilities',sampleVerified:false,checkedAt:new Date().toISOString()};
24
- }
25
-
26
- export async function registerInstallation(directory,endpoint,{guideId}={}){
27
- const root=realpathSync(directory);
28
- return locked(environmentRoot(root),'registration',async()=>{
29
- const report=await verifyInstallation(root,endpoint,{guideId});
30
- if(!report.ok)throw new Error('环境验收未通过:'+report.issues.join(';'));
31
- const record=writeMarker(root,{python:report.python,endpoint,recipe:report.guideId,verification:'capabilities'});
32
- return {ok:true,root,...record,sampleVerified:false};
33
- });
34
- }
35
-
36
- export async function unregisterInstallation(directory){
37
- const root=realpathSync(directory);
38
- return locked(environmentRoot(root),'registration',async()=>{
39
- const file=join(environmentRoot(root),'environment.json');
40
- if(!existsSync(file))throw new Error('环境未登记');
41
- const record=JSON.parse(readFileSync(file,'utf8'));
42
- if(record.root!==root)throw new Error('环境登记身份不匹配');
43
- // Only registry records are removed; installation and service remain untouched.
44
- rmSync(file);
45
- const marker=join(root,MARKER);
46
- if(existsSync(marker)&&JSON.parse(readFileSync(marker,'utf8')).environmentId===record.environmentId)rmSync(marker);
47
- return {ok:true,root};
48
- });
49
- }
1
+ import {createHash} from 'node:crypto';
2
+ import {createReadStream,realpathSync,existsSync,readFileSync,rmSync} from 'node:fs';
3
+ import {join} from 'node:path';
4
+ import {deploymentGuide} from './deployment-guide.mjs';
5
+ import {inspectInstallation,writeMarker,environmentRoot,MARKER} from './environments.mjs';
6
+ import {locked} from './runtime.mjs';
7
+
8
+ export async function verifyInstallation(directory,endpoint,{cancelled=()=>false,guideId}={}){
9
+ const report=await inspectInstallation(directory,endpoint,guideId);
10
+ const issues=[...report.missing,...(report.conflict?[report.conflict]:[])];
11
+ if(report.markerError)issues.push(report.markerError);
12
+ if(!report.live)issues.push('服务与工作流能力尚未通过');
13
+ for(const model of deploymentGuide(report.guideId).contract.models){
14
+ const file=join(report.root,'ComfyUI/models',model.path);
15
+ if(!existsSync(file))continue;
16
+ const digest=createHash('sha256');
17
+ for await(const chunk of createReadStream(file)){
18
+ if(cancelled())throw new Error('环境验收已取消');
19
+ digest.update(chunk);
20
+ }
21
+ if(digest.digest('hex')!==model.sha256)issues.push('SHA256 不匹配:'+model.path);
22
+ }
23
+ return {...report,ok:issues.length===0,issues,verification:'capabilities',sampleVerified:false,checkedAt:new Date().toISOString()};
24
+ }
25
+
26
+ export async function registerInstallation(directory,endpoint,{guideId}={}){
27
+ const root=realpathSync(directory);
28
+ return locked(environmentRoot(root),'registration',async()=>{
29
+ const report=await verifyInstallation(root,endpoint,{guideId});
30
+ if(!report.ok)throw new Error('环境验收未通过:'+report.issues.join(';'));
31
+ const record=writeMarker(root,{python:report.python,endpoint,recipe:report.guideId,verification:'capabilities'});
32
+ return {ok:true,root,...record,sampleVerified:false};
33
+ });
34
+ }
35
+
36
+ export async function unregisterInstallation(directory){
37
+ const root=realpathSync(directory);
38
+ return locked(environmentRoot(root),'registration',async()=>{
39
+ const file=join(environmentRoot(root),'environment.json');
40
+ if(!existsSync(file))throw new Error('环境未登记');
41
+ const record=JSON.parse(readFileSync(file,'utf8'));
42
+ if(record.root!==root)throw new Error('环境登记身份不匹配');
43
+ // Only registry records are removed; installation and service remain untouched.
44
+ rmSync(file);
45
+ const marker=join(root,MARKER);
46
+ if(existsSync(marker)&&JSON.parse(readFileSync(marker,'utf8')).environmentId===record.environmentId)rmSync(marker);
47
+ return {ok:true,root};
48
+ });
49
+ }
@@ -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
+ }
@@ -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
+ }