@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
@@ -0,0 +1,84 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {mkdir,open,readFile,rm,stat} from 'node:fs/promises';
3
+ import {dirname} from 'node:path';
4
+ import {projectPath} from './video/path.mjs';
5
+ import {withResource} from './video/resource.mjs';
6
+ import {atomicJson} from './video/atomic.mjs';
7
+ const base='.vant/state/video';
8
+ const fail=(code,message,extra={})=>Object.assign(new Error(message),{code,...extra});
9
+ const canonical=value=>Array.isArray(value)?'['+value.map(canonical).join(',')+']':value&&typeof value==='object'?'{'+Object.keys(value).sort().map(key=>JSON.stringify(key)+':'+canonical(value[key])).join(',')+'}':JSON.stringify(value);
10
+ const digest=value=>createHash('sha256').update(value).digest('hex');
11
+ const validExecution=id=>typeof id==='string'&&/^video-[a-f0-9-]{36}$/.test(id);
12
+ export function videoExecutionId(value){
13
+ if(validExecution(value))return value;
14
+ if(typeof value!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value)||value.endsWith('.')||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value))throw fail('video-cli-operation-invalid','视频写入需要稳定的 --operation(1–128位字母数字、点、下划线或连字符)。');
15
+ const hash=digest('art-workshop/video/cli/'+value);
16
+ return `video-${hash.slice(0,8)}-${hash.slice(8,12)}-5${hash.slice(13,16)}-a${hash.slice(17,20)}-${hash.slice(20,32)}`;
17
+ }
18
+ async function readRecord(root,path){
19
+ const file=await projectPath(root,path);
20
+ try{const info=await stat(file);if(!info.isFile()||info.size>64*1024*1024)throw new Error('视频操作记录不是有效文件');return JSON.parse(await readFile(file,'utf8'));}
21
+ catch(error){if(error.code==='ENOENT')return null;throw fail('video-cli-record-unknown','视频原操作记录不可读取,请保留并核对,不得重投。',{unknown:true,cause:error});}
22
+ }
23
+ async function syncFile(file){const handle=await open(file,'r+');try{await handle.sync();}finally{await handle.close();}}
24
+ async function durableCreate(root,path,value,{raw=false}={}){
25
+ let file=await projectPath(root,path);await mkdir(dirname(file),{recursive:true});file=await projectPath(root,path);
26
+ const handle=await open(file,'wx',0o600);try{await handle.writeFile(raw?value:JSON.stringify(value));await handle.sync();}finally{await handle.close();}
27
+ }
28
+ async function durableReceipt(file,value){await atomicJson(file,value);await syncFile(file);}
29
+ const terminal=receipt=>receipt&&['succeeded','failed','cancelled','submitted'].includes(receipt.status)&&!receipt.unknown;
30
+ function receiptResult(receipt){
31
+ if(!terminal(receipt))throw fail('video-execution-unknown','原操作结果未知;请查询原身份,不得再次执行。',{unknown:true,operationId:receipt.operationId});
32
+ if(!Object.hasOwn(receipt,'result'))throw fail(receipt.error?.code||'video-failed',receipt.error?.message||'原操作已失败,保留原回执。',{operationId:receipt.operationId});
33
+ const metadata={operationId:receipt.operationId,originOperationId:receipt.originOperationId||null,status:receipt.status},value=receipt.result;
34
+ return value&&typeof value==='object'&&!Array.isArray(value)?{...value,cliExecution:metadata}:{result:value,cliExecution:metadata};
35
+ }
36
+ export async function readChannelOperation({root,operationId}){
37
+ const id=videoExecutionId(operationId),value=await readRecord(root,`${base}/operations/${id}.json`);
38
+ if(!value)return {operationId:id,originOperationId:operationId,status:'not-found'};
39
+ if(value.version!==1||value.operationId!==id)throw fail('video-cli-record-unknown','原操作意图格式损坏,请人工核对。',{unknown:true,operationId:id});
40
+ return {...value,status:value.status==='executing'?'unknown':value.status,unknown:value.unknown===true||['executing','unknown'].includes(value.status)};
41
+ }
42
+ async function claimSharedIntent(root,operationId,request){
43
+ const semanticDigest=digest(canonical(request)),path=`${base}/unresolved/${semanticDigest}.json`,file=await projectPath(root,path),prior=await readRecord(root,path);
44
+ if(prior){
45
+ if(prior.version!==1||prior.semanticDigest!==semanticDigest||!validExecution(prior.operationId))throw fail('business-intent-corrupt','未决操作索引损坏,不得重投。',{unknown:true,operationId:prior.operationId||operationId});
46
+ const receipt=await readChannelOperation({root,operationId:prior.operationId});
47
+ if(!terminal(receipt))throw fail('business-intent-unresolved','相同业务请求已有未决原操作;不能换入口或身份再次执行。',{unknown:true,operationId:prior.operationId});
48
+ await rm(file);
49
+ }
50
+ const value={version:1,operationId,semanticDigest,action:request.action,origin:'cli',createdAt:new Date().toISOString()},raw=JSON.stringify(value);
51
+ await durableCreate(root,path,raw,{raw:true});
52
+ return {semanticDigest,async release(){if(await readFile(file,'utf8').catch(()=>null)===raw)await rm(file,{force:true});}};
53
+ }
54
+ /** CLI admission shares DSH's unresolved claims and receipt format, not a second video state machine. */
55
+ export async function executeChannelOperation({root,workspaceId,operationId:originOperationId,action,input,execute,writeReceipt=durableReceipt}){
56
+ const operationId=videoExecutionId(originOperationId),request={action,input},raw=JSON.stringify(request),requestDigest=digest(raw);
57
+ return withResource(root,`${base}/cli-journal`,async()=>{
58
+ const requestPath=`${base}/requests/${operationId}.json`,receiptPath=`${base}/operations/${operationId}.json`;
59
+ const priorRequest=await readRecord(root,requestPath);
60
+ if(priorRequest&&canonical(priorRequest)!==canonical(request))throw fail('video-operation-conflict','原视频执行身份已用于不同请求;保留原意图。',{operationId});
61
+ const prior=await readChannelOperation({root,operationId});
62
+ if(prior.status!=='not-found'){
63
+ if(prior.workspaceId!==workspaceId||prior.semanticDigest&&prior.semanticDigest!==digest(canonical(request))||!priorRequest)throw fail('video-operation-conflict','原视频回执与当前请求不匹配。',{operationId});
64
+ return receiptResult(prior);
65
+ }
66
+ if(!priorRequest)await durableCreate(root,requestPath,raw,{raw:true});
67
+ const claim=await claimSharedIntent(root,operationId,request);
68
+ const ledger={version:1,operationId,originOperationId,requestDigest,semanticDigest:claim.semanticDigest,workspaceId,action,origin:'cli',sessionId:null,status:'executing',createdAt:new Date().toISOString()};
69
+ await durableCreate(root,receiptPath,ledger);
70
+ let result;
71
+ try{result=JSON.parse(JSON.stringify(await execute()));}
72
+ catch(error){
73
+ ledger.status='unknown';ledger.unknown=true;ledger.error={code:error.code||'video-cli-operation-unknown',message:error.message||'视频写入结果未知'};ledger.settledAt=new Date().toISOString();
74
+ try{await writeReceipt(await projectPath(root,receiptPath),ledger);}catch{}
75
+ throw fail(ledger.error.code,ledger.error.message,{unknown:true,operationId,cause:error});
76
+ }
77
+ const run=result?.operations?.find(operation=>operation.id===input.operationId)?.runs?.at(-1);
78
+ ledger.result=result;ledger.status=run?.status==='unknown'?'unknown':run&&['running','dispatching'].includes(run.status)?'submitted':'succeeded';ledger.unknown=ledger.status==='unknown';ledger.settledAt=new Date().toISOString();
79
+ try{await writeReceipt(await projectPath(root,receiptPath),ledger);}
80
+ catch(error){throw fail('video-receipt-unknown','视频业务已返回但回执未完整落盘;请核对原操作,不得重投。',{unknown:true,operationId,cause:error});}
81
+ if(ledger.status!=='unknown')await claim.release().catch(()=>{});
82
+ return receiptResult(ledger);
83
+ });
84
+ }
@@ -1,17 +1,17 @@
1
- /** Only recorded prompt identities may be queried; never infer a new submission. */
2
- export function comfyRecoveryPrompts(task) {
3
- if (task.plan?.backend?.provider !== 'comfyui') return null;
4
- const prompts = structuredClone(task.comfyPrompts ?? {});
5
- // The original worker records a single current prompt before polling.
6
- if (task.promptId && task.currentItem) {
7
- const item = task.items?.find(i => i.itemId === task.currentItem.itemId && i.variantId === task.currentItem.variantId);
8
- if (item && (item.execution ?? task.plan.execution).perValue === 1 && !prompts[item.inputHash])
9
- prompts[item.inputHash] = [task.promptId];
10
- }
11
- const entries = Object.entries(prompts);
12
- if (!entries.length || entries.some(([key, ids]) => {
13
- const item = task.items?.find(i => i.inputHash === key);
14
- return !item || !Array.isArray(ids) || ids.length > (item.execution ?? task.plan.execution).perValue || !ids.length || ids.some(id => typeof id !== 'string' || !id.trim());
15
- })) return null;
16
- return prompts;
17
- }
1
+ /** Only recorded prompt identities may be queried; never infer a new submission. */
2
+ export function comfyRecoveryPrompts(task) {
3
+ if (task.plan?.backend?.provider !== 'comfyui') return null;
4
+ const prompts = structuredClone(task.comfyPrompts ?? {});
5
+ // The original worker records a single current prompt before polling.
6
+ if (task.promptId && task.currentItem) {
7
+ const item = task.items?.find(i => i.itemId === task.currentItem.itemId && i.variantId === task.currentItem.variantId);
8
+ if (item && (item.execution ?? task.plan.execution).perValue === 1 && !prompts[item.inputHash])
9
+ prompts[item.inputHash] = [task.promptId];
10
+ }
11
+ const entries = Object.entries(prompts);
12
+ if (!entries.length || entries.some(([key, ids]) => {
13
+ const item = task.items?.find(i => i.inputHash === key);
14
+ return !item || !Array.isArray(ids) || ids.length > (item.execution ?? task.plan.execution).perValue || !ids.length || ids.some(id => typeof id !== 'string' || !id.trim());
15
+ })) return null;
16
+ return prompts;
17
+ }
@@ -1,77 +1,77 @@
1
- import {existsSync,readFileSync} from 'node:fs';
2
- import {join,resolve,dirname,relative,isAbsolute} from 'node:path';
3
- import {keys,id,description,integer,hash,readJson,writeJson} from './shared.mjs';
4
- import {execution,finishPlan} from './plan.mjs';
5
- import {backendDefaults,bindBackend} from './backends.mjs';
6
- import {startTask,taskStatus,taskView,recoverTask,cancelTask,resumeTask,shutdown} from './tasks.mjs';
7
- import {runtimeRoot,locked,tasks} from './runtime.mjs';
8
- import {sha256File} from './bl.mjs';
9
- import {externalPath} from './settings.mjs';
10
- import {validateImage} from './images.mjs';
11
-
12
- export function conversationFile(settings,session,request){id(session,'session');id(request,'request');return join(settings.paths.workspace,'conversations',session,request+'.json');}
13
- export async function compileConversation(request,settings){
14
- keys(request,['sessionId','requestId','mode','prompt','negative','images','preserve','style','size','count','seed','backend'],'conversation');
15
- id(request.sessionId,'sessionId');id(request.requestId,'requestId');
16
- if(!['generate','edit'].includes(request.mode))throw new Error('会话模式必须为 generate 或 edit');
17
- description(request.prompt,'prompt');
18
- const images=request.images??[];if(!Array.isArray(images))throw new Error('images 必须为数组');
19
- if(request.mode==='edit'&&!images.length)throw new Error('编辑必须明确底图');
20
- const refs=await Promise.all(images.map(async(image,index)=>{keys(image,['path','purpose'],'image');description(image.purpose,'purpose');const path=externalPath(resolve(image.path));await validateImage(readFileSync(path));return {path,hash:sha256File(path),purpose:image.purpose,index:index+1};}));
21
- const selected=request.backend??settings.generation?.defaultBackend;
22
- const config=execution({}, {...(request.size?{size:request.size}:{}),...(request.count!==undefined?{perValue:request.count}: {})},backendDefaults(settings,selected));
23
- const seed=request.seed??parseInt(hash([request.sessionId,request.requestId]).slice(0,7),16);integer(seed,'seed');
24
- const prompt=[request.prompt,request.style?'绘制语言:'+description(request.style,'style'):'',request.preserve?'必须保留:'+description(request.preserve,'preserve'):'',...refs.map(r=>'输入图'+r.index+'仅用于:'+r.purpose)].filter(Boolean).join('\n');
25
- const plan=finishPlan({compilerVersion:4,module:refs.length?'edit':request.mode,scope:{kind:'conversation',sessionId:request.sessionId,requestId:request.requestId},project:'conversation-'+hash(request.sessionId).slice(0,32),job:request.requestId,execution:config,sources:{requestHash:hash(request)},snapshots:{request},refs:refs.map(({path,hash})=>({path,hash})),items:[{itemId:'image',variantId:'base',seed,prompt,negativeBlock:request.negative??'',imageArgs:refs.map(r=>r.path),checks:{content:[],style:[],asset:[]}}]});
26
- return bindBackend(plan,settings,selected);
27
- }
28
-
29
- export async function startConversation(request,settings){
30
- const file=conversationFile(settings,request.sessionId,request.requestId);
31
- return locked(runtimeRoot(settings),'conversation',async()=>{
32
- if(existsSync(file)){
33
- const existing=readJson(file);if(hash(existing.request)!==hash(request))throw new Error('同一会话请求已提交,不能修改请求后重投');
34
- return readConversationStatus(settings,request.sessionId,request.requestId);
35
- }
36
- const plan=await compileConversation(request,settings),operationId='conversation-'+hash([request.sessionId,request.requestId]).slice(0,48);
37
- const record={schema:'art-workshop/conversation',request,plan,operationId,status:'dispatching',createdAt:new Date().toISOString()};
38
- writeJson(file,record);
39
- try{const started=await startTask(plan,plan.items,settings,{operationId});record.runId=started.taskId;record.status='queued';writeJson(file,record);}
40
- catch(error){record.status='unknown';record.error=error.message;writeJson(file,record);}
41
- return readConversationStatus(settings,request.sessionId,request.requestId);
42
- },{timeout:10000});
43
- }
44
- export async function conversationStatus(settings,session,request){
45
- return locked(runtimeRoot(settings),'conversation',()=>readConversationStatus(settings,session,request),{timeout:10000});
46
- }
47
- function readConversationStatus(settings,session,request){
48
- const file=conversationFile(settings,session,request);
49
- if(!existsSync(file))return {requestId:request,status:'failed',stopConfirmed:true,preSubmission:true,stopPolling:true,error:'未登记请求,未提交上游',artifacts:[]};
50
- const record=readJson(file);
51
- if(!record.runId){
52
- try{const recovered=recoverTask(runtimeRoot(settings),record.plan.project,record.operationId);record.runId=recovered.taskId;writeJson(file,record);}catch{}
53
- }
54
- if(!record.runId){
55
- // startTask 在拉起工作进程前持久登记;持有会话锁且无任务才可证明未提交。
56
- const matches=tasks(runtimeRoot(settings)).filter(t=>t.operationId===record.operationId);
57
- if(matches.length)throw new Error('原运行证据冲突,不能重投');
58
- record.status='failed';writeJson(file,record);
59
- return {requestId:request,status:'failed',stopConfirmed:true,preSubmission:true,stopPolling:true,error:record.error??'上游提交前已停止',artifacts:[]};
60
- }
61
- const task=taskStatus(runtimeRoot(settings),record.runId),view=taskView(task),artifacts=[];
62
- if(task.manifestPath&&existsSync(task.manifestPath)){
63
- const manifest=readJson(task.manifestPath);if(manifest.taskId!==task.taskId||manifest.planHash!==record.plan.planHash)throw new Error('会话产物身份不一致');
64
- for(const row of manifest.items??[])if(row.ok)for(const name of row.files??[]){const path=resolve(dirname(task.manifestPath),name),delta=relative(dirname(task.manifestPath),path);if(isAbsolute(delta)||delta.startsWith('..'))throw new Error('会话图片路径越界');if(!row.outputHashes?.[name]||sha256File(path)!==row.outputHashes[name])throw new Error('会话图片已变化');artifacts.push({path,sha256:row.outputHashes[name]});}
65
- }
66
- return {requestId:request,runId:task.taskId,status:view.status,stopConfirmed:view.stopConfirmed,canResume:view.canResume,stopPolling:['succeeded','failed','cancelled','unknown'].includes(view.status),error:view.error,artifacts};
67
- }
68
- export async function controlConversation(settings,session,request,action){
69
- return locked(runtimeRoot(settings),'conversation',async()=>{
70
- if(action==='close')return shutdown(settings,{closeServices:false});
71
- const current=readConversationStatus(settings,session,request);if(!current.runId)return current;
72
- if(action==='cancel')await cancelTask(runtimeRoot(settings),current.runId,{wait:false});
73
- else if(action==='resume')await resumeTask(runtimeRoot(settings),current.runId);
74
- else throw new Error('未知会话控制动作');
75
- return readConversationStatus(settings,session,request);
76
- },{timeout:10000});
77
- }
1
+ import {existsSync,readFileSync} from 'node:fs';
2
+ import {join,resolve,dirname,relative,isAbsolute} from 'node:path';
3
+ import {keys,id,description,integer,hash,readJson,writeJson} from './shared.mjs';
4
+ import {execution,finishPlan} from './plan.mjs';
5
+ import {backendDefaults,bindBackend} from './backends.mjs';
6
+ import {startTask,taskStatus,taskView,recoverTask,cancelTask,resumeTask,shutdown} from './tasks.mjs';
7
+ import {runtimeRoot,locked,tasks} from './runtime.mjs';
8
+ import {sha256File} from './bl.mjs';
9
+ import {externalPath} from './settings.mjs';
10
+ import {validateImage} from './images.mjs';
11
+
12
+ export function conversationFile(settings,session,request){id(session,'session');id(request,'request');return join(settings.paths.workspace,'conversations',session,request+'.json');}
13
+ export async function compileConversation(request,settings){
14
+ keys(request,['sessionId','requestId','mode','prompt','negative','images','preserve','style','size','count','seed','backend'],'conversation');
15
+ id(request.sessionId,'sessionId');id(request.requestId,'requestId');
16
+ if(!['generate','edit'].includes(request.mode))throw new Error('会话模式必须为 generate 或 edit');
17
+ description(request.prompt,'prompt');
18
+ const images=request.images??[];if(!Array.isArray(images))throw new Error('images 必须为数组');
19
+ if(request.mode==='edit'&&!images.length)throw new Error('编辑必须明确底图');
20
+ const refs=await Promise.all(images.map(async(image,index)=>{keys(image,['path','purpose'],'image');description(image.purpose,'purpose');const path=externalPath(resolve(image.path));await validateImage(readFileSync(path));return {path,hash:sha256File(path),purpose:image.purpose,index:index+1};}));
21
+ const selected=request.backend??settings.generation?.defaultBackend;
22
+ const config=execution({}, {...(request.size?{size:request.size}:{}),...(request.count!==undefined?{perValue:request.count}: {})},backendDefaults(settings,selected));
23
+ const seed=request.seed??parseInt(hash([request.sessionId,request.requestId]).slice(0,7),16);integer(seed,'seed');
24
+ const prompt=[request.prompt,request.style?'绘制语言:'+description(request.style,'style'):'',request.preserve?'必须保留:'+description(request.preserve,'preserve'):'',...refs.map(r=>'输入图'+r.index+'仅用于:'+r.purpose)].filter(Boolean).join('\n');
25
+ const plan=finishPlan({compilerVersion:4,module:refs.length?'edit':request.mode,scope:{kind:'conversation',sessionId:request.sessionId,requestId:request.requestId},project:'conversation-'+hash(request.sessionId).slice(0,32),job:request.requestId,execution:config,sources:{requestHash:hash(request)},snapshots:{request},refs:refs.map(({path,hash})=>({path,hash})),items:[{itemId:'image',variantId:'base',seed,prompt,negativeBlock:request.negative??'',imageArgs:refs.map(r=>r.path),checks:{content:[],style:[],asset:[]}}]});
26
+ return bindBackend(plan,settings,selected);
27
+ }
28
+
29
+ export async function startConversation(request,settings){
30
+ const file=conversationFile(settings,request.sessionId,request.requestId);
31
+ return locked(runtimeRoot(settings),'conversation',async()=>{
32
+ if(existsSync(file)){
33
+ const existing=readJson(file);if(hash(existing.request)!==hash(request))throw new Error('同一会话请求已提交,不能修改请求后重投');
34
+ return readConversationStatus(settings,request.sessionId,request.requestId);
35
+ }
36
+ const plan=await compileConversation(request,settings),operationId='conversation-'+hash([request.sessionId,request.requestId]).slice(0,48);
37
+ const record={schema:'art-workshop/conversation',request,plan,operationId,status:'dispatching',createdAt:new Date().toISOString()};
38
+ writeJson(file,record);
39
+ try{const started=await startTask(plan,plan.items,settings,{operationId});record.runId=started.taskId;record.status='queued';writeJson(file,record);}
40
+ catch(error){record.status='unknown';record.error=error.message;writeJson(file,record);}
41
+ return readConversationStatus(settings,request.sessionId,request.requestId);
42
+ },{timeout:10000});
43
+ }
44
+ export async function conversationStatus(settings,session,request){
45
+ return locked(runtimeRoot(settings),'conversation',()=>readConversationStatus(settings,session,request),{timeout:10000});
46
+ }
47
+ function readConversationStatus(settings,session,request){
48
+ const file=conversationFile(settings,session,request);
49
+ if(!existsSync(file))return {requestId:request,status:'failed',stopConfirmed:true,preSubmission:true,stopPolling:true,error:'未登记请求,未提交上游',artifacts:[]};
50
+ const record=readJson(file);
51
+ if(!record.runId){
52
+ try{const recovered=recoverTask(runtimeRoot(settings),record.plan.project,record.operationId);record.runId=recovered.taskId;writeJson(file,record);}catch{}
53
+ }
54
+ if(!record.runId){
55
+ // startTask 在拉起工作进程前持久登记;持有会话锁且无任务才可证明未提交。
56
+ const matches=tasks(runtimeRoot(settings)).filter(t=>t.operationId===record.operationId);
57
+ if(matches.length)throw new Error('原运行证据冲突,不能重投');
58
+ record.status='failed';writeJson(file,record);
59
+ return {requestId:request,status:'failed',stopConfirmed:true,preSubmission:true,stopPolling:true,error:record.error??'上游提交前已停止',artifacts:[]};
60
+ }
61
+ const task=taskStatus(runtimeRoot(settings),record.runId),view=taskView(task),artifacts=[];
62
+ if(task.manifestPath&&existsSync(task.manifestPath)){
63
+ const manifest=readJson(task.manifestPath);if(manifest.taskId!==task.taskId||manifest.planHash!==record.plan.planHash)throw new Error('会话产物身份不一致');
64
+ for(const row of manifest.items??[])if(row.ok)for(const name of row.files??[]){const path=resolve(dirname(task.manifestPath),name),delta=relative(dirname(task.manifestPath),path);if(isAbsolute(delta)||delta.startsWith('..'))throw new Error('会话图片路径越界');if(!row.outputHashes?.[name]||sha256File(path)!==row.outputHashes[name])throw new Error('会话图片已变化');artifacts.push({path,sha256:row.outputHashes[name]});}
65
+ }
66
+ return {requestId:request,runId:task.taskId,status:view.status,stopConfirmed:view.stopConfirmed,canResume:view.canResume,stopPolling:['succeeded','failed','cancelled','unknown'].includes(view.status),error:view.error,artifacts};
67
+ }
68
+ export async function controlConversation(settings,session,request,action){
69
+ return locked(runtimeRoot(settings),'conversation',async()=>{
70
+ if(action==='close')return shutdown(settings,{closeServices:false});
71
+ const current=readConversationStatus(settings,session,request);if(!current.runId)return current;
72
+ if(action==='cancel')await cancelTask(runtimeRoot(settings),current.runId,{wait:false});
73
+ else if(action==='resume')await resumeTask(runtimeRoot(settings),current.runId);
74
+ else throw new Error('未知会话控制动作');
75
+ return readConversationStatus(settings,session,request);
76
+ },{timeout:10000});
77
+ }
package/lib/core.mjs CHANGED
@@ -1,75 +1,104 @@
1
- import { existsSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';
2
- import { dirname, join } from 'node:path';
3
- import { hash, readJson, id, keys, text, texts, choice, writeJson } from './shared.mjs';
4
- import { ROOT, loadProject, projectPath } from './project.mjs';
5
- import { TOOL_ROOT } from './settings.mjs';
6
- import {EXAMPLE_CONFIG,STYLE_SCHEMA_VERSION,STYLE_BOUNDARY,OBSERVATION_SCOPES,RULE_TOPICS,RULE_LABELS} from './style-contract.mjs';
7
- export {EXAMPLE_CONFIG} from './style-contract.mjs';
8
-
9
- export function guidance() { return readJson(join(TOOL_ROOT, 'rules', 'core-guidance.json')); }
10
-
11
- export {validateStyleConfig as validateCoreConfig} from './style-contract.mjs';
12
- export {validateReport} from './style-report.mjs';
13
- import {validateReport} from './style-report.mjs';
14
- import {validateStyleConfig as validateCoreConfig,validateIssues,unresolvedIssues,resolvedRecommendation} from './style-review.mjs';
15
-
16
- export function freezeCore({ projectId, report, root = ROOT, note = '确认采用此报告推荐配置', history=[] }) {
17
- const project = loadProject(projectId, root); validateReport(report, projectId);
18
- if (unresolvedIssues(report).length) throw new Error('仍有待决定的问题;记录取舍后再采用');
19
- const body = { schema: 'art-workshop/core', schemaVersion:STYLE_SCHEMA_VERSION, project: projectId, id: report.id,
20
- guidance: guidance(root), config: resolvedRecommendation(report), report, approvedAt: new Date().toISOString(), approvalNote: text(note, 'approvalNote'), decisionHistory: history };
21
- const core = { ...body, coreHash: hash(body) };
22
- const path = projectPath(root, projectId, 'cores', report.id);
23
- if (existsSync(path)) throw new Error('核心已冻结,不能覆写;新风格请使用新身份');
24
- mkdirSync(dirname(path), { recursive: true });
25
- writeFileSync(path, JSON.stringify(core, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' });
26
- if (!project.cores.includes(report.id)) project.cores.push(report.id);
27
- if (!project.defaultCore) project.defaultCore = report.id;
28
- try { writeJson(join(root, 'projects', projectId, 'project.json'), project); }
29
- catch (error) { unlinkSync(path); throw error; }
30
- return core;
31
- }
32
- export function loadCore(projectId, coreId, root = ROOT) {
33
- const project = loadProject(projectId, root);
34
- if (!project.cores.includes(coreId)) throw new Error(`核心 ${coreId} 不属于工程 ${projectId}`);
35
- const core = readJson(projectPath(root, projectId, 'cores', coreId));
36
- const { coreHash, ...body } = core;
37
- if (core.schema !== 'art-workshop/core' || core.project !== projectId || core.id !== coreId || hash(body) !== coreHash) throw new Error('冻结核心身份或哈希校验失败');
38
- if(core.schemaVersion!==STYLE_SCHEMA_VERSION)throw new Error('旧风格核心需派生并重新分析采用,不能自动转换造型、材质或光照约束');
39
- validateCoreConfig(core.config); return core;
40
- }
41
- export function selectCore(project, job, requested, root = ROOT) {
42
- if (requested && job.core && requested !== job.core) throw new Error('指定核心与任务绑定冲突;请明确修改任务的 core');
43
- const selected = requested ?? job.core ?? project.defaultCore;
44
- if (!selected) throw new Error('未选定基础核心;请指定 core,不能猜测或跨工程回退');
45
- return { core: loadCore(project.id, selected, root), source: requested ? '显式选择' : job.core ? '任务绑定' : '工程默认' };
46
- }
47
-
48
- export function corePrompt(core) {
49
- validateCoreConfig(core.config);
50
- return [STYLE_BOUNDARY,'默认倾向可按任务调整;有适用条件的规则仅在条件成立时使用。',
51
- ...RULE_TOPICS.flatMap(topic=>{
52
- const seen=new Set();
53
- const rules=core.config.rules.filter(rule=>rule.scope===topic.id&&!(rule.strength==='avoid'&&!rule.when.trim()&&rule.negative?.length)).filter(rule=>{
54
- const key=JSON.stringify([rule.strength,rule.instruction.trim(),rule.when.trim(),rule.negative??[]]);
55
- if(seen.has(key))return false;seen.add(key);return true;
56
- });
57
- return rules.length?[`【${topic.label}】`,...rules.map(rule=>{
58
- const terms=(rule.negative??[]).filter(term=>!rule.instruction.includes(term));
59
- return `${RULE_LABELS[rule.strength]}${rule.when.trim()?'('+rule.when+')':''}:${rule.instruction}${terms.length?';排除表达:'+[...new Set(terms)].join('、'):''}`;
60
- })]:[];
61
- })].join('\n');
62
- }
63
- /** Explicit unconditional terms only. Never infer negation or evaluate conditions. */
64
- export function coreNegative(core){
65
- validateCoreConfig(core.config);
66
- const seen=new Set(),terms=[];
67
- for(const rule of core.config.rules){
68
- if(rule.strength!=='avoid'||rule.when.trim())continue;
69
- for(const value of rule.negative??[]){
70
- const term=value.trim(),key=term.normalize('NFKC').toLowerCase();
71
- if(!seen.has(key)){seen.add(key);terms.push(term);}
72
- }
73
- }
74
- return terms.join(', ');
75
- }
1
+ import { existsSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { hash, readJson, id, keys, text, texts, choice, writeJson } from './shared.mjs';
4
+ import { ROOT, loadProject, projectPath } from './project.mjs';
5
+ import { TOOL_ROOT } from './settings.mjs';
6
+ import {ownedPath} from './workspace.mjs';
7
+ import {EXAMPLE_CONFIG,STYLE_SCHEMA_VERSION,STYLE_BOUNDARY,OBSERVATION_SCOPES,RULE_TOPICS,RULE_LABELS} from './style-contract.mjs';
8
+ export {EXAMPLE_CONFIG} from './style-contract.mjs';
9
+
10
+ export function guidance() { return readJson(join(TOOL_ROOT, 'rules', 'core-guidance.json')); }
11
+
12
+ export {validateStyleConfig as validateCoreConfig} from './style-contract.mjs';
13
+ export {validateReport} from './style-report.mjs';
14
+ import {validateReport} from './style-report.mjs';
15
+ import {validateStyleConfig as validateCoreConfig,validateIssues,unresolvedIssues,resolvedRecommendation} from './style-review.mjs';
16
+
17
+ export function freezeCore({ projectId, report, root = ROOT, note = '确认采用此报告推荐配置', history=[] }) {
18
+ const project = loadProject(projectId, root); validateReport(report, projectId);
19
+ if (unresolvedIssues(report).length) throw new Error('仍有待决定的问题;记录取舍后再采用');
20
+ const body = { schema: 'art-workshop/core', schemaVersion:STYLE_SCHEMA_VERSION, project: projectId, id: report.id,
21
+ guidance: guidance(root), config: resolvedRecommendation(report), report, approvedAt: new Date().toISOString(), approvalNote: text(note, 'approvalNote'), decisionHistory: history };
22
+ const core = { ...body, coreHash: hash(body) };
23
+ const path = projectPath(root, projectId, 'cores', report.id);
24
+ if (existsSync(path)) throw new Error('核心已冻结,不能覆写;新风格请使用新身份');
25
+ mkdirSync(dirname(path), { recursive: true });
26
+ writeFileSync(path, JSON.stringify(core, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' });
27
+ if (!project.cores.includes(report.id)) project.cores.push(report.id);
28
+ if (!project.defaultCore) project.defaultCore = report.id;
29
+ try { writeJson(join(root, 'projects', projectId, 'project.json'), project); }
30
+ catch (error) { unlinkSync(path); throw error; }
31
+ return core;
32
+ }
33
+ /** Publish a saved style while retaining every prior execution snapshot by hash. */
34
+ export function syncStyleCore(root, record) {
35
+ if (!Array.isArray(record.config.rules) || ['discarded','cleanup-required'].includes(record.status)) return () => {};
36
+ validateCoreConfig({rules:record.config.rules});
37
+ const path=projectPath(root,record.project,'cores',record.id),previous=existsSync(path)?readJson(path):null;
38
+ if(previous){const {coreHash,...body}=previous;if(hash(body)!==coreHash||previous.id!==record.id||previous.project!==record.project)throw new Error('风格核心身份或哈希校验失败');}
39
+ const projectFile=join(root,'projects',record.project,'project.json'),previousProject=loadProject(record.project,root),project=structuredClone(previousProject);
40
+ const body={schema:'art-workshop/core',schemaVersion:STYLE_SCHEMA_VERSION,project:record.project,id:record.id,
41
+ revision:record.revision,guidance:guidance(),config:{rules:structuredClone(record.config.rules)},
42
+ report:record.report?.data??previous?.report??null,approvedSamples:structuredClone(record.samples??[]),
43
+ savedAt:record.updatedAt??record.createdAt};
44
+ const core={...body,coreHash:hash(body)},history=ownedPath(dirname(path),'core-history');
45
+ for(const snapshot of [previous,core].filter(Boolean)){
46
+ const file=ownedPath(history,snapshot.coreHash+'.json');
47
+ if(existsSync(file)){if(hash(readJson(file))!==hash(snapshot))throw new Error('历史风格快照完整性校验失败');}
48
+ else {mkdirSync(history,{recursive:true});writeFileSync(file,JSON.stringify(snapshot,null,2)+'\n',{encoding:'utf8',flag:'wx'});}
49
+ }
50
+ const rollback=()=>{if(previous)writeJson(path,previous);else if(existsSync(path))unlinkSync(path);writeJson(projectFile,previousProject);};
51
+ try{
52
+ writeJson(path,core);
53
+ if(!project.cores.includes(record.id)){project.cores.push(record.id);project.defaultCore??=record.id;project.revision=(project.revision??1)+1;writeJson(projectFile,project);}
54
+ }catch(error){rollback();throw error;}
55
+ record.status='frozen';record.coreHash=core.coreHash;
56
+ return rollback;
57
+ }
58
+ export function loadCore(projectId, coreId, root = ROOT) {
59
+ const project = loadProject(projectId, root);
60
+ if (!project.cores.includes(coreId)) throw new Error(`核心 ${coreId} 不属于工程 ${projectId}`);
61
+ const recordFile=join(dirname(projectPath(root,projectId,'cores',coreId)),'style.json'),record=existsSync(recordFile)?readJson(recordFile):null;
62
+ if(record&&['discarded','cleanup-required'].includes(record.status))throw new Error('风格已归档或不可用,请选择有效风格');
63
+ const core = readJson(projectPath(root, projectId, 'cores', coreId));
64
+ const { coreHash, ...body } = core;
65
+ if (core.schema !== 'art-workshop/core' || core.project !== projectId || core.id !== coreId || hash(body) !== coreHash) throw new Error('冻结核心身份或哈希校验失败');
66
+ if(core.revision!==undefined&&record&&(record.revision!==core.revision||record.coreHash!==coreHash))throw new Error('风格保存尚未完成,请重新读取并保存;不能执行不匹配的版本');
67
+ if(core.schemaVersion!==STYLE_SCHEMA_VERSION)throw new Error('旧风格核心需派生并重新分析采用,不能自动转换造型、材质或光照约束');
68
+ validateCoreConfig(core.config); return core;
69
+ }
70
+ export function selectCore(project, job, requested, root = ROOT) {
71
+ if (requested && job.core && requested !== job.core) throw new Error('指定核心与任务绑定冲突;请明确修改任务的 core');
72
+ const selected = requested ?? job.core ?? project.defaultCore;
73
+ if (!selected) throw new Error('未选定基础核心;请指定 core,不能猜测或跨工程回退');
74
+ return { core: loadCore(project.id, selected, root), source: requested ? '显式选择' : job.core ? '任务绑定' : '工程默认' };
75
+ }
76
+
77
+ export function corePrompt(core) {
78
+ validateCoreConfig(core.config);
79
+ return [STYLE_BOUNDARY,'默认倾向可按任务调整;有适用条件的规则仅在条件成立时使用。',
80
+ ...RULE_TOPICS.flatMap(topic=>{
81
+ const seen=new Set();
82
+ const rules=core.config.rules.filter(rule=>rule.scope===topic.id&&!(rule.strength==='avoid'&&!rule.when.trim()&&rule.negative?.length)).filter(rule=>{
83
+ const key=JSON.stringify([rule.strength,rule.instruction.trim(),rule.when.trim(),rule.negative??[]]);
84
+ if(seen.has(key))return false;seen.add(key);return true;
85
+ });
86
+ return rules.length?[`【${topic.label}】`,...rules.map(rule=>{
87
+ const terms=(rule.negative??[]).filter(term=>!rule.instruction.includes(term));
88
+ return `${RULE_LABELS[rule.strength]}${rule.when.trim()?'('+rule.when+')':''}:${rule.instruction}${terms.length?';排除表达:'+[...new Set(terms)].join('、'):''}`;
89
+ })]:[];
90
+ })].join('\n');
91
+ }
92
+ /** Explicit unconditional terms only. Never infer negation or evaluate conditions. */
93
+ export function coreNegative(core){
94
+ validateCoreConfig(core.config);
95
+ const seen=new Set(),terms=[];
96
+ for(const rule of core.config.rules){
97
+ if(rule.strength!=='avoid'||rule.when.trim())continue;
98
+ for(const value of rule.negative??[]){
99
+ const term=value.trim(),key=term.normalize('NFKC').toLowerCase();
100
+ if(!seen.has(key)){seen.add(key);terms.push(term);}
101
+ }
102
+ }
103
+ return terms.join(', ');
104
+ }
@@ -1,12 +1,12 @@
1
- import {readFileSync,readdirSync} from 'node:fs';
2
- import {fileURLToPath} from 'node:url';
3
- const root=new URL('../docs/local-models/',import.meta.url);
4
- export function deploymentGuide(id){
5
- const entries=readdirSync(root).filter(name=>name.endsWith('.json')).map(name=>({name,contract:JSON.parse(readFileSync(new URL(name,root),'utf8'))}));
6
- const selected=id?entries.find(entry=>entry.contract.id===id):entries.find(entry=>entry.name==='qwen-image-2.1.json');
7
- if(!selected)throw new Error('未知部署指南 '+id);
8
- if(selected.contract.backend.workflow && !selected.contract.backend.workflow.startsWith('vant-builtin-'))selected.contract.backend.workflow=fileURLToPath(new URL(selected.contract.backend.workflow,root));
9
- return {schema:'art-workshop/deployment-guide',id:selected.contract.id,contract:selected.contract,
10
- available:entries.map(entry=>({id:entry.contract.id,model:entry.contract.backend.model})),
11
- instructions:readFileSync(new URL(selected.name.replace(/\.json$/,'.md'),root),'utf8'),directory:fileURLToPath(root)};
12
- }
1
+ import {readFileSync,readdirSync} from 'node:fs';
2
+ import {fileURLToPath} from 'node:url';
3
+ const root=new URL('../docs/local-models/',import.meta.url);
4
+ export function deploymentGuide(id){
5
+ const entries=readdirSync(root).filter(name=>name.endsWith('.json')).map(name=>({name,contract:JSON.parse(readFileSync(new URL(name,root),'utf8'))}));
6
+ const selected=id?entries.find(entry=>entry.contract.id===id):entries.find(entry=>entry.name==='qwen-image-2.1.json');
7
+ if(!selected)throw new Error('未知部署指南 '+id);
8
+ if(selected.contract.backend.workflow && !selected.contract.backend.workflow.startsWith('vant-builtin-'))selected.contract.backend.workflow=fileURLToPath(new URL(selected.contract.backend.workflow,root));
9
+ return {schema:'art-workshop/deployment-guide',id:selected.contract.id,contract:selected.contract,
10
+ available:entries.map(entry=>({id:entry.contract.id,model:entry.contract.backend.model})),
11
+ instructions:readFileSync(new URL(selected.name.replace(/\.json$/,'.md'),root),'utf8'),directory:fileURLToPath(root)};
12
+ }
package/lib/design.mjs CHANGED
@@ -1,29 +1,29 @@
1
- import {resolveDimensions,DIMENSION_CAPABILITIES} from './dimensions.mjs';
2
- import { keys, integer } from './shared.mjs';
3
-
4
- // 设计基准归资产规格,单体尺寸与倍率归任务;出图尺寸由它们确定。
5
- export function design(profile, override, explicitExecution = {}) {
6
- if (profile.design === undefined) {
7
- if (override !== undefined) throw new Error('单体 design 需要资产规格声明 design');
8
- return null;
9
- }
10
- const base = profile.design;
11
- keys(base, ['resolution', 'outputScale'], 'profile.design');
12
- keys(base.resolution, ['width', 'height'], 'design.resolution');
13
- integer(base.resolution.width, 'design.resolution.width', 1, 16384);
14
- integer(base.resolution.height, 'design.resolution.height', 1, 16384);
15
- if(!Number.isFinite(base.outputScale)||base.outputScale<1||base.outputScale>4)throw new Error('预留缩放必须在 1 到 4 之间');
16
- if (override !== undefined) keys(override, ['width', 'height', 'outputScale'], 'item.design');
17
- const size = override === undefined ? base.resolution : override;
18
- integer(size.width, 'design.width', 1, base.resolution.width);
19
- integer(size.height, 'design.height', 1, base.resolution.height);
20
- const outputScale = override?.outputScale ?? base.outputScale;
21
- if(!Number.isFinite(outputScale)||outputScale<1||outputScale>4)throw new Error('预留缩放必须在 1 到 4 之间');
22
- if (explicitExecution.size !== undefined) throw new Error('设计尺寸与任务 execution.size 不能同时指定');
23
- const requestedSize={ width: size.width * outputScale, height: size.height * outputScale },dimensions=resolveDimensions(requestedSize,DIMENSION_CAPABILITIES.bailian),outputSize=dimensions.actual;
24
- return { resolution: { ...base.resolution }, size: { width: size.width, height: size.height }, outputScale, requestedSize,outputSize,dimensions };
25
- }
26
-
27
- export function designPrompt(value) {
28
- return `UI 设计基准 ${value.resolution.width}×${value.resolution.height};本单体设计尺寸 ${value.size.width}×${value.size.height};出图倍率 ${value.outputScale},画布 ${value.outputSize.width}×${value.outputSize.height} 像素。保持设计宽高比,完整展示并在画布内居中;描边、圆角与细节随同一倍率缩放。`;
29
- }
1
+ import {resolveDimensions,DIMENSION_CAPABILITIES} from './dimensions.mjs';
2
+ import { keys, integer } from './shared.mjs';
3
+
4
+ // 设计基准归资产规格,单体尺寸与倍率归任务;出图尺寸由它们确定。
5
+ export function design(profile, override, explicitExecution = {}) {
6
+ if (profile.design === undefined) {
7
+ if (override !== undefined) throw new Error('单体 design 需要资产规格声明 design');
8
+ return null;
9
+ }
10
+ const base = profile.design;
11
+ keys(base, ['resolution', 'outputScale'], 'profile.design');
12
+ keys(base.resolution, ['width', 'height'], 'design.resolution');
13
+ integer(base.resolution.width, 'design.resolution.width', 1, 16384);
14
+ integer(base.resolution.height, 'design.resolution.height', 1, 16384);
15
+ if(!Number.isFinite(base.outputScale)||base.outputScale<1||base.outputScale>4)throw new Error('预留缩放必须在 1 到 4 之间');
16
+ if (override !== undefined) keys(override, ['width', 'height', 'outputScale'], 'item.design');
17
+ const size = override === undefined ? base.resolution : override;
18
+ integer(size.width, 'design.width', 1, base.resolution.width);
19
+ integer(size.height, 'design.height', 1, base.resolution.height);
20
+ const outputScale = override?.outputScale ?? base.outputScale;
21
+ if(!Number.isFinite(outputScale)||outputScale<1||outputScale>4)throw new Error('预留缩放必须在 1 到 4 之间');
22
+ if (explicitExecution.size !== undefined) throw new Error('设计尺寸与任务 execution.size 不能同时指定');
23
+ const requestedSize={ width: size.width * outputScale, height: size.height * outputScale },dimensions=resolveDimensions(requestedSize,DIMENSION_CAPABILITIES.bailian),outputSize=dimensions.actual;
24
+ return { resolution: { ...base.resolution }, size: { width: size.width, height: size.height }, outputScale, requestedSize,outputSize,dimensions };
25
+ }
26
+
27
+ export function designPrompt(value) {
28
+ return `UI 设计基准 ${value.resolution.width}×${value.resolution.height};本单体设计尺寸 ${value.size.width}×${value.size.height};出图倍率 ${value.outputScale},画布 ${value.outputSize.width}×${value.outputSize.height} 像素。保持设计宽高比,完整展示并在画布内居中;描边、圆角与细节随同一倍率缩放。`;
29
+ }