@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,67 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {existsSync,readFileSync,readdirSync,realpathSync,statSync,createReadStream} from 'node:fs';
3
+ import {homedir} from 'node:os';
4
+ import {join,resolve,dirname} from 'node:path';
5
+ import {hash,writeJson} from './shared.mjs';
6
+ import {loadBackend,BUILTIN_WORKFLOW} from './workflows.mjs';
7
+ import {inspectEnvironment} from './diagnostics.mjs';
8
+ import {LOCAL_RECIPE} from './deployment.mjs';
9
+ import {ensureService,externalIdentity} from './service.mjs';
10
+ export const MARKER='vant.art.config.json';
11
+ export const globalHome=()=>resolve(process.env.VANT_HOME??join(homedir(),'.vant'));
12
+ export const defaultInstallRoot=()=>join(globalHome(),'art-env');
13
+ export function environmentRoot(root){const canonical=existsSync(root)?realpathSync(root):resolve(root);return join(globalHome(),'state','art-environments',hash(process.platform==='win32'?canonical.toLowerCase():canonical));}
14
+ export function readMarker(root){
15
+ const file=join(root,MARKER);if(!existsSync(file))return null;
16
+ const value=JSON.parse(readFileSync(file,'utf8'));
17
+ let endpoint;try{endpoint=new URL(value.endpoint);}catch{throw new Error('环境标记缺少合法服务地址');}
18
+ if(endpoint.protocol!=='http:'||!['127.0.0.1','localhost'].includes(endpoint.hostname)||endpoint.pathname!=='/'||endpoint.search||endpoint.hash||endpoint.username||endpoint.password)throw new Error('环境标记只允许本机 HTTP 根地址');
19
+ if(value.schema!=='vant/art-environment-v1'||value.comfy!=='ComfyUI'||!['python_embeded/python.exe','.venv/Scripts/python.exe'].includes(value.python))throw new Error('美术环境标记无效:'+file);
20
+ return value;
21
+ }
22
+ export function writeMarker(root,{python,endpoint,recipe,verification='capabilities'}){
23
+ const value={schema:'vant/art-environment-v1',environmentId:hash(realpathSync(root).toLowerCase()),comfy:'ComfyUI',python,endpoint,workflow:BUILTIN_WORKFLOW,recipe,verification,verifiedAt:new Date().toISOString()};
24
+ writeJson(join(root,MARKER),value);
25
+ writeJson(join(environmentRoot(root),'environment.json'),{root:realpathSync(root),...value});return value;
26
+ }
27
+ export function backendFor(root,endpoint){
28
+ const python=existsSync(join(root,'python_embeded/python.exe'))?'python_embeded/python.exe':'.venv/Scripts/python.exe';
29
+ return {python,backend:loadBackend({file:join(root,'vant.art.config.json'),generation:{backends:{local:{provider:'comfyui',model:'qwen-image-2.1-UC-Q4_K_M.gguf',endpoints:[endpoint],launch:{executable:join(root,python),cwd:root,args:['-s','ComfyUI/main.py','--disable-dynamic-vram','--lowvram','--disable-auto-launch','--port',new URL(endpoint).port||'80']}}}}},'local')};
30
+ }
31
+ export async function inspectInstallation(root,endpoint){
32
+ root=resolve(root);let marker=null,markerError;try{marker=readMarker(root);}catch(e){markerError=e.message;}
33
+ const {python,backend}=backendFor(root,endpoint),missing=[];
34
+ if(!existsSync(join(root,python)))missing.push('Python 环境');
35
+ if(!existsSync(join(root,'ComfyUI/main.py')))missing.push('ComfyUI');
36
+ if(!existsSync(join(root,'ComfyUI/custom_nodes/ComfyUI-GGUF')))missing.push('ComfyUI-GGUF 节点');
37
+ for(const model of LOCAL_RECIPE.models){const file=join(root,'ComfyUI/models',model.path);if(!existsSync(file)||statSync(file).size!==model.bytes)missing.push(model.path+'(缺失或大小不符)');}
38
+ let service;try{service=await inspectEnvironment(endpoint,backend);if(service.ok){const edited=loadBackend({file:join(root,MARKER),generation:{backends:{local:{provider:'comfyui',model:backend.model,endpoints:[endpoint]}}}},'local','edit');const editReport=await inspectEnvironment(endpoint,edited);if(!editReport.ok)service=editReport;}}catch{}
39
+ let conflict;
40
+ if(service?.ok===true&&process.platform==='win32'&&!externalIdentity(endpoint,backend.launch))conflict='指定端口属于另一套环境';
41
+ if(marker?.endpoint&&marker.endpoint!==endpoint){try{const previous=await inspectEnvironment(marker.endpoint,backend);if(previous.ok)conflict='此环境已在 '+marker.endpoint+' 运行,请使用原端口或先关闭原服务';}catch{}}
42
+ const models=LOCAL_RECIPE.models.map(model=>({path:model.path,bytes:model.bytes,present:existsSync(join(root,'ComfyUI/models',model.path))&&statSync(join(root,'ComfyUI/models',model.path)).size===model.bytes}));
43
+ return {models,conflict,root,endpoint,managed:!!marker,markerError,python,missing,service,reusable:!markerError&&!missing.length,live:service?.ok===true};
44
+ }
45
+ export function discoverInstallations(){
46
+ const found=new Set(),index=join(globalHome(),'state','art-environments');
47
+ if(existsSync(index))for(const entry of readdirSync(index,{withFileTypes:true})){const file=join(index,entry.name,'environment.json');if(entry.isDirectory()&&existsSync(file)){try{const record=JSON.parse(readFileSync(file,'utf8'));if(typeof record.root==='string'&&existsSync(record.root))found.add(realpathSync(record.root));}catch{}}}
48
+ let budget=1500;
49
+ const scan=(root,depth)=>{if(--budget<0||!existsSync(root))return;try{if(existsSync(join(root,MARKER))||existsSync(join(root,'ComfyUI/main.py'))) {found.add(realpathSync(root));return;}if(depth===0)return;for(const entry of readdirSync(root,{withFileTypes:true})){if(entry.isDirectory()&&!entry.isSymbolicLink()&&!['node_modules','.git','AppData','Windows','models','python_embeded'].includes(entry.name))scan(join(root,entry.name),depth-1);}}catch{}};
50
+ for(const root of [join(globalHome(),'art-env'),join(homedir(),'AI'),...(process.platform==='win32'?['C:/AI','D:/AI','E:/AI']:[])])scan(root,3);
51
+ return [...found];
52
+ }
53
+ export async function adoptInstallation(root,endpoint,{cancelled=()=>false,onStage=()=>{}}={}){
54
+ const report=await inspectInstallation(root,endpoint);if(!report.reusable)throw new Error('现有环境需要补齐:'+report.missing.join('、'));
55
+ for(const model of LOCAL_RECIPE.models){
56
+ onStage('校验已有模型 '+model.path);const digest=createHash('sha256');
57
+ for await(const chunk of createReadStream(join(report.root,'ComfyUI/models',model.path))){if(cancelled())throw new Error('接入已取消');digest.update(chunk);}
58
+ if(digest.digest('hex')!==model.sha256)throw new Error('模型校验失败,保留原文件:'+model.path);
59
+ }
60
+ onStage('核验服务与工作流能力');
61
+ const {backend,python}=backendFor(report.root,endpoint);
62
+ if(report.live&&process.platform==='win32'&&!externalIdentity(endpoint,backend.launch))throw new Error('端口由其他环境占用,不能将其登记到指定目录');
63
+ await ensureService(backend,join(environmentRoot(report.root),'runtime'),{cancelled});
64
+ const current=await inspectInstallation(report.root,endpoint);if(!current.live)throw new Error('现有环境工作流能力检测未通过');
65
+ if(cancelled())throw new Error('接入已取消');
66
+ writeMarker(report.root,{python,endpoint,verification:'capabilities'});return current;
67
+ }
@@ -0,0 +1,156 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFile, writeFile, mkdir, link, rm } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import sharp from "sharp";
5
+ import { hash } from "../shared.mjs";
6
+ import { boundedBody, RemoteError } from "../transport/http.mjs";
7
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8
+ async function download(receipt, context) {
9
+ if (!context.outputDir) return { urls: receipt.urls };
10
+ if (!/^[a-zA-Z0-9_.-]+$/.test(context.prefix))
11
+ throw new Error("产物前缀无效");
12
+ await mkdir(context.outputDir, { recursive: true });
13
+ const files = [];
14
+ for (const [index, url] of receipt.urls.entries()) {
15
+ if (context.cancelled?.()) throw new Error("本地下载已取消,上游已完成");
16
+ // A pre-signed download receives no model credential, including on redirects.
17
+ const controller = new AbortController(),
18
+ timeout = setTimeout(() => controller.abort(), 60000),
19
+ timer = setInterval(() => {
20
+ if (context.cancelled?.()) controller.abort();
21
+ }, 100);
22
+ let buffer;
23
+ try {
24
+ const response = await (context.transport ?? fetch)(url, {
25
+ redirect: "follow",
26
+ signal: controller.signal,
27
+ });
28
+ if (!response.ok)
29
+ throw new Error("图片下载失败(HTTP " + response.status + ")");
30
+ buffer = await boundedBody(response, 64 * 1024 * 1024);
31
+ } finally {
32
+ clearTimeout(timeout);
33
+ clearInterval(timer);
34
+ }
35
+ const info = await sharp(buffer, {
36
+ limitInputPixels: 64 * 1024 * 1024,
37
+ }).metadata();
38
+ if (!["png", "jpeg", "webp"].includes(info.format))
39
+ throw new Error("生成产物不是可支持的图片格式");
40
+ const file =
41
+ context.prefix +
42
+ (index ? "--" + (index + 1) : "") +
43
+ "." +
44
+ (info.format === "jpeg" ? "jpg" : info.format),
45
+ path = join(context.outputDir, file);
46
+ const temporary = path + ".tmp-" + randomUUID();
47
+ try {
48
+ await writeFile(temporary, buffer, { flag: "wx" });
49
+ try {
50
+ await link(temporary, path);
51
+ } catch (error) {
52
+ if (
53
+ error.code !== "EEXIST" ||
54
+ hash(await readFile(path)) !== hash(buffer)
55
+ )
56
+ throw error;
57
+ }
58
+ } finally {
59
+ await rm(temporary, { force: true });
60
+ }
61
+ files.push(file);
62
+ }
63
+ return { files, urls: receipt.urls };
64
+ }
65
+ /** Provider-neutral lifecycle. Persist each transition before polling or downloading. */
66
+ export async function executeRemote(request, adapter, context = {}) {
67
+ const cancelled = context.cancelled ?? (() => false),
68
+ requestHash = hash(request);
69
+ let receipt = context.receipt,
70
+ baseUrl = context.baseUrl?.replace(/\/$/, "") ?? receipt?.baseUrl;
71
+ const persist = async (value) => {
72
+ receipt = { ...receipt, ...value };
73
+ await context.onReceipt?.(structuredClone(receipt));
74
+ };
75
+ if (request.transport.version !== adapter.version)
76
+ throw new Error("图片协议执行版本已变化,请重新预演");
77
+ if (
78
+ receipt &&
79
+ (receipt.requestHash !== requestHash ||
80
+ receipt.adapter !== adapter.id ||
81
+ receipt.adapterVersion !== adapter.version ||
82
+ receipt.baseUrl !== baseUrl)
83
+ )
84
+ throw new Error("上游任务与当前请求身份不一致;禁止重新提交");
85
+ if (receipt?.state === "dispatching")
86
+ throw new RemoteError("上次提交结果未知;禁止重复提交", {
87
+ unsettled: true,
88
+ });
89
+ try {
90
+ if (!receipt) {
91
+ if (cancelled()) throw new Error("任务已取消,尚未提交");
92
+ const prepared = await adapter.prepare(request, { ...context, baseUrl });
93
+ baseUrl = prepared.endpoint ?? baseUrl;
94
+ if (typeof baseUrl !== "string" || !baseUrl)
95
+ throw new Error("协议适配器未提供执行地址");
96
+ if (cancelled()) throw new Error("任务已取消,尚未提交");
97
+ await persist({
98
+ schema: "art/remote-receipt-v1",
99
+ adapter: adapter.id,
100
+ adapterVersion: adapter.version,
101
+ requestHash,
102
+ baseUrl,
103
+ state: "dispatching",
104
+ submittedAt: new Date().toISOString(),
105
+ });
106
+ if (cancelled()) {
107
+ await persist({ state: "cancelled", message: "请求尚未发出,已取消" });
108
+ throw new RemoteError("请求尚未发出,已取消", {
109
+ code: "upstream_cancelled",
110
+ });
111
+ }
112
+ const submitted = await adapter.submit(request, {
113
+ ...context,
114
+ baseUrl,
115
+ prepared,
116
+ });
117
+ await persist(submitted);
118
+ }
119
+ while (receipt.state === "accepted") {
120
+ if (cancelled())
121
+ throw new RemoteError("本地等待已停止,上游停止未确认", {
122
+ unsettled: true,
123
+ });
124
+ const next = await adapter.query(receipt, { ...context, baseUrl });
125
+ await persist(next);
126
+ if (receipt.state === "accepted")
127
+ await pause(context.pollMilliseconds ?? 500);
128
+ }
129
+ if (receipt.state === "failed" || receipt.state === "cancelled")
130
+ throw new RemoteError(receipt.message ?? "上游执行未成功", {
131
+ code:
132
+ receipt.state === "cancelled"
133
+ ? "upstream_cancelled"
134
+ : "upstream_failed",
135
+ });
136
+ if (
137
+ receipt.state !== "completed" ||
138
+ !Array.isArray(receipt.urls) ||
139
+ !receipt.urls.length
140
+ )
141
+ throw new RemoteError("协议适配器返回无效完成结果", { unsettled: true });
142
+ if (receipt.urls.length !== request.count)
143
+ throw new RemoteError("上游产物数量与冻结请求不同");
144
+ return await download(receipt, context);
145
+ } catch (error) {
146
+ if (receipt?.state === "dispatching" && !error.unsettled)
147
+ await persist({ state: "failed", message: error.message });
148
+ if (receipt?.state === "accepted" || receipt?.state === "dispatching") {
149
+ error.unsettled = true;
150
+ context.onRemoteCancel?.();
151
+ }
152
+ // A completed upstream job stays settled even if downloading its result fails.
153
+ if (receipt?.state === "completed") error.unsettled = false;
154
+ throw error;
155
+ }
156
+ }
package/lib/executor.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import {compileRemoteRequest} from './generation-policy.mjs';
2
+ import {adapters} from './adapters/index.mjs';
1
3
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from 'node:fs';
2
4
  import { join, dirname, resolve, relative, isAbsolute } from 'node:path';
3
5
  import { randomUUID } from 'node:crypto';
@@ -6,14 +8,17 @@ import { hash, writeJson } from './shared.mjs';
6
8
  export { validatePlan } from './plan.mjs';
7
9
  export { writeJson } from './shared.mjs';
8
10
  import { runBl, sha256File, resolveBlEntry } from './bl.mjs';
11
+ import {ownedPath} from './workspace.mjs';
9
12
  import {loadSettings,externalPath} from './settings.mjs';
13
+ import {assertExecutableStyle} from './style-contract.mjs';
10
14
 
11
15
  function runtimeVersion() {
12
16
  try { return JSON.parse(readFileSync(join(dirname(dirname(resolveBlEntry())), 'package.json'), 'utf8')).version ?? 'unknown'; }
13
17
  catch { return 'unknown'; }
14
18
  }
15
- export function executePlan(plan, items, { outputRoot=loadSettings().paths.output, dry = false, runner = runBl, log = console.log } = {}) {
19
+ export function executePlan(plan, items, { outputRoot=loadSettings().paths.output, dry = false, runner, log = console.log } = {}) {
16
20
  validatePlan(plan);
21
+ assertExecutableStyle(plan);
17
22
  if (!items.length) throw new Error('没有选中任何计划项');
18
23
  for (const item of items) {
19
24
  const expected = plan.items.find(x => x.inputHash === item.inputHash);
@@ -23,15 +28,16 @@ export function executePlan(plan, items, { outputRoot=loadSettings().paths.outpu
23
28
  externalPath(outputRoot,'输出目录');
24
29
  if (dry) {
25
30
  const requests = items.map(item => ({ ...(item.design?{design:item.design,execution:item.execution}:{}),itemId: item.itemId, variantId: item.variantId, seed: item.seed,
26
- inputHash: item.inputHash, args: buildArgs(plan, item, join(outputRoot,'<runId>'), `${item.itemId}--${item.variantId}`) }));
31
+ inputHash: item.inputHash, ...(plan.backend?.provider!=='comfyui'?(()=>{const request=item.request??compileRemoteRequest(plan,item);return {request,wireRequest:adapters.get(request.adapter).preview?.(request)};})():{}), args: buildArgs(plan, item, join(outputRoot,'<runId>'), `${item.itemId}--${item.variantId}`) }));
27
32
  log(JSON.stringify({ dry: true, remoteCalls: 0, planHash: plan.planHash, requests }, null, 2));
28
33
  return { dry: true, requests };
29
34
  }
35
+ if(!runner)throw new Error('真实执行必须使用受管 task 生命周期;executePlan 仅用于预演或注入测试');
30
36
  const runId = `${plan.job.replaceAll('/', '-')}-${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID().slice(0, 8)}`;
31
37
  const runDir = join(outputRoot, runId);
32
38
  mkdirSync(runDir, { recursive: true });
33
39
  const manifest = { schema: 'art-workshop/run', runId, plan, planHash: plan.planHash, blVersion: runner === runBl ? runtimeVersion() : 'injected',
34
- startedAt: new Date().toISOString(), items: [], review: [], selections: {} };
40
+ startedAt: new Date().toISOString(), items: [] };
35
41
  const manifestPath = join(runDir, 'manifest.json');
36
42
  const persist = () => {
37
43
  manifest.summary = { completed: manifest.items.filter(x => x.status !== 'running').length, expected: items.length,
@@ -77,10 +83,10 @@ export function outputPath(manifestPath, file) {
77
83
  const path = resolve(base, file);
78
84
  const rel = relative(base, path);
79
85
  if (isAbsolute(rel) || rel === '..' || rel.startsWith('..\\') || rel.startsWith('../')) throw new Error('输出路径越界');
80
- return path;
86
+ return ownedPath(base,file);
81
87
  }
82
88
 
83
- export function checkRun(manifest, manifestPath, review = manifest.review ?? []) {
89
+ export function checkRun(manifest, manifestPath) {
84
90
  validatePlan(manifest.plan);
85
91
  for (const item of manifest.items) {
86
92
  const expected = manifest.plan.items.find(x => x.itemId === item.itemId && x.variantId === item.variantId);
@@ -89,28 +95,10 @@ export function checkRun(manifest, manifestPath, review = manifest.review ?? [])
89
95
  if (hash({value:item[key]}) !== hash({value:expected[key]})) throw new Error(`执行记录已改变:${item.itemId}.${key}`);
90
96
  }
91
97
  }
92
- if (!Array.isArray(review)) throw new Error('review 必须为数组');
93
- const keys = new Set();
94
- for (const row of review) {
95
- // check 导出的失败记录也可保留在人工模板中,但不能被批准。
96
- if (row.file === null && manifest.items.some(i => i.itemId === row.itemId && i.variantId === row.variantId && !i.files.length && !i.ok)) {
97
- if (row.accepted === true) throw new Error('无产物的失败项不能通过验收');
98
- continue;
99
- }
100
- const key = `${row.itemId}/${row.variantId}/${row.file}`;
101
- if (keys.has(key)) throw new Error(`重复 review:${key}`);
102
- keys.add(key);
103
- if (!manifest.items.some(i => i.itemId === row.itemId && i.variantId === row.variantId && i.files.includes(row.file))) throw new Error(`review 未匹配产物:${key}`);
104
- for (const dimension of ['content', 'style', 'asset']) {
105
- if (!['pass', 'fail', 'pending'].includes(row[dimension])) throw new Error(`review.${dimension} 必须为 pass/fail/pending`);
106
- }
107
- }
108
98
  return manifest.items.flatMap(item => item.files.length ? item.files.map(file => {
109
99
  const path = outputPath(manifestPath, file);
110
100
  const integrity = existsSync(path) && sha256File(path) === item.outputHashes[file];
111
- const row = review.find(r => r.itemId === item.itemId && r.variantId === item.variantId && r.file === file);
112
101
  return { itemId: item.itemId, variantId: item.variantId, file, path, integrity, generated: item.ok,
113
- checks: item.checks, content: row?.content ?? 'pending', style: row?.style ?? 'pending', asset: row?.asset ?? 'pending',
114
- reason: row?.reason ?? '', accepted: integrity && item.ok && ['content', 'style', 'asset'].every(k => row?.[k] === 'pass') };
102
+ checks: item.checks, accepted: integrity && item.ok && !!manifest.finishedAt && !item.deleted };
115
103
  }) : [{ itemId: item.itemId, variantId: item.variantId, file: null, generated: false, accepted: false, error: item.error }]);
116
104
  }
package/lib/generate.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import {taskReferencePrompt} from './task-references.mjs';
2
+ import {readObject,verifyReferences} from './workspace.mjs';
1
3
  import { readJson, keys, id, text, texts, integer, hash } from './shared.mjs';
2
4
  import { ROOT,loadProject,loadJob,projectPath } from './project.mjs';
3
5
  import {selectCore,corePrompt,coreNegative} from './core.mjs';
@@ -5,12 +7,14 @@ import {execution,finishPlan} from './plan.mjs';
5
7
  import {presentation,assetPrompt} from './presentation.mjs';
6
8
  import {design,designPrompt} from './design.mjs';
7
9
  export function compileGenerate({projectId,jobId,coreId,root=ROOT,localExecution={}}) {
10
+ const taskRecord=readObject(root,projectId,'task',jobId);const dynamicRefs=verifyReferences(root,taskRecord),referencePrompt=taskReferencePrompt(taskRecord);
8
11
  const project=loadProject(projectId,root),job=loadJob(projectId,jobId,'generate',root);
9
- keys(job,['project','kind','core','profile','execution','items'],'job');
12
+ keys(job,['project','kind','core','profile','asset','execution','items'],'job');
10
13
  const selected=selectCore(project,job,coreId,root),core=selected.core;
11
- const profile=readJson(projectPath(root,projectId,'profiles',job.profile));
14
+ if(Boolean(job.asset)===Boolean(job.profile))throw new Error('任务必须指定一份内联资产规格或一个资产规格模板');
15
+ const profile=job.asset??readJson(projectPath(root,projectId,'profiles',job.profile));
12
16
  keys(profile,['project','id','name','constraints','defaults','allowedOverrides','presets','checks','design'],'profile');
13
- if(profile.project!==projectId||profile.id!==job.profile) throw new Error('资产配置工程身份不匹配');
17
+ if(profile.project!==projectId||job.profile&&profile.id!==job.profile) throw new Error('资产配置工程身份不匹配');
14
18
  keys(profile.constraints,['text','frame','scene','crop','shadow'],'constraints');
15
19
  for(const v of Object.values(profile.constraints)) if(typeof v!=='boolean') throw new Error('资产约束必须为布尔值');
16
20
  texts(profile.checks,'profile.checks');
@@ -26,7 +30,6 @@ export function compileGenerate({projectId,jobId,coreId,root=ROOT,localExecution
26
30
  for(const e of source.entities) {
27
31
  keys(e,['id','kind','appearance','color','role','count','action'],'entity'); id(e.id); id(e.kind);
28
32
  if(objectIds.has(e.id)) throw new Error('实体 ID 重复'); objectIds.add(e.id);
29
- if(!core.config.domains[e.kind]) throw new Error(`核心缺少题材规则 ${e.kind}`);
30
33
  if(!['primary','support'].includes(e.role)) throw new Error('实体角色不合法');
31
34
  integer(e.count,'count',1,100); text(e.appearance,'appearance');text(e.color,'color'); if(e.action) text(e.action,'action');
32
35
  lines.push(`${e.id}:${e.count} 个${e.appearance},${e.color},${e.role==='primary'?'主要':'辅助'}实体${e.action?','+e.action:''}。`);
@@ -44,8 +47,8 @@ export function compileGenerate({projectId,jobId,coreId,root=ROOT,localExecution
44
47
  const p=presentation(profile,{...source.composition,...variant.composition},d);
45
48
  if(!objectIds.has(p.value.focalTarget)) throw new Error('视觉焦点不存在');
46
49
  const seed=variant.seed??source.seed??parseInt(hash([projectId,jobId,source.id]).slice(0,7),16); integer(seed,'seed');
47
- items.push({...(d?{design:d,execution:execution(project,{...job.execution,size:`${d.outputSize.width}*${d.outputSize.height}`},localExecution)}:{}),itemId:source.id,variantId:variant.id,seed,brief:{...source,composition:p.value},prompt:`【风格核心】\n${corePrompt(core,source.entities.map(e=>e.kind))}\n【真实需求】\n${source.intent}。\n${lines.join('\n')}\n视觉焦点:${p.value.focalTarget}。\n【构图与资产】\n${p.prompt}\n${d ? designPrompt(d) : ""}\n${assetPrompt(profile)}`,negativeBlock:[coreNegative(core),profile.constraints.text?'':'文字, 字母, 水印',profile.constraints.frame?'':'装饰外框'].filter(Boolean).join(', '),imageArgs:[],checks:{content:source.mustRead,style:[corePrompt(core,source.entities.map(e=>e.kind))],asset:[...profile.checks,p.background]}});
50
+ items.push({...(d?{design:d,execution:execution(project,{...job.execution,size:`${d.outputSize.width}*${d.outputSize.height}`},localExecution)}:{}),itemId:source.id,variantId:variant.id,seed,brief:{...source,composition:p.value},prompt:`【风格核心】\n${corePrompt(core)}\n【真实需求】\n${source.intent}。\n${lines.join('\n')}\n视觉焦点:${p.value.focalTarget}。\n【构图与资产】\n${p.prompt}\n${d ? designPrompt(d) : ""}\n${assetPrompt(profile)}${referencePrompt}`,negativeBlock:[coreNegative(core),profile.constraints.text?'':'文字, 字母, 水印',profile.constraints.frame?'':'装饰外框'].filter(Boolean).join(', '),imageArgs:[],checks:{content:source.mustRead,style:[corePrompt(core)],asset:[...profile.checks,p.background]}});
48
51
  }
49
52
  }
50
- return finishPlan({module:'generate',project:projectId,job:jobId,execution:execution(project,job.execution,localExecution),sources:{core:core.id,coreHash:core.coreHash,selection:selected.source},snapshots:{project,core,profile,job},refs:[],items});
53
+ return finishPlan({module:'generate',project:projectId,job:jobId,execution:execution(project,job.execution,localExecution),sources:{taskRevision:taskRecord.revision,taskConfigHash:hash(taskRecord.config),core:core.id,coreHash:core.coreHash,selection:selected.source},snapshots:{project,core,profile,job},refs:dynamicRefs.map(r=>({path:r.path,hash:r.hash})),items});
51
54
  }
@@ -0,0 +1,198 @@
1
+ import { hash } from "./shared.mjs";
2
+ import {
3
+ resolveModel,
4
+ contractHash,
5
+ modelRegistry,
6
+ } from "./model-registry.mjs";
7
+ export function remotePrompt(item, compatibility) {
8
+ return compatibility.negativeInPrompt && item.negativeBlock
9
+ ? item.prompt +
10
+ "\n\n必须避免以下内容(由负向约束并入主提示词):\n" +
11
+ item.negativeBlock
12
+ : item.prompt;
13
+ }
14
+ export function validateRemotePlan(plan, registry = modelRegistry) {
15
+ const model = plan.backend?.model ?? plan.execution.model;
16
+ const compatibility = registry.resolve(
17
+ plan.backend?.credentialReference?.api ?? "dashscope",
18
+ model,
19
+ plan.module,
20
+ );
21
+ if (!compatibility.supported)
22
+ throw new Error(model + ":" + compatibility.reason);
23
+ if (!compatibility.modes.includes(plan.module))
24
+ throw new Error(
25
+ model +
26
+ " 不支持当前任务类型(支持:" +
27
+ compatibility.modes
28
+ .map((mode) => (mode === "generate" ? "生成" : "编辑"))
29
+ .join(" / ") +
30
+ ")",
31
+ );
32
+ for (const item of plan.items) {
33
+ const e = item.execution ?? plan.execution;
34
+ if (e.model !== model) throw new Error("计划执行模型与适配模型不一致");
35
+ const [w, h] = String(e.size).split("*").map(Number),
36
+ d = registry.resolve(
37
+ compatibility.api,
38
+ model,
39
+ plan.module,
40
+ !!item.imageArgs?.length,
41
+ ).dimensions;
42
+ if (
43
+ !Number.isInteger(w) ||
44
+ !Number.isInteger(h) ||
45
+ w < d.min ||
46
+ h < d.min ||
47
+ w > d.max ||
48
+ h > d.max ||
49
+ w % d.step ||
50
+ h % d.step ||
51
+ w * h < d.minArea ||
52
+ w * h > d.maxArea ||
53
+ w / h < (d.minRatio ?? 0) ||
54
+ w / h > (d.maxRatio ?? Infinity)
55
+ )
56
+ throw new Error(model + " 分辨率超出适配范围,请重新编译预案");
57
+ if (
58
+ !Number.isInteger(e.perValue) ||
59
+ e.perValue < 1 ||
60
+ e.perValue > compatibility.maxCount
61
+ )
62
+ throw new Error("生成数量超出工具适配范围");
63
+ if (
64
+ !Number.isInteger(item.seed) ||
65
+ item.seed < 0 ||
66
+ item.seed > compatibility.maxSeed
67
+ )
68
+ throw new Error("seed 超出模型范围");
69
+ if ((item.imageArgs ?? []).length > compatibility.maxImages)
70
+ throw new Error("参考输入图片超过模型上限");
71
+ if (plan.module === "edit" && !(item.imageArgs ?? []).length)
72
+ throw new Error("编辑模型需要输入底图");
73
+ if (!compatibility.fields?.promptExtend && e.promptExtend)
74
+ throw new Error(
75
+ model + " 不支持提示词扩写,请关闭 promptExtend 后重新预演",
76
+ );
77
+ if (!compatibility.fields?.watermark && e.watermark)
78
+ throw new Error(model + " 不支持水印参数");
79
+ if (
80
+ compatibility.maxNegativeCharacters &&
81
+ [...(item.negativeBlock ?? "")].length >
82
+ compatibility.maxNegativeCharacters
83
+ )
84
+ throw new Error(
85
+ "负向提示词超过 " + compatibility.maxNegativeCharacters + " 字符",
86
+ );
87
+ if (
88
+ compatibility.maxPromptCharacters &&
89
+ [...remotePrompt(item, compatibility)].length >
90
+ compatibility.maxPromptCharacters
91
+ )
92
+ throw new Error(
93
+ "主提示词与负向约束合计超过 " +
94
+ compatibility.maxPromptCharacters +
95
+ " 字符",
96
+ );
97
+ }
98
+ return compatibility;
99
+ }
100
+
101
+ export function compileRemoteRequest(
102
+ plan,
103
+ item,
104
+ { registry = modelRegistry } = {},
105
+ ) {
106
+ const e = item.execution ?? plan.execution,
107
+ api = plan.backend?.credentialReference?.api ?? "dashscope";
108
+ const spec = registry.resolve(
109
+ api,
110
+ e.model,
111
+ plan.module,
112
+ !!item.imageArgs?.length,
113
+ );
114
+ validateRemotePlan({ ...plan, items: [item] }, registry);
115
+ const parameters = { size: e.size, n: e.perValue, seed: item.seed },
116
+ adjustments = [];
117
+ const reserved = new Set([
118
+ "model",
119
+ "size",
120
+ "perValue",
121
+ "promptExtend",
122
+ "watermark",
123
+ ]);
124
+ for (const key of Object.keys(e))
125
+ if (!reserved.has(key) && !spec.fields?.[key])
126
+ throw new Error("模型不支持参数 " + key);
127
+ for (const [key, rule] of Object.entries(spec.fields ?? {})) {
128
+ const value = e[key] ?? rule.default;
129
+ if (value === undefined) continue;
130
+ if (
131
+ rule.type === "integer"
132
+ ? !Number.isSafeInteger(value) ||
133
+ value < (rule.min ?? -Infinity) ||
134
+ value > (rule.max ?? Infinity)
135
+ : typeof value !== rule.type
136
+ )
137
+ throw new Error("模型参数类型或范围错误:" + key);
138
+ if (rule.enum && !rule.enum.includes(value))
139
+ throw new Error("模型参数取值无效:" + key);
140
+ parameters[rule.wire] = value;
141
+ }
142
+ if (item.dimensionAdjustment)
143
+ adjustments.push({
144
+ parameter: "size",
145
+ action: "resolve-dimensions",
146
+ ...item.dimensionAdjustment,
147
+ message: "尺寸已解析到当前模型的合法范围",
148
+ });
149
+ const prompt = remotePrompt(item, spec);
150
+ if (prompt !== item.prompt)
151
+ adjustments.push({
152
+ parameter: "negativePrompt",
153
+ action: "append-to-prompt",
154
+ message: "负向约束已明确并入主提示词",
155
+ });
156
+ if (item.negativeBlock && !spec.negativeInPrompt)
157
+ parameters.negative_prompt = item.negativeBlock;
158
+ return {
159
+ schema: "art/image-request-v1",
160
+ api,
161
+ adapter: spec.transport.adapter,
162
+ transport: spec.transport,
163
+ inputPolicy: spec.inputPolicy,
164
+ contractHash: contractHash(spec),
165
+ module: plan.module,
166
+ model: e.model,
167
+ prompt,
168
+ negativePrompt: spec.negativeInPrompt ? "" : (item.negativeBlock ?? ""),
169
+ images: [...(item.imageArgs ?? [])],
170
+ parameters,
171
+ size: e.size,
172
+ seed: item.seed,
173
+ count: e.perValue,
174
+ adjustments,
175
+ };
176
+ }
177
+ export function freezeRemotePlan(plan) {
178
+ const requests = plan.items.map((item) => compileRemoteRequest(plan, item));
179
+ return {
180
+ requests,
181
+ contract: {
182
+ schema: "art/execution-contract-v1",
183
+ hash: hash(requests.map((r) => r.contractHash)),
184
+ },
185
+ };
186
+ }
187
+ export function assertRemoteContract(plan) {
188
+ if (!plan.executionContract || !plan.items.every((item) => item.request))
189
+ throw new Error("预案缺少当前执行契约,请重新预演");
190
+ const current = freezeRemotePlan(plan);
191
+ if (
192
+ hash(current.contract) !== hash(plan.executionContract) ||
193
+ plan.items.some(
194
+ (item, index) => hash(item.request) !== hash(current.requests[index]),
195
+ )
196
+ )
197
+ throw new Error("模型执行契约已变化,请重新预演");
198
+ }
package/lib/images.mjs ADDED
@@ -0,0 +1,10 @@
1
+ import sharp from 'sharp';
2
+ export async function validateImage(buffer){
3
+ if(!Buffer.isBuffer(buffer)||buffer.length>20*1024*1024)throw new Error('单张图片最大 20MB');
4
+ try{
5
+ const pipeline=sharp(buffer,{limitInputPixels:64*1024*1024,failOn:'warning'}),metadata=await pipeline.metadata();
6
+ if(!['png','jpeg','webp'].includes(metadata.format)||!metadata.width||!metadata.height||metadata.pages>1)throw new Error('只支持单帧 PNG/JPEG/WebP');
7
+ await pipeline.resize(1,1).raw().toBuffer();
8
+ return {format:metadata.format,width:metadata.width,height:metadata.height};
9
+ }catch(error){throw new Error('图片无法完整解码:'+error.message);}
10
+ }
@@ -0,0 +1,40 @@
1
+ /** Execution completion is separate from proof that all side effects have stopped. */
2
+ export const RUN_STATES = Object.freeze([
3
+ "queued",
4
+ "running",
5
+ "cancelling",
6
+ "succeeded",
7
+ "failed",
8
+ "cancelled",
9
+ "unknown",
10
+ ]);
11
+ export const terminal = (status) =>
12
+ ["succeeded", "failed", "cancelled", "unknown"].includes(status);
13
+ export function executionSettled(task) {
14
+ return (
15
+ terminal(task.status) &&
16
+ task.status !== "unknown" &&
17
+ task.stopConfirmed === true &&
18
+ !task.unsettled &&
19
+ !task.promptId &&
20
+ !task.remoteCancellation &&
21
+ !Object.values(task.remoteExecutions ?? {}).some((receipt) =>
22
+ ["dispatching", "accepted"].includes(receipt.state),
23
+ )
24
+ );
25
+ }
26
+ export function executionLifecycle(task) {
27
+ if (task.status === "queued") return "accepted";
28
+ if (["running", "cancelling"].includes(task.status)) return "running";
29
+ if (!executionSettled(task)) return "unknown";
30
+ return { succeeded: "completed", failed: "failed", cancelled: "cancelled" }[
31
+ task.status
32
+ ];
33
+ }
34
+ export function assertIdle(runs, label = "对象") {
35
+ const blocked = runs.filter((run) => !executionSettled(run));
36
+ if (blocked.length)
37
+ throw new Error(
38
+ `${label}存在运行中或停止未确认的执行:${blocked.map((run) => run.taskId).join(", ")}`,
39
+ );
40
+ }