dsh-sendcomfy 0.0.0-stage → 0.5.0

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/lib/http.mjs ADDED
@@ -0,0 +1,302 @@
1
+ /**
2
+ * dsh-sendcomfy —— /api/sendcomfy/* 的 HTTP 适配层
3
+ * ============================================================================
4
+ * 只做「请求 → actions → JSON」的翻译,不写业务逻辑:
5
+ * - 浏览器半端(client.js)全部走这些同源路由,不直连 ComfyUI;
6
+ * - 路由由 Host 插件的 ctx.webServer.register({ kind:'prefix', path:'/api/sendcomfy' }) 挂上。
7
+ *
8
+ * 响应约定:动作级失败也返回 HTTP 200 + `{ ok:false, error }`(面板统一看 json.ok),
9
+ * 只有协议错误(坏 JSON / 超大 body / 未知路由)用 4xx/5xx。
10
+ *
11
+ * 诊断:每个请求完成时追加一行到 `$DSH_HOME/sendcomfy/requests.log`
12
+ * (method / 路由 / HTTP 状态 / 耗时 / 请求体摘要;不含图片二进制与完整工作流 JSON),
13
+ * 用于排查「点了按钮没反应」这类前端问题。日志写失败绝不影响请求。
14
+ */
15
+ import fs from 'node:fs'
16
+ import os from 'node:os'
17
+ import path from 'node:path'
18
+
19
+ const DEFAULT_PREFIX = '/api/sendcomfy'
20
+ const MAX_BODY_BYTES = 5 * 1024 * 1024
21
+ const MAX_LOG_BYTES = 1024 * 1024
22
+
23
+ let requestLogPath = null
24
+ function resolveRequestLogPath() {
25
+ if (requestLogPath) return requestLogPath
26
+ try {
27
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
28
+ const dir = path.join(home, 'sendcomfy')
29
+ fs.mkdirSync(dir, { recursive: true })
30
+ requestLogPath = path.join(dir, 'requests.log')
31
+ return requestLogPath
32
+ } catch {
33
+ return null
34
+ }
35
+ }
36
+
37
+ function summarizeBody(value) {
38
+ if (value === undefined || value === null) return ''
39
+ if (typeof value !== 'object') return String(value).slice(0, 120)
40
+ const parts = []
41
+ for (const key of ['action', 'id', 'name', 'path', 'workflow', 'baseUrl']) {
42
+ if (value[key] !== undefined && value[key] !== null && typeof value[key] !== 'object') {
43
+ parts.push(`${key}=${String(value[key]).slice(0, 80)}`)
44
+ }
45
+ }
46
+ if (typeof value.json === 'string') parts.push(`jsonLen=${value.json.length}`)
47
+ if (value.prompt !== undefined) parts.push('prompt=…')
48
+ if (value.params !== undefined) parts.push('params=…')
49
+ return parts.join(' ')
50
+ }
51
+
52
+ function appendRequestLog(line) {
53
+ try {
54
+ const file = resolveRequestLogPath()
55
+ if (!file) return
56
+ try {
57
+ if (fs.statSync(file).size > MAX_LOG_BYTES) fs.renameSync(file, `${file}.1`)
58
+ } catch {
59
+ /* 文件还不存在 */
60
+ }
61
+ fs.appendFileSync(file, `${line}\n`)
62
+ } catch {
63
+ /* 日志失败不影响请求 */
64
+ }
65
+ }
66
+
67
+ function sendJson(res, status, value) {
68
+ const body = JSON.stringify(value === undefined ? null : value)
69
+ res.writeHead(status, {
70
+ 'Content-Type': 'application/json; charset=utf-8',
71
+ 'Content-Length': Buffer.byteLength(body),
72
+ 'Cache-Control': 'no-store',
73
+ })
74
+ res.end(body)
75
+ }
76
+
77
+ function httpError(status, message) {
78
+ const error = new Error(message)
79
+ error.status = status
80
+ return error
81
+ }
82
+
83
+ async function readBody(req) {
84
+ const chunks = []
85
+ let size = 0
86
+ for await (const chunk of req) {
87
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
88
+ size += buffer.length
89
+ if (size > MAX_BODY_BYTES) throw httpError(413, '请求体过大(上限 5MB)')
90
+ chunks.push(buffer)
91
+ }
92
+ return Buffer.concat(chunks)
93
+ }
94
+
95
+ async function readJson(req) {
96
+ const buffer = await readBody(req)
97
+ if (buffer.length === 0) return {}
98
+ const text = buffer.toString('utf8').trim()
99
+ if (text === '') return {}
100
+ try {
101
+ const value = JSON.parse(text)
102
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
103
+ throw httpError(400, '请求体必须是 JSON 对象')
104
+ }
105
+ req.__sendcomfyBody = value
106
+ return value
107
+ } catch (error) {
108
+ if (error?.status) throw error
109
+ throw httpError(400, `请求体不是合法 JSON:${error?.message || error}`)
110
+ }
111
+ }
112
+
113
+ function truthyQuery(value) {
114
+ return ['1', 'true', 'yes', 'on'].includes(String(value || '').toLowerCase())
115
+ }
116
+
117
+ /**
118
+ * @param {ReturnType<import('./actions.mjs').createActions>} actions
119
+ * @param {{ prefix?: string }} [options]
120
+ * @returns {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => Promise<void>}
121
+ */
122
+ export function createApiHandler(actions, { prefix = DEFAULT_PREFIX } = {}) {
123
+ return async function handle(req, res) {
124
+ if (!req || !res) return
125
+ const startedAt = Date.now()
126
+ let responseStatus = 200
127
+ try {
128
+ const originalWriteHead = res.writeHead
129
+ res.writeHead = function writeHeadPatched(status, ...rest) {
130
+ responseStatus = Number(status) || 200
131
+ return originalWriteHead.call(this, status, ...rest)
132
+ }
133
+ res.once('finish', () => {
134
+ const pathname = (() => {
135
+ try {
136
+ return new URL(req.url || '/', 'http://127.0.0.1').pathname
137
+ } catch {
138
+ return String(req.url || '')
139
+ }
140
+ })()
141
+ appendRequestLog([
142
+ new Date().toISOString(),
143
+ String(req.method || 'GET').toUpperCase(),
144
+ pathname,
145
+ String(responseStatus),
146
+ `${Date.now() - startedAt}ms`,
147
+ summarizeBody(req.__sendcomfyBody),
148
+ ].filter(Boolean).join(' '))
149
+ })
150
+ } catch {
151
+ /* 诊断失败不影响请求 */
152
+ }
153
+ let url
154
+ try {
155
+ url = new URL(req.url || '/', 'http://127.0.0.1')
156
+ } catch {
157
+ sendJson(res, 400, { ok: false, error: '非法请求 URL' })
158
+ return
159
+ }
160
+ const { pathname } = url
161
+ if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) {
162
+ sendJson(res, 404, { ok: false, error: `未知接口:${pathname}` })
163
+ return
164
+ }
165
+ const sub = pathname.slice(prefix.length).replace(/\/+$/, '') || '/'
166
+ const method = String(req.method || 'GET').toUpperCase()
167
+ const wfMatch = /^\/workflows\/([^/]+)$/.exec(sub)
168
+
169
+ try {
170
+ /* ── 状态 / 连接 ─────────────────────────────────────── */
171
+ if (method === 'GET' && sub === '/state') {
172
+ sendJson(res, 200, await actions.getState())
173
+ return
174
+ }
175
+ if (method === 'POST' && sub === '/config') {
176
+ sendJson(res, 200, await actions.setConfig(await readJson(req)))
177
+ return
178
+ }
179
+ if (method === 'POST' && sub === '/test') {
180
+ sendJson(res, 200, await actions.test(await readJson(req)))
181
+ return
182
+ }
183
+
184
+ /* ── 模型 ────────────────────────────────────────────── */
185
+ if (method === 'GET' && sub === '/models') {
186
+ sendJson(res, 200, await actions.listModels({ refresh: truthyQuery(url.searchParams.get('refresh')) }))
187
+ return
188
+ }
189
+
190
+ /* ── 工作流 ──────────────────────────────────────────── */
191
+ if (method === 'GET' && sub === '/workflows') {
192
+ sendJson(res, 200, await actions.listWorkflows())
193
+ return
194
+ }
195
+ if (method === 'GET' && wfMatch) {
196
+ let workflowId
197
+ try {
198
+ workflowId = decodeURIComponent(wfMatch[1])
199
+ } catch {
200
+ throw httpError(400, '工作流 id 的 URL 编码不合法')
201
+ }
202
+ sendJson(res, 200, await actions.getWorkflow(workflowId))
203
+ return
204
+ }
205
+ if (method === 'POST' && sub === '/workflows') {
206
+ const body = await readJson(req)
207
+ const action = String(body.action || '')
208
+ if (action === 'import') {
209
+ sendJson(res, 200, await actions.importWorkflow({ name: body.name, json: body.json, source: body.source }))
210
+ return
211
+ }
212
+ if (action === 'rename') {
213
+ sendJson(res, 200, await actions.renameWorkflow({ id: body.id, name: body.name }))
214
+ return
215
+ }
216
+ if (action === 'update') {
217
+ sendJson(res, 200, await actions.updateWorkflowMeta({
218
+ id: body.id,
219
+ description: body.description,
220
+ tags: body.tags,
221
+ }))
222
+ return
223
+ }
224
+ if (action === 'delete') {
225
+ sendJson(res, 200, await actions.deleteWorkflow(body.id))
226
+ return
227
+ }
228
+ throw httpError(400, `未知 action:${action || '(空)'}(可用 import / rename / delete)`)
229
+ }
230
+
231
+ /* ── ComfyUI 服务器上的工作流 ─────────────────────────── */
232
+ if (method === 'GET' && sub === '/server-workflows') {
233
+ sendJson(res, 200, await actions.listServerWorkflows())
234
+ return
235
+ }
236
+ if (method === 'GET' && sub === '/server-workflows/detail') {
237
+ sendJson(res, 200, await actions.getServerWorkflowDetail({
238
+ path: url.searchParams.get('path') || '',
239
+ name: url.searchParams.get('name') || undefined,
240
+ }))
241
+ return
242
+ }
243
+ if (method === 'POST' && sub === '/server-workflows') {
244
+ const body = await readJson(req)
245
+ if (String(body.action || '') !== 'import') {
246
+ throw httpError(400, `未知 action:${body.action || '(空)'}(可用 import)`)
247
+ }
248
+ sendJson(res, 200, await actions.importServerWorkflow({ path: body.path, name: body.name }))
249
+ return
250
+ }
251
+
252
+ /* ── 运行 / 结果 / 队列 ──────────────────────────────── */
253
+ if (method === 'POST' && sub === '/run') {
254
+ const body = await readJson(req)
255
+ sendJson(res, 200, await actions.run({
256
+ workflow: body.workflow,
257
+ prompt: body.prompt,
258
+ negativePrompt: body.negativePrompt,
259
+ params: body.params,
260
+ wait: body.wait === false ? false : true,
261
+ timeoutSec: body.timeoutSec,
262
+ saveDir: null,
263
+ }))
264
+ return
265
+ }
266
+ if (method === 'GET' && sub === '/image') {
267
+ const result = await actions.getImage({
268
+ filename: url.searchParams.get('filename') || '',
269
+ subfolder: url.searchParams.get('subfolder') || '',
270
+ type: url.searchParams.get('type') || 'output',
271
+ })
272
+ if (!result.ok || !result.buffer) {
273
+ sendJson(res, 404, { ok: false, error: result.error || '图片不存在' })
274
+ return
275
+ }
276
+ res.writeHead(200, {
277
+ 'Content-Type': result.contentType || 'application/octet-stream',
278
+ 'Content-Length': result.buffer.length,
279
+ 'Cache-Control': 'no-store',
280
+ })
281
+ res.end(result.buffer)
282
+ return
283
+ }
284
+ if (method === 'GET' && sub === '/queue') {
285
+ sendJson(res, 200, await actions.getQueue())
286
+ return
287
+ }
288
+ if (method === 'POST' && sub === '/cancel') {
289
+ const body = await readJson(req)
290
+ sendJson(res, 200, await actions.cancel({ promptId: body.promptId }))
291
+ return
292
+ }
293
+
294
+ sendJson(res, 404, { ok: false, error: `未知接口:${method} ${pathname}` })
295
+ } catch (error) {
296
+ const status = Number.isInteger(error?.status) ? error.status : 500
297
+ sendJson(res, status, { ok: false, error: error?.message || String(error) })
298
+ }
299
+ }
300
+ }
301
+
302
+ export default createApiHandler
package/lib/state.mjs ADDED
@@ -0,0 +1,384 @@
1
+ /**
2
+ * dsh-sendcomfy — 本地状态存储(契约见 CONTRACT.md §3)
3
+ *
4
+ * 状态文件:`$DSH_HOME/sendcomfy/state.json`(DSH_HOME 缺省 `~/.dsh`)。
5
+ * - dataDir():返回并确保目录存在。
6
+ * - createStateStore({ dir }):dir 可传(测试用临时目录),不依赖 cwd。
7
+ * - store.read():不存在 -> 默认 State;坏 JSON -> 备份 state.bad-<ts>.json 后回默认。
8
+ * - store.write(state):原子写(临时文件 + rename);写前 normalize。
9
+ * - store.update(mutator):read -> mutator -> write,串行化(并发不丢数据)。
10
+ *
11
+ * 零第三方依赖,只 import Node 内建。
12
+ */
13
+
14
+ import fs from 'node:fs'
15
+ import fsp from 'node:fs/promises'
16
+ import os from 'node:os'
17
+ import path from 'node:path'
18
+ import crypto from 'node:crypto'
19
+ import { DEFAULT_BASE_URL, normalizeBaseUrl } from './comfy.mjs'
20
+
21
+ const STATE_FILE = 'state.json'
22
+ const DEFAULT_TIMEOUT_SEC = 300
23
+ const TIMEOUT_MIN_SEC = 5
24
+ const TIMEOUT_MAX_SEC = 3600
25
+ const MAX_WORKFLOWS = 100
26
+ const MAX_LAST_RUNS = 20
27
+ const VALID_SOURCES = new Set(['ui', 'api', 'server'])
28
+ const VALID_RUN_STATES = new Set(['queued', 'done', 'error', 'timeout'])
29
+ const VALID_PARAM_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'enum'])
30
+
31
+ /** `$DSH_HOME/sendcomfy`,确保 mkdir -p;DSH_HOME 缺省 ~/.dsh。 */
32
+ export function dataDir() {
33
+ const rawHome = process.env.DSH_HOME
34
+ const home = typeof rawHome === 'string' && rawHome.trim()
35
+ ? rawHome.trim()
36
+ : path.join(os.homedir(), '.dsh')
37
+ const dir = path.join(home, 'sendcomfy')
38
+ fs.mkdirSync(dir, { recursive: true })
39
+ return dir
40
+ }
41
+
42
+ /** 'dsh-sendcomfy-<随机>',首次生成后持久。 */
43
+ export function newClientId() {
44
+ return `dsh-sendcomfy-${crypto.randomBytes(6).toString('hex')}`
45
+ }
46
+
47
+ /** slug(name)+'-'+6位hex(契约 §3 WorkflowRecord.id)。 */
48
+ export function makeWorkflowId(name) {
49
+ const slug = String(name || '')
50
+ .toLowerCase()
51
+ .replace(/[^a-z0-9]+/g, '-')
52
+ .replace(/^-+|-+$/g, '')
53
+ .slice(0, 48) || 'workflow'
54
+ return `${slug}-${crypto.randomBytes(3).toString('hex')}`
55
+ }
56
+
57
+ function normalizeIsoString(value) {
58
+ if (value instanceof Date) {
59
+ return Number.isNaN(value.getTime()) ? new Date().toISOString() : value.toISOString()
60
+ }
61
+ if (typeof value === 'string' && value.trim()) {
62
+ const time = Date.parse(value)
63
+ if (!Number.isNaN(time)) return new Date(time).toISOString()
64
+ }
65
+ return new Date().toISOString()
66
+ }
67
+
68
+ function normalizeBaseUrlOr(value) {
69
+ try {
70
+ return normalizeBaseUrl(value)
71
+ } catch {
72
+ return DEFAULT_BASE_URL
73
+ }
74
+ }
75
+
76
+ function normalizeTimeoutSec(value) {
77
+ if (value === undefined || value === null || value === '') return DEFAULT_TIMEOUT_SEC
78
+ const n = Number(value)
79
+ if (!Number.isFinite(n)) return DEFAULT_TIMEOUT_SEC
80
+ return Math.min(TIMEOUT_MAX_SEC, Math.max(TIMEOUT_MIN_SEC, Math.round(n)))
81
+ }
82
+
83
+ function normalizeClientId(value) {
84
+ if (typeof value === 'string') {
85
+ const trimmed = value.trim()
86
+ if (trimmed && trimmed.length <= 200 && !/\s/.test(trimmed)) return trimmed
87
+ }
88
+ return newClientId()
89
+ }
90
+
91
+ function stringArray(value) {
92
+ if (!Array.isArray(value)) return []
93
+ return value.filter((item) => typeof item === 'string' && item !== '')
94
+ }
95
+
96
+ function normalizePrimitive(value) {
97
+ if (typeof value === 'string' || typeof value === 'boolean') return value
98
+ if (typeof value === 'number' && Number.isFinite(value)) return value
99
+ if (value === undefined || value === null) return ''
100
+ if (typeof value === 'object') {
101
+ try {
102
+ return JSON.stringify(value)
103
+ } catch {
104
+ return ''
105
+ }
106
+ }
107
+ return String(value)
108
+ }
109
+
110
+ function normalizeNodes(value) {
111
+ if (!Array.isArray(value)) return []
112
+ const nodes = []
113
+ for (const node of value) {
114
+ if (!node || typeof node !== 'object') continue
115
+ const id = node.id === undefined || node.id === null ? '' : String(node.id)
116
+ const nodeClass = typeof node.class === 'string' ? node.class : (typeof node.type === 'string' ? node.type : '')
117
+ if (!id && !nodeClass) continue
118
+ const out = { id, class: nodeClass }
119
+ if (typeof node.title === 'string' && node.title) out.title = node.title
120
+ nodes.push(out)
121
+ }
122
+ return nodes
123
+ }
124
+
125
+ function normalizeParams(value) {
126
+ if (!Array.isArray(value)) return []
127
+ const params = []
128
+ for (const param of value) {
129
+ if (!param || typeof param !== 'object' || Array.isArray(param)) continue
130
+ const nodeId = param.nodeId === undefined || param.nodeId === null ? '' : String(param.nodeId)
131
+ const inputName = typeof param.inputName === 'string' ? param.inputName : ''
132
+ let paramPath = typeof param.path === 'string' ? param.path : ''
133
+ if (!paramPath && (nodeId || inputName)) paramPath = `${nodeId}.${inputName}`
134
+ if (!paramPath) continue
135
+ const dot = paramPath.indexOf('.')
136
+ const fallbackNodeId = dot >= 0 ? paramPath.slice(0, dot) : nodeId
137
+ const fallbackInputName = dot >= 0 ? paramPath.slice(dot + 1) : inputName
138
+ if (!fallbackInputName) continue
139
+ const value = normalizePrimitive(param.value)
140
+ let type = VALID_PARAM_TYPES.has(param.type) ? param.type : undefined
141
+ if (!type) {
142
+ if (typeof value === 'boolean') type = 'boolean'
143
+ else if (typeof value === 'number') type = Number.isInteger(value) ? 'integer' : 'number'
144
+ else type = 'string'
145
+ }
146
+ const out = {
147
+ path: paramPath,
148
+ nodeId: fallbackNodeId,
149
+ inputName: fallbackInputName,
150
+ nodeClass: typeof param.nodeClass === 'string' ? param.nodeClass : '',
151
+ type,
152
+ value,
153
+ }
154
+ if (typeof param.nodeTitle === 'string' && param.nodeTitle) out.nodeTitle = param.nodeTitle
155
+ const options = stringArray(param.options)
156
+ if (options.length) out.options = options
157
+ for (const key of ['min', 'max', 'step']) {
158
+ const raw = param[key]
159
+ if (raw === undefined || raw === null || raw === '') continue
160
+ const n = Number(raw)
161
+ if (Number.isFinite(n)) out[key] = n
162
+ }
163
+ if (param.multiline === true) out.multiline = true
164
+ if (param.isPrompt === true) out.isPrompt = true
165
+ params.push(out)
166
+ }
167
+ return params
168
+ }
169
+
170
+ function normalizeWorkflow(value) {
171
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null
172
+ const rawName = typeof value.name === 'string' ? value.name.trim() : ''
173
+ const name = rawName ? rawName.slice(0, 200) : '未命名工作流'
174
+ const source = VALID_SOURCES.has(value.source)
175
+ ? value.source
176
+ : (value.uiGraph && typeof value.uiGraph === 'object' ? 'ui' : 'api')
177
+ const id = typeof value.id === 'string' && value.id.trim() ? value.id.trim() : makeWorkflowId(name)
178
+ const apiGraph = value.apiGraph && typeof value.apiGraph === 'object' && !Array.isArray(value.apiGraph)
179
+ ? value.apiGraph
180
+ : {}
181
+ const workflow = {
182
+ id,
183
+ name,
184
+ source,
185
+ apiGraph,
186
+ nodes: normalizeNodes(value.nodes),
187
+ params: normalizeParams(value.params),
188
+ promptTargets: {
189
+ positive: stringArray(value.promptTargets && value.promptTargets.positive),
190
+ negative: stringArray(value.promptTargets && value.promptTargets.negative),
191
+ },
192
+ createdAt: normalizeIsoString(value.createdAt),
193
+ updatedAt: normalizeIsoString(value.updatedAt),
194
+ }
195
+ if (value.uiGraph !== undefined && value.uiGraph !== null) workflow.uiGraph = value.uiGraph
196
+ const warnings = stringArray(value.warnings)
197
+ if (warnings.length) workflow.warnings = warnings
198
+ // §11:AI 选型用的用途说明 / 标签(缺省不落盘,读取时由 describeWorkflow().summary 兜底)
199
+ const description = typeof value.description === 'string' ? value.description.trim().slice(0, 500) : ''
200
+ if (description) workflow.description = description
201
+ const tags = [...new Set(
202
+ stringArray(value.tags)
203
+ .map((tag) => tag.trim().slice(0, 40))
204
+ .filter(Boolean),
205
+ )].slice(0, 12)
206
+ if (tags.length) workflow.tags = tags
207
+ return workflow
208
+ }
209
+
210
+ function normalizeWorkflows(value) {
211
+ if (!Array.isArray(value)) return []
212
+ const workflows = []
213
+ const seen = new Set()
214
+ for (const item of value) {
215
+ const workflow = normalizeWorkflow(item)
216
+ if (!workflow) continue
217
+ if (seen.has(workflow.id)) continue // id 冲突:新的在前,丢旧的
218
+ seen.add(workflow.id)
219
+ workflows.push(workflow)
220
+ if (workflows.length >= MAX_WORKFLOWS) break
221
+ }
222
+ return workflows
223
+ }
224
+
225
+ function normalizeRunImages(value) {
226
+ if (!Array.isArray(value)) return []
227
+ const images = []
228
+ for (const item of value) {
229
+ if (!item || typeof item !== 'object') continue
230
+ if (typeof item.filename !== 'string' || !item.filename) continue
231
+ const image = {
232
+ filename: item.filename,
233
+ subfolder: typeof item.subfolder === 'string' ? item.subfolder : '',
234
+ type: typeof item.type === 'string' && item.type ? item.type : 'output',
235
+ }
236
+ if (typeof item.contentType === 'string' && item.contentType) image.contentType = item.contentType
237
+ images.push(image)
238
+ }
239
+ return images
240
+ }
241
+
242
+ function normalizeLastRuns(value) {
243
+ if (!Array.isArray(value)) return []
244
+ const runs = []
245
+ for (const item of value) {
246
+ if (!item || typeof item !== 'object' || Array.isArray(item)) continue
247
+ let promptId = ''
248
+ if (typeof item.promptId === 'string') promptId = item.promptId
249
+ else if (typeof item.prompt_id === 'string') promptId = item.prompt_id
250
+ if (!promptId) continue
251
+ const run = {
252
+ promptId,
253
+ workflowName: typeof item.workflowName === 'string' ? item.workflowName : '',
254
+ state: VALID_RUN_STATES.has(item.state) ? item.state : 'queued',
255
+ createdAt: normalizeIsoString(item.createdAt),
256
+ }
257
+ if (typeof item.workflowId === 'string' && item.workflowId) run.workflowId = item.workflowId
258
+ if (item.durationMs !== undefined && item.durationMs !== null && item.durationMs !== '') {
259
+ const duration = Number(item.durationMs)
260
+ if (Number.isFinite(duration)) run.durationMs = Math.max(0, Math.round(duration))
261
+ }
262
+ const images = normalizeRunImages(item.images)
263
+ if (images.length) run.images = images
264
+ if (typeof item.error === 'string' && item.error) run.error = item.error
265
+ runs.push(run)
266
+ if (runs.length >= MAX_LAST_RUNS) break
267
+ }
268
+ return runs
269
+ }
270
+
271
+ /** 默认 State(每次调用生成新的 clientId)。 */
272
+ export function defaultState() {
273
+ return {
274
+ baseUrl: DEFAULT_BASE_URL,
275
+ timeoutSec: DEFAULT_TIMEOUT_SEC,
276
+ clientId: newClientId(),
277
+ workflows: [],
278
+ lastRuns: [],
279
+ }
280
+ }
281
+
282
+ /** 把任意输入 normalize 成合法 State(非法字段回默认、去重、截断)。 */
283
+ export function normalizeState(input) {
284
+ const source = input && typeof input === 'object' && !Array.isArray(input) ? input : {}
285
+ return {
286
+ baseUrl: normalizeBaseUrlOr(source.baseUrl),
287
+ timeoutSec: normalizeTimeoutSec(source.timeoutSec),
288
+ clientId: normalizeClientId(source.clientId),
289
+ workflows: normalizeWorkflows(source.workflows),
290
+ lastRuns: normalizeLastRuns(source.lastRuns),
291
+ }
292
+ }
293
+
294
+ function isPlainObject(value) {
295
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
296
+ }
297
+
298
+ /**
299
+ * 创建状态仓库。
300
+ * @param {{ dir?: string }} [options] dir 可选(测试用临时目录);不传则用 dataDir()。
301
+ */
302
+ export function createStateStore({ dir } = {}) {
303
+ const baseDir = typeof dir === 'string' && dir.trim() ? dir.trim() : dataDir()
304
+ fs.mkdirSync(baseDir, { recursive: true })
305
+ const file = path.join(baseDir, STATE_FILE)
306
+
307
+ // 所有 read/write/update 走同一条串行队列:并发 update 不会丢数据。
308
+ let chain = Promise.resolve()
309
+ function enqueue(task) {
310
+ const run = chain.then(task, task)
311
+ chain = run.then(() => undefined, () => undefined)
312
+ return run
313
+ }
314
+
315
+ async function readFromDisk() {
316
+ let text
317
+ try {
318
+ text = await fsp.readFile(file, 'utf8')
319
+ } catch (err) {
320
+ if (err && err.code === 'ENOENT') return defaultState()
321
+ throw err
322
+ }
323
+ if (!text || !text.trim()) return defaultState()
324
+ try {
325
+ return normalizeState(JSON.parse(text))
326
+ } catch {
327
+ // 坏 JSON:备份后回默认
328
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
329
+ const backup = path.join(baseDir, `state.bad-${stamp}-${crypto.randomBytes(2).toString('hex')}.json`)
330
+ try {
331
+ await fsp.rename(file, backup)
332
+ } catch {
333
+ // 备份失败也继续回默认
334
+ }
335
+ return defaultState()
336
+ }
337
+ }
338
+
339
+ async function writeToDisk(state) {
340
+ const normalized = normalizeState(state)
341
+ const tmpFile = path.join(
342
+ baseDir,
343
+ `.state.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`,
344
+ )
345
+ const text = `${JSON.stringify(normalized, null, 2)}\n`
346
+ await fsp.writeFile(tmpFile, text, 'utf8')
347
+ try {
348
+ await fsp.rename(tmpFile, file)
349
+ } catch (err) {
350
+ try {
351
+ await fsp.unlink(tmpFile)
352
+ } catch {
353
+ // ignore
354
+ }
355
+ throw err
356
+ }
357
+ return normalized
358
+ }
359
+
360
+ return {
361
+ dir: baseDir,
362
+ file,
363
+ /** -> Promise<State>;不存在/坏 JSON 回默认(坏 JSON 先备份)。 */
364
+ read() {
365
+ return enqueue(() => readFromDisk())
366
+ },
367
+ /** -> Promise<State>;原子写,返回 normalize 后的实际内容。 */
368
+ write(state) {
369
+ return enqueue(() => writeToDisk(state))
370
+ },
371
+ /**
372
+ * read -> mutator(state)(原地改或返回新对象)-> write,串行化。
373
+ * -> Promise<State>
374
+ */
375
+ update(mutator) {
376
+ return enqueue(async () => {
377
+ const current = await readFromDisk()
378
+ const result = typeof mutator === 'function' ? await mutator(current) : undefined
379
+ const target = isPlainObject(result) ? result : current
380
+ return writeToDisk(target)
381
+ })
382
+ },
383
+ }
384
+ }