@kevlns/art-workshop 0.5.1 → 0.5.2

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 (57) hide show
  1. package/AGENTS.md +25 -25
  2. package/LICENSE +21 -21
  3. package/README.md +63 -63
  4. package/art-workshop.mjs +174 -174
  5. package/docs/configuration.md +82 -82
  6. package/docs/core-guidance.md +50 -50
  7. package/docs/data-formats.md +85 -85
  8. package/docs/deployment.md +32 -32
  9. package/docs/local-models/qwen-image-2.1.json +73 -73
  10. package/docs/local-models/qwen-image-2.1.md +33 -33
  11. package/docs/model-architecture.md +78 -78
  12. package/docs/modes.md +67 -67
  13. package/lib/agent.mjs +32 -32
  14. package/lib/analysis-worker.mjs +32 -32
  15. package/lib/analyze.mjs +85 -85
  16. package/lib/asset-profile.mjs +23 -23
  17. package/lib/candidates.mjs +103 -103
  18. package/lib/comfy-recovery.mjs +17 -17
  19. package/lib/conversation.mjs +77 -77
  20. package/lib/core.mjs +75 -75
  21. package/lib/deployment-guide.mjs +12 -12
  22. package/lib/design.mjs +29 -29
  23. package/lib/dimensions.mjs +22 -22
  24. package/lib/edit.mjs +41 -41
  25. package/lib/environment-operations.mjs +49 -49
  26. package/lib/environment-runtime.mjs +99 -99
  27. package/lib/environments.mjs +55 -55
  28. package/lib/executor.mjs +107 -107
  29. package/lib/generate.mjs +58 -58
  30. package/lib/heartbeat.mjs +16 -16
  31. package/lib/images.mjs +1 -1
  32. package/lib/lifecycle.mjs +53 -53
  33. package/lib/migration.mjs +154 -154
  34. package/lib/process-identity.mjs +22 -14
  35. package/lib/project.mjs +39 -39
  36. package/lib/refs.mjs +26 -26
  37. package/lib/runtime.mjs +25 -25
  38. package/lib/service.mjs +134 -126
  39. package/lib/settings.mjs +50 -50
  40. package/lib/shared.mjs +67 -67
  41. package/lib/style-bundle.mjs +85 -85
  42. package/lib/style-contract.mjs +74 -74
  43. package/lib/style-lifecycle.mjs +125 -125
  44. package/lib/style-review.mjs +14 -14
  45. package/lib/task-contract.mjs +93 -93
  46. package/lib/tasks.mjs +497 -497
  47. package/lib/templates.mjs +80 -80
  48. package/lib/vision.mjs +56 -56
  49. package/lib/worker-process.mjs +6 -6
  50. package/lib/workspace.mjs +292 -292
  51. package/package.json +1 -1
  52. package/rules/core-guidance.json +22 -22
  53. package/skills/art-workshop/SKILL.md +17 -17
  54. package/skills/art-workshop/references/conversation.md +11 -11
  55. package/skills/art-workshop/references/expression.md +27 -27
  56. package/skills/art-workshop/references/project.md +109 -109
  57. package/v-cli.plugin.json +2747 -2747
package/lib/executor.mjs CHANGED
@@ -1,107 +1,107 @@
1
- import {compileRemoteRequest} from './generation-policy.mjs';
2
- import {adapters} from './adapters/index.mjs';
3
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from 'node:fs';
4
- import { join, dirname, resolve, relative, isAbsolute } from 'node:path';
5
- import { randomUUID } from 'node:crypto';
6
- import { buildArgs, validatePlan } from './plan.mjs';
7
- import { hash, writeJson } from './shared.mjs';
8
- export { validatePlan } from './plan.mjs';
9
- export { writeJson } from './shared.mjs';
10
- import { runBl, sha256File, resolveBlEntry } from './bl.mjs';
11
- import {ownedPath} from './workspace.mjs';
12
- import {loadSettings,externalPath} from './settings.mjs';
13
- import {assertExecutableStyle} from './style-contract.mjs';
14
-
15
- function runtimeVersion() {
16
- try { return JSON.parse(readFileSync(join(dirname(dirname(resolveBlEntry())), 'package.json'), 'utf8')).version ?? 'unknown'; }
17
- catch { return 'unknown'; }
18
- }
19
- export function executePlan(plan, items, { outputRoot=loadSettings().paths.output, dry = false, runner, log = console.log } = {}) {
20
- validatePlan(plan);
21
- assertExecutableStyle(plan);
22
- if (!items.length) throw new Error('没有选中任何计划项');
23
- for (const item of items) {
24
- const expected = plan.items.find(x => x.inputHash === item.inputHash);
25
- if (!expected || hash(item) !== hash(expected)) throw new Error('执行项不属于该计划或内容已改变');
26
- }
27
- for (const ref of plan.refs) { externalPath(ref.path,'原图/参考图'); if (!existsSync(ref.path) || sha256File(ref.path) !== ref.hash) throw new Error(`参考图已变化:${ref.path}`); }
28
- externalPath(outputRoot,'输出目录');
29
- if (dry) {
30
- const requests = items.map(item => ({ output:item.output, ...(item.design?{design:item.design,execution:item.execution}:{}),itemId: item.itemId, variantId: item.variantId, seed: item.seed,
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}`) }));
32
- log(JSON.stringify({ dry: true, remoteCalls: 0, planHash: plan.planHash, requests }, null, 2));
33
- return { dry: true, requests };
34
- }
35
- if(!runner)throw new Error('真实执行必须使用受管 task 生命周期;executePlan 仅用于预演或注入测试');
36
- const runId = `${plan.job.replaceAll('/', '-')}-${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID().slice(0, 8)}`;
37
- const runDir = join(outputRoot, runId);
38
- mkdirSync(runDir, { recursive: true });
39
- const manifest = { schema: 'art-workshop/run', runId, plan, planHash: plan.planHash, blVersion: runner === runBl ? runtimeVersion() : 'injected',
40
- startedAt: new Date().toISOString(), items: [] };
41
- const manifestPath = join(runDir, 'manifest.json');
42
- const persist = () => {
43
- manifest.summary = { completed: manifest.items.filter(x => x.status !== 'running').length, expected: items.length,
44
- ok: manifest.items.filter(x => x.ok).length, failed: manifest.items.filter(x => x.status === 'failed').length };
45
- writeJson(manifestPath, manifest);
46
- };
47
- persist();
48
- for (const item of items) {
49
- const prefix = `${item.itemId}--${item.variantId}`;
50
- const args = buildArgs(plan, item, runDir, prefix);
51
- const record = { ...structuredClone(item), args, ok: false, status: 'running', files: [], urls: [], outputHashes: {} };
52
- manifest.items.push(record); persist();
53
- const before = new Set(readdirSync(runDir));
54
- try {
55
- const response = runner(args);
56
- const fresh = readdirSync(runDir).filter(f => !before.has(f) && /\.(png|jpe?g|webp)$/i.test(f)).sort();
57
- fresh.forEach((file, index) => {
58
- const target = `${prefix}${index ? '--' + (index + 1) : ''}${file.slice(file.lastIndexOf('.'))}`;
59
- if (file !== target) {
60
- if (existsSync(join(runDir, target))) throw new Error(`输出文件已存在:${target}`);
61
- renameSync(join(runDir, file), join(runDir, target));
62
- }
63
- record.files.push(target); record.outputHashes[target] = sha256File(join(runDir, target));
64
- });
65
- record.urls = response.urls ?? [];
66
- const expectedCount = (item.execution??plan.execution).perValue;
67
- if (record.files.length !== expectedCount) throw new Error(`期望 ${expectedCount} 张,实际 ${record.files.length} 张`);
68
- record.ok = true; record.status = 'generated';
69
- log(`✔ ${item.itemId}/${item.variantId} seed=${item.seed} → ${record.files.join(', ')}`);
70
- } catch (e) {
71
- record.status = 'failed'; record.error = String(e.message ?? e).slice(0, 1000);
72
- log(`✗ ${item.itemId}/${item.variantId}:${record.error}`);
73
- }
74
- persist();
75
- }
76
- manifest.finishedAt = new Date().toISOString(); persist();
77
- log(`manifest → ${manifestPath}`);
78
- return { manifest, manifestPath, runDir };
79
- }
80
-
81
- export function outputPath(manifestPath, file) {
82
- const base = dirname(resolve(manifestPath));
83
- const path = resolve(base, file);
84
- const rel = relative(base, path);
85
- if (isAbsolute(rel) || rel === '..' || rel.startsWith('..\\') || rel.startsWith('../')) throw new Error('输出路径越界');
86
- return ownedPath(base,file);
87
- }
88
-
89
- export function checkRun(manifest, manifestPath) {
90
- validatePlan(manifest.plan);
91
- for (const item of manifest.items) {
92
- const expected = manifest.plan.items.find(x => x.itemId === item.itemId && x.variantId === item.variantId);
93
- if (!expected || expected.inputHash !== item.inputHash) throw new Error('执行记录不属于原始计划');
94
- for (const key of ['prompt', 'seed', 'checks', 'negativeBlock', 'imageArgs', 'execution', 'design', 'output']) {
95
- if (hash({value:item[key]}) !== hash({value:expected[key]})) throw new Error(`执行记录已改变:${item.itemId}.${key}`);
96
- }
97
- }
98
- return manifest.items.flatMap(item => item.files.length ? item.files.map(file => {
99
- const path = outputPath(manifestPath, file);
100
- const exists = existsSync(path), recordedHash = item.outputHashes[file];
101
- const integrity = exists && sha256File(path) === recordedHash;
102
- const editable = exists && !!manifest.finishedAt && !item.deleted &&
103
- (integrity || (!recordedHash && !item.ok && item.status === 'failed'));
104
- return { itemId: item.itemId, variantId: item.variantId, file, path, integrity, generated: item.ok,
105
- editable, checks: item.checks, accepted: integrity && item.ok && !!manifest.finishedAt && !item.deleted };
106
- }) : [{ itemId: item.itemId, variantId: item.variantId, file: null, generated: false, accepted: false, error: item.error }]);
107
- }
1
+ import {compileRemoteRequest} from './generation-policy.mjs';
2
+ import {adapters} from './adapters/index.mjs';
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from 'node:fs';
4
+ import { join, dirname, resolve, relative, isAbsolute } from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { buildArgs, validatePlan } from './plan.mjs';
7
+ import { hash, writeJson } from './shared.mjs';
8
+ export { validatePlan } from './plan.mjs';
9
+ export { writeJson } from './shared.mjs';
10
+ import { runBl, sha256File, resolveBlEntry } from './bl.mjs';
11
+ import {ownedPath} from './workspace.mjs';
12
+ import {loadSettings,externalPath} from './settings.mjs';
13
+ import {assertExecutableStyle} from './style-contract.mjs';
14
+
15
+ function runtimeVersion() {
16
+ try { return JSON.parse(readFileSync(join(dirname(dirname(resolveBlEntry())), 'package.json'), 'utf8')).version ?? 'unknown'; }
17
+ catch { return 'unknown'; }
18
+ }
19
+ export function executePlan(plan, items, { outputRoot=loadSettings().paths.output, dry = false, runner, log = console.log } = {}) {
20
+ validatePlan(plan);
21
+ assertExecutableStyle(plan);
22
+ if (!items.length) throw new Error('没有选中任何计划项');
23
+ for (const item of items) {
24
+ const expected = plan.items.find(x => x.inputHash === item.inputHash);
25
+ if (!expected || hash(item) !== hash(expected)) throw new Error('执行项不属于该计划或内容已改变');
26
+ }
27
+ for (const ref of plan.refs) { externalPath(ref.path,'原图/参考图'); if (!existsSync(ref.path) || sha256File(ref.path) !== ref.hash) throw new Error(`参考图已变化:${ref.path}`); }
28
+ externalPath(outputRoot,'输出目录');
29
+ if (dry) {
30
+ const requests = items.map(item => ({ output:item.output, ...(item.design?{design:item.design,execution:item.execution}:{}),itemId: item.itemId, variantId: item.variantId, seed: item.seed,
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}`) }));
32
+ log(JSON.stringify({ dry: true, remoteCalls: 0, planHash: plan.planHash, requests }, null, 2));
33
+ return { dry: true, requests };
34
+ }
35
+ if(!runner)throw new Error('真实执行必须使用受管 task 生命周期;executePlan 仅用于预演或注入测试');
36
+ const runId = `${plan.job.replaceAll('/', '-')}-${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID().slice(0, 8)}`;
37
+ const runDir = join(outputRoot, runId);
38
+ mkdirSync(runDir, { recursive: true });
39
+ const manifest = { schema: 'art-workshop/run', runId, plan, planHash: plan.planHash, blVersion: runner === runBl ? runtimeVersion() : 'injected',
40
+ startedAt: new Date().toISOString(), items: [] };
41
+ const manifestPath = join(runDir, 'manifest.json');
42
+ const persist = () => {
43
+ manifest.summary = { completed: manifest.items.filter(x => x.status !== 'running').length, expected: items.length,
44
+ ok: manifest.items.filter(x => x.ok).length, failed: manifest.items.filter(x => x.status === 'failed').length };
45
+ writeJson(manifestPath, manifest);
46
+ };
47
+ persist();
48
+ for (const item of items) {
49
+ const prefix = `${item.itemId}--${item.variantId}`;
50
+ const args = buildArgs(plan, item, runDir, prefix);
51
+ const record = { ...structuredClone(item), args, ok: false, status: 'running', files: [], urls: [], outputHashes: {} };
52
+ manifest.items.push(record); persist();
53
+ const before = new Set(readdirSync(runDir));
54
+ try {
55
+ const response = runner(args);
56
+ const fresh = readdirSync(runDir).filter(f => !before.has(f) && /\.(png|jpe?g|webp)$/i.test(f)).sort();
57
+ fresh.forEach((file, index) => {
58
+ const target = `${prefix}${index ? '--' + (index + 1) : ''}${file.slice(file.lastIndexOf('.'))}`;
59
+ if (file !== target) {
60
+ if (existsSync(join(runDir, target))) throw new Error(`输出文件已存在:${target}`);
61
+ renameSync(join(runDir, file), join(runDir, target));
62
+ }
63
+ record.files.push(target); record.outputHashes[target] = sha256File(join(runDir, target));
64
+ });
65
+ record.urls = response.urls ?? [];
66
+ const expectedCount = (item.execution??plan.execution).perValue;
67
+ if (record.files.length !== expectedCount) throw new Error(`期望 ${expectedCount} 张,实际 ${record.files.length} 张`);
68
+ record.ok = true; record.status = 'generated';
69
+ log(`✔ ${item.itemId}/${item.variantId} seed=${item.seed} → ${record.files.join(', ')}`);
70
+ } catch (e) {
71
+ record.status = 'failed'; record.error = String(e.message ?? e).slice(0, 1000);
72
+ log(`✗ ${item.itemId}/${item.variantId}:${record.error}`);
73
+ }
74
+ persist();
75
+ }
76
+ manifest.finishedAt = new Date().toISOString(); persist();
77
+ log(`manifest → ${manifestPath}`);
78
+ return { manifest, manifestPath, runDir };
79
+ }
80
+
81
+ export function outputPath(manifestPath, file) {
82
+ const base = dirname(resolve(manifestPath));
83
+ const path = resolve(base, file);
84
+ const rel = relative(base, path);
85
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('..\\') || rel.startsWith('../')) throw new Error('输出路径越界');
86
+ return ownedPath(base,file);
87
+ }
88
+
89
+ export function checkRun(manifest, manifestPath) {
90
+ validatePlan(manifest.plan);
91
+ for (const item of manifest.items) {
92
+ const expected = manifest.plan.items.find(x => x.itemId === item.itemId && x.variantId === item.variantId);
93
+ if (!expected || expected.inputHash !== item.inputHash) throw new Error('执行记录不属于原始计划');
94
+ for (const key of ['prompt', 'seed', 'checks', 'negativeBlock', 'imageArgs', 'execution', 'design', 'output']) {
95
+ if (hash({value:item[key]}) !== hash({value:expected[key]})) throw new Error(`执行记录已改变:${item.itemId}.${key}`);
96
+ }
97
+ }
98
+ return manifest.items.flatMap(item => item.files.length ? item.files.map(file => {
99
+ const path = outputPath(manifestPath, file);
100
+ const exists = existsSync(path), recordedHash = item.outputHashes[file];
101
+ const integrity = exists && sha256File(path) === recordedHash;
102
+ const editable = exists && !!manifest.finishedAt && !item.deleted &&
103
+ (integrity || (!recordedHash && !item.ok && item.status === 'failed'));
104
+ return { itemId: item.itemId, variantId: item.variantId, file, path, integrity, generated: item.ok,
105
+ editable, checks: item.checks, accepted: integrity && item.ok && !!manifest.finishedAt && !item.deleted };
106
+ }) : [{ itemId: item.itemId, variantId: item.variantId, file: null, generated: false, accepted: false, error: item.error }]);
107
+ }
package/lib/generate.mjs CHANGED
@@ -1,58 +1,58 @@
1
- import {assertObjectCurrent} from './workspace.mjs';
2
- import {description,descriptions} from './shared.mjs';
3
- import {generationPrompt,COMPILER_VERSION} from './prompt-structure.mjs';
4
- import {TRANSPARENT_OUTPUT} from './transparent-output.mjs';
5
- import {GENERATION_FIELDS,textSpecs,textSpecLine,textFidelityNegative} from './task-contract.mjs';
6
- import {taskReferencePrompt} from './task-references.mjs';
7
- import {readObject,verifyReferences} from './workspace.mjs';
8
- import { keys, id, integer, hash } from './shared.mjs';
9
- import { ROOT,loadProject,loadJob } from './project.mjs';
10
- import {selectCore,corePrompt,coreNegative} from './core.mjs';
11
- import {execution,finishPlan} from './plan.mjs';
12
- import {presentation,assetPrompt} from './presentation.mjs';
13
- import {resolveAssetProfile} from './asset-profile.mjs';
14
- import {design,designPrompt} from './design.mjs';
15
- export function compileGenerate({projectId,jobId,coreId,root=ROOT,localExecution={}}) {
16
- const taskRecord=readObject(root,projectId,'task',jobId);assertObjectCurrent(root,taskRecord);const dynamicRefs=verifyReferences(root,taskRecord);
17
- const project=loadProject(projectId,root),job=loadJob(projectId,jobId,'generate',root);
18
- keys(job,['project','kind','core','profile','asset','execution','analysis','generation','items'],'job');
19
- if(job.generation&&localExecution.model)job.execution={...job.execution,model:localExecution.model};
20
- const selected=selectCore(project,job,coreId,root),core=selected.core;
21
- const profile=resolveAssetProfile(root,projectId,job);
22
- const items=[],ids=new Set();
23
- if(!Array.isArray(job.items)||!job.items.length) throw new Error('任务 items 必须非空');
24
- for(const [sourceIndex,source] of job.items.entries()) {
25
- keys(source,GENERATION_FIELDS.item,'item');
26
- const readable=textSpecs(source.textSpecs,`items[${sourceIndex}].textSpecs`);
27
- if(readable.length&&profile.constraints.text!==true)throw new Error(`items[${sourceIndex}].textSpecs:资产规格禁用文字`);
28
- const d=design(profile,source.design,job.execution);
29
- id(source.id); if(ids.has(source.id)) throw new Error('item ID 重复'); ids.add(source.id);
30
- description(source.intent,'intent'); descriptions(source.mustRead,'mustRead');
31
- if(!Array.isArray(source.entities)||!source.entities.length) throw new Error('entities 必须非空');
32
- const objectIds=new Set(), lines=[];
33
- for(const [entityIndex,e] of source.entities.entries()) {
34
- keys(e,GENERATION_FIELDS.entity,'entity'); id(e.id); id(e.kind);
35
- if(objectIds.has(e.id)) throw new Error('实体 ID 重复'); objectIds.add(e.id);
36
- if(!['primary','support'].includes(e.role)) throw new Error('实体角色不合法');
37
- integer(e.count,'count',1,100); description(e.appearance,'appearance');description(e.color,'color'); if(e.action) description(e.action,'action');
38
- if(e.material!==undefined)description(e.material,`items[${sourceIndex}].entities[${entityIndex}].material`);
39
- lines.push(`${e.id}:${e.count} 个${e.appearance}${e.material!==undefined?',材质 '+e.material:''},${e.color},${e.role==='primary'?'主要':'辅助'}实体${e.action?','+e.action:''}。`);
40
- }
41
- for(const e of source.effects??[]) {
42
- keys(e,GENERATION_FIELDS.effect,'effect');id(e.id);
43
- if(objectIds.has(e.id)||!source.entities.some(x=>x.id===e.target)) throw new Error('效果 ID 重复或目标不存在'); objectIds.add(e.id);
44
- for(const k of ['kind','color','relation']) description(e[k],k); integer(e.count,'count',1,100);
45
- lines.push(`${e.id}:${e.count} 个${e.color}${e.kind},作用于 ${e.target};${e.relation}。`);
46
- }
47
- for(const r of source.relations??[]) {keys(r,GENERATION_FIELDS.relation,'relation'); if(!objectIds.has(r.from)||!objectIds.has(r.to)) throw new Error('关系目标不存在');lines.push(`${r.from} → ${r.to}:${description(r.action,'action')}。`);}
48
- const variants=source.variants?.length?source.variants:[{id:'base'}],variantIds=new Set();
49
- for(const variant of variants) {
50
- keys(variant,GENERATION_FIELDS.variant,'variant');id(variant.id); if(variantIds.has(variant.id)) throw new Error('variant ID 重复');variantIds.add(variant.id);
51
- const p=presentation(profile,{...source.composition,...variant.composition},d);
52
- if(!objectIds.has(p.value.focalTarget)) throw new Error('视觉焦点不存在');
53
- const seed=variant.seed??source.seed??parseInt(hash([projectId,jobId,source.id]).slice(0,7),16); integer(seed,'seed');
54
- items.push({...(p.value.background.type==='transparent'?{output:TRANSPARENT_OUTPUT}:{}),...(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:generationPrompt({intent:source.intent,frozen:corePrompt(core),details:lines,composition:`视觉焦点:${p.value.focalTarget}。\n${p.prompt}`,delivery:d?designPrompt(d):'',asset:assetPrompt(profile),references:taskReferencePrompt(taskRecord,source.id),mustRead:source.mustRead,textSpecs:readable}),negativeBlock:textFidelityNegative([coreNegative(core),profile.constraints.text?'':'文字, 字母, 水印',profile.constraints.frame?'':'装饰外框'].filter(Boolean).join(', '),readable),imageArgs:[],checks:{content:readable.length?[...source.mustRead,...readable.map(textSpecLine)]:source.mustRead,style:[corePrompt(core)],asset:[...profile.checks,p.background]}});
55
- }
56
- }
57
- return finishPlan({compilerVersion:COMPILER_VERSION,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});
58
- }
1
+ import {assertObjectCurrent} from './workspace.mjs';
2
+ import {description,descriptions} from './shared.mjs';
3
+ import {generationPrompt,COMPILER_VERSION} from './prompt-structure.mjs';
4
+ import {TRANSPARENT_OUTPUT} from './transparent-output.mjs';
5
+ import {GENERATION_FIELDS,textSpecs,textSpecLine,textFidelityNegative} from './task-contract.mjs';
6
+ import {taskReferencePrompt} from './task-references.mjs';
7
+ import {readObject,verifyReferences} from './workspace.mjs';
8
+ import { keys, id, integer, hash } from './shared.mjs';
9
+ import { ROOT,loadProject,loadJob } from './project.mjs';
10
+ import {selectCore,corePrompt,coreNegative} from './core.mjs';
11
+ import {execution,finishPlan} from './plan.mjs';
12
+ import {presentation,assetPrompt} from './presentation.mjs';
13
+ import {resolveAssetProfile} from './asset-profile.mjs';
14
+ import {design,designPrompt} from './design.mjs';
15
+ export function compileGenerate({projectId,jobId,coreId,root=ROOT,localExecution={}}) {
16
+ const taskRecord=readObject(root,projectId,'task',jobId);assertObjectCurrent(root,taskRecord);const dynamicRefs=verifyReferences(root,taskRecord);
17
+ const project=loadProject(projectId,root),job=loadJob(projectId,jobId,'generate',root);
18
+ keys(job,['project','kind','core','profile','asset','execution','analysis','generation','items'],'job');
19
+ if(job.generation&&localExecution.model)job.execution={...job.execution,model:localExecution.model};
20
+ const selected=selectCore(project,job,coreId,root),core=selected.core;
21
+ const profile=resolveAssetProfile(root,projectId,job);
22
+ const items=[],ids=new Set();
23
+ if(!Array.isArray(job.items)||!job.items.length) throw new Error('任务 items 必须非空');
24
+ for(const [sourceIndex,source] of job.items.entries()) {
25
+ keys(source,GENERATION_FIELDS.item,'item');
26
+ const readable=textSpecs(source.textSpecs,`items[${sourceIndex}].textSpecs`);
27
+ if(readable.length&&profile.constraints.text!==true)throw new Error(`items[${sourceIndex}].textSpecs:资产规格禁用文字`);
28
+ const d=design(profile,source.design,job.execution);
29
+ id(source.id); if(ids.has(source.id)) throw new Error('item ID 重复'); ids.add(source.id);
30
+ description(source.intent,'intent'); descriptions(source.mustRead,'mustRead');
31
+ if(!Array.isArray(source.entities)||!source.entities.length) throw new Error('entities 必须非空');
32
+ const objectIds=new Set(), lines=[];
33
+ for(const [entityIndex,e] of source.entities.entries()) {
34
+ keys(e,GENERATION_FIELDS.entity,'entity'); id(e.id); id(e.kind);
35
+ if(objectIds.has(e.id)) throw new Error('实体 ID 重复'); objectIds.add(e.id);
36
+ if(!['primary','support'].includes(e.role)) throw new Error('实体角色不合法');
37
+ integer(e.count,'count',1,100); description(e.appearance,'appearance');description(e.color,'color'); if(e.action) description(e.action,'action');
38
+ if(e.material!==undefined)description(e.material,`items[${sourceIndex}].entities[${entityIndex}].material`);
39
+ lines.push(`${e.id}:${e.count} 个${e.appearance}${e.material!==undefined?',材质 '+e.material:''},${e.color},${e.role==='primary'?'主要':'辅助'}实体${e.action?','+e.action:''}。`);
40
+ }
41
+ for(const e of source.effects??[]) {
42
+ keys(e,GENERATION_FIELDS.effect,'effect');id(e.id);
43
+ if(objectIds.has(e.id)||!source.entities.some(x=>x.id===e.target)) throw new Error('效果 ID 重复或目标不存在'); objectIds.add(e.id);
44
+ for(const k of ['kind','color','relation']) description(e[k],k); integer(e.count,'count',1,100);
45
+ lines.push(`${e.id}:${e.count} 个${e.color}${e.kind},作用于 ${e.target};${e.relation}。`);
46
+ }
47
+ for(const r of source.relations??[]) {keys(r,GENERATION_FIELDS.relation,'relation'); if(!objectIds.has(r.from)||!objectIds.has(r.to)) throw new Error('关系目标不存在');lines.push(`${r.from} → ${r.to}:${description(r.action,'action')}。`);}
48
+ const variants=source.variants?.length?source.variants:[{id:'base'}],variantIds=new Set();
49
+ for(const variant of variants) {
50
+ keys(variant,GENERATION_FIELDS.variant,'variant');id(variant.id); if(variantIds.has(variant.id)) throw new Error('variant ID 重复');variantIds.add(variant.id);
51
+ const p=presentation(profile,{...source.composition,...variant.composition},d);
52
+ if(!objectIds.has(p.value.focalTarget)) throw new Error('视觉焦点不存在');
53
+ const seed=variant.seed??source.seed??parseInt(hash([projectId,jobId,source.id]).slice(0,7),16); integer(seed,'seed');
54
+ items.push({...(p.value.background.type==='transparent'?{output:TRANSPARENT_OUTPUT}:{}),...(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:generationPrompt({intent:source.intent,frozen:corePrompt(core),details:lines,composition:`视觉焦点:${p.value.focalTarget}。\n${p.prompt}`,delivery:d?designPrompt(d):'',asset:assetPrompt(profile),references:taskReferencePrompt(taskRecord,source.id),mustRead:source.mustRead,textSpecs:readable}),negativeBlock:textFidelityNegative([coreNegative(core),profile.constraints.text?'':'文字, 字母, 水印',profile.constraints.frame?'':'装饰外框'].filter(Boolean).join(', '),readable),imageArgs:[],checks:{content:readable.length?[...source.mustRead,...readable.map(textSpecLine)]:source.mustRead,style:[corePrompt(core)],asset:[...profile.checks,p.background]}});
55
+ }
56
+ }
57
+ return finishPlan({compilerVersion:COMPILER_VERSION,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});
58
+ }
package/lib/heartbeat.mjs CHANGED
@@ -1,16 +1,16 @@
1
- /** Heartbeats are advisory. Durable transitions still use strict writes. */
2
- export function heartbeatTick(persist, warn = console.warn) {
3
- try { persist(); return true; }
4
- catch (error) {
5
- warn(`心跳写入失败,下次重试;关键状态写入仍须成功:${error.code ?? ''} ${error.message}`);
6
- return false;
7
- }
8
- }
9
- export function startHeartbeat(persist, interval = 1000) {
10
- let failed = false;
11
- return setInterval(() => {
12
- const ok = heartbeatTick(persist, message => { if (!failed) console.warn(message); });
13
- if (ok && failed) console.warn('心跳写入已恢复');
14
- failed = !ok;
15
- }, interval);
16
- }
1
+ /** Heartbeats are advisory. Durable transitions still use strict writes. */
2
+ export function heartbeatTick(persist, warn = console.warn) {
3
+ try { persist(); return true; }
4
+ catch (error) {
5
+ warn(`心跳写入失败,下次重试;关键状态写入仍须成功:${error.code ?? ''} ${error.message}`);
6
+ return false;
7
+ }
8
+ }
9
+ export function startHeartbeat(persist, interval = 1000) {
10
+ let failed = false;
11
+ return setInterval(() => {
12
+ const ok = heartbeatTick(persist, message => { if (!failed) console.warn(message); });
13
+ if (ok && failed) console.warn('心跳写入已恢复');
14
+ failed = !ok;
15
+ }, interval);
16
+ }
package/lib/images.mjs CHANGED
@@ -7,4 +7,4 @@ export async function validateImage(buffer){
7
7
  await pipeline.resize(1,1).raw().toBuffer();
8
8
  return {format:metadata.format,width:metadata.width,height:metadata.height};
9
9
  }catch(error){throw new Error('图片无法完整解码:'+error.message);}
10
- }
10
+ }
package/lib/lifecycle.mjs CHANGED
@@ -1,53 +1,53 @@
1
- import {workerAlive} from './worker-process.mjs';
2
- /** Execution completion is separate from proof that all side effects have stopped. */
3
- export const RUN_STATES = Object.freeze([
4
- "queued",
5
- "running",
6
- "cancelling",
7
- "succeeded",
8
- "failed",
9
- "cancelled",
10
- "unknown",
11
- ]);
12
- export const terminal = (status) =>
13
- ["succeeded", "failed", "cancelled", "unknown"].includes(status);
14
- /** Analysis only observes remote input. Its finalized, exited worker cannot mutate
15
- * the draft again; an unqueryable upstream request may still consume credits.
16
- * Generation receipts never qualify for this local-only completion proof. */
17
- export function analysisLocallyStopped(task) {
18
- if (!['style-analysis', 'task-reference-analysis'].includes(task.kind) ||
19
- !['succeeded', 'failed', 'cancelled'].includes(task.status) ||
20
- !Number.isFinite(Date.parse(task.finishedAt)) ||
21
- !Number.isSafeInteger(task.workerPid) || task.workerPid <= 0 ||
22
- task.plan || task.promptId || Object.keys(task.remoteExecutions ?? {}).length) return false;
23
- return !workerAlive(task);
24
- }
25
- export function executionSettled(task) {
26
- if (analysisLocallyStopped(task)) return true;
27
- return (
28
- terminal(task.status) &&
29
- task.status !== "unknown" &&
30
- task.stopConfirmed === true &&
31
- !task.unsettled &&
32
- !task.promptId &&
33
- !task.remoteCancellation &&
34
- !Object.values(task.remoteExecutions ?? {}).some((receipt) =>
35
- ["dispatching", "accepted"].includes(receipt.state),
36
- )
37
- );
38
- }
39
- export function executionLifecycle(task) {
40
- if (task.status === "queued") return "accepted";
41
- if (["running", "cancelling"].includes(task.status)) return "running";
42
- if (!executionSettled(task)) return "unknown";
43
- return { succeeded: "completed", failed: "failed", cancelled: "cancelled" }[
44
- task.status
45
- ];
46
- }
47
- export function assertIdle(runs, label = "对象") {
48
- const blocked = runs.filter((run) => !executionSettled(run));
49
- if (blocked.length)
50
- throw new Error(
51
- `${label}存在运行中或停止未确认的执行:${blocked.map((run) => run.taskId).join(", ")}`,
52
- );
53
- }
1
+ import {workerAlive} from './worker-process.mjs';
2
+ /** Execution completion is separate from proof that all side effects have stopped. */
3
+ export const RUN_STATES = Object.freeze([
4
+ "queued",
5
+ "running",
6
+ "cancelling",
7
+ "succeeded",
8
+ "failed",
9
+ "cancelled",
10
+ "unknown",
11
+ ]);
12
+ export const terminal = (status) =>
13
+ ["succeeded", "failed", "cancelled", "unknown"].includes(status);
14
+ /** Analysis only observes remote input. Its finalized, exited worker cannot mutate
15
+ * the draft again; an unqueryable upstream request may still consume credits.
16
+ * Generation receipts never qualify for this local-only completion proof. */
17
+ export function analysisLocallyStopped(task) {
18
+ if (!['style-analysis', 'task-reference-analysis'].includes(task.kind) ||
19
+ !['succeeded', 'failed', 'cancelled'].includes(task.status) ||
20
+ !Number.isFinite(Date.parse(task.finishedAt)) ||
21
+ !Number.isSafeInteger(task.workerPid) || task.workerPid <= 0 ||
22
+ task.plan || task.promptId || Object.keys(task.remoteExecutions ?? {}).length) return false;
23
+ return !workerAlive(task);
24
+ }
25
+ export function executionSettled(task) {
26
+ if (analysisLocallyStopped(task)) return true;
27
+ return (
28
+ terminal(task.status) &&
29
+ task.status !== "unknown" &&
30
+ task.stopConfirmed === true &&
31
+ !task.unsettled &&
32
+ !task.promptId &&
33
+ !task.remoteCancellation &&
34
+ !Object.values(task.remoteExecutions ?? {}).some((receipt) =>
35
+ ["dispatching", "accepted"].includes(receipt.state),
36
+ )
37
+ );
38
+ }
39
+ export function executionLifecycle(task) {
40
+ if (task.status === "queued") return "accepted";
41
+ if (["running", "cancelling"].includes(task.status)) return "running";
42
+ if (!executionSettled(task)) return "unknown";
43
+ return { succeeded: "completed", failed: "failed", cancelled: "cancelled" }[
44
+ task.status
45
+ ];
46
+ }
47
+ export function assertIdle(runs, label = "对象") {
48
+ const blocked = runs.filter((run) => !executionSettled(run));
49
+ if (blocked.length)
50
+ throw new Error(
51
+ `${label}存在运行中或停止未确认的执行:${blocked.map((run) => run.taskId).join(", ")}`,
52
+ );
53
+ }