@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
@@ -0,0 +1,154 @@
1
+ import {existsSync,mkdirSync,readdirSync,cpSync,rmSync} from 'node:fs';
2
+ import {join,dirname,relative,resolve} from 'node:path';
3
+ import {randomUUID} from 'node:crypto';
4
+ import {id,readJson,writeJson,hash,renameWithRetry} from './shared.mjs';
5
+ import {createHash} from 'node:crypto';
6
+ import {externalPath} from './settings.mjs';
7
+ import {readFileSync} from 'node:fs';
8
+ import {locked,tasks,runtimeRoot,alive,taskFile} from './runtime.mjs';
9
+ import {taskStatus} from './tasks.mjs';
10
+ import {assertIdle} from './lifecycle.mjs';
11
+ import {ownedPath,STYLE_CATEGORIES,TASK_PURPOSES} from './workspace.mjs';
12
+ import {validateImage} from './images.mjs';
13
+ import {checkRun} from './executor.mjs';
14
+
15
+ /** Preflight old executions and synchronous manifests without modifying evidence. */
16
+ async function legacyRuns(settings,projectId){
17
+ const result=new Map(),oldRoot=join(dirname(settings.file),'.runtime',hash(settings.file).slice(0,12));
18
+ for(const run of tasks(oldRoot).filter(run=>(run.plan?.project??run.project)===projectId)){
19
+ if(alive(run.workerPid)||!['succeeded','failed','cancelled'].includes(run.status)||run.promptId||run.unsettled||run.remoteCancellation)throw new Error('旧工程存在运行或停止未知的执行,必须先核验原运行');
20
+ if(!run.finishedAt)throw new Error('旧执行缺少停止证据,不能推断完成');
21
+ result.set(run.taskId,{...run,stopConfirmed:true,root:runtimeRoot(settings),migration:{source:taskFile(oldRoot,run.taskId)}});
22
+ }
23
+ const manifests=[];
24
+ const scan=directory=>{if(!existsSync(directory))return;for(const entry of readdirSync(directory,{withFileTypes:true})){const path=ownedPath(settings.paths.output,directory,entry.name);if(entry.isDirectory())scan(path);else if(entry.name==='manifest.json')manifests.push(path);}};
25
+ scan(settings.paths.output);
26
+ for(const path of manifests){const manifest=readJson(path);if(manifest.schema!=='art-workshop/run'||manifest.plan?.project!==projectId)continue;
27
+ if(!manifest.finishedAt)throw new Error('历史批次缺少完成证据:'+manifest.runId);
28
+ const rows=checkRun(manifest,path);for(const row of rows.filter(row=>row.generated)){if(!row.integrity)throw new Error('历史候选完整性失败:'+row.file);await validateImage(readFileSync(row.path));}
29
+ const runId=manifest.taskId??('task-legacy-'+hash({path,runId:manifest.runId}).slice(0,24));id(runId);
30
+ const existing=result.get(runId);if(existing&&existing.plan?.planHash!==manifest.planHash)throw new Error('旧批次运行身份冲突');
31
+ result.set(runId,{...(existing??{}),schema:'art-workshop/task',taskId:runId,status:manifest.summary?.failed?'failed':'succeeded',stopConfirmed:true,createdAt:manifest.startedAt,finishedAt:manifest.finishedAt,plan:manifest.plan,items:manifest.plan.items,manifestPath:path,root:runtimeRoot(settings),outputRoot:settings.paths.output,migration:{...existing?.migration,manifestRunId:manifest.runId,review:manifest.review??[]}});
32
+ }
33
+ return [...result.values()];
34
+ }
35
+
36
+ /** Explicit one-time upgrade. Readers never fall back to legacy documents. */
37
+ export async function upgradeProject(root,projectId,{dry=true,referenceAssignments={},settings}={}){
38
+ if(!dry&&!settings)throw new Error('升级必须提供执行配置以检查运行占用');
39
+ const upgrade=async()=>{
40
+ id(projectId);
41
+ const journal=ownedPath(root,'.runtime/upgrades',projectId+'.json');
42
+ if(existsSync(journal)){
43
+ if(dry)throw new Error('升级事务未完成,请先显式执行 project upgrade 恢复原工程');
44
+ const transaction=readJson(journal),source=ownedPath(root,'projects',projectId);
45
+ if(transaction.schema!=='art-workshop/upgrade'||transaction.project!==projectId)throw new Error('升级事务身份不匹配');
46
+ const backup=ownedPath(root,'backups',transaction.backup),staging=ownedPath(root,'projects',transaction.staging);
47
+ if(existsSync(backup)){
48
+ for(const run of transaction.createdRuns){const file=taskFile(runtimeRoot(settings),run.taskId);if(existsSync(file)){if(hash(readJson(file))!==run.hash)throw new Error('升级后的执行记录被修改,不能自动回滚');rmSync(file,{force:true});}}
49
+ if(existsSync(source)){if(readJson(join(source,'project.json')).schemaVersion!==2)throw new Error('升级目标被修改,不能自动回滚');rmSync(source,{recursive:true,force:true});}
50
+ renameWithRetry(backup,source);
51
+ }
52
+ if(existsSync(staging))rmSync(staging,{recursive:true,force:true});
53
+ rmSync(journal,{force:true});
54
+ }
55
+ if(settings)assertIdle(tasks(runtimeRoot(settings)).filter(t=>t.plan?.project===projectId||t.project===projectId).map(t=>taskStatus(runtimeRoot(settings),t.taskId)),'工程');
56
+ id(projectId);const source=ownedPath(root,'projects',projectId),project=readJson(ownedPath(source,'project.json'));
57
+ if(project.schemaVersion===2)return {project:projectId,current:true,changes:[]};
58
+ const runs=settings?await legacyRuns(settings,projectId):[];
59
+ const jobs=existsSync(ownedPath(source,'jobs'))?readdirSync(ownedPath(source,'jobs')).filter(f=>f.endsWith('.json')):[];
60
+ const cores=existsSync(ownedPath(source,'cores'))?readdirSync(ownedPath(source,'cores')).filter(f=>f.endsWith('.json')):[];
61
+ for(const file of jobs){const config=readJson(ownedPath(source,'jobs',file));if(config.kind==='edit')for(const item of config.items??[]){if(!item.source)throw new Error('旧编辑任务缺少底图:'+file);await validateImage(readFileSync(externalPath(resolve(root,item.source),'旧编辑底图')));}}
62
+ const approvedByRun=new Map(),groups=new Map(),selected=new Set();
63
+ for(const run of runs){
64
+ const manifest=run.manifestPath?readJson(run.manifestPath):null;
65
+ const approved=manifest?checkRun(manifest,run.manifestPath).filter(row=>row.integrity&&row.generated&&(run.migration.review??[]).some(review=>review.itemId===row.itemId&&review.variantId===row.variantId&&review.file===row.file&&['content','style','asset'].every(key=>review[key]==='pass'))):[];
66
+ approvedByRun.set(run.taskId,approved);
67
+ for(const row of approved){const key=run.plan.job+'/'+row.itemId,entry={runId:run.taskId,row};groups.set(key,[...(groups.get(key)??[]),entry]);}
68
+ }
69
+ for(const [key,entries] of groups){
70
+ const mapping=referenceAssignments.selections?.find(selection=>selection.task+'/'+selection.assetId===key);
71
+ const choice=mapping?entries.find(entry=>entry.runId===mapping.runId&&entry.row.file===mapping.file&&entry.row.variantId===mapping.variantId):entries.length===1?entries[0]:null;
72
+ if(!choice)throw new Error('同一资产存在多份旧采用记录,需在 selections 映射中明确 runId/file/variantId:'+key);
73
+ selected.add(hash({runId:choice.runId,assetId:choice.row.itemId,variantId:choice.row.variantId,file:choice.row.file}));
74
+ }
75
+ const refs=project.refsDir;
76
+ if(refs&&!referenceAssignments.confirmed)throw new Error('旧项目共享 refs 必须先明确归属映射,禁止猜测升级');
77
+ const result={project:projectId,current:false,runs:runs.map(run=>({id:run.taskId,job:run.plan?.job,status:run.status})),changes:[...jobs.map(f=>'jobs/'+f+' → tasks/'+f.slice(0,-5)+'/task.json'),...cores.map(f=>'cores/'+f+' → styles/'+f.slice(0,-5)+'/core.json')],dry};
78
+ if(refs){
79
+ const assignments=referenceAssignments.references;if(!Array.isArray(assignments))throw new Error('参考映射必须包含 references 列表');
80
+ const importRoot=externalPath(join(root,refs),'旧参考目录'),images=[];
81
+ const scan=dir=>{for(const entry of readdirSync(dir,{withFileTypes:true})){const file=ownedPath(importRoot,dir,entry.name);if(entry.isDirectory())scan(file);else if(/\.(png|jpe?g|webp)$/i.test(entry.name))images.push(file);}};
82
+ if(existsSync(importRoot))scan(importRoot);
83
+ for(const file of images)if(!assignments.some(a=>ownedPath(importRoot,a.path)===file))throw new Error('参考未明确映射:'+file);
84
+ for(const assignment of assignments){
85
+ if(!['style','task'].includes(assignment.kind))throw new Error('映射对象类型非法');id(assignment.id);
86
+ if(assignment.kind==='style'&&!STYLE_CATEGORIES.includes(assignment.category))throw new Error('风格映射分类非法');
87
+ if(assignment.kind==='task'&&(!assignment.purposes?.length||assignment.purposes.some(p=>!TASK_PURPOSES.includes(p))))throw new Error('任务映射用途非法');
88
+ const existing=ownedPath(source,assignment.kind==='style'?'styles':'tasks',assignment.id,assignment.kind+'.json');
89
+ const legacy=ownedPath(source,assignment.kind==='style'?'cores':'jobs',assignment.id+'.json');
90
+ if(!existsSync(existing)&&!existsSync(legacy))throw new Error('映射目标不存在:'+assignment.id);
91
+ await validateImage(readFileSync(ownedPath(importRoot,assignment.path)));
92
+ }
93
+ }
94
+ if(dry)return result;
95
+ // No symlink is allowed in a managed conversion tree.
96
+ const check=directory=>{for(const name of readdirSync(directory,{withFileTypes:true})){const path=ownedPath(directory,name.name);if(name.isDirectory())check(path);}};check(source);
97
+ const staging=ownedPath(root,'projects',projectId+'-upgrade-'+randomUUID()),backup=ownedPath(root,'backups',projectId+'-'+randomUUID());
98
+ cpSync(source,staging,{recursive:true,errorOnExist:true,force:false});
99
+ try{
100
+ for(const file of jobs){
101
+ const objectId=file.slice(0,-5);id(objectId);const config=readJson(join(staging,'jobs',file));
102
+ if(config.kind==='edit')for(const item of config.items??[]){
103
+ if(!item.source)throw new Error('旧编辑任务缺少底图,不能丢弃配置:'+objectId);
104
+ const input=externalPath(resolve(root,item.source),'旧编辑底图'),buffer=readFileSync(input);await validateImage(buffer);
105
+ const extension=input.slice(input.lastIndexOf('.')).toLowerCase();if(!['.png','.jpg','.jpeg','.webp'].includes(extension))throw new Error('旧编辑底图格式非法');
106
+ const name=randomUUID()+extension,target=ownedPath(staging,'tasks',objectId,'sources',name);mkdirSync(dirname(target),{recursive:true});cpSync(input,target,{errorOnExist:true,force:false});
107
+ item.source=relative(root,ownedPath(source,'tasks',objectId,'sources',name)).replaceAll('\\','/');
108
+ }
109
+ writeJson(join(staging,'tasks',objectId,'task.json'),{schema:'art-workshop/task',schemaVersion:2,project:projectId,id:objectId,name:objectId,revision:1,status:'draft',createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),source:null,config,references:[],report:null});
110
+ }
111
+ for(const file of cores){const objectId=file.slice(0,-5);id(objectId);const core=readJson(join(staging,'cores',file));const {coreHash,...body}=core;if(hash(body)!==coreHash||core.project!==projectId||core.id!==objectId)throw new Error('旧冻结核心完整性失败');writeJson(join(staging,'styles',objectId,'core.json'),core);writeJson(join(staging,'styles',objectId,'style.json'),{schema:'art-workshop/style',schemaVersion:2,project:projectId,id:objectId,name:objectId,revision:1,status:'frozen',coreHash,createdAt:core.approvedAt,updatedAt:core.approvedAt,source:null,config:core.config,references:[],report:{data:core.report,sourceRevision:1,path:null,runId:null,sourceHash:null}});}
112
+ for(const run of runs){
113
+ const file=ownedPath(staging,'tasks',run.plan?.job,'task.json');if(!existsSync(file))throw new Error('历史运行没有对应任务,不能丢弃:'+run.taskId);
114
+ const record=readJson(file),approved=approvedByRun.get(run.taskId);
115
+ for(const row of approved){const candidateId=hash({runId:run.taskId,assetId:row.itemId,variantId:row.variantId,file:row.file}),selection={assetId:row.itemId,runId:run.taskId,candidateId,path:row.path,hash:createHash('sha256').update(readFileSync(row.path)).digest('hex'),taskConfigHash:hash(record.config),actor:'legacy-upgrade',createdAt:run.finishedAt,revision:1};
116
+ if(selected.has(candidateId)){record.finalizations??=[];record.finalizations.push(selection);}else{record.finalizationHistory??=[];record.finalizationHistory.push({...selection,supersededByMigration:true});}
117
+ }
118
+ writeJson(file,record);
119
+ const destination=taskFile(runtimeRoot(settings),run.taskId);if(existsSync(destination)&&hash(readJson(destination))!==hash(run))throw new Error('目标执行记录冲突,保留原工程');
120
+ }
121
+ delete project.refsDir;project.schemaVersion=2;project.revision=1;writeJson(join(staging,'project.json'),project);
122
+ // Reject unresolved external refs rather than silently drop their associations.
123
+ if(refs){
124
+ const assignments=referenceAssignments.references;
125
+ if(!Array.isArray(assignments))throw new Error('参考映射必须包含 references 列表');
126
+ const importRoot=externalPath(join(root,refs),'旧参考目录');
127
+ const images=[];const scan=dir=>{for(const entry of readdirSync(dir,{withFileTypes:true})){const path=ownedPath(importRoot,dir,entry.name);if(entry.isDirectory())scan(path);else if(/\.(png|jpe?g|webp)$/i.test(entry.name))images.push(path);}};if(existsSync(importRoot))scan(importRoot);
128
+ for(const path of images)if(!assignments.some(a=>ownedPath(importRoot,a.path)===path))throw new Error('参考未明确映射:'+path);
129
+ for(const assignment of assignments){
130
+ if(!['style','task'].includes(assignment.kind))throw new Error('映射对象类型非法');id(assignment.id);
131
+ if(assignment.kind==='style'&&!STYLE_CATEGORIES.includes(assignment.category))throw new Error('风格映射分类非法');
132
+ if(assignment.kind==='task'&&(!assignment.purposes?.length||assignment.purposes.some(p=>!TASK_PURPOSES.includes(p))))throw new Error('任务映射用途非法');
133
+ const objectDir=ownedPath(staging,assignment.kind==='style'?'styles':'tasks',assignment.id),file=ownedPath(objectDir,assignment.kind+'.json');
134
+ const record=readJson(file),input=ownedPath(importRoot,assignment.path),buffer=readFileSync(input),refId='ref-'+randomUUID();
135
+ const extension=input.slice(input.lastIndexOf('.')).toLowerCase();if(!['.png','.jpg','.jpeg','.webp'].includes(extension))throw new Error('参考格式非法');
136
+ const target=['refs',...(assignment.kind==='style'?[assignment.category]:[]),refId+extension].join('/');
137
+ const destination=ownedPath(objectDir,target);mkdirSync(join(destination,'..'),{recursive:true});
138
+ cpSync(input,destination,{recursive:false,force:false});
139
+ record.references.push({id:refId,path:target,hash:createHash('sha256').update(buffer).digest('hex'),source:input,category:assignment.category??null,purposes:assignment.purposes??[],usage:'understand',note:assignment.note??'',ignore:assignment.ignore??''});writeJson(file,record);
140
+ }
141
+ }
142
+ for(const dir of ['jobs','cores'])rmSync(ownedPath(staging,dir),{recursive:true,force:true});
143
+ const createdRuns=runs.filter(run=>!existsSync(taskFile(runtimeRoot(settings),run.taskId))).map(run=>({taskId:run.taskId,hash:hash(run)}));
144
+ writeJson(journal,{schema:'art-workshop/upgrade',project:projectId,backup:relative(join(root,'backups'),backup),staging:relative(join(root,'projects'),staging),createdRuns});
145
+ mkdirSync(join(root,'backups'),{recursive:true});renameWithRetry(source,backup);
146
+ const created=[];
147
+ try{renameWithRetry(staging,source);for(const run of runs){const file=taskFile(runtimeRoot(settings),run.taskId);if(!existsSync(file)){created.push(file);writeJson(file,run);}}}
148
+ catch(error){for(const file of created)rmSync(file,{force:true});if(existsSync(source))rmSync(ownedPath(root,source),{recursive:true,force:true});renameWithRetry(backup,source);rmSync(journal,{force:true});throw error;}
149
+ rmSync(journal,{force:true});
150
+ return {...result,backup};
151
+ }finally{if(existsSync(staging))rmSync(ownedPath(root,'projects',staging),{recursive:true,force:true});}
152
+ };
153
+ return dry?upgrade():locked(runtimeRoot(settings),'control',upgrade);
154
+ }
@@ -0,0 +1,288 @@
1
+ // Explicit tool contracts: model names alone never choose a fallback API.
2
+ const common = {
3
+ api: "dashscope",
4
+ inputPolicy: {
5
+ maxBytes: 10 * 1024 * 1024,
6
+ formats: ["jpeg", "png", "webp", "bmp", "tiff", "gif"],
7
+ },
8
+ input: ["text", "image"],
9
+ output: ["image"],
10
+ transport: {
11
+ adapter: "dashscope",
12
+ version: 1,
13
+ timeoutMilliseconds: 1800000,
14
+ mode: "sync",
15
+ path: "/api/v1/services/aigc/multimodal-generation/generation",
16
+ },
17
+ fields: {
18
+ promptExtend: {
19
+ type: "boolean",
20
+ default: false,
21
+ wire: "prompt_extend",
22
+ cli: "--prompt-extend",
23
+ },
24
+ watermark: {
25
+ type: "boolean",
26
+ default: false,
27
+ wire: "watermark",
28
+ cli: "--watermark",
29
+ },
30
+ },
31
+ modes: ["generate", "edit"],
32
+ maxCount: 4,
33
+ maxSeed: 2147483647,
34
+ };
35
+ const qwen = {
36
+ ...common,
37
+ maxImages: 3,
38
+ maxNegativeCharacters: 500,
39
+ dimensions: {
40
+ min: 256,
41
+ max: 4096,
42
+ step: 1,
43
+ minArea: 512 ** 2,
44
+ maxArea: 2048 ** 2,
45
+ },
46
+ };
47
+ const cancellation = "取消仅停止本地等待;远端停止未确认时保留执行记录";
48
+ const qwenNotes = [
49
+ "支持文生图与底图编辑;编辑最多 3 张输入图",
50
+ "总像素 512²–2048²;每项 1–4 张(工具当前上限)",
51
+ "负向提示词最多 500 字符;支持提示词扩写、seed 与水印",
52
+ ];
53
+ const profiles = [
54
+ {
55
+ ...qwen,
56
+ id: "dashscope-qwen-image-3.0-v1",
57
+ models: ["qwen-image-3.0", "qwen-image-3.0-pro"],
58
+ notes: [...qwenNotes, cancellation],
59
+ source:
60
+ "https://help.aliyun.com/zh/model-studio/qwen-image-generation-and-editing-api-reference",
61
+ },
62
+ {
63
+ ...qwen,
64
+ id: "dashscope-qwen-image-2.0-v1",
65
+ models: [
66
+ "qwen-image-2.0",
67
+ "qwen-image-2.0-pro",
68
+ "qwen-image-2.0-2026-03-03",
69
+ "qwen-image-2.0-pro-2026-03-03",
70
+ "qwen-image-2.0-pro-2026-04-22",
71
+ "qwen-image-2.0-pro-2026-06-22",
72
+ ],
73
+ editDimensions: { step: 16 },
74
+ notes: [
75
+ ...qwenNotes,
76
+ "编辑尺寸按 16 像素对齐;正向提示词上限 1300 Token,由服务端计算",
77
+ cancellation,
78
+ ],
79
+ source: "https://help.aliyun.com/zh/model-studio/qwen-image-edit-api",
80
+ },
81
+ {
82
+ ...common,
83
+ id: "dashscope-wan2.6-t2i-v1",
84
+ models: ["wan2.6-t2i"],
85
+ input: ["text"],
86
+ transport: {
87
+ adapter: "dashscope",
88
+ version: 1,
89
+ mode: "async",
90
+ path: "/api/v1/services/aigc/image-generation/generation",
91
+ },
92
+ modes: ["generate"],
93
+ maxImages: 0,
94
+ maxPromptCharacters: 2000,
95
+ maxNegativeCharacters: 500,
96
+ dimensions: {
97
+ min: 256,
98
+ max: 4096,
99
+ step: 16,
100
+ minArea: 1280 ** 2,
101
+ maxArea: 1440 ** 2,
102
+ minRatio: 1 / 4,
103
+ maxRatio: 4,
104
+ },
105
+ notes: [
106
+ "仅文生图,不接收输入图;编辑请选择 wan2.6-image",
107
+ "总像素 1280²–1440²;比例 1:4–4:1;工具按 16 像素对齐",
108
+ "正向词最多 2000 字符,负向词最多 500 字符;每项 1–4 张",
109
+ "异步提交并轮询原任务;不自动重提",
110
+ cancellation,
111
+ ],
112
+ source:
113
+ "https://help.aliyun.com/zh/model-studio/text-to-image-v2-api-reference",
114
+ },
115
+ {
116
+ ...common,
117
+ id: "dashscope-wan2.6-image-v1",
118
+ models: ["wan2.6-image"],
119
+ modes: ["edit"],
120
+ maxImages: 4,
121
+ inputPolicy: {
122
+ maxBytes: 10 * 1024 * 1024,
123
+ formats: ["jpeg", "png", "webp", "bmp"],
124
+ minAxis: 240,
125
+ maxAxis: 8000,
126
+ alpha: false,
127
+ },
128
+ maxPromptCharacters: 2000,
129
+ maxNegativeCharacters: 500,
130
+ dimensions: {
131
+ min: 256,
132
+ max: 4096,
133
+ step: 16,
134
+ minArea: 768 ** 2,
135
+ maxArea: 2048 ** 2,
136
+ minRatio: 1 / 4,
137
+ maxRatio: 4,
138
+ },
139
+ notes: [
140
+ "仅图像编辑,必须提供 1–4 张底图;不开放流式图文混排",
141
+ "总像素 768²–2048²;比例 1:4–4:1;工具按 16 像素对齐",
142
+ "正向词最多 2000 字符,负向词最多 500 字符;每项 1–4 张",
143
+ cancellation,
144
+ ],
145
+ source:
146
+ "https://help.aliyun.com/zh/model-studio/wan-image-generation-api-reference",
147
+ },
148
+ ...[false, true].map((pro) => ({
149
+ ...common,
150
+ id: `dashscope-wan2.7-image${pro ? "-pro" : ""}-v1`,
151
+ models: [`wan2.7-image${pro ? "-pro" : ""}`],
152
+ maxImages: 9,
153
+ inputPolicy: {
154
+ maxBytes: 20 * 1024 * 1024,
155
+ formats: ["jpeg", "png", "webp", "bmp"],
156
+ minAxis: 240,
157
+ maxAxis: 8000,
158
+ minRatio: 1 / 8,
159
+ maxRatio: 8,
160
+ alpha: false,
161
+ },
162
+ maxPromptCharacters: 5000,
163
+ negativeInPrompt: true,
164
+ fields: { watermark: common.fields.watermark },
165
+ dimensions: {
166
+ min: 256,
167
+ max: 4096,
168
+ step: 1,
169
+ minArea: 768 ** 2,
170
+ maxArea: (pro ? 4096 : 2048) ** 2,
171
+ minRatio: 1 / 8,
172
+ maxRatio: 8,
173
+ },
174
+ editDimensions: { maxArea: 2048 ** 2 },
175
+ notes: [
176
+ "支持文生图与编辑;编辑最多 9 张输入图",
177
+ pro
178
+ ? "纯文生图总像素 768²–4096²;带图生成和编辑最高 2048²"
179
+ : "总像素 768²–2048²",
180
+ "宽高比 1:8–8:1;单边 256–4096(工具范围);每项 1–4 张",
181
+ "负向约束会标明并入主提示词;合并后最多 5000 字符;不支持提示词扩写开关",
182
+ "当前不开放组图、框选编辑与调色板;沿用服务端默认思考模式;输出尺寸可能有微小差异",
183
+ cancellation,
184
+ ],
185
+ source:
186
+ "https://help.aliyun.com/zh/model-studio/wan-image-generation-and-editing-api-reference",
187
+ })),
188
+ ];
189
+ const recorded = [
190
+ {
191
+ models: [
192
+ "qwen-image",
193
+ "qwen-image-max",
194
+ "qwen-image-max-2025-12-30",
195
+ "qwen-image-plus",
196
+ "qwen-image-plus-2026-01-09",
197
+ ],
198
+ modes: ["generate"],
199
+ reason: "早期 Qwen 图片生成模型,仅登记;固定尺寸与独立调用规格尚未接入",
200
+ notes: [
201
+ "仅文生图;使用旧版固定分辨率及输出数量规范,不复用 Qwen 2/3 的自由尺寸",
202
+ ],
203
+ source: "https://help.aliyun.com/zh/model-studio/image-model/",
204
+ },
205
+ {
206
+ models: [
207
+ "qwen-image-edit",
208
+ "qwen-image-edit-max",
209
+ "qwen-image-edit-max-2026-01-16",
210
+ "qwen-image-edit-plus",
211
+ "qwen-image-edit-plus-2025-12-15",
212
+ "qwen-image-edit-plus-2025-10-30",
213
+ ],
214
+ modes: ["edit"],
215
+ reason: "早期 Qwen 编辑模型,仅登记;旧版尺寸与输出数量规范尚未接入",
216
+ notes: ["仅编辑;不同版本输出数量与分辨率不同,不能按 Qwen 2/3 参数提交"],
217
+ source: "https://help.aliyun.com/zh/model-studio/image-model/",
218
+ },
219
+ {
220
+ models: [
221
+ "wan2.5-t2i-preview",
222
+ "wan2.2-t2i-plus",
223
+ "wan2.2-t2i-flash",
224
+ "wanx2.1-t2i-plus",
225
+ "wanx2.1-t2i-turbo",
226
+ "wan2.1-t2i-plus",
227
+ "wan2.1-t2i-turbo",
228
+ "wanx2.0-t2i-turbo",
229
+ ],
230
+ modes: ["generate"],
231
+ reason: "早期万相文生图模型,仅登记;旧版异步接口与尺寸规范尚未接入",
232
+ notes: [
233
+ "2.5 为像素面积与比例限制;2.2 及更早为单边尺寸限制;不能套用 2.6/2.7 参数",
234
+ ],
235
+ source:
236
+ "https://help.aliyun.com/zh/model-studio/text-to-image-v2-api-reference",
237
+ },
238
+ {
239
+ models: ["wan2.5-i2i-preview"],
240
+ modes: ["edit"],
241
+ reason: "早期万相 2.5 编辑模型,仅登记;独立输入结构与尺寸规范尚未接入",
242
+ notes: ["使用 input.images 与旧版图编辑接口,不套用多模态 messages 请求"],
243
+ source:
244
+ "https://help.aliyun.com/zh/model-studio/wan2-5-image-edit-api-reference",
245
+ },
246
+ {
247
+ models: ["wanx2.1-imageedit"],
248
+ modes: ["edit"],
249
+ reason: "专用图像编辑模型,仅登记;需要 function、底图及功能专属参数",
250
+ notes: ["换背景、扩图、超分等功能参数不同;当前通用任务未提供对应配置"],
251
+ source:
252
+ "https://help.aliyun.com/zh/model-studio/wanx-image-edit-api-reference",
253
+ },
254
+ {
255
+ models: ["wanx-v1"],
256
+ modes: ["generate"],
257
+ reason: "早期万相 V1 模型,仅登记;旧版风格及参考图工作流尚未接入",
258
+ notes: ["使用旧版异步接口,风格与参考图语义不同"],
259
+ source:
260
+ "https://help.aliyun.com/zh/model-studio/text-to-image-api-reference",
261
+ },
262
+ {
263
+ models: ["wanx-sketch-to-image-lite"],
264
+ modes: ["edit"],
265
+ reason: "涂鸦专用模型,仅登记;需要线稿输入与专属控制参数",
266
+ notes: ["通用编辑底图不能替代线稿角色与控制参数"],
267
+ source:
268
+ "https://help.aliyun.com/zh/model-studio/wanx-sketch-to-image-api-reference",
269
+ },
270
+ {
271
+ models: ["wanx-x-painting"],
272
+ modes: ["edit"],
273
+ reason: "局部重绘专用模型,仅登记;需要独立蒙版与底图",
274
+ notes: ["需要 mask_image_url 和 base_image_url;当前任务没有蒙版工作流"],
275
+ source: "https://help.aliyun.com/zh/model-studio/vary-region-api-reference",
276
+ },
277
+ ];
278
+
279
+ export const modelDefinitions = [
280
+ ...profiles.map((p) => ({ ...p, supported: true })),
281
+ ...recorded.map((p) => ({
282
+ ...p,
283
+ api: "dashscope",
284
+ input: p.modes.includes("edit") ? ["text", "image"] : ["text"],
285
+ output: ["image"],
286
+ supported: false,
287
+ })),
288
+ ];
@@ -0,0 +1,234 @@
1
+ import { hash } from "./shared.mjs";
2
+ import { modelDefinitions } from "./model-catalog.mjs";
3
+ const modes = new Set(["generate", "edit"]);
4
+ /** Boot-time validation prevents incomplete declarations from silently relaxing limits. */
5
+ export function createModelRegistry(definitions) {
6
+ const index = new Map(),
7
+ entries = structuredClone(definitions);
8
+ for (const entry of entries) {
9
+ const allowed = new Set([
10
+ "id",
11
+ "api",
12
+ "input",
13
+ "output",
14
+ "inputPolicy",
15
+ "transport",
16
+ "fields",
17
+ "models",
18
+ "modes",
19
+ "maxImages",
20
+ "maxCount",
21
+ "maxSeed",
22
+ "maxNegativeCharacters",
23
+ "maxPromptCharacters",
24
+ "dimensions",
25
+ "editDimensions",
26
+ "negativeInPrompt",
27
+ "notes",
28
+ "source",
29
+ "supported",
30
+ "reason",
31
+ "registered",
32
+ "status",
33
+ ]);
34
+ if (Object.keys(entry).some((key) => !allowed.has(key)))
35
+ throw new Error("模型声明包含未知字段");
36
+ if (
37
+ !entry.api ||
38
+ !Array.isArray(entry.models) ||
39
+ !entry.models.length ||
40
+ !entry.modes?.length ||
41
+ entry.modes.some((mode) => !modes.has(mode)) ||
42
+ !Array.isArray(entry.input) ||
43
+ !Array.isArray(entry.output) ||
44
+ !Array.isArray(entry.notes) ||
45
+ !entry.source
46
+ )
47
+ throw new Error("模型声明缺少必要字段");
48
+ if (entry.supported) {
49
+ if (
50
+ !entry.id ||
51
+ !entry.transport?.adapter ||
52
+ !Number.isSafeInteger(entry.transport.version) ||
53
+ entry.transport.version < 1 ||
54
+ typeof entry.transport.mode !== "string" ||
55
+ (entry.transport.path &&
56
+ (!entry.transport.path.startsWith("/") ||
57
+ entry.transport.path.startsWith("//")))
58
+ )
59
+ throw new Error("模型协议声明无效");
60
+ for (const field of ["maxCount", "maxSeed", "maxImages"])
61
+ if (
62
+ !Number.isSafeInteger(entry[field]) ||
63
+ entry[field] < (field === "maxCount" ? 1 : 0)
64
+ )
65
+ throw new Error("模型限制无效:" + field);
66
+ const d = entry.dimensions;
67
+ if (
68
+ !d ||
69
+ !["min", "max", "step", "minArea", "maxArea"].every(
70
+ (key) => Number.isSafeInteger(d[key]) && d[key] > 0,
71
+ ) ||
72
+ d.min > d.max ||
73
+ d.minArea > d.maxArea
74
+ )
75
+ throw new Error("模型尺寸声明无效");
76
+ if (
77
+ entry.maxImages > 0 &&
78
+ (!Number.isSafeInteger(entry.inputPolicy?.maxBytes) ||
79
+ entry.inputPolicy.maxBytes <= 0 ||
80
+ !entry.inputPolicy.formats?.length)
81
+ )
82
+ throw new Error("输入图片限制声明无效");
83
+ if (
84
+ d.minRatio !== undefined &&
85
+ (!(d.minRatio > 0) || !(d.maxRatio >= d.minRatio))
86
+ )
87
+ throw new Error("模型比例声明无效");
88
+ const wires = new Set(["size", "n", "seed", "negative_prompt"]);
89
+ for (const [key, rule] of Object.entries(entry.fields ?? {})) {
90
+ if (
91
+ !["boolean", "integer", "string"].includes(rule.type) ||
92
+ !/^[a-z][a-z0-9_]*$/.test(rule.wire ?? "") ||
93
+ !key ||
94
+ wires.has(rule.wire)
95
+ )
96
+ throw new Error("模型参数声明无效或协议字段重复");
97
+ wires.add(rule.wire);
98
+ if (
99
+ rule.default !== undefined &&
100
+ (rule.type === "integer"
101
+ ? !Number.isSafeInteger(rule.default) ||
102
+ rule.default < (rule.min ?? -Infinity) ||
103
+ rule.default > (rule.max ?? Infinity)
104
+ : typeof rule.default !== rule.type)
105
+ )
106
+ throw new Error("模型参数默认值无效");
107
+ if (
108
+ rule.enum &&
109
+ (!Array.isArray(rule.enum) ||
110
+ !rule.enum.length ||
111
+ (rule.default !== undefined && !rule.enum.includes(rule.default)))
112
+ )
113
+ throw new Error("模型参数枚举无效");
114
+ }
115
+ } else if (!entry.reason) throw new Error("未接入型号必须声明原因");
116
+ for (const model of entry.models) {
117
+ const key = entry.api + ":" + model;
118
+ if (typeof model !== "string" || !model || index.has(key))
119
+ throw new Error("重复或无效的模型标识:" + model);
120
+ index.set(key, entry);
121
+ }
122
+ }
123
+ const resolve = (api, model, mode = "generate", hasImages = false) => {
124
+ const value = index.get(api + ":" + model);
125
+ if (!value)
126
+ return {
127
+ supported: false,
128
+ registered: false,
129
+ reason: "该协议下的模型尚未适配参数与调用流程",
130
+ };
131
+ const result = structuredClone(value);
132
+ if (result.supported && (mode === "edit" || hasImages))
133
+ Object.assign(result.dimensions, result.editDimensions);
134
+ return {
135
+ ...result,
136
+ registered: true,
137
+ status: result.supported ? "adapted" : "recorded",
138
+ };
139
+ };
140
+ return Object.freeze({
141
+ resolve,
142
+ catalog: () =>
143
+ entries.map((entry) => ({
144
+ ...structuredClone(entry),
145
+ registered: true,
146
+ status: entry.supported ? "adapted" : "recorded",
147
+ })),
148
+ });
149
+ }
150
+ export const modelRegistry = createModelRegistry(modelDefinitions);
151
+ export const resolveModel = (...args) => modelRegistry.resolve(...args);
152
+ export const modelCatalog = () => modelRegistry.catalog();
153
+ export function executionContract(spec) {
154
+ const {
155
+ models,
156
+ notes,
157
+ source,
158
+ reason,
159
+ registered,
160
+ status,
161
+ supported,
162
+ ...execution
163
+ } = spec;
164
+ return {
165
+ schema: "art/model-contract-v1",
166
+ ...execution,
167
+ fields: Object.fromEntries(
168
+ Object.entries(execution.fields ?? {}).map(([key, { cli, ...rule }]) => [
169
+ key,
170
+ rule,
171
+ ]),
172
+ ),
173
+ };
174
+ }
175
+ export const contractHash = (spec) => hash(executionContract(spec));
176
+ /** Shared by UI selection and execution configuration; no credential values required. */
177
+ export function modelEligibility(
178
+ {
179
+ providerEnabled = true,
180
+ available,
181
+ enabled,
182
+ credential,
183
+ capabilitySource,
184
+ input = [],
185
+ output = [],
186
+ protocol,
187
+ protocolError = "",
188
+ model,
189
+ },
190
+ registry = modelRegistry,
191
+ ) {
192
+ const profile = protocol ? registry.resolve(protocol, model) : null;
193
+ const image =
194
+ output.includes("image") ||
195
+ (capabilitySource === "unknown" && profile?.supported);
196
+ const reason = !providerEnabled
197
+ ? "实例未启用"
198
+ : !available
199
+ ? "目录中不可用"
200
+ : !enabled
201
+ ? "模型未启用"
202
+ : !credential
203
+ ? "尚未保存凭据"
204
+ : protocolError ||
205
+ (!protocol
206
+ ? "请配置图片生成接口"
207
+ : profile?.registered && !profile.supported
208
+ ? profile.reason
209
+ : capabilitySource === "unknown" && !profile?.supported
210
+ ? "能力待确认"
211
+ : !image
212
+ ? "不支持图片输出"
213
+ : !profile?.supported
214
+ ? profile?.reason
215
+ : "");
216
+ return {
217
+ generation: !reason,
218
+ generationReason: reason || "",
219
+ vision: !!(
220
+ available &&
221
+ enabled &&
222
+ credential &&
223
+ capabilitySource !== "unknown" &&
224
+ input.includes("image") &&
225
+ output.includes("text")
226
+ ),
227
+ imageCandidate: !!(
228
+ output.includes("image") ||
229
+ capabilitySource === "unknown" ||
230
+ profile?.registered
231
+ ),
232
+ compatibility: profile,
233
+ };
234
+ }