@kevlns/art-workshop 0.4.2 → 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 -105
- package/LICENSE +21 -21
- package/README.md +63 -63
- package/art-workshop.mjs +174 -167
- 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 -79
- 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 -0
- 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 -38
- 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 -59
- 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/presentation.mjs +18 -2
- package/lib/process-identity.mjs +14 -14
- package/lib/project.mjs +39 -39
- package/lib/prompt-structure.mjs +7 -3
- 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 -59
- package/lib/tasks.mjs +497 -495
- package/lib/templates.mjs +80 -70
- 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 -112
- 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
package/lib/prompt-structure.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
export
|
|
1
|
+
import {textSpecLine} from './task-contract.mjs';
|
|
2
|
+
export const COMPILER_VERSION = 4;
|
|
3
|
+
const textSection=entries=>entries?.length?`【画面文字规格】\n仅将「」内的内容作为画面文字,其余为布局要求。\n${entries.map(entry=>'- '+textSpecLine(entry)).join('\n')}`:'';
|
|
4
|
+
export function generationPrompt({intent,frozen,details,composition,delivery,asset,references,mustRead,textSpecs}){
|
|
3
5
|
return [
|
|
4
6
|
`【本次用途与主体】\n${intent}。`,
|
|
5
7
|
`【静态冻结风格】\n${frozen}`,
|
|
@@ -7,16 +9,18 @@ export function generationPrompt({intent,frozen,details,composition,delivery,ass
|
|
|
7
9
|
`【动态构图与背景】\n${composition}`,
|
|
8
10
|
`【交付规格与约束】\n${[delivery,asset].filter(Boolean).join('\n')}`,
|
|
9
11
|
mustRead?.length?`【必须可读的特征】\n${[...new Set(mustRead)].map(x=>'- '+x).join('\n')}`:'',
|
|
12
|
+
textSection(textSpecs),
|
|
10
13
|
references,
|
|
11
14
|
].filter(Boolean).join('\n');
|
|
12
15
|
}
|
|
13
|
-
export function editingPrompt({changes,preserve,frozen,references,mustRead}){
|
|
16
|
+
export function editingPrompt({changes,preserve,frozen,references,mustRead,textSpecs}){
|
|
14
17
|
return [
|
|
15
18
|
'【本次任务】\n基于输入原图编辑。未声明修改的部分保持原样。',
|
|
16
19
|
`【动态修改要求】\n${changes.join('\n')}`,
|
|
17
20
|
`【动态保留要求】\n${preserve.join('\n')}`,
|
|
18
21
|
frozen?`【静态冻结风格】\n${frozen}`:'',
|
|
19
22
|
mustRead?.length?`【必须可读的特征】\n${[...new Set(mustRead)].map(x=>'- '+x).join('\n')}`:'',
|
|
23
|
+
textSection(textSpecs),
|
|
20
24
|
references,
|
|
21
25
|
].filter(Boolean).join('\n');
|
|
22
26
|
}
|
package/lib/refs.mjs
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
import {existsSync,mkdirSync,statSync} from 'node:fs';
|
|
2
|
-
import {join,resolve} from 'node:path';
|
|
3
|
-
import {externalPath} from './settings.mjs';
|
|
4
|
-
|
|
5
|
-
import {REFERENCE_CATEGORIES} from './style-contract.mjs';
|
|
6
|
-
export {REFERENCE_CATEGORIES} from './style-contract.mjs';
|
|
7
|
-
export function referenceRoot({defaultRefsDir,refsDir}={}) {
|
|
8
|
-
return externalPath(refsDir??defaultRefsDir,'素材导入目录');
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export function ensureReferenceDirectories(root) {
|
|
12
|
-
root=externalPath(root,'参考目录');
|
|
13
|
-
const paths=[root,...REFERENCE_CATEGORIES.map(category=>externalPath(join(root,category.directory),'参考分类目录'))];
|
|
14
|
-
for(const path of paths) if(existsSync(path)&&!statSync(path).isDirectory()) throw new Error(`参考目录位置被文件占用:${path}`);
|
|
15
|
-
for(const path of paths) mkdirSync(path,{recursive:true});
|
|
16
|
-
return root;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export function referenceGuide(root) {
|
|
20
|
-
return ['# 美术工坊参考职责',`素材导入目录:${root}`,'',
|
|
21
|
-
'| 风格目录 | 提炼范围 | 示例 |','| --- | --- | --- |',
|
|
22
|
-
...REFERENCE_CATEGORIES.map(x=>`| ${x.directory}/ | ${x.purpose} | ${x.recommended} |`),'',
|
|
23
|
-
'风格静态参考归属 styleId,仅在分析中理解;生成读取冻结核心,不自动上传静态参考。',
|
|
24
|
-
'任务动态参考归属 taskId:subject/composition/pose/identity-color/surface/scene-light/text;编辑底图单独保存在 sources。',
|
|
25
|
-
'reference import 显式导入到对象私有目录。发现、配置与预演不创建参考目录,不自动识别、扫描或绑定素材。'].join('\n');
|
|
26
|
-
}
|
|
1
|
+
import {existsSync,mkdirSync,statSync} from 'node:fs';
|
|
2
|
+
import {join,resolve} from 'node:path';
|
|
3
|
+
import {externalPath} from './settings.mjs';
|
|
4
|
+
|
|
5
|
+
import {REFERENCE_CATEGORIES} from './style-contract.mjs';
|
|
6
|
+
export {REFERENCE_CATEGORIES} from './style-contract.mjs';
|
|
7
|
+
export function referenceRoot({defaultRefsDir,refsDir}={}) {
|
|
8
|
+
return externalPath(refsDir??defaultRefsDir,'素材导入目录');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function ensureReferenceDirectories(root) {
|
|
12
|
+
root=externalPath(root,'参考目录');
|
|
13
|
+
const paths=[root,...REFERENCE_CATEGORIES.map(category=>externalPath(join(root,category.directory),'参考分类目录'))];
|
|
14
|
+
for(const path of paths) if(existsSync(path)&&!statSync(path).isDirectory()) throw new Error(`参考目录位置被文件占用:${path}`);
|
|
15
|
+
for(const path of paths) mkdirSync(path,{recursive:true});
|
|
16
|
+
return root;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function referenceGuide(root) {
|
|
20
|
+
return ['# 美术工坊参考职责',`素材导入目录:${root}`,'',
|
|
21
|
+
'| 风格目录 | 提炼范围 | 示例 |','| --- | --- | --- |',
|
|
22
|
+
...REFERENCE_CATEGORIES.map(x=>`| ${x.directory}/ | ${x.purpose} | ${x.recommended} |`),'',
|
|
23
|
+
'风格静态参考归属 styleId,仅在分析中理解;生成读取冻结核心,不自动上传静态参考。',
|
|
24
|
+
'任务动态参考归属 taskId:subject/composition/pose/identity-color/surface/scene-light/text;编辑底图单独保存在 sources。',
|
|
25
|
+
'reference import 显式导入到对象私有目录。发现、配置与预演不创建参考目录,不自动识别、扫描或绑定素材。'].join('\n');
|
|
26
|
+
}
|
package/lib/runtime.mjs
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
import {existsSync,mkdirSync,rmSync,readdirSync,lstatSync} from 'node:fs';
|
|
2
|
-
import {join,resolve,relative,isAbsolute} from 'node:path';
|
|
3
|
-
import {randomUUID} from 'node:crypto';
|
|
4
|
-
import {readJson,writeJson,id} from './shared.mjs';
|
|
5
|
-
export const sleep=ms=>new Promise(r=>setTimeout(r,ms));
|
|
6
|
-
export {terminal} from './lifecycle.mjs';
|
|
7
|
-
// A workspace owns its runs and mutation guard. Selecting another configuration
|
|
8
|
-
// must not create a second execution registry for the same objects.
|
|
9
|
-
export const runtimeRoot=settings=>join(resolve(settings.paths.workspace),'.runtime');
|
|
10
|
-
export function alive(pid){try{process.kill(pid,0);return true;}catch{return false;}}
|
|
11
|
-
export function stateRead(path){return existsSync(path)?readJson(path):null;}
|
|
12
|
-
export async function locked(root,name,fn,{timeout=150000}={}) {
|
|
13
|
-
if(!/^[a-z0-9-]+$/.test(name))throw new Error('非法锁名称');
|
|
14
|
-
mkdirSync(root,{recursive:true});const path=join(root,name+'.lock'),token=randomUUID(),deadline=Date.now()+timeout;
|
|
15
|
-
const rel=relative(resolve(root),resolve(path));if(isAbsolute(rel)||rel.startsWith('..'))throw new Error('锁路径越界');
|
|
16
|
-
while(true){try{mkdirSync(path);writeJson(join(path,'owner.json'),{pid:process.pid,token});break;}catch(e){if(e.code!=='EEXIST')throw e;if(lstatSync(path).isSymbolicLink())throw new Error('锁目录不能是链接');const owner=stateRead(join(path,'owner.json'));if(owner&&!alive(owner.pid)){rmSync(path,{recursive:true});continue;}if(Date.now()>deadline)throw new Error('等待锁超时 '+name);await sleep(100);}}
|
|
17
|
-
try{return await fn();}finally{if(stateRead(join(path,'owner.json'))?.token===token)rmSync(path,{recursive:true});}
|
|
18
|
-
}
|
|
19
|
-
export function taskFile(root,taskId){id(taskId,'task');return join(root,'tasks',taskId+'.json');}
|
|
20
|
-
export function tasks(root){const dir=join(root,'tasks');return existsSync(dir)?readdirSync(dir).filter(x=>x.endsWith('.json')).map(x=>stateRead(join(dir,x))).filter(x=>x?.schema==='art-workshop/task'):[];}
|
|
21
|
-
export async function http(endpoint,path,{method='GET',body,timeout=10000}={}) {
|
|
22
|
-
const response=await fetch(new URL(path,endpoint),{method,signal:AbortSignal.timeout(timeout),...(body?{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});
|
|
23
|
-
if(!response.ok){const content=await response.text(),error=new Error(`ComfyUI HTTP ${response.status}: ${content.slice(0,1000)}`);error.httpStatus=response.status;try{error.response=JSON.parse(content);}catch{};throw error;}
|
|
24
|
-
const content=await response.text();return content?JSON.parse(content):{};
|
|
25
|
-
}
|
|
1
|
+
import {existsSync,mkdirSync,rmSync,readdirSync,lstatSync} from 'node:fs';
|
|
2
|
+
import {join,resolve,relative,isAbsolute} from 'node:path';
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
import {readJson,writeJson,id} from './shared.mjs';
|
|
5
|
+
export const sleep=ms=>new Promise(r=>setTimeout(r,ms));
|
|
6
|
+
export {terminal} from './lifecycle.mjs';
|
|
7
|
+
// A workspace owns its runs and mutation guard. Selecting another configuration
|
|
8
|
+
// must not create a second execution registry for the same objects.
|
|
9
|
+
export const runtimeRoot=settings=>join(resolve(settings.paths.workspace),'.runtime');
|
|
10
|
+
export function alive(pid){try{process.kill(pid,0);return true;}catch{return false;}}
|
|
11
|
+
export function stateRead(path){return existsSync(path)?readJson(path):null;}
|
|
12
|
+
export async function locked(root,name,fn,{timeout=150000}={}) {
|
|
13
|
+
if(!/^[a-z0-9-]+$/.test(name))throw new Error('非法锁名称');
|
|
14
|
+
mkdirSync(root,{recursive:true});const path=join(root,name+'.lock'),token=randomUUID(),deadline=Date.now()+timeout;
|
|
15
|
+
const rel=relative(resolve(root),resolve(path));if(isAbsolute(rel)||rel.startsWith('..'))throw new Error('锁路径越界');
|
|
16
|
+
while(true){try{mkdirSync(path);writeJson(join(path,'owner.json'),{pid:process.pid,token});break;}catch(e){if(e.code!=='EEXIST')throw e;if(lstatSync(path).isSymbolicLink())throw new Error('锁目录不能是链接');const owner=stateRead(join(path,'owner.json'));if(owner&&!alive(owner.pid)){rmSync(path,{recursive:true});continue;}if(Date.now()>deadline)throw new Error('等待锁超时 '+name);await sleep(100);}}
|
|
17
|
+
try{return await fn();}finally{if(stateRead(join(path,'owner.json'))?.token===token)rmSync(path,{recursive:true});}
|
|
18
|
+
}
|
|
19
|
+
export function taskFile(root,taskId){id(taskId,'task');return join(root,'tasks',taskId+'.json');}
|
|
20
|
+
export function tasks(root){const dir=join(root,'tasks');return existsSync(dir)?readdirSync(dir).filter(x=>x.endsWith('.json')).map(x=>stateRead(join(dir,x))).filter(x=>x?.schema==='art-workshop/task'):[];}
|
|
21
|
+
export async function http(endpoint,path,{method='GET',body,timeout=10000}={}) {
|
|
22
|
+
const response=await fetch(new URL(path,endpoint),{method,signal:AbortSignal.timeout(timeout),...(body?{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});
|
|
23
|
+
if(!response.ok){const content=await response.text(),error=new Error(`ComfyUI HTTP ${response.status}: ${content.slice(0,1000)}`);error.httpStatus=response.status;try{error.response=JSON.parse(content);}catch{};throw error;}
|
|
24
|
+
const content=await response.text();return content?JSON.parse(content):{};
|
|
25
|
+
}
|
package/lib/service.mjs
CHANGED
|
@@ -1,126 +1,126 @@
|
|
|
1
|
-
import {processIdentity} from './process-identity.mjs';
|
|
2
|
-
export {processIdentity} from './process-identity.mjs';
|
|
3
|
-
import {homedir} from 'node:os';
|
|
4
|
-
import {spawn,execFileSync} from 'node:child_process';
|
|
5
|
-
import {openSync,closeSync,existsSync,readdirSync} from 'node:fs';
|
|
6
|
-
import {createServer} from 'node:net';
|
|
7
|
-
import {join,resolve} from 'node:path';
|
|
8
|
-
import {writeJson,hash} from './shared.mjs';
|
|
9
|
-
import {http,sleep,locked,stateRead,alive} from './runtime.mjs';
|
|
10
|
-
import {inspectEnvironment,workflowError} from './diagnostics.mjs';
|
|
11
|
-
|
|
12
|
-
export async function stopIdentity(identity,{timeout=10000}={}) {
|
|
13
|
-
const current=processIdentity(identity.pid);
|
|
14
|
-
if(!current)return;
|
|
15
|
-
if(hash(current)!==hash(identity))throw new Error('服务进程身份已变化,拒绝终止复用的 PID');
|
|
16
|
-
if(process.platform==='win32')execFileSync('taskkill.exe',['/PID',String(identity.pid),'/T','/F'],{windowsHide:true});
|
|
17
|
-
else process.kill(identity.pid,'SIGTERM');
|
|
18
|
-
const deadline=Date.now()+timeout;
|
|
19
|
-
while(alive(identity.pid)){if(Date.now()>deadline)throw new Error('服务进程未停止');await sleep(100);}
|
|
20
|
-
}
|
|
21
|
-
export async function healthy(endpoint,backend) {
|
|
22
|
-
try {
|
|
23
|
-
const stats=await http(endpoint,'/system_stats',{timeout:2000});if(!stats.system?.comfyui_version)return false;
|
|
24
|
-
const [major,minor]=stats.system.comfyui_version.split('.').map(Number);
|
|
25
|
-
if(major===0&&minor<39)return false;
|
|
26
|
-
if(backend.template){const nodes=await http(endpoint,'/object_info',{timeout:4000});for(const n of Object.values(backend.template))if(!nodes[n.class_type])return false;}
|
|
27
|
-
return stats;
|
|
28
|
-
}catch{return false;}
|
|
29
|
-
}
|
|
30
|
-
export const serviceRoot=()=>join(process.env.VANT_HOME??join(homedir(),'.vant'),'state','art-services');
|
|
31
|
-
function serviceFile(root,endpoint){return join(serviceRoot(),'services',hash(endpoint)+'.json');}
|
|
32
|
-
export function externalIdentity(endpoint,launch) {
|
|
33
|
-
if(process.platform!=='win32'||!launch)return null;
|
|
34
|
-
const port=Number(new URL(endpoint).port||80);
|
|
35
|
-
const script=`Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique | ConvertTo-Json -Compress`;
|
|
36
|
-
let pids;try{pids=JSON.parse(execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true}).trim()||'null');}catch{return null;}
|
|
37
|
-
for(const pid of [].concat(pids??[])) {
|
|
38
|
-
const p=processIdentity(pid);
|
|
39
|
-
if(!p?.exe||resolve(p.exe).toLowerCase()!==resolve(launch.executable).toLowerCase())continue;
|
|
40
|
-
// Require the configured entrypoint, not just a Python interpreter or an occupied port.
|
|
41
|
-
const entry=launch.args.find(x=>/main\.py$|\.mjs$|\.js$/.test(x));
|
|
42
|
-
if(!entry||!p.command.toLowerCase().includes(entry.toLowerCase()))continue;
|
|
43
|
-
return p;
|
|
44
|
-
}
|
|
45
|
-
return null;
|
|
46
|
-
}
|
|
47
|
-
export async function ensureService(backend,root,{cancelled=()=>false}={}) {
|
|
48
|
-
root=serviceRoot();
|
|
49
|
-
return locked(root,'services',async()=>{
|
|
50
|
-
if(stateRead(join(root,'shutdown.json')))throw new Error('服务正在 shutdown');
|
|
51
|
-
const incompatible=[];
|
|
52
|
-
for(const endpoint of backend.endpoints) {
|
|
53
|
-
let report;try{report=await inspectEnvironment(endpoint,backend);}catch{continue;}
|
|
54
|
-
if(!report.ok){incompatible.push(report);continue;}
|
|
55
|
-
const file=serviceFile(root,endpoint),previous=stateRead(file);
|
|
56
|
-
const identity=previous?.identity&&hash(processIdentity(previous.identity.pid))===hash(previous.identity)?previous.identity:externalIdentity(endpoint,backend.launch);
|
|
57
|
-
const sameOwner=!!(identity&&previous?.owned&&hash(previous.identity)===hash(identity));
|
|
58
|
-
writeJson(file,{endpoint,backend:backend.id,identity,owned:sameOwner,...(sameOwner&&previous.owner?{owner:previous.owner}:{}),observedAt:new Date().toISOString()});
|
|
59
|
-
return endpoint;
|
|
60
|
-
}
|
|
61
|
-
if(incompatible.length){const error=workflowError('现有 ComfyUI 环境无法执行工作流',backend,{stage:'environment'});error.diagnostic.environments=incompatible;throw error;}
|
|
62
|
-
if(!backend.launch)throw new Error('没有可用 ComfyUI,也未配置 launch');
|
|
63
|
-
if(cancelled())throw new Error('任务已取消');
|
|
64
|
-
const endpoint=backend.endpoints[0],file=serviceFile(root,endpoint),previous=stateRead(file);
|
|
65
|
-
if(previous?.identity&&hash(processIdentity(previous.identity.pid))===hash(previous.identity))throw new Error('现有服务不健康,请先 shutdown;不重复启动');
|
|
66
|
-
const logPath=join(root,'comfyui-'+hash(endpoint).slice(0,8)+'.log'),fd=openSync(logPath,'a');
|
|
67
|
-
const child=spawn(backend.launch.executable,backend.launch.args,{cwd:backend.launch.cwd,detached:true,windowsHide:true,stdio:['ignore',fd,fd]});closeSync(fd);
|
|
68
|
-
let spawnError;child.once('error',error=>{spawnError=error;});child.unref();
|
|
69
|
-
await sleep(100);
|
|
70
|
-
if(spawnError||!child.pid)throw spawnError??new Error('服务启动失败');
|
|
71
|
-
const identity=processIdentity(child.pid);if(!identity)throw new Error('无法记录服务进程身份');
|
|
72
|
-
writeJson(file,{endpoint,backend:backend.id,identity,owned:true,...(process.env.VANT_SERVICE_INSTANCE?{owner:{application:'vant',instanceId:process.env.VANT_SERVICE_INSTANCE}}:{}),logPath});
|
|
73
|
-
const deadline=Date.now()+(backend.launch.startupTimeoutSeconds??120)*1000;
|
|
74
|
-
try {
|
|
75
|
-
while(Date.now()<deadline){if(cancelled())throw new Error('任务已取消');let report;try{report=await inspectEnvironment(endpoint,backend);}catch{};if(report?.ok)return endpoint;if(report){const error=workflowError('启动后的 ComfyUI 环境无法执行工作流,查看 '+logPath,backend,{stage:'environment'});error.diagnostic.environments=[report];throw error;}if(!alive(child.pid))throw new Error('ComfyUI 进程提前退出,查看 '+logPath);await sleep(300);}
|
|
76
|
-
throw new Error('ComfyUI 启动超时,查看 '+logPath);
|
|
77
|
-
}catch(error){await stopIdentity(identity);throw error;}
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
export function rememberedService(root,endpoint){return stateRead(serviceFile(root,endpoint));}
|
|
81
|
-
// Application exit never adopts an external process as a termination target.
|
|
82
|
-
export async function shutdownOwnedServices() {
|
|
83
|
-
return locked(serviceRoot(),'control',async()=>{
|
|
84
|
-
const folder=join(serviceRoot(),'services'),results=[],failures=[];
|
|
85
|
-
for(const name of existsSync(folder)?readdirSync(folder):[]) {
|
|
86
|
-
if(!name.endsWith('.json'))continue;
|
|
87
|
-
const file=join(folder,name),record=stateRead(file);
|
|
88
|
-
if(record?.owned!==true||record.owner?.application!=='vant'||record.stopped)continue;
|
|
89
|
-
try {
|
|
90
|
-
if(!record.identity)throw new Error('缺少服务进程身份,不能确认停止');
|
|
91
|
-
const url=new URL(record.endpoint);
|
|
92
|
-
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('服务地址不是本机回环地址');
|
|
93
|
-
if(name!==hash(record.endpoint)+'.json')throw new Error('服务记录身份不匹配');
|
|
94
|
-
await stopIdentity(record.identity);
|
|
95
|
-
const deadline=Date.now()+15000;
|
|
96
|
-
while(true){
|
|
97
|
-
try {
|
|
98
|
-
await new Promise((resolve,reject)=>{
|
|
99
|
-
const probe=createServer();probe.once('error',reject);
|
|
100
|
-
probe.listen({host:'127.0.0.1',port:Number(url.port||80),exclusive:true},()=>probe.close(error=>error?reject(error):resolve()));
|
|
101
|
-
});
|
|
102
|
-
break;
|
|
103
|
-
}catch(error){if(error.code!=='EADDRINUSE'||Date.now()>deadline)throw error;await sleep(200);}
|
|
104
|
-
}
|
|
105
|
-
writeJson(file,{...record,owned:false,stopped:true,stoppedAt:new Date().toISOString()});
|
|
106
|
-
results.push({endpoint:record.endpoint,stopped:true,portReleased:true});
|
|
107
|
-
}catch(error){failures.push(record.endpoint+': '+error.message);}
|
|
108
|
-
}
|
|
109
|
-
if(failures.length)throw new Error('本机服务清理未确认:'+failures.join('; '));
|
|
110
|
-
return results;
|
|
111
|
-
});
|
|
112
|
-
}
|
|
113
|
-
export async function closeService(root,endpoint,backend) {
|
|
114
|
-
return locked(serviceRoot(),'queue-'+new URL(endpoint).port,()=>closeSharedService(serviceRoot(),endpoint,backend));
|
|
115
|
-
}
|
|
116
|
-
async function closeSharedService(root,endpoint,backend) {
|
|
117
|
-
if(await healthy(endpoint,backend)){const queue=await http(endpoint,'/queue');if((queue.queue_running??[]).length||(queue.queue_pending??[]).length)throw new Error('共享服务仍有其他任务,保留服务');}
|
|
118
|
-
const remembered=rememberedService(root,endpoint);
|
|
119
|
-
const previous=remembered?.identity;
|
|
120
|
-
const identity=previous&&hash(processIdentity(previous.pid))===hash(previous)?previous:externalIdentity(endpoint,backend.launch);
|
|
121
|
-
if(!identity){if(await healthy(endpoint,backend))throw new Error('无法验证服务进程身份:'+endpoint);return {endpoint,stopped:false};}
|
|
122
|
-
await stopIdentity(identity);
|
|
123
|
-
if(await healthy(endpoint,backend))throw new Error('关闭进程后服务仍可访问:'+endpoint);
|
|
124
|
-
writeJson(serviceFile(root,endpoint),{endpoint,stopped:true,stoppedAt:new Date().toISOString()});
|
|
125
|
-
return {endpoint,stopped:true};
|
|
126
|
-
}
|
|
1
|
+
import {processIdentity} from './process-identity.mjs';
|
|
2
|
+
export {processIdentity} from './process-identity.mjs';
|
|
3
|
+
import {homedir} from 'node:os';
|
|
4
|
+
import {spawn,execFileSync} from 'node:child_process';
|
|
5
|
+
import {openSync,closeSync,existsSync,readdirSync} from 'node:fs';
|
|
6
|
+
import {createServer} from 'node:net';
|
|
7
|
+
import {join,resolve} from 'node:path';
|
|
8
|
+
import {writeJson,hash} from './shared.mjs';
|
|
9
|
+
import {http,sleep,locked,stateRead,alive} from './runtime.mjs';
|
|
10
|
+
import {inspectEnvironment,workflowError} from './diagnostics.mjs';
|
|
11
|
+
|
|
12
|
+
export async function stopIdentity(identity,{timeout=10000}={}) {
|
|
13
|
+
const current=processIdentity(identity.pid);
|
|
14
|
+
if(!current)return;
|
|
15
|
+
if(hash(current)!==hash(identity))throw new Error('服务进程身份已变化,拒绝终止复用的 PID');
|
|
16
|
+
if(process.platform==='win32')execFileSync('taskkill.exe',['/PID',String(identity.pid),'/T','/F'],{windowsHide:true});
|
|
17
|
+
else process.kill(identity.pid,'SIGTERM');
|
|
18
|
+
const deadline=Date.now()+timeout;
|
|
19
|
+
while(alive(identity.pid)){if(Date.now()>deadline)throw new Error('服务进程未停止');await sleep(100);}
|
|
20
|
+
}
|
|
21
|
+
export async function healthy(endpoint,backend) {
|
|
22
|
+
try {
|
|
23
|
+
const stats=await http(endpoint,'/system_stats',{timeout:2000});if(!stats.system?.comfyui_version)return false;
|
|
24
|
+
const [major,minor]=stats.system.comfyui_version.split('.').map(Number);
|
|
25
|
+
if(major===0&&minor<39)return false;
|
|
26
|
+
if(backend.template){const nodes=await http(endpoint,'/object_info',{timeout:4000});for(const n of Object.values(backend.template))if(!nodes[n.class_type])return false;}
|
|
27
|
+
return stats;
|
|
28
|
+
}catch{return false;}
|
|
29
|
+
}
|
|
30
|
+
export const serviceRoot=()=>join(process.env.VANT_HOME??join(homedir(),'.vant'),'state','art-services');
|
|
31
|
+
function serviceFile(root,endpoint){return join(serviceRoot(),'services',hash(endpoint)+'.json');}
|
|
32
|
+
export function externalIdentity(endpoint,launch) {
|
|
33
|
+
if(process.platform!=='win32'||!launch)return null;
|
|
34
|
+
const port=Number(new URL(endpoint).port||80);
|
|
35
|
+
const script=`Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique | ConvertTo-Json -Compress`;
|
|
36
|
+
let pids;try{pids=JSON.parse(execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true}).trim()||'null');}catch{return null;}
|
|
37
|
+
for(const pid of [].concat(pids??[])) {
|
|
38
|
+
const p=processIdentity(pid);
|
|
39
|
+
if(!p?.exe||resolve(p.exe).toLowerCase()!==resolve(launch.executable).toLowerCase())continue;
|
|
40
|
+
// Require the configured entrypoint, not just a Python interpreter or an occupied port.
|
|
41
|
+
const entry=launch.args.find(x=>/main\.py$|\.mjs$|\.js$/.test(x));
|
|
42
|
+
if(!entry||!p.command.toLowerCase().includes(entry.toLowerCase()))continue;
|
|
43
|
+
return p;
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
export async function ensureService(backend,root,{cancelled=()=>false}={}) {
|
|
48
|
+
root=serviceRoot();
|
|
49
|
+
return locked(root,'services',async()=>{
|
|
50
|
+
if(stateRead(join(root,'shutdown.json')))throw new Error('服务正在 shutdown');
|
|
51
|
+
const incompatible=[];
|
|
52
|
+
for(const endpoint of backend.endpoints) {
|
|
53
|
+
let report;try{report=await inspectEnvironment(endpoint,backend);}catch{continue;}
|
|
54
|
+
if(!report.ok){incompatible.push(report);continue;}
|
|
55
|
+
const file=serviceFile(root,endpoint),previous=stateRead(file);
|
|
56
|
+
const identity=previous?.identity&&hash(processIdentity(previous.identity.pid))===hash(previous.identity)?previous.identity:externalIdentity(endpoint,backend.launch);
|
|
57
|
+
const sameOwner=!!(identity&&previous?.owned&&hash(previous.identity)===hash(identity));
|
|
58
|
+
writeJson(file,{endpoint,backend:backend.id,identity,owned:sameOwner,...(sameOwner&&previous.owner?{owner:previous.owner}:{}),observedAt:new Date().toISOString()});
|
|
59
|
+
return endpoint;
|
|
60
|
+
}
|
|
61
|
+
if(incompatible.length){const error=workflowError('现有 ComfyUI 环境无法执行工作流',backend,{stage:'environment'});error.diagnostic.environments=incompatible;throw error;}
|
|
62
|
+
if(!backend.launch)throw new Error('没有可用 ComfyUI,也未配置 launch');
|
|
63
|
+
if(cancelled())throw new Error('任务已取消');
|
|
64
|
+
const endpoint=backend.endpoints[0],file=serviceFile(root,endpoint),previous=stateRead(file);
|
|
65
|
+
if(previous?.identity&&hash(processIdentity(previous.identity.pid))===hash(previous.identity))throw new Error('现有服务不健康,请先 shutdown;不重复启动');
|
|
66
|
+
const logPath=join(root,'comfyui-'+hash(endpoint).slice(0,8)+'.log'),fd=openSync(logPath,'a');
|
|
67
|
+
const child=spawn(backend.launch.executable,backend.launch.args,{cwd:backend.launch.cwd,detached:true,windowsHide:true,stdio:['ignore',fd,fd]});closeSync(fd);
|
|
68
|
+
let spawnError;child.once('error',error=>{spawnError=error;});child.unref();
|
|
69
|
+
await sleep(100);
|
|
70
|
+
if(spawnError||!child.pid)throw spawnError??new Error('服务启动失败');
|
|
71
|
+
const identity=processIdentity(child.pid);if(!identity)throw new Error('无法记录服务进程身份');
|
|
72
|
+
writeJson(file,{endpoint,backend:backend.id,identity,owned:true,...(process.env.VANT_SERVICE_INSTANCE?{owner:{application:'vant',instanceId:process.env.VANT_SERVICE_INSTANCE}}:{}),logPath});
|
|
73
|
+
const deadline=Date.now()+(backend.launch.startupTimeoutSeconds??120)*1000;
|
|
74
|
+
try {
|
|
75
|
+
while(Date.now()<deadline){if(cancelled())throw new Error('任务已取消');let report;try{report=await inspectEnvironment(endpoint,backend);}catch{};if(report?.ok)return endpoint;if(report){const error=workflowError('启动后的 ComfyUI 环境无法执行工作流,查看 '+logPath,backend,{stage:'environment'});error.diagnostic.environments=[report];throw error;}if(!alive(child.pid))throw new Error('ComfyUI 进程提前退出,查看 '+logPath);await sleep(300);}
|
|
76
|
+
throw new Error('ComfyUI 启动超时,查看 '+logPath);
|
|
77
|
+
}catch(error){await stopIdentity(identity);throw error;}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
export function rememberedService(root,endpoint){return stateRead(serviceFile(root,endpoint));}
|
|
81
|
+
// Application exit never adopts an external process as a termination target.
|
|
82
|
+
export async function shutdownOwnedServices() {
|
|
83
|
+
return locked(serviceRoot(),'control',async()=>{
|
|
84
|
+
const folder=join(serviceRoot(),'services'),results=[],failures=[];
|
|
85
|
+
for(const name of existsSync(folder)?readdirSync(folder):[]) {
|
|
86
|
+
if(!name.endsWith('.json'))continue;
|
|
87
|
+
const file=join(folder,name),record=stateRead(file);
|
|
88
|
+
if(record?.owned!==true||record.owner?.application!=='vant'||record.stopped)continue;
|
|
89
|
+
try {
|
|
90
|
+
if(!record.identity)throw new Error('缺少服务进程身份,不能确认停止');
|
|
91
|
+
const url=new URL(record.endpoint);
|
|
92
|
+
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('服务地址不是本机回环地址');
|
|
93
|
+
if(name!==hash(record.endpoint)+'.json')throw new Error('服务记录身份不匹配');
|
|
94
|
+
await stopIdentity(record.identity);
|
|
95
|
+
const deadline=Date.now()+15000;
|
|
96
|
+
while(true){
|
|
97
|
+
try {
|
|
98
|
+
await new Promise((resolve,reject)=>{
|
|
99
|
+
const probe=createServer();probe.once('error',reject);
|
|
100
|
+
probe.listen({host:'127.0.0.1',port:Number(url.port||80),exclusive:true},()=>probe.close(error=>error?reject(error):resolve()));
|
|
101
|
+
});
|
|
102
|
+
break;
|
|
103
|
+
}catch(error){if(error.code!=='EADDRINUSE'||Date.now()>deadline)throw error;await sleep(200);}
|
|
104
|
+
}
|
|
105
|
+
writeJson(file,{...record,owned:false,stopped:true,stoppedAt:new Date().toISOString()});
|
|
106
|
+
results.push({endpoint:record.endpoint,stopped:true,portReleased:true});
|
|
107
|
+
}catch(error){failures.push(record.endpoint+': '+error.message);}
|
|
108
|
+
}
|
|
109
|
+
if(failures.length)throw new Error('本机服务清理未确认:'+failures.join('; '));
|
|
110
|
+
return results;
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
export async function closeService(root,endpoint,backend) {
|
|
114
|
+
return locked(serviceRoot(),'queue-'+new URL(endpoint).port,()=>closeSharedService(serviceRoot(),endpoint,backend));
|
|
115
|
+
}
|
|
116
|
+
async function closeSharedService(root,endpoint,backend) {
|
|
117
|
+
if(await healthy(endpoint,backend)){const queue=await http(endpoint,'/queue');if((queue.queue_running??[]).length||(queue.queue_pending??[]).length)throw new Error('共享服务仍有其他任务,保留服务');}
|
|
118
|
+
const remembered=rememberedService(root,endpoint);
|
|
119
|
+
const previous=remembered?.identity;
|
|
120
|
+
const identity=previous&&hash(processIdentity(previous.pid))===hash(previous)?previous:externalIdentity(endpoint,backend.launch);
|
|
121
|
+
if(!identity){if(await healthy(endpoint,backend))throw new Error('无法验证服务进程身份:'+endpoint);return {endpoint,stopped:false};}
|
|
122
|
+
await stopIdentity(identity);
|
|
123
|
+
if(await healthy(endpoint,backend))throw new Error('关闭进程后服务仍可访问:'+endpoint);
|
|
124
|
+
writeJson(serviceFile(root,endpoint),{endpoint,stopped:true,stoppedAt:new Date().toISOString()});
|
|
125
|
+
return {endpoint,stopped:true};
|
|
126
|
+
}
|
package/lib/settings.mjs
CHANGED
|
@@ -1,50 +1,50 @@
|
|
|
1
|
-
import {existsSync,readFileSync,realpathSync} from 'node:fs';
|
|
2
|
-
import {execFileSync} from 'node:child_process';
|
|
3
|
-
import {homedir} from 'node:os';
|
|
4
|
-
import {dirname,basename,join,resolve,relative,isAbsolute} from 'node:path';
|
|
5
|
-
import {fileURLToPath} from 'node:url';
|
|
6
|
-
import {readJson,writeJson,keys,text,id} from './shared.mjs';
|
|
7
|
-
import {execution} from './plan.mjs';
|
|
8
|
-
import {generationConfig} from './backends.mjs';
|
|
9
|
-
export const TOOL_ROOT=dirname(dirname(fileURLToPath(import.meta.url)));
|
|
10
|
-
export function downloadsDirectory({platform=process.platform,home=homedir(),env=process.env,knownFolder}={}) {
|
|
11
|
-
if(platform==='win32') {
|
|
12
|
-
try {
|
|
13
|
-
const read=knownFolder??(()=>JSON.parse(execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); $downloadPath = (Get-ItemProperty -LiteralPath 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders').'{374DE290-123F-4565-9164-39C4925E467B}'; $downloadPath | ConvertTo-Json -Compress"],{encoding:'utf8',windowsHide:true}).trim()));
|
|
14
|
-
const value=read();if(typeof value==='string'&&value.trim()){const expanded=value.replace(/%([^%]+)%/g,(_,name)=>Object.entries(env).find(([key])=>key.toLowerCase()===name.toLowerCase())?.[1]??'%'+name+'%');if(!expanded.includes('%'))return expanded;}
|
|
15
|
-
}catch{}
|
|
16
|
-
}
|
|
17
|
-
if(platform==='linux') {
|
|
18
|
-
const file=join(env.XDG_CONFIG_HOME??join(home,'.config'),'user-dirs.dirs');
|
|
19
|
-
if(existsSync(file)){const match=readFileSync(file,'utf8').match(/^XDG_DOWNLOAD_DIR="([^"]+)"/m);if(match){const value=match[1].replace(/\$\{HOME\}|\$HOME/g,home);if(!value.includes('$')&&isAbsolute(value))return resolve(value);}}
|
|
20
|
-
}
|
|
21
|
-
return join(home,'Downloads');
|
|
22
|
-
}
|
|
23
|
-
export function externalPath(value,label='路径') {
|
|
24
|
-
text(value,label,2048);const path=resolve(value);
|
|
25
|
-
let ancestor=path;const tail=[];while(!existsSync(ancestor)){const parent=dirname(ancestor);if(parent===ancestor)break;tail.unshift(basename(ancestor));ancestor=parent;}
|
|
26
|
-
const actual=existsSync(ancestor)?join(realpathSync(ancestor),...tail):path;
|
|
27
|
-
const rel=relative(realpathSync(TOOL_ROOT),actual);
|
|
28
|
-
if(rel===''||!isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..\\')&&!rel.startsWith('../'))throw new Error(`${label} 必须在工具目录之外:${path}`);
|
|
29
|
-
return path;
|
|
30
|
-
}
|
|
31
|
-
export function configFile(env=process.env,home=homedir(),platform=process.platform) {
|
|
32
|
-
return externalPath(env.ART_WORKSHOP_CONFIG??join(env.VANT_HOME??join(home,'.vant'),'tools','art-workshop','config.json'),'本地配置');
|
|
33
|
-
}
|
|
34
|
-
export function loadSettings({file=configFile(),workspace,output,refs,cache}={}) {
|
|
35
|
-
const base=join(process.env.VANT_HOME??join(homedir(),'.vant'),'tools','art-workshop','workspace');
|
|
36
|
-
const local=existsSync(file)?readJson(file):{};
|
|
37
|
-
keys(local,['paths','execution','generation','analysisModel','defaultProject','autoSyncSkills'],'config');
|
|
38
|
-
keys(local.paths??{},['workspace','output','refs','cache'],'config.paths');
|
|
39
|
-
execution({execution:{}},{},local.execution??{});
|
|
40
|
-
if(local.analysisModel!==undefined&&local.analysisModel!==null)text(local.analysisModel,'analysisModel');
|
|
41
|
-
if(local.defaultProject!==undefined&&local.defaultProject!==null)id(local.defaultProject,'defaultProject');
|
|
42
|
-
if(local.autoSyncSkills!==undefined&&typeof local.autoSyncSkills!=='boolean')throw new Error('autoSyncSkills 必须为布尔值');
|
|
43
|
-
const overrides={workspace,output,refs,cache},defaults={workspace:base,output:base,refs:join(base,'refs'),cache:join(base,'.cache')};
|
|
44
|
-
const paths=Object.fromEntries(Object.keys(defaults).map(key=>[key,externalPath(overrides[key]??local.paths?.[key]??defaults[key],key)]));
|
|
45
|
-
return {file:externalPath(file,'本地配置'),paths,execution:local.execution??{},generation:generationConfig(local.generation??{}),analysisModel:local.analysisModel??null,defaultProject:local.defaultProject??null
|
|
46
|
-
}
|
|
47
|
-
export function initSettings(file=configFile()) {
|
|
48
|
-
externalPath(file,'本地配置');if(existsSync(file))return loadSettings({file});
|
|
49
|
-
const {file:ignored,...config}=loadSettings({file});writeJson(file,config);return loadSettings({file});
|
|
50
|
-
}
|
|
1
|
+
import {existsSync,readFileSync,realpathSync} from 'node:fs';
|
|
2
|
+
import {execFileSync} from 'node:child_process';
|
|
3
|
+
import {homedir} from 'node:os';
|
|
4
|
+
import {dirname,basename,join,resolve,relative,isAbsolute} from 'node:path';
|
|
5
|
+
import {fileURLToPath} from 'node:url';
|
|
6
|
+
import {readJson,writeJson,keys,text,id} from './shared.mjs';
|
|
7
|
+
import {execution} from './plan.mjs';
|
|
8
|
+
import {generationConfig} from './backends.mjs';
|
|
9
|
+
export const TOOL_ROOT=dirname(dirname(fileURLToPath(import.meta.url)));
|
|
10
|
+
export function downloadsDirectory({platform=process.platform,home=homedir(),env=process.env,knownFolder}={}) {
|
|
11
|
+
if(platform==='win32') {
|
|
12
|
+
try {
|
|
13
|
+
const read=knownFolder??(()=>JSON.parse(execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); $downloadPath = (Get-ItemProperty -LiteralPath 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders').'{374DE290-123F-4565-9164-39C4925E467B}'; $downloadPath | ConvertTo-Json -Compress"],{encoding:'utf8',windowsHide:true}).trim()));
|
|
14
|
+
const value=read();if(typeof value==='string'&&value.trim()){const expanded=value.replace(/%([^%]+)%/g,(_,name)=>Object.entries(env).find(([key])=>key.toLowerCase()===name.toLowerCase())?.[1]??'%'+name+'%');if(!expanded.includes('%'))return expanded;}
|
|
15
|
+
}catch{}
|
|
16
|
+
}
|
|
17
|
+
if(platform==='linux') {
|
|
18
|
+
const file=join(env.XDG_CONFIG_HOME??join(home,'.config'),'user-dirs.dirs');
|
|
19
|
+
if(existsSync(file)){const match=readFileSync(file,'utf8').match(/^XDG_DOWNLOAD_DIR="([^"]+)"/m);if(match){const value=match[1].replace(/\$\{HOME\}|\$HOME/g,home);if(!value.includes('$')&&isAbsolute(value))return resolve(value);}}
|
|
20
|
+
}
|
|
21
|
+
return join(home,'Downloads');
|
|
22
|
+
}
|
|
23
|
+
export function externalPath(value,label='路径') {
|
|
24
|
+
text(value,label,2048);const path=resolve(value);
|
|
25
|
+
let ancestor=path;const tail=[];while(!existsSync(ancestor)){const parent=dirname(ancestor);if(parent===ancestor)break;tail.unshift(basename(ancestor));ancestor=parent;}
|
|
26
|
+
const actual=existsSync(ancestor)?join(realpathSync(ancestor),...tail):path;
|
|
27
|
+
const rel=relative(realpathSync(TOOL_ROOT),actual);
|
|
28
|
+
if(rel===''||!isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..\\')&&!rel.startsWith('../'))throw new Error(`${label} 必须在工具目录之外:${path}`);
|
|
29
|
+
return path;
|
|
30
|
+
}
|
|
31
|
+
export function configFile(env=process.env,home=homedir(),platform=process.platform) {
|
|
32
|
+
return externalPath(env.ART_WORKSHOP_CONFIG??join(env.VANT_HOME??join(home,'.vant'),'tools','art-workshop','config.json'),'本地配置');
|
|
33
|
+
}
|
|
34
|
+
export function loadSettings({file=configFile(),workspace,output,refs,cache}={}) {
|
|
35
|
+
const base=join(process.env.VANT_HOME??join(homedir(),'.vant'),'tools','art-workshop','workspace');
|
|
36
|
+
const local=existsSync(file)?readJson(file):{};
|
|
37
|
+
keys(local,['paths','execution','generation','analysisModel','defaultProject','autoSyncSkills'],'config');
|
|
38
|
+
keys(local.paths??{},['workspace','output','refs','cache'],'config.paths');
|
|
39
|
+
execution({execution:{}},{},local.execution??{});
|
|
40
|
+
if(local.analysisModel!==undefined&&local.analysisModel!==null)text(local.analysisModel,'analysisModel');
|
|
41
|
+
if(local.defaultProject!==undefined&&local.defaultProject!==null)id(local.defaultProject,'defaultProject');
|
|
42
|
+
if(local.autoSyncSkills!==undefined&&typeof local.autoSyncSkills!=='boolean')throw new Error('autoSyncSkills 必须为布尔值');
|
|
43
|
+
const overrides={workspace,output,refs,cache},defaults={workspace:base,output:base,refs:join(base,'refs'),cache:join(base,'.cache')};
|
|
44
|
+
const paths=Object.fromEntries(Object.keys(defaults).map(key=>[key,externalPath(overrides[key]??local.paths?.[key]??defaults[key],key)]));
|
|
45
|
+
return {file:externalPath(file,'本地配置'),paths,execution:local.execution??{},generation:generationConfig(local.generation??{}),analysisModel:local.analysisModel??null,defaultProject:local.defaultProject??null};
|
|
46
|
+
}
|
|
47
|
+
export function initSettings(file=configFile()) {
|
|
48
|
+
externalPath(file,'本地配置');if(existsSync(file))return loadSettings({file});
|
|
49
|
+
const {file:ignored,...config}=loadSettings({file});writeJson(file,config);return loadSettings({file});
|
|
50
|
+
}
|