@kevlns/art-workshop 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/AGENTS.md +26 -49
  2. package/README.md +31 -93
  3. package/art-workshop.mjs +70 -26
  4. package/docs/commands.md +913 -80
  5. package/docs/configuration.md +33 -139
  6. package/docs/core-guidance.md +15 -76
  7. package/docs/data-formats.md +15 -151
  8. package/docs/deployment.md +42 -0
  9. package/docs/model-architecture.md +52 -0
  10. package/docs/modes.md +15 -116
  11. package/docs/remote-models.md +42 -0
  12. package/docs/troubleshooting.md +31 -67
  13. package/lib/adapters/dashscope.mjs +234 -0
  14. package/lib/adapters/index.mjs +28 -0
  15. package/lib/agent.mjs +2 -2
  16. package/lib/analysis-worker.mjs +27 -0
  17. package/lib/analyze.mjs +29 -13
  18. package/lib/backends.mjs +350 -74
  19. package/lib/bl.mjs +3 -18
  20. package/lib/candidates.mjs +82 -0
  21. package/lib/comfyui.mjs +10 -8
  22. package/lib/contracts.d.ts +67 -0
  23. package/lib/core.mjs +24 -45
  24. package/lib/deployment-process.mjs +19 -0
  25. package/lib/deployment-source.mjs +24 -0
  26. package/lib/deployment-worker.mjs +86 -0
  27. package/lib/deployment.mjs +75 -0
  28. package/lib/design.mjs +5 -5
  29. package/lib/dimensions.mjs +22 -0
  30. package/lib/edit.mjs +6 -3
  31. package/lib/environments.mjs +67 -0
  32. package/lib/execution/remote.mjs +156 -0
  33. package/lib/executor.mjs +12 -24
  34. package/lib/generate.mjs +9 -6
  35. package/lib/generation-policy.mjs +198 -0
  36. package/lib/images.mjs +10 -0
  37. package/lib/lifecycle.mjs +40 -0
  38. package/lib/migration.mjs +154 -0
  39. package/lib/model-catalog.mjs +288 -0
  40. package/lib/model-registry.mjs +234 -0
  41. package/lib/plan.mjs +98 -28
  42. package/lib/project.mjs +13 -4
  43. package/lib/providers.mjs +27 -22
  44. package/lib/refs.mjs +10 -18
  45. package/lib/runtime.mjs +6 -4
  46. package/lib/service.mjs +45 -4
  47. package/lib/settings.mjs +2 -4
  48. package/lib/shared.mjs +10 -7
  49. package/lib/style-contract.mjs +19 -0
  50. package/lib/style-lifecycle.mjs +73 -0
  51. package/lib/task-references.mjs +37 -0
  52. package/lib/task-worker.mjs +225 -50
  53. package/lib/tasks.mjs +442 -63
  54. package/lib/templates.mjs +68 -0
  55. package/lib/transport/cli.mjs +69 -0
  56. package/lib/transport/http.mjs +82 -0
  57. package/lib/vision.mjs +46 -0
  58. package/lib/workflows.mjs +10 -1
  59. package/lib/workspace.mjs +211 -0
  60. package/package.json +9 -3
  61. package/rules/core-guidance.json +14 -13
  62. package/skills/art-workshop/SKILL.md +28 -53
  63. package/v-cli.plugin.json +1257 -143
  64. package/docs//351/227/256/351/242/230/346/212/245/345/221/212-2026-10-08.md +0 -29
package/lib/comfyui.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import {serviceRoot} from './service.mjs';
1
2
  import {readFileSync,writeFileSync} from 'node:fs';
2
3
  import {join,basename} from 'node:path';
3
4
  import {randomUUID} from 'node:crypto';
@@ -5,19 +6,20 @@ import {buildComfyRequest} from './backends.mjs';
5
6
  import {http,sleep,locked} from './runtime.mjs';
6
7
  import {workflowError} from './diagnostics.mjs';
7
8
 
8
- export async function cancelPrompt(endpoint,promptId,{all=false}={}) {
9
- await http(endpoint,'/queue',{method:'POST',body:all?{clear:true}:{delete:[promptId]}});
9
+ export async function cancelPrompt(endpoint,promptId) {
10
+ if(typeof promptId!=='string'||!promptId)throw new Error('缺少可核验的后端任务身份');
11
+ await http(endpoint,'/queue',{method:'POST',body:{delete:[promptId]}});
10
12
  const queue=await http(endpoint,'/queue');
11
- if(all||queue.queue_running?.some(row=>row[1]===promptId)) {
12
- if(!all&&queue.queue_running.some(row=>row[1]!==promptId))throw new Error('其他任务正在运行,拒绝全局中断');
13
+ if(queue.queue_running?.some(row=>row[1]===promptId)) {
14
+ if(queue.queue_running.some(row=>row[1]!==promptId))throw new Error('其他任务正在运行,拒绝全局中断');
13
15
  // ComfyUI interrupt supports a prompt_id guard, preventing an unrelated next task from being interrupted.
14
- await http(endpoint,'/interrupt',{method:'POST',body:all?{}:{prompt_id:promptId}});
16
+ await http(endpoint,'/interrupt',{method:'POST',body:{prompt_id:promptId}});
15
17
  }
16
18
  const deadline=Date.now()+30000;
17
- while(true){const q=await http(endpoint,'/queue');const active=[...(q.queue_running??[]),...(q.queue_pending??[])];if(!active.some(row=>all||row[1]===promptId))return;if(Date.now()>deadline)throw new Error('ComfyUI 任务停止超时');await sleep(200);}
19
+ while(true){const q=await http(endpoint,'/queue');const active=[...(q.queue_running??[]),...(q.queue_pending??[])];if(!active.some(row=>row[1]===promptId))return;if(Date.now()>deadline)throw new Error('ComfyUI 任务停止超时');await sleep(200);}
18
20
  }
19
21
  export async function generateComfy(plan,item,{endpoint,root,outputDir,cancelled=()=>false,onPrompt=()=>{}}) {
20
- return locked(root,'queue-'+new URL(endpoint).port,async()=>{
22
+ return locked(serviceRoot(),'queue-'+new URL(endpoint).port,async()=>{
21
23
  const b=plan.backend,e=item.execution??plan.execution,files=[];
22
24
  if(item.imageArgs.length>1)throw new Error('当前编辑适配器只接受一张原图');
23
25
  let image;
@@ -31,7 +33,7 @@ export async function generateComfy(plan,item,{endpoint,root,outputDir,cancelled
31
33
  const request=buildComfyRequest(plan,item,{index,image});
32
34
  let result;
33
35
  try{result=await http(endpoint,'/prompt',{method:'POST',body:{prompt:request.prompt,client_id:randomUUID()}});}
34
- catch(error){if(error.response)throw workflowError('ComfyUI 拒绝工作流:'+JSON.stringify(error.response.error??error.response),b,{stage:'submission',nodeErrors:error.response.node_errors,cause:error});throw error;}
36
+ catch(error){if(error.response)throw workflowError('ComfyUI 拒绝工作流:'+JSON.stringify(error.response.error??error.response),b,{stage:'submission',nodeErrors:error.response.node_errors,cause:error});error.unsettled=true;throw error;}
35
37
  if(!result.prompt_id||Object.keys(result.node_errors??{}).length){
36
38
  const error=workflowError('ComfyUI 拒绝工作流',b,{stage:'submission',promptId:result.prompt_id,nodeErrors:result.node_errors});
37
39
  if(result.prompt_id){onPrompt(result.prompt_id);try{await cancelPrompt(endpoint,result.prompt_id);}catch{error.unsettled=true;}}
@@ -0,0 +1,67 @@
1
+ /** Stable image extension contracts. Runtime validation lives in model-registry. */
2
+ export type ImageMode = "generate" | "edit";
3
+ export type ImageParameterRule = {
4
+ type: "boolean" | "integer" | "string";
5
+ wire: string;
6
+ cli?: string;
7
+ default?: boolean | number | string;
8
+ min?: number;
9
+ max?: number;
10
+ enum?: (boolean | number | string)[];
11
+ };
12
+ export interface ImageRequest {
13
+ schema: "art/image-request-v1";
14
+ api: string;
15
+ adapter: string;
16
+ contractHash: string;
17
+ module: ImageMode;
18
+ model: string;
19
+ prompt: string;
20
+ negativePrompt: string;
21
+ images: string[];
22
+ transport: {
23
+ adapter: string;
24
+ version: number;
25
+ mode: string;
26
+ path?: string;
27
+ timeoutMilliseconds?: number;
28
+ };
29
+ inputPolicy?: {
30
+ maxBytes: number;
31
+ formats: string[];
32
+ minAxis?: number;
33
+ maxAxis?: number;
34
+ minRatio?: number;
35
+ maxRatio?: number;
36
+ alpha?: boolean;
37
+ };
38
+ parameters: Record<string, boolean | number | string>;
39
+ size: string;
40
+ seed: number;
41
+ count: number;
42
+ adjustments: { parameter: string; action: string; message: string }[];
43
+ }
44
+ export interface RemoteReceipt {
45
+ schema: "art/remote-receipt-v1";
46
+ adapter: string;
47
+ adapterVersion: number;
48
+ requestHash: string;
49
+ baseUrl: string;
50
+ submittedAt: string;
51
+ state: "dispatching" | "accepted" | "completed" | "failed" | "cancelled";
52
+ taskId?: string;
53
+ urls?: string[];
54
+ message?: string;
55
+ }
56
+ export type RemoteTransition = Pick<RemoteReceipt, "state"> &
57
+ Partial<Pick<RemoteReceipt, "taskId" | "urls" | "message">>;
58
+ export interface ImageAdapter {
59
+ id: string;
60
+ label?: string;
61
+ version: number;
62
+ cancellation: "unsupported" | "supported";
63
+ prepare(request: ImageRequest, context: object): Promise<object>;
64
+ submit(request: ImageRequest, context: object): Promise<RemoteTransition>;
65
+ query(receipt: RemoteReceipt, context: object): Promise<RemoteTransition>;
66
+ preview?(request: ImageRequest): object;
67
+ }
package/lib/core.mjs CHANGED
@@ -3,29 +3,21 @@ import { dirname, join } from 'node:path';
3
3
  import { hash, readJson, id, keys, text, texts, integer, choice, hex, writeJson } from './shared.mjs';
4
4
  import { ROOT, loadProject, projectPath } from './project.mjs';
5
5
  import { TOOL_ROOT } from './settings.mjs';
6
+ import {EXAMPLE_CONFIG,STYLE_SCHEMA_VERSION,STYLE_BOUNDARY,OBSERVATION_SCOPES} from './style-contract.mjs';
7
+ export {EXAMPLE_CONFIG} from './style-contract.mjs';
6
8
 
7
- export const EXAMPLE_CONFIG = {
8
- medium: 'illustration',
9
- shape: { contour: 'rounded', detail: 'low' },
10
- render: { shading: 'cel', toneSteps: 2, outline: { enabled: true, color: '#34445C', width: 0.004 }, highlights: 'hard-edge', finish: 'matte', texture: 'none' },
11
- lighting: { direction: 'top-front', contrast: 'medium' },
12
- color: { preserveIdentity: true, shadowShift: 'cool' },
13
- domains: { cell: { treatment: 'organic', signature: '保留圆润生物轮廓,科幻点缀仅作用于自身表面。' } }
14
- };
15
9
  export function guidance() { return readJson(join(TOOL_ROOT, 'rules', 'core-guidance.json')); }
16
10
 
17
11
  export function validateCoreConfig(config) {
18
- keys(config, ['medium', 'shape', 'render', 'lighting', 'color', 'domains'], 'core');
12
+ keys(config, ['medium', 'render', 'color'], 'core');
19
13
  choice(config.medium, ['illustration', 'painting', 'pixel-art', 'photography'], 'medium');
20
- keys(config.shape, ['contour', 'detail'], 'shape');
21
- choice(config.shape.contour, ['rounded', 'angular', 'mixed'], 'shape.contour');
22
- choice(config.shape.detail, ['low', 'medium', 'high'], 'shape.detail');
23
14
  const r = config.render;
24
- keys(r, ['shading', 'toneSteps', 'outline', 'highlights', 'finish', 'texture'], 'render');
15
+ keys(r, ['shading', 'toneSteps', 'detail', 'outline', 'highlights', 'brushwork', 'valueContrast'], 'render');
25
16
  choice(r.shading, ['cel', 'flat', 'smooth', 'painterly', 'pixel'], 'render.shading');
26
17
  choice(r.highlights, ['hard-edge', 'soft', 'none'], 'render.highlights');
27
- choice(r.finish, ['matte', 'glossy'], 'render.finish');
28
- choice(r.texture, ['none', 'visible'], 'render.texture');
18
+ choice(r.detail, ['low', 'medium', 'high'], 'render.detail');
19
+ choice(r.brushwork, ['clean', 'visible'], 'render.brushwork');
20
+ choice(r.valueContrast, ['low', 'medium', 'high'], 'render.valueContrast');
29
21
  keys(r.outline, ['enabled', 'color', 'width'], 'render.outline');
30
22
  if (typeof r.outline.enabled !== 'boolean') throw new Error('outline.enabled 必须为布尔值');
31
23
  hex(r.outline.color, 'outline.color');
@@ -33,34 +25,26 @@ export function validateCoreConfig(config) {
33
25
  || r.outline.enabled && r.outline.width === 0 || !r.outline.enabled && r.outline.width !== 0) throw new Error('描边开关与宽度矛盾');
34
26
  if (['cel', 'flat', 'pixel'].includes(r.shading)) integer(r.toneSteps, 'toneSteps', 1, 8);
35
27
  else if (r.toneSteps !== null) throw new Error('连续或笔触明暗不应同时冻结固定色阶数');
36
- if (r.shading === 'cel' && (r.toneSteps < 2 || r.highlights === 'soft' || r.texture !== 'none')) throw new Error('赛璐璐与色阶、高光或纹理规则矛盾');
28
+ if (r.shading === 'cel' && (r.toneSteps < 2 || r.highlights === 'soft' || r.brushwork !== 'clean')) throw new Error('赛璐璐与色阶、高光或笔触规则矛盾');
37
29
  if (r.shading === 'flat' && r.toneSteps !== 1) throw new Error('平涂只能定义一个主色阶');
38
30
  if (config.medium === 'pixel-art' && r.shading !== 'pixel' || config.medium !== 'pixel-art' && r.shading === 'pixel') throw new Error('像素媒介与渲染方式矛盾');
39
31
  if (config.medium === 'photography' && (r.shading !== 'smooth' || r.outline.enabled)) throw new Error('摄影媒介与渲染或轮廓描边矛盾');
40
- keys(config.lighting, ['direction', 'contrast'], 'lighting');
41
- choice(config.lighting.direction, ['top-front', 'front', 'left', 'right', 'diffuse'], 'lighting.direction');
42
- choice(config.lighting.contrast, ['low', 'medium', 'high'], 'lighting.contrast');
43
- keys(config.color, ['preserveIdentity', 'shadowShift'], 'color');
44
- if (typeof config.color.preserveIdentity !== 'boolean') throw new Error('preserveIdentity 必须为布尔值');
32
+ keys(config.color, ['saturation', 'contrast', 'shadowShift'], 'color');
33
+ choice(config.color.saturation, ['low', 'medium', 'high'], 'color.saturation');
34
+ choice(config.color.contrast, ['low', 'medium', 'high'], 'color.contrast');
45
35
  choice(config.color.shadowShift, ['cool', 'warm', 'neutral'], 'shadowShift');
46
- if (!config.domains || typeof config.domains !== 'object' || Array.isArray(config.domains)) throw new Error('domains 必须为对象');
47
- for (const [kind, domain] of Object.entries(config.domains)) {
48
- id(kind, 'domain kind'); keys(domain, ['treatment', 'signature'], `domains.${kind}`);
49
- choice(domain.treatment, ['organic', 'hard-surface', 'emissive', 'structure', 'symbol'], 'domain.treatment');
50
- text(domain.signature, 'domain.signature', 80);
51
- if (/背景|居中|留白|画幅|水印|seed|模型|分辨率|只能出现|唯一主体|不得出现第二|必须.*(?:红色|蓝色|绿色|白色|黑色)/i.test(domain.signature)) throw new Error('题材描述越过职责边界');
52
- }
53
36
  return config;
54
37
  }
55
38
 
56
39
  export function validateReport(report, projectId) {
57
- keys(report, ['schema', 'project', 'id', 'summary', 'observations', 'recommendation', 'conflicts', 'uncertainties', 'provenance'], 'report');
40
+ keys(report, ['schema', 'schemaVersion', 'project', 'id', 'summary', 'observations', 'recommendation', 'conflicts', 'uncertainties', 'provenance'], 'report');
41
+ if(report.schemaVersion!==STYLE_SCHEMA_VERSION)throw new Error('风格报告职责版本已变化,请重新分析,不能采用旧报告');
58
42
  if (report.schema !== 'art-workshop/style-report' || report.project !== projectId) throw new Error('风格报告身份不匹配');
59
43
  id(report.id, 'report.id'); text(report.summary, 'report.summary', 300);
60
44
  if (!Array.isArray(report.observations)) throw new Error('observations 必须为数组');
61
45
  for (const item of report.observations) {
62
46
  keys(item, ['source', 'scope', 'feature', 'evidence', 'confidence'], 'observation');
63
- text(item.source, 'source', 1024); choice(item.scope, ['style', 'content', 'asset'], 'scope');
47
+ text(item.source, 'source', 1024); choice(item.scope, OBSERVATION_SCOPES, 'scope');
64
48
  text(item.feature, 'feature'); text(item.evidence, 'evidence');
65
49
  if (!Number.isFinite(item.confidence) || item.confidence < 0 || item.confidence > 1) throw new Error('confidence 必须在 0~1');
66
50
  }
@@ -71,7 +55,7 @@ export function validateReport(report, projectId) {
71
55
  export function freezeCore({ projectId, report, root = ROOT, note = '确认采用此报告推荐配置' }) {
72
56
  const project = loadProject(projectId, root); validateReport(report, projectId);
73
57
  if (report.conflicts.length || report.uncertainties.length) throw new Error('报告仍有冲突或未确定项;处理后再冻结');
74
- const body = { schema: 'art-workshop/core', project: projectId, id: report.id,
58
+ const body = { schema: 'art-workshop/core', schemaVersion:STYLE_SCHEMA_VERSION, project: projectId, id: report.id,
75
59
  guidance: guidance(root), config: report.recommendation, report, approvedAt: new Date().toISOString(), approvalNote: text(note, 'approvalNote') };
76
60
  const core = { ...body, coreHash: hash(body) };
77
61
  const path = projectPath(root, projectId, 'cores', report.id);
@@ -90,6 +74,7 @@ export function loadCore(projectId, coreId, root = ROOT) {
90
74
  const core = readJson(projectPath(root, projectId, 'cores', coreId));
91
75
  const { coreHash, ...body } = core;
92
76
  if (core.schema !== 'art-workshop/core' || core.project !== projectId || core.id !== coreId || hash(body) !== coreHash) throw new Error('冻结核心身份或哈希校验失败');
77
+ if(core.schemaVersion!==STYLE_SCHEMA_VERSION)throw new Error('旧风格核心需派生并重新分析采用,不能自动转换造型、材质或光照约束');
93
78
  validateCoreConfig(core.config); return core;
94
79
  }
95
80
  export function selectCore(project, job, requested, root = ROOT) {
@@ -100,25 +85,19 @@ export function selectCore(project, job, requested, root = ROOT) {
100
85
  }
101
86
 
102
87
  const labels = { illustration: '数字插画', painting: '绘画', 'pixel-art': '像素艺术', photography: '摄影',
103
- rounded: '圆润', angular: '棱角明确', mixed: '圆润与棱角结合', low: '低', medium: '中', high: '高',
88
+ low: '低', medium: '中', high: '高', clean:'干净无明显笔触', visible:'可见笔触',
104
89
  cel: '赛璐璐硬边明暗', flat: '平涂', smooth: '连续明暗', painterly: '笔触塑形', pixel: '像素色块',
105
- 'hard-edge': '硬边色块高光', soft: '柔和高光', none: '无', matte: '哑光', glossy: '光泽', visible: '可见',
106
- 'top-front': '顶偏前', front: '正前', left: '左侧', right: '右侧', diffuse: '漫射', cool: '偏冷', warm: '偏暖', neutral: '中性',
107
- organic: '有机表面', 'hard-surface': '硬表面', emissive: '发光形态', structure: '连接结构', symbol: '简洁符号' };
108
- export function corePrompt(core, kinds = []) {
90
+ 'hard-edge': '硬边色块高光', soft: '柔和高光', none: '无', cool: '偏冷', warm: '偏暖', neutral: '中性' };
91
+ export function corePrompt(core) {
109
92
  const c = core.config, r = c.render;
110
- const lines = [`媒介:${labels[c.medium]}。轮廓:${labels[c.shape.contour]};细节密度:${labels[c.shape.detail]}。`,
111
- `明暗:${labels[r.shading]}${r.toneSteps === null ? '' : `,${r.toneSteps} 个主色阶`}。${labels[r.highlights]};表面${labels[r.finish]};纹理${labels[r.texture]}。`,
93
+ const lines = [STYLE_BOUNDARY,`媒介:${labels[c.medium]}。描绘细节密度:${labels[r.detail]};结构与部件完整服从任务。`,
94
+ `明暗:${labels[r.shading]}${r.toneSteps === null ? '' : `,${r.toneSteps} 个主色阶`}。高光画法:${labels[r.highlights]};笔触:${labels[r.brushwork]};明度对比:${labels[r.valueContrast]}。`,
112
95
  r.outline.enabled ? `轮廓描边:${r.outline.color},粗细约画幅宽度的 ${r.outline.width * 100}%。` : '不使用轮廓描边。',
113
- `主光源:${labels[c.lighting.direction]};明暗对比:${labels[c.lighting.contrast]}。阴影偏色:${labels[c.color.shadowShift]}。`,
114
- c.color.preserveIdentity ? '保留内容声明的身份色,色相分别按实体与效果声明执行。' : '色相按本张内容声明执行。'];
115
- for (const kind of new Set(kinds)) {
116
- const domain = c.domains[kind]; if (domain) lines.push(`${kind}:${labels[domain.treatment]};${domain.signature}`);
117
- }
96
+ `色彩饱和度倾向:${labels[c.color.saturation]};色相对比倾向:${labels[c.color.contrast]};阴影偏色:${labels[c.color.shadowShift]}。`,
97
+ '主体身份色、造型、物理材质与实际光源按任务声明执行,不从参考作品继承。'];
118
98
  return lines.join('\n');
119
99
  }
120
100
  export function coreNegative(core) {
121
101
  const r = core.config.render;
122
- return [...(r.texture === 'none' ? ['表面纹理堆砌'] : []), ...(r.shading === 'cel' ? ['平滑明暗过渡', '柔和高光', '写实反射'] : []),
123
- ...(core.config.shape.detail === 'low' ? ['繁复细节', '繁复纹样'] : [])].join(', ');
102
+ return [...(r.brushwork === 'clean' ? ['额外绘画笔触'] : []), ...(r.shading === 'cel' ? ['连续渐变式明暗', '软边高光画法'] : [])].join(', ');
124
103
  }
@@ -0,0 +1,19 @@
1
+ import {statSync} from 'node:fs';
2
+ import {spawn,execFileSync} from 'node:child_process';
3
+
4
+ export function deploymentCommandError(executable,error){
5
+ const missing=error.code==='ENOENT';
6
+ const detail=missing
7
+ ? `找不到部署命令 ${executable}。${executable==='git'?'请安装 Git for Windows 并加入 PATH,然后完全退出并重新启动 Vant。':'请确认该命令已安装并在 Vant 的 PATH 中可用。'}`
8
+ : `部署命令 ${executable} 无法执行(${error.code??error.status??'未知错误'}),请查看部署日志。`;
9
+ return new Error(detail,{cause:error});
10
+ }
11
+ export function checkDeploymentCommand(executable){
12
+ try{execFileSync(executable,['--version'],{windowsHide:true,timeout:10000,stdio:'pipe'});}
13
+ catch(error){throw deploymentCommandError(executable,error);}
14
+ }
15
+ export function spawnDeploymentCommand(executable,args,cwd){
16
+ try{if(!statSync(cwd).isDirectory())throw new Error('不是目录');}
17
+ catch(error){throw new Error(`部署工作目录不可用:${cwd}。请重新检测安装目录。`,{cause:error});}
18
+ return spawn(executable,args,{cwd,windowsHide:true,stdio:['ignore','inherit','inherit']});
19
+ }
@@ -0,0 +1,24 @@
1
+ import {existsSync,mkdirSync,renameSync,rmSync} from 'node:fs';
2
+ import {dirname} from 'node:path';
3
+ import {execFileSync} from 'node:child_process';
4
+ import {ownedPath} from './workspace.mjs';
5
+ import {hash} from './shared.mjs';
6
+ import {deploymentCommandError} from './deployment-process.mjs';
7
+
8
+ export async function ensureDeploymentSource(path,source,{control,command,check}){
9
+ check();
10
+ if(existsSync(path)){
11
+ const git=args=>{try{return execFileSync('git',['-C',path,...args],{encoding:'utf8',windowsHide:true,timeout:10000}).trim();}catch(error){throw deploymentCommandError('git',error);}};
12
+ const current=git(['rev-parse','HEAD']),remote=git(['remote','get-url','origin']).replace(/\.git$/,''),dirty=git(['status','--porcelain','--untracked-files=no']);
13
+ if(current!==source.commit||remote!==source.repository||dirty)throw new Error('现有源码不是干净的固定部署版本,保留用户环境;请另选空目录');return;
14
+ }
15
+ mkdirSync(dirname(path),{recursive:true});
16
+ const staging=ownedPath(control,'staging','source-'+hash(source).slice(0,16));
17
+ // spawn requires its working directory to exist even when Git is installed.
18
+ mkdirSync(dirname(staging),{recursive:true});
19
+ if(existsSync(staging))rmSync(staging,{recursive:true,force:true});
20
+ const network=['-c','http.lowSpeedLimit=1024','-c','http.lowSpeedTime=60'];
21
+ await command('git',[...network,'clone','--filter=blob:none','--no-checkout',source.repository,staging],dirname(staging));
22
+ await command('git',[...network,'-C',staging,'checkout','--detach',source.commit],dirname(staging));
23
+ check();if(existsSync(path))throw new Error('源码目标被其他操作创建,禁止覆盖');renameSync(staging,path);
24
+ }
@@ -0,0 +1,86 @@
1
+ import {environmentRoot,writeMarker} from './environments.mjs';
2
+ import {existsSync,mkdirSync,createReadStream,renameSync,rmSync,readFileSync} from 'node:fs';
3
+ import {join,dirname} from 'node:path';
4
+ import {spawnDeploymentCommand,deploymentCommandError} from './deployment-process.mjs';
5
+ import {ensureDeploymentSource} from './deployment-source.mjs';
6
+ import {createHash} from 'node:crypto';
7
+ import {readJson,writeJson,hash} from './shared.mjs';
8
+ import {loadSettings} from './settings.mjs';
9
+ import {ownedPath} from './workspace.mjs';
10
+ import {locked,sleep,stateRead} from './runtime.mjs';
11
+ import {processIdentity,stopIdentity,ensureService} from './service.mjs';
12
+ import {LOCAL_RECIPE,validateDeploymentPlan} from './deployment.mjs';
13
+ import {loadBackend,BUILTIN_WORKFLOW} from './workflows.mjs';
14
+ import {inspectEnvironment} from './diagnostics.mjs';
15
+ import {generate} from './providers.mjs';
16
+ import {cancelPrompt} from './comfyui.mjs';
17
+ import {finishPlan} from './plan.mjs';
18
+ import {bindBackend} from './backends.mjs';
19
+ import {validateImage} from './images.mjs';
20
+
21
+ const file=process.argv[2],state=readJson(file),plan=state.plan,settings=loadSettings({file:plan.settingsFile});
22
+ const persist=()=>{state.heartbeat=new Date().toISOString();writeJson(file,state);};
23
+ const cancelled=()=>existsSync(file+'.cancel');
24
+ const check=()=>{if(cancelled())throw new Error('部署已取消');};
25
+ const stage=value=>{state.stage=value;persist();check();};
26
+ state.workerPid=process.pid;state.status='running';persist();const heartbeat=setInterval(persist,1000);
27
+ let childIdentity,unsettled=false;
28
+ async function command(executable,args,cwd){
29
+ check();const child=spawnDeploymentCommand(executable,args,cwd);
30
+ const completion=new Promise((resolve,reject)=>{child.once('error',error=>reject(deploymentCommandError(executable,error)));child.once('exit',(code)=>code===0?resolve():reject(new Error('部署命令 '+executable+' 失败,退出码 '+code)));});
31
+ // Attach rejection immediately while awaiting the process identity.
32
+ completion.catch(()=>{});await sleep(100);childIdentity=child.pid?processIdentity(child.pid):null;
33
+ let stopping;
34
+ const timer=setInterval(()=>{if(cancelled()&&childIdentity){clearInterval(timer);stopping=stopIdentity(childIdentity).catch(()=>{unsettled=true;});}},100);
35
+ try{await completion;check();}finally{clearInterval(timer);if(stopping)await stopping;if(childIdentity&&processIdentity(childIdentity.pid)){try{await stopIdentity(childIdentity);}catch{unsettled=true;}}childIdentity=null;}
36
+ }
37
+ async function sha256(path){const digest=createHash('sha256');let bytes=0;for await(const chunk of createReadStream(path)){check();digest.update(chunk);bytes+=chunk.length;state.processedBytes=bytes;}return digest.digest('hex');}
38
+ const repository=(path,source)=>ensureDeploymentSource(path,source,{control:environmentRoot(plan.installRoot),command,check});
39
+
40
+ try{
41
+ validateDeploymentPlan(plan,settings);
42
+ const control=environmentRoot(plan.installRoot),claim=ownedPath(control,'deployment.json');
43
+ await locked(control,'install',async()=>{
44
+ const old=stateRead(claim);if(old&&old.deploymentId!==state.deploymentId&&old.stopConfirmed!==true)throw new Error('该安装目录已有运行或停止未知的部署,禁止重复操作');
45
+ writeJson(claim,{deploymentId:state.deploymentId,workspace:plan.workspace,status:'running',stopConfirmed:false});
46
+ try{
47
+ stage('校验固定源码与节点');await repository(ownedPath(plan.installRoot,'ComfyUI'),LOCAL_RECIPE.comfy);
48
+ await repository(ownedPath(plan.installRoot,'ComfyUI/custom_nodes/ComfyUI-GGUF'),LOCAL_RECIPE.plugin);
49
+ const venvOwner=ownedPath(control,'venv-owned.json'),ownedVenv=stateRead(venvOwner);
50
+ const installPython=!plan.portable&&(!existsSync(plan.python)||ownedVenv?.recipeHash===hash(LOCAL_RECIPE));
51
+ if(installPython){
52
+ if(!existsSync(plan.python)){writeJson(venvOwner,{recipeHash:hash(LOCAL_RECIPE),python:plan.python});stage('创建独立 Python 环境');await command(plan.basePython,['-m','venv',ownedPath(plan.installRoot,'.venv')],plan.installRoot);}
53
+ stage('安装 CUDA 运行依赖');await command(plan.python,['-m','pip','install','torch=='+LOCAL_RECIPE.torch,'torchvision=='+LOCAL_RECIPE.torchvision,'--index-url',LOCAL_RECIPE.torchIndex],plan.installRoot);
54
+ await command(plan.python,['-m','pip','install','-r',ownedPath(plan.installRoot,'ComfyUI/requirements.txt'),'gguf=='+LOCAL_RECIPE.gguf,'sentencepiece','protobuf'],plan.installRoot);
55
+ }
56
+ stage('核验 Python 与 CUDA');await command(plan.python,['-c',`import torch,gguf; import importlib.metadata as m; assert torch.cuda.is_available(), 'NVIDIA CUDA unavailable'; assert torch.__version__.split('+')[0]=='${LOCAL_RECIPE.torch}', 'Torch version differs'; assert m.version('gguf')=='${LOCAL_RECIPE.gguf}', 'GGUF version differs'`],plan.installRoot);
57
+ for(const model of LOCAL_RECIPE.models){
58
+ const destination=ownedPath(plan.installRoot,'ComfyUI/models',model.path);stage('校验模型 '+model.path);state.processedBytes=0;
59
+ if(existsSync(destination)){if(await sha256(destination)!==model.sha256)throw new Error('现有模型哈希不匹配,保留原文件:'+model.path);continue;}
60
+ stage('下载模型 '+model.path);mkdirSync(dirname(destination),{recursive:true});const temporary=ownedPath(control,hash(model.path)+'.part');
61
+ try{await command('curl.exe',['--fail','--location','--retry','2','--connect-timeout','20','--max-time','7200','--output',temporary,model.url],plan.installRoot);if(await sha256(temporary)!==model.sha256)throw new Error('下载模型哈希校验失败');check();if(existsSync(destination))throw new Error('模型目标被其他操作创建,禁止覆盖');renameSync(temporary,destination);}finally{rmSync(temporary,{force:true});}
62
+ }
63
+ const configured={...settings,generation:{defaultBackend:'local-qwen',defaults:{},backends:{'local-qwen':{provider:'comfyui',model:LOCAL_RECIPE.models[0].path.split('/').at(-1),endpoints:[plan.endpoint],launch:{executable:plan.python,cwd:plan.installRoot,args:['-s','ComfyUI/main.py','--disable-dynamic-vram','--lowvram','--disable-auto-launch',...(new URL(plan.endpoint).port?['--port',new URL(plan.endpoint).port]:[])]}}}}};
64
+ stage('检测固定工作流与环境');const backend=loadBackend(configured,'local-qwen'),endpoint=await ensureService(backend,join(control,'runtime'),{cancelled});
65
+ const report=await inspectEnvironment(endpoint,backend);if(!report.ok)throw new Error('部署环境检查未通过');state.environment=report;
66
+ // Readiness is proved by generation and editing, rather than a listening port.
67
+ const {queue_running=[],queue_pending=[]}=await(await fetch(new URL('/queue',endpoint))).json();if(queue_running.length||queue_pending.length)throw new Error('现有服务正在执行其他任务,本次不插入验收采样;任务结束后重试部署验证');
68
+ const output=ownedPath(control,'verification',state.deploymentId);mkdirSync(output,{recursive:true});
69
+ let source;
70
+ for(const mode of ['generate','edit']){
71
+ stage(mode==='generate'?'单图生成验证':'底图编辑验证');
72
+ const base=finishPlan({module:mode,project:'deployment',job:'verification',execution:{model:LOCAL_RECIPE.models[0].path.split('/').at(-1),size:'512*512',perValue:1,promptExtend:false,watermark:false},sources:{recipe:LOCAL_RECIPE.id},snapshots:{},refs:[],items:[{itemId:'verification',variantId:'base',seed:7619,prompt:mode==='generate'?'一个圆润的青绿色科幻能量球,简洁轮廓,柔和高光,纯白背景。':'保持原图轮廓和构图,将主体颜色改成金黄色。',negativeBlock:'文字,水印',imageArgs:mode==='edit'?[source]:[],checks:{content:[],style:[],asset:[]}}]});
73
+ const modeOutput=ownedPath(output,mode);mkdirSync(modeOutput,{recursive:true});
74
+ const bound=bindBackend(base,configured,'local-qwen'),result=await generate(bound,bound.items[0],{endpoint,root:join(control,'runtime'),outputDir:modeOutput,prefix:mode,cancelled,onPrompt:promptId=>{state.promptId=promptId;persist();}});
75
+ state.promptId=null;const path=ownedPath(modeOutput,result.files[0]),info=await validateImage(readFileSync(path));if(info.width!==512||info.height!==512)throw new Error('部署验证图片尺寸不符');source=path;state.verification??=[];state.verification.push({mode,path,hash:await sha256(path),planHash:bound.planHash});persist();
76
+ }
77
+ stage('保存已验证部署配置');for(const evidence of state.verification)if(await sha256(evidence.path)!==evidence.hash)throw new Error('部署采样证据发生变化,不保存完成状态');const raw=readJson(settings.file);raw.generation={...raw.generation,defaultBackend:'local-qwen',backends:{...raw.generation?.backends,'local-qwen':configured.generation.backends['local-qwen']}};writeJson(settings.file,raw);
78
+ writeMarker(plan.installRoot,{python:plan.portable?'python_embeded/python.exe':'.venv/Scripts/python.exe',endpoint:plan.endpoint,recipe:LOCAL_RECIPE.id,verification:'generate-and-edit'});state.status='succeeded';state.stopConfirmed=true;state.workflow=BUILTIN_WORKFLOW;
79
+ }catch(error){
80
+ if(error.unsettled&&!state.promptId)unsettled=true;
81
+ if(state.promptId){try{await cancelPrompt(plan.endpoint,state.promptId);state.promptId=null;}catch{unsettled=true;}}
82
+ state.status=unsettled?'unknown':cancelled()?'cancelled':'failed';state.stopConfirmed=!unsettled;state.error=error.message;
83
+ }finally{writeJson(claim,{deploymentId:state.deploymentId,workspace:plan.workspace,status:state.status,stopConfirmed:state.stopConfirmed});}
84
+ });
85
+ }catch(error){if(error.unsettled)unsettled=true;state.status=unsettled?'unknown':cancelled()?'cancelled':'failed';state.stopConfirmed=!unsettled;state.error=error.message;}
86
+ finally{clearInterval(heartbeat);state.finishedAt=new Date().toISOString();persist();}
@@ -0,0 +1,75 @@
1
+ import {existsSync,openSync,closeSync,statfsSync} from 'node:fs';
2
+ import {join,resolve} from 'node:path';
3
+ import {spawn,execFileSync} from 'node:child_process';
4
+ import {fileURLToPath} from 'node:url';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {hash,readJson,writeJson,keys,id} from './shared.mjs';
7
+ import {externalPath} from './settings.mjs';
8
+ import {ownedPath} from './workspace.mjs';
9
+ import {runtimeRoot,locked,alive} from './runtime.mjs';
10
+ import {checkDeploymentCommand} from './deployment-process.mjs';
11
+
12
+ // This recipe is the tested local installation, not a user-editable workflow.
13
+ export const LOCAL_RECIPE={
14
+ id:'qwen-image-2.1-Q4-cpu-text-v1',
15
+ comfy:{repository:'https://github.com/Comfy-Org/ComfyUI',commit:'b0b743566f65daafc423b4fea8a2fbda94b3384a'},
16
+ plugin:{repository:'https://github.com/leejet/ComfyUI-GGUF',commit:'373048b8403a7820620065210a691263d4da0a61'},
17
+ models:[
18
+ {path:'diffusion_models/qwen-image-2.1-UC-Q4_K_M.gguf',bytes:4_604_558_112,url:'https://huggingface.co/abenzerps/Qwen-Image-2.1-Uncensored-GGUF/resolve/main/qwen-image-2.1-UC-Q4_K_M.gguf',sha256:'e79c8a009f2ecbdb6c70fd663d9aea9ee304a0d91f347e4169a756b8ad141b41'},
19
+ {path:'text_encoders/qwen3vl_8b_int8_convrot.safetensors',bytes:9_350_798_360,url:'https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors',sha256:'8bfd0f6e12abf2d2d697ecc888e5e90b0d6741d6708f05799f53afa560452e8f'},
20
+ {path:'vae/qwen_image_2.1_vae_bf16.safetensors',bytes:675_509_688,url:'https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors',sha256:'bb21f7473051e1ac368515dd3f2e15cd44d7a11748ee8823e1ddca3e4876b7c9'},
21
+ ],
22
+ torch:'2.14.0',torchvision:'0.29.0',torchIndex:'https://download.pytorch.org/whl/cu130',gguf:'0.19.0',
23
+ };
24
+ export function deploymentPlan(settings,{directory,endpoint='http://127.0.0.1:8188/'}={}){
25
+ if(process.platform!=='win32')throw new Error('固定自动部署方案目前仅适配 Windows NVIDIA 环境');
26
+ const target=ownedPath(externalPath(directory,'部署目录')),url=new URL(endpoint);
27
+ 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('部署服务地址必须为本机 HTTP 根地址');
28
+ checkDeploymentCommand('git');
29
+ let gpu;
30
+ try{gpu=execFileSync('nvidia-smi',['--query-gpu=name,memory.total,driver_version','--format=csv,noheader,nounits'],{encoding:'utf8',windowsHide:true,timeout:10000}).trim().split('\n').filter(Boolean).map(line=>{const [name,memoryMiB,driver]=line.split(',').map(value=>value.trim());return {name,memoryMiB:Number(memoryMiB),driver};});if(!gpu.length||gpu.some(device=>!device.name||!Number.isFinite(device.memoryMiB)))throw new Error('GPU 信息无效');}
31
+ catch{throw new Error('固定自动部署需要可检测的 NVIDIA GPU 与驱动,请先安装驱动');}
32
+ const portable=existsSync(ownedPath(target,'python_embeded/python.exe')),venv=ownedPath(target,'.venv/Scripts/python.exe');
33
+ let python=portable?ownedPath(target,'python_embeded/python.exe'):existsSync(venv)?venv:null,basePython=null;
34
+ if(!python){try{basePython=execFileSync('python',['-c','import sys; assert sys.version_info >= (3,12); print(sys.executable)'],{encoding:'utf8',windowsHide:true,timeout:10000}).trim();}catch{throw new Error('自动部署需要已安装的 Python 3.12 或以上;现有便携版可直接复用');}python=venv;}
35
+ const present=LOCAL_RECIPE.models.map(model=>({...model,present:existsSync(ownedPath(target,'ComfyUI/models',model.path))}));
36
+ if(present.some(model=>!model.present))checkDeploymentCommand('curl.exe');
37
+ let ancestor=target;while(!existsSync(ancestor)){const parent=resolve(ancestor,'..');if(parent===ancestor)break;ancestor=parent;}
38
+ const storage=statfsSync(ancestor),available=Number(storage.bavail)*Number(storage.bsize),required=present.filter(model=>!model.present).reduce((sum,model)=>sum+model.bytes,0)+(!portable&&!existsSync(venv)?8_000_000_000:1_000_000_000);
39
+ if(available<required)throw new Error('部署磁盘空间不足,需要至少 '+Math.ceil(required/1e9)+' GB');
40
+ const plan={schema:'art-workshop/deployment-plan',recipe:LOCAL_RECIPE,gpu,installRoot:target,endpoint:url.href,python,basePython,portable,models:present,requiredBytes:required,availableBytes:available,settingsFile:settings.file,workspace:settings.paths.workspace};
41
+ return {...plan,planHash:hash(plan)};
42
+ }
43
+ export function validateDeploymentPlan(plan,settings){
44
+ keys(plan,['schema','recipe','gpu','installRoot','endpoint','python','basePython','portable','models','requiredBytes','availableBytes','settingsFile','workspace','planHash'],'部署预案');
45
+ const {planHash,...body}=plan;if(plan.schema!=='art-workshop/deployment-plan'||hash(body)!==planHash||hash(plan.recipe)!==hash(LOCAL_RECIPE))throw new Error('部署预案或固定方案已变化');
46
+ if(plan.settingsFile!==settings.file||resolve(plan.workspace)!==resolve(settings.paths.workspace))throw new Error('部署预案不属于当前配置与工程');
47
+ const expected=deploymentPlan(settings,{directory:plan.installRoot,endpoint:plan.endpoint});
48
+ for(const key of ['gpu','python','basePython','portable','models'])if(hash(expected[key])!==hash(plan[key]))throw new Error('部署环境已变化,请重新预演');
49
+ return plan;
50
+ }
51
+ export function deploymentStatus(settings,deploymentId){
52
+ const state=readJson(ownedPath(runtimeRoot(settings),'deployments',id(deploymentId)+'.json'));
53
+ if(state.schema!=='art-workshop/deployment'||state.deploymentId!==deploymentId)throw new Error('部署身份不匹配');
54
+ if(!['succeeded','failed','cancelled','unknown'].includes(state.status)&&Date.now()-Date.parse(state.heartbeat??state.createdAt)>10000&&!alive(state.workerPid)){state.status='unknown';state.stopConfirmed=false;state.error='部署工作进程退出;禁止重复启动或清理,先核验原操作';writeJson(ownedPath(runtimeRoot(settings),'deployments',deploymentId+'.json'),state);}
55
+ return state;
56
+ }
57
+ export async function startDeployment(settings,plan,{operationId}={}){
58
+ if(typeof operationId!=='string'||!/^[a-z0-9-]{1,128}$/.test(operationId))throw new Error('部署需要稳定操作身份');
59
+ return locked(runtimeRoot(settings),'deployment',async()=>{
60
+ const {readdirSync}=await import('node:fs'),directory=ownedPath(runtimeRoot(settings),'deployments');
61
+ const previous=existsSync(directory)?readdirSync(directory).filter(file=>file.endsWith('.json')).map(file=>deploymentStatus(settings,file.slice(0,-5))):[];
62
+ const same=previous.find(state=>state.operationId===operationId);if(same){if(same.plan.planHash!==plan.planHash)throw new Error('部署操作身份已用于其他预案');return same;}
63
+ const deploymentId='deploy-'+randomUUID(),file=ownedPath(directory,deploymentId+'.json'),logPath=ownedPath(directory,deploymentId+'.log');
64
+ const state={schema:'art-workshop/deployment',deploymentId,operationId,status:'queued',stopConfirmed:false,createdAt:new Date().toISOString(),plan,logPath};writeJson(file,state);
65
+ // Record rejected requests too: a caller losing an error receipt can recover
66
+ // proof that this operation never started, without repeating the deployment.
67
+ try{validateDeploymentPlan(plan,settings);if(previous.some(state=>state.stopConfirmed!==true))throw new Error('已有部署运行或停止未知,先处理原操作');}
68
+ catch(error){state.status='failed';state.stopConfirmed=true;state.finishedAt=new Date().toISOString();state.error=error.message;writeJson(file,state);throw error;}
69
+ const fd=openSync(logPath,'a'),child=spawn(process.execPath,[fileURLToPath(new URL('./deployment-worker.mjs',import.meta.url)),file],{detached:true,windowsHide:true,stdio:['ignore',fd,fd],env:{...process.env,ART_VISION_KEY:'',DASHSCOPE_API_KEY:''}});closeSync(fd);
70
+ try{await new Promise((resolve,reject)=>{child.once('spawn',resolve);child.once('error',reject);});}catch(error){state.status='failed';state.stopConfirmed=true;state.error='部署进程启动失败';writeJson(file,state);throw error;}
71
+ child.unref();return {deploymentId,status:'queued',stopConfirmed:false};
72
+ });
73
+ }
74
+ export function cancelDeployment(settings,deploymentId){const state=deploymentStatus(settings,deploymentId);if(state.stopConfirmed===true)return state;writeJson(ownedPath(runtimeRoot(settings),'deployments',deploymentId+'.json.cancel'),{requestedAt:new Date().toISOString()});return {deploymentId,status:'cancelling',stopConfirmed:false};}
75
+ export async function recoverDeployment(settings,operationId){const {readdirSync}=await import('node:fs');const directory=ownedPath(runtimeRoot(settings),'deployments');const records=existsSync(directory)?readdirSync(directory).filter(file=>file.endsWith('.json')).map(file=>deploymentStatus(settings,file.slice(0,-5))).filter(state=>state.operationId===operationId):[];if(records.length!==1)throw new Error('没有唯一原部署记录,停止状态未知;禁止重新提交');return records[0];}
package/lib/design.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import {resolveDimensions,DIMENSION_CAPABILITIES} from './dimensions.mjs';
1
2
  import { keys, integer } from './shared.mjs';
2
3
 
3
4
  // 设计基准归资产规格,单体尺寸与倍率归任务;出图尺寸由它们确定。
@@ -11,17 +12,16 @@ export function design(profile, override, explicitExecution = {}) {
11
12
  keys(base.resolution, ['width', 'height'], 'design.resolution');
12
13
  integer(base.resolution.width, 'design.resolution.width', 1, 16384);
13
14
  integer(base.resolution.height, 'design.resolution.height', 1, 16384);
14
- integer(base.outputScale, 'design.outputScale', 1, 4);
15
+ if(!Number.isFinite(base.outputScale)||base.outputScale<1||base.outputScale>4)throw new Error('预留缩放必须在 1 到 4 之间');
15
16
  if (override !== undefined) keys(override, ['width', 'height', 'outputScale'], 'item.design');
16
17
  const size = override === undefined ? base.resolution : override;
17
18
  integer(size.width, 'design.width', 1, base.resolution.width);
18
19
  integer(size.height, 'design.height', 1, base.resolution.height);
19
20
  const outputScale = override?.outputScale ?? base.outputScale;
20
- integer(outputScale, 'design.outputScale', 1, 4);
21
+ if(!Number.isFinite(outputScale)||outputScale<1||outputScale>4)throw new Error('预留缩放必须在 1 到 4 之间');
21
22
  if (explicitExecution.size !== undefined) throw new Error('设计尺寸与任务 execution.size 不能同时指定');
22
- const outputSize = { width: size.width * outputScale, height: size.height * outputScale };
23
- for (const axis of ['width', 'height']) integer(outputSize[axis], `设计换算出图 ${axis}`, 256, 4096);
24
- return { resolution: { ...base.resolution }, size: { width: size.width, height: size.height }, outputScale, outputSize };
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
25
  }
26
26
 
27
27
  export function designPrompt(value) {
@@ -0,0 +1,22 @@
1
+ import {keys,integer} from './shared.mjs';
2
+ export const DIMENSION_CAPABILITIES=Object.freeze({bailian:{min:256,max:4096,step:1,maxArea:4096*4096},comfyui:{min:256,max:4096,step:32,maxArea:4096*4096}});
3
+ /** Exhaustive finite grid; nearest pixel distance, then aspect ratio, then area/width. */
4
+ export function resolveDimensions(requested,capability){
5
+ keys(requested,['width','height'],'requested dimensions');
6
+ for(const axis of ['width','height'])if(!Number.isFinite(requested[axis])||requested[axis]<=0||requested[axis]>65536)throw new Error('请求尺寸超出有效范围');
7
+ const {min,max,step,maxArea,minArea=1}=capability;
8
+ integer(min,'min',1,16384);integer(max,'max',min,16384);integer(step,'step',1,512);integer(maxArea,'maxArea',1,16384*16384);
9
+ let best;
10
+ const ratio=requested.width/requested.height;
11
+ for(let width=Math.ceil(min/step)*step;width<=max;width+=step){
12
+ const upper=Math.min(max,Math.floor(maxArea/width),width/(capability.minRatio??Number.MIN_VALUE)),low=Math.ceil(Math.max(min,minArea/width,width/(capability.maxRatio??Infinity))/step)*step,high=Math.floor(upper/step)*step;if(high<low)continue;
13
+ // Convex pixel-distance objective: only adjacent heights to the requested height can win.
14
+ const nearest=requested.height/step;
15
+ for(const height of new Set([Math.max(low,Math.min(high,Math.floor(nearest)*step)),Math.max(low,Math.min(high,Math.ceil(nearest)*step))])){
16
+ const score=[(width-requested.width)**2+(height-requested.height)**2,Math.abs(width/height-ratio),width*height,width,height];
17
+ if(!best||score.some((v,i)=>v<best.score[i]&&score.slice(0,i).every((p,k)=>p===best.score[k])))best={width,height,score};
18
+ }
19
+ }
20
+ if(!best)throw new Error('后端没有合法分辨率');
21
+ return {requested:{...requested},actual:{width:best.width,height:best.height},clamped:best.width!==requested.width||best.height!==requested.height,capability:{...capability}};
22
+ }
package/lib/edit.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import {taskReferencePrompt} from './task-references.mjs';
2
+ import {readObject,verifyReferences} from './workspace.mjs';
1
3
  import {keys,id,text,texts,integer,hash} from './shared.mjs';
2
4
  import {ROOT,loadProject,loadJob,sourcePath} from './project.mjs';
3
5
  import {loadCore,corePrompt,coreNegative} from './core.mjs';
@@ -6,10 +8,11 @@ import {background} from './presentation.mjs';
6
8
  import {sha256File} from './bl.mjs';
7
9
  const targets=['background','style','shape','color','composition','content','detail','text'];
8
10
  export function compileEdit({projectId,jobId,coreId,root=ROOT,localExecution={}}) {
11
+ const taskRecord=readObject(root,projectId,'task',jobId);const dynamicRefs=verifyReferences(root,taskRecord),referencePrompt=taskReferencePrompt(taskRecord);
9
12
  const project=loadProject(projectId,root),job=loadJob(projectId,jobId,'edit',root);
10
13
  keys(job,['project','kind','core','execution','items'],'edit job');
11
14
  if(coreId&&job.core&&coreId!==job.core) throw new Error('核心与编辑任务绑定冲突');
12
- const selected=coreId??job.core,core=selected?loadCore(projectId,selected,root):null,refs=[],items=[],ids=new Set();
15
+ const selected=coreId??job.core,core=selected?loadCore(projectId,selected,root):null,refs=dynamicRefs.map(r=>({path:r.path,hash:r.hash})),items=[],ids=new Set();
13
16
  if(!Array.isArray(job.items)||!job.items.length) throw new Error('编辑 items 必须非空');
14
17
  for(const source of job.items) {
15
18
  keys(source,['id','source','changes','preserve','mustRead','seed'],'edit item');id(source.id);
@@ -26,7 +29,7 @@ export function compileEdit({projectId,jobId,coreId,root=ROOT,localExecution={}}
26
29
  if([...changed].some(x=>preserved.has(x))) throw new Error('修改与保留范围冲突');
27
30
  if(core&&(changed.has('style')||preserved.has('style'))) throw new Error('绑定核心时,风格由核心负责,不能再声明修改或保留原风格');
28
31
  texts(source.mustRead,'mustRead');const seed=source.seed??parseInt(hash([projectId,jobId,source.id]).slice(0,7),16);integer(seed,'seed');
29
- items.push({itemId:source.id,variantId:'base',seed,brief:source,prompt:`基于输入原图编辑。未声明修改的部分保持原样。\n【修改】\n${changes.join('\n')}\n【保留】\n${preserve.join('\n')}${core?'\n【目标风格核心】\n'+corePrompt(core):''}`,negativeBlock:core?coreNegative(core):'',imageArgs:[path],checks:{content:source.mustRead,style:core?[corePrompt(core)]:['原图风格保持一致'],asset:changes.concat(preserve)}});
32
+ items.push({itemId:source.id,variantId:'base',seed,brief:source,prompt:`基于输入原图编辑。未声明修改的部分保持原样。\n【修改】\n${changes.join('\n')}\n【保留】\n${preserve.join('\n')}${core?'\n【目标风格核心】\n'+corePrompt(core):''}${referencePrompt}`,negativeBlock:core?coreNegative(core):'',imageArgs:[path],checks:{content:source.mustRead,style:core?[corePrompt(core)]:['原图风格保持一致'],asset:changes.concat(preserve)}});
30
33
  }
31
- return finishPlan({module:'edit',project:projectId,job:jobId,execution:execution(project,job.execution,localExecution),sources:{core:core?.id??null,coreHash:core?.coreHash??null,selection:selected?'编辑显式绑定':'保留原图'},snapshots:{project,core,job},refs,items});
34
+ return finishPlan({module:'edit',project:projectId,job:jobId,execution:execution(project,job.execution,localExecution),sources:{taskRevision:taskRecord.revision,taskConfigHash:hash(taskRecord.config),core:core?.id??null,coreHash:core?.coreHash??null,selection:selected?'编辑显式绑定':'保留原图'},snapshots:{project,core,job},refs,items});
32
35
  }