@kevlns/art-workshop 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/AGENTS.md +25 -25
  2. package/LICENSE +21 -21
  3. package/README.md +65 -63
  4. package/art-workshop.mjs +219 -174
  5. package/docs/channels.md +49 -0
  6. package/docs/commands.md +2259 -22
  7. package/docs/configuration.md +90 -82
  8. package/docs/core-guidance.md +58 -50
  9. package/docs/data-formats.md +89 -85
  10. package/docs/deployment.md +32 -32
  11. package/docs/local-models/qwen-image-2.1.json +73 -73
  12. package/docs/local-models/qwen-image-2.1.md +33 -33
  13. package/docs/model-architecture.md +78 -78
  14. package/docs/modes.md +73 -67
  15. package/docs/release-0.6.0.md +9 -0
  16. package/lib/agent.mjs +32 -32
  17. package/lib/analysis-worker.mjs +36 -32
  18. package/lib/analyze.mjs +85 -85
  19. package/lib/asset-profile.mjs +23 -23
  20. package/lib/backends.mjs +2 -0
  21. package/lib/candidates.mjs +104 -103
  22. package/lib/channel-operation.mjs +84 -0
  23. package/lib/comfy-recovery.mjs +17 -17
  24. package/lib/conversation.mjs +77 -77
  25. package/lib/core.mjs +104 -75
  26. package/lib/deployment-guide.mjs +12 -12
  27. package/lib/design.mjs +29 -29
  28. package/lib/dimensions.mjs +22 -22
  29. package/lib/edit.mjs +43 -41
  30. package/lib/environment-operations.mjs +49 -49
  31. package/lib/environment-runtime.mjs +99 -99
  32. package/lib/environments.mjs +55 -55
  33. package/lib/executor.mjs +107 -107
  34. package/lib/generate.mjs +60 -58
  35. package/lib/generation-policy.mjs +1 -1
  36. package/lib/heartbeat.mjs +16 -16
  37. package/lib/images.mjs +1 -1
  38. package/lib/lifecycle.mjs +53 -53
  39. package/lib/migration.mjs +154 -154
  40. package/lib/object-format.mjs +1 -1
  41. package/lib/process-identity.mjs +22 -14
  42. package/lib/project.mjs +39 -39
  43. package/lib/prompt-structure.mjs +3 -3
  44. package/lib/refs.mjs +26 -26
  45. package/lib/runtime.mjs +25 -25
  46. package/lib/service.mjs +155 -126
  47. package/lib/settings.mjs +50 -50
  48. package/lib/shared.mjs +67 -67
  49. package/lib/style-bundle.mjs +98 -85
  50. package/lib/style-contract.mjs +74 -74
  51. package/lib/style-lifecycle.mjs +124 -125
  52. package/lib/style-review.mjs +14 -14
  53. package/lib/style-samples.mjs +92 -0
  54. package/lib/task-contract.mjs +94 -93
  55. package/lib/tasks.mjs +497 -497
  56. package/lib/templates.mjs +80 -80
  57. package/lib/video/PROVENANCE.json +63 -0
  58. package/lib/video/atomic.mjs +32 -0
  59. package/lib/video/channel.mjs +70 -0
  60. package/lib/video/contract-local-media.mjs +42 -0
  61. package/lib/video/contract-story.mjs +213 -0
  62. package/lib/video/contract-video.mjs +117 -0
  63. package/lib/video/contracts.mjs +3 -0
  64. package/lib/video/h3.mjs +232 -0
  65. package/lib/video/local-runtime.mjs +20 -0
  66. package/lib/video/media.mjs +223 -0
  67. package/lib/video/models.mjs +336 -0
  68. package/lib/video/path.mjs +18 -0
  69. package/lib/video/process.mjs +15 -0
  70. package/lib/video/resource.mjs +15 -0
  71. package/lib/video/service.mjs +731 -0
  72. package/lib/video/workflow.mjs +571 -0
  73. package/lib/video.mjs +12 -0
  74. package/lib/vision.mjs +56 -56
  75. package/lib/worker-process.mjs +6 -6
  76. package/lib/workspace.mjs +305 -292
  77. package/package.json +8 -3
  78. package/rules/core-guidance.json +22 -22
  79. package/skills/art-workshop/SKILL.md +19 -17
  80. package/skills/art-workshop/references/conversation.md +11 -11
  81. package/skills/art-workshop/references/expression.md +27 -27
  82. package/skills/art-workshop/references/project.md +119 -109
  83. package/skills/art-workshop/references/style-discussion.md +7 -3
  84. package/skills/art-workshop/references/video.md +13 -0
  85. package/v-cli.plugin.json +7240 -2747
package/lib/service.mjs CHANGED
@@ -1,126 +1,155 @@
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,inspectProcess} 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,inspect=inspectProcess}={}) {
13
+ const current=inspect(identity.pid);
14
+ if(current.state==='missing')return;
15
+ if(current.state!=='running')throw new Error('服务进程身份未知,无法确认停止');
16
+ if(hash(current.identity)!==hash(identity))throw new Error('服务进程身份已变化,拒绝终止复用的 PID');
17
+ try {
18
+ if(process.platform==='win32')execFileSync('taskkill.exe',['/PID',String(identity.pid),'/T','/F'],{windowsHide:true,timeout,stdio:['ignore','pipe','pipe']});
19
+ else process.kill(identity.pid,'SIGTERM');
20
+ }catch(error){if(inspect(identity.pid).state!=='missing')throw error;return;}
21
+ const deadline=Date.now()+timeout;
22
+ while(true){
23
+ const result=inspect(identity.pid);
24
+ if(result.state==='missing'||result.state==='running'&&hash(result.identity)!==hash(identity))return;
25
+ if(result.state==='unknown')throw new Error('服务进程停止结果未知');
26
+ if(Date.now()>deadline)throw new Error('服务进程未停止');await sleep(100);
27
+ }
28
+ }
29
+ export async function healthy(endpoint,backend) {
30
+ try {
31
+ const stats=await http(endpoint,'/system_stats',{timeout:2000});if(!stats.system?.comfyui_version)return false;
32
+ const [major,minor]=stats.system.comfyui_version.split('.').map(Number);
33
+ if(major===0&&minor<39)return false;
34
+ 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;}
35
+ return stats;
36
+ }catch{return false;}
37
+ }
38
+ export const serviceRoot=()=>join(process.env.VANT_HOME??join(homedir(),'.vant'),'state','art-services');
39
+ function serviceFile(root,endpoint){return join(serviceRoot(),'services',hash(endpoint)+'.json');}
40
+ export function externalIdentity(endpoint,launch) {
41
+ if(process.platform!=='win32'||!launch)return null;
42
+ const port=Number(new URL(endpoint).port||80);
43
+ const script=`Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique | ConvertTo-Json -Compress`;
44
+ let pids;try{pids=JSON.parse(execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true}).trim()||'null');}catch{return null;}
45
+ for(const pid of [].concat(pids??[])) {
46
+ const p=processIdentity(pid);
47
+ if(!p?.exe||resolve(p.exe).toLowerCase()!==resolve(launch.executable).toLowerCase())continue;
48
+ // Require the configured entrypoint, not just a Python interpreter or an occupied port.
49
+ const entry=launch.args.find(x=>/main\.py$|\.mjs$|\.js$/.test(x));
50
+ if(!entry||!p.command.toLowerCase().includes(entry.toLowerCase()))continue;
51
+ return p;
52
+ }
53
+ return null;
54
+ }
55
+ export async function ensureService(backend,root,{cancelled=()=>false}={}) {
56
+ root=serviceRoot();
57
+ return locked(root,'services',async()=>{
58
+ if(stateRead(join(root,'shutdown.json')))throw new Error('服务正在 shutdown');
59
+ const incompatible=[];
60
+ for(const endpoint of backend.endpoints) {
61
+ let report;try{report=await inspectEnvironment(endpoint,backend);}catch{continue;}
62
+ if(!report.ok){incompatible.push(report);continue;}
63
+ const file=serviceFile(root,endpoint),previous=stateRead(file);
64
+ const identity=previous?.identity&&hash(processIdentity(previous.identity.pid))===hash(previous.identity)?previous.identity:externalIdentity(endpoint,backend.launch);
65
+ const sameOwner=!!(identity&&previous?.owned&&hash(previous.identity)===hash(identity));
66
+ writeJson(file,{endpoint,backend:backend.id,identity,owned:sameOwner,...(sameOwner&&previous.owner?{owner:previous.owner}:{}),observedAt:new Date().toISOString()});
67
+ return endpoint;
68
+ }
69
+ if(incompatible.length){const error=workflowError('现有 ComfyUI 环境无法执行工作流',backend,{stage:'environment'});error.diagnostic.environments=incompatible;throw error;}
70
+ if(!backend.launch)throw new Error('没有可用 ComfyUI,也未配置 launch');
71
+ if(cancelled())throw new Error('任务已取消');
72
+ const endpoint=backend.endpoints[0],file=serviceFile(root,endpoint),previous=stateRead(file);
73
+ if(previous?.identity&&hash(processIdentity(previous.identity.pid))===hash(previous.identity))throw new Error('现有服务不健康,请先 shutdown;不重复启动');
74
+ const logPath=join(root,'comfyui-'+hash(endpoint).slice(0,8)+'.log'),fd=openSync(logPath,'a');
75
+ const child=spawn(backend.launch.executable,backend.launch.args,{cwd:backend.launch.cwd,detached:true,windowsHide:true,stdio:['ignore',fd,fd]});closeSync(fd);
76
+ let spawnError;child.once('error',error=>{spawnError=error;});child.unref();
77
+ await sleep(100);
78
+ if(spawnError||!child.pid)throw spawnError??new Error('服务启动失败');
79
+ const identity=processIdentity(child.pid);if(!identity)throw new Error('无法记录服务进程身份');
80
+ writeJson(file,{endpoint,backend:backend.id,identity,owned:true,...(process.env.VANT_SERVICE_INSTANCE?{owner:{application:'vant',instanceId:process.env.VANT_SERVICE_INSTANCE}}:{}),logPath});
81
+ const deadline=Date.now()+(backend.launch.startupTimeoutSeconds??120)*1000;
82
+ try {
83
+ 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);}
84
+ throw new Error('ComfyUI 启动超时,查看 '+logPath);
85
+ }catch(error){await stopIdentity(identity);throw error;}
86
+ });
87
+ }
88
+ export function rememberedService(root,endpoint){return stateRead(serviceFile(root,endpoint));}
89
+ // Application exit never adopts an external process as a termination target.
90
+ export async function shutdownOwnedServices() {
91
+ return locked(serviceRoot(),'control',async()=>{
92
+ const folder=join(serviceRoot(),'services'),results=[],failures=[];
93
+ for(const name of existsSync(folder)?readdirSync(folder):[]) {
94
+ if(!name.endsWith('.json'))continue;
95
+ const file=join(folder,name),record=stateRead(file);
96
+ if(record?.owned!==true||record.owner?.application!=='vant'||record.stopped)continue;
97
+ try {
98
+ if(!record.identity)throw new Error('缺少服务进程身份,不能确认停止');
99
+ const url=new URL(record.endpoint);
100
+ 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('服务地址不是本机回环地址');
101
+ if(name!==hash(record.endpoint)+'.json')throw new Error('服务记录身份不匹配');
102
+ await stopIdentity(record.identity);
103
+ const deadline=Date.now()+15000;
104
+ while(true){
105
+ try {
106
+ await new Promise((resolve,reject)=>{
107
+ const probe=createServer();probe.once('error',reject);
108
+ probe.listen({host:'127.0.0.1',port:Number(url.port||80),exclusive:true},()=>probe.close(error=>error?reject(error):resolve()));
109
+ });
110
+ break;
111
+ }catch(error){if(error.code!=='EADDRINUSE'||Date.now()>deadline)throw error;await sleep(200);}
112
+ }
113
+ writeJson(file,{...record,owned:false,stopped:true,stoppedAt:new Date().toISOString()});
114
+ results.push({endpoint:record.endpoint,stopped:true,portReleased:true});
115
+ }catch(error){failures.push(record.endpoint+': '+error.message);}
116
+ }
117
+ if(failures.length)throw new Error('本机服务清理未确认:'+failures.join('; '));
118
+ return results;
119
+ });
120
+ }
121
+ export async function closeService(root,endpoint,backend) {
122
+ return locked(serviceRoot(),'queue-'+new URL(endpoint).port,()=>closeSharedService(serviceRoot(),endpoint,backend));
123
+ }
124
+ const ownedCloseFailure=(code,message)=>Object.assign(new Error(message),{code});
125
+ async function assertOwnedPortReleased(endpoint){
126
+ const url=new URL(endpoint),hosts=url.hostname==='localhost'?['127.0.0.1','::1']:[url.hostname.replace(/^\[|\]$/g,'')];
127
+ for(const host of hosts)await new Promise((resolve,reject)=>{const probe=createServer();probe.once('error',error=>reject(Object.assign(ownedCloseFailure('service-owned-stop-unconfirmed','原服务已停止,但端口仍被占用或无法核对;不会停止其他进程'),{cause:error})));probe.listen({host,port:Number(url.port||80),exclusive:true},()=>probe.close(error=>error?reject(error):resolve()));});
128
+ }
129
+ /** Strict application-owned close: checks stay inside the shared queue/service locks and never adopt an external PID. */
130
+ export async function closeOwnedService(root,endpoint,backend,{owner,identity}={},dependencies={}){
131
+ const url=new URL(endpoint);
132
+ if(url.protocol!=='http:'||!['127.0.0.1','localhost','[::1]'].includes(url.hostname)||url.pathname!=='/'||url.search||url.hash||url.username||url.password)throw ownedCloseFailure('service-owned-endpoint-invalid','只能关闭已记录的本机服务');
133
+ if(!owner?.instanceId||!Number.isSafeInteger(identity?.pid)||identity.pid<=0)throw ownedCloseFailure('service-owner-mismatch','缺少明确的服务所有者与原进程身份');
134
+ const expected=structuredClone({owner,identity}),controlRoot=serviceRoot();
135
+ const lock=dependencies.lock||locked,read=dependencies.readRecord||rememberedService,inspect=dependencies.inspect||processIdentity,health=dependencies.health||healthy,queue=dependencies.queue||((endpoint)=>http(endpoint,'/queue')),stop=dependencies.stop||stopIdentity,portReleased=dependencies.portReleased||assertOwnedPortReleased,write=dependencies.writeRecord||((root,endpoint,value)=>writeJson(serviceFile(root,endpoint),value));
136
+ const assertRecord=(checkProcess=true)=>{const record=read(root,endpoint);if(record?.endpoint!==endpoint||record.owned!==true||record.stopped||hash(record.owner)!==hash(expected.owner)||hash(record.identity)!==hash(expected.identity))throw ownedCloseFailure('service-owner-mismatch','服务所有者或原进程记录已变化,停止未确认');if(checkProcess&&hash(inspect(expected.identity.pid))!==hash(expected.identity))throw ownedCloseFailure('service-owner-mismatch','原服务进程身份已变化,拒绝关闭其他进程');return record;};
137
+ return lock(controlRoot,'queue-'+url.port,()=>lock(controlRoot,'services',async()=>{
138
+ assertRecord();const reachable=await health(endpoint,backend);assertRecord();
139
+ if(reachable){const observed=await queue(endpoint);assertRecord();if((observed.queue_running??[]).length||(observed.queue_pending??[]).length)throw ownedCloseFailure('service-shared-busy','共享服务仍有其他任务,保留服务');}
140
+ assertRecord();await stop(expected.identity);
141
+ if(hash(inspect(expected.identity.pid))===hash(expected.identity)||await health(endpoint,backend))throw ownedCloseFailure('service-owned-stop-unconfirmed','原服务停止尚未确认;不会关闭新占用端口的进程');
142
+ await portReleased(endpoint);const record=assertRecord(false);write(root,endpoint,{...record,owned:false,stopped:true,stoppedAt:new Date().toISOString()});return {endpoint,stopped:true,portReleased:true};
143
+ }));
144
+ }
145
+ async function closeSharedService(root,endpoint,backend) {
146
+ if(await healthy(endpoint,backend)){const queue=await http(endpoint,'/queue');if((queue.queue_running??[]).length||(queue.queue_pending??[]).length)throw new Error('共享服务仍有其他任务,保留服务');}
147
+ const remembered=rememberedService(root,endpoint);
148
+ const previous=remembered?.identity;
149
+ const identity=previous&&hash(processIdentity(previous.pid))===hash(previous)?previous:externalIdentity(endpoint,backend.launch);
150
+ if(!identity){if(await healthy(endpoint,backend))throw new Error('无法验证服务进程身份:'+endpoint);return {endpoint,stopped:false};}
151
+ await stopIdentity(identity);
152
+ if(await healthy(endpoint,backend))throw new Error('关闭进程后服务仍可访问:'+endpoint);
153
+ writeJson(serviceFile(root,endpoint),{endpoint,stopped:true,stoppedAt:new Date().toISOString()});
154
+ return {endpoint,stopped:true};
155
+ }
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
+ }
package/lib/shared.mjs CHANGED
@@ -1,67 +1,67 @@
1
- import {ContractError} from './errors.mjs';
2
- import { createHash, randomUUID } from 'node:crypto';
3
- import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
4
- import { dirname } from 'node:path';
5
-
6
- export function hash(value) {
7
- const ordered = v => Array.isArray(v) ? v.map(ordered) : v && typeof v === 'object'
8
- ? Object.fromEntries(Object.keys(v).sort().map(k => [k, ordered(v[k])])) : v;
9
- return createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
10
- }
11
- export function readJson(path) {
12
- try { return JSON.parse(readFileSync(path, 'utf8')); }
13
- catch (e) { throw new Error(`读取 ${path} 失败:${e.message}`); }
14
- }
15
- export function renameWithRetry(source,target) {
16
- for(let attempt=0;;attempt++) {
17
- try {renameSync(source,target);return;}
18
- catch(error) {
19
- if(process.platform!=='win32'||!['EPERM','EACCES','EBUSY'].includes(error.code)||attempt>=50)throw error;
20
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20);
21
- }
22
- }
23
- }
24
- export function writeJson(path, data) {
25
- mkdirSync(dirname(path), { recursive: true });
26
- const temporary = path + '.tmp-' + randomUUID();
27
- writeFileSync(temporary, JSON.stringify(data, null, 2) + '\n', 'utf8');
28
- // Windows readers and antivirus can temporarily deny replacement of a state file.
29
- // Keep the previous complete document until rename succeeds; never truncate it.
30
- try {
31
- renameWithRetry(temporary,path);
32
- } finally {try{rmSync(temporary,{force:true});}catch{}}
33
- }
34
- export function keys(value, allowed, label) {
35
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new ContractError(`${label} 必须为对象`);
36
- for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new ContractError(`${label} 不支持字段 ${key}`);
37
- }
38
- export function text(value, label, max = 160) {
39
- if (typeof value !== 'string' || !value.trim() || value.length > max) throw new ContractError(Number.isFinite(max) ? `${label} 必须是 1~${max} 字的精炼文本` : `${label} 必须是非空文本`);
40
- if (/\bTODO\b|<[^>]+>|待填写/.test(value)) throw new ContractError(`${label} 有未完成的占位符`);
41
- return value;
42
- }
43
- export function id(value, label = 'id') {
44
- if (typeof value !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(value)
45
- || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value)) throw new ContractError(`${label} 必须使用小写字母、数字、连字符`);
46
- return value;
47
- }
48
- export function integer(value, label, min = 0, max = 2147483647) {
49
- if (!Number.isSafeInteger(value) || value < min || value > max) throw new ContractError(`${label} 必须为 ${min}~${max} 的整数`);
50
- return value;
51
- }
52
- export function choice(value, values, label) {
53
- if (!values.includes(value)) throw new ContractError(`${label} 必须为 ${values.join('/')}`);
54
- return value;
55
- }
56
- export function texts(value, label, { empty = false, max = 160 } = {}) {
57
- if (!Array.isArray(value) || (!empty && !value.length)) throw new ContractError(`${label} 必须为${empty ? '' : '非空'}数组`);
58
- value.forEach(x => text(x, label, max)); return value;
59
- }
60
- export function hex(value, label) {
61
- if (typeof value !== 'string' || !/^#[0-9a-f]{6}$/i.test(value)) throw new ContractError(`${label} 必须为 #RRGGBB`);
62
- return value.toUpperCase();
63
- }
64
-
65
- /** User-authored art requirements are not limited by character count. */
66
- export const description = (value, label) => text(value, label, Infinity);
67
- export const descriptions = (value, label) => texts(value, label, {max: Infinity});
1
+ import {ContractError} from './errors.mjs';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
4
+ import { dirname } from 'node:path';
5
+
6
+ export function hash(value) {
7
+ const ordered = v => Array.isArray(v) ? v.map(ordered) : v && typeof v === 'object'
8
+ ? Object.fromEntries(Object.keys(v).sort().map(k => [k, ordered(v[k])])) : v;
9
+ return createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
10
+ }
11
+ export function readJson(path) {
12
+ try { return JSON.parse(readFileSync(path, 'utf8')); }
13
+ catch (e) { throw new Error(`读取 ${path} 失败:${e.message}`); }
14
+ }
15
+ export function renameWithRetry(source,target) {
16
+ for(let attempt=0;;attempt++) {
17
+ try {renameSync(source,target);return;}
18
+ catch(error) {
19
+ if(process.platform!=='win32'||!['EPERM','EACCES','EBUSY'].includes(error.code)||attempt>=50)throw error;
20
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20);
21
+ }
22
+ }
23
+ }
24
+ export function writeJson(path, data) {
25
+ mkdirSync(dirname(path), { recursive: true });
26
+ const temporary = path + '.tmp-' + randomUUID();
27
+ writeFileSync(temporary, JSON.stringify(data, null, 2) + '\n', 'utf8');
28
+ // Windows readers and antivirus can temporarily deny replacement of a state file.
29
+ // Keep the previous complete document until rename succeeds; never truncate it.
30
+ try {
31
+ renameWithRetry(temporary,path);
32
+ } finally {try{rmSync(temporary,{force:true});}catch{}}
33
+ }
34
+ export function keys(value, allowed, label) {
35
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new ContractError(`${label} 必须为对象`);
36
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new ContractError(`${label} 不支持字段 ${key}`);
37
+ }
38
+ export function text(value, label, max = 160) {
39
+ if (typeof value !== 'string' || !value.trim() || value.length > max) throw new ContractError(Number.isFinite(max) ? `${label} 必须是 1~${max} 字的精炼文本` : `${label} 必须是非空文本`);
40
+ if (/\bTODO\b|<[^>]+>|待填写/.test(value)) throw new ContractError(`${label} 有未完成的占位符`);
41
+ return value;
42
+ }
43
+ export function id(value, label = 'id') {
44
+ if (typeof value !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(value)
45
+ || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value)) throw new ContractError(`${label} 必须使用小写字母、数字、连字符`);
46
+ return value;
47
+ }
48
+ export function integer(value, label, min = 0, max = 2147483647) {
49
+ if (!Number.isSafeInteger(value) || value < min || value > max) throw new ContractError(`${label} 必须为 ${min}~${max} 的整数`);
50
+ return value;
51
+ }
52
+ export function choice(value, values, label) {
53
+ if (!values.includes(value)) throw new ContractError(`${label} 必须为 ${values.join('/')}`);
54
+ return value;
55
+ }
56
+ export function texts(value, label, { empty = false, max = 160 } = {}) {
57
+ if (!Array.isArray(value) || (!empty && !value.length)) throw new ContractError(`${label} 必须为${empty ? '' : '非空'}数组`);
58
+ value.forEach(x => text(x, label, max)); return value;
59
+ }
60
+ export function hex(value, label) {
61
+ if (typeof value !== 'string' || !/^#[0-9a-f]{6}$/i.test(value)) throw new ContractError(`${label} 必须为 #RRGGBB`);
62
+ return value.toUpperCase();
63
+ }
64
+
65
+ /** User-authored art requirements are not limited by character count. */
66
+ export const description = (value, label) => text(value, label, Infinity);
67
+ export const descriptions = (value, label) => texts(value, label, {max: Infinity});