@kevlns/art-workshop 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kevlns
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,127 @@
1
- # Temporary Holding Version
1
+ # 美术工坊
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 三个独立模块:风格分析与核心冻结、文生图、图编辑。默认模型 qwen-image-3.0-pro,尺寸 1024*1024,关闭 prompt 扩写。
4
+
5
+ ## 随包 skill 与能力发现
6
+
7
+ skills/art-workshop 是精简的使用指导,随 npm 包一起分发,支持隐式发现。安装或更新包时,以及正常分析、冻结、生成或编辑调用时,自动同步到当前目录及用户目录下已有的 Agent 技能目录(含 .codex/skills、.agents/skills、.claude/skills 等;也支持 CODEX_HOME/skills)。不存在的技能目录不创建。只读查询、plan 与 --dry 不自动同步。
8
+
9
+ ```powershell
10
+ node art-workshop.mjs agent index
11
+ node art-workshop.mjs agent docs
12
+ node art-workshop.mjs agent init --directory C:/MyProject --dry
13
+ node art-workshop.mjs agent init --directory C:/MyProject
14
+ npm run skill:sync
15
+ ```
16
+
17
+ index 输出工程、核心、任务及模块入口,docs 输出随包完整指导。init 只同步技能,不写 AGENTS.md。随包文件是权威来源,同名文件更新,其他扩展文件保留;同步结果列出 current/updated/would-update。runtime.json 记录实际工具入口,已发现的 skill 无须猜测安装位置。Agent 通常在下次加载技能列表或新会话时发现它。安装:`npm install -g @kevlns/art-workshop`;本地配置与工程冻结核心均位于工具目录之外,不随 npm 包发布。
18
+
19
+ ## 本地配置与外部路径
20
+
21
+ 本地配置默认位于 Windows 的 %APPDATA%/art-workshop/config.json、macOS 的 ~/Library/Application Support/art-workshop/config.json、Linux 的 $XDG_CONFIG_HOME/art-workshop/config.json(未设置时使用 ~/.config)。它在用户目录,不进入工具 Git 仓库或 npm 包。
22
+
23
+ `config path` 查看位置,`config show` 查看生效配置,`config init` 创建默认文件,不覆盖已有文件。通过 `--config FILE` 或 ART_WORKSHOP_CONFIG 可指定其他外部配置文件。
24
+
25
+ 配置结构:
26
+
27
+ ```json
28
+ {
29
+ "paths": {
30
+ "workspace": "C:/Users/你的用户名/Downloads/image.g",
31
+ "output": "C:/Users/你的用户名/Downloads/image.g",
32
+ "refs": "D:/ArtReferences",
33
+ "cache": "C:/Users/你的用户名/Downloads/image.g/.cache"
34
+ },
35
+ "execution": {},
36
+ "analysisModel": null,
37
+ "defaultProject": null,
38
+ "autoSyncSkills": true
39
+ }
40
+ ```
41
+
42
+ paths 的四个目录均可独立修改;默认采用系统下载目录/image.g,Windows 会读取实际下载 Known Folder,Linux 尊重 XDG 下载目录。workspace 存放 projects;output 存放每次运行的独立文件夹与 manifest;refs 为默认参考图目录;cache 为分析缓存。所有运行资源路径必须在工具目录之外,包括编辑原图、报告与计划。
43
+
44
+ execution 可配置 model、size、promptExtend、perValue、watermark。尺寸使用明确像素,如 1024*1024。生图参数优先级为内置默认 → 工程配置 → 本地 execution → 任务 execution;已有冻结计划保留预演时的实际参数,需重新 plan 才能采用新默认值。analysisModel 覆盖工程的分析模型;defaultProject 可省略常用 --project;autoSyncSkills 控制自动同步,手动 agent init 始终可用。
45
+
46
+ 命令行 --workspace、--output-dir、--refs-dir、--cache-dir 临时覆盖对应路径。参考图的相对 path 以参考图目录解析,绝对 path 直接使用;参考目录优先级为 --refs-dir → 工程 refsDir → 本地配置。其他相对资源文件路径以 workspace 解析;check/select 的相对运行目录以 output 解析。
47
+
48
+ 每次 CLI 配置生效时,自动检查并补齐 refs 下的 style、palette、subject、composition、material、text、pose 分类目录;选定工程有独立 refsDir 时也会检查该目录。包括只读查询和 --dry,只创建缺少的目录,不移动或覆盖素材;目录位置被文件占用时明确报错。配置解析本身无文件写入,CLI 应用配置时完成目录初始化。
49
+
50
+ `refs guide` 解释各目录作用、推荐图片样式与可用分析 scope,并显示实际参考目录;可加 `--project P` 查看工程目录,或 `--refs-dir DIR` 临时指定。目录仅用于整理,不自动识别角色或绑定图片。分析仍在输入 refs 中显式声明 path、scope 和 note。构图、文字、姿态的具体要求属于单体计划,不自动冻结进核心。
51
+
52
+ ```powershell
53
+ node art-workshop.mjs config show
54
+ node art-workshop.mjs refs guide --project cellgame
55
+ node art-workshop.mjs style analyze --project cellgame --input projects/cellgame/briefs/style.json --refs-dir D:/ArtReferences --dry
56
+ node art-workshop.mjs generate run --plan .cache/plans/white-cell.json --dry
57
+ ```
58
+
59
+ ## 工程结构
60
+
61
+ 顶层指导规则:rules/core-guidance.json。工程配置位于 projects/<project>/project.json;briefs 保存分析输入,reports 保存报告,cores 保存冻结核心,profiles 保存资产规格,jobs 保存真实需求。这些目录位于外部工作目录,不属于工具安装目录。输出默认位于系统下载目录的 image.g,参考图与缓存也使用外部路径。
62
+
63
+ 所有模块明确指定工程;核心不跨工程回退。新工程须创建自己的 project.json,并通过该工程的报告冻结核心,不能复制冻结文件并修改身份。工程 cores 可列多份核心,defaultCore 为明确默认或 null。
64
+
65
+ ## 风格分析与冻结
66
+
67
+ 输入包含 project、id、description、refs、constraints。图片参考声明 path、scope(style/palette/shape/render)、note。纯语言也可分析;多图分别观察后合并。参考图只用于分析,文生图不会自动把这些图片传给生图模型。
68
+
69
+ ```powershell
70
+ node art-workshop.mjs style analyze --project cellgame --input projects/cellgame/briefs/style.json --dry
71
+ node art-workshop.mjs style analyze --project cellgame --input projects/cellgame/briefs/style.json --out projects/cellgame/reports/new-style.json
72
+ node art-workshop.mjs style validate --project cellgame --report projects/cellgame/reports/new-style.json
73
+ node art-workshop.mjs style freeze --project cellgame --report projects/cellgame/reports/new-style.json
74
+ node art-workshop.mjs style show --project cellgame --core new-style
75
+ ```
76
+
77
+ 分析只生成报告,不自动冻结。报告区分观察证据、置信度、推荐配置、conflicts 与 uncertainties。处理完冲突和未确定项才能冻结。freeze 表示采用推荐配置;已有核心不能覆写,另一套风格使用新的核心 ID。
78
+
79
+ 核心只拥有媒介、形体、渲染、光照、色彩关系与题材适配。正向和负向风格提示词从同一结构化核心生成。结构校验覆盖已定义的矛盾;自然语言证据与完整语义仍需审阅。规则详见 docs/core-guidance.md。
80
+
81
+ ## 文生图
82
+
83
+ 任务 kind 为 generate,core 绑定风格,profile 绑定资产规格。items 声明 intent、entities、effects、relations、composition、mustRead、seed 与 variants。候选只调整构图和 seed。
84
+
85
+ 核心选择顺序:显式 --core → 任务 core → 工程 defaultCore。显式指定与任务绑定冲突时报错,须先修改任务绑定。没有明确选择时不能猜测。计划保存核心身份、哈希、选择依据与完整快照。
86
+
87
+ ```powershell
88
+ node art-workshop.mjs generate show --project cellgame --job skills
89
+ node art-workshop.mjs generate plan --project cellgame --job skills --out .cache/skills-plan.json
90
+ node art-workshop.mjs generate run --plan .cache/skills-plan.json --item skill-01 --dry
91
+ node art-workshop.mjs generate run --plan .cache/skills-plan.json --limit 2
92
+ node art-workshop.mjs generate run --plan .cache/skills-plan.json --item skill-01 --variant front --dry
93
+ ```
94
+
95
+ plan 编译全部候选;run 默认 base,--variant 选指定候选,--explore 执行全部候选。修改任务后重新 plan,冻结计划不能同时修改来源配置。
96
+
97
+ 背景默认 {type:solid,color:#FFFFFF},纯黑用 #000000。其他纯色可显式配置,渐变用 gradient/from/to,场景用 scene/description 且须被资产规格允许。背景提示词和验收共用解析结果。
98
+
99
+ ## 图编辑
100
+
101
+ 任务 kind 为 edit,每项有 source、changes、preserve、mustRead、可选 seed。范围为 background/style/shape/color/composition/content/detail/text;同一范围不能同时修改和保留。背景修改用结构化 value,其他范围用 instruction。
102
+
103
+ ```powershell
104
+ node art-workshop.mjs edit show --project cellgame --job edit-white-background
105
+ node art-workshop.mjs edit plan --project cellgame --job edit-white-background --out .cache/edit-plan.json
106
+ node art-workshop.mjs edit run --plan .cache/edit-plan.json --dry
107
+ node art-workshop.mjs edit run --plan .cache/edit-plan.json
108
+ ```
109
+
110
+ 编辑默认保留原图风格,不自动读取工程默认核心或替换背景。目标风格须明确绑定 core,此时不能再写 style 修改或保留。原图哈希写入计划,原图改变后须重新预演。示例任务将已有 skill-01 改成纯白背景,保留主体、效果和构图。
111
+
112
+ ## 预演与验收
113
+
114
+ plan 与 run --dry 均不调用远程生图,分别返回完整编译快照与选定项实际请求参数,不生成图片。分析 --dry 返回预计请求,实际远程调用数为 0。
115
+
116
+ 实际 run 保存图片、输入和输出哈希、失败记录。人工分别检查 content/style/asset,产物完整、生成成功且三个维度全部 pass 才能 select。check 汇总人工验收,不自动评价图像。
117
+
118
+ ```powershell
119
+ node art-workshop.mjs check <runId> --out .cache/review.json
120
+ # 编辑 review 的 content/style/asset 为 pass/fail/pending,并填写 reason。
121
+ node art-workshop.mjs check <runId> --review .cache/review.json
122
+ node art-workshop.mjs select <runId> --item skill-01 --variant base --review .cache/review.json
123
+ node art-workshop.mjs compare .cache/plan-a.json .cache/plan-b.json
124
+ node --test tests/art-workshop.test.mjs
125
+ ```
126
+
127
+ 依赖 Node.js 与已配置的 bailian-cli。历史图片保留供对照,旧配置和旧计划接口不再支持。真实模型效果需另行实测。
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ import {readdirSync,existsSync} from 'node:fs';
3
+ import {join,resolve} from 'node:path';
4
+ import {loadJob,loadProject} from './lib/project.mjs';
5
+ import {referenceRoot,ensureReferenceDirectories,referenceGuide} from './lib/refs.mjs';
6
+ import {loadSettings,initSettings,externalPath} from './lib/settings.mjs';
7
+ import {readJson,writeJson} from './lib/shared.mjs';
8
+ import {analyzeStyle} from './lib/analyze.mjs';
9
+ import {validateReport,freezeCore,loadCore} from './lib/core.mjs';
10
+ import {compileGenerate} from './lib/generate.mjs';
11
+ import {compileEdit} from './lib/edit.mjs';
12
+ import {validatePlan,selectItems} from './lib/plan.mjs';
13
+ import {executePlan,checkRun} from './lib/executor.mjs';
14
+ import {agentIndex,agentDocs,syncSkill,autoSync} from './lib/agent.mjs';
15
+ const args=process.argv.slice(2),pos=[],options={};
16
+ if(args.length===1&&['--version','-V'].includes(args[0])){console.log(readJson(new URL('./package.json',import.meta.url)).version);process.exit(0);}
17
+ const flags=new Set(['dry','explore']);
18
+ const allowed=new Set(['config','workspace','output-dir','refs-dir','cache-dir','directory','project','input','out','report','note','core','job','plan','item','variant','offset','limit','review','file',...flags]);
19
+ for(let i=0;i<args.length;i++){if(args[i].startsWith('--')){const k=args[i].slice(2);if(!allowed.has(k)||k in options) throw new Error('未知或重复参数 '+k);options[k]=flags.has(k)?true:args[++i];if(options[k]===undefined) throw new Error('参数缺少值 '+k);}else pos.push(args[i]);}
20
+ const print=x=>console.log(JSON.stringify(x,null,2));
21
+ const settings=loadSettings({file:options.config?resolve(options.config):undefined,workspace:options.workspace,output:options['output-dir'],refs:options['refs-dir'],cache:options['cache-dir']});
22
+ const ROOT=settings.paths.workspace;
23
+ const path=x=>externalPath(resolve(ROOT,x),'资源文件');
24
+ function required(k){const value=options[k]??(k==='project'?settings.defaultProject:undefined);if(!value) throw new Error('需要 --'+k);return value;}
25
+ function manifestPath(value){const p=externalPath(resolve(settings.paths.output,value));return p.endsWith('.json')?p:join(p,'manifest.json');}
26
+ try {
27
+ const [module,action]=pos;
28
+ ensureReferenceDirectories(settings.paths.refs);
29
+ const selectedProject=options.project??(['refs','style','generate','edit'].includes(module)?settings.defaultProject:undefined);
30
+ const effectiveRefs=selectedProject?referenceRoot({workspace:ROOT,defaultRefsDir:settings.paths.refs,refsDir:options['refs-dir']?settings.paths.refs:undefined,project:loadProject(selectedProject,ROOT)}):settings.paths.refs;
31
+ ensureReferenceDirectories(effectiveRefs);
32
+ if(settings.autoSyncSkills&&!options.dry&&['style','generate','edit'].includes(module)&&['analyze','freeze','run'].includes(action)){try{autoSync();}catch(error){console.error('skill 自动同步失败:'+error.message+';可用 agent init 重试。');}}
33
+ if(module==='config'){
34
+ if(action==='path') console.log(settings.file);
35
+ else if(action==='show') print(settings);
36
+ else if(action==='init') print(initSettings(settings.file));
37
+ else throw new Error('未知 config 操作');
38
+ }
39
+ else if(module==='refs'){
40
+ if(action!=='guide') throw new Error('未知 refs 操作;使用 refs guide');
41
+ console.log(referenceGuide(effectiveRefs));
42
+ }
43
+ else if(module==='agent'){
44
+ if(action==='index') print({...agentIndex(undefined,ROOT),config:settings.file,paths:settings.paths});
45
+ else if(action==='docs') console.log(agentDocs());
46
+ else if(action==='init') print(syncSkill({directory:resolve(options.directory??process.cwd()),dry:options.dry}));
47
+ else throw new Error('未知 agent 操作');
48
+ }
49
+ else if(module==='list'){print((existsSync(join(ROOT,'projects'))?readdirSync(join(ROOT,'projects')):[]).map(id=>readJson(join(ROOT,'projects',id,'project.json'))));}
50
+ else if(module==='style'){
51
+ const projectId=required('project');
52
+ if(action==='analyze'){const result=analyzeStyle({projectId,input:readJson(path(required('input'))),out:options.out?path(options.out):undefined,root:ROOT,refsDir:options['refs-dir']?settings.paths.refs:undefined,defaultRefsDir:settings.paths.refs,cacheDir:join(settings.paths.cache,'analysis'),analysisModel:settings.analysisModel,dry:options.dry});print(result);}
53
+ else if(action==='validate') print(validateReport(readJson(path(required('report'))),projectId));
54
+ else if(action==='freeze') print(freezeCore({projectId,report:readJson(path(required('report'))),note:options.note,root:ROOT}));
55
+ else if(action==='show') print(loadCore(projectId,required('core'),ROOT));
56
+ else throw new Error('未知 style 操作');
57
+ }else if(['generate','edit'].includes(module)){
58
+ if(action==='show') print(loadJob(required('project'),required('job'),module,ROOT));
59
+ else if(['plan','run'].includes(action)){
60
+ let plan;
61
+ if(options.plan){if(action!=='run'||['project','job','core','explore'].some(k=>options[k]!==undefined)) throw new Error('冻结计划不能同时调整来源;修改任务后重新 plan');plan=readJson(path(options.plan));validatePlan(plan);if(plan.module!==module) throw new Error('计划模块不匹配');}
62
+ else plan=(module==='generate'?compileGenerate:compileEdit)({projectId:required('project'),jobId:required('job'),coreId:options.core,root:ROOT,localExecution:settings.execution});
63
+ if(action==='plan'){if(options.out) writeJson(path(options.out),plan);print(plan);}
64
+ else {const variant=options.variant??(options.explore?undefined:'base');const items=selectItems(plan,{item:options.item,variant,offset:options.offset===undefined?0:Number(options.offset),limit:options.limit===undefined?undefined:Number(options.limit)});const result=executePlan(plan,items,{outputRoot:settings.paths.output,dry:options.dry});if(result.manifest?.summary.failed) process.exitCode=1;}
65
+ }else throw new Error('未知模块操作');
66
+ }else if(['check','select'].includes(module)){
67
+ const file=manifestPath(action??required('file')),manifest=readJson(file);
68
+ const review=options.review?readJson(path(options.review)):manifest.review;
69
+ const rows=checkRun(manifest,file,review);
70
+ if(module==='check'){if(options.out) writeJson(path(options.out),rows);print(rows);}
71
+ else {const matched=rows.filter(x=>x.itemId===required('item')&&x.variantId===required('variant')&&(!options.file||x.file===options.file));if(matched.length!==1||!matched[0].accepted) throw new Error('只能选择唯一且全部验收通过的产物');manifest.review=rows;manifest.selections[options.item]=matched[0];writeJson(file,manifest);print(matched[0]);}
72
+ }else if(module==='compare'){const read=value=>{const data=readJson(path(value));const plan=data.plan??data;validatePlan(plan);return plan;};const a=read(action),b=read(pos[2]);print({sameCore:a.sources.coreHash===b.sources.coreHash,execution:{before:a.execution,after:b.execution},items:b.items.map(x=>({itemId:x.itemId,variantId:x.variantId,changed:a.items.find(y=>y.itemId===x.itemId&&y.variantId===x.variantId)?.inputHash!==x.inputHash}))});}
73
+ else if(!module||module==='help') console.log('art-workshop: config path/show/init | refs guide | agent index/docs/init | list | style analyze/validate/freeze/show | generate show/plan/run | edit show/plan/run | check/select RUN | compare PLAN PLAN');
74
+ else throw new Error('未知模块或旧入口:'+module);
75
+ }catch(e){console.error(e.message);process.exitCode=1;}
@@ -0,0 +1,15 @@
1
+ # 核心冻结指导规则
2
+
3
+ 权威规则:rules/core-guidance.json。模型分析、配置校验和冻结记录共用这一份。
4
+
5
+ 1. 语言精炼:每条规则表达一个可执行要求,避免重复和修辞。
6
+ 2. 用词准确:统一术语,明确强度、范围与条件,不混用不同渲染机制。
7
+ 3. 前后一致:报告、推荐、冻结、正向和负向提示词、验收要求保持一致。
8
+ 4. 职责分明:核心定义视觉规律;资产定义背景和构图许可;需求定义主体、数量、动作与关系;执行定义模型和尺寸;编辑定义修改与保留。
9
+ 5. 单一来源:一个事实只有一个权威字段,提示词从结构化配置生成。
10
+ 6. 作用域明确:规则明确作用对象,题材适配不能覆盖全局渲染或冻结单张内容。
11
+ 7. 观察与建议分开:观察保留证据和置信度,建议进入推荐配置,不确定性显式列出。
12
+ 8. 跨内容复用:不把参考图偶然的颜色、数量、背景和布局冻结为普遍要求。
13
+ 9. 冻结可追溯:保留报告、规则、身份和哈希,冻结后不原地修改,任务明确选择基础核心。
14
+
15
+ 校验覆盖结构、枚举、已知语义组合、精炼度与常见职责越界,不能穷尽自然语言全部语义矛盾,冻结前仍需审阅。未解决的 conflicts 或 uncertainties 会阻止冻结。
package/lib/agent.mjs ADDED
@@ -0,0 +1,44 @@
1
+ import {existsSync,lstatSync,statSync,readFileSync,mkdirSync,writeFileSync,readdirSync} from 'node:fs';
2
+ import {join,resolve,relative,isAbsolute,dirname} from 'node:path';
3
+ import {homedir} from 'node:os';
4
+ import {loadProject} from './project.mjs';
5
+ import {TOOL_ROOT as ROOT,loadSettings} from './settings.mjs';
6
+ import {hash} from './shared.mjs';
7
+
8
+ export const AGENT_DIRS=['.codex/skills','.agents/skills','.claude/skills','.claude/skill','.cursor/skills','.gemini/skills','.agent/skills','.agent/skill','AgentHome/skills','.windsurf/skills','.trae/skills','.kilocode/skills','.roo/skills','.opencode/skills','.augment/skills','.kiro/skills','.amazonq/skills','.continue/skills'];
9
+ const files=['SKILL.md','agents/openai.yaml'];
10
+ function directory(path) {return existsSync(path)&&statSync(path).isDirectory();}
11
+ function regular(path) {if(existsSync(path)&&!lstatSync(path).isFile()) throw new Error(`同步目标不是普通文件:${path}`);}
12
+ export function syncSkill({directory:base,root=ROOT,dry=false,skillDirs}={}) {
13
+ if(!skillDirs&&(!base||!directory(resolve(base)))) throw new Error('技能同步目标目录不存在');
14
+ const source=join(root,'skills','art-workshop');
15
+ const content=Object.fromEntries(files.map(file=>[file,readFileSync(join(source,file),'utf8')]));
16
+ const runtime=JSON.stringify({entry:join(root,'art-workshop.mjs'),root},null,2)+'\n';
17
+ const targets=skillDirs??AGENT_DIRS.map(dir=>join(resolve(base),dir)).filter(directory);
18
+ const result={skill:'art-workshop',source,sourceHash:hash(content),dry,targets:[]};
19
+ for(const dir of [...new Set(targets.map(x=>resolve(x)))]) {
20
+ if(!directory(dir)) continue;
21
+ const target=join(dir,'art-workshop'),rel=relative(dir,target);
22
+ if(isAbsolute(rel)||rel.startsWith('..')) throw new Error('技能同步路径越界');
23
+ if(existsSync(target)&&(lstatSync(target).isSymbolicLink()||!lstatSync(target).isDirectory())) throw new Error(`技能目录不是普通目录:${target}`);
24
+ const destinations={...content,'runtime.json':runtime};
25
+ for(const file of Object.keys(destinations)) {
26
+ const parent=dirname(join(target,file));
27
+ if(existsSync(parent)&&lstatSync(parent).isSymbolicLink()) throw new Error(`技能子目录不能是链接:${parent}`);
28
+ regular(join(target,file));
29
+ }
30
+ const changed=Object.entries(destinations).some(([file,data])=>!existsSync(join(target,file))||readFileSync(join(target,file),'utf8')!==data);
31
+ result.targets.push({directory:dir,target,action:changed?(dry?'would-update':'updated'):'current'});
32
+ if(!dry&&changed) for(const [file,data] of Object.entries(destinations)){const path=join(target,file);mkdirSync(dirname(path),{recursive:true});writeFileSync(path,data,'utf8');}
33
+ }
34
+ return result;
35
+ }
36
+ export function autoSync({root=ROOT,cwd=process.cwd(),home=homedir(),env=process.env}={}) {
37
+ const dirs=[...new Set([cwd,home].flatMap(base=>AGENT_DIRS.map(dir=>join(base,dir))))];
38
+ if(env.CODEX_HOME) dirs.push(join(env.CODEX_HOME,'skills'));
39
+ return syncSkill({root,skillDirs:dirs});
40
+ }
41
+ export function agentIndex(root=ROOT,workspace=loadSettings().paths.workspace) {
42
+ return {tool:'art-workshop',displayName:'美术工坊',root,workspace,config:loadSettings().file,entry:join(root,'art-workshop.mjs'),skill:{name:'art-workshop',source:join(root,'skills','art-workshop','SKILL.md'),automaticDiscovery:true},modules:[{name:'style',actions:['analyze','validate','freeze','show']},{name:'generate',actions:['show','plan','run']},{name:'edit',actions:['show','plan','run']},{name:'refs',actions:['guide']},{name:'agent',actions:['index','docs','init']}],utilities:['list','check','select','compare'],projects:(directory(join(workspace,'projects'))?readdirSync(join(workspace,'projects')):[]).filter(id=>directory(join(workspace,'projects',id))).map(id=>{const p=loadProject(id,workspace);return {id:p.id,cores:p.cores,defaultCore:p.defaultCore,jobs:readdirSync(join(workspace,'projects',id,'jobs')).filter(x=>x.endsWith('.json')).map(x=>x.slice(0,-5))};})};
43
+ }
44
+ export function agentDocs(root=ROOT) {return readFileSync(join(root,'README.md'),'utf8')+'\n'+readFileSync(join(root,'docs','core-guidance.md'),'utf8');}
@@ -0,0 +1,33 @@
1
+ import {join} from 'node:path';
2
+ import {externalPath} from './settings.mjs';
3
+ import {referenceRoot,ensureReferenceDirectories} from './refs.mjs';
4
+ import {hash,keys,id,text,texts,writeJson} from './shared.mjs';
5
+ import {ROOT,loadProject,sourcePath} from './project.mjs';
6
+ import {guidance,EXAMPLE_CONFIG,validateReport} from './core.mjs';
7
+ import {runBl,sha256File,extractText,extractJson,cacheRead,cacheWrite} from './bl.mjs';
8
+ export function analyzeStyle({projectId,input,out,root=ROOT,refsDir,defaultRefsDir=join(root,'refs'),cacheDir=join(root,'.cache','analysis'),analysisModel,dry=false,runner=runBl}) {
9
+ externalPath(cacheDir,'缓存目录');if(out)externalPath(out,'报告输出');
10
+ const project=loadProject(projectId,root);
11
+ keys(input,['project','id','description','refs','constraints'],'analysis input');
12
+ if(input.project!==projectId) throw new Error('分析输入工程不匹配');id(input.id);text(input.description,'description',2000);texts(input.constraints,'constraints',{empty:true});
13
+ if(!Array.isArray(input.refs)) throw new Error('refs 必须为数组');
14
+ const effectiveRefs=ensureReferenceDirectories(referenceRoot({workspace:root,defaultRefsDir,refsDir,project}));
15
+ const refs=input.refs.map(ref=>{keys(ref,['path','scope','note'],'analysis ref');if(!['style','palette','shape','render'].includes(ref.scope)) throw new Error('参考范围非法');text(ref.note,'ref.note');const path=sourcePath(effectiveRefs,ref.path);return {...ref,path,hash:sha256File(path)};});
16
+ const model=analysisModel??project.analysisModel;
17
+ const rules=guidance(),provenance={model,inputHash:hash(input),refs,guidanceHash:hash(rules)};
18
+ const prompt=`按照顶层规则分析并推荐风格。只返回 JSON,不自动冻结。参考图的内容与背景不得误写为风格约束。不能确认的地方写入 uncertainties;矛盾写入 conflicts。\n规则:${JSON.stringify(rules)}\n输入:${JSON.stringify(input)}\n报告格式:${JSON.stringify({schema:'art-workshop/style-report',project:projectId,id:input.id,summary:'简洁风格摘要',observations:[{source:'语言或图片路径',scope:'style',feature:'观察特征',evidence:'证据',confidence:0.9}],recommendation:EXAMPLE_CONFIG,conflicts:[],uncertainties:[]})}\nrecommendation 严格使用该结构与枚举;示例值仅说明结构,必须根据证据重新判断。domains 只定义相关题材表现,不写数量、背景、构图、模型和尺寸。`;
19
+ const contract='允许枚举:medium=illustration/painting/pixel-art/photography;shape.contour=rounded/angular/mixed;shape.detail=low/medium/high;shading=cel/flat/smooth/painterly/pixel;toneSteps=1至8整数(smooth/painterly 为 null);highlights=hard-edge/soft/none;finish=matte/glossy;texture=none/visible;lighting.direction=top-front/front/left/right/diffuse;contrast=low/medium/high;shadowShift=cool/warm/neutral;treatment=organic/hard-surface/emissive/structure/symbol。cel 至少两阶且无软高光、无纹理;flat 一阶;pixel-art 对应 pixel;photography 对应 smooth 且无描边。outline.width 为画幅宽度比0至0.03,关闭描边时为0。颜色为 #RRGGBB。signature 不超过80字,摘要不超过300字。';
20
+ const fullPrompt=prompt+'\n'+contract;
21
+ const requests=refs.map(ref=>['vision','describe','--image',ref.path,'--model',model,'--prompt',refs.length===1?fullPrompt:`观察此图的 ${ref.scope},${ref.note}。区分风格、内容、资产规格,列出证据及不确定性。`]);
22
+ if(refs.length!==1) requests.push(['text','chat','--model',model,'--message',fullPrompt]);
23
+ if(dry) return {dry:true,remoteCalls:0,plannedCalls:requests.length,provenance,requests};
24
+ const key=hash({input,provenance,fullPrompt});let report=cacheRead(cacheDir,key);
25
+ if(!report) {
26
+ let response;
27
+ if(refs.length===1) response=runner(requests[0]);
28
+ else {const observations=requests.slice(0,-1).map(args=>extractText(runner(args)).join('\n'));const args=[...requests.at(-1)];args[args.length-1]+='\n参考观察:'+JSON.stringify(observations);response=runner(args);}
29
+ report=extractJson(extractText(response).join('\n'));if(!report) throw new Error('模型未返回有效风格报告 JSON');
30
+ report.provenance=provenance;validateReport(report,projectId);cacheWrite(cacheDir,key,report);
31
+ }
32
+ validateReport(report,projectId);if(out) writeJson(out,report);return report;
33
+ }
package/lib/bl.mjs ADDED
@@ -0,0 +1,81 @@
1
+ /**
2
+ * bl 调用封装 —— 全部通过 execFile 传数组参数,绝不经过 shell。
3
+ * 背景:Windows 下 shell:true 会把带空格/中文的 prompt 拆散;git bash 会静默丢弃参数。
4
+ * 唯一可靠的做法是直接 node 入口脚本 + 数组参数。
5
+ */
6
+ import { execFileSync } from "node:child_process";
7
+ import { createHash } from "node:crypto";
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+
11
+ let BL_ENTRY = null;
12
+
13
+ /** 定位 bailian-cli 入口脚本(绕开 .ps1/.cmd shim 与 shell) */
14
+ export function resolveBlEntry() {
15
+ if (BL_ENTRY) return BL_ENTRY;
16
+ if (process.env.BL_BIN) return (BL_ENTRY = process.env.BL_BIN);
17
+ // Windows 上先看 APPDATA 标准位置,避免为了找入口去 spawn npm(会触发 DEP0190 噪音)
18
+ const cands = [];
19
+ if (process.env.APPDATA) cands.push(join(process.env.APPDATA, "npm", "node_modules", "bailian-cli", "dist", "bailian.mjs"));
20
+ for (const p of cands) if (existsSync(p)) return (BL_ENTRY = p);
21
+ // 兜底:非标准安装位置才去问 npm
22
+ try {
23
+ const root = execFileSync("npm", ["root", "-g"], {
24
+ encoding: "utf8", shell: process.platform === "win32", stdio: ["ignore", "pipe", "ignore"],
25
+ }).trim();
26
+ const p = join(root, "bailian-cli", "dist", "bailian.mjs");
27
+ if (existsSync(p)) return (BL_ENTRY = p);
28
+ } catch { /* npm 不可用 */ }
29
+ for (const p of cands) if (existsSync(p)) return (BL_ENTRY = p);
30
+ throw new Error("找不到 bailian-cli 入口;请设置 BL_BIN 指向 bailian-cli/dist/bailian.mjs");
31
+ }
32
+
33
+ /**
34
+ * 运行 bl。默认追加 --output json。
35
+ * dry=true 追加 --dry-run(仅生成类命令有效;查询类命令会忽略它)。
36
+ * parse=false 返回原始字符串(部分命令输出不是 JSON)。
37
+ */
38
+ export function runBl(args, { dry = false, parse = true } = {}) {
39
+ const full = [...args, "--output", "json"];
40
+ if (dry) full.push("--dry-run");
41
+ const out = execFileSync(process.execPath, [resolveBlEntry(), ...full], {
42
+ encoding: "utf8", maxBuffer: 64 * 1024 * 1024,
43
+ });
44
+ if (!parse) return out;
45
+ try { return JSON.parse(out); } catch { return { _raw: out }; }
46
+ }
47
+
48
+ export function sha256File(p) {
49
+ return createHash("sha256").update(readFileSync(p)).digest("hex");
50
+ }
51
+
52
+ /** 内容寻址缓存:key = 文件内容哈希,保证同一张图只描述一次 */
53
+ export function cacheRead(cacheDir, key) {
54
+ const f = join(cacheDir, key + ".json");
55
+ if (!existsSync(f)) return null;
56
+ try { return JSON.parse(readFileSync(f, "utf8")); } catch { return null; }
57
+ }
58
+
59
+ export function cacheWrite(cacheDir, key, value) {
60
+ mkdirSync(cacheDir, { recursive: true });
61
+ writeFileSync(join(cacheDir, key + ".json"), JSON.stringify(value, null, 2), "utf8");
62
+ }
63
+
64
+ /** 从任意形状的响应里捞出所有文本(bl 输出结构可能随版本变化,保持防御性) */
65
+ export function extractText(node, acc = []) {
66
+ if (node == null) return acc;
67
+ if (typeof node === "string") { acc.push(node); return acc; }
68
+ if (Array.isArray(node)) { for (const v of node) extractText(v, acc); return acc; }
69
+ if (typeof node === "object") { for (const v of Object.values(node)) extractText(v, acc); return acc; }
70
+ return acc;
71
+ }
72
+
73
+ /** 从模型回复里抠出第一个 JSON 对象(容忍代码块包裹与前后废话) */
74
+ export function extractJson(text) {
75
+ const body = String(text).replace(/^[\s\S]*?```(?:json)?/m, "").replace(/```[\s\S]*$/, "");
76
+ const src = body.includes("{") ? body : String(text);
77
+ const start = src.indexOf("{");
78
+ const end = src.lastIndexOf("}");
79
+ if (start === -1 || end <= start) return null;
80
+ try { return JSON.parse(src.slice(start, end + 1)); } catch { return null; }
81
+ }
package/lib/core.mjs ADDED
@@ -0,0 +1,124 @@
1
+ import { existsSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { hash, readJson, id, keys, text, texts, integer, choice, hex, writeJson } from './shared.mjs';
4
+ import { ROOT, loadProject, projectPath } from './project.mjs';
5
+ import { TOOL_ROOT } from './settings.mjs';
6
+
7
+ export const EXAMPLE_CONFIG = {
8
+ medium: 'illustration',
9
+ shape: { contour: 'rounded', detail: 'low' },
10
+ render: { shading: 'cel', toneSteps: 2, outline: { enabled: true, color: '#34445C', width: 0.004 }, highlights: 'hard-edge', finish: 'matte', texture: 'none' },
11
+ lighting: { direction: 'top-front', contrast: 'medium' },
12
+ color: { preserveIdentity: true, shadowShift: 'cool' },
13
+ domains: { cell: { treatment: 'organic', signature: '保留圆润生物轮廓,科幻点缀仅作用于自身表面。' } }
14
+ };
15
+ export function guidance() { return readJson(join(TOOL_ROOT, 'rules', 'core-guidance.json')); }
16
+
17
+ export function validateCoreConfig(config) {
18
+ keys(config, ['medium', 'shape', 'render', 'lighting', 'color', 'domains'], 'core');
19
+ choice(config.medium, ['illustration', 'painting', 'pixel-art', 'photography'], 'medium');
20
+ keys(config.shape, ['contour', 'detail'], 'shape');
21
+ choice(config.shape.contour, ['rounded', 'angular', 'mixed'], 'shape.contour');
22
+ choice(config.shape.detail, ['low', 'medium', 'high'], 'shape.detail');
23
+ const r = config.render;
24
+ keys(r, ['shading', 'toneSteps', 'outline', 'highlights', 'finish', 'texture'], 'render');
25
+ choice(r.shading, ['cel', 'flat', 'smooth', 'painterly', 'pixel'], 'render.shading');
26
+ choice(r.highlights, ['hard-edge', 'soft', 'none'], 'render.highlights');
27
+ choice(r.finish, ['matte', 'glossy'], 'render.finish');
28
+ choice(r.texture, ['none', 'visible'], 'render.texture');
29
+ keys(r.outline, ['enabled', 'color', 'width'], 'render.outline');
30
+ if (typeof r.outline.enabled !== 'boolean') throw new Error('outline.enabled 必须为布尔值');
31
+ hex(r.outline.color, 'outline.color');
32
+ if (typeof r.outline.width !== 'number' || !Number.isFinite(r.outline.width) || r.outline.width < 0 || r.outline.width > 0.03
33
+ || r.outline.enabled && r.outline.width === 0 || !r.outline.enabled && r.outline.width !== 0) throw new Error('描边开关与宽度矛盾');
34
+ if (['cel', 'flat', 'pixel'].includes(r.shading)) integer(r.toneSteps, 'toneSteps', 1, 8);
35
+ else if (r.toneSteps !== null) throw new Error('连续或笔触明暗不应同时冻结固定色阶数');
36
+ if (r.shading === 'cel' && (r.toneSteps < 2 || r.highlights === 'soft' || r.texture !== 'none')) throw new Error('赛璐璐与色阶、高光或纹理规则矛盾');
37
+ if (r.shading === 'flat' && r.toneSteps !== 1) throw new Error('平涂只能定义一个主色阶');
38
+ if (config.medium === 'pixel-art' && r.shading !== 'pixel' || config.medium !== 'pixel-art' && r.shading === 'pixel') throw new Error('像素媒介与渲染方式矛盾');
39
+ if (config.medium === 'photography' && (r.shading !== 'smooth' || r.outline.enabled)) throw new Error('摄影媒介与渲染或轮廓描边矛盾');
40
+ keys(config.lighting, ['direction', 'contrast'], 'lighting');
41
+ choice(config.lighting.direction, ['top-front', 'front', 'left', 'right', 'diffuse'], 'lighting.direction');
42
+ choice(config.lighting.contrast, ['low', 'medium', 'high'], 'lighting.contrast');
43
+ keys(config.color, ['preserveIdentity', 'shadowShift'], 'color');
44
+ if (typeof config.color.preserveIdentity !== 'boolean') throw new Error('preserveIdentity 必须为布尔值');
45
+ choice(config.color.shadowShift, ['cool', 'warm', 'neutral'], 'shadowShift');
46
+ if (!config.domains || typeof config.domains !== 'object' || Array.isArray(config.domains)) throw new Error('domains 必须为对象');
47
+ for (const [kind, domain] of Object.entries(config.domains)) {
48
+ id(kind, 'domain kind'); keys(domain, ['treatment', 'signature'], `domains.${kind}`);
49
+ choice(domain.treatment, ['organic', 'hard-surface', 'emissive', 'structure', 'symbol'], 'domain.treatment');
50
+ text(domain.signature, 'domain.signature', 80);
51
+ if (/背景|居中|留白|画幅|水印|seed|模型|分辨率|只能出现|唯一主体|不得出现第二|必须.*(?:红色|蓝色|绿色|白色|黑色)/i.test(domain.signature)) throw new Error('题材描述越过职责边界');
52
+ }
53
+ return config;
54
+ }
55
+
56
+ export function validateReport(report, projectId) {
57
+ keys(report, ['schema', 'project', 'id', 'summary', 'observations', 'recommendation', 'conflicts', 'uncertainties', 'provenance'], 'report');
58
+ if (report.schema !== 'art-workshop/style-report' || report.project !== projectId) throw new Error('风格报告身份不匹配');
59
+ id(report.id, 'report.id'); text(report.summary, 'report.summary', 300);
60
+ if (!Array.isArray(report.observations)) throw new Error('observations 必须为数组');
61
+ for (const item of report.observations) {
62
+ keys(item, ['source', 'scope', 'feature', 'evidence', 'confidence'], 'observation');
63
+ text(item.source, 'source', 1024); choice(item.scope, ['style', 'content', 'asset'], 'scope');
64
+ text(item.feature, 'feature'); text(item.evidence, 'evidence');
65
+ if (!Number.isFinite(item.confidence) || item.confidence < 0 || item.confidence > 1) throw new Error('confidence 必须在 0~1');
66
+ }
67
+ texts(report.conflicts, 'conflicts', { empty: true }); texts(report.uncertainties, 'uncertainties', { empty: true });
68
+ validateCoreConfig(report.recommendation); return report;
69
+ }
70
+
71
+ export function freezeCore({ projectId, report, root = ROOT, note = '确认采用此报告推荐配置' }) {
72
+ const project = loadProject(projectId, root); validateReport(report, projectId);
73
+ if (report.conflicts.length || report.uncertainties.length) throw new Error('报告仍有冲突或未确定项;处理后再冻结');
74
+ const body = { schema: 'art-workshop/core', project: projectId, id: report.id,
75
+ guidance: guidance(root), config: report.recommendation, report, approvedAt: new Date().toISOString(), approvalNote: text(note, 'approvalNote') };
76
+ const core = { ...body, coreHash: hash(body) };
77
+ const path = projectPath(root, projectId, 'cores', report.id);
78
+ if (existsSync(path)) throw new Error('核心已冻结,不能覆写;新风格请使用新身份');
79
+ mkdirSync(dirname(path), { recursive: true });
80
+ writeFileSync(path, JSON.stringify(core, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' });
81
+ if (!project.cores.includes(report.id)) project.cores.push(report.id);
82
+ if (!project.defaultCore) project.defaultCore = report.id;
83
+ try { writeJson(join(root, 'projects', projectId, 'project.json'), project); }
84
+ catch (error) { unlinkSync(path); throw error; }
85
+ return core;
86
+ }
87
+ export function loadCore(projectId, coreId, root = ROOT) {
88
+ const project = loadProject(projectId, root);
89
+ if (!project.cores.includes(coreId)) throw new Error(`核心 ${coreId} 不属于工程 ${projectId}`);
90
+ const core = readJson(projectPath(root, projectId, 'cores', coreId));
91
+ const { coreHash, ...body } = core;
92
+ if (core.schema !== 'art-workshop/core' || core.project !== projectId || core.id !== coreId || hash(body) !== coreHash) throw new Error('冻结核心身份或哈希校验失败');
93
+ validateCoreConfig(core.config); return core;
94
+ }
95
+ export function selectCore(project, job, requested, root = ROOT) {
96
+ if (requested && job.core && requested !== job.core) throw new Error('指定核心与任务绑定冲突;请明确修改任务的 core');
97
+ const selected = requested ?? job.core ?? project.defaultCore;
98
+ if (!selected) throw new Error('未选定基础核心;请指定 core,不能猜测或跨工程回退');
99
+ return { core: loadCore(project.id, selected, root), source: requested ? '显式选择' : job.core ? '任务绑定' : '工程默认' };
100
+ }
101
+
102
+ const labels = { illustration: '数字插画', painting: '绘画', 'pixel-art': '像素艺术', photography: '摄影',
103
+ rounded: '圆润', angular: '棱角明确', mixed: '圆润与棱角结合', low: '低', medium: '中', high: '高',
104
+ cel: '赛璐璐硬边明暗', flat: '平涂', smooth: '连续明暗', painterly: '笔触塑形', pixel: '像素色块',
105
+ 'hard-edge': '硬边色块高光', soft: '柔和高光', none: '无', matte: '哑光', glossy: '光泽', visible: '可见',
106
+ 'top-front': '顶偏前', front: '正前', left: '左侧', right: '右侧', diffuse: '漫射', cool: '偏冷', warm: '偏暖', neutral: '中性',
107
+ organic: '有机表面', 'hard-surface': '硬表面', emissive: '发光形态', structure: '连接结构', symbol: '简洁符号' };
108
+ export function corePrompt(core, kinds = []) {
109
+ const c = core.config, r = c.render;
110
+ const lines = [`媒介:${labels[c.medium]}。轮廓:${labels[c.shape.contour]};细节密度:${labels[c.shape.detail]}。`,
111
+ `明暗:${labels[r.shading]}${r.toneSteps === null ? '' : `,${r.toneSteps} 个主色阶`}。${labels[r.highlights]};表面${labels[r.finish]};纹理${labels[r.texture]}。`,
112
+ r.outline.enabled ? `轮廓描边:${r.outline.color},粗细约画幅宽度的 ${r.outline.width * 100}%。` : '不使用轮廓描边。',
113
+ `主光源:${labels[c.lighting.direction]};明暗对比:${labels[c.lighting.contrast]}。阴影偏色:${labels[c.color.shadowShift]}。`,
114
+ c.color.preserveIdentity ? '保留内容声明的身份色,色相分别按实体与效果声明执行。' : '色相按本张内容声明执行。'];
115
+ for (const kind of new Set(kinds)) {
116
+ const domain = c.domains[kind]; if (domain) lines.push(`${kind}:${labels[domain.treatment]};${domain.signature}`);
117
+ }
118
+ return lines.join('\n');
119
+ }
120
+ export function coreNegative(core) {
121
+ const r = core.config.render;
122
+ return [...(r.texture === 'none' ? ['表面纹理堆砌'] : []), ...(r.shading === 'cel' ? ['平滑明暗过渡', '柔和高光', '写实反射'] : []),
123
+ ...(core.config.shape.detail === 'low' ? ['繁复细节', '繁复纹样'] : [])].join(', ');
124
+ }
package/lib/edit.mjs ADDED
@@ -0,0 +1,32 @@
1
+ import {keys,id,text,texts,integer,hash} from './shared.mjs';
2
+ import {ROOT,loadProject,loadJob,sourcePath} from './project.mjs';
3
+ import {loadCore,corePrompt,coreNegative} from './core.mjs';
4
+ import {execution,finishPlan} from './plan.mjs';
5
+ import {background} from './presentation.mjs';
6
+ import {sha256File} from './bl.mjs';
7
+ const targets=['background','style','shape','color','composition','content','detail','text'];
8
+ export function compileEdit({projectId,jobId,coreId,root=ROOT,localExecution={}}) {
9
+ const project=loadProject(projectId,root),job=loadJob(projectId,jobId,'edit',root);
10
+ keys(job,['project','kind','core','execution','items'],'edit job');
11
+ if(coreId&&job.core&&coreId!==job.core) throw new Error('核心与编辑任务绑定冲突');
12
+ const selected=coreId??job.core,core=selected?loadCore(projectId,selected,root):null,refs=[],items=[],ids=new Set();
13
+ if(!Array.isArray(job.items)||!job.items.length) throw new Error('编辑 items 必须非空');
14
+ for(const source of job.items) {
15
+ keys(source,['id','source','changes','preserve','mustRead','seed'],'edit item');id(source.id);
16
+ if(ids.has(source.id)) throw new Error('编辑 item ID 重复');ids.add(source.id);
17
+ const path=sourcePath(root,source.source),fileHash=sha256File(path);refs.push({path,hash:fileHash});
18
+ if(!source.changes?.length||!Array.isArray(source.preserve)) throw new Error('编辑必须明确 changes 和 preserve');
19
+ const changed=new Set(),preserved=new Set();
20
+ const render=(row,set,isChange)=>{
21
+ keys(row,['target','instruction','value'],'edit scope'); if(!targets.includes(row.target)||set.has(row.target)) throw new Error('编辑范围非法或重复');set.add(row.target);
22
+ if(isChange&&row.target==='background') {keys(row,['target','value'],'background change'); return background(row.value,true);}
23
+ keys(row,['target','instruction'],'edit instruction');return `${row.target}:${text(row.instruction,'instruction')}。`;
24
+ };
25
+ const changes=source.changes.map(x=>render(x,changed,true)),preserve=source.preserve.map(x=>render(x,preserved,false));
26
+ if([...changed].some(x=>preserved.has(x))) throw new Error('修改与保留范围冲突');
27
+ if(core&&(changed.has('style')||preserved.has('style'))) throw new Error('绑定核心时,风格由核心负责,不能再声明修改或保留原风格');
28
+ texts(source.mustRead,'mustRead');const seed=source.seed??parseInt(hash([projectId,jobId,source.id]).slice(0,7),16);integer(seed,'seed');
29
+ items.push({itemId:source.id,variantId:'base',seed,brief:source,prompt:`基于输入原图编辑。未声明修改的部分保持原样。\n【修改】\n${changes.join('\n')}\n【保留】\n${preserve.join('\n')}${core?'\n【目标风格核心】\n'+corePrompt(core):''}`,negativeBlock:core?coreNegative(core):'',imageArgs:[path],checks:{content:source.mustRead,style:core?[corePrompt(core)]:['原图风格保持一致'],asset:changes.concat(preserve)}});
30
+ }
31
+ return finishPlan({module:'edit',project:projectId,job:jobId,execution:execution(project,job.execution,localExecution),sources:{core:core?.id??null,coreHash:core?.coreHash??null,selection:selected?'编辑显式绑定':'保留原图'},snapshots:{project,core,job},refs,items});
32
+ }
@@ -0,0 +1,112 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from 'node:fs';
2
+ import { join, dirname, resolve, relative, isAbsolute } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { buildArgs, validatePlan } from './plan.mjs';
5
+ import { hash, writeJson } from './shared.mjs';
6
+ export { validatePlan } from './plan.mjs';
7
+ export { writeJson } from './shared.mjs';
8
+ import { runBl, sha256File, resolveBlEntry } from './bl.mjs';
9
+ import {loadSettings,externalPath} from './settings.mjs';
10
+
11
+ function runtimeVersion() {
12
+ try { return JSON.parse(readFileSync(join(dirname(dirname(resolveBlEntry())), 'package.json'), 'utf8')).version ?? 'unknown'; }
13
+ catch { return 'unknown'; }
14
+ }
15
+ export function executePlan(plan, items, { outputRoot=loadSettings().paths.output, dry = false, runner = runBl, log = console.log } = {}) {
16
+ validatePlan(plan);
17
+ if (!items.length) throw new Error('没有选中任何计划项');
18
+ for (const item of items) if (!plan.items.some(x => x.inputHash === item.inputHash)) throw new Error('执行项不属于该计划');
19
+ for (const ref of plan.refs) { externalPath(ref.path,'原图/参考图'); if (!existsSync(ref.path) || sha256File(ref.path) !== ref.hash) throw new Error(`参考图已变化:${ref.path}`); }
20
+ externalPath(outputRoot,'输出目录');
21
+ if (dry) {
22
+ const requests = items.map(item => ({ itemId: item.itemId, variantId: item.variantId, seed: item.seed,
23
+ inputHash: item.inputHash, args: buildArgs(plan, item, join(outputRoot,'<runId>'), `${item.itemId}--${item.variantId}`) }));
24
+ log(JSON.stringify({ dry: true, remoteCalls: 0, planHash: plan.planHash, requests }, null, 2));
25
+ return { dry: true, requests };
26
+ }
27
+ const runId = `${plan.job.replaceAll('/', '-')}-${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID().slice(0, 8)}`;
28
+ const runDir = join(outputRoot, runId);
29
+ mkdirSync(runDir, { recursive: true });
30
+ const manifest = { schema: 'art-workshop/run', runId, plan, planHash: plan.planHash, blVersion: runner === runBl ? runtimeVersion() : 'injected',
31
+ startedAt: new Date().toISOString(), items: [], review: [], selections: {} };
32
+ const manifestPath = join(runDir, 'manifest.json');
33
+ const persist = () => {
34
+ manifest.summary = { completed: manifest.items.filter(x => x.status !== 'running').length, expected: items.length,
35
+ ok: manifest.items.filter(x => x.ok).length, failed: manifest.items.filter(x => x.status === 'failed').length };
36
+ writeJson(manifestPath, manifest);
37
+ };
38
+ persist();
39
+ for (const item of items) {
40
+ const prefix = `${item.itemId}--${item.variantId}`;
41
+ const args = buildArgs(plan, item, runDir, prefix);
42
+ const record = { ...item, args, ok: false, status: 'running', files: [], urls: [], outputHashes: {} };
43
+ manifest.items.push(record); persist();
44
+ const before = new Set(readdirSync(runDir));
45
+ try {
46
+ const response = runner(args);
47
+ const fresh = readdirSync(runDir).filter(f => !before.has(f) && /\.(png|jpe?g|webp)$/i.test(f)).sort();
48
+ fresh.forEach((file, index) => {
49
+ const target = `${prefix}${index ? '--' + (index + 1) : ''}${file.slice(file.lastIndexOf('.'))}`;
50
+ if (file !== target) {
51
+ if (existsSync(join(runDir, target))) throw new Error(`输出文件已存在:${target}`);
52
+ renameSync(join(runDir, file), join(runDir, target));
53
+ }
54
+ record.files.push(target); record.outputHashes[target] = sha256File(join(runDir, target));
55
+ });
56
+ record.urls = response.urls ?? [];
57
+ if (record.files.length !== plan.execution.perValue) throw new Error(`期望 ${plan.execution.perValue} 张,实际 ${record.files.length} 张`);
58
+ record.ok = true; record.status = 'generated';
59
+ log(`✔ ${item.itemId}/${item.variantId} seed=${item.seed} → ${record.files.join(', ')}`);
60
+ } catch (e) {
61
+ record.status = 'failed'; record.error = String(e.message ?? e).slice(0, 1000);
62
+ log(`✗ ${item.itemId}/${item.variantId}:${record.error}`);
63
+ }
64
+ persist();
65
+ }
66
+ manifest.finishedAt = new Date().toISOString(); persist();
67
+ log(`manifest → ${manifestPath}`);
68
+ return { manifest, manifestPath, runDir };
69
+ }
70
+
71
+ export function outputPath(manifestPath, file) {
72
+ const base = dirname(resolve(manifestPath));
73
+ const path = resolve(base, file);
74
+ const rel = relative(base, path);
75
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('..\\') || rel.startsWith('../')) throw new Error('输出路径越界');
76
+ return path;
77
+ }
78
+
79
+ export function checkRun(manifest, manifestPath, review = manifest.review ?? []) {
80
+ validatePlan(manifest.plan);
81
+ for (const item of manifest.items) {
82
+ const expected = manifest.plan.items.find(x => x.itemId === item.itemId && x.variantId === item.variantId);
83
+ if (!expected || expected.inputHash !== item.inputHash) throw new Error('执行记录不属于原始计划');
84
+ for (const key of ['prompt', 'seed', 'checks', 'negativeBlock', 'imageArgs']) {
85
+ if (hash(item[key]) !== hash(expected[key])) throw new Error(`执行记录已改变:${item.itemId}.${key}`);
86
+ }
87
+ }
88
+ if (!Array.isArray(review)) throw new Error('review 必须为数组');
89
+ const keys = new Set();
90
+ for (const row of review) {
91
+ // check 导出的失败记录也可保留在人工模板中,但不能被批准。
92
+ if (row.file === null && manifest.items.some(i => i.itemId === row.itemId && i.variantId === row.variantId && !i.files.length && !i.ok)) {
93
+ if (row.accepted === true) throw new Error('无产物的失败项不能通过验收');
94
+ continue;
95
+ }
96
+ const key = `${row.itemId}/${row.variantId}/${row.file}`;
97
+ if (keys.has(key)) throw new Error(`重复 review:${key}`);
98
+ keys.add(key);
99
+ if (!manifest.items.some(i => i.itemId === row.itemId && i.variantId === row.variantId && i.files.includes(row.file))) throw new Error(`review 未匹配产物:${key}`);
100
+ for (const dimension of ['content', 'style', 'asset']) {
101
+ if (!['pass', 'fail', 'pending'].includes(row[dimension])) throw new Error(`review.${dimension} 必须为 pass/fail/pending`);
102
+ }
103
+ }
104
+ return manifest.items.flatMap(item => item.files.length ? item.files.map(file => {
105
+ const path = outputPath(manifestPath, file);
106
+ const integrity = existsSync(path) && sha256File(path) === item.outputHashes[file];
107
+ const row = review.find(r => r.itemId === item.itemId && r.variantId === item.variantId && r.file === file);
108
+ return { itemId: item.itemId, variantId: item.variantId, file, path, integrity, generated: item.ok,
109
+ checks: item.checks, content: row?.content ?? 'pending', style: row?.style ?? 'pending', asset: row?.asset ?? 'pending',
110
+ reason: row?.reason ?? '', accepted: integrity && item.ok && ['content', 'style', 'asset'].every(k => row?.[k] === 'pass') };
111
+ }) : [{ itemId: item.itemId, variantId: item.variantId, file: null, generated: false, accepted: false, error: item.error }]);
112
+ }
@@ -0,0 +1,49 @@
1
+ import { readJson, keys, id, text, texts, integer, hash } from './shared.mjs';
2
+ import { ROOT,loadProject,loadJob,projectPath } from './project.mjs';
3
+ import {selectCore,corePrompt,coreNegative} from './core.mjs';
4
+ import {execution,finishPlan} from './plan.mjs';
5
+ import {presentation,assetPrompt} from './presentation.mjs';
6
+ export function compileGenerate({projectId,jobId,coreId,root=ROOT,localExecution={}}) {
7
+ const project=loadProject(projectId,root),job=loadJob(projectId,jobId,'generate',root);
8
+ keys(job,['project','kind','core','profile','execution','items'],'job');
9
+ const selected=selectCore(project,job,coreId,root),core=selected.core;
10
+ const profile=readJson(projectPath(root,projectId,'profiles',job.profile));
11
+ keys(profile,['project','id','name','constraints','defaults','allowedOverrides','presets','checks'],'profile');
12
+ if(profile.project!==projectId||profile.id!==job.profile) throw new Error('资产配置工程身份不匹配');
13
+ keys(profile.constraints,['text','frame','scene','crop','shadow'],'constraints');
14
+ for(const v of Object.values(profile.constraints)) if(typeof v!=='boolean') throw new Error('资产约束必须为布尔值');
15
+ texts(profile.checks,'profile.checks');
16
+ const items=[],ids=new Set();
17
+ if(!Array.isArray(job.items)||!job.items.length) throw new Error('任务 items 必须非空');
18
+ for(const source of job.items) {
19
+ keys(source,['id','seed','intent','entities','effects','relations','composition','mustRead','variants'],'item');
20
+ id(source.id); if(ids.has(source.id)) throw new Error('item ID 重复'); ids.add(source.id);
21
+ text(source.intent,'intent'); texts(source.mustRead,'mustRead');
22
+ if(!Array.isArray(source.entities)||!source.entities.length) throw new Error('entities 必须非空');
23
+ const objectIds=new Set(), lines=[];
24
+ for(const e of source.entities) {
25
+ keys(e,['id','kind','appearance','color','role','count','action'],'entity'); id(e.id); id(e.kind);
26
+ if(objectIds.has(e.id)) throw new Error('实体 ID 重复'); objectIds.add(e.id);
27
+ if(!core.config.domains[e.kind]) throw new Error(`核心缺少题材规则 ${e.kind}`);
28
+ if(!['primary','support'].includes(e.role)) throw new Error('实体角色不合法');
29
+ integer(e.count,'count',1,100); text(e.appearance,'appearance');text(e.color,'color'); if(e.action) text(e.action,'action');
30
+ lines.push(`${e.id}:${e.count} 个${e.appearance},${e.color},${e.role==='primary'?'主要':'辅助'}实体${e.action?','+e.action:''}。`);
31
+ }
32
+ for(const e of source.effects??[]) {
33
+ keys(e,['id','kind','target','color','relation','count'],'effect');id(e.id);
34
+ if(objectIds.has(e.id)||!source.entities.some(x=>x.id===e.target)) throw new Error('效果 ID 重复或目标不存在'); objectIds.add(e.id);
35
+ for(const k of ['kind','color','relation']) text(e[k],k); integer(e.count,'count',1,100);
36
+ lines.push(`${e.id}:${e.count} 个${e.color}${e.kind},作用于 ${e.target};${e.relation}。`);
37
+ }
38
+ for(const r of source.relations??[]) {keys(r,['from','to','action'],'relation'); if(!objectIds.has(r.from)||!objectIds.has(r.to)) throw new Error('关系目标不存在');lines.push(`${r.from} → ${r.to}:${text(r.action,'action')}。`);}
39
+ const variants=source.variants?.length?source.variants:[{id:'base'}],variantIds=new Set();
40
+ for(const variant of variants) {
41
+ keys(variant,['id','composition','seed'],'variant');id(variant.id); if(variantIds.has(variant.id)) throw new Error('variant ID 重复');variantIds.add(variant.id);
42
+ const p=presentation(profile,{...source.composition,...variant.composition});
43
+ if(!objectIds.has(p.value.focalTarget)) throw new Error('视觉焦点不存在');
44
+ const seed=variant.seed??source.seed??parseInt(hash([projectId,jobId,source.id]).slice(0,7),16); integer(seed,'seed');
45
+ items.push({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${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]}});
46
+ }
47
+ }
48
+ 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});
49
+ }
package/lib/plan.mjs ADDED
@@ -0,0 +1,35 @@
1
+ import { hash, keys, integer, text } from './shared.mjs';
2
+ export function execution(project, overrides = {},local = {}) {
3
+ keys(overrides, ['model','size','promptExtend','perValue','watermark'], 'execution');
4
+ const e = {model:'qwen-image-3.0-pro',size:'1024*1024',promptExtend:false,perValue:1,watermark:false,...project.execution,...local,...overrides};
5
+ keys(e, ['model','size','promptExtend','perValue','watermark'], 'execution');
6
+ text(e.model,'model'); if (!/^\d+\*\d+$/.test(e.size)) throw new Error('size 必须是明确像素尺寸');
7
+ const [w,h] = e.size.split('*').map(Number); integer(w,'width',256,4096); integer(h,'height',256,4096);
8
+ integer(e.perValue,'perValue',1,4);
9
+ for (const k of ['promptExtend','watermark']) if(typeof e[k] !== 'boolean') throw new Error(`${k} 必须为布尔值`);
10
+ return e;
11
+ }
12
+ export function finishPlan(body) {
13
+ const items = body.items.map(x => ({...x,inputHash:hash({...x,execution:body.execution})}));
14
+ const plan = {schema:'art-workshop/plan',...body,items}; return {...plan,planHash:hash(plan)};
15
+ }
16
+ export function validatePlan(plan) {
17
+ if(plan.schema !== 'art-workshop/plan' || !['generate','edit'].includes(plan.module) || !plan.items?.length) throw new Error('不是有效的当前计划');
18
+ const {planHash,...body} = plan; if(hash(body)!==planHash) throw new Error('计划已改变;请修改任务后重新预演');
19
+ for(const {inputHash,...item} of plan.items) if(hash({...item,execution:plan.execution})!==inputHash) throw new Error('计划项校验失败');
20
+ }
21
+ export function selectItems(plan,{item,variant,offset=0,limit}={}) {
22
+ integer(offset,'offset'); if(limit!==undefined) integer(limit,'limit',1);
23
+ let result=plan.items.filter(x=>(!item||x.itemId===item)&&(!variant||x.variantId===variant));
24
+ if(!result.length) throw new Error('没有匹配的计划项');
25
+ const ids=[...new Set(result.map(x=>x.itemId))].slice(offset,limit===undefined?undefined:offset+limit);
26
+ return result.filter(x=>ids.includes(x.itemId));
27
+ }
28
+ export function buildArgs(plan,item,outDir,prefix) {
29
+ const e=plan.execution, args=['image',plan.module==='edit'?'edit':'generate'];
30
+ for(const path of item.imageArgs) args.push('--image',path);
31
+ args.push('--prompt',item.prompt,'--model',e.model,'--size',e.size,'--n',String(e.perValue));
32
+ if(item.negativeBlock) args.push('--negative-prompt',item.negativeBlock);
33
+ args.push('--seed',String(item.seed),'--prompt-extend',String(e.promptExtend),'--watermark',String(e.watermark),'--out-dir',outDir,'--out-prefix',prefix);
34
+ return args;
35
+ }
@@ -0,0 +1,21 @@
1
+ import { keys, choice, text, hex } from './shared.mjs';
2
+ export function background(value,allowScene=false) {
3
+ keys(value,['type','color','from','to','description'],'background');
4
+ if(value.type==='solid') { keys(value,['type','color'],'background'); return `纯色背景 ${hex(value.color,'background.color')},整张背景颜色均匀,无渐变、光晕或纹理。`; }
5
+ if(value.type==='gradient') { keys(value,['type','from','to'],'background'); return `渐变背景,从 ${hex(value.from,'from')} 到 ${hex(value.to,'to')}。`; }
6
+ if(value.type==='scene'&&allowScene) { keys(value,['type','description'],'background'); return `场景背景:${text(value.description,'scene')}。`; }
7
+ throw new Error('背景类型不支持或资产不允许场景');
8
+ }
9
+ export function presentation(profile,overrides={}) {
10
+ keys(overrides,['preset','view','direction','occupancy','effectIntensity','background','focalTarget'],'composition');
11
+ const c={...profile.defaults,...overrides};
12
+ for(const k of ['preset','view','direction','effectIntensity']) choice(c[k],profile.allowedOverrides[k],k);
13
+ const range=profile.allowedOverrides.occupancy;
14
+ if(!Number.isFinite(c.occupancy)||c.occupancy<range.min||c.occupancy>range.max) throw new Error('主体占比越界');
15
+ const bg=background(c.background,profile.constraints.scene);
16
+ return {value:c,prompt:`${profile.presets[c.preset]}。视角:${c.view};方向:${c.direction};整体占画幅约 ${c.occupancy*100}%;效果强度:${c.effectIntensity}。\n${bg}`,background:bg};
17
+ }
18
+ export function assetPrompt(profile) {
19
+ const c=profile.constraints;
20
+ return [profile.name,c.text?'允许需求声明的文字':'无文字',c.frame?'允许需求声明的外框':'画幅无装饰外框',c.crop?'允许裁切':'主体和效果边缘完整,四周留出空间',c.shadow?'主体正下方简洁投影':'不添加地面投影'].join(';')+'。';
21
+ }
@@ -0,0 +1,30 @@
1
+ import { join, resolve } from 'node:path';
2
+ import { loadSettings,externalPath } from './settings.mjs';
3
+ import { readJson, id, keys, text } from './shared.mjs';
4
+
5
+ export const ROOT = loadSettings().paths.workspace;
6
+ export function projectPath(root, projectId, folder, name) {
7
+ id(projectId, 'project'); id(name, folder);
8
+ return externalPath(join(root, 'projects', projectId, folder, name + '.json'));
9
+ }
10
+ export function loadProject(projectId, root = ROOT) {
11
+ id(projectId, 'project');
12
+ const project = readJson(externalPath(join(root, 'projects', projectId, 'project.json')));
13
+ keys(project, ['id', 'name', 'analysisModel', 'execution', 'cores', 'defaultCore', 'refsDir'], 'project');
14
+ if (project.id !== projectId) throw new Error('工程身份不匹配');
15
+ text(project.name, 'project.name'); text(project.analysisModel, 'analysisModel');
16
+ if (!Array.isArray(project.cores)) throw new Error('project.cores 必须为数组');
17
+ project.cores.forEach(x => id(x, 'core'));
18
+ if (new Set(project.cores).size !== project.cores.length) throw new Error('工程核心列表重复');
19
+ if (project.defaultCore !== null && !project.cores.includes(project.defaultCore)) throw new Error('defaultCore 不属于该工程');
20
+ return project;
21
+ }
22
+ export function loadJob(projectId, jobId, module, root = ROOT) {
23
+ const job = readJson(projectPath(root, projectId, 'jobs', jobId));
24
+ if (job.project !== projectId || job.kind !== module) throw new Error('任务工程或模块不匹配');
25
+ return job;
26
+ }
27
+ export function sourcePath(root, path) {
28
+ text(path, 'source.path', 1024);
29
+ return externalPath(resolve(root, path),'资源');
30
+ }
package/lib/refs.mjs ADDED
@@ -0,0 +1,34 @@
1
+ import {existsSync,mkdirSync,statSync} from 'node:fs';
2
+ import {join,resolve} from 'node:path';
3
+ import {externalPath} from './settings.mjs';
4
+
5
+ export const REFERENCE_CATEGORIES=[
6
+ {directory:'style',purpose:'整体视觉语言:媒介、笔触、描边与统一画风',recommended:'同一画风的完整作品;轮廓清晰,主体与背景可区分,避免混合多种画风的拼图',scope:'style'},
7
+ {directory:'palette',purpose:'配色关系:主色、辅色、点缀色与冷暖',recommended:'色板或配色明确的作品;避免强烈滤镜、偏色照片与无法区分固有色的复杂光照',scope:'palette'},
8
+ {directory:'subject',purpose:'主体结构与辨识特征',recommended:'清晰的单主体、多角度或结构展示图;分析核心时只提取通用造型规律,具体身份写入单体需求',scope:'shape'},
9
+ {directory:'composition',purpose:'布局、视角、占比与留白',recommended:'构图清楚的示例、剪影或布局草图;具体布局写入资产配置或单体计划',scope:null},
10
+ {directory:'material',purpose:'表面材质、纹理、光泽与质感',recommended:'清晰的材质近景;光照适中,能分辨表面纹理与反射,避免过曝和重度压缩',scope:'render'},
11
+ {directory:'text',purpose:'字形、排版与文字装饰',recommended:'清晰可读的字体或排版样张;实际文字内容与排版要求写入单体需求',scope:null},
12
+ {directory:'pose',purpose:'动作、姿态与肢体关系',recommended:'完整主体的动作图或姿态草图;关节与接触关系清楚,具体动作写入单体需求',scope:null}
13
+ ];
14
+
15
+ export function referenceRoot({workspace,defaultRefsDir,refsDir,project}={}) {
16
+ return externalPath(refsDir??(project?.refsDir?resolve(workspace,project.refsDir):defaultRefsDir),'参考目录');
17
+ }
18
+
19
+ export function ensureReferenceDirectories(root) {
20
+ root=externalPath(root,'参考目录');
21
+ const paths=[root,...REFERENCE_CATEGORIES.map(category=>externalPath(join(root,category.directory),'参考分类目录'))];
22
+ for(const path of paths) if(existsSync(path)&&!statSync(path).isDirectory()) throw new Error(`参考目录位置被文件占用:${path}`);
23
+ for(const path of paths) mkdirSync(path,{recursive:true});
24
+ return root;
25
+ }
26
+
27
+ export function referenceGuide(root) {
28
+ return ['# 美术工坊参考图目录',`当前参考目录:${root}`,'',
29
+ '| 目录 | 作用 | 推荐图片 | 分析 scope |','| --- | --- | --- | --- |',
30
+ ...REFERENCE_CATEGORIES.map(x=>`| ${x.directory}/ | ${x.purpose} | ${x.recommended} | ${x.scope??'单体计划,不写入核心'} |`),'',
31
+ '目录仅用于整理素材,不自动识别、扫描、绑定或传给生图模型。风格分析须在输入 refs 中显式声明 path、scope 和 note;scope 支持 style/palette/shape/render,目录名不替代 scope。',
32
+ '相对参考路径从当前参考目录解析。工程可设置 refsDir;优先级为 --refs-dir → 工程 refsDir → 本地 paths.refs。',
33
+ '每次 CLI 配置生效时检查并补齐分类目录,包括 --dry;只创建缺少的目录,不移动或覆盖图片。预演仍不调用远程模型、不产生图片。'].join('\n');
34
+ }
@@ -0,0 +1,51 @@
1
+ import {existsSync,readFileSync,realpathSync} from 'node:fs';
2
+ import {execFileSync} from 'node:child_process';
3
+ import {homedir} from 'node:os';
4
+ import {dirname,basename,join,resolve,relative,isAbsolute} from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {readJson,writeJson,keys,text,id} from './shared.mjs';
7
+ import {execution} from './plan.mjs';
8
+ export const TOOL_ROOT=dirname(dirname(fileURLToPath(import.meta.url)));
9
+ export function downloadsDirectory({platform=process.platform,home=homedir(),env=process.env,knownFolder}={}) {
10
+ if(platform==='win32') {
11
+ try {
12
+ const read=knownFolder??(()=>JSON.parse(execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); $downloadPath = (Get-ItemProperty -LiteralPath 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders').'{374DE290-123F-4565-9164-39C4925E467B}'; $downloadPath | ConvertTo-Json -Compress"],{encoding:'utf8',windowsHide:true}).trim()));
13
+ const value=read();if(typeof value==='string'&&value.trim()){const expanded=value.replace(/%([^%]+)%/g,(_,name)=>Object.entries(env).find(([key])=>key.toLowerCase()===name.toLowerCase())?.[1]??'%'+name+'%');if(!expanded.includes('%'))return expanded;}
14
+ }catch{}
15
+ }
16
+ if(platform==='linux') {
17
+ const file=join(env.XDG_CONFIG_HOME??join(home,'.config'),'user-dirs.dirs');
18
+ if(existsSync(file)){const match=readFileSync(file,'utf8').match(/^XDG_DOWNLOAD_DIR="([^"]+)"/m);if(match){const value=match[1].replace(/\$\{HOME\}|\$HOME/g,home);if(!value.includes('$')&&isAbsolute(value))return resolve(value);}}
19
+ }
20
+ return join(home,'Downloads');
21
+ }
22
+ export function externalPath(value,label='路径') {
23
+ text(value,label,2048);const path=resolve(value);
24
+ let ancestor=path;const tail=[];while(!existsSync(ancestor)){const parent=dirname(ancestor);if(parent===ancestor)break;tail.unshift(basename(ancestor));ancestor=parent;}
25
+ const actual=existsSync(ancestor)?join(realpathSync(ancestor),...tail):path;
26
+ const rel=relative(realpathSync(TOOL_ROOT),actual);
27
+ if(rel===''||!isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..\\')&&!rel.startsWith('../'))throw new Error(`${label} 必须在工具目录之外:${path}`);
28
+ return path;
29
+ }
30
+ export function configFile(env=process.env,home=homedir(),platform=process.platform) {
31
+ const base=platform==='win32'?(env.APPDATA??join(home,'AppData','Roaming')):platform==='darwin'?join(home,'Library','Application Support'):(env.XDG_CONFIG_HOME??join(home,'.config'));
32
+ return externalPath(env.ART_WORKSHOP_CONFIG??join(base,'art-workshop','config.json'),'本地配置');
33
+ }
34
+ export function loadSettings({file=configFile(),workspace,output,refs,cache}={}) {
35
+ const base=join(downloadsDirectory(),'image.g');
36
+ const local=existsSync(file)?readJson(file):{};
37
+ keys(local,['paths','execution','analysisModel','defaultProject','autoSyncSkills'],'config');
38
+ keys(local.paths??{},['workspace','output','refs','cache'],'config.paths');
39
+ keys(local.execution??{},['model','size','promptExtend','perValue','watermark'],'config.execution');
40
+ execution({execution:{}},{},local.execution??{});
41
+ if(local.analysisModel!==undefined&&local.analysisModel!==null)text(local.analysisModel,'analysisModel');
42
+ if(local.defaultProject!==undefined&&local.defaultProject!==null)id(local.defaultProject,'defaultProject');
43
+ if(local.autoSyncSkills!==undefined&&typeof local.autoSyncSkills!=='boolean')throw new Error('autoSyncSkills 必须为布尔值');
44
+ const overrides={workspace,output,refs,cache},defaults={workspace:base,output:base,refs:join(base,'refs'),cache:join(base,'.cache')};
45
+ const paths=Object.fromEntries(Object.keys(defaults).map(key=>[key,externalPath(overrides[key]??local.paths?.[key]??defaults[key],key)]));
46
+ return {file:externalPath(file,'本地配置'),paths,execution:local.execution??{},analysisModel:local.analysisModel??null,defaultProject:local.defaultProject??null,autoSyncSkills:local.autoSyncSkills??true};
47
+ }
48
+ export function initSettings(file=configFile()) {
49
+ externalPath(file,'本地配置');if(existsSync(file))return loadSettings({file});
50
+ const {file:ignored,...config}=loadSettings({file});writeJson(file,config);return loadSettings({file});
51
+ }
package/lib/shared.mjs ADDED
@@ -0,0 +1,49 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs';
3
+ import { dirname } from 'node:path';
4
+
5
+ export function hash(value) {
6
+ const ordered = v => Array.isArray(v) ? v.map(ordered) : v && typeof v === 'object'
7
+ ? Object.fromEntries(Object.keys(v).sort().map(k => [k, ordered(v[k])])) : v;
8
+ return createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
9
+ }
10
+ export function readJson(path) {
11
+ try { return JSON.parse(readFileSync(path, 'utf8')); }
12
+ catch (e) { throw new Error(`读取 ${path} 失败:${e.message}`); }
13
+ }
14
+ export function writeJson(path, data) {
15
+ mkdirSync(dirname(path), { recursive: true });
16
+ const temporary = path + '.tmp-' + randomUUID();
17
+ writeFileSync(temporary, JSON.stringify(data, null, 2) + '\n', 'utf8');
18
+ renameSync(temporary, path);
19
+ }
20
+ export function keys(value, allowed, label) {
21
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} 必须为对象`);
22
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new Error(`${label} 不支持字段 ${key}`);
23
+ }
24
+ export function text(value, label, max = 160) {
25
+ if (typeof value !== 'string' || !value.trim() || value.length > max) throw new Error(`${label} 必须是 1~${max} 字的精炼文本`);
26
+ if (/\bTODO\b|<[^>]+>|待填写/.test(value)) throw new Error(`${label} 有未完成的占位符`);
27
+ return value;
28
+ }
29
+ export function id(value, label = 'id') {
30
+ if (typeof value !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(value)
31
+ || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value)) throw new Error(`${label} 必须使用小写字母、数字、连字符`);
32
+ return value;
33
+ }
34
+ export function integer(value, label, min = 0, max = 2147483647) {
35
+ if (!Number.isSafeInteger(value) || value < min || value > max) throw new Error(`${label} 必须为 ${min}~${max} 的整数`);
36
+ return value;
37
+ }
38
+ export function choice(value, values, label) {
39
+ if (!values.includes(value)) throw new Error(`${label} 必须为 ${values.join('/')}`);
40
+ return value;
41
+ }
42
+ export function texts(value, label, { empty = false, max = 160 } = {}) {
43
+ if (!Array.isArray(value) || (!empty && !value.length)) throw new Error(`${label} 必须为${empty ? '' : '非空'}数组`);
44
+ value.forEach(x => text(x, label, max)); return value;
45
+ }
46
+ export function hex(value, label) {
47
+ if (typeof value !== 'string' || !/^#[0-9a-f]{6}$/i.test(value)) throw new Error(`${label} 必须为 #RRGGBB`);
48
+ return value.toUpperCase();
49
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@kevlns/art-workshop",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "private": false,
5
+ "description": "美术工坊:统一风格的多工程图片生成与编辑工具",
6
+ "type": "module",
7
+ "bin": {
8
+ "art-workshop": "art-workshop.mjs"
9
+ },
10
+ "files": [
11
+ "art-workshop.mjs",
12
+ "lib/",
13
+ "rules/",
14
+ "skills/",
15
+ "scripts/sync-skill.mjs",
16
+ "README.md",
17
+ "docs/core-guidance.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "postinstall": "node scripts/sync-skill.mjs",
22
+ "skill:sync": "node scripts/sync-skill.mjs",
23
+ "test": "node scripts/test.mjs",
24
+ "pack:guard": "node scripts/pack-guard.mjs",
25
+ "check": "npm test && npm run pack:guard",
26
+ "test:package": "node scripts/test-package-install.mjs"
27
+ },
28
+ "engines": {
29
+ "node": ">=20"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/kevlns/art-workshop.git"
34
+ },
35
+ "homepage": "https://github.com/kevlns/art-workshop#readme",
36
+ "bugs": {
37
+ "url": "https://github.com/kevlns/art-workshop/issues"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "license": "MIT",
43
+ "author": "kevlns"
44
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "principles": [
3
+ "语言精炼:一条规则只表达一个判断,删去同义重复和无助于生成的修辞。",
4
+ "用词准确:使用明确的视觉术语,颜色、强度、数量和适用范围必须可解释。",
5
+ "前后一致:同一视觉属性只有一个定义,不同时要求互斥的媒介、明暗、高光或材质处理。",
6
+ "模块职责分明:核心只定义视觉语言;主体与动作属于需求;背景与留白属于资产规格;模型与尺寸属于执行配置。",
7
+ "单一信息来源:渲染和负向约束从同一份结构化核心派生,不另写一段可能冲突的冻结提示词。",
8
+ "作用范围明确:题材规则只作用于声明的实体类别,参考图的主体、颜色和构图不得被当成全局内容要求。",
9
+ "区分观察与建议:记录证据、置信度、推断与未确定项;不把未经证实的猜测写成必须规则。",
10
+ "跨内容可复用:推荐配置应同时容纳不同主体与表现,不借固定颜色、单物体或固定构图伪造风格一致性。",
11
+ "冻结可追溯:冻结前校验报告和推荐配置,保留来源与规则指纹;发布后的核心不可原地覆写。"
12
+ ],
13
+ "ownership": {
14
+ "core": "媒介、轮廓语言、细节密度、渲染、光照与色彩关系;按类别声明的表面处理",
15
+ "profile": "画幅、背景、留白、文字、外框、场景与投影要求",
16
+ "brief": "实体、数量、身份色、动作、关系、效果和本张构图",
17
+ "execution": "模型、像素尺寸、候选数量、seed、水印与扩写",
18
+ "edit": "明确的修改目标、保持目标和编辑底图;二者不得重叠"
19
+ }
20
+ }
@@ -0,0 +1,6 @@
1
+ import {autoSync} from '../lib/agent.mjs';
2
+ import {loadSettings} from '../lib/settings.mjs';
3
+ try {
4
+ const result=process.env.npm_lifecycle_event==='postinstall'&&!loadSettings().autoSyncSkills?{skipped:true,reason:'autoSyncSkills=false'}:autoSync({cwd:process.env.INIT_CWD??process.cwd()});
5
+ console.log(JSON.stringify(result,null,2));
6
+ } catch(error) {console.error(`美术工坊 skill 同步失败:${error.message};可稍后运行 agent init 重试。`);process.exitCode=1;}
@@ -0,0 +1,28 @@
1
+ ---
2
+ name: art-workshop
3
+ description: 使用 美术工坊 分析并冻结视觉风格、在多工程中按核心配置生成统一风格图片,或按修改与保留计划编辑现有图片。任务提到 美术工坊、核心冻结、风格报告、统一风格批量生图或本工具的图片编辑时使用。
4
+ ---
5
+
6
+ # 美术工坊
7
+
8
+ 读取同目录 `runtime.json`,通过 `node <entry>` 调用工具;已安装全局命令时可用 `art-workshop`。随包直接使用时,在工具目录执行 `node art-workshop.mjs`。下文用 `art-workshop` 表示该入口。
9
+
10
+ 先用 `art-workshop config show` 读取本地配置与外部工作目录,再用 `art-workshop agent index` 发现模块、工程及核心;需要完整用法或配置结构时读取 `art-workshop agent docs`。查看实际任务用 `<generate|edit> show --project <工程> --job <任务>`,不要猜测任务或核心身份。
11
+
12
+ 用 `art-workshop refs guide [--project P] [--refs-dir DIR]` 查看实际参考目录、分类用途与推荐图片。每次 CLI 配置生效都会补齐缺少的参考分类目录,包括 --dry;不覆盖素材。分类不自动绑定图片,分析仍显式声明 path、scope、note,构图、文字和姿态的具体要求放入单体计划。
13
+
14
+ - **风格分析与冻结**:`style analyze --project P --input FILE --out REPORT` 生成证据、推荐配置、冲突与未确定项;`style validate --project P --report REPORT` 校验;用户采用该报告后用 `style freeze --project P --report REPORT`。分析不会自动冻结,已有冻结核心不能覆写。
15
+ - **文生图**:`generate plan --project P --job J --out PLAN`,再 `generate run --plan PLAN --item ID --dry` 查看真实请求,实际生成去掉 `--dry`。run 默认 base,`--variant ID` 选择候选,`--explore` 执行全部候选,`--limit N` 限制单体数。
16
+ - **图编辑**:`edit plan --project P --job J --out PLAN`,再 `edit run --plan PLAN [--dry]`。任务必须明确原图、修改范围与保留范围;原图发生变化后重新预演。
17
+
18
+ 核心只定义可复用的视觉语言;主体、数量、颜色、动作归需求;背景和构图许可归资产配置;模型与尺寸归执行。语言精炼、用词准确、前后一致,各模块职责清楚。核心选择依次为显式 `--core`、任务绑定、工程默认;显式选择与任务绑定冲突时先修改任务,不跨工程回退。
19
+
20
+ 文生图默认纯白背景;纯黑、其他纯色、渐变或场景须明确声明。编辑保留原图未要求修改的部分,不自动换背景或套工程默认核心。编辑绑定核心时,风格由核心负责,不能又声明保留原图风格。
21
+
22
+ plan 和 `--dry` 不产生图片、没有远程生图调用;真实分析或 run 会调用模型,按用户已授权范围执行,不因预演请求擅自开始付费调用。修改需求后重新编译计划,不手改冻结计划。
23
+
24
+ 生成后用 `check RUN --out REVIEW` 导出人工验收,分别审查 content/style/asset,再用 `check RUN --review REVIEW` 汇总;只有三项全部 pass 才能 `select RUN --item ID --variant ID --review REVIEW`。check 不自动评价图片。
25
+
26
+ 随包 skill 是权威来源,`agent init --directory DIR` 同步到 DIR 下已有的 Agent 技能目录;保留项目扩展文件。修改随包源后重新同步,不直接改已同步的 SKILL.md。
27
+
28
+ 资源路径:工程、报告、计划、参考图、缓存、编辑原图与输出均放在工具目录之外。默认输出为系统下载目录/image.g。参考目录可用 --refs-dir 指定;其他路径用 --workspace、--output-dir、--cache-dir 覆盖。相对资源文件按 workspace 解析,参考图按 refs 目录解析;不要在安装目录创建工程或产物。本地配置位于用户配置目录,通过 config path/show/init 发现;不纳入 Git。
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "美术工坊"
3
+ policy:
4
+ allow_implicit_invocation: true