dsh-group-mode 0.0.0-stage → 0.3.4

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/channel.js ADDED
@@ -0,0 +1,961 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { constants } from 'node:fs'
3
+ import { link, lstat, mkdir, open, readFile, realpath, rename, rm, unlink } from 'node:fs/promises'
4
+ import { dirname, isAbsolute, join, relative, sep } from 'node:path'
5
+ import { setTimeout as delay } from 'node:timers/promises'
6
+
7
+ const idPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
8
+ const sessionPattern = /^session-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i
9
+ const needsWrite = Symbol('channel-store-needs-write')
10
+ export const continuousRulesVersion = 3
11
+
12
+ export function validChannelId(value) {
13
+ return typeof value === 'string' && idPattern.test(value)
14
+ }
15
+
16
+ export function identity(sessionId) {
17
+ const match = sessionPattern.exec(sessionId)
18
+ return match ? { sessionToken: match[1] } : undefined
19
+ }
20
+
21
+ export function anchorSessionId(id) {
22
+ if (!validChannelId(id)) throw new Error('频道标识无效')
23
+ return `session-${id}`
24
+ }
25
+
26
+ export function newSessionId() {
27
+ return `session-${randomUUID()}`
28
+ }
29
+
30
+ export function text(value, label, max = 100000) {
31
+ if (typeof value !== 'string' || !value.trim() || value.length > max) throw new Error(`${label}为空或超过 ${max} 个字符`)
32
+ return value.trim()
33
+ }
34
+
35
+ export function mode(value) {
36
+ if (value !== 'ask' && value !== 'auto') throw new Error('选择「询问」或「自动」')
37
+ return value
38
+ }
39
+
40
+ export function instructions(value = '') {
41
+ if (typeof value !== 'string' || value.length > 8000) throw new Error('频道说明不能超过 8000 个字符')
42
+ return value.trim()
43
+ }
44
+
45
+ export function activeMembers(channel) {
46
+ return channel.members.filter(member => !member.removedAt)
47
+ }
48
+
49
+ export function rosterName(channel, value, { memberId, forkId, useSuffix = false } = {}) {
50
+ const name = text(value, '成员名', 256)
51
+ const used = new Set([
52
+ ...activeMembers(channel).filter(member => member.id !== memberId).map(member => member.name),
53
+ ...channel.memberForks.filter(fork => fork.id !== forkId).map(fork => fork.cut?.name ?? fork.requestedName).filter(Boolean),
54
+ ].map(name => name.toLocaleLowerCase()))
55
+ if (!used.has(name.toLocaleLowerCase())) return name
56
+ if (!useSuffix) throw new Error(`本频道已有「${name}」`)
57
+ let suffix = 2
58
+ while (used.has(`${name} (${suffix})`.toLocaleLowerCase())) suffix++
59
+ return `${name} (${suffix})`
60
+ }
61
+
62
+ function draftMembers(members) {
63
+ return members.filter(member => !member.fork).map(({ id, name, preset, provider, model, reasoningEffort, permissionPreset }) => ({
64
+ id, name, preset, provider, model, reasoningEffort, permissionPreset,
65
+ }))
66
+ }
67
+
68
+ export function makeChannel(id, draft) {
69
+ if (!validChannelId(id)) throw new Error('频道标识无效')
70
+ if (draft.sessionId !== anchorSessionId(id)) throw new Error('频道会话标识必须使用频道标识')
71
+ if (typeof draft.cwd !== 'string' || !draft.cwd) throw new Error('频道工作区无效')
72
+ const name = text(draft.name, '频道名', 80)
73
+ if (!Array.isArray(draft.members) || !draft.members.length) throw new Error('至少选择一位成员')
74
+ const names = new Set()
75
+ const members = draft.members.map(item => {
76
+ const name = text(item.name, '成员名', 64)
77
+ const key = name.toLocaleLowerCase()
78
+ if (names.has(key)) throw new Error(`本频道已有「${name}」`)
79
+ names.add(key)
80
+ const memberId = randomUUID()
81
+ const member = { id: memberId, sessionId: newSessionId(), name, ready: false, executionOptionsState: { status: 'saved' } }
82
+ if (item.preset) member.preset = text(item.preset, '角色', 256)
83
+ if (member.preset === 'group-channel') throw new Error('请选择成员角色')
84
+ if (item.model || item.provider) {
85
+ member.provider = text(item.provider, '模型提供方', 256)
86
+ member.model = text(item.model, '模型', 512)
87
+ }
88
+ if (item.reasoningEffort != null) member.reasoningEffort = text(item.reasoningEffort, '推理等级', 128)
89
+ if (item.permissionPreset != null) member.permissionPreset = text(item.permissionPreset, '权限等级', 128)
90
+ if (!member.preset && !member.model) throw new Error(`请选择「${name}」的角色或模型`)
91
+ return member
92
+ })
93
+ const leaderIndex = draft.leaderIndex ?? 0
94
+ if (!Number.isSafeInteger(leaderIndex)) throw new Error('组长必须是频道成员')
95
+ const leader = members[leaderIndex]
96
+ if (!leader) throw new Error('组长必须是频道成员')
97
+ const initialMode = mode(draft.mode ?? 'ask')
98
+ const initialInstructions = instructions(draft.instructions)
99
+ return {
100
+ version: 2, rulesVersion: continuousRulesVersion, id, sessionId: draft.sessionId, anchorReady: false, cwd: draft.cwd, name,
101
+ initialSettings: {
102
+ leaderId: leader.id, mode: initialMode, instructions: initialInstructions,
103
+ members: draftMembers(members),
104
+ },
105
+ leaderId: leader.id, mode: initialMode, instructions: initialInstructions, members, memberForks: [],
106
+ messages: [], tasks: [], receipts: [], discussions: [], pendingDiscussionContexts: [], leaderNotices: [], rulesRevision: 1, rulesContextIds: {},
107
+ }
108
+ }
109
+
110
+ export function matchesChannelDraft(channel, draft) {
111
+ const requestedMode = mode(draft.mode ?? 'ask')
112
+ const requestedName = text(draft.name, '频道名', 80)
113
+ const initial = channel.initialSettings ?? channel
114
+ if (channel.name !== requestedName || initial.mode !== requestedMode || (initial.instructions ?? '') !== instructions(draft.instructions)) return false
115
+ const initialMembers = initial.members ?? channel.members.filter(member => !member.fork)
116
+ if (!Array.isArray(draft.members) || initialMembers.length !== draft.members.length) return false
117
+ const leaderIndex = draft.leaderIndex ?? 0
118
+ if (!Number.isSafeInteger(leaderIndex) || initialMembers[leaderIndex]?.id !== initial.leaderId) return false
119
+ return initialMembers.every((member, index) => {
120
+ const requested = draft.members[index]
121
+ return requested
122
+ && member.name === text(requested.name, '成员名', 64)
123
+ && (member.preset ?? null) === (requested.preset ? text(requested.preset, '角色', 256) : null)
124
+ && (member.provider ?? null) === (requested.provider ? text(requested.provider, '模型提供方', 256) : null)
125
+ && (member.model ?? null) === (requested.model ? text(requested.model, '模型', 512) : null)
126
+ && (member.reasoningEffort ?? null) === (requested.reasoningEffort ? text(requested.reasoningEffort, '推理等级', 128) : null)
127
+ && (member.permissionPreset ?? null) === (requested.permissionPreset ? text(requested.permissionPreset, '权限等级', 128) : null)
128
+ })
129
+ }
130
+
131
+ export const human = Object.freeze({ kind: 'user', name: '你' })
132
+ export const authorOf = member => ({ kind: 'member', id: member.id, name: member.name })
133
+
134
+ export function originalRequest(channel, row) {
135
+ return channel.messages.find(entry => entry.id === row.requestId && entry.kind === 'message' && entry.author.kind === 'user')
136
+ }
137
+
138
+ export function fileReferences(value) {
139
+ if (value === undefined) return []
140
+ if (!Array.isArray(value) || value.length > 24) throw new Error('最多引用 24 个工作区文件')
141
+ return [...new Set(value.map(path => {
142
+ if (typeof path !== 'string' || !path || path.length > 512 || /[\p{Cc}\p{Cf}:]/u.test(path)) throw new Error('文件引用路径无效')
143
+ const normalized = path.replaceAll('\\', '/')
144
+ const parts = normalized.split('/').filter(part => part && part !== '.')
145
+ if (normalized.startsWith('/') || !parts.length || parts.some(part => /[. ]$/.test(part))) {
146
+ throw new Error('文件引用必须使用工作区相对路径,且不能包含父路径')
147
+ }
148
+ return parts.join('/')
149
+ }))]
150
+ }
151
+
152
+ export function resultFileReferences(value) {
153
+ if (Array.isArray(value) && value.some(path => typeof path === 'string'
154
+ && /^(?:sha256:|(?:dsh-|openbot-)?attachments?:|blob:)/iu.test(path.trimStart()))) {
155
+ throw new Error('频道交付不接受会话附件 ID 作为文件路径。请将本轮生成的附件 ID 填到 attachment_ids。已保存的成果用 files 填写工作区相对路径,例如 成果/报告.pdf。')
156
+ }
157
+ return fileReferences(value)
158
+ }
159
+
160
+ function assertResultAttachmentScope(channelId, path) {
161
+ const [root, directory, owner] = path.toLowerCase().split('/')
162
+ if (root === '.dsh-group' && directory === 'attachments' && owner !== channelId.toLowerCase()) {
163
+ throw new Error('此附件属于其他频道。请在当前频道重新添加文件,或引用本工作区内已保存的成果文件。')
164
+ }
165
+ }
166
+
167
+ export async function validateResultFiles(channel, files) {
168
+ if (!files?.length) return
169
+ const root = await realpath(channel.cwd)
170
+ for (const path of files) {
171
+ assertResultAttachmentScope(channel.id, path)
172
+ const resolved = await realpath(join(root, path)).catch(error => {
173
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error
174
+ throw new Error('本频道工作区没有找到成果文件「' + path + '」。请核对文件是否已保存,并提交相对路径。')
175
+ })
176
+ const destination = relative(root, resolved)
177
+ if (!destination || isAbsolute(destination) || destination === '..' || destination.startsWith('..' + sep)) {
178
+ throw new Error('成果文件必须在本频道工作区内。')
179
+ }
180
+ assertResultAttachmentScope(channel.id, destination.split(sep).join('/'))
181
+ if (!(await lstat(resolved)).isFile()) throw new Error('成果路径「' + path + '」必须指向文件。')
182
+ }
183
+ }
184
+
185
+ export async function inferResultFile(channel, body) {
186
+ if (typeof body !== 'string') return
187
+ const line = body.trim()
188
+ if (!line || line.length > 1024 || /[\r\n]/u.test(line)) return
189
+ const pathText = line.replace(/^(?:成果文件|文件路径)[::]\s*/u, '').trim()
190
+ const quoted = /^([\x60"'])(.+)\1$/u.exec(pathText)
191
+ const candidate = quoted?.[2] ?? pathText
192
+ try {
193
+ const relativePath = isAbsolute(candidate) ? relative(channel.cwd, candidate) : candidate
194
+ const paths = resultFileReferences([relativePath])
195
+ await validateResultFiles(channel, paths)
196
+ return paths[0]
197
+ } catch {
198
+ // A prose result or an inaccessible path is still valid as plain text.
199
+ return undefined
200
+ }
201
+ }
202
+
203
+ export function channelUploads(channelId, attachments) {
204
+ if (!attachments.length) return []
205
+ if (!validChannelId(channelId)) throw new Error('频道标识无效')
206
+ if (attachments.length > 12) throw new Error('每条频道消息最多上传 12 个附件')
207
+ const uploads = new Map()
208
+ let totalBytes = 0
209
+ for (const block of attachments) {
210
+ if (block.type !== 'file') throw new Error('频道仅接收文件回执,请将图片作为文件上传')
211
+ const ref = block.attachment
212
+ const digest = /^sha256:([a-f0-9]{64})$/u.exec(ref?.attachmentId)?.[1]
213
+ const name = ref?.name
214
+ if (!digest || typeof name !== 'string' || !name || Buffer.byteLength(name) > 255
215
+ || /[\\/:<>|?*"\p{Cc}\p{Cf}]|[. ]$/u.test(name) || name !== name.trimStart()
216
+ || /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]|conin\$|conout\$) *(?:\.|$)/iu.test(name)) {
217
+ throw new Error('频道附件的文件名或标识无效')
218
+ }
219
+ if (!Number.isSafeInteger(ref.bytes) || ref.bytes < 0 || ref.bytes > 20 * 1024 * 1024) {
220
+ throw new Error('单个频道附件不能超过 20 MiB')
221
+ }
222
+ const key = createHash('sha256').update(digest).update('\0').update(name).digest('hex')
223
+ const dirs = ['.dsh-group', 'attachments', channelId, key]
224
+ const path = [...dirs, name].join('/')
225
+ const previous = uploads.get(path)
226
+ if (previous) {
227
+ if (previous.ref.bytes !== ref.bytes) throw new Error('频道附件的文件大小不一致')
228
+ continue
229
+ }
230
+ totalBytes += ref.bytes
231
+ if (totalBytes > 50 * 1024 * 1024) throw new Error('每条频道消息的上传附件合计不能超过 50 MiB')
232
+ uploads.set(path, { path, dirs, ref, digest })
233
+ }
234
+ return [...uploads.values()]
235
+ }
236
+
237
+ function uploadEntry(path) {
238
+ return lstat(path).catch(error => { if (error.code !== 'ENOENT') throw error })
239
+ }
240
+
241
+ async function uploadDirectory(cwd, parts, create = false) {
242
+ let directory = cwd
243
+ let entry = await lstat(cwd)
244
+ if (!entry.isDirectory() || relative(cwd, await realpath(cwd)) !== '') throw new Error('频道附件工作区必须是真实目录')
245
+ for (const part of parts) {
246
+ directory = join(directory, part)
247
+ entry = await uploadEntry(directory)
248
+ if (!entry && create) {
249
+ await mkdir(directory).catch(error => { if (error.code !== 'EEXIST') throw error })
250
+ entry = await lstat(directory)
251
+ }
252
+ if (!entry?.isDirectory() || relative(directory, await realpath(directory)) !== '') {
253
+ throw new Error('频道附件目录无效或包含链接')
254
+ }
255
+ }
256
+ return entry
257
+ }
258
+
259
+ const sameEntry = (a, b) => a?.dev === b?.dev && a?.ino === b?.ino
260
+
261
+ async function uploadFileInfo(path) {
262
+ const entry = await uploadEntry(path)
263
+ if (entry && !entry.isFile()) throw new Error('频道附件路径不是普通文件或包含链接')
264
+ return entry
265
+ }
266
+
267
+ async function verifyUpload(path, entry, { ref, digest }, signal) {
268
+ if (entry.nlink !== 1 || entry.size !== ref.bytes) throw new Error('频道附件目标存在链接或内容冲突')
269
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
270
+ try {
271
+ const opened = await handle.stat()
272
+ if (!opened.isFile() || opened.nlink !== 1 || !sameEntry(entry, opened)) throw new Error('频道附件目标已改变')
273
+ const hash = createHash('sha256')
274
+ let bytes = 0
275
+ for await (const chunk of handle.createReadStream({ autoClose: false, signal })) {
276
+ bytes += chunk.byteLength
277
+ if (bytes > ref.bytes) throw new Error('频道附件目标内容冲突')
278
+ hash.update(chunk)
279
+ }
280
+ if (bytes !== ref.bytes || hash.digest('hex') !== digest) throw new Error('频道附件目标内容冲突')
281
+ } finally { await handle.close() }
282
+ }
283
+
284
+ async function writeUpload(handle, { ref, digest }, read, signal) {
285
+ const hash = createHash('sha256')
286
+ let bytes = 0
287
+ for await (const chunk of read(ref, signal)) {
288
+ signal?.throwIfAborted()
289
+ bytes += chunk.byteLength
290
+ if (bytes > ref.bytes) throw new Error('频道附件超出回执声明的大小')
291
+ hash.update(chunk)
292
+ let offset = 0
293
+ while (offset < chunk.byteLength) {
294
+ const { bytesWritten } = await handle.write(chunk, offset, chunk.byteLength - offset)
295
+ if (!bytesWritten) throw new Error('频道附件写入未完成')
296
+ offset += bytesWritten
297
+ }
298
+ }
299
+ signal?.throwIfAborted()
300
+ if (bytes !== ref.bytes || hash.digest('hex') !== digest) throw new Error('频道附件校验失败')
301
+ await handle.sync()
302
+ }
303
+
304
+ export function sameFiles(entry, files) {
305
+ const existing = entry.files ?? []
306
+ return existing.length === files.length && files.every(path => existing.includes(path))
307
+ }
308
+
309
+ function explicitDiscussionReply(channel, body) {
310
+ const discussionAt = body.indexOf('讨论')
311
+ if (discussionAt < 0) return null
312
+ const directives = [...body.matchAll(/(?:然后|之后|最后|讨论后|讨论完(?:后)?|完成后|结束后|并|再|[,,;;。]\s*(?=请|由|让|叫))[,、,\s]*(?:请|只|由|让|叫|安排|\s)*/gu)]
313
+ const candidates = activeMembers(channel).filter(member => member.ready !== false)
314
+ .sort((a, b) => b.name.length - a.name.length)
315
+ const matches = new Set()
316
+ for (const directive of directives) {
317
+ if (directive.index < discussionAt) continue
318
+ const tail = body.slice(directive.index + directive[0].length).replace(/^@\s*/u, '')
319
+ const member = candidates.find(item => tail.startsWith(item.name)
320
+ && /^\s*(?:成员)?\s*(?:单独|直接|最终)?\s*(?:来\s*)?(?:回复|答复|回答|汇报|给我(?:回复|答复|回答))/u.test(tail.slice(item.name.length)))
321
+ if (member) matches.add(member.id)
322
+ }
323
+ return matches.size === 1 ? matches.values().next().value : null
324
+ }
325
+
326
+ export function message(channel, author, body, kind, replyTo, id = randomUUID(), files = []) {
327
+ const row = { id, author, text: files.length && body === '' ? '' : text(body, '消息'), kind, at: Date.now(), replyTo: replyTo ?? null }
328
+ if (files.length) row.files = files
329
+ channel.messages.push(row)
330
+ return row
331
+ }
332
+
333
+ export function task(channel, owner, source, requestId = source.id, parentId = null) {
334
+ const row = {
335
+ id: randomUUID(), memberId: owner.id, assignedBy: source.author,
336
+ instruction: source.text || '请查看随需求提供的工作区文件。',
337
+ sourceId: source.id, requestId, parentId, status: 'queued', answers: [], receipts: [], noticeId: null,
338
+ }
339
+ if (channel.rulesVersion === continuousRulesVersion) {
340
+ row.at = Date.now()
341
+ row.goal = row.instruction
342
+ row.attempts = []
343
+ row.contextId = randomUUID()
344
+ row.contextDeliveredTo = {}
345
+ }
346
+ channel.tasks.push(row)
347
+ return row
348
+ }
349
+
350
+ export function structuralTask(row) {
351
+ return row.treeRootId && (row.kind === 'request' || row.kind === 'submission' || row.kind === 'discussion' && !row.planningStage)
352
+ }
353
+
354
+ export function treeTask(channel, root, owner, parentId, kind, goal, fields = {}) {
355
+ const row = task(channel, owner, { id: root.sourceId, text: goal, author: authorOf(owner) }, root.requestId, parentId)
356
+ Object.assign(row, { kind, treeRootId: root.id, dependsOn: [], ...fields })
357
+ if (structuralTask(row)) delete row.contextId
358
+ return row
359
+ }
360
+
361
+ function leadingMembers(body, roster, allowUnknown = false) {
362
+ const members = []
363
+ const sorted = [...roster].sort((a, b) => b.name.length - a.name.length)
364
+ const boundary = /^(?:$|[\s@,.:;!?,。;:!?、))])/u
365
+ let tail = body
366
+ while (tail.startsWith('@')) {
367
+ const address = tail.slice(1)
368
+ const everyone = ['全体成员', '全员', '所有人'].find(name => address.startsWith(name) && boundary.test(address.slice(name.length)))
369
+ const member = everyone ? null : sorted.find(item => address.slice(0, item.name.length).toLocaleLowerCase() === item.name.toLocaleLowerCase()
370
+ && boundary.test(address.slice(item.name.length)))
371
+ if (!everyone && !member) {
372
+ if (allowUnknown) break
373
+ throw new Error('未找到开头点名的成员,请从频道成员列表选择')
374
+ }
375
+ for (const item of everyone ? roster : [member]) {
376
+ if (!members.some(existing => existing.id === item.id)) members.push(item)
377
+ }
378
+ tail = address.slice((everyone ?? member.name).length).replace(/^[\s,,、::]+/u, '')
379
+ }
380
+ return { members, goal: tail }
381
+ }
382
+
383
+ function treeIntent(goal, roster) {
384
+ const recipients = [], reporters = []
385
+ const names = [...roster].sort((a, b) => b.name.length - a.name.length)
386
+ const find = (tail, suffix) => names.find(member => tail.startsWith(member.name) && suffix.test(tail.slice(member.name.length)))
387
+ for (const match of goal.matchAll(/(?:请|让|由|交给|提交给|转交给|发给|给)\s*@?\s*/gu)) {
388
+ const tail = goal.slice(match.index + match[0].length)
389
+ const reporter = find(tail, /^\s*(?:成员)?\s*(?:来\s*)?(?:汇报|回复|答复|报告)(?:给我|给用户|到频道|我)/u)
390
+ const recipient = /给/u.test(match[0]) && find(tail, /^(?:$|[\s,,。;;、]|成员|汇总|总结|核对|复核|审阅|处理)/u)
391
+ if (reporter && !reporters.includes(reporter.id)) reporters.push(reporter.id)
392
+ if (recipient && !recipients.includes(recipient.id)) recipients.push(recipient.id)
393
+ }
394
+ const multipleDeliverables = reporters.length > 1
395
+ || /(?:各自|分别)(?:独立(?:提交|交付|汇报)|(?:汇报|回复)给我)|[2-82-8两二三四五六七八多]\s*(?:份|个|项)\s*(?:独立|单独)(?:的)?(?:交付|结论|结果|汇报)/u.test(goal)
396
+ return { recipientIds: recipients, reporterIds: reporters, multipleDeliverables }
397
+ }
398
+
399
+ function startTaskTree(channel, source, participants, goal) {
400
+ const [coordinator] = participants
401
+ const root = task(channel, coordinator, source)
402
+ Object.assign(root, { kind: 'request', treeRootId: root.id, dependsOn: [], goal, instruction: goal, status: 'paused',
403
+ intent: treeIntent(goal, activeMembers(channel)) })
404
+ delete root.contextId
405
+ const discussion = treeTask(channel, root, coordinator, root.id, 'discussion', '规划分工与交付', {
406
+ status: 'paused', participantIds: participants.map(member => member.id), turns: [],
407
+ })
408
+ for (const [position, member] of participants.entries()) {
409
+ const previous = discussion.turns.at(-1)
410
+ const turn = treeTask(channel, root, member, discussion.id, 'discussion', '提出分工与依赖建议', {
411
+ planningStage: 'speech', planningTurn: position + 1, status: previous ? 'paused' : 'queued',
412
+ dependsOn: previous ? [previous.taskId] : [],
413
+ })
414
+ discussion.turns.push({ number: position + 1, taskId: turn.id, memberId: member.id })
415
+ }
416
+ const confirmation = treeTask(channel, root, coordinator, discussion.id, 'discussion', '书面确认分工与交付', {
417
+ planningStage: 'confirm', dependsOn: [discussion.turns.at(-1).taskId], status: 'paused',
418
+ })
419
+ discussion.planTaskId = confirmation.id
420
+ return root
421
+ }
422
+
423
+ function sameIds(left, right) {
424
+ return left.length === right.length && left.every((id, index) => id === right[index])
425
+ }
426
+
427
+ function planMember(channel, id) {
428
+ const member = channel.members.find(item => item.id === id && !item.removedAt && item.ready !== false)
429
+ if (!member) throw new Error('计划引用了未就绪或不在频道的成员')
430
+ return member
431
+ }
432
+
433
+ function rolesFor(channel, root, drafts) {
434
+ const { recipientIds, reporterIds } = root.intent
435
+ const matchedRecipients = new Set(), matchedReporters = new Set()
436
+ const roles = drafts.map(draft => {
437
+ const reporterId = draft.reporter_id ?? (reporterIds.length === 1 ? reporterIds[0] : undefined)
438
+ const recipientId = draft.recipient_id ?? (recipientIds.length === 1 ? recipientIds[0] : reporterId ?? root.memberId)
439
+ if (recipientIds.length && !recipientIds.includes(recipientId)) throw new Error('接收人必须符合用户的原始需求')
440
+ if (reporterIds.length && !reporterIds.includes(reporterId)) throw new Error('公开汇报人必须符合用户的原始需求')
441
+ if (recipientIds.length && !reporterIds.length && reporterId) throw new Error('用户只指定内部接收人,不能安排公开汇报')
442
+ const recipient = planMember(channel, recipientId)
443
+ const reporter = reporterId || !recipientIds.length && !draft.recipient_id
444
+ ? planMember(channel, reporterId ?? root.memberId) : null
445
+ matchedRecipients.add(recipient.id)
446
+ if (reporter) matchedReporters.add(reporter.id)
447
+ return { recipient, reporter }
448
+ })
449
+ if (recipientIds.some(id => !matchedRecipients.has(id)) || reporterIds.some(id => !matchedReporters.has(id))) {
450
+ throw new Error('计划须覆盖用户指定的各个接收人和汇报人')
451
+ }
452
+ return roles
453
+ }
454
+
455
+ export function registerTreePlan(channel, row, drafts) {
456
+ const root = channel.tasks.find(task => task.id === row.treeRootId)
457
+ const discussion = channel.tasks.find(task => task.id === row.parentId)
458
+ if (row.planningStage !== 'confirm' || discussion.planTaskId !== row.id || discussion.plan) throw new Error('只有协调人的书面确认任务可以登记计划')
459
+ if (drafts.length > 1 && !root.intent.multipleDeliverables) throw new Error('原需求未明确要求多份独立交付,请登记一份或向用户澄清')
460
+ const coordinator = planMember(channel, root.memberId)
461
+ const roles = rolesFor(channel, root, drafts)
462
+ const usedMembers = new Set()
463
+ const groups = drafts.map((draft, index) => {
464
+ const { recipient, reporter } = roles[index]
465
+ const keys = new Map(draft.executions.map(item => [item.key, item]))
466
+ if (keys.size !== draft.executions.length || new Set(draft.executions.map(item => item.member_id)).size !== keys.size) {
467
+ throw new Error('同一交付中的执行人和执行键必须唯一,更多工作可由执行人继续拆分')
468
+ }
469
+ const ordered = []
470
+ const remaining = new Map(keys)
471
+ while (remaining.size) {
472
+ const ready = [...remaining.values()].filter(item => item.depends_on.every(key => keys.has(key) && !remaining.has(key)))
473
+ if (!ready.length) throw new Error('执行依赖不存在或形成循环')
474
+ for (const item of ready) {
475
+ ordered.push(item)
476
+ remaining.delete(item.key)
477
+ }
478
+ }
479
+ const submission = treeTask(channel, root, coordinator, root.id, 'submission', draft.goal, {
480
+ status: 'paused', recipientId: recipient.id, reporterId: reporter?.id ?? null, collected: [],
481
+ })
482
+ const executions = new Map()
483
+ for (const item of ordered) {
484
+ if (!discussion.participantIds.includes(item.member_id)) throw new Error('计划的直接执行人须为开头点名的成员')
485
+ const owner = planMember(channel, item.member_id)
486
+ usedMembers.add(owner.id)
487
+ executions.set(item.key, treeTask(channel, root, owner, submission.id, 'execution', item.goal, {
488
+ assignedBy: authorOf(coordinator), status: item.depends_on.length ? 'paused' : 'queued',
489
+ dependsOn: item.depends_on.map(key => executions.get(key).id),
490
+ }))
491
+ }
492
+ if (reporter) {
493
+ const report = treeTask(channel, root, reporter, root.id, 'report', draft.goal, {
494
+ assignedBy: authorOf(coordinator), status: 'paused', dependsOn: [submission.id], submissionId: submission.id,
495
+ })
496
+ submission.reportTaskId = report.id
497
+ }
498
+ return { submissionId: submission.id, reportTaskId: submission.reportTaskId ?? null, executionIds: [...executions.values()].map(item => item.id) }
499
+ })
500
+ if (discussion.participantIds.some(id => !usedMembers.has(id))) throw new Error('计划须分配全部被点名成员的工作')
501
+ discussion.plan = groups
502
+ discussion.blockedBy = []
503
+ row.status = discussion.status = 'done'
504
+ return groups
505
+ }
506
+
507
+ function taskBlocker(row) {
508
+ return { taskId: row.id, memberId: row.memberId, status: row.status, reason: row.error ?? null }
509
+ }
510
+
511
+ export function advanceTaskTrees(channel) {
512
+ const trees = channel.tasks.filter(row => row.treeRootId)
513
+ if (!trees.length) return false
514
+ const previous = new Map(trees.map(task => [task.id, JSON.stringify([
515
+ task.status, task.blockedBy, task.collected, task.handoff, task.waitingForChildren, task.error,
516
+ ])]))
517
+ const byId = new Map(trees.map(row => [row.id, row]))
518
+ const active = new Set(activeMembers(channel).map(member => member.id))
519
+ const children = new Map()
520
+ for (const row of trees) {
521
+ if (row.parentId) {
522
+ const list = children.get(row.parentId) ?? []
523
+ list.push(row)
524
+ children.set(row.parentId, list)
525
+ }
526
+ }
527
+ // 按反向创建顺序先折算较深的执行节点,再汇集直接子任务。
528
+ for (const row of [...trees].reverse()) {
529
+ if (row.status === 'cancelled' || row.kind === 'request') continue
530
+ const direct = children.get(row.id) ?? []
531
+ if (row.kind === 'submission' && row.status !== 'done') {
532
+ row.collected = direct.filter(child => child.status === 'done' && child.internalResult)
533
+ .map(child => ({ taskId: child.id, resultId: child.internalResult.id }))
534
+ row.blockedBy = direct.filter(child => child.status !== 'done' || !child.internalResult).map(taskBlocker)
535
+ if (direct.length && !row.blockedBy.length && !row.handoff) {
536
+ row.handoff = { id: `group-handoff-${row.id}`, recipientId: row.recipientId, status: 'pending', inputs: row.collected }
537
+ }
538
+ if (row.handoff?.status === 'pending' && !active.has(row.recipientId)) {
539
+ row.handoff.status = 'failed'
540
+ row.error = '接收人已移除,无法交接'
541
+ }
542
+ } else if (row.kind === 'discussion' && !row.planningStage && row.status !== 'done') {
543
+ row.blockedBy = direct.filter(child => child.status !== 'done').map(taskBlocker)
544
+ } else if (row.status === 'paused' && row.waitingForChildren) {
545
+ row.blockedBy = direct.filter(child => child.status !== 'done' || !child.internalResult).map(taskBlocker)
546
+ if (!row.blockedBy.length && !row.pendingQuestionId) {
547
+ delete row.waitingForChildren
548
+ if (!row.manualPause) {
549
+ row.status = 'queued'
550
+ delete row.error
551
+ }
552
+ }
553
+ }
554
+ }
555
+ for (const row of trees) {
556
+ if (row.status !== 'paused' || row.error || structuralTask(row) || !row.dependsOn.length) continue
557
+ const pending = row.dependsOn.map(id => byId.get(id)).filter(dependency => dependency.status !== 'done')
558
+ row.blockedBy = pending.map(taskBlocker)
559
+ if (!pending.length && !row.manualPause) row.status = 'queued'
560
+ }
561
+ for (const root of trees.filter(row => row.kind === 'request' && row.status !== 'cancelled')) {
562
+ const direct = children.get(root.id) ?? []
563
+ root.blockedBy = direct.filter(child => child.status !== 'done').map(taskBlocker)
564
+ if (direct.length && !root.blockedBy.length) root.status = 'done'
565
+ }
566
+ return trees.some(row => previous.get(row.id) !== JSON.stringify([
567
+ row.status, row.blockedBy, row.collected, row.handoff, row.waitingForChildren, row.error,
568
+ ]))
569
+ }
570
+
571
+ function hasLiveChildren(channel, row) {
572
+ const pending = channel.tasks.filter(child => child.parentId === row.id)
573
+ const visited = new Set()
574
+ while (pending.length) {
575
+ const child = pending.pop()
576
+ if (visited.has(child.id)) continue
577
+ visited.add(child.id)
578
+ if (child.status === 'done' || child.status === 'cancelled') continue
579
+ if (child.status !== 'delegated') return true
580
+ pending.push(...channel.tasks.filter(candidate => candidate.parentId === child.id))
581
+ }
582
+ return false
583
+ }
584
+
585
+ export function post(channel, args) {
586
+ if (!validChannelId(args.id)) throw new Error('消息标识无效')
587
+ const existing = channel.messages.find(m => m.id === args.id)
588
+ const files = fileReferences(args.files)
589
+ const body = files.length && (args.text === undefined || typeof args.text === 'string' && !args.text.trim())
590
+ ? '' : text(args.text, '消息')
591
+ if (args.allMembers !== undefined && typeof args.allMembers !== 'boolean') throw new Error('全员投递选项无效')
592
+ const continuous = channel.rulesVersion === continuousRulesVersion
593
+ const mentionPattern = /(?:^|[\s,。;、((])@/gu
594
+ const mentionEnd = /^(?:$|[\s,.:;!?,。;:!?、))])/u
595
+ const mentions = [...body.matchAll(mentionPattern)].map(match => body.slice(match.index + match[0].length))
596
+ const everyone = tail => ['全员', '所有人'].some(name => tail.startsWith(name) && mentionEnd.test(tail.slice(name.length)))
597
+ const broadcastMentions = /@全体成员(?=$|[\s@,.:;!?,。;:!?、))])/gu
598
+ const broadcastBoundary = /[\s@,.:;!?,。;:!?、(())\p{Script=Han}]/u
599
+ const allMembers = args.allMembers === true || (continuous && !args.answerTo
600
+ && [...body.matchAll(broadcastMentions)].some(({ index }) => {
601
+ if (!index || broadcastBoundary.test(body[index - 1])) return true
602
+ const prefix = body.slice(0, index).toLocaleLowerCase()
603
+ return activeMembers(channel).some(member => prefix.endsWith('@' + member.name.toLocaleLowerCase()))
604
+ }))
605
+ if (allMembers && channel.rulesVersion !== continuousRulesVersion) throw new Error('当前频道规则不支持全员投递')
606
+ if (args.answerTo) {
607
+ if (allMembers) throw new Error('答复任务时不能同时选择全员投递')
608
+ if (existing) {
609
+ const answered = channel.tasks.find(t => t.id === args.answerTo)
610
+ if (existing.kind !== 'answer' || existing.taskId !== args.answerTo || !answered?.answers.includes(existing.id)
611
+ || existing.text !== body || existing.author.kind !== 'user' || !sameFiles(existing, files)
612
+ || (args.questionId !== undefined && existing.replyTo !== args.questionId)) {
613
+ throw new Error('消息标识已用于其他内容')
614
+ }
615
+ return { duplicate: true, message: existing }
616
+ }
617
+ if (args.questionId && channel.messages.some(item => item.id === args.questionId && item.closedByTransfer)) {
618
+ throw new Error('这个问题已因任务移交关闭')
619
+ }
620
+ const waiting = channel.tasks.find(t => t.id === args.answerTo && t.status === 'waiting')
621
+ if (!waiting) throw new Error('这个问题已答复或已取消')
622
+ const questionId = waiting.pendingQuestionId ?? waiting.questionId
623
+ if (args.questionId !== undefined && args.questionId !== questionId) throw new Error('这个问题已更新,请刷新后再答复')
624
+ const row = message(channel, human, body, 'answer', questionId, args.id, files)
625
+ row.taskId = waiting.id
626
+ waiting.answers.push(row.id)
627
+ waiting.pendingQuestionId = null
628
+ waiting.answeredQuestionId = questionId
629
+ if (waiting.planningStage === 'confirm') {
630
+ const root = channel.tasks.find(task => task.id === waiting.treeRootId)
631
+ const clarified = treeIntent(body, activeMembers(channel))
632
+ if (clarified.recipientIds.length || clarified.reporterIds.length) {
633
+ root.intent.recipientIds = clarified.recipientIds
634
+ root.intent.reporterIds = clarified.reporterIds
635
+ }
636
+ root.intent.multipleDeliverables ||= clarified.multipleDeliverables
637
+ }
638
+ if (channel.rulesVersion === continuousRulesVersion && hasLiveChildren(channel, waiting)) {
639
+ waiting.status = 'paused'
640
+ waiting.waitingForChildren = true
641
+ waiting.error = '已收到答复,等待子任务完成'
642
+ } else {
643
+ waiting.status = 'queued'
644
+ waiting.noticeId = null
645
+ delete waiting.waitingForChildren
646
+ delete waiting.error
647
+ }
648
+ return { duplicate: false, message: row }
649
+ }
650
+ if (args.targets != null && !Array.isArray(args.targets)) throw new Error('点名列表无效')
651
+ if (args.targets?.some(id => typeof id !== 'string' || !id)) throw new Error('成员标识无效')
652
+ const explicitTargets = [...new Set(args.targets ?? [])].sort()
653
+ if (existing?.explicitTargets) {
654
+ if (existing.kind !== 'message' || existing.text !== body || existing.author.kind !== 'user' || !sameFiles(existing, files)
655
+ || (existing.mentionIds !== undefined ? Boolean(existing.allMembers) !== allMembers : Boolean(existing.allMembers) !== (allMembers || mentions.some(everyone)))
656
+ || !sameIds(existing.explicitTargets, explicitTargets)) {
657
+ throw new Error('消息标识已用于其他内容')
658
+ }
659
+ return { duplicate: true, message: existing }
660
+ }
661
+ const members = activeMembers(channel)
662
+ const leading = continuous ? leadingMembers(body, members, allMembers) : { members: [], goal: body }
663
+ const replyMemberId = continuous && !allMembers && !leading.members.length ? explicitDiscussionReply(channel, body) : null
664
+ const chosen = new Set([...leading.members.map(member => member.id), ...explicitTargets])
665
+ // A typed mention is useful without a picker. Match complete roster names,
666
+ // including spaces and punctuation, and keep names out of regular expressions.
667
+ for (const tail of continuous ? [] : mentions) {
668
+ const matched = members.filter(m => {
669
+ const suffix = tail.slice(m.name.length)
670
+ return tail.toLocaleLowerCase().startsWith(m.name.toLocaleLowerCase()) && mentionEnd.test(suffix)
671
+ }).sort((a, b) => b.name.length - a.name.length)[0]
672
+ if (!matched) throw new Error('未找到被点名的成员,请从频道成员列表选择')
673
+ chosen.add(matched.id)
674
+ }
675
+ if (allMembers) for (const member of members) chosen.add(member.id)
676
+ // Keep the addressed members as submitted, before applying the leader default.
677
+ // A retry can arrive after the leader or the task status has changed.
678
+ const targets = [...chosen].sort()
679
+ if (existing) {
680
+ const original = existing.targets ?? channel.tasks.filter(t => t.sourceId === args.id && !t.parentId).map(t => t.memberId).sort()
681
+ const legacyDefault = existing.targets === undefined && !targets.length && original.length === 1 && !allMembers
682
+ if (existing.kind !== 'message' || existing.text !== body || existing.author.kind !== 'user' || !sameFiles(existing, files)
683
+ || Boolean(existing.allMembers) !== allMembers
684
+ || (!legacyDefault && (original.length !== targets.length || original.some((id, index) => id !== targets[index])))) {
685
+ throw new Error('消息标识已用于其他内容')
686
+ }
687
+ return { duplicate: true, message: existing }
688
+ }
689
+ if (!chosen.size) chosen.add(channel.leaderId)
690
+ const owners = [...chosen].map(id => {
691
+ const found = members.find(m => m.id === id)
692
+ if (!found) throw new Error('被点名的成员不在此频道')
693
+ return found
694
+ })
695
+ const row = message(channel, human, body, 'message', null, args.id, files)
696
+ row.targets = targets
697
+ if (continuous) {
698
+ row.explicitTargets = explicitTargets
699
+ row.mentionIds = leading.members.map(member => member.id)
700
+ }
701
+ if (allMembers) row.allMembers = true
702
+ if (!allMembers && leading.members.length > 1) {
703
+ const root = startTaskTree(channel, row, leading.members, leading.goal || '请按频道需求协同完成交付。')
704
+ return { duplicate: false, message: row, tasks: [root] }
705
+ }
706
+ const tasks = owners.map(owner => task(channel, owner, row))
707
+ if (replyMemberId && owners.some(owner => owner.id === channel.leaderId)) {
708
+ (channel.replyPlans ??= {})[row.id] = { memberId: replyMemberId }
709
+ }
710
+ return { duplicate: false, message: row, tasks }
711
+ }
712
+
713
+ // Older transfers moved the unanswered question onto the successor. Reopen
714
+ // only that inherited wait, preserving answers already saved by older versions.
715
+ function closeInheritedQuestions(channel) {
716
+ if (channel.rulesVersion !== continuousRulesVersion) return false
717
+ let changed = false
718
+ const tasks = new Map(channel.tasks.map(row => [row.id, row]))
719
+ const answered = new Set(channel.messages.filter(item => item.kind === 'answer').map(item => item.replyTo))
720
+ for (const question of channel.messages) {
721
+ if (question.kind !== 'question' || question.closedByTransfer || answered.has(question.id)) continue
722
+ const holder = tasks.get(question.taskId)
723
+ if (!holder?.handoffs?.length) continue
724
+ const original = holder.handoffs.map(handoff => tasks.get(handoff.fromTaskId)).find(row =>
725
+ row?.status === 'delegated' && row.sourceId === question.replyTo && row.questionId === question.id)
726
+ if (!original) continue
727
+
728
+ const pending = (holder.pendingQuestionId ?? (holder.status === 'waiting' ? holder.questionId : null)) === question.id
729
+ question.closedByTransfer = true
730
+ question.taskId = original.id
731
+ if (holder.questionId === question.id) holder.questionId = holder.answeredQuestionId ?? null
732
+ if (holder.cancellation?.pendingQuestionId === question.id) holder.cancellation.pendingQuestionId = null
733
+ if (pending) {
734
+ holder.pendingQuestionId = null
735
+ if (holder.status === 'waiting') {
736
+ holder.waitingForChildren = hasLiveChildren(channel, holder)
737
+ holder.status = holder.waitingForChildren ? 'paused' : 'queued'
738
+ if (holder.waitingForChildren) holder.error = '接手任务并等待现有子任务'
739
+ else delete holder.error
740
+ }
741
+ holder.handoffs.at(-1).closedQuestionId = question.id
742
+ }
743
+ if (Array.isArray(channel.pendingMemberMessages)) {
744
+ channel.pendingMemberMessages = channel.pendingMemberMessages.filter(item =>
745
+ item.messageId !== question.id || item.taskId === original.id)
746
+ }
747
+ changed = true
748
+ }
749
+ return changed
750
+ }
751
+
752
+ export class ChannelStore {
753
+ constructor() { this.writes = new Map() }
754
+
755
+ path(cwd, id) {
756
+ if (!validChannelId(id)) throw new Error('频道标识无效')
757
+ return join(cwd, '.dsh-group', 'channels', `${id}.json`)
758
+ }
759
+
760
+ async read(cwd, id) {
761
+ const state = JSON.parse(await readFile(this.path(cwd, id), 'utf8'))
762
+ // A stored v2 mapping is authoritative, including anchors minted separately
763
+ // from the channel UUID. The host verifies these IDs against the workspace.
764
+ if (![1, 2].includes(state.version) || state.id !== id || typeof state.sessionId !== 'string' || !state.sessionId
765
+ || typeof state.cwd !== 'string' || !state.cwd || relative(cwd, state.cwd) !== '' || !Array.isArray(state.members)
766
+ || !Array.isArray(state.messages) || !Array.isArray(state.tasks)) {
767
+ throw new Error('频道数据版本或标识不匹配')
768
+ }
769
+ let upgraded = state.version !== 2
770
+ if (state.rulesVersion === undefined) {
771
+ state.rulesVersion = 2
772
+ upgraded = true
773
+ }
774
+ if (![2, continuousRulesVersion].includes(state.rulesVersion)) throw new Error('频道规则版本不受支持')
775
+ const sessions = new Set([state.sessionId]), members = new Set()
776
+ for (const member of state.members) {
777
+ if (!member.id || typeof member.sessionId !== 'string' || !member.sessionId || members.has(member.id) || sessions.has(member.sessionId)) {
778
+ throw new Error('频道成员与会话映射冲突')
779
+ }
780
+ members.add(member.id)
781
+ sessions.add(member.sessionId)
782
+ }
783
+ if (!state.initialSettings) {
784
+ state.initialSettings = { leaderId: state.leaderId, mode: state.mode }
785
+ upgraded = true
786
+ }
787
+ if (!Array.isArray(state.initialSettings.members)) {
788
+ state.initialSettings.members = draftMembers(state.members)
789
+ upgraded = true
790
+ }
791
+ if (!Array.isArray(state.memberForks)) {
792
+ state.memberForks = []
793
+ upgraded = true
794
+ }
795
+ if (!Array.isArray(state.receipts)) {
796
+ state.receipts = []
797
+ upgraded = true
798
+ }
799
+ if (!Array.isArray(state.leaderNotices)) {
800
+ state.leaderNotices = []
801
+ upgraded = true
802
+ }
803
+ if (!state.rulesContextIds || typeof state.rulesContextIds !== 'object' || Array.isArray(state.rulesContextIds)) {
804
+ state.rulesContextIds = {}
805
+ upgraded = true
806
+ }
807
+ if (!Number.isSafeInteger(state.rulesRevision) || state.rulesRevision < 1) {
808
+ state.rulesRevision = 1
809
+ upgraded = true
810
+ }
811
+ if (state.rulesVersion === continuousRulesVersion) {
812
+ for (const field of ['discussions', 'pendingDiscussionContexts']) {
813
+ if (!Array.isArray(state[field])) {
814
+ state[field] = []
815
+ upgraded = true
816
+ }
817
+ }
818
+ }
819
+ state.version = 2
820
+ for (const row of state.tasks) {
821
+ if (!Array.isArray(row.answers)) {
822
+ row.answers = []
823
+ upgraded = true
824
+ }
825
+ if (!Array.isArray(row.receipts)) {
826
+ row.receipts = []
827
+ upgraded = true
828
+ }
829
+ if (state.rulesVersion === continuousRulesVersion && !Array.isArray(row.attempts)) {
830
+ row.attempts = []
831
+ upgraded = true
832
+ }
833
+ if (state.rulesVersion === continuousRulesVersion && !row.contextId && !structuralTask(row)) {
834
+ row.contextId = randomUUID()
835
+ upgraded = true
836
+ }
837
+ if (state.rulesVersion === continuousRulesVersion && !row.contextDeliveredTo) {
838
+ row.contextDeliveredTo = {}
839
+ upgraded = true
840
+ }
841
+ if (row.noticeId === undefined) {
842
+ row.noticeId = null
843
+ upgraded = true
844
+ }
845
+ }
846
+ if (closeInheritedQuestions(state)) upgraded = true
847
+ if (upgraded) Object.defineProperty(state, needsWrite, { value: true, configurable: true })
848
+ return state
849
+ }
850
+
851
+ discussionTurnPath(cwd, channelId, contentId) {
852
+ if (!validChannelId(channelId) || !validChannelId(contentId)) throw new Error('讨论发言标识无效')
853
+ return join(cwd, '.dsh-group', 'discussion-turns', channelId, `${contentId}.txt`)
854
+ }
855
+
856
+ readDiscussionTurn(cwd, channelId, contentId) {
857
+ return readFile(this.discussionTurnPath(cwd, channelId, contentId), 'utf8')
858
+ }
859
+
860
+ writeDiscussionTurn(cwd, channelId, contentId, body) {
861
+ return this.publish(this.discussionTurnPath(cwd, channelId, contentId), body)
862
+ }
863
+
864
+ async assertUploadChannel(cwd, id) {
865
+ await uploadDirectory(cwd, ['.dsh-group', 'channels'])
866
+ const state = await uploadFileInfo(this.path(cwd, id))
867
+ if (state?.nlink !== 1) throw new Error('频道数据必须是普通文件且不能是链接')
868
+ }
869
+
870
+ async persistUploads(cwd, uploads, read, signal) {
871
+ const staged = []
872
+ try {
873
+ for (const upload of uploads) {
874
+ signal?.throwIfAborted()
875
+ const directory = await uploadDirectory(cwd, upload.dirs, true)
876
+ const path = join(cwd, upload.path)
877
+ const pendingName = upload.ref.name.toLowerCase() === '.upload.tmp' ? '.upload.part' : '.upload.tmp'
878
+ const temporary = join(cwd, ...upload.dirs, pendingName)
879
+ const checkDirectory = async () => {
880
+ if (!sameEntry(directory, await uploadDirectory(cwd, upload.dirs))) throw new Error('频道附件目录已改变')
881
+ }
882
+ let existing = await uploadFileInfo(path)
883
+ const pending = await uploadFileInfo(temporary)
884
+ if (pending) {
885
+ // 进程可能在发布前停止,也可能在创建目标后、移除暂存名之前停止。
886
+ const published = existing?.nlink === 2 && pending.nlink === 2 && sameEntry(existing, pending)
887
+ if (pending.nlink !== 1 && !published) throw new Error('频道附件暂存路径包含链接')
888
+ await checkDirectory()
889
+ await unlink(temporary)
890
+ if (published) existing = await uploadFileInfo(path)
891
+ }
892
+ if (existing) {
893
+ await verifyUpload(path, existing, upload, signal)
894
+ continue
895
+ }
896
+ await checkDirectory()
897
+ const handle = await open(temporary, 'wx')
898
+ const item = { checkDirectory, temporary, path }
899
+ staged.push(item)
900
+ try {
901
+ item.entry = await handle.stat()
902
+ await writeUpload(handle, upload, read, signal)
903
+ } finally { await handle.close() }
904
+ }
905
+ // 全部字节验证成功后再发布。独占发布避免覆盖任何现有路径。
906
+ for (const item of staged) {
907
+ signal?.throwIfAborted()
908
+ await item.checkDirectory()
909
+ const pending = await uploadFileInfo(item.temporary)
910
+ if (pending?.nlink !== 1 || !sameEntry(item.entry, pending)) throw new Error('频道附件暂存文件已改变')
911
+ await link(item.temporary, item.path)
912
+ }
913
+ } finally {
914
+ for (const item of staged) {
915
+ await item.checkDirectory()
916
+ const pending = await uploadFileInfo(item.temporary)
917
+ if (pending && sameEntry(item.entry, pending)) await unlink(item.temporary)
918
+ }
919
+ }
920
+ }
921
+
922
+ async publish(file, body, beforePublish) {
923
+ await beforePublish?.()
924
+ await mkdir(dirname(file), { recursive: true })
925
+ const temporary = `${file}.${randomUUID()}.tmp`
926
+ try {
927
+ const handle = await open(temporary, 'wx')
928
+ try { await handle.writeFile(body); await handle.sync() } finally { await handle.close() }
929
+ // Windows 上的短暂读锁可能阻止替换。重试前重新校验调用者。
930
+ for (let attempt = 0; ; attempt++) {
931
+ await beforePublish?.()
932
+ try { await rename(temporary, file); break } catch (error) {
933
+ if (process.platform !== 'win32' || !['EPERM', 'EBUSY', 'EACCES'].includes(error.code) || attempt >= 6) throw error
934
+ await delay(10 * 2 ** attempt)
935
+ }
936
+ }
937
+ } finally { await rm(temporary, { force: true }) }
938
+ }
939
+
940
+ // One DSH host owns the workspace sessions. Serialize each channel's changes
941
+ // and publish a whole generation with a same-directory rename.
942
+ update(cwd, id, change, create = false, beforePublish) {
943
+ const file = this.path(cwd, id)
944
+ const operation = (this.writes.get(file) ?? Promise.resolve()).then(async () => {
945
+ let state
946
+ try { state = await this.read(cwd, id) } catch (error) { if (!create || error.code !== 'ENOENT') throw error }
947
+ if (state === undefined) state = await change()
948
+ else {
949
+ const changed = await change(state)
950
+ if (changed === false && !state[needsWrite]) return state
951
+ advanceTaskTrees(state)
952
+ }
953
+ if (state[needsWrite]) delete state[needsWrite]
954
+ await this.publish(file, JSON.stringify(state, null, 2), beforePublish)
955
+ return state
956
+ })
957
+ const settled = operation.catch(() => {})
958
+ this.writes.set(file, settled)
959
+ return operation.finally(() => { if (this.writes.get(file) === settled) this.writes.delete(file) })
960
+ }
961
+ }