@kevlns/art-workshop 0.5.0 → 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 (42) hide show
  1. package/AGENTS.md +6 -90
  2. package/README.md +1 -1
  3. package/art-workshop.mjs +15 -9
  4. package/docs/commands.md +116 -8
  5. package/docs/configuration.md +1 -1
  6. package/lib/agent.mjs +19 -34
  7. package/lib/analysis-worker.mjs +5 -2
  8. package/lib/analyze.mjs +27 -20
  9. package/lib/asset-profile.mjs +2 -0
  10. package/lib/candidates.mjs +2 -0
  11. package/lib/conversation.mjs +77 -0
  12. package/lib/core.mjs +3 -17
  13. package/lib/edit.mjs +2 -1
  14. package/lib/errors.mjs +32 -0
  15. package/lib/generate.mjs +2 -1
  16. package/lib/object-format.mjs +112 -0
  17. package/lib/process-identity.mjs +17 -9
  18. package/lib/service.mjs +16 -8
  19. package/lib/settings.mjs +1 -1
  20. package/lib/shared.mjs +10 -9
  21. package/lib/style-contract.mjs +39 -0
  22. package/lib/style-evidence.mjs +39 -0
  23. package/lib/style-lifecycle.mjs +6 -1
  24. package/lib/style-report.mjs +201 -0
  25. package/lib/style-review.mjs +7 -68
  26. package/lib/task-contract.mjs +2 -0
  27. package/lib/tasks.mjs +2 -0
  28. package/lib/templates.mjs +7 -1
  29. package/lib/vision.mjs +16 -6
  30. package/lib/worker-process.mjs +6 -6
  31. package/lib/workspace.mjs +74 -20
  32. package/package.json +3 -5
  33. package/skills/art-workshop/SKILL.md +9 -108
  34. package/skills/art-workshop/references/conversation.md +11 -0
  35. package/skills/art-workshop/references/expression.md +27 -0
  36. package/skills/art-workshop/references/getty.md +76 -0
  37. package/skills/art-workshop/references/project.md +109 -0
  38. package/skills/art-workshop/references/style-discussion.md +27 -0
  39. package/skills/art-workshop/scripts/getty.py +269 -0
  40. package/v-cli.plugin.json +271 -15
  41. package/scripts/sync-skill.mjs +0 -6
  42. /package/{skills/art-workshop → adapters/codex}/agents/openai.yaml +0 -0
@@ -0,0 +1,201 @@
1
+ import { hash, keys, id, text, texts, choice } from "./shared.mjs";
2
+ import { ContractError, AnalysisError } from "./errors.mjs";
3
+ import {
4
+ STYLE_SCHEMA_VERSION,
5
+ OBSERVATION_SCOPES,
6
+ validateStyleConfig as validateCoreConfig,
7
+ } from "./style-contract.mjs";
8
+ const validateStyleConfig = validateCoreConfig;
9
+ export function validateReport(report, projectId) {
10
+ keys(
11
+ report,
12
+ [
13
+ "schema",
14
+ "schemaVersion",
15
+ "project",
16
+ "id",
17
+ "summary",
18
+ "observations",
19
+ "recommendation",
20
+ "issues",
21
+ "notes",
22
+ "decisions",
23
+ "provenance",
24
+ ],
25
+ "report",
26
+ );
27
+ if (report.schemaVersion !== STYLE_SCHEMA_VERSION)
28
+ throw new ContractError(
29
+ "风格报告职责版本已变化,请重新分析,不能采用旧报告",
30
+ );
31
+ if (
32
+ report.schema !== "art-workshop/style-report" ||
33
+ report.project !== projectId
34
+ )
35
+ throw new ContractError("风格报告身份不匹配");
36
+ id(report.id, "report.id");
37
+ text(report.summary, "report.summary", 300);
38
+ if (!Array.isArray(report.observations))
39
+ throw new ContractError("observations 必须为数组");
40
+ for (const item of report.observations) {
41
+ keys(
42
+ item,
43
+ ["source", "scope", "feature", "evidence", "confidence"],
44
+ "observation",
45
+ );
46
+ text(item.source, "source", 1024);
47
+ choice(item.scope, OBSERVATION_SCOPES, "scope");
48
+ text(item.feature, "feature");
49
+ text(item.evidence, "evidence");
50
+ if (
51
+ !Number.isFinite(item.confidence) ||
52
+ item.confidence < 0 ||
53
+ item.confidence > 1
54
+ )
55
+ throw new ContractError("confidence 必须在 0~1");
56
+ }
57
+ texts(report.notes, "notes", { empty: true });
58
+ validateIssues(report);
59
+ validateCoreConfig(report.recommendation);
60
+ return report;
61
+ }
62
+
63
+ export const issueFingerprint = (issue) =>
64
+ hash({ id: issue.id, question: issue.question, options: issue.options });
65
+ export function validateIssues(report) {
66
+ if (!Array.isArray(report.issues) || report.issues.length > 30)
67
+ throw new ContractError("问题列表非法");
68
+ const ids = new Set();
69
+ for (const issue of report.issues) {
70
+ keys(issue, ["id", "question", "options", "reopenReason"], "issue");
71
+ id(issue.id, "issue.id");
72
+ if (ids.has(issue.id)) throw new ContractError("问题ID重复");
73
+ ids.add(issue.id);
74
+ text(issue.question, "issue.question", 2000);
75
+ if (typeof issue.reopenReason !== "string")
76
+ throw new ContractError("问题重新打开原因必须是文本");
77
+ if (
78
+ !Array.isArray(issue.options) ||
79
+ issue.options.length < 2 ||
80
+ issue.options.length > 5
81
+ )
82
+ throw new ContractError("每个问题需要2至5个具体可执行方案");
83
+ const options = new Set();
84
+ for (const option of issue.options) {
85
+ keys(option, ["id", "label", "remove", "upsert"], "issue option");
86
+ id(option.id, "option.id");
87
+ if (options.has(option.id)) throw new ContractError("方案ID重复");
88
+ options.add(option.id);
89
+ text(option.label, "option.label", 1000);
90
+ texts(option.remove, "option.remove", { empty: true });
91
+ if (new Set(option.remove).size !== option.remove.length)
92
+ throw new ContractError("删除规则重复");
93
+ if (!Array.isArray(option.upsert))
94
+ throw new ContractError("方案规则非法");
95
+ if (option.upsert.length) validateStyleConfig({ rules: option.upsert });
96
+ applyOption(report.recommendation, option);
97
+ }
98
+ }
99
+ if (!Array.isArray(report.decisions))
100
+ throw new ContractError("问题决定必须是数组");
101
+ const decisions = new Set();
102
+ for (const decision of report.decisions) {
103
+ keys(
104
+ decision,
105
+ ["issueId", "fingerprint", "optionId", "note", "decidedAt"],
106
+ "decision",
107
+ );
108
+ const issue = report.issues.find((i) => i.id === decision.issueId);
109
+ if (
110
+ !issue ||
111
+ issueFingerprint(issue) !== decision.fingerprint ||
112
+ !issue.options.some((o) => o.id === decision.optionId) ||
113
+ decisions.has(issue.id)
114
+ )
115
+ throw new ContractError("问题决定与当前问题不匹配");
116
+ decisions.add(issue.id);
117
+ text(decision.note, "decision.note", 2000);
118
+ text(decision.decidedAt, "decision.decidedAt");
119
+ }
120
+ }
121
+ export function applyOption(config, option) {
122
+ const rules = config.rules.filter((r) => !option.remove.includes(r.id));
123
+ for (const rule of option.upsert) {
124
+ const index = rules.findIndex((r) => r.id === rule.id);
125
+ if (index < 0) rules.push(rule);
126
+ else rules[index] = rule;
127
+ }
128
+ return validateStyleConfig({ rules });
129
+ }
130
+ export function unresolvedIssues(report) {
131
+ return report.issues.filter(
132
+ (issue) =>
133
+ !report.decisions.some(
134
+ (d) =>
135
+ d.issueId === issue.id && d.fingerprint === issueFingerprint(issue),
136
+ ),
137
+ );
138
+ }
139
+ export function resolvedRecommendation(report) {
140
+ return report.decisions.reduce((config, decision) => {
141
+ const issue = report.issues.find((i) => i.id === decision.issueId);
142
+ if (!issue || issueFingerprint(issue) !== decision.fingerprint)
143
+ throw new ContractError("已确认问题发生变化,请重新决定");
144
+ return applyOption(
145
+ config,
146
+ issue.options.find((o) => o.id === decision.optionId),
147
+ );
148
+ }, report.recommendation);
149
+ }
150
+
151
+ export function assertReportIdentity(report, expected) {
152
+ if (report.project !== expected.project || report.id !== expected.id)
153
+ throw new AnalysisError(
154
+ "REPORT_IDENTITY_MISMATCH",
155
+ "风格报告身份与当前对象不匹配",
156
+ { recovery: "review-report" },
157
+ );
158
+ }
159
+ export function inspectStyleReport(report, expected) {
160
+ try {
161
+ validateReport(report, expected.project);
162
+ assertReportIdentity(report, expected);
163
+ return { valid: true };
164
+ } catch (error) {
165
+ return {
166
+ valid: false,
167
+ reason: error.message,
168
+ code: error.code ?? "REPORT_FORMAT_INVALID",
169
+ };
170
+ }
171
+ }
172
+ export function modelStyleReport(value, expected, provenance) {
173
+ if (!value) throw new ContractError("模型未返回有效风格报告 JSON");
174
+ for (const [key, want] of Object.entries({
175
+ schema: "art-workshop/style-report",
176
+ schemaVersion: STYLE_SCHEMA_VERSION,
177
+ project: expected.project,
178
+ id: expected.id,
179
+ }))
180
+ if (value[key] !== undefined && value[key] !== want)
181
+ throw new AnalysisError(
182
+ "REPORT_IDENTITY_MISMATCH",
183
+ "风格报告身份或职责版本与当前对象不匹配",
184
+ { recovery: "review-report" },
185
+ );
186
+ if (value.decisions?.length)
187
+ throw new AnalysisError(
188
+ "REPORT_FORGED_DECISION",
189
+ "模型不能代替用户确认风格取舍",
190
+ );
191
+ const report = {
192
+ ...value,
193
+ schema: "art-workshop/style-report",
194
+ schemaVersion: STYLE_SCHEMA_VERSION,
195
+ ...expected,
196
+ provenance,
197
+ decisions: [],
198
+ };
199
+ validateReport(report, expected.project);
200
+ return report;
201
+ }
@@ -1,75 +1,14 @@
1
- import {hash,keys,id,text,choice,texts} from './shared.mjs';
2
- import {RULE_SCOPES,RULE_STRENGTHS,STYLE_SCHEMA_VERSION} from './style-contract.mjs';
3
-
4
- export function validateStyleConfig(config){
5
- keys(config,['rules'],'style rules');
6
- if(!Array.isArray(config.rules)||!config.rules.length||config.rules.length>60)throw new Error('风格必须包含1至60条规则');
7
- const ids=new Set();
8
- for(const rule of config.rules){
9
- keys(rule,['id','scope','strength','instruction','when','negative'],'style rule');
10
- id(rule.id,'rule.id');if(ids.has(rule.id))throw new Error('规则ID重复');ids.add(rule.id);
11
- choice(rule.scope,RULE_SCOPES,'rule.scope');choice(rule.strength,RULE_STRENGTHS,'rule.strength');
12
- text(rule.instruction,'rule.instruction',300);
13
- if(/本轮|上一[轮版]|上次|本次调整|已[经]?修改|为解决.*冲突/.test(rule.instruction))throw new Error('风格规则必须为独立成稿,不包含迭代过程描述');
14
- if(typeof rule.when!=='string'||rule.when.length>1000)throw new Error('规则适用条件非法');
15
- if(rule.negative!==undefined){
16
- if(rule.strength!=='avoid')throw new Error('仅 avoid 规则可配置 negative;默认倾向不能升级为负向禁止');
17
- if(!Array.isArray(rule.negative)||rule.negative.length>20)throw new Error('规则 negative 必须为不超过20项的字符串数组');
18
- for(const term of rule.negative){
19
- text(term,'rule.negative',200);
20
- if(/^(?:避免|不要|不得|禁止|不允许|不使用|排除|no\b|without\b|avoid\b)/i.test(term.trim()))throw new Error('negative 直接描述被排除的绘制特征,不加否定前缀;适用条件写入 when');
21
- }
22
- }
23
- }
24
- return config;
25
- }
26
- export const issueFingerprint=issue=>hash({id:issue.id,question:issue.question,options:issue.options});
27
- export function validateIssues(report){
28
- if(!Array.isArray(report.issues)||report.issues.length>30)throw new Error('问题列表非法');
29
- const ids=new Set();
30
- for(const issue of report.issues){
31
- keys(issue,['id','question','options','reopenReason'],'issue');id(issue.id,'issue.id');
32
- if(ids.has(issue.id))throw new Error('问题ID重复');ids.add(issue.id);text(issue.question,'issue.question',2000);
33
- if(typeof issue.reopenReason!=='string')throw new Error('问题重新打开原因必须是文本');
34
- if(!Array.isArray(issue.options)||issue.options.length<2||issue.options.length>5)throw new Error('每个问题需要2至5个具体可执行方案');
35
- const options=new Set();
36
- for(const option of issue.options){
37
- keys(option,['id','label','remove','upsert'],'issue option');id(option.id,'option.id');
38
- if(options.has(option.id))throw new Error('方案ID重复');options.add(option.id);text(option.label,'option.label',1000);
39
- texts(option.remove,'option.remove',{empty:true});if(new Set(option.remove).size!==option.remove.length)throw new Error('删除规则重复');
40
- if(!Array.isArray(option.upsert))throw new Error('方案规则非法');
41
- if(option.upsert.length)validateStyleConfig({rules:option.upsert});
42
- applyOption(report.recommendation,option);
43
- }
44
- }
45
- if(!Array.isArray(report.decisions))throw new Error('问题决定必须是数组');
46
- const decisions=new Set();
47
- for(const decision of report.decisions){
48
- keys(decision,['issueId','fingerprint','optionId','note','decidedAt'],'decision');
49
- const issue=report.issues.find(i=>i.id===decision.issueId);
50
- if(!issue||issueFingerprint(issue)!==decision.fingerprint||!issue.options.some(o=>o.id===decision.optionId)||decisions.has(issue.id))throw new Error('问题决定与当前问题不匹配');
51
- decisions.add(issue.id);text(decision.note,'decision.note',2000);text(decision.decidedAt,'decision.decidedAt');
52
- }
53
- }
54
- export function applyOption(config,option){
55
- const rules=config.rules.filter(r=>!option.remove.includes(r.id));
56
- for(const rule of option.upsert){const index=rules.findIndex(r=>r.id===rule.id);if(index<0)rules.push(rule);else rules[index]=rule;}
57
- return validateStyleConfig({rules});
58
- }
59
- export function unresolvedIssues(report){return report.issues.filter(issue=>!report.decisions.some(d=>d.issueId===issue.id&&d.fingerprint===issueFingerprint(issue)));}
1
+ import {hash} from './shared.mjs';
2
+ import {STYLE_SCHEMA_VERSION} from './style-contract.mjs';
3
+ import {inspectStyleReport,unresolvedIssues,resolvedRecommendation} from './style-report.mjs';
4
+ export {validateStyleConfig} from './style-contract.mjs';
5
+ export {issueFingerprint,validateIssues,applyOption,unresolvedIssues,resolvedRecommendation} from './style-report.mjs';
60
6
  export function styleSourceHash(record){return hash({config:record.config,references:record.references});}
61
7
  export function styleEvidenceHash(record){return hash({references:record.references,analysis:record.config.analysis??null});}
62
8
  export function styleReviewState(record){
63
9
  if(!record.report)return {ready:false,stale:false,openIssues:[],reason:'请先生成风格报告'};
64
- if(record.report.data.schemaVersion!==STYLE_SCHEMA_VERSION)return {ready:false,stale:true,openIssues:[],reason:'历史报告已保留,请生成新版风格报告'};
10
+ if(record.report.data?.schemaVersion!==STYLE_SCHEMA_VERSION)return {ready:false,stale:true,openIssues:[],reason:'历史报告已保留,请生成新版风格报告'};
11
+ const validity=inspectStyleReport(record.report.data,{project:record.project,id:record.id});if(!validity.valid)return {ready:false,stale:true,openIssues:[],reason:validity.reason};
65
12
  const stale=record.report.sourceHash!==styleSourceHash(record),openIssues=unresolvedIssues(record.report.data).map(i=>i.id);
66
13
  return {ready:!stale&&!openIssues.length,stale,openIssues,recommendation:resolvedRecommendation(record.report.data),reason:stale?'草稿或参考已修改,请复核报告':openIssues.length?`还有 ${openIssues.length} 项待决定;确认取舍后即可采用`:'风格方案已就绪,可确认采用'};
67
14
  }
68
-
69
- export function resolvedRecommendation(report){
70
- return report.decisions.reduce((config,decision)=>{
71
- const issue=report.issues.find(i=>i.id===decision.issueId);
72
- if(!issue||issueFingerprint(issue)!==decision.fingerprint)throw new Error('已确认问题发生变化,请重新决定');
73
- return applyOption(config,issue.options.find(o=>o.id===decision.optionId));
74
- },report.recommendation);
75
- }
@@ -1,3 +1,4 @@
1
+ export const TASK_FIELDS={generate:['project','kind','core','profile','asset','execution','analysis','generation','items'],edit:['project','kind','core','execution','analysis','generation','items']};
1
2
  import {keys,text,integer,description} from './shared.mjs';
2
3
  import {background} from './presentation.mjs';
3
4
 
@@ -55,6 +56,7 @@ export function taskContract(kind){
55
56
  }
56
57
  /** Drafts may be incomplete, but never accept fields the compiler will discard. */
57
58
  export function validateTaskDraft(config){
59
+ if(TASK_FIELDS[config.kind])keys(config,TASK_FIELDS[config.kind],"task config");
58
60
  if(config.analysis!==undefined){keys(config.analysis,['provider','model'],'analysis');text(config.analysis.provider,'analysis.provider');text(config.analysis.model,'analysis.model');}
59
61
  if(config.generation!==undefined){keys(config.generation,['backend','remote','options'],'generation');text(config.generation.backend,'generation.backend');if(config.generation.remote){keys(config.generation.remote,['provider','model'],'generation.remote');text(config.generation.remote.provider,'generation.remote.provider');text(config.generation.remote.model,'generation.remote.model');}if(config.generation.options!==undefined){if(config.generation.backend==='bailian')throw new Error('远程后端不支持本地采样参数');taskSamplingOptions(config.generation.options);}}
60
62
  if(config.kind==='edit'){
package/lib/tasks.mjs CHANGED
@@ -53,6 +53,7 @@ export function taskView(task) {
53
53
  promptId,
54
54
  manifestPath,
55
55
  error,
56
+ errorDetail,
56
57
  diagnostic,
57
58
  remoteCancellation,
58
59
  unsettled,
@@ -92,6 +93,7 @@ export function taskView(task) {
92
93
  promptId,
93
94
  manifestPath,
94
95
  error,
96
+ errorDetail,
95
97
  diagnostic,
96
98
  remoteCancellation,
97
99
  remoteExecutions,
package/lib/templates.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import {loadCore} from './core.mjs';
2
2
  import {loadProject} from './project.mjs';
3
3
  import {LOCAL_SAMPLING_DEFAULTS} from './task-contract.mjs';
4
- function generateTemplate(projectId,core,kind) {
4
+ export function generateTemplate(projectId,core,kind) {
5
5
  return {
6
6
  project: projectId,
7
7
  kind: "generate",
@@ -72,3 +72,9 @@ export function jobTemplate(root,projectId,{kind='generate',core}={}){
72
72
  loadCore(projectId,core,root);
73
73
  return {...generateTemplate(projectId,core,'subject'),generation};
74
74
  }
75
+
76
+ export function emptyJobTemplate(projectId,kind='generate'){
77
+ const generation={backend:'local-qwen',options:{...LOCAL_SAMPLING_DEFAULTS}};
78
+ if(kind==='edit')return {project:projectId,kind,generation,items:[{id:'asset-1',changes:[],preserve:[],mustRead:[]}]};
79
+ if(kind!=='generate')throw new Error('任务类型非法');return {...generateTemplate(projectId,null,'subject'),generation};
80
+ }
package/lib/vision.mjs CHANGED
@@ -1,15 +1,15 @@
1
+ import {AnalysisError} from './errors.mjs';
1
2
  import {readFileSync} from 'node:fs';
2
3
 
3
4
  /** The harness supplies one selected credential in process memory, never in argv or run evidence. */
4
- export async function callVision(args,{cancelled=()=>false,onRemoteCancel,transport=fetch}={}) {
5
+ export async function callVision(args,{cancelled=()=>false,onRemoteCancel,onEvidence=()=>{},transport=fetch}={}) {
5
6
  const config=JSON.parse(process.env.ART_VISION_CONFIG??'null'),key=process.env.ART_VISION_KEY;
6
7
  if(!config||!key)throw new Error('视觉模型实例未配置');
7
8
  const value=name=>args[args.indexOf(name)+1],model=value('--model');
8
9
  const image=args.includes('--image')?value('--image'):null,text=args.includes('--prompt')?value('--prompt'):value('--message');
9
10
  if(!model||!text)throw new Error('视觉调用缺少模型或提示');
10
11
  if(config.model&&model!==config.model)throw new Error('视觉模型与授权实例不匹配');
11
- const configuredTokens=config.maxTokens??16384;if(!Number.isSafeInteger(configuredTokens)||configuredTokens<1024)throw new Error('视觉模型输出额度非法');
12
- const maxTokens=Math.min(configuredTokens,32768);
12
+ const {effectiveMaxTokens:maxTokens}=visionOutputBudget(config);
13
13
  const base=new URL(config.baseUrl);if(!['http:','https:'].includes(base.protocol)||base.username||base.password||base.search||base.hash)throw new Error('视觉模型地址非法');
14
14
  let mime='image/png',data;if(image){const bytes=readFileSync(image);mime=bytes[0]===255?'image/jpeg':bytes.subarray(0,4).toString()==='RIFF'?'image/webp':'image/png';data=bytes.toString('base64');}
15
15
  let endpoint,headers,body;
@@ -28,19 +28,29 @@ export async function callVision(args,{cancelled=()=>false,onRemoteCancel,transp
28
28
  try{
29
29
  sent=true;
30
30
  const response=await transport(base.href.replace(/\/$/,'')+endpoint,{method:'POST',headers:{...headers,'Content-Type':'application/json'},body:JSON.stringify(body),redirect:'error',signal:controller.signal});
31
- if(!response.ok)throw new Error('视觉模型请求失败(HTTP '+response.status+')');
31
+ if(!response.ok){
32
+ const reader=response.body?.getReader();let size=0,raw='';if(reader)try{while(size<8192){const next=await reader.read();if(next.done)break;size+=next.value.byteLength;raw+=Buffer.from(next.value).toString('utf8');}}finally{await reader.cancel().catch(()=>{});}
33
+ let code;try{const payload=JSON.parse(raw);const value=payload.error?.code??payload.code;if(typeof value==='string'&&/^[a-zA-Z0-9_.-]{1,100}$/.test(value)&&!value.includes(key))code=value;}catch{}
34
+ throw new AnalysisError('UPSTREAM_REJECTED','视觉模型请求失败(HTTP '+response.status+')'+(code?',错误码 '+code:''),{upstream:{status:response.status,...(code?{code}:{})},recovery:'fix-connection'});
35
+ }
32
36
  const reader=response.body?.getReader();if(!reader)throw new Error('视觉模型未返回报告');
33
37
  const chunks=[];let size=0;
34
38
  while(true){const next=await reader.read();if(next.done)break;size+=next.value.byteLength;if(size>8_000_000){await reader.cancel();throw new Error('视觉响应过大');}chunks.push(next.value);}
35
39
  const raw=Buffer.concat(chunks).toString('utf8');
36
40
  const result=JSON.parse(raw);
37
- if(result.choices?.[0]?.finish_reason==='length'||result.status==='incomplete'||result.stop_reason==='max_tokens'||result.candidates?.some(c=>c.finishReason==='MAX_TOKENS'))throw new Error('视觉报告超出模型输出额度,请调整输出额度后重新分析;未回填截断结果');
38
41
  // Return only assistant text, rather than recursively interpreting arbitrary response metadata as a report.
39
42
  const texts=config.api==='openai-completions'?[result.choices?.[0]?.message?.content]:config.api==='openai-responses'?(result.output??[]).flatMap(item=>(item.content??[]).filter(c=>c.type==='output_text').map(c=>c.text)):config.api==='anthropic-messages'?(result.content??[]).filter(c=>c.type==='text').map(c=>c.text):(result.candidates??[]).flatMap(item=>(item.content?.parts??[]).map(c=>c.text));
40
- if(!texts.length||texts.some(t=>typeof t!=='string'))throw new Error('视觉模型未返回文字报告');
43
+ const assistantText=texts.filter(t=>typeof t==='string').join('\n');
44
+ const truncated=result.choices?.[0]?.finish_reason==='length'||result.status==='incomplete'||result.stop_reason==='max_tokens'||result.candidates?.some(c=>c.finishReason==='MAX_TOKENS');
45
+ try{onEvidence({text:assistantText,effectiveMaxTokens:maxTokens,truncated});}catch(error){throw new AnalysisError('EVIDENCE_WRITE_FAILED','分析证据保存失败:'+error.message);}
46
+ if(truncated)throw new AnalysisError('OUTPUT_TRUNCATED','视觉报告超出模型输出额度(本次 '+maxTokens+' tokens);请核对实际额度,未回填截断结果',{effectiveMaxTokens:maxTokens,recovery:'review-budget'});
47
+ if(!assistantText.trim()||texts.some(t=>typeof t!=='string'))throw new Error('视觉模型未返回文字报告');
41
48
  return {text:texts.join('\n')};
42
49
  }catch(error){
50
+ if(error instanceof AnalysisError)throw error;
43
51
  if(sent&&(controller.signal.aborted||error instanceof TypeError)){onRemoteCancel?.();throw new Error(cancelled()?'分析请求已取消;云端计算与计费是否停止无法确认,不会自动重发':'分析请求超时或连接中断;云端计算与计费是否停止无法确认,未回填报告,不会自动重发');}
44
52
  throw new Error(/^视觉/.test(error.message)?error.message:'视觉模型响应解析失败');
45
53
  }finally{clearInterval(timer);clearTimeout(timeout);}
46
54
  }
55
+
56
+ export function visionOutputBudget(config={}){const max=config.maxTokens??16384;if(!Number.isSafeInteger(max)||max<1)throw new AnalysisError('INVALID_OUTPUT_BUDGET','视觉模型输出额度非法',{recovery:'fix-input'});return {configuredMaxTokens:max,effectiveMaxTokens:max,limitReason:null};}
@@ -1,16 +1,16 @@
1
- import {processIdentity} from './process-identity.mjs';
1
+ import {inspectProcess} from './process-identity.mjs';
2
2
  import {hash} from './shared.mjs';
3
3
 
4
4
  // A recycled PID is not evidence that an old task is still running.
5
5
  // Unreadable identities remain live: uncertainty never authorizes termination.
6
- export function workerAlive(task, inspect = processIdentity) {
6
+ export function workerAlive(task, inspect = inspectProcess) {
7
7
  const pid = task.workerPid;
8
8
  if (!Number.isSafeInteger(pid) || pid <= 0) return false;
9
- // ESRCH:PID 已消失。其余错误(Windows 的 EPERM/EACCES)只说明该 PID 存在
10
- // 但不归我们管,通常是 PID 被复用;交给下面的身份比对判定。
11
9
  try { process.kill(pid, 0); } catch (error) { if (error.code === 'ESRCH') return false; }
12
- const current = inspect(pid);
13
- if (!current) return true;
10
+ const result = inspect(pid);
11
+ if (result.state === 'missing') return false;
12
+ if (result.state !== 'running') return true;
13
+ const current = result.identity;
14
14
  if (task.workerIdentity) return hash(current) === hash(task.workerIdentity);
15
15
  // Historical receipts have no identity. A process born after the completed
16
16
  // task cannot be its worker; allow one second for Unix ps time precision.
package/lib/workspace.mjs CHANGED
@@ -1,3 +1,6 @@
1
+ import {inspectObjectFormat,assertSupportedObject} from './object-format.mjs';
2
+ import {styleProvenance} from './style-evidence.mjs';
3
+ import {validateStyleDraft as styleConfig,validateReferenceNotes,styleAnalysisReadiness} from './style-contract.mjs';
1
4
  import {validateTaskDraft} from './task-contract.mjs';
2
5
  import {existsSync,mkdirSync,readdirSync,readFileSync,writeFileSync,lstatSync,rmSync,cpSync} from 'node:fs';
3
6
  import {resolve,join,dirname,relative,isAbsolute} from 'node:path';
@@ -15,14 +18,6 @@ import {styleReviewState,resolvedRecommendation,validateStyleConfig,styleEvidenc
15
18
  export {STYLE_CATEGORIES} from './style-contract.mjs';
16
19
  export const TASK_PURPOSES=['subject','composition','pose','identity-color','surface','scene-light','text'];
17
20
  const now=()=>new Date().toISOString();
18
- function styleConfig(config){
19
- keys(config,['description','constraints','rules','analysis'],'style config');
20
- if(config.rules!==undefined)validateStyleConfig({rules:config.rules});
21
- if(config.description!==undefined&&(typeof config.description!=='string'||config.description.length>12000))throw new Error('风格描述必须是12000字以内文本');
22
- if(config.constraints!==undefined)texts(config.constraints,'constraints',{empty:true});
23
- if(config.analysis!==undefined){keys(config.analysis,['provider','model'],'analysis');text(config.analysis.provider,'analysis.provider');text(config.analysis.model,'analysis.model');}
24
- return structuredClone(config);
25
- }
26
21
  /** Resolve every existing ancestor: no user-controlled link may escape the project. */
27
22
  export function ownedPath(root,...segments){
28
23
  const base=externalPath(resolve(root)),path=resolve(base,...segments),rel=relative(base,path);
@@ -43,24 +38,29 @@ export function readObject(root,projectId,kind,objectId){
43
38
  if(existsSync(ownedPath(root,'.runtime/upgrades',id(projectId)+'.json')))throw new Error('工程升级事务未完成,请显式 project upgrade 恢复');
44
39
  if(kind==='style'&&existsSync(ownedPath(objectDirectory(root,projectId,kind,objectId),'adoption.json')))throw new Error('风格采用事务未完成,请 style recover 后再操作');
45
40
  const record=readJson(objectFile(root,projectId,kind,objectId));
46
- if(record.schema!=='art-workshop/'+kind||record.schemaVersion!==2||record.project!==projectId||record.id!==objectId)throw new Error('对象身份或版本不匹配,请显式升级工程');
41
+ if(record.schema!=='art-workshop/'+kind||record.project!==projectId||record.id!==objectId)throw new Error('对象身份或版本不匹配,请显式升级工程');
47
42
  integer(record.revision,'revision',1);return record;
48
43
  }
49
44
  export function listObjects(root,projectId,kind){
50
45
  const folder=ownedPath(root,'projects',id(projectId),kind==='style'?'styles':'tasks');
51
- return existsSync(folder)?readdirSync(folder).filter(x=>existsSync(ownedPath(folder,x,kind+'.json'))).map(x=>readObject(root,projectId,kind,x)):[];
46
+ return existsSync(folder)?readdirSync(folder).filter(x=>existsSync(ownedPath(folder,x,kind+'.json'))).map(x=>{try{return readObject(root,projectId,kind,x);}catch(error){return {schema:'art-workshop/'+kind,schemaVersion:2,project:projectId,id:x,name:x,status:'unreadable',revision:1,config:{},references:[],report:null,readError:error.message};}}):[];
52
47
  }
53
48
  /** Read projection only: never rewrite old frozen evidence or reinterpret old references. */
49
+ export function objectFormat(root,record){
50
+ let core,dependency;
51
+ if(record.schema==='art-workshop/style'&&record.status==='frozen'){try{core=readJson(ownedPath(objectDirectory(root,record.project,'style',record.id),'core.json'));}catch(error){return {status:'unreadable',reasons:[error.message],canEdit:false,canDerive:false};}}
52
+ if(record.schema==='art-workshop/task'&&record.config?.core){try{
53
+ const file=objectFile(root,record.project,'style',record.config.core);
54
+ if(existsSync(file))dependency=objectFormat(root,readObject(root,record.project,'style',record.config.core));
55
+ else {const core=readJson(ownedPath(objectDirectory(root,record.project,'style',record.config.core),'core.json'));dependency=inspectObjectFormat({schema:'art-workshop/style',schemaVersion:2,status:'frozen',config:core.config,report:{data:core.report},references:[]},{core});}
56
+ }catch(error){dependency={status:'unreadable',reasons:[error.message]};}}
57
+ return inspectObjectFormat(record,{core,dependency});
58
+ }
59
+ export function assertObjectCurrent(root,record,{allowMigration=false}={}){assertSupportedObject(objectFormat(root,record));if(!allowMigration&&record.migration?.status==='pending')throw new Error('迁移尚未完成,请继续迁移讨论并校验草稿');}
54
60
  export function styleView(root,record){
55
- const pendingReferences=record.references.filter(ref=>!STYLE_CATEGORIES.includes(ref.category)).map(ref=>ref.id);
56
- const reasons=[];
57
- if(record.report&&record.report.data?.schemaVersion!==STYLE_SCHEMA_VERSION)reasons.push('旧分析报告职责版本已变化,请重新分析后采用。');
58
- if(pendingReferences.length)reasons.push('旧参考分类已取消,请逐图指定当前风格分类;具体造型参考应导入任务。');
59
- if(record.status==='frozen'){
60
- const core=readJson(ownedPath(objectDirectory(root,record.project,'style',record.id),'core.json'));
61
- if(core.schemaVersion!==STYLE_SCHEMA_VERSION)reasons.push('旧核心包含已取消的风格职能,请派生草稿、核对参考并重新分析采用;原核心与历史产物保留。');
62
- }
63
- return {...record,review:styleReviewState(record),compatibility:{usable:reasons.length===0,pendingReferences,reasons}};
61
+ const format=objectFormat(root,record);
62
+ const pendingReferences=(record.references??[]).filter(ref=>!STYLE_CATEGORIES.includes(ref.category)).map(ref=>ref.id);
63
+ return {...record,format,analysisReadiness:styleAnalysisReadiness(record),review:styleReviewState(record),compatibility:{usable:format.status==='current',pendingReferences,reasons:format.reasons}};
64
64
  }
65
65
  function objectRuns(settings,record){return tasks(runtimeRoot(settings)).filter(t=>(t.plan?.project??t.project)===record.project&&(record.schema==='art-workshop/task'?(t.plan?.job===record.id||t.objectId===record.id&&t.objectKind==='task'):t.styleId===record.id&&t.project===record.project)).map(t=>taskStatus(runtimeRoot(settings),t.taskId));}
66
66
  export async function mutateObject(settings,projectId,kind,objectId,revision,change,{allowFrozen=false}={}){
@@ -68,6 +68,7 @@ export async function mutateObject(settings,projectId,kind,objectId,revision,cha
68
68
  return locked(runtimeRoot(settings),'control',async()=>{
69
69
  const before=readObject(settings.paths.workspace,projectId,kind,objectId);
70
70
  if(['discarded','cleanup-required'].includes(before.status)&&!allowFrozen)throw new Error('对象已放弃或需要清理,不能继续编辑');
71
+ if(!allowFrozen)assertObjectCurrent(settings.paths.workspace,before,{allowMigration:true});
71
72
  if(before.revision!==revision)throw new Error('对象版本冲突,请重新读取');
72
73
  assertIdle(objectRuns(settings,before),kind==='style'?'风格':'任务');
73
74
  if(kind==='style'&&before.status==='frozen'&&!allowFrozen)throw new Error('冻结风格只读,请派生新风格');
@@ -84,6 +85,7 @@ export async function createObject(settings,projectId,kind,{name,config={},sourc
84
85
  if(typeof name!=='string'||!name.trim())throw new Error('对象名称不能为空');
85
86
  const objectId=kind+'-'+randomUUID(),record={schema:'art-workshop/'+kind,schemaVersion:2,project:projectId,id:objectId,name:name.trim(),revision:1,status:'draft',createdAt:now(),updatedAt:now(),source,config:kind==='style'?styleConfig(config):structuredClone(config),references:[],report:null};
86
87
  if(kind==='task'){validateTaskDraft(config);if(!['generate','edit'].includes(config.kind))throw new Error('任务必须声明生成或编辑类型');record.config.project=projectId;}
88
+ if(kind==='task')assertSupportedObject(objectFormat(settings.paths.workspace,{...record,source:null}));
87
89
  const directory=objectDirectory(settings.paths.workspace,projectId,kind,objectId);
88
90
  try{if(kind==='task')record.config=await importSources(settings,record,record.config);writeJson(objectFile(settings.paths.workspace,projectId,kind,objectId),record);return record;}
89
91
  catch(error){if(existsSync(directory))rmSync(ownedPath(settings.paths.workspace,directory),{recursive:true,force:true});throw error;}
@@ -99,6 +101,7 @@ function imageExtension(buffer){
99
101
  throw new Error('只允许有效 PNG/JPEG/WebP 图片');
100
102
  }
101
103
  export async function importReference(settings,projectId,kind,objectId,revision,{source,category,purposes=[],itemId,usage='understand',note='',ignore=''}={}){
104
+ validateReferenceNotes({note,ignore});
102
105
  if(kind==='style'&&!STYLE_CATEGORIES.includes(category))throw new Error('风格参考分类非法');
103
106
  if(kind==='task'&&(!purposes.length||purposes.some(p=>!TASK_PURPOSES.includes(p))))throw new Error('任务参考用途非法');
104
107
  if(usage!=='understand')throw new Error('后端直接参考尚未完成用途约束适配');
@@ -151,6 +154,8 @@ export async function deriveObject(settings,projectId,kind,objectId,revision){
151
154
  assertIdle(objectRuns(settings,source));
152
155
  if(source.revision!==revision)throw new Error('对象版本冲突');
153
156
  verifyReferences(settings.paths.workspace,source);
157
+ if(objectFormat(settings.paths.workspace,source).status==='unreadable')throw new Error('源数据不可读,请先核对完整性');
158
+ if(objectFormat(settings.paths.workspace,source).status!=='current')return createMigrationDraft(settings,source,kind);
154
159
  const frozenCore=kind==='style'&&source.status==='frozen'&&source.report?.data?.schemaVersion===STYLE_SCHEMA_VERSION?(await import('./core.mjs')).loadCore(projectId,objectId,settings.paths.workspace):null;
155
160
  const finalRules=frozenCore?.config.rules??null;
156
161
  const config=kind==='style'?{description:finalRules?source.report.data.summary:source.config.description??source.report?.data?.summary??'',constraints:finalRules?[]:source.config.constraints??[],...(finalRules?{rules:structuredClone(finalRules)}:source.config.rules?{rules:structuredClone(source.config.rules)}:{}),...(source.config.analysis?{analysis:source.config.analysis}:{})}:source.config;
@@ -159,7 +164,7 @@ export async function deriveObject(settings,projectId,kind,objectId,revision){
159
164
  const directory=objectDirectory(settings.paths.workspace,projectId,kind,derived.id);
160
165
  for(const ref of source.references){const old=ownedPath(objectDirectory(settings.paths.workspace,projectId,kind,source.id),ref.path),target=ownedPath(directory,ref.path);mkdirSync(dirname(target),{recursive:true});cpSync(old,target,{errorOnExist:true,force:false});derived.references.push({...ref});}
161
166
  if(finalRules){
162
- const data={...structuredClone(source.report.data),id:derived.id,recommendation:{rules:structuredClone(finalRules)},issues:[],decisions:[],provenance:{method:'inherited-frozen',source:{id:source.id,revision:source.revision,coreHash:source.coreHash},sourceReportHash:hash(source.report.data),evidence:source.report.data.provenance??null}};
167
+ const data={...structuredClone(source.report.data),id:derived.id,recommendation:{rules:structuredClone(finalRules)},issues:[],decisions:[],provenance:styleProvenance(source.report.data.provenance,{method:'inherited-frozen',source:{id:source.id,revision:source.revision,coreHash:source.coreHash},sourceReportHash:hash(source.report.data)})};
163
168
  derived.report={data,sourceRevision:derived.revision,sourceHash:hash({config:derived.config,references:derived.references}),evidenceHash:styleEvidenceHash(derived),path:null,runId:null};
164
169
  }
165
170
  writeJson(objectFile(settings.paths.workspace,projectId,kind,derived.id),derived);return derived;
@@ -197,7 +202,15 @@ export async function restoreTask(settings,projectId,objectId,revision){
197
202
  },{allowFrozen:true});
198
203
  }
199
204
  export function assertPlanCurrent(plan,settings){
205
+ if(plan.scope?.kind==='conversation'){
206
+ id(plan.scope.sessionId,'session');id(plan.scope.requestId,'request');
207
+ const saved=readJson(ownedPath(settings.paths.workspace,'conversations',plan.scope.sessionId,plan.scope.requestId+'.json'));
208
+ if(hash(saved.request)!==plan.sources.requestHash||hash(saved.plan)!==hash(plan))throw new Error('会话请求与预案不一致');
209
+ for(const ref of plan.refs)if(!existsSync(ref.path)||createHash('sha256').update(readFileSync(ref.path)).digest('hex')!==ref.hash)throw new Error('会话参考已变化');
210
+ return;
211
+ }
200
212
  const current=readObject(settings.paths.workspace,plan.project,'task',plan.job);
213
+ assertObjectCurrent(settings.paths.workspace,current);
201
214
  if(current.status==='discarded'||current.revision!==plan.sources.taskRevision||hash(current.config)!==plan.sources.taskConfigHash)throw new Error('计划来源已变化,请重新编译');
202
215
  verifyReferences(settings.paths.workspace,current);
203
216
  const project=readJson(ownedPath(settings.paths.workspace,'projects',plan.project,'project.json'));
@@ -236,3 +249,44 @@ async function importSources(settings,record,config){
236
249
  }
237
250
  return result;}catch(error){for(const file of created)rmSync(ownedPath(directory,file),{force:true});throw error;}
238
251
  }
252
+
253
+ async function createMigrationDraft(settings,source,kind){
254
+ const root=settings.paths.workspace;
255
+ const existing=listObjects(root,source.project,kind).find(r=>r.migration?.status==='pending'&&r.migration.source.id===source.id&&r.migration.source.revision===source.revision);
256
+ if(existing)return existing;
257
+ const config=kind==='style'?{description:'',constraints:[]}:(await import('./templates.mjs')).emptyJobTemplate(source.project,source.config.kind);
258
+ const staged=listObjects(root,source.project,kind).find(r=>r.source?.kind==='migration'&&!r.migration&&r.source.id===source.id&&r.source.revision===source.revision);
259
+ const derived=staged??await createObject(settings,source.project,kind,{name:source.name+' · 迁移',config,source:{kind:'migration',id:source.id,revision:source.revision}});
260
+ const directory=objectDirectory(root,source.project,kind,derived.id),resources=[];
261
+ try{
262
+ const originals=verifyReferences(root,source);
263
+ if(kind==='task'&&source.config.kind==='edit')for(const item of source.config.items??[])if(item.source){const path=ownedPath(root,item.source);originals.push({id:item.id,path,hash:createHash('sha256').update(readFileSync(path)).digest('hex'),role:'edit-source'});}
264
+ for(const [index,ref] of originals.entries()){
265
+ const bytes=readFileSync(ref.path);if(createHash('sha256').update(bytes).digest('hex')!==ref.hash)throw new Error('迁移源图片完整性失败');
266
+ const path='migration/resources/'+index+imageExtension(bytes);mkdirSync(ownedPath(directory,'migration/resources'),{recursive:true});writeJson(ownedPath(directory,'migration/marker.json'),{version:1});if(existsSync(ownedPath(directory,path))){if(createHash('sha256').update(readFileSync(ownedPath(directory,path))).digest('hex')!==ref.hash)throw new Error('迁移暂存图片发生变化');}else cpSync(ref.path,ownedPath(directory,path),{force:false,errorOnExist:true});resources.push({...ref,path,source:undefined});
267
+ }
268
+ const snapshot={schema:'art-workshop/migration-source',version:1,object:source,resources};
269
+ if(kind==='style'&&source.status==='frozen')snapshot.core=readJson(ownedPath(objectDirectory(root,source.project,kind,source.id),'core.json'));
270
+ writeJson(ownedPath(directory,'migration/source.json'),snapshot);
271
+ derived.status='draft';delete derived.error;
272
+ derived.migration={id:'migration-'+randomUUID(),status:'pending',source:{kind,id:source.id,revision:source.revision},snapshotHash:hash(snapshot),createdAt:now()};
273
+ writeJson(objectFile(root,source.project,kind,derived.id),derived);return derived;
274
+ }catch(error){derived.status='cleanup-required';derived.error=error.message;writeJson(objectFile(root,source.project,kind,derived.id),derived);throw error;}
275
+ }
276
+ export function migrationSource(root,record){
277
+ if(!record.migration)throw new Error('当前对象没有迁移来源');const directory=objectDirectory(root,record.project,record.schema.slice('art-workshop/'.length),record.id);
278
+ const snapshot=readJson(ownedPath(directory,'migration/source.json'));if(hash(snapshot)!==record.migration.snapshotHash)throw new Error('迁移来源快照已变化');
279
+ for(const resource of snapshot.resources){const file=ownedPath(directory,resource.path);if(createHash('sha256').update(readFileSync(file)).digest('hex')!==resource.hash)throw new Error('迁移来源图片已变化');}
280
+ return snapshot;
281
+ }
282
+ export async function finishMigration(settings,projectId,kind,objectId,revision,{note}={}){
283
+ if(typeof note!=='string'||!note.trim())throw new Error('请说明迁移结果、未沿用内容及原因');
284
+ return mutateObject(settings,projectId,kind,objectId,revision,record=>{
285
+ if(!record.migration)throw new Error('当前草稿没有迁移来源');migrationSource(settings.paths.workspace,record);assertObjectCurrent(settings.paths.workspace,record,{allowMigration:true});
286
+ if(kind==='style'){if(!styleAnalysisReadiness(record).ready)throw new Error('迁移草稿仍缺少风格内容');}
287
+ else {validateTaskDraft(record.config);if(!record.config.items?.length)throw new Error('任务内容尚未迁移');if(record.config.kind==='generate'&&(!record.config.core||record.config.items.some(i=>!i.intent?.trim()||!i.entities?.length||i.entities.some(e=>!e.appearance?.trim()))))throw new Error('请先填写任务主体、需求并绑定已采用的当前风格');if(record.config.kind==='edit'&&record.config.items.some(i=>!i.source||!i.changes?.length))throw new Error('编辑底图或修改需求尚未迁移');}
288
+ verifyReferences(settings.paths.workspace,record);record.migration={...record.migration,status:'ready',note:note.trim(),completedAt:now()};return record;
289
+ });
290
+ }
291
+
292
+ export async function confirmMigration(settings,projectId,kind,id,revision){return mutateObject(settings,projectId,kind,id,revision,record=>{if(record.migration?.status!=='ready')throw new Error('请先完成配置迁移');record.migration.confirmedAt=now();return record;});}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kevlns/art-workshop",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "private": false,
5
5
  "description": "管理项目风格、参考图、图片生成、编辑和定版。支持本地 ComfyUI 与远程图片模型。",
6
6
  "type": "module",
@@ -12,17 +12,15 @@
12
12
  "lib/",
13
13
  "rules/",
14
14
  "skills/",
15
- "scripts/sync-skill.mjs",
16
15
  "README.md",
17
16
  "LICENSE",
18
17
  "v-cli.plugin.json",
19
18
  "AGENTS.md",
20
19
  "workflows/",
21
- "docs/"
20
+ "docs/",
21
+ "adapters/"
22
22
  ],
23
23
  "scripts": {
24
- "postinstall": "node scripts/sync-skill.mjs",
25
- "skill:sync": "node scripts/sync-skill.mjs",
26
24
  "test": "node scripts/test.mjs",
27
25
  "pack:guard": "node scripts/pack-guard.mjs",
28
26
  "check": "npm run docs:style && npm run docs:check && npm test && npm run pack:guard",