@kevlns/art-workshop 0.3.3 → 0.3.5

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/AGENTS.md CHANGED
@@ -42,3 +42,5 @@ candidate delete 先确认影响,拒绝运行中或被计划/底图引用的
42
42
  远端上游身份持久化后才能轮询。`task resume TASK` 只恢复原身份查询与取回,不重发生成;无回执或仍处于 dispatching 的提交保持未知。界面与保存共用 modelEligibility,展示字段不进入执行契约。
43
43
 
44
44
  风格报告和核心职责版本 schemaVersion=3;不再包含 shape、lighting、domains,不限定主体题材。旧核心保留,只能派生后重新分析采用;旧分类参考必须明确重新分类,不能猜测搬到任务或渲染。低刻画密度不删任务结构,干净笔触不禁止物体纹理,高光画法不统一物理材质。
45
+
46
+ 任务草稿允许内容尚未完成,但拒绝编译器不支持的字段。生成任务的字段正本为 lib/task-contract.mjs;effect 使用 id/kind/target/color/relation/count,不支持 description。先读当前对象,完整保留未修改字段,按当前 revision 保存;保存成功后仍需编译预案,不能声称已生成图片。任务编译错误依据执行回执修正,不猜测风格或尺寸问题。
@@ -1,3 +1,4 @@
1
+ import {processIdentity} from './process-identity.mjs';
1
2
  import {existsSync} from 'node:fs';
2
3
  import {join} from 'node:path';
3
4
  import {readJson,writeJson,hash} from './shared.mjs';
@@ -10,7 +11,7 @@ import {extractText} from './bl.mjs';
10
11
  const file=process.argv[2],task=readJson(file);
11
12
  const persist=()=>{task.heartbeat=new Date().toISOString();writeJson(file,task);};
12
13
  const cancelled=()=>existsSync(file+'.cancel')||existsSync(join(task.root,'shutdown.json'));
13
- task.workerPid=process.pid;task.status='running';persist();const heartbeat=setInterval(persist,1000);
14
+ task.workerPid=process.pid;task.workerIdentity=processIdentity(process.pid);task.status='running';persist();const heartbeat=setInterval(persist,1000);
14
15
  let responseIndex=0;
15
16
  try{
16
17
  const analyzer=task.objectKind==='task'?analyzeTaskReferences:analyzeStyle;
package/lib/generate.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import {GENERATION_FIELDS} from './task-contract.mjs';
1
2
  import {taskReferencePrompt} from './task-references.mjs';
2
3
  import {readObject,verifyReferences} from './workspace.mjs';
3
4
  import { readJson, keys, id, text, texts, integer, hash } from './shared.mjs';
@@ -21,29 +22,29 @@ export function compileGenerate({projectId,jobId,coreId,root=ROOT,localExecution
21
22
  const items=[],ids=new Set();
22
23
  if(!Array.isArray(job.items)||!job.items.length) throw new Error('任务 items 必须非空');
23
24
  for(const source of job.items) {
24
- keys(source,['id','seed','intent','entities','effects','relations','composition','mustRead','variants','design'],'item');
25
+ keys(source,GENERATION_FIELDS.item,'item');
25
26
  const d=design(profile,source.design,job.execution);
26
27
  id(source.id); if(ids.has(source.id)) throw new Error('item ID 重复'); ids.add(source.id);
27
28
  text(source.intent,'intent'); texts(source.mustRead,'mustRead');
28
29
  if(!Array.isArray(source.entities)||!source.entities.length) throw new Error('entities 必须非空');
29
30
  const objectIds=new Set(), lines=[];
30
31
  for(const e of source.entities) {
31
- keys(e,['id','kind','appearance','color','role','count','action'],'entity'); id(e.id); id(e.kind);
32
+ keys(e,GENERATION_FIELDS.entity,'entity'); id(e.id); id(e.kind);
32
33
  if(objectIds.has(e.id)) throw new Error('实体 ID 重复'); objectIds.add(e.id);
33
34
  if(!['primary','support'].includes(e.role)) throw new Error('实体角色不合法');
34
35
  integer(e.count,'count',1,100); text(e.appearance,'appearance');text(e.color,'color'); if(e.action) text(e.action,'action');
35
36
  lines.push(`${e.id}:${e.count} 个${e.appearance},${e.color},${e.role==='primary'?'主要':'辅助'}实体${e.action?','+e.action:''}。`);
36
37
  }
37
38
  for(const e of source.effects??[]) {
38
- keys(e,['id','kind','target','color','relation','count'],'effect');id(e.id);
39
+ keys(e,GENERATION_FIELDS.effect,'effect');id(e.id);
39
40
  if(objectIds.has(e.id)||!source.entities.some(x=>x.id===e.target)) throw new Error('效果 ID 重复或目标不存在'); objectIds.add(e.id);
40
41
  for(const k of ['kind','color','relation']) text(e[k],k); integer(e.count,'count',1,100);
41
42
  lines.push(`${e.id}:${e.count} 个${e.color}${e.kind},作用于 ${e.target};${e.relation}。`);
42
43
  }
43
- 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')}。`);}
44
+ for(const r of source.relations??[]) {keys(r,GENERATION_FIELDS.relation,'relation'); if(!objectIds.has(r.from)||!objectIds.has(r.to)) throw new Error('关系目标不存在');lines.push(`${r.from} → ${r.to}:${text(r.action,'action')}。`);}
44
45
  const variants=source.variants?.length?source.variants:[{id:'base'}],variantIds=new Set();
45
46
  for(const variant of variants) {
46
- keys(variant,['id','composition','seed'],'variant');id(variant.id); if(variantIds.has(variant.id)) throw new Error('variant ID 重复');variantIds.add(variant.id);
47
+ keys(variant,GENERATION_FIELDS.variant,'variant');id(variant.id); if(variantIds.has(variant.id)) throw new Error('variant ID 重复');variantIds.add(variant.id);
47
48
  const p=presentation(profile,{...source.composition,...variant.composition},d);
48
49
  if(!objectIds.has(p.value.focalTarget)) throw new Error('视觉焦点不存在');
49
50
  const seed=variant.seed??source.seed??parseInt(hash([projectId,jobId,source.id]).slice(0,7),16); integer(seed,'seed');
package/lib/lifecycle.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import {workerAlive} from './worker-process.mjs';
1
2
  /** Execution completion is separate from proof that all side effects have stopped. */
2
3
  export const RUN_STATES = Object.freeze([
3
4
  "queued",
@@ -19,9 +20,7 @@ export function analysisLocallyStopped(task) {
19
20
  !Number.isFinite(Date.parse(task.finishedAt)) ||
20
21
  !Number.isSafeInteger(task.workerPid) || task.workerPid <= 0 ||
21
22
  task.plan || task.promptId || Object.keys(task.remoteExecutions ?? {}).length) return false;
22
- try { process.kill(task.workerPid, 0); return false; } catch (error) {
23
- return error.code === 'ESRCH';
24
- }
23
+ return !workerAlive(task);
25
24
  }
26
25
  export function executionSettled(task) {
27
26
  if (analysisLocallyStopped(task)) return true;
@@ -0,0 +1,14 @@
1
+ import {execFileSync} from 'node:child_process';
2
+ export function processIdentity(pid) {
3
+ if(!Number.isSafeInteger(pid)||pid<1)return null;
4
+ try {
5
+ if(process.platform==='win32') {
6
+ const script=`$p=Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"; if($p){[pscustomobject]@{pid=$p.ProcessId;exe=$p.ExecutablePath;created=$p.CreationDate.ToUniversalTime().ToString('o');command=$p.CommandLine}|ConvertTo-Json -Compress}`;
7
+ const output=execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true}).trim();
8
+ return output?JSON.parse(output):null;
9
+ }
10
+ const created=execFileSync('ps',['-p',String(pid),'-o','lstart='],{encoding:'utf8'}).trim();
11
+ const command=execFileSync('ps',['-p',String(pid),'-o','args='],{encoding:'utf8'}).trim();
12
+ return created?{pid,created,command}:null;
13
+ }catch{return null;}
14
+ }
package/lib/service.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import {processIdentity} from './process-identity.mjs';
2
+ export {processIdentity} from './process-identity.mjs';
1
3
  import {homedir} from 'node:os';
2
4
  import {spawn,execFileSync} from 'node:child_process';
3
5
  import {openSync,closeSync,existsSync,readdirSync} from 'node:fs';
@@ -7,19 +9,6 @@ import {writeJson,hash} from './shared.mjs';
7
9
  import {http,sleep,locked,stateRead,alive} from './runtime.mjs';
8
10
  import {inspectEnvironment,workflowError} from './diagnostics.mjs';
9
11
 
10
- export function processIdentity(pid) {
11
- if(!Number.isSafeInteger(pid)||pid<1)return null;
12
- try {
13
- if(process.platform==='win32') {
14
- const script=`$p=Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"; if($p){[pscustomobject]@{pid=$p.ProcessId;exe=$p.ExecutablePath;created=$p.CreationDate.ToUniversalTime().ToString('o');command=$p.CommandLine}|ConvertTo-Json -Compress}`;
15
- const output=execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true}).trim();
16
- return output?JSON.parse(output):null;
17
- }
18
- const created=execFileSync('ps',['-p',String(pid),'-o','lstart='],{encoding:'utf8'}).trim();
19
- const command=execFileSync('ps',['-p',String(pid),'-o','args='],{encoding:'utf8'}).trim();
20
- return created?{pid,created,command}:null;
21
- }catch{return null;}
22
- }
23
12
  export async function stopIdentity(identity,{timeout=10000}={}) {
24
13
  const current=processIdentity(identity.pid);
25
14
  if(!current)return;
@@ -0,0 +1,29 @@
1
+ import {keys} from './shared.mjs';
2
+
3
+ export const GENERATION_FIELDS = Object.freeze({
4
+ item:['id','seed','intent','entities','effects','relations','composition','mustRead','variants','design'],
5
+ entity:['id','kind','appearance','color','role','count','action'],
6
+ effect:['id','kind','target','color','relation','count'],
7
+ relation:['from','to','action'],
8
+ variant:['id','composition','seed'],
9
+ });
10
+ export function taskContract(kind){
11
+ return kind==='generate'?{
12
+ fields:GENERATION_FIELDS,
13
+ effectExample:{id:'glow',kind:'放射光束',target:'subject',color:'橙黄',relation:'从主体裂纹向外辐射',count:1},
14
+ rules:['effects 不支持 description;用 kind 描述效果类型,relation 描述位置和作用方式。','target、from、to 和 focalTarget 必须引用当前资产内的实体ID。','资产规格由 asset 配置;主体、身份色、材质、光效和构图属于任务需求。','草稿允许尚未填完;预案要求内容完整,不会发起生图。'],
15
+ }:{rules:['编辑任务使用 source、changes、preserve、mustRead;保留未修改范围。']};
16
+ }
17
+ /** Drafts may be incomplete, but never accept fields the compiler will discard. */
18
+ export function validateTaskDraft(config){
19
+ if(config.kind!=='generate')return config;
20
+ if(config.items!==undefined&&!Array.isArray(config.items))throw new Error('items 必须是数组');
21
+ for(const [index,item] of (config.items??[]).entries()){
22
+ keys(item,GENERATION_FIELDS.item,`items[${index}]`);
23
+ for(const [field,shape] of [['entities','entity'],['effects','effect'],['relations','relation'],['variants','variant']]){
24
+ if(item[field]!==undefined&&!Array.isArray(item[field]))throw new Error(`items[${index}].${field} 必须是数组`);
25
+ for(const [row,value] of (item[field]??[]).entries())keys(value,GENERATION_FIELDS[shape],`items[${index}].${field}[${row}]`);
26
+ }
27
+ }
28
+ return config;
29
+ }
@@ -1,3 +1,4 @@
1
+ import {processIdentity} from './process-identity.mjs';
1
2
  import { existsSync, readdirSync, renameSync, readFileSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { readJson, writeJson, hash } from "./shared.mjs";
@@ -27,6 +28,7 @@ const persist = () => {
27
28
  writeJson(file, task);
28
29
  };
29
30
  task.workerPid = process.pid;
31
+ task.workerIdentity = processIdentity(process.pid);
30
32
  task.status = "running";
31
33
  persist();
32
34
  const heartbeat = setInterval(persist, 1000);
package/lib/tasks.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import {workerAlive} from './worker-process.mjs';
1
2
  import { spawn } from "node:child_process";
2
3
  import { mkdirSync, openSync, closeSync, existsSync, rmSync } from "node:fs";
3
4
  import { join } from "node:path";
@@ -51,7 +52,7 @@ export function taskView(task) {
51
52
  canResume:
52
53
  terminal(task.status) &&
53
54
  task.status !== "succeeded" &&
54
- !alive(task.workerPid) &&
55
+ !workerAlive(task) &&
55
56
  Object.values(task.remoteExecutions ?? {}).some((receipt) =>
56
57
  ["accepted", "completed"].includes(receipt.state),
57
58
  ) &&
@@ -95,7 +96,7 @@ export function taskStatus(root, taskId) {
95
96
  if (
96
97
  !terminal(task.status) &&
97
98
  Date.now() - Date.parse(task.heartbeat ?? task.createdAt) > 10000 &&
98
- !alive(task.workerPid)
99
+ !workerAlive(task)
99
100
  ) {
100
101
  task.status = "unknown";
101
102
  task.stopConfirmed = false;
@@ -266,17 +267,17 @@ export async function cancelTask(root, taskId, { wait = true } = {}) {
266
267
  if (terminal(task.status)) {
267
268
  if (['style-analysis', 'task-reference-analysis'].includes(task.kind) && task.finishedAt) {
268
269
  const deadline = Date.now() + 5000;
269
- while (alive(task.workerPid) && Date.now() < deadline) await sleep(50);
270
+ while (workerAlive(task) && Date.now() < deadline) await sleep(50);
270
271
  const latest = taskStatus(root, taskId);
271
272
  if (executionSettled(latest)) return latest;
272
273
  }
273
- if (alive(task.workerPid))
274
+ if (workerAlive(task))
274
275
  throw new Error("工作进程尚未退出,停止结果待确认");
275
276
  if (!task.endpoint || !task.promptId)
276
277
  throw new Error("没有可核验的后端任务身份,停止结果未知;保留资源");
277
278
  await cancelPrompt(task.endpoint, task.promptId);
278
279
  const latest = taskStatus(root, taskId);
279
- if (alive(latest.workerPid) || latest.promptId !== task.promptId)
280
+ if (workerAlive(latest) || latest.promptId !== task.promptId)
280
281
  throw new Error("执行身份已变化,请重新查询");
281
282
  latest.promptId = null;
282
283
  latest.unsettled = false;
@@ -327,7 +328,7 @@ export async function shutdown(settings, { closeServices = true } = {}) {
327
328
  // A final heartbeat may precede worker exit by a few milliseconds.
328
329
  const exitDeadline = Date.now() + 5000;
329
330
  while (
330
- tasks(root).some((t) => alive(t.workerPid)) &&
331
+ tasks(root).some((t) => workerAlive(t)) &&
331
332
  Date.now() < exitDeadline
332
333
  )
333
334
  await sleep(50);
@@ -335,7 +336,7 @@ export async function shutdown(settings, { closeServices = true } = {}) {
335
336
  if (
336
337
  tasks(root).some(
337
338
  (t) =>
338
- !executionSettled(taskStatus(root, t.taskId)) || alive(t.workerPid),
339
+ !executionSettled(taskStatus(root, t.taskId)) || workerAlive(t),
339
340
  )
340
341
  )
341
342
  throw new Error("任务尚未停止,保留服务:" + failures.join("; "));
@@ -401,7 +402,7 @@ export async function resumeTask(root, taskId) {
401
402
  return locked(root, "control", async () => {
402
403
  const task = taskStatus(root, taskId),
403
404
  file = taskFile(root, taskId);
404
- if (alive(task.workerPid) || !terminal(task.status))
405
+ if (workerAlive(task) || !terminal(task.status))
405
406
  throw new Error("原工作进程仍在执行,不能恢复");
406
407
  validatePlan(task.plan);
407
408
  if (executionSettled(task) && task.status === "succeeded")
@@ -440,6 +441,7 @@ export async function resumeTask(root, taskId) {
440
441
  task.finishedAt = null;
441
442
  task.heartbeat = new Date().toISOString();
442
443
  task.workerPid = null;
444
+ task.workerIdentity = null;
443
445
  rmSync(file + ".cancel", { force: true });
444
446
  if (gate) rmSync(join(root, "shutdown.json"), { force: true });
445
447
  writeJson(file, task);
@@ -0,0 +1,17 @@
1
+ import {processIdentity} from './process-identity.mjs';
2
+ import {hash} from './shared.mjs';
3
+
4
+ // A recycled PID is not evidence that an old task is still running.
5
+ // Unreadable identities remain live: uncertainty never authorizes termination.
6
+ export function workerAlive(task, inspect = processIdentity) {
7
+ const pid = task.workerPid;
8
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
9
+ try { process.kill(pid, 0); } catch (error) { return error.code !== 'ESRCH'; }
10
+ const current = inspect(pid);
11
+ if (!current) return true;
12
+ if (task.workerIdentity) return hash(current) === hash(task.workerIdentity);
13
+ // Historical receipts have no identity. A process born after the completed
14
+ // task cannot be its worker; allow one second for Unix ps time precision.
15
+ const finished = Date.parse(task.finishedAt), created = Date.parse(current.created);
16
+ return !(Number.isFinite(finished) && Number.isFinite(created) && created > finished + 1000);
17
+ }
package/lib/workspace.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import {validateTaskDraft} from './task-contract.mjs';
1
2
  import {existsSync,mkdirSync,readdirSync,readFileSync,writeFileSync,lstatSync,rmSync,cpSync} from 'node:fs';
2
3
  import {resolve,join,dirname,relative,isAbsolute} from 'node:path';
3
4
  import {randomUUID,createHash} from 'node:crypto';
@@ -81,7 +82,7 @@ export async function createObject(settings,projectId,kind,{name,config={},sourc
81
82
  if(project.schemaVersion!==2)throw new Error('工程需先显式升级');
82
83
  if(typeof name!=='string'||!name.trim())throw new Error('对象名称不能为空');
83
84
  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};
84
- if(kind==='task'){if(!['generate','edit'].includes(config.kind))throw new Error('任务必须声明生成或编辑类型');record.config.project=projectId;}
85
+ if(kind==='task'){validateTaskDraft(config);if(!['generate','edit'].includes(config.kind))throw new Error('任务必须声明生成或编辑类型');record.config.project=projectId;}
85
86
  const directory=objectDirectory(settings.paths.workspace,projectId,kind,objectId);
86
87
  try{if(kind==='task')record.config=await importSources(settings,record,record.config);writeJson(objectFile(settings.paths.workspace,projectId,kind,objectId),record);return record;}
87
88
  catch(error){if(existsSync(directory))rmSync(ownedPath(settings.paths.workspace,directory),{recursive:true,force:true});throw error;}
@@ -112,7 +113,7 @@ export async function importReference(settings,projectId,kind,objectId,revision,
112
113
  });}catch(error){if(created)rmSync(created,{force:true});throw error;}
113
114
  }
114
115
  export async function updateObject(settings,projectId,kind,objectId,revision,{name,config}={}){
115
- return mutateObject(settings,projectId,kind,objectId,revision,async record=>{const before=hash(record.config);if(name!==undefined){if(!name.trim())throw new Error('名称不能为空');record.name=name;}if(config!==undefined){if(kind==='task'&&(config.kind!==record.config.kind||config.project&&config.project!==projectId))throw new Error('任务类型/工程不可修改');record.config=kind==='task'?await importSources(settings,record,config):styleConfig(config);if(kind==='task')record.config.project=projectId;}if(hash(record.config)!==before)if(kind==='task')record.report=null;return record;});
116
+ return mutateObject(settings,projectId,kind,objectId,revision,async record=>{const before=hash(record.config);if(name!==undefined){if(!name.trim())throw new Error('名称不能为空');record.name=name;}if(config!==undefined){if(kind==='task'&&(config.kind!==record.config.kind||config.project&&config.project!==projectId))throw new Error('任务类型/工程不可修改');record.config=kind==='task'?await importSources(settings,record,validateTaskDraft(config)):styleConfig(config);if(kind==='task')record.config.project=projectId;}if(hash(record.config)!==before)if(kind==='task')record.report=null;return record;});
116
117
  }
117
118
  export async function removeReference(settings,projectId,kind,objectId,revision,referenceId){
118
119
  // Keep immutable snapshot resources. A later explicit object cleanup owns deletion.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kevlns/art-workshop",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "private": false,
5
5
  "description": "美术工坊:统一风格的多工程图片生成与编辑工具",
6
6
  "type": "module",