@kevlns/art-workshop 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/AGENTS.md +25 -25
  2. package/LICENSE +21 -21
  3. package/README.md +63 -63
  4. package/art-workshop.mjs +174 -174
  5. package/docs/configuration.md +82 -82
  6. package/docs/core-guidance.md +50 -50
  7. package/docs/data-formats.md +85 -85
  8. package/docs/deployment.md +32 -32
  9. package/docs/local-models/qwen-image-2.1.json +73 -73
  10. package/docs/local-models/qwen-image-2.1.md +33 -33
  11. package/docs/model-architecture.md +78 -78
  12. package/docs/modes.md +67 -67
  13. package/lib/agent.mjs +32 -32
  14. package/lib/analysis-worker.mjs +32 -32
  15. package/lib/analyze.mjs +85 -85
  16. package/lib/asset-profile.mjs +23 -23
  17. package/lib/candidates.mjs +103 -103
  18. package/lib/comfy-recovery.mjs +17 -17
  19. package/lib/conversation.mjs +77 -77
  20. package/lib/core.mjs +75 -75
  21. package/lib/deployment-guide.mjs +12 -12
  22. package/lib/design.mjs +29 -29
  23. package/lib/dimensions.mjs +22 -22
  24. package/lib/edit.mjs +41 -41
  25. package/lib/environment-operations.mjs +49 -49
  26. package/lib/environment-runtime.mjs +99 -99
  27. package/lib/environments.mjs +55 -55
  28. package/lib/executor.mjs +107 -107
  29. package/lib/generate.mjs +58 -58
  30. package/lib/heartbeat.mjs +16 -16
  31. package/lib/images.mjs +1 -1
  32. package/lib/lifecycle.mjs +53 -53
  33. package/lib/migration.mjs +154 -154
  34. package/lib/process-identity.mjs +22 -14
  35. package/lib/project.mjs +39 -39
  36. package/lib/refs.mjs +26 -26
  37. package/lib/runtime.mjs +25 -25
  38. package/lib/service.mjs +134 -126
  39. package/lib/settings.mjs +50 -50
  40. package/lib/shared.mjs +67 -67
  41. package/lib/style-bundle.mjs +85 -85
  42. package/lib/style-contract.mjs +74 -74
  43. package/lib/style-lifecycle.mjs +125 -125
  44. package/lib/style-review.mjs +14 -14
  45. package/lib/task-contract.mjs +93 -93
  46. package/lib/tasks.mjs +497 -497
  47. package/lib/templates.mjs +80 -80
  48. package/lib/vision.mjs +56 -56
  49. package/lib/worker-process.mjs +6 -6
  50. package/lib/workspace.mjs +292 -292
  51. package/package.json +1 -1
  52. package/rules/core-guidance.json +22 -22
  53. package/skills/art-workshop/SKILL.md +17 -17
  54. package/skills/art-workshop/references/conversation.md +11 -11
  55. package/skills/art-workshop/references/expression.md +27 -27
  56. package/skills/art-workshop/references/project.md +109 -109
  57. package/v-cli.plugin.json +2747 -2747
package/lib/tasks.mjs CHANGED
@@ -1,497 +1,497 @@
1
- import {comfyRecoveryPrompts} from './comfy-recovery.mjs';
2
- import {workerAlive} from './worker-process.mjs';
3
- import { spawn } from "node:child_process";
4
- import { mkdirSync, openSync, closeSync, existsSync, rmSync } from "node:fs";
5
- import { join } from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import { randomUUID } from "node:crypto";
8
- import { writeJson, hash } from "./shared.mjs";
9
- import {
10
- runtimeRoot,
11
- taskFile,
12
- tasks,
13
- stateRead,
14
- terminal,
15
- sleep,
16
- locked,
17
- alive,
18
- http,
19
- } from "./runtime.mjs";
20
- import { closeService, healthy } from "./service.mjs";
21
- import { cancelPrompt } from "./comfyui.mjs";
22
- import { validatePlan } from "./plan.mjs";
23
- import {assertExecutableStyle} from './style-contract.mjs';
24
- import { executionSettled, executionLifecycle, analysisLocallyStopped } from "./lifecycle.mjs";
25
- import { bindBackend } from "./backends.mjs";
26
- import { assertPlanCurrent } from "./workspace.mjs";
27
- import {
28
- validateRemotePlan,
29
- assertRemoteContract,
30
- } from "./generation-policy.mjs";
31
-
32
- export function taskItemStates(task) {
33
- if (!task.plan || !Array.isArray(task.items)) return [];
34
- const manifest = task.manifestPath ? stateRead(task.manifestPath) : null;
35
- const rows = manifest?.taskId === task.taskId && manifest?.planHash === task.plan.planHash ? manifest.items ?? [] : [];
36
- return task.items.map(item => {
37
- const row = rows.find(row => row.inputHash === item.inputHash);
38
- return { itemId: item.itemId, variantId: item.variantId, status: row?.status ?? 'queued',
39
- files: row?.files ?? [], expected: (item.execution ?? task.plan.execution)?.perValue ?? 1 };
40
- });
41
- }
42
-
43
- export function taskView(task) {
44
- const {
45
- schema,
46
- taskId,
47
- status,
48
- createdAt,
49
- heartbeat,
50
- finishedAt,
51
- workerPid,
52
- endpoint,
53
- promptId,
54
- manifestPath,
55
- error,
56
- errorDetail,
57
- diagnostic,
58
- remoteCancellation,
59
- unsettled,
60
- currentItem,
61
- logPath,
62
- remoteExecutions,
63
- } = task;
64
- const itemStates = taskItemStates(task);
65
- return {
66
- itemStates,
67
- resultVersion: hash(itemStates),
68
- canResume:
69
- terminal(task.status) &&
70
- task.status !== "succeeded" &&
71
- !workerAlive(task) &&
72
- (!!comfyRecoveryPrompts(task) || Object.values(task.remoteExecutions ?? {}).some((receipt) =>
73
- ["accepted", "completed"].includes(receipt.state),
74
- ) &&
75
- Object.values(task.remoteExecutions ?? {}).every(
76
- (receipt) => receipt.state !== "dispatching",
77
- )),
78
- operationId: task.operationId ?? null,
79
- project: task.plan?.project ?? task.project,
80
- job: task.plan?.job ?? (task.objectKind === "task" ? task.objectId : null),
81
- styleId: task.styleId ?? null,
82
- lifecycle: executionLifecycle(task),
83
- stopConfirmed: executionSettled(task),
84
- upstreamExecutionUnknown: analysisLocallyStopped(task) && !!task.remoteCancellation,
85
- schema,
86
- taskId,
87
- status,
88
- createdAt,
89
- heartbeat,
90
- finishedAt,
91
- workerPid,
92
- endpoint,
93
- promptId,
94
- manifestPath,
95
- error,
96
- errorDetail,
97
- diagnostic,
98
- remoteCancellation,
99
- remoteExecutions,
100
- unsettled,
101
- currentItem,
102
- logPath,
103
- backend:
104
- task.plan?.backend?.id ?? task.analysisProvider?.providerId ?? "bailian",
105
- configuration: task.plan?.snapshots?.job ?? null,
106
- };
107
- }
108
-
109
- export function taskStatus(root, taskId) {
110
- const file = taskFile(root, taskId),
111
- task = stateRead(file);
112
- if (!task) throw new Error("任务不存在 " + taskId);
113
- if (
114
- !terminal(task.status) &&
115
- Date.now() - Date.parse(task.heartbeat ?? task.createdAt) > 10000 &&
116
- !workerAlive(task)
117
- ) {
118
- task.status = "unknown";
119
- task.stopConfirmed = false;
120
- task.unsettled = true;
121
- task.error =
122
- "工作进程退出;后端任务可能仍在运行,请恢复原运行以查询并取回结果,或停止任务确认清理";
123
- writeJson(file, task);
124
- }
125
- return analysisLocallyStopped(task) ? { ...task, stopConfirmed: true } : task;
126
- }
127
- export function failedItems(root, runId, plan) {
128
- const original = taskStatus(root, runId);
129
- if (!executionSettled(original))
130
- throw new Error("原批次停止尚未确认,不能重试");
131
- if (original.plan?.planHash !== plan.planHash)
132
- throw new Error("重试必须使用原批次预案,配置已变化请创建新批次");
133
- if (!original.manifestPath)
134
- throw new Error("原批次没有逐项结果,不能猜测失败项");
135
- const manifest = stateRead(original.manifestPath);
136
- if (manifest?.taskId !== runId || manifest.planHash !== plan.planHash)
137
- throw new Error("原批次结果身份不匹配");
138
- const recovered = new Set();
139
- for (const retry of tasks(root).filter((task) => task.retryOf === runId)) {
140
- const state = taskStatus(root, retry.taskId);
141
- if (!executionSettled(state)) throw new Error("已有重试批次停止尚未确认");
142
- if (state.plan?.planHash !== plan.planHash || !state.manifestPath)
143
- throw new Error("已有重试批次证据不完整");
144
- const result = stateRead(state.manifestPath);
145
- if (result?.taskId !== state.taskId || result.planHash !== plan.planHash)
146
- throw new Error("重试批次结果身份不匹配");
147
- for (const row of result.items)
148
- if (row.ok && row.status === "generated") recovered.add(row.inputHash);
149
- }
150
- const failed = manifest.items.filter(
151
- (row) =>
152
- row.status === "failed" && !row.ok && !recovered.has(row.inputHash),
153
- );
154
- if (failed.some((row) => row.remote?.state === "completed"))
155
- throw new Error("上游已完成,请恢复原运行取回产物,不能重新提交生成");
156
- const items = failed.map((row) => {
157
- const item = plan.items.find((item) => item.inputHash === row.inputHash);
158
- if (!item) throw new Error("失败项不属于原预案");
159
- return item;
160
- });
161
- if (
162
- !items.length ||
163
- new Set(items.map((item) => item.inputHash)).size !== items.length
164
- )
165
- throw new Error("没有唯一可重试的失败项");
166
- return items;
167
- }
168
- export async function startTask(
169
- plan,
170
- items,
171
- settings,
172
- { operationId = null, retryRun = null } = {},
173
- ) {
174
- validatePlan(plan);
175
- assertExecutableStyle(plan);
176
- if (!items.length) throw new Error("没有选中任务");
177
- if (plan.backend?.provider !== "comfyui") {
178
- assertRemoteContract(plan);
179
- validateRemotePlan({ ...plan, items });
180
- }
181
- for (const item of items)
182
- if (!plan.items.some((x) => hash(x) === hash(item)))
183
- throw new Error("执行项不属于计划");
184
- const root = runtimeRoot(settings);
185
- return locked(root, "control", async () => {
186
- if (retryRun) items = failedItems(root, retryRun, plan);
187
- if (operationId) {
188
- if (!/^[a-z0-9-]{1,128}$/.test(operationId))
189
- throw new Error("操作身份非法");
190
- const existing = tasks(root).filter((t) => t.operationId === operationId);
191
- if (existing.length) {
192
- if (
193
- existing.length !== 1 ||
194
- existing[0].plan?.planHash !== plan.planHash ||
195
- hash(existing[0].items) !== hash(items)
196
- )
197
- throw new Error("操作身份已用于其他请求");
198
- return taskView(taskStatus(root, existing[0].taskId));
199
- }
200
- }
201
- assertPlanCurrent(plan, settings);
202
- if (
203
- plan.backend &&
204
- bindBackend(plan, settings, plan.backend.id).planHash !== plan.planHash
205
- )
206
- throw new Error("后端能力或工作流已变化,请重新编译");
207
- const blocked = tasks(root).filter(
208
- (t) =>
209
- (t.plan?.project ?? t.project) === plan.project &&
210
- (t.plan?.job === plan.job ||
211
- (t.objectKind === "task" && t.objectId === plan.job)) &&
212
- !executionSettled(taskStatus(root, t.taskId)),
213
- );
214
- if (blocked.length) throw new Error("同一任务已有运行中或停止未确认的执行");
215
- const gate = stateRead(join(root, "shutdown.json"));
216
- if (gate && alive(gate.pid))
217
- throw new Error("shutdown 正在执行,不能启动任务");
218
- if (gate) rmSync(join(root, "shutdown.json"), { force: true });
219
- const taskId = "task-" + randomUUID(),
220
- file = taskFile(root, taskId);
221
- const logPath = join(root, "tasks", taskId + ".log");
222
- const task = {
223
- schema: "art-workshop/task",
224
- operationId,
225
- retryOf: retryRun,
226
- taskId,
227
- status: "queued",
228
- stopConfirmed: false,
229
- createdAt: new Date().toISOString(),
230
- plan,
231
- items,
232
- outputRoot: settings.paths.output,
233
- root,
234
- config: settings.file,
235
- logPath,
236
- };
237
- writeJson(file, task);
238
- const fd = openSync(logPath, "a");
239
- const child = spawn(
240
- process.execPath,
241
- [fileURLToPath(new URL("./task-worker.mjs", import.meta.url)), file],
242
- { detached: true, windowsHide: true, stdio: ["ignore", fd, fd] },
243
- );
244
- closeSync(fd);
245
- try {
246
- await new Promise((resolve, reject) => {
247
- child.once("spawn", resolve);
248
- child.once("error", reject);
249
- });
250
- } catch (error) {
251
- task.status = "failed";
252
- task.error = "工作进程启动失败:" + error.message;
253
- task.stopConfirmed = true;
254
- task.finishedAt = new Date().toISOString();
255
- writeJson(file, task);
256
- throw error;
257
- }
258
- child.unref();
259
- return {
260
- taskId,
261
- status: "queued",
262
- project: plan.project,
263
- job: plan.job,
264
- logPath,
265
- };
266
- });
267
- }
268
- export async function waitTask(root, taskId, { timeoutSeconds = 3600 } = {}) {
269
- const deadline = Date.now() + timeoutSeconds * 1000;
270
- while (true) {
271
- const state = taskStatus(root, taskId);
272
- if (terminal(state.status)) return state;
273
- if (Date.now() > deadline) throw new Error("等待超时;任务仍在后台运行");
274
- await sleep(250);
275
- }
276
- }
277
- export async function cancelTask(root, taskId, { wait = true } = {}) {
278
- const task = taskStatus(root, taskId),
279
- file = taskFile(root, taskId);
280
- if (executionSettled(task)) return task;
281
- // Only the worker writes a live run document. Cancellation is a separate request;
282
- // parent read-modify-write would race its heartbeat and lose prompt identities.
283
- writeJson(file + ".cancel", { requestedAt: new Date().toISOString() });
284
- if (terminal(task.status)) {
285
- if (['style-analysis', 'task-reference-analysis'].includes(task.kind) && task.finishedAt) {
286
- const deadline = Date.now() + 5000;
287
- while (workerAlive(task) && Date.now() < deadline) await sleep(50);
288
- const latest = taskStatus(root, taskId);
289
- if (executionSettled(latest)) return latest;
290
- }
291
- if (workerAlive(task))
292
- throw new Error("工作进程尚未退出,停止结果待确认");
293
- if (!task.endpoint || !task.promptId)
294
- throw new Error("没有可核验的后端任务身份,停止结果未知;保留资源");
295
- await cancelPrompt(task.endpoint, task.promptId);
296
- const latest = taskStatus(root, taskId);
297
- if (workerAlive(latest) || latest.promptId !== task.promptId)
298
- throw new Error("执行身份已变化,请重新查询");
299
- latest.promptId = null;
300
- latest.unsettled = false;
301
- latest.stopConfirmed = true;
302
- latest.status = "cancelled";
303
- latest.finishedAt = new Date().toISOString();
304
- writeJson(file, latest);
305
- return latest;
306
- }
307
- return wait
308
- ? waitTask(root, taskId, { timeoutSeconds: 60 })
309
- : { taskId, status: "cancelling", stopConfirmed: false };
310
- }
311
-
312
- export async function shutdown(settings, { closeServices = true } = {}) {
313
- const root = runtimeRoot(settings);
314
- return locked(root, "control", async () => {
315
- const gate = join(root, "shutdown.json");
316
- writeJson(gate, { pid: process.pid, startedAt: new Date().toISOString() });
317
- const failures = [],
318
- stopped = [];
319
- try {
320
- const active = tasks(root).filter(
321
- (t) => !executionSettled(taskStatus(root, t.taskId)),
322
- );
323
- for (const task of active)
324
- try {
325
- await cancelTask(root, task.taskId, { wait: false });
326
- } catch (e) {
327
- failures.push(task.taskId + ": " + e.message);
328
- }
329
- const backends = Object.entries(settings.generation?.backends ?? {})
330
- .filter(([, b]) => b.provider === "comfyui")
331
- .map(([id, b]) => ({ id, ...b }));
332
- // Frozen tasks may refer to backends removed from the current configuration.
333
- for (const task of tasks(root))
334
- if (task.plan?.backend?.provider === "comfyui")
335
- backends.push(task.plan.backend);
336
- const endpoints = new Map();
337
- for (const b of backends)
338
- for (const endpoint of b.endpoints) endpoints.set(endpoint, b);
339
- for (const task of active)
340
- try {
341
- await waitTask(root, task.taskId, { timeoutSeconds: 60 });
342
- } catch (e) {
343
- failures.push(task.taskId + ": " + e.message);
344
- }
345
- // A final heartbeat may precede worker exit by a few milliseconds.
346
- const exitDeadline = Date.now() + 5000;
347
- while (
348
- tasks(root).some((t) => workerAlive(t)) &&
349
- Date.now() < exitDeadline
350
- )
351
- await sleep(50);
352
- // Never close the service while a live art worker is still using it.
353
- const blockers = tasks(root).filter(
354
- (t) =>
355
- !executionSettled(taskStatus(root, t.taskId)) || workerAlive(t),
356
- );
357
- if (blockers.length)
358
- throw new Error(
359
- "任务尚未停止,保留服务:" +
360
- (failures.length
361
- ? failures.join("; ")
362
- : blockers
363
- .map(
364
- (t) =>
365
- t.taskId + "(status=" + t.status + ", pid=" + t.workerPid + ")",
366
- )
367
- .join("; ")),
368
- );
369
- if (failures.length)
370
- throw new Error("任务停止尚未确认,保留服务:" + failures.join("; "));
371
- if (!closeServices)
372
- return {
373
- ok: true,
374
- cancelledTasks: active.map((t) => t.taskId),
375
- services: [],
376
- };
377
- // A shared ComfyUI can contain jobs outside this workspace. Never clear its
378
- // queue or interrupt them; owned workers cancel only their verified prompt.
379
- for (const [endpoint, backend] of endpoints)
380
- if (await healthy(endpoint, backend)) {
381
- const queue = await http(endpoint, "/queue");
382
- if (
383
- (queue.queue_running ?? []).length ||
384
- (queue.queue_pending ?? []).length
385
- )
386
- throw new Error("服务仍有其他任务,保留服务:" + endpoint);
387
- }
388
- for (const [endpoint, backend] of endpoints)
389
- try {
390
- stopped.push(await closeService(root, endpoint, backend));
391
- } catch (e) {
392
- failures.push(endpoint + ": " + e.message);
393
- }
394
- if (failures.length)
395
- throw new Error("shutdown 未完整完成:" + failures.join("; "));
396
- return {
397
- ok: true,
398
- cancelledTasks: active.map((t) => t.taskId),
399
- remoteCancellationUnconfirmed: active
400
- .filter((t) => taskStatus(root, t.taskId).remoteCancellation)
401
- .map((t) => t.taskId),
402
- services: stopped,
403
- };
404
- } finally {
405
- rmSync(gate, { force: true });
406
- }
407
- });
408
- }
409
-
410
- export function recoverTask(root, projectId, operationId) {
411
- if (
412
- typeof operationId !== "string" ||
413
- !/^[a-z0-9-]{1,128}$/.test(operationId)
414
- )
415
- throw new Error("恢复操作身份非法");
416
- const matches = tasks(root).filter(
417
- (t) =>
418
- t.operationId === operationId &&
419
- (t.plan?.project ?? t.project) === projectId,
420
- );
421
- if (matches.length !== 1)
422
- throw new Error("没有唯一的原运行证据,停止状态未知;禁止重新启动");
423
- return taskView(taskStatus(root, matches[0].taskId));
424
- }
425
-
426
- /** Resume only durable original remote identities. This path never submits a new request. */
427
- export async function resumeTask(root, taskId) {
428
- return locked(root, "control", async () => {
429
- const task = taskStatus(root, taskId),
430
- file = taskFile(root, taskId);
431
- if (workerAlive(task) || !terminal(task.status))
432
- throw new Error("原工作进程仍在执行,不能恢复");
433
- validatePlan(task.plan);
434
- if (executionSettled(task) && task.status === "succeeded")
435
- return taskView(task);
436
- const localPrompts = comfyRecoveryPrompts(task);
437
- const identities = Object.entries(task.remoteExecutions ?? {});
438
- if (
439
- !localPrompts && (!identities.length ||
440
- identities.some(
441
- ([key, receipt]) =>
442
- !["accepted", "completed", "failed", "cancelled"].includes(
443
- receipt.state,
444
- ) ||
445
- !task.items.some(
446
- (item) =>
447
- item.inputHash === key &&
448
- item.request &&
449
- hash(item.request) === receipt.requestHash,
450
- ),
451
- ))
452
- )
453
- throw new Error("缺少唯一可恢复的上游任务身份;禁止重新提交");
454
- if (
455
- !localPrompts && !identities.some(([, receipt]) =>
456
- ["accepted", "completed"].includes(receipt.state),
457
- )
458
- )
459
- throw new Error("没有可继续查询或取回的原任务");
460
- const gate = stateRead(join(root, "shutdown.json"));
461
- if (gate && alive(gate.pid)) throw new Error("shutdown 正在执行,不能恢复");
462
- task.error = null;
463
- task.diagnostic = null;
464
- if (localPrompts) task.comfyPrompts = localPrompts;
465
- task.resumeOnly = true;
466
- task.status = "queued";
467
- task.stopConfirmed = false;
468
- task.unsettled = true;
469
- task.finishedAt = null;
470
- task.heartbeat = new Date().toISOString();
471
- task.workerPid = null;
472
- task.workerIdentity = null;
473
- rmSync(file + ".cancel", { force: true });
474
- if (gate) rmSync(join(root, "shutdown.json"), { force: true });
475
- writeJson(file, task);
476
- const fd = openSync(task.logPath, "a"),
477
- child = spawn(
478
- process.execPath,
479
- [fileURLToPath(new URL("./task-worker.mjs", import.meta.url)), file],
480
- { detached: true, windowsHide: true, stdio: ["ignore", fd, fd] },
481
- );
482
- closeSync(fd);
483
- try {
484
- await new Promise((resolve, reject) => {
485
- child.once("spawn", resolve);
486
- child.once("error", reject);
487
- });
488
- } catch (error) {
489
- task.status = "unknown";
490
- task.error = error.message;
491
- writeJson(file, task);
492
- throw error;
493
- }
494
- child.unref();
495
- return taskView(task);
496
- });
497
- }
1
+ import {comfyRecoveryPrompts} from './comfy-recovery.mjs';
2
+ import {workerAlive} from './worker-process.mjs';
3
+ import { spawn } from "node:child_process";
4
+ import { mkdirSync, openSync, closeSync, existsSync, rmSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { randomUUID } from "node:crypto";
8
+ import { writeJson, hash } from "./shared.mjs";
9
+ import {
10
+ runtimeRoot,
11
+ taskFile,
12
+ tasks,
13
+ stateRead,
14
+ terminal,
15
+ sleep,
16
+ locked,
17
+ alive,
18
+ http,
19
+ } from "./runtime.mjs";
20
+ import { closeService, healthy } from "./service.mjs";
21
+ import { cancelPrompt } from "./comfyui.mjs";
22
+ import { validatePlan } from "./plan.mjs";
23
+ import {assertExecutableStyle} from './style-contract.mjs';
24
+ import { executionSettled, executionLifecycle, analysisLocallyStopped } from "./lifecycle.mjs";
25
+ import { bindBackend } from "./backends.mjs";
26
+ import { assertPlanCurrent } from "./workspace.mjs";
27
+ import {
28
+ validateRemotePlan,
29
+ assertRemoteContract,
30
+ } from "./generation-policy.mjs";
31
+
32
+ export function taskItemStates(task) {
33
+ if (!task.plan || !Array.isArray(task.items)) return [];
34
+ const manifest = task.manifestPath ? stateRead(task.manifestPath) : null;
35
+ const rows = manifest?.taskId === task.taskId && manifest?.planHash === task.plan.planHash ? manifest.items ?? [] : [];
36
+ return task.items.map(item => {
37
+ const row = rows.find(row => row.inputHash === item.inputHash);
38
+ return { itemId: item.itemId, variantId: item.variantId, status: row?.status ?? 'queued',
39
+ files: row?.files ?? [], expected: (item.execution ?? task.plan.execution)?.perValue ?? 1 };
40
+ });
41
+ }
42
+
43
+ export function taskView(task) {
44
+ const {
45
+ schema,
46
+ taskId,
47
+ status,
48
+ createdAt,
49
+ heartbeat,
50
+ finishedAt,
51
+ workerPid,
52
+ endpoint,
53
+ promptId,
54
+ manifestPath,
55
+ error,
56
+ errorDetail,
57
+ diagnostic,
58
+ remoteCancellation,
59
+ unsettled,
60
+ currentItem,
61
+ logPath,
62
+ remoteExecutions,
63
+ } = task;
64
+ const itemStates = taskItemStates(task);
65
+ return {
66
+ itemStates,
67
+ resultVersion: hash(itemStates),
68
+ canResume:
69
+ terminal(task.status) &&
70
+ task.status !== "succeeded" &&
71
+ !workerAlive(task) &&
72
+ (!!comfyRecoveryPrompts(task) || Object.values(task.remoteExecutions ?? {}).some((receipt) =>
73
+ ["accepted", "completed"].includes(receipt.state),
74
+ ) &&
75
+ Object.values(task.remoteExecutions ?? {}).every(
76
+ (receipt) => receipt.state !== "dispatching",
77
+ )),
78
+ operationId: task.operationId ?? null,
79
+ project: task.plan?.project ?? task.project,
80
+ job: task.plan?.job ?? (task.objectKind === "task" ? task.objectId : null),
81
+ styleId: task.styleId ?? null,
82
+ lifecycle: executionLifecycle(task),
83
+ stopConfirmed: executionSettled(task),
84
+ upstreamExecutionUnknown: analysisLocallyStopped(task) && !!task.remoteCancellation,
85
+ schema,
86
+ taskId,
87
+ status,
88
+ createdAt,
89
+ heartbeat,
90
+ finishedAt,
91
+ workerPid,
92
+ endpoint,
93
+ promptId,
94
+ manifestPath,
95
+ error,
96
+ errorDetail,
97
+ diagnostic,
98
+ remoteCancellation,
99
+ remoteExecutions,
100
+ unsettled,
101
+ currentItem,
102
+ logPath,
103
+ backend:
104
+ task.plan?.backend?.id ?? task.analysisProvider?.providerId ?? "bailian",
105
+ configuration: task.plan?.snapshots?.job ?? null,
106
+ };
107
+ }
108
+
109
+ export function taskStatus(root, taskId) {
110
+ const file = taskFile(root, taskId),
111
+ task = stateRead(file);
112
+ if (!task) throw new Error("任务不存在 " + taskId);
113
+ if (
114
+ !terminal(task.status) &&
115
+ Date.now() - Date.parse(task.heartbeat ?? task.createdAt) > 10000 &&
116
+ !workerAlive(task)
117
+ ) {
118
+ task.status = "unknown";
119
+ task.stopConfirmed = false;
120
+ task.unsettled = true;
121
+ task.error =
122
+ "工作进程退出;后端任务可能仍在运行,请恢复原运行以查询并取回结果,或停止任务确认清理";
123
+ writeJson(file, task);
124
+ }
125
+ return analysisLocallyStopped(task) ? { ...task, stopConfirmed: true } : task;
126
+ }
127
+ export function failedItems(root, runId, plan) {
128
+ const original = taskStatus(root, runId);
129
+ if (!executionSettled(original))
130
+ throw new Error("原批次停止尚未确认,不能重试");
131
+ if (original.plan?.planHash !== plan.planHash)
132
+ throw new Error("重试必须使用原批次预案,配置已变化请创建新批次");
133
+ if (!original.manifestPath)
134
+ throw new Error("原批次没有逐项结果,不能猜测失败项");
135
+ const manifest = stateRead(original.manifestPath);
136
+ if (manifest?.taskId !== runId || manifest.planHash !== plan.planHash)
137
+ throw new Error("原批次结果身份不匹配");
138
+ const recovered = new Set();
139
+ for (const retry of tasks(root).filter((task) => task.retryOf === runId)) {
140
+ const state = taskStatus(root, retry.taskId);
141
+ if (!executionSettled(state)) throw new Error("已有重试批次停止尚未确认");
142
+ if (state.plan?.planHash !== plan.planHash || !state.manifestPath)
143
+ throw new Error("已有重试批次证据不完整");
144
+ const result = stateRead(state.manifestPath);
145
+ if (result?.taskId !== state.taskId || result.planHash !== plan.planHash)
146
+ throw new Error("重试批次结果身份不匹配");
147
+ for (const row of result.items)
148
+ if (row.ok && row.status === "generated") recovered.add(row.inputHash);
149
+ }
150
+ const failed = manifest.items.filter(
151
+ (row) =>
152
+ row.status === "failed" && !row.ok && !recovered.has(row.inputHash),
153
+ );
154
+ if (failed.some((row) => row.remote?.state === "completed"))
155
+ throw new Error("上游已完成,请恢复原运行取回产物,不能重新提交生成");
156
+ const items = failed.map((row) => {
157
+ const item = plan.items.find((item) => item.inputHash === row.inputHash);
158
+ if (!item) throw new Error("失败项不属于原预案");
159
+ return item;
160
+ });
161
+ if (
162
+ !items.length ||
163
+ new Set(items.map((item) => item.inputHash)).size !== items.length
164
+ )
165
+ throw new Error("没有唯一可重试的失败项");
166
+ return items;
167
+ }
168
+ export async function startTask(
169
+ plan,
170
+ items,
171
+ settings,
172
+ { operationId = null, retryRun = null } = {},
173
+ ) {
174
+ validatePlan(plan);
175
+ assertExecutableStyle(plan);
176
+ if (!items.length) throw new Error("没有选中任务");
177
+ if (plan.backend?.provider !== "comfyui") {
178
+ assertRemoteContract(plan);
179
+ validateRemotePlan({ ...plan, items });
180
+ }
181
+ for (const item of items)
182
+ if (!plan.items.some((x) => hash(x) === hash(item)))
183
+ throw new Error("执行项不属于计划");
184
+ const root = runtimeRoot(settings);
185
+ return locked(root, "control", async () => {
186
+ if (retryRun) items = failedItems(root, retryRun, plan);
187
+ if (operationId) {
188
+ if (!/^[a-z0-9-]{1,128}$/.test(operationId))
189
+ throw new Error("操作身份非法");
190
+ const existing = tasks(root).filter((t) => t.operationId === operationId);
191
+ if (existing.length) {
192
+ if (
193
+ existing.length !== 1 ||
194
+ existing[0].plan?.planHash !== plan.planHash ||
195
+ hash(existing[0].items) !== hash(items)
196
+ )
197
+ throw new Error("操作身份已用于其他请求");
198
+ return taskView(taskStatus(root, existing[0].taskId));
199
+ }
200
+ }
201
+ assertPlanCurrent(plan, settings);
202
+ if (
203
+ plan.backend &&
204
+ bindBackend(plan, settings, plan.backend.id).planHash !== plan.planHash
205
+ )
206
+ throw new Error("后端能力或工作流已变化,请重新编译");
207
+ const blocked = tasks(root).filter(
208
+ (t) =>
209
+ (t.plan?.project ?? t.project) === plan.project &&
210
+ (t.plan?.job === plan.job ||
211
+ (t.objectKind === "task" && t.objectId === plan.job)) &&
212
+ !executionSettled(taskStatus(root, t.taskId)),
213
+ );
214
+ if (blocked.length) throw new Error("同一任务已有运行中或停止未确认的执行");
215
+ const gate = stateRead(join(root, "shutdown.json"));
216
+ if (gate && alive(gate.pid))
217
+ throw new Error("shutdown 正在执行,不能启动任务");
218
+ if (gate) rmSync(join(root, "shutdown.json"), { force: true });
219
+ const taskId = "task-" + randomUUID(),
220
+ file = taskFile(root, taskId);
221
+ const logPath = join(root, "tasks", taskId + ".log");
222
+ const task = {
223
+ schema: "art-workshop/task",
224
+ operationId,
225
+ retryOf: retryRun,
226
+ taskId,
227
+ status: "queued",
228
+ stopConfirmed: false,
229
+ createdAt: new Date().toISOString(),
230
+ plan,
231
+ items,
232
+ outputRoot: settings.paths.output,
233
+ root,
234
+ config: settings.file,
235
+ logPath,
236
+ };
237
+ writeJson(file, task);
238
+ const fd = openSync(logPath, "a");
239
+ const child = spawn(
240
+ process.execPath,
241
+ [fileURLToPath(new URL("./task-worker.mjs", import.meta.url)), file],
242
+ { detached: true, windowsHide: true, stdio: ["ignore", fd, fd] },
243
+ );
244
+ closeSync(fd);
245
+ try {
246
+ await new Promise((resolve, reject) => {
247
+ child.once("spawn", resolve);
248
+ child.once("error", reject);
249
+ });
250
+ } catch (error) {
251
+ task.status = "failed";
252
+ task.error = "工作进程启动失败:" + error.message;
253
+ task.stopConfirmed = true;
254
+ task.finishedAt = new Date().toISOString();
255
+ writeJson(file, task);
256
+ throw error;
257
+ }
258
+ child.unref();
259
+ return {
260
+ taskId,
261
+ status: "queued",
262
+ project: plan.project,
263
+ job: plan.job,
264
+ logPath,
265
+ };
266
+ });
267
+ }
268
+ export async function waitTask(root, taskId, { timeoutSeconds = 3600 } = {}) {
269
+ const deadline = Date.now() + timeoutSeconds * 1000;
270
+ while (true) {
271
+ const state = taskStatus(root, taskId);
272
+ if (terminal(state.status)) return state;
273
+ if (Date.now() > deadline) throw new Error("等待超时;任务仍在后台运行");
274
+ await sleep(250);
275
+ }
276
+ }
277
+ export async function cancelTask(root, taskId, { wait = true } = {}) {
278
+ const task = taskStatus(root, taskId),
279
+ file = taskFile(root, taskId);
280
+ if (executionSettled(task)) return task;
281
+ // Only the worker writes a live run document. Cancellation is a separate request;
282
+ // parent read-modify-write would race its heartbeat and lose prompt identities.
283
+ writeJson(file + ".cancel", { requestedAt: new Date().toISOString() });
284
+ if (terminal(task.status)) {
285
+ if (['style-analysis', 'task-reference-analysis'].includes(task.kind) && task.finishedAt) {
286
+ const deadline = Date.now() + 5000;
287
+ while (workerAlive(task) && Date.now() < deadline) await sleep(50);
288
+ const latest = taskStatus(root, taskId);
289
+ if (executionSettled(latest)) return latest;
290
+ }
291
+ if (workerAlive(task))
292
+ throw new Error("工作进程尚未退出,停止结果待确认");
293
+ if (!task.endpoint || !task.promptId)
294
+ throw new Error("没有可核验的后端任务身份,停止结果未知;保留资源");
295
+ await cancelPrompt(task.endpoint, task.promptId);
296
+ const latest = taskStatus(root, taskId);
297
+ if (workerAlive(latest) || latest.promptId !== task.promptId)
298
+ throw new Error("执行身份已变化,请重新查询");
299
+ latest.promptId = null;
300
+ latest.unsettled = false;
301
+ latest.stopConfirmed = true;
302
+ latest.status = "cancelled";
303
+ latest.finishedAt = new Date().toISOString();
304
+ writeJson(file, latest);
305
+ return latest;
306
+ }
307
+ return wait
308
+ ? waitTask(root, taskId, { timeoutSeconds: 60 })
309
+ : { taskId, status: "cancelling", stopConfirmed: false };
310
+ }
311
+
312
+ export async function shutdown(settings, { closeServices = true } = {}) {
313
+ const root = runtimeRoot(settings);
314
+ return locked(root, "control", async () => {
315
+ const gate = join(root, "shutdown.json");
316
+ writeJson(gate, { pid: process.pid, startedAt: new Date().toISOString() });
317
+ const failures = [],
318
+ stopped = [];
319
+ try {
320
+ const active = tasks(root).filter(
321
+ (t) => !executionSettled(taskStatus(root, t.taskId)),
322
+ );
323
+ for (const task of active)
324
+ try {
325
+ await cancelTask(root, task.taskId, { wait: false });
326
+ } catch (e) {
327
+ failures.push(task.taskId + ": " + e.message);
328
+ }
329
+ const backends = Object.entries(settings.generation?.backends ?? {})
330
+ .filter(([, b]) => b.provider === "comfyui")
331
+ .map(([id, b]) => ({ id, ...b }));
332
+ // Frozen tasks may refer to backends removed from the current configuration.
333
+ for (const task of tasks(root))
334
+ if (task.plan?.backend?.provider === "comfyui")
335
+ backends.push(task.plan.backend);
336
+ const endpoints = new Map();
337
+ for (const b of backends)
338
+ for (const endpoint of b.endpoints) endpoints.set(endpoint, b);
339
+ for (const task of active)
340
+ try {
341
+ await waitTask(root, task.taskId, { timeoutSeconds: 60 });
342
+ } catch (e) {
343
+ failures.push(task.taskId + ": " + e.message);
344
+ }
345
+ // A final heartbeat may precede worker exit by a few milliseconds.
346
+ const exitDeadline = Date.now() + 5000;
347
+ while (
348
+ tasks(root).some((t) => workerAlive(t)) &&
349
+ Date.now() < exitDeadline
350
+ )
351
+ await sleep(50);
352
+ // Never close the service while a live art worker is still using it.
353
+ const blockers = tasks(root).filter(
354
+ (t) =>
355
+ !executionSettled(taskStatus(root, t.taskId)) || workerAlive(t),
356
+ );
357
+ if (blockers.length)
358
+ throw new Error(
359
+ "任务尚未停止,保留服务:" +
360
+ (failures.length
361
+ ? failures.join("; ")
362
+ : blockers
363
+ .map(
364
+ (t) =>
365
+ t.taskId + "(status=" + t.status + ", pid=" + t.workerPid + ")",
366
+ )
367
+ .join("; ")),
368
+ );
369
+ if (failures.length)
370
+ throw new Error("任务停止尚未确认,保留服务:" + failures.join("; "));
371
+ if (!closeServices)
372
+ return {
373
+ ok: true,
374
+ cancelledTasks: active.map((t) => t.taskId),
375
+ services: [],
376
+ };
377
+ // A shared ComfyUI can contain jobs outside this workspace. Never clear its
378
+ // queue or interrupt them; owned workers cancel only their verified prompt.
379
+ for (const [endpoint, backend] of endpoints)
380
+ if (await healthy(endpoint, backend)) {
381
+ const queue = await http(endpoint, "/queue");
382
+ if (
383
+ (queue.queue_running ?? []).length ||
384
+ (queue.queue_pending ?? []).length
385
+ )
386
+ throw new Error("服务仍有其他任务,保留服务:" + endpoint);
387
+ }
388
+ for (const [endpoint, backend] of endpoints)
389
+ try {
390
+ stopped.push(await closeService(root, endpoint, backend));
391
+ } catch (e) {
392
+ failures.push(endpoint + ": " + e.message);
393
+ }
394
+ if (failures.length)
395
+ throw new Error("shutdown 未完整完成:" + failures.join("; "));
396
+ return {
397
+ ok: true,
398
+ cancelledTasks: active.map((t) => t.taskId),
399
+ remoteCancellationUnconfirmed: active
400
+ .filter((t) => taskStatus(root, t.taskId).remoteCancellation)
401
+ .map((t) => t.taskId),
402
+ services: stopped,
403
+ };
404
+ } finally {
405
+ rmSync(gate, { force: true });
406
+ }
407
+ });
408
+ }
409
+
410
+ export function recoverTask(root, projectId, operationId) {
411
+ if (
412
+ typeof operationId !== "string" ||
413
+ !/^[a-z0-9-]{1,128}$/.test(operationId)
414
+ )
415
+ throw new Error("恢复操作身份非法");
416
+ const matches = tasks(root).filter(
417
+ (t) =>
418
+ t.operationId === operationId &&
419
+ (t.plan?.project ?? t.project) === projectId,
420
+ );
421
+ if (matches.length !== 1)
422
+ throw new Error("没有唯一的原运行证据,停止状态未知;禁止重新启动");
423
+ return taskView(taskStatus(root, matches[0].taskId));
424
+ }
425
+
426
+ /** Resume only durable original remote identities. This path never submits a new request. */
427
+ export async function resumeTask(root, taskId) {
428
+ return locked(root, "control", async () => {
429
+ const task = taskStatus(root, taskId),
430
+ file = taskFile(root, taskId);
431
+ if (workerAlive(task) || !terminal(task.status))
432
+ throw new Error("原工作进程仍在执行,不能恢复");
433
+ validatePlan(task.plan);
434
+ if (executionSettled(task) && task.status === "succeeded")
435
+ return taskView(task);
436
+ const localPrompts = comfyRecoveryPrompts(task);
437
+ const identities = Object.entries(task.remoteExecutions ?? {});
438
+ if (
439
+ !localPrompts && (!identities.length ||
440
+ identities.some(
441
+ ([key, receipt]) =>
442
+ !["accepted", "completed", "failed", "cancelled"].includes(
443
+ receipt.state,
444
+ ) ||
445
+ !task.items.some(
446
+ (item) =>
447
+ item.inputHash === key &&
448
+ item.request &&
449
+ hash(item.request) === receipt.requestHash,
450
+ ),
451
+ ))
452
+ )
453
+ throw new Error("缺少唯一可恢复的上游任务身份;禁止重新提交");
454
+ if (
455
+ !localPrompts && !identities.some(([, receipt]) =>
456
+ ["accepted", "completed"].includes(receipt.state),
457
+ )
458
+ )
459
+ throw new Error("没有可继续查询或取回的原任务");
460
+ const gate = stateRead(join(root, "shutdown.json"));
461
+ if (gate && alive(gate.pid)) throw new Error("shutdown 正在执行,不能恢复");
462
+ task.error = null;
463
+ task.diagnostic = null;
464
+ if (localPrompts) task.comfyPrompts = localPrompts;
465
+ task.resumeOnly = true;
466
+ task.status = "queued";
467
+ task.stopConfirmed = false;
468
+ task.unsettled = true;
469
+ task.finishedAt = null;
470
+ task.heartbeat = new Date().toISOString();
471
+ task.workerPid = null;
472
+ task.workerIdentity = null;
473
+ rmSync(file + ".cancel", { force: true });
474
+ if (gate) rmSync(join(root, "shutdown.json"), { force: true });
475
+ writeJson(file, task);
476
+ const fd = openSync(task.logPath, "a"),
477
+ child = spawn(
478
+ process.execPath,
479
+ [fileURLToPath(new URL("./task-worker.mjs", import.meta.url)), file],
480
+ { detached: true, windowsHide: true, stdio: ["ignore", fd, fd] },
481
+ );
482
+ closeSync(fd);
483
+ try {
484
+ await new Promise((resolve, reject) => {
485
+ child.once("spawn", resolve);
486
+ child.once("error", reject);
487
+ });
488
+ } catch (error) {
489
+ task.status = "unknown";
490
+ task.error = error.message;
491
+ writeJson(file, task);
492
+ throw error;
493
+ }
494
+ child.unref();
495
+ return taskView(task);
496
+ });
497
+ }