@kevlns/art-workshop 0.3.8 → 0.3.11

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.
@@ -1,12 +1,11 @@
1
- import {createHash} from 'node:crypto';
2
- import {existsSync,readFileSync,readdirSync,realpathSync,statSync,createReadStream} from 'node:fs';
1
+ import {existsSync,readFileSync,readdirSync,realpathSync,statSync} from 'node:fs';
3
2
  import {homedir} from 'node:os';
4
- import {join,resolve,dirname} from 'node:path';
3
+ import {join,resolve} from 'node:path';
5
4
  import {hash,writeJson} from './shared.mjs';
6
- import {loadBackend,BUILTIN_WORKFLOW} from './workflows.mjs';
5
+ import {loadBackend} from './workflows.mjs';
7
6
  import {inspectEnvironment} from './diagnostics.mjs';
8
- import {LOCAL_RECIPE} from './deployment.mjs';
9
- import {ensureService,externalIdentity} from './service.mjs';
7
+ import {deploymentGuide} from './deployment-guide.mjs';
8
+ import {externalIdentity} from './service.mjs';
10
9
  export const MARKER='vant.art.config.json';
11
10
  export const globalHome=()=>resolve(process.env.VANT_HOME??join(homedir(),'.vant'));
12
11
  export const defaultInstallRoot=()=>join(globalHome(),'art-env');
@@ -16,31 +15,32 @@ export function readMarker(root){
16
15
  const value=JSON.parse(readFileSync(file,'utf8'));
17
16
  let endpoint;try{endpoint=new URL(value.endpoint);}catch{throw new Error('环境标记缺少合法服务地址');}
18
17
  if(endpoint.protocol!=='http:'||!['127.0.0.1','localhost'].includes(endpoint.hostname)||endpoint.pathname!=='/'||endpoint.search||endpoint.hash||endpoint.username||endpoint.password)throw new Error('环境标记只允许本机 HTTP 根地址');
19
- if(value.schema!=='vant/art-environment-v1'||value.comfy!=='ComfyUI'||!['python_embeded/python.exe','.venv/Scripts/python.exe'].includes(value.python))throw new Error('美术环境标记无效:'+file);
18
+ if(value.schema!=='vant/art-environment-v1'||value.comfy!=='ComfyUI'||!deploymentGuide(value.recipe).contract.pythonCandidates.includes(value.python))throw new Error('美术环境标记无效:'+file);
20
19
  return value;
21
20
  }
22
- export function writeMarker(root,{python,endpoint,recipe,verification='capabilities'}){
23
- const value={schema:'vant/art-environment-v1',environmentId:hash(realpathSync(root).toLowerCase()),comfy:'ComfyUI',python,endpoint,workflow:BUILTIN_WORKFLOW,recipe,verification,verifiedAt:new Date().toISOString()};
21
+ export function writeMarker(root,{python,endpoint,recipe=deploymentGuide().id,verification='capabilities'}){
22
+ 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
23
  writeJson(join(root,MARKER),value);
25
24
  writeJson(join(environmentRoot(root),'environment.json'),{root:realpathSync(root),...value});return value;
26
25
  }
27
- export function backendFor(root,endpoint){
28
- const python=existsSync(join(root,'python_embeded/python.exe'))?'python_embeded/python.exe':'.venv/Scripts/python.exe';
29
- return {python,backend:loadBackend({file:join(root,'vant.art.config.json'),generation:{backends:{local:{provider:'comfyui',model:'qwen-image-2.1-UC-Q4_K_M.gguf',endpoints:[endpoint],launch:{executable:join(root,python),cwd:root,args:['-s','ComfyUI/main.py','--disable-dynamic-vram','--lowvram','--disable-auto-launch','--port',new URL(endpoint).port||'80']}}}}},'local')};
26
+ export function backendFor(root,endpoint,guideId){
27
+ const profile=deploymentGuide(guideId??readMarker(root)?.recipe).contract;
28
+ const python=profile.pythonCandidates.find(candidate=>existsSync(join(root,candidate)))??profile.pythonCandidates[0];
29
+ 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')};
30
30
  }
31
- export async function inspectInstallation(root,endpoint){
31
+ export async function inspectInstallation(root,endpoint,guideId){
32
32
  root=resolve(root);let marker=null,markerError;try{marker=readMarker(root);}catch(e){markerError=e.message;}
33
- const {python,backend}=backendFor(root,endpoint),missing=[];
33
+ const PROFILE=deploymentGuide(guideId??marker?.recipe).contract;
34
+ const {python,backend}=backendFor(root,endpoint,PROFILE.id),missing=[];
34
35
  if(!existsSync(join(root,python)))missing.push('Python 环境');
35
- if(!existsSync(join(root,'ComfyUI/main.py')))missing.push('ComfyUI');
36
- if(!existsSync(join(root,'ComfyUI/custom_nodes/ComfyUI-GGUF')))missing.push('ComfyUI-GGUF 节点');
37
- for(const model of LOCAL_RECIPE.models){const file=join(root,'ComfyUI/models',model.path);if(!existsSync(file)||statSync(file).size!==model.bytes)missing.push(model.path+'(缺失或大小不符)');}
38
- let service;try{service=await inspectEnvironment(endpoint,backend);if(service.ok){const edited=loadBackend({file:join(root,MARKER),generation:{backends:{local:{provider:'comfyui',model:backend.model,endpoints:[endpoint]}}}},'local','edit');const editReport=await inspectEnvironment(endpoint,edited);if(!editReport.ok)service=editReport;}}catch{}
36
+ for(const path of PROFILE.requiredPaths)if(!existsSync(join(root,path)))missing.push(path);
37
+ 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+'(缺失或大小不符)');}
38
+ 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{}
39
39
  let conflict;
40
40
  if(service?.ok===true&&process.platform==='win32'&&!externalIdentity(endpoint,backend.launch))conflict='指定端口属于另一套环境';
41
41
  if(marker?.endpoint&&marker.endpoint!==endpoint){try{const previous=await inspectEnvironment(marker.endpoint,backend);if(previous.ok)conflict='此环境已在 '+marker.endpoint+' 运行,请使用原端口或先关闭原服务';}catch{}}
42
- const models=LOCAL_RECIPE.models.map(model=>({path:model.path,bytes:model.bytes,present:existsSync(join(root,'ComfyUI/models',model.path))&&statSync(join(root,'ComfyUI/models',model.path)).size===model.bytes}));
43
- return {models,conflict,root,endpoint,managed:!!marker,markerError,python,missing,service,reusable:!markerError&&!missing.length,live:service?.ok===true};
42
+ 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}));
43
+ return {guideId:PROFILE.id,models,conflict,root,endpoint,managed:!!marker,markerError,python,missing,service,reusable:!markerError&&!missing.length,live:service?.ok===true};
44
44
  }
45
45
  export function discoverInstallations(){
46
46
  const found=new Set(),index=join(globalHome(),'state','art-environments');
@@ -50,18 +50,3 @@ export function discoverInstallations(){
50
50
  for(const root of [join(globalHome(),'art-env'),join(homedir(),'AI'),...(process.platform==='win32'?['C:/AI','D:/AI','E:/AI']:[])])scan(root,3);
51
51
  return [...found];
52
52
  }
53
- export async function adoptInstallation(root,endpoint,{cancelled=()=>false,onStage=()=>{}}={}){
54
- const report=await inspectInstallation(root,endpoint);if(!report.reusable)throw new Error('现有环境需要补齐:'+report.missing.join('、'));
55
- for(const model of LOCAL_RECIPE.models){
56
- onStage('校验已有模型 '+model.path);const digest=createHash('sha256');
57
- for await(const chunk of createReadStream(join(report.root,'ComfyUI/models',model.path))){if(cancelled())throw new Error('接入已取消');digest.update(chunk);}
58
- if(digest.digest('hex')!==model.sha256)throw new Error('模型校验失败,保留原文件:'+model.path);
59
- }
60
- onStage('核验服务与工作流能力');
61
- const {backend,python}=backendFor(report.root,endpoint);
62
- if(report.live&&process.platform==='win32'&&!externalIdentity(endpoint,backend.launch))throw new Error('端口由其他环境占用,不能将其登记到指定目录');
63
- await ensureService(backend,join(environmentRoot(report.root),'runtime'),{cancelled});
64
- const current=await inspectInstallation(report.root,endpoint);if(!current.live)throw new Error('现有环境工作流能力检测未通过');
65
- if(cancelled())throw new Error('接入已取消');
66
- writeMarker(report.root,{python,endpoint,verification:'capabilities'});return current;
67
- }
@@ -0,0 +1,85 @@
1
+ import {readFileSync,writeFileSync,mkdirSync,existsSync,renameSync,rmSync,readdirSync} from 'node:fs';
2
+ import {join,resolve,relative,isAbsolute} from 'node:path';
3
+ import {randomUUID,createHash} from 'node:crypto';
4
+ import {readObject,objectDirectory,ownedPath,verifyReferences} from './workspace.mjs';
5
+ import {hash,id,readJson,writeJson} from './shared.mjs';
6
+ import {loadProject} from './project.mjs';
7
+ import {locked,runtimeRoot} from './runtime.mjs';
8
+
9
+ const bytesHash=b=>createHash('sha256').update(b).digest('hex');
10
+ const safe=(root,path)=>{if(typeof path!=='string'||!path||isAbsolute(path)||path.includes('\\')||path.split('/').some(x=>!x||x==='.'||x==='..'))throw new Error('风格包资源路径非法');return ownedPath(root,path);};
11
+ export function validateStyleBundle(bundle){
12
+ if(bundle?.schema!=='art-workshop/style-bundle'||bundle.schemaVersion!==1)throw new Error('风格包格式不支持');
13
+ const {bundleHash,...body}=bundle;if(hash(body)!==bundleHash)throw new Error('风格包完整性校验失败');
14
+ const {coreHash,...core}=bundle.core??{};
15
+ if(hash(core)!==coreHash||bundle.style?.status!=='frozen'||bundle.style.coreHash!==coreHash||bundle.style.id!==core.id||bundle.style.project!==core.project)throw new Error('冻结风格身份或核心校验失败');
16
+ id(core.id);id(core.project);
17
+ if(!Array.isArray(bundle.style.references)||!Array.isArray(bundle.files)||bundle.files.length>500)throw new Error('风格包参考非法');
18
+ const seen=new Set();let total=0;
19
+ for(const file of bundle.files){
20
+ safe('/bundle',file.path);if(seen.has(file.path))throw new Error('风格包路径重复');seen.add(file.path);
21
+ if(typeof file.data!=='string')throw new Error('风格包图片数据非法');
22
+ const bytes=Buffer.from(file.data,'base64');total+=bytes.length;
23
+ if(bytes.toString('base64')!==file.data||bytesHash(bytes)!==file.hash||total>100*1024*1024)throw new Error('风格包图片校验失败或超限');
24
+ }
25
+ for(const ref of bundle.style.references){safe('/bundle',ref.path);if(!bundle.files.some(file=>file.path===ref.path&&file.hash===ref.hash))throw new Error('风格包缺少参考依赖');}
26
+ if(bundle.files.some(file=>!bundle.style.references.some(ref=>ref.path===file.path)))throw new Error('风格包包含未声明的参考资源');
27
+ return bundle;
28
+ }
29
+ export function exportStyleBundle(root,project,styleId,destination){
30
+ const style=readObject(root,project,'style',styleId);
31
+ if(style.status!=='frozen')throw new Error('只可导出已冻结风格');
32
+ const core=readJson(ownedPath(objectDirectory(root,project,'style',styleId),'core.json'));
33
+ const references=verifyReferences(root,style);
34
+ // Export only frozen evidence and explicitly owned reference bytes, never settings or runtime files.
35
+ const files=references.map(ref=>({path:style.references.find(item=>item.id===ref.id).path,hash:ref.hash,data:readFileSync(ref.path).toString('base64')}));
36
+ const portable={schema:style.schema,schemaVersion:style.schemaVersion,project:style.project,id:style.id,name:style.name,revision:style.revision,status:style.status,coreHash:style.coreHash,createdAt:style.createdAt,updatedAt:style.updatedAt,config:style.config,references:style.references,report:{data:core.report,sourceRevision:style.revision,path:null,runId:null,sourceHash:null},source:style.source??null};
37
+ const body={schema:'art-workshop/style-bundle',schemaVersion:1,style:portable,core,files};
38
+ const bundle=validateStyleBundle({...body,bundleHash:hash(body)});
39
+ if(existsSync(destination))throw new Error('导出目标已存在,不覆盖共享风格');
40
+ mkdirSync(resolve(destination,'..'),{recursive:true});writeFileSync(destination,JSON.stringify(bundle,null,2)+'\n',{flag:'wx'});
41
+ return {path:destination,id:style.id,revision:style.revision,bundleHash:bundle.bundleHash};
42
+ }
43
+ export function listStyleSources(directories){
44
+ const sources=directories.map(directory=>{
45
+ const items=[],errors=[];
46
+ try{for(const file of readdirSync(directory).filter(file=>file.endsWith('.style.json')).sort()){
47
+ try{const path=ownedPath(directory,file),raw=readFileSync(path);if(raw.length>150*1024*1024)throw new Error('风格包超限');const bundle=validateStyleBundle(JSON.parse(raw));items.push({path,id:bundle.style.id,name:bundle.style.name,revision:bundle.style.revision,coreHash:bundle.core.coreHash,bundleHash:bundle.bundleHash,project:bundle.style.project});}
48
+ catch(error){errors.push(file+':'+error.message);}
49
+ }}catch(error){errors.push(error.message);}
50
+ return {directory,items,...(errors.length?{error:errors.join(';')}:{})};
51
+ });
52
+ for(const source of sources)for(const item of source.items){
53
+ item.conflict=sources.flatMap(source=>source.items).some(other=>other.project===item.project&&other.id===item.id&&other.revision===item.revision&&other.coreHash!==item.coreHash);
54
+ }
55
+ return sources;
56
+ }
57
+ export async function importStyleBundle(settings,projectId,file,expectedHash){
58
+ const raw=readFileSync(file);if(raw.length>150*1024*1024)throw new Error('风格包超限');
59
+ const bundle=validateStyleBundle(JSON.parse(raw));
60
+ if(expectedHash && bundle.bundleHash!==expectedHash)throw new Error("来源风格已变化,请刷新后重新选择");
61
+ return locked(runtimeRoot(settings),'control',async()=>{
62
+ const root=settings.paths.workspace,project=loadProject(projectId,root);
63
+ const localId='shared-'+bundle.bundleHash.slice(0,32);
64
+ const directory=objectDirectory(root,projectId,'style',localId);
65
+ if(existsSync(directory)){
66
+ const existing=readObject(root,projectId,'style',localId);
67
+ if(existing.source?.bundleHash!==bundle.bundleHash)throw new Error('导入身份冲突');
68
+ verifyReferences(root,existing);return existing;
69
+ }
70
+ const origin={id:bundle.style.id,project:bundle.style.project,revision:bundle.style.revision,coreHash:bundle.core.coreHash,bundleHash:bundle.bundleHash};
71
+ const body={...bundle.core,project:projectId,id:localId,report:{...bundle.core.report,project:projectId,id:localId},origin};delete body.coreHash;
72
+ const core={...body,coreHash:hash(body)};
73
+ const style={...bundle.style,project:projectId,id:localId,source:origin,coreHash:core.coreHash,report:{...bundle.style.report,data:core.report}};
74
+ const staging=objectDirectory(root,projectId,'style','import-'+randomUUID());
75
+ try{
76
+ mkdirSync(staging,{recursive:true});
77
+ for(const item of bundle.files){const target=safe(staging,item.path);mkdirSync(resolve(target,'..'),{recursive:true});writeFileSync(target,Buffer.from(item.data,'base64'),{flag:'wx'});}
78
+ writeJson(join(staging,'style.json'),style);writeJson(join(staging,'core.json'),core);
79
+ renameSync(staging,directory);
80
+ try{project.cores.push(localId);project.defaultCore??=localId;writeJson(ownedPath(root,'projects',projectId,'project.json'),project);}
81
+ catch(error){rmSync(directory,{recursive:true,force:true});throw error;}
82
+ return style;
83
+ }finally{rmSync(staging,{recursive:true,force:true});}
84
+ });
85
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kevlns/art-workshop",
3
- "version": "0.3.8",
3
+ "version": "0.3.11",
4
4
  "private": false,
5
5
  "description": "管理项目风格、参考图、图片生成、编辑和定版。支持本地 ComfyUI 与远程图片模型。",
6
6
  "type": "module",
@@ -70,6 +70,15 @@ candidate delete 先确认影响,拒绝运行中或被计划/底图引用的
70
70
 
71
71
  `v-cli capability coverage --json` 核对结构化调用覆盖。参考导入的 `--item-id` 指定当前任务出图对象,省略表示任务共用;工具校验对象身份。
72
72
 
73
+ ### 本地环境部署
74
+
75
+ 使用 environment guide 获取部署指南与契约,environment inspect 读取机器环境。Pi 通过基础工具和动态工作流完成安装、下载、修正与采样;environment verify 独立校验文件、服务和节点,environment register 验收后登记。任务授权、进程、互斥与恢复交由 Harness。不得把模型回复或服务连通当作真实出图。unregister 仅解除登记,不删除模型或停止外部服务。按 --guide 选择随包方案,模型事实和启动参数只由 art 维护。
76
+
77
+ ### 共享冻结风格
78
+
79
+ 用户要求共享时使用 style export --project ID --id STYLE --out FILE.style.json,收集冻结核心和必要参考,不复制运行记录或设置。style sources --input DIRS.json 只读列出多个来源,单个来源不可用时报告并继续,重复身份内容冲突按来源明确选择。style import --project TARGET --file FILE.style.json 导入固定快照,保留来源身份、版本及核心哈希;不重新分析、采用或随来源更新。导入的冻结对象只读,改动使用 style derive。输出文件不覆盖已有版本。
80
+
81
+
73
82
  ## 结果验证
74
83
 
75
84
  核对原始错误、任务身份、停止状态及实际产物。只报告已经完成的验证,模拟测试与真实执行分别说明。