@dabuliu_wsy/dsh-im 0.0.0-stage → 0.3.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.
Files changed (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +204 -3
  3. package/cordis.patch.yml +4 -0
  4. package/dist/core/agent-state.d.ts +38 -0
  5. package/dist/core/agent-state.js +59 -0
  6. package/dist/core/arbiter-bridge.d.ts +25 -0
  7. package/dist/core/arbiter-bridge.js +20 -0
  8. package/dist/core/arbiter.d.ts +29 -0
  9. package/dist/core/arbiter.js +59 -0
  10. package/dist/core/avatar-brands.d.ts +23 -0
  11. package/dist/core/avatar-brands.js +75 -0
  12. package/dist/core/avatar-presets.d.ts +21 -0
  13. package/dist/core/avatar-presets.js +38 -0
  14. package/dist/core/avatar.d.ts +1 -0
  15. package/dist/core/avatar.js +18 -0
  16. package/dist/core/blocked.d.ts +12 -0
  17. package/dist/core/blocked.js +23 -0
  18. package/dist/core/budget-plan.d.ts +41 -0
  19. package/dist/core/budget-plan.js +69 -0
  20. package/dist/core/calibration-samples.d.ts +77 -0
  21. package/dist/core/calibration-samples.js +168 -0
  22. package/dist/core/calibrator.d.ts +57 -0
  23. package/dist/core/calibrator.js +125 -0
  24. package/dist/core/chapter-tree.d.ts +128 -0
  25. package/dist/core/chapter-tree.js +400 -0
  26. package/dist/core/consensus.d.ts +135 -0
  27. package/dist/core/consensus.js +394 -0
  28. package/dist/core/context-budget.d.ts +153 -0
  29. package/dist/core/context-budget.js +183 -0
  30. package/dist/core/curator.d.ts +28 -0
  31. package/dist/core/curator.js +190 -0
  32. package/dist/core/dual-window.d.ts +86 -0
  33. package/dist/core/dual-window.js +175 -0
  34. package/dist/core/events.d.ts +110 -0
  35. package/dist/core/events.js +117 -0
  36. package/dist/core/facts.d.ts +114 -0
  37. package/dist/core/facts.js +400 -0
  38. package/dist/core/fence.d.ts +34 -0
  39. package/dist/core/fence.js +129 -0
  40. package/dist/core/floor.d.ts +18 -0
  41. package/dist/core/floor.js +80 -0
  42. package/dist/core/ids.d.ts +11 -0
  43. package/dist/core/ids.js +29 -0
  44. package/dist/core/im.d.ts +213 -0
  45. package/dist/core/im.js +1640 -0
  46. package/dist/core/index.d.ts +34 -0
  47. package/dist/core/index.js +34 -0
  48. package/dist/core/log.d.ts +21 -0
  49. package/dist/core/log.js +63 -0
  50. package/dist/core/memory-claims.d.ts +67 -0
  51. package/dist/core/memory-claims.js +164 -0
  52. package/dist/core/memory-context.d.ts +121 -0
  53. package/dist/core/memory-context.js +303 -0
  54. package/dist/core/memory-visibility.d.ts +58 -0
  55. package/dist/core/memory-visibility.js +36 -0
  56. package/dist/core/memory.d.ts +12 -0
  57. package/dist/core/memory.js +73 -0
  58. package/dist/core/metrics.d.ts +49 -0
  59. package/dist/core/metrics.js +89 -0
  60. package/dist/core/multi-hop.d.ts +116 -0
  61. package/dist/core/multi-hop.js +278 -0
  62. package/dist/core/persist.d.ts +21 -0
  63. package/dist/core/persist.js +94 -0
  64. package/dist/core/proactive.d.ts +54 -0
  65. package/dist/core/proactive.js +108 -0
  66. package/dist/core/prompt.d.ts +82 -0
  67. package/dist/core/prompt.js +164 -0
  68. package/dist/core/receipt.d.ts +107 -0
  69. package/dist/core/receipt.js +86 -0
  70. package/dist/core/retrieval.d.ts +69 -0
  71. package/dist/core/retrieval.js +260 -0
  72. package/dist/core/role-state.d.ts +16 -0
  73. package/dist/core/role-state.js +65 -0
  74. package/dist/core/runtime.d.ts +137 -0
  75. package/dist/core/runtime.js +574 -0
  76. package/dist/core/summary.d.ts +19 -0
  77. package/dist/core/summary.js +96 -0
  78. package/dist/core/text.d.ts +10 -0
  79. package/dist/core/text.js +45 -0
  80. package/dist/core/time.d.ts +22 -0
  81. package/dist/core/time.js +84 -0
  82. package/dist/core/tool-schema.d.ts +12 -0
  83. package/dist/core/tool-schema.js +92 -0
  84. package/dist/core/tools.d.ts +137 -0
  85. package/dist/core/tools.js +348 -0
  86. package/dist/core/trash.d.ts +110 -0
  87. package/dist/core/trash.js +56 -0
  88. package/dist/core/types.d.ts +400 -0
  89. package/dist/core/types.js +1 -0
  90. package/dist/core/window.d.ts +6 -0
  91. package/dist/core/window.js +7 -0
  92. package/dist/core/workspace-node.d.ts +28 -0
  93. package/dist/core/workspace-node.js +232 -0
  94. package/dist/core/workspace.d.ts +9 -0
  95. package/dist/core/workspace.js +45 -0
  96. package/dist/host/agent-session.d.ts +296 -0
  97. package/dist/host/agent-session.js +964 -0
  98. package/dist/host/attachment-gc.d.ts +37 -0
  99. package/dist/host/attachment-gc.js +97 -0
  100. package/dist/host/calibration-samples-store.d.ts +5 -0
  101. package/dist/host/calibration-samples-store.js +67 -0
  102. package/dist/host/capabilities.d.ts +45 -0
  103. package/dist/host/capabilities.js +67 -0
  104. package/dist/host/derived-store.d.ts +36 -0
  105. package/dist/host/derived-store.js +199 -0
  106. package/dist/host/dsh-llm.d.ts +143 -0
  107. package/dist/host/dsh-llm.js +395 -0
  108. package/dist/host/event-store.d.ts +47 -0
  109. package/dist/host/event-store.js +154 -0
  110. package/dist/host/fs-atomic.d.ts +1 -0
  111. package/dist/host/fs-atomic.js +26 -0
  112. package/dist/host/group-files.d.ts +26 -0
  113. package/dist/host/group-files.js +142 -0
  114. package/dist/host/im-api.d.ts +408 -0
  115. package/dist/host/im-api.js +1188 -0
  116. package/dist/host/index.d.ts +103 -0
  117. package/dist/host/index.js +509 -0
  118. package/dist/host/media-type.d.ts +10 -0
  119. package/dist/host/media-type.js +39 -0
  120. package/dist/host/memory-index.d.ts +65 -0
  121. package/dist/host/memory-index.js +181 -0
  122. package/dist/host/metrics-store.d.ts +7 -0
  123. package/dist/host/metrics-store.js +104 -0
  124. package/dist/host/models.d.ts +39 -0
  125. package/dist/host/models.js +67 -0
  126. package/dist/host/persona-tools.d.ts +57 -0
  127. package/dist/host/persona-tools.js +226 -0
  128. package/dist/host/preflight.d.ts +31 -0
  129. package/dist/host/preflight.js +29 -0
  130. package/dist/host/receipt-store.d.ts +26 -0
  131. package/dist/host/receipt-store.js +68 -0
  132. package/dist/host/run-check.d.ts +51 -0
  133. package/dist/host/run-check.js +190 -0
  134. package/dist/host/state-roots.d.ts +50 -0
  135. package/dist/host/state-roots.js +163 -0
  136. package/dist/host/tool-cache.d.ts +25 -0
  137. package/dist/host/tool-cache.js +90 -0
  138. package/dist/host/tool-call-budget.d.ts +29 -0
  139. package/dist/host/tool-call-budget.js +38 -0
  140. package/dist/host/trash-store.d.ts +32 -0
  141. package/dist/host/trash-store.js +316 -0
  142. package/dsh-plugin.json +25 -0
  143. package/lib/client.inner.cjs +3933 -0
  144. package/lib/client.js +3941 -0
  145. package/package.json +86 -6
@@ -0,0 +1,1640 @@
1
+ import { applyDecision, canSpeak, createRuntimeState, expireIfStale, finishSpeaking, resolveWait, } from './agent-state.js';
2
+ import { decideNext } from './arbiter-bridge.js';
3
+ import { generateAvatar } from './avatar.js';
4
+ import { createId } from './ids.js';
5
+ import { repairDerivedThreadTitles } from './persist.js';
6
+ import { eligiblePersonaIds, parseMentions, shouldEnterReview } from './floor.js';
7
+ import { appendThreadMemory, catalogFor, identityText, refreshThreadSummary, speechLeaksOtherThread, threadMemories, userGlobals, wakeKey, windowMessages, } from './memory.js';
8
+ import { resolveToolFilter } from './tools.js';
9
+ import { DEFAULT_PROACTIVE_LIMITS, proactiveEligibility } from './proactive.js';
10
+ import { defaultChair, MockSpeaker } from './runtime.js';
11
+ import { buildConsensusState, isTransientClaim } from './consensus.js';
12
+ import { buildThreadDigest } from './summary.js';
13
+ import { splitSummaryBudget, SUMMARY_DIRECTORY_SHARE } from './chapter-tree.js';
14
+ import { groupBudgetForThread } from './context-budget.js';
15
+ import { appendMetric } from './metrics.js';
16
+ import { buildRoleState } from './role-state.js';
17
+ import { factsFromMessages, projectFactsFromList, } from './facts.js';
18
+ import { memorySink, summaryRelPath } from './workspace.js';
19
+ import { canRestoreHistory, cloneJson, sanitizeThreadSnapshot, trashHistoryDetail, trashPersonaDetail, trashThreadDetail, } from './trash.js';
20
+ const HOUR = 60 * 60 * 1000;
21
+ export class ImService {
22
+ speaker;
23
+ chair;
24
+ files;
25
+ state;
26
+ constructor(speaker = new MockSpeaker(), chair = defaultChair(), initial, files = memorySink()) {
27
+ this.speaker = speaker;
28
+ this.chair = chair;
29
+ this.files = files;
30
+ this.state = {
31
+ personas: initial?.personas ?? [],
32
+ threads: initial?.threads ?? [],
33
+ memories: initial?.memories ?? [],
34
+ wakeExcerpts: initial?.wakeExcerpts ?? {},
35
+ pendingRecall: initial?.pendingRecall ?? null,
36
+ lastProactiveAt: initial?.lastProactiveAt ?? {},
37
+ };
38
+ }
39
+ /** 角色运行时状态:只在内存、带 TTL,不落盘(崩溃留下的 thinking 自动过期)。 */
40
+ agentStates = new Map();
41
+ /** 正在生成共识的群:防止 UI 自动触发和轮末自动触发重复调用 curator。 */
42
+ consensusInFlight = new Set();
43
+ /** 正在跑事实抽取的群:界面据此显示“抽取中”,而不是误以为任务板空白。 */
44
+ extractionInFlight = new Set();
45
+ /** 异步事实抽取完成时通知界面(重新渲染 + 触发落盘)。 */
46
+ onAsyncChange;
47
+ /** 生成期间出现新消息时的处理策略:重算一次(默认)/ 标注旧版本 / 丢弃。 */
48
+ stalePolicy = 'regenerate';
49
+ /** 按需检索档位:off / shadow(默认,只记录不进 prompt)/ on。 */
50
+ retrievalMode = 'shadow';
51
+ /** 引用句柄协议档位(Phase 1):off / shadow(默认,只写回执)/ on(注入)。 */
52
+ memoryContextMode = 'shadow';
53
+ /**
54
+ * 群级预算输入(A-1/A-2:客户端注入,prompt 组装与 L1 摘要生成用同一份)。
55
+ * 不注入时摘要预算回退到旧的静态口径(`DEFAULT_SUMMARY_TOTAL_CHARS`,digest 份额 = 旧 8000)。
56
+ */
57
+ groupBudgetPolicy;
58
+ /** 章节目录占 summary 预算的比例(默认 40%)。 */
59
+ summaryChapterShare = SUMMARY_DIRECTORY_SHARE;
60
+ /**
61
+ * 共识状态开关(默认开):每轮事实抽取之后自动跑 curator,生成 thread.consensusState。
62
+ * 只有 `localStorage dsh-im:consensus='off'` 才关闭(回滚开关,不需要用户默认点)。
63
+ */
64
+ consensusEnabled = true;
65
+ /** 主动私聊的全局限制(档位数值在 proactive.ts 的预设里;这里可覆盖)。 */
66
+ proactiveLimits = { ...DEFAULT_PROACTIVE_LIMITS };
67
+ snapshot() {
68
+ return structuredClone(this.state);
69
+ }
70
+ /** 当前群的有效事实(用户在任务板归档的已排除,异步抽取的也合并进来)。 */
71
+ factsFor(threadId) {
72
+ return this.localFacts(this.requireThread(threadId));
73
+ }
74
+ /** 任务板:把一条事实归档(写 retract,下一次保存落成事件)。 */
75
+ completeFact(threadId, factId) {
76
+ const thread = this.requireThread(threadId);
77
+ const fact = this.factsFor(threadId).find((item) => item.factId === factId);
78
+ if (!fact)
79
+ return;
80
+ thread.retractedFactIds = [...new Set([...(thread.retractedFactIds ?? []), factId])];
81
+ this.queueFactOp(thread, {
82
+ op: 'retract',
83
+ factId,
84
+ kind: fact.kind,
85
+ text: fact.text,
86
+ source: 'user',
87
+ at: Date.now(),
88
+ });
89
+ this.pushMessage(thread, {
90
+ kind: 'system',
91
+ authorName: '系统主持',
92
+ text: `已把「${fact.text}」归档,不再作为群事实。`,
93
+ });
94
+ this.refreshDigest(thread);
95
+ }
96
+ /** 客户端可见的事实投影:host 投影 + 覆盖点之后的新消息派生事实 + 本地异步抽取,再去掉本地归档的。 */
97
+ localFacts(thread) {
98
+ const retracted = new Set(thread.retractedFactIds ?? []);
99
+ const covered = thread.factsUntilSeq ?? 0;
100
+ // host 投影已覆盖的消息不再本地重算:否则用户在任务板归档的决定会被消息规则重新拉起来。
101
+ const freshDerived = factsFromMessages(thread.messages).active
102
+ .filter((fact) => (fact.seq ?? 0) > covered);
103
+ const merged = projectFactsFromList([
104
+ ...freshDerived,
105
+ ...(thread.facts ?? []),
106
+ ...(thread.extractedFacts ?? []),
107
+ ]).active;
108
+ return retracted.size ? merged.filter((fact) => !retracted.has(fact.factId)) : merged;
109
+ }
110
+ queueFactOp(thread, op) {
111
+ const list = thread.pendingFactOps ?? (thread.pendingFactOps = []);
112
+ const key = `${op.op}|${op.factId}|${op.text}`;
113
+ if (list.some((item) => `${item.op}|${item.factId}|${item.text}` === key))
114
+ return;
115
+ list.push(op);
116
+ if (list.length > 200)
117
+ list.splice(0, list.length - 200);
118
+ }
119
+ applyExtractedFacts(thread, extracted) {
120
+ if (extracted.length === 0 || !this.state.threads.includes(thread))
121
+ return;
122
+ const retracted = new Set(thread.retractedFactIds ?? []);
123
+ const baseSeq = (thread.messages.at(-1)?.seq ?? thread.messages.length) + 1;
124
+ const facts = extracted
125
+ .filter((item) => !retracted.has(item.fact.factId))
126
+ .map((item, index) => ({
127
+ factId: item.fact.factId,
128
+ kind: item.fact.factKind,
129
+ text: item.text,
130
+ ...(item.fact.owner === undefined ? {} : { owner: item.fact.owner }),
131
+ source: 'extractor',
132
+ confidence: item.fact.confidence ?? 0.5,
133
+ seq: baseSeq + index,
134
+ at: item.at,
135
+ ...(item.fact.sourceMessageId === undefined ? {} : { sourceMessageId: item.fact.sourceMessageId }),
136
+ ...(item.fact.sourceMessageSeq === undefined ? {} : { sourceMessageSeq: item.fact.sourceMessageSeq }),
137
+ }));
138
+ thread.extractedFacts = projectFactsFromList([...(thread.extractedFacts ?? []), ...facts]).active;
139
+ for (const fact of facts) {
140
+ this.queueFactOp(thread, {
141
+ op: 'assert',
142
+ factId: fact.factId,
143
+ kind: fact.kind,
144
+ text: fact.text,
145
+ source: 'extractor',
146
+ ...(fact.owner === undefined ? {} : { owner: fact.owner }),
147
+ ...(fact.sourceMessageId === undefined ? {} : { sourceMessageId: fact.sourceMessageId }),
148
+ ...(fact.sourceMessageSeq === undefined ? {} : { sourceMessageSeq: fact.sourceMessageSeq }),
149
+ at: fact.at,
150
+ });
151
+ }
152
+ this.refreshDigest(thread);
153
+ this.onAsyncChange?.();
154
+ }
155
+ /**
156
+ * 每轮结束后异步抽一次事实(有 LLM 通道才跑):不阻塞回复,失败静默。
157
+ * 短招呼(<6 字且非评审)不抽,避免每句都多一次调用。
158
+ */
159
+ scheduleFactExtraction(thread) {
160
+ const extractor = this.speaker;
161
+ if (typeof extractor.extractFacts !== 'function')
162
+ return Promise.resolve();
163
+ const persona = thread.memberIds
164
+ .map((id) => this.state.personas.find((item) => item.id === id))
165
+ .find((item) => Boolean(item?.model));
166
+ if (!persona)
167
+ return Promise.resolve();
168
+ const recent = thread.messages.filter((message) => message.kind !== 'system');
169
+ if (recent.length < 2)
170
+ return Promise.resolve();
171
+ const lastUser = [...recent].reverse().find((message) => message.kind === 'user');
172
+ if (!lastUser)
173
+ return Promise.resolve();
174
+ if (lastUser.text.trim().length < 6 && thread.roundMode !== 'review')
175
+ return Promise.resolve();
176
+ const startedAt = Date.now();
177
+ this.extractionInFlight.add(thread.id);
178
+ return Promise.resolve()
179
+ .then(() => extractor.extractFacts({ thread, messages: recent.slice(-12), persona }))
180
+ .then((facts) => {
181
+ this.recordMetric(thread, {
182
+ at: Date.now(),
183
+ kind: 'extraction',
184
+ value: Date.now() - startedAt,
185
+ fields: { ok: true, facts: facts.length },
186
+ });
187
+ this.applyExtractedFacts(thread, facts);
188
+ })
189
+ .catch((err) => {
190
+ this.recordMetric(thread, {
191
+ at: Date.now(),
192
+ kind: 'extraction',
193
+ value: Date.now() - startedAt,
194
+ fields: { ok: false, error: (err instanceof Error ? err.message : String(err)).slice(0, 120) },
195
+ });
196
+ })
197
+ .finally(() => {
198
+ this.extractionInFlight.delete(thread.id);
199
+ this.onAsyncChange?.();
200
+ });
201
+ }
202
+ /** 事实抽取是否在跑(任务板显示“抽取中”)。 */
203
+ extractionPending(threadId) {
204
+ return this.extractionInFlight.has(threadId);
205
+ }
206
+ /** 共识整理是否在跑(任务板显示“整理中”)。 */
207
+ consensusPending(threadId) {
208
+ return this.consensusInFlight.has(threadId);
209
+ }
210
+ /**
211
+ * 每轮事实抽取之后跑一次 curator → consensus builder,产出 thread.consensusState。
212
+ * `force=true` 供任务板“生成本轮共识”按钮使用(开关关闭时不自动跑,显式点击才跑)。
213
+ *
214
+ * 能力/环境自述由本层先按确定性规则摘出来,直接进 D 栏归档,不交给模型判断:
215
+ * 这样即使 curator 犯错,也不会把“我没有 shell”写进 A/B/C 变成长期约束。
216
+ */
217
+ scheduleConsensus(thread, force = false) {
218
+ if (!this.consensusEnabled && !force)
219
+ return;
220
+ if (this.consensusInFlight.has(thread.id))
221
+ return;
222
+ const curator = this.speaker;
223
+ const facts = this.factsFor(thread.id).map((fact) => ({
224
+ factId: fact.factId,
225
+ eventSeq: fact.seq,
226
+ kind: fact.kind,
227
+ owner: fact.owner ?? '',
228
+ text: fact.text,
229
+ ...(fact.sourceMessageId === undefined ? {} : { sourceMessageId: fact.sourceMessageId }),
230
+ ...(fact.sourceMessageSeq === undefined ? {} : { sourceMessageSeq: fact.sourceMessageSeq }),
231
+ }));
232
+ if (facts.length === 0)
233
+ return;
234
+ this.consensusInFlight.add(thread.id);
235
+ const mode = facts.some((fact) => !fact.sourceMessageId) ? 'legacy' : 'new';
236
+ const isUserOwned = (owner) => owner === '用户' || owner === '你';
237
+ const transient = facts.filter((fact) => !isUserOwned(fact.owner) && isTransientClaim(fact.text));
238
+ const transientIds = new Set(transient.map((fact) => fact.factId));
239
+ const curatable = facts.filter((fact) => !transientIds.has(fact.factId));
240
+ const persona = thread.memberIds
241
+ .map((id) => this.state.personas.find((item) => item.id === id))
242
+ .find((item) => Boolean(item?.model));
243
+ const startedAt = Date.now();
244
+ const finalize = (base) => {
245
+ try {
246
+ const covered = new Set(base.clusters.flatMap((cluster) => cluster.factIds));
247
+ const usedKeys = new Set([
248
+ ...base.clusters.map((cluster) => cluster.key),
249
+ ...(base.derived ?? []).map((cluster) => cluster.key),
250
+ ]);
251
+ const autoClusters = transient
252
+ .filter((fact) => !covered.has(fact.factId))
253
+ .map((fact, index) => {
254
+ let key = `auto-D${index + 1}`;
255
+ while (usedKeys.has(key))
256
+ key += '_';
257
+ usedKeys.add(key);
258
+ return {
259
+ key,
260
+ lane: 'D',
261
+ kind: '能力自述',
262
+ status: 'archived',
263
+ factIds: [fact.factId],
264
+ text: fact.text,
265
+ };
266
+ });
267
+ const draft = {
268
+ clusters: [...base.clusters, ...autoClusters],
269
+ ...(base.derived ? { derived: base.derived } : {}),
270
+ };
271
+ const built = buildConsensusState(facts, draft, {
272
+ mode,
273
+ knownMessageIds: thread.messages.map((message) => message.id),
274
+ });
275
+ if (!built.ok || !built.state) {
276
+ throw new Error('consensus 契约不通过:' + built.errors.slice(0, 3).join(';'));
277
+ }
278
+ if (!this.state.threads.includes(thread))
279
+ return;
280
+ thread.consensusState = built.state;
281
+ thread.consensusError = undefined;
282
+ this.recordMetric(thread, {
283
+ at: Date.now(),
284
+ kind: 'consensus',
285
+ value: Date.now() - startedAt,
286
+ fields: {
287
+ ok: true,
288
+ mode,
289
+ facts: built.state.metrics.facts,
290
+ clusters: built.state.metrics.clusters,
291
+ archived: built.state.metrics.archivedFacts,
292
+ autoArchived: autoClusters.length,
293
+ version: built.state.version,
294
+ },
295
+ });
296
+ this.onAsyncChange?.();
297
+ }
298
+ finally {
299
+ this.consensusInFlight.delete(thread.id);
300
+ }
301
+ };
302
+ if (curatable.length === 0) {
303
+ try {
304
+ finalize({ clusters: [], derived: [] });
305
+ }
306
+ catch (err) {
307
+ const message = err instanceof Error ? err.message : String(err);
308
+ thread.consensusError = message;
309
+ this.recordMetric(thread, {
310
+ at: Date.now(),
311
+ kind: 'consensus',
312
+ value: Date.now() - startedAt,
313
+ fields: { ok: false, mode, error: message.slice(0, 160) },
314
+ });
315
+ this.consensusInFlight.delete(thread.id);
316
+ }
317
+ return;
318
+ }
319
+ if (!persona || typeof curator.curate !== 'function') {
320
+ this.consensusInFlight.delete(thread.id);
321
+ return;
322
+ }
323
+ void Promise.resolve()
324
+ .then(() => curator.curate({
325
+ threadId: thread.id,
326
+ threadTitle: thread.title,
327
+ projectRoot: thread.projectRoot,
328
+ facts: curatable,
329
+ persona,
330
+ }))
331
+ .then(finalize)
332
+ .catch((err) => {
333
+ const message = err instanceof Error ? err.message : String(err);
334
+ thread.consensusError = message;
335
+ this.recordMetric(thread, {
336
+ at: Date.now(),
337
+ kind: 'consensus',
338
+ value: Date.now() - startedAt,
339
+ fields: { ok: false, mode, error: message.slice(0, 160) },
340
+ });
341
+ this.consensusInFlight.delete(thread.id);
342
+ });
343
+ }
344
+ /**
345
+ * 界面自动触发:当前群有事实、但没有共识状态(或共识落后于最新消息)时生成一次。
346
+ * 不需要用户点任何按钮;同一群并发去重,失败只留下 consensusError 供界面提示。
347
+ */
348
+ ensureConsensus(threadId) {
349
+ if (!this.consensusEnabled)
350
+ return;
351
+ let thread;
352
+ try {
353
+ thread = this.requireThread(threadId);
354
+ }
355
+ catch {
356
+ return;
357
+ }
358
+ if (this.consensusInFlight.has(threadId))
359
+ return;
360
+ const facts = this.factsFor(threadId);
361
+ if (facts.length === 0)
362
+ return;
363
+ const state = thread.consensusState;
364
+ if (state) {
365
+ // 用“事实序号”判断是否落后,而不是最后一条消息序号:
366
+ // 回复消息不进 facts,用消息序号必判落后 → 每次 state 更新都重复 curate。
367
+ const maxFactSeq = facts.reduce((max, fact) => Math.max(max, fact.seq), 0);
368
+ const maxRefFactSeq = Math.max(0, ...state.clusters.flatMap((cluster) => cluster.refs.map((ref) => ref.factEventSeq)), ...state.derived.flatMap((cluster) => cluster.refs.map((ref) => ref.factEventSeq)));
369
+ if (maxRefFactSeq >= maxFactSeq)
370
+ return;
371
+ }
372
+ this.scheduleConsensus(thread, true);
373
+ }
374
+ /** 任务板按钮:手动生成/刷新本轮共识(显式动作,不受自动开关限制)。 */
375
+ refreshConsensus(threadId) {
376
+ this.scheduleConsensus(this.requireThread(threadId), true);
377
+ }
378
+ /** 只读一份运行时状态(界面/调试用;不参与落盘)。 */
379
+ runtimeStates() {
380
+ return [...this.agentStates.values()].map((state) => ({ ...state }));
381
+ }
382
+ runtimeState(personaId) {
383
+ const state = this.agentStates.get(personaId);
384
+ return state ? { ...state } : undefined;
385
+ }
386
+ stateOf(personaId, now) {
387
+ const current = this.agentStates.get(personaId) ?? createRuntimeState(personaId, now);
388
+ const fresh = expireIfStale(current, now);
389
+ if (fresh !== current || !this.agentStates.has(personaId))
390
+ this.agentStates.set(personaId, fresh);
391
+ return fresh;
392
+ }
393
+ setAgentState(personaId, next) {
394
+ this.agentStates.set(personaId, next);
395
+ }
396
+ setAgentIdle(personaId, now) {
397
+ const current = this.stateOf(personaId, now);
398
+ this.setAgentState(personaId, { ...current, status: 'idle', since: now, waitingOn: undefined });
399
+ }
400
+ /** 发言完成:本人回 idle 并记冷却;正在等他的角色解除等待。 */
401
+ settleSpeak(personaId, now) {
402
+ this.setAgentState(personaId, finishSpeaking(this.stateOf(personaId, now), now));
403
+ for (const [id, state] of this.agentStates) {
404
+ if (id === personaId)
405
+ continue;
406
+ const next = resolveWait(state, personaId, now);
407
+ if (next !== state)
408
+ this.setAgentState(id, next);
409
+ }
410
+ }
411
+ recordFloorDecision(thread, personaId, action, reason, at = Date.now()) {
412
+ const list = thread.floorDecisions ?? (thread.floorDecisions = []);
413
+ list.push({ personaId, action, reason, at });
414
+ if (list.length > 50)
415
+ list.splice(0, list.length - 50);
416
+ }
417
+ /** 每轮结束刷新分层摘要投影:L1 旧消息压缩 + L2 事实/决策/待办,并推进窗口边界。 */
418
+ refreshDigest(thread) {
419
+ const before = thread.summaryState?.version;
420
+ // A-2:摘要块预算贯通——L1 生成器与冷区章节目录共用群级 summary 预算(目录:摘要=40:60)。
421
+ // 没有注入预算输入时用静态回退:总 13333 → digest 8000(= 旧 L1_CHAR_BUDGET),行为不变。
422
+ const groupBudget = this.groupBudgetPolicy ? groupBudgetForThread(thread, this.groupBudgetPolicy) : undefined;
423
+ const summaryTotal = groupBudget?.summaryChars ?? Math.round(8000 / (1 - this.summaryChapterShare));
424
+ const split = splitSummaryBudget(summaryTotal, { chapterShare: this.summaryChapterShare });
425
+ const digest = buildThreadDigest(thread, thread.summaryState, {
426
+ facts: this.localFacts(thread),
427
+ charBudget: split.digestChars,
428
+ });
429
+ thread.summaryState = digest;
430
+ thread.summaryUntilSeq = digest.untilSeq;
431
+ if (digest.version !== before) {
432
+ this.recordMetric(thread, {
433
+ at: Date.now(),
434
+ kind: 'summary',
435
+ value: digest.untilSeq,
436
+ fields: { l1Chars: digest.l1.length, l2Count: digest.l2.length, factsVersion: digest.factsVersion },
437
+ });
438
+ }
439
+ }
440
+ nameOf(personaId) {
441
+ return this.state.personas.find((persona) => persona.id === personaId)?.name ?? personaId;
442
+ }
443
+ /** 当前最后一条消息 seq(没有 seq 的老消息按 0 算)。 */
444
+ lastMessageSeq(thread) {
445
+ return thread.messages.reduce((max, message) => Math.max(max, message.seq ?? 0), 0);
446
+ }
447
+ recordMetric(thread, entry) {
448
+ thread.pendingMetrics = appendMetric(thread.pendingMetrics, entry);
449
+ }
450
+ /** 每轮结束记一次地板指标(speak/wait/pass 计数)。 */
451
+ recordFloorMetric(thread) {
452
+ const decisions = thread.floorDecisions ?? [];
453
+ const counts = { speak: 0, wait: 0, pass: 0 };
454
+ for (const decision of decisions)
455
+ counts[decision.action] += 1;
456
+ this.recordMetric(thread, {
457
+ at: Date.now(),
458
+ kind: 'floor_round',
459
+ value: decisions.length,
460
+ fields: { ...counts },
461
+ });
462
+ }
463
+ createPersona(input) {
464
+ const name = input.name.trim();
465
+ const model = input.model.trim();
466
+ if (!name)
467
+ throw new Error('角色名不能为空');
468
+ if (!model)
469
+ throw new Error('角色必须绑定模型');
470
+ const tools = resolveToolFilter({ toolAllow: input.toolAllow, toolDeny: input.toolDeny });
471
+ const persona = {
472
+ id: input.id ?? createId('p'),
473
+ name,
474
+ post: input.post?.trim() || undefined,
475
+ avatar: input.avatar || name.slice(0, 1),
476
+ avatarUrl: input.avatarUrl || generateAvatar(name),
477
+ personality: input.personality,
478
+ duties: input.duties,
479
+ origin: input.origin ?? 'mine',
480
+ provider: input.provider,
481
+ model,
482
+ toolAllow: tools.toolAllow,
483
+ toolDeny: tools.toolDeny,
484
+ proactiveDm: input.proactiveDm ?? false,
485
+ proactiveLevel: input.proactiveLevel ?? 'standard',
486
+ defaultActivity: input.defaultActivity ?? 'review',
487
+ };
488
+ this.state.personas.push(persona);
489
+ return persona;
490
+ }
491
+ updatePersona(id, patch) {
492
+ const p = this.requirePersona(id);
493
+ if (patch.model !== undefined && !patch.model.trim())
494
+ throw new Error('角色必须绑定模型');
495
+ const previousName = p.name;
496
+ const next = { ...patch };
497
+ if (patch.toolAllow || patch.toolDeny) {
498
+ Object.assign(next, resolveToolFilter({
499
+ toolAllow: patch.toolAllow ?? (patch.toolDeny ? undefined : p.toolAllow),
500
+ toolDeny: patch.toolDeny,
501
+ }));
502
+ }
503
+ Object.assign(p, next, { id: p.id });
504
+ if (patch.name !== undefined && p.name !== previousName) {
505
+ // DM 标题、以及没被用户改过名的三人小窗标题,都从角色名派生:改名后整体重建一遍。
506
+ repairDerivedThreadTitles(this.state);
507
+ }
508
+ return p;
509
+ }
510
+ listPersonas() {
511
+ return this.state.personas;
512
+ }
513
+ /** 用户明确说“私聊/小窗”且只点了一个人时,返回该角色。 */
514
+ privateChatTarget(thread, text, mentioned) {
515
+ if (thread.kind === 'dm')
516
+ return undefined;
517
+ if (!/私聊|私信|单独聊|单独说|小窗|私下|密聊|悄悄话/.test(text))
518
+ return undefined;
519
+ const ids = mentioned.length
520
+ ? [...new Set(mentioned)]
521
+ : this.personasIn(thread).filter((persona) => text.includes(persona.name)).map((persona) => persona.id);
522
+ const inThread = ids.filter((id) => thread.memberIds.includes(id));
523
+ return inThread.length === 1 ? this.requirePersona(inThread[0]) : undefined;
524
+ }
525
+ /** 改群的“关联项目”目录(角色读/搜/run_check 的根目录)。 */
526
+ setThreadProjectRoot(threadId, projectRoot) {
527
+ const thread = this.requireThread(threadId);
528
+ const next = projectRoot.trim();
529
+ if (!next)
530
+ throw new Error('关联项目不能为空');
531
+ if (next === thread.projectRoot)
532
+ return thread;
533
+ thread.projectRoot = next;
534
+ this.pushMessage(thread, {
535
+ kind: 'system',
536
+ authorName: '系统主持',
537
+ text: `关联项目已改为:${next}`,
538
+ });
539
+ return thread;
540
+ }
541
+ openDm(personaId, projectRoot) {
542
+ const existing = this.state.threads.find((t) => t.kind === 'dm' && t.memberIds.length === 1 && t.memberIds[0] === personaId);
543
+ if (existing)
544
+ return existing;
545
+ const p = this.requirePersona(personaId);
546
+ return this.createThread({
547
+ kind: 'dm',
548
+ title: p.name,
549
+ memberIds: [personaId],
550
+ projectRoot,
551
+ });
552
+ }
553
+ createTriad(personaIds, projectRoot) {
554
+ const [a, b] = personaIds.map((id) => this.requirePersona(id));
555
+ return this.createThread({
556
+ kind: 'triad',
557
+ title: `${a.name}、${b.name}`,
558
+ memberIds: [a.id, b.id],
559
+ projectRoot,
560
+ });
561
+ }
562
+ /** 建群:群名由用户填,留空退回「新群」(UI 的占位也是这个,保证标题永不为空)。 */
563
+ createGroup(title, memberIds, projectRoot) {
564
+ const name = title.trim() || '新群';
565
+ return this.createThread({ kind: 'group', title: name, memberIds, projectRoot });
566
+ }
567
+ /**
568
+ * 改会话名:群(名字本来就是用户起的)与三人小窗(默认标题由角色名派生,改名后置
569
+ * `titleCustom` 锁定,之后角色改名不再覆盖)。DM 标题永远从角色名派生,不允许手改。
570
+ */
571
+ setThreadTitle(threadId, title) {
572
+ const thread = this.requireThread(threadId);
573
+ if (thread.kind === 'dm')
574
+ throw new Error('私聊标题跟着角色名走,不能改名(要改就改角色名)');
575
+ const name = title.trim();
576
+ if (!name)
577
+ throw new Error('名称不能为空');
578
+ if (name === thread.title)
579
+ return thread;
580
+ thread.title = name;
581
+ if (thread.kind === 'triad')
582
+ thread.titleCustom = true;
583
+ return thread;
584
+ }
585
+ setActivity(threadId, personaId, activity) {
586
+ const m = this.requireThread(threadId).members.find((x) => x.personaId === personaId);
587
+ if (m)
588
+ m.activity = activity;
589
+ }
590
+ /**
591
+ * 邀请角色进群(只有群支持;私聊/三人小窗请新建会话)。
592
+ * - 先校验全部 personaId 再落状态,不会"加了一半";
593
+ * - 已在群里的角色跳过并如实回报;
594
+ * - 入群写一条系统记录;活跃度沿用角色默认值,本轮未发言(下一轮完整参与)。
595
+ */
596
+ addMembers(threadId, personaIds) {
597
+ const thread = this.requireThread(threadId);
598
+ if (thread.kind !== 'group') {
599
+ throw new Error('只有群可以邀请成员;私聊/三人小窗请新建会话');
600
+ }
601
+ const unique = [...new Set(personaIds.map((id) => id.trim()).filter(Boolean))];
602
+ if (unique.length === 0)
603
+ return { thread, added: [], skipped: [] };
604
+ const personas = unique.map((id) => this.requirePersona(id));
605
+ const added = personas.filter((persona) => !thread.memberIds.includes(persona.id));
606
+ const skipped = personas
607
+ .filter((persona) => thread.memberIds.includes(persona.id))
608
+ .map((persona) => persona.id);
609
+ if (added.length === 0)
610
+ return { thread, added: [], skipped };
611
+ for (const persona of added) {
612
+ thread.memberIds.push(persona.id);
613
+ thread.members.push({
614
+ personaId: persona.id,
615
+ activity: persona.defaultActivity,
616
+ completedRound: false,
617
+ passedRound: false,
618
+ });
619
+ }
620
+ this.pushMessage(thread, {
621
+ kind: 'system',
622
+ authorName: '系统主持',
623
+ text: `已邀请「${added.map((persona) => persona.name).join('、')}」加入本群。`,
624
+ });
625
+ return { thread, added, skipped };
626
+ }
627
+ // ── 软删除 / 清空 / 恢复(回收站) ─────────────────────────────────────
628
+ //
629
+ // 这一层只改**内存状态**并返回快照计划;物理目录搬运由 host 的回收站负责
630
+ // (`src/host/trash-store.ts` + `/api/im/trash/*`)。调用方(面板)顺序:
631
+ // 1) 调这里的删除方法拿到计划;2) 立即落盘 state;3) 再调 host 把它移入回收站。
632
+ // 任何一步失败都要用对应 restore* 方法回滚内存状态,不能半删。
633
+ /** 删除会话 / 解散群:会话从 state 移除,返回回收站快照。 */
634
+ deleteThread(threadId) {
635
+ const thread = this.requireThread(threadId);
636
+ const snapshot = sanitizeThreadSnapshot(thread);
637
+ this.state.threads = this.state.threads.filter((item) => item.id !== threadId);
638
+ this.dropThreadReferences(threadId);
639
+ return {
640
+ threadId,
641
+ label: thread.title,
642
+ detail: trashThreadDetail(thread),
643
+ snapshot,
644
+ };
645
+ }
646
+ /**
647
+ * 清空聊天记录:会话外壳(标题/成员/关联工作区/自定义小窗名)保留,
648
+ * 消息、事实、共识、摘要、执行轨迹、附件、线程记忆全部清掉;旧数据由 host 移入回收站。
649
+ */
650
+ clearThreadHistory(threadId) {
651
+ const thread = this.requireThread(threadId);
652
+ const snapshot = sanitizeThreadSnapshot(thread);
653
+ const memories = this.state.memories
654
+ .filter((memory) => memory.scope === 'thread' && memory.threadId === threadId)
655
+ .map((memory) => cloneJson(memory));
656
+ const wakeExcerpts = {};
657
+ for (const [key, value] of Object.entries(this.state.wakeExcerpts)) {
658
+ if (key.endsWith(`:${threadId}`))
659
+ wakeExcerpts[key] = [...value];
660
+ }
661
+ thread.messages = [];
662
+ thread.topic = thread.title;
663
+ thread.shortSummary = '';
664
+ thread.summaryState = undefined;
665
+ thread.summaryUntilSeq = 0;
666
+ thread.facts = [];
667
+ thread.factsVersion = undefined;
668
+ thread.factsUntilSeq = 0;
669
+ thread.consensusState = undefined;
670
+ thread.consensusError = undefined;
671
+ thread.traces = [];
672
+ thread.floorDecisions = [];
673
+ thread.blocked = undefined;
674
+ thread.speakingPersonaId = undefined;
675
+ thread.nextHint = undefined;
676
+ thread.roundMode = 'idle';
677
+ thread.unread = 0;
678
+ thread.updatedAt = Date.now();
679
+ this.dropThreadReferences(threadId);
680
+ return {
681
+ threadId,
682
+ label: thread.title,
683
+ detail: trashHistoryDetail(snapshot),
684
+ snapshot,
685
+ memories,
686
+ wakeExcerpts,
687
+ };
688
+ }
689
+ /**
690
+ * 删除角色(彻底连带口径):
691
+ * - 角色从通讯录移除;
692
+ * - 它的私聊(dm)与三人小窗(triad)整个会话一起进回收站;
693
+ * - 群里只移除成员:群历史保留,写一条系统记录说明谁被移出;
694
+ * - 线程记忆 / 唤醒摘要 / pendingRecall / 运行时状态 / 主动私聊节流一起清理。
695
+ */
696
+ deletePersona(personaId) {
697
+ const persona = this.requirePersona(personaId);
698
+ const deletedIds = new Set(this.state.threads
699
+ .filter((thread) => thread.kind !== 'group' && thread.memberIds.includes(personaId))
700
+ .map((thread) => thread.id));
701
+ const threads = this.state.threads
702
+ .filter((thread) => deletedIds.has(thread.id))
703
+ .map((thread) => sanitizeThreadSnapshot(thread));
704
+ const memberships = [];
705
+ for (const thread of this.state.threads) {
706
+ if (thread.kind !== 'group' || !thread.memberIds.includes(personaId))
707
+ continue;
708
+ memberships.push({
709
+ threadId: thread.id,
710
+ index: thread.memberIds.indexOf(personaId),
711
+ activity: this.memberOf(thread, personaId)?.activity ?? persona.defaultActivity,
712
+ });
713
+ }
714
+ const memories = this.state.memories
715
+ .filter((memory) => memory.scope === 'thread' && memory.threadId !== undefined && deletedIds.has(memory.threadId))
716
+ .map((memory) => cloneJson(memory));
717
+ const wakeExcerpts = {};
718
+ for (const [key, value] of Object.entries(this.state.wakeExcerpts)) {
719
+ if (key.startsWith(`${personaId}:`) || [...deletedIds].some((id) => key.endsWith(`:${id}`))) {
720
+ wakeExcerpts[key] = [...value];
721
+ }
722
+ }
723
+ this.state.personas = this.state.personas.filter((item) => item.id !== personaId);
724
+ this.state.threads = this.state.threads.filter((thread) => !deletedIds.has(thread.id));
725
+ for (const id of deletedIds)
726
+ this.dropThreadReferences(id);
727
+ // 群:只移除成员,并留一条历史记录(不然群里会"凭空少一个人")。
728
+ const now = Date.now();
729
+ for (const thread of this.state.threads) {
730
+ if (thread.kind !== 'group')
731
+ continue;
732
+ const index = thread.memberIds.indexOf(personaId);
733
+ if (index < 0)
734
+ continue;
735
+ thread.memberIds.splice(index, 1);
736
+ thread.members = thread.members.filter((member) => member.personaId !== personaId);
737
+ if (thread.speakingPersonaId === personaId)
738
+ thread.speakingPersonaId = undefined;
739
+ if (thread.blocked?.personaId === personaId)
740
+ thread.blocked = undefined;
741
+ this.pushMessage(thread, {
742
+ kind: 'system',
743
+ authorName: '系统主持',
744
+ text: `角色「${persona.name}」已被删除,已移出本群。`,
745
+ }, now);
746
+ }
747
+ // 角色级运行时状态 / 主动私聊节流 / 唤醒摘要。
748
+ this.agentStates.delete(personaId);
749
+ delete this.state.lastProactiveAt[personaId];
750
+ for (const key of Object.keys(this.state.wakeExcerpts)) {
751
+ if (key.startsWith(`${personaId}:`))
752
+ delete this.state.wakeExcerpts[key];
753
+ }
754
+ const recall = this.state.pendingRecall;
755
+ if (recall && (recall.personaId === personaId
756
+ || deletedIds.has(recall.threadId)
757
+ || deletedIds.has(recall.targetThreadId))) {
758
+ this.state.pendingRecall = null;
759
+ }
760
+ return {
761
+ persona: cloneJson(persona),
762
+ label: persona.name,
763
+ detail: trashPersonaDetail(persona, threads, memberships),
764
+ threads,
765
+ memberships,
766
+ memories,
767
+ wakeExcerpts,
768
+ };
769
+ }
770
+ /**
771
+ * 恢复会话(回收站 → 列表)。
772
+ * - 同 id 会话已在列表:拒绝(说明已经恢复过);
773
+ * - DM / 三人小窗里的角色已被删掉:拒绝并提示先恢复角色(否则恢复出一个没有成员的空壳);
774
+ * - 群里有成员已不存在:保留会话、移除失效成员并写系统记录(不静默丢成员关系)。
775
+ */
776
+ restoreThread(snapshot) {
777
+ if (this.state.threads.some((thread) => thread.id === snapshot.id)) {
778
+ throw new Error('回收站里的这个会话已经恢复过了');
779
+ }
780
+ const thread = cloneJson(snapshot);
781
+ const missing = thread.memberIds.filter((id) => !this.state.personas.some((persona) => persona.id === id));
782
+ if (missing.length && thread.kind !== 'group') {
783
+ throw new Error('会话里的角色已被删除,恢复不了;请先到回收站恢复角色,再恢复这个会话');
784
+ }
785
+ thread.memberIds = thread.memberIds.filter((id) => !missing.includes(id));
786
+ thread.members = thread.members.filter((member) => !missing.includes(member.personaId));
787
+ thread.speakingPersonaId = undefined;
788
+ thread.blocked = undefined;
789
+ thread.floorDecisions = [];
790
+ thread.unread = 0;
791
+ thread.roundMode = 'idle';
792
+ thread.updatedAt = Date.now();
793
+ if (missing.length) {
794
+ this.pushMessage(thread, {
795
+ kind: 'system',
796
+ authorName: '系统主持',
797
+ text: '恢复会话时移除了已不存在的角色。',
798
+ });
799
+ }
800
+ this.state.threads.push(thread);
801
+ return thread;
802
+ }
803
+ /**
804
+ * 恢复「清空聊天记录」:把快照里的消息/事实/共识/摘要/轨迹写回**同一个会话**。
805
+ * 只有当前会话一条消息都没有时才允许(否则恢复会盖掉清空后新聊的内容)。
806
+ */
807
+ restoreThreadHistory(snapshot, extras) {
808
+ const thread = this.requireThread(snapshot.id);
809
+ if (!canRestoreHistory(thread)) {
810
+ throw new Error('这个会话清空后又有新消息,不能直接恢复;可先删除会话再恢复,或放弃这条回收站记录');
811
+ }
812
+ const restored = cloneJson(snapshot);
813
+ thread.messages = restored.messages;
814
+ thread.topic = restored.topic;
815
+ thread.shortSummary = restored.shortSummary;
816
+ thread.summaryState = restored.summaryState;
817
+ thread.summaryUntilSeq = restored.summaryUntilSeq;
818
+ thread.facts = restored.facts;
819
+ thread.factsVersion = restored.factsVersion;
820
+ thread.factsUntilSeq = restored.factsUntilSeq;
821
+ thread.consensusState = restored.consensusState;
822
+ thread.consensusError = undefined;
823
+ thread.traces = restored.traces;
824
+ thread.blocked = undefined;
825
+ thread.speakingPersonaId = undefined;
826
+ thread.nextHint = undefined;
827
+ thread.floorDecisions = [];
828
+ thread.roundMode = 'idle';
829
+ thread.unread = 0;
830
+ thread.updatedAt = Date.now();
831
+ for (const memory of extras?.memories ?? []) {
832
+ if (!this.state.memories.some((item) => item.id === memory.id))
833
+ this.state.memories.push(cloneJson(memory));
834
+ }
835
+ for (const [key, value] of Object.entries(extras?.wakeExcerpts ?? {})) {
836
+ if (!this.state.wakeExcerpts[key])
837
+ this.state.wakeExcerpts[key] = [...value];
838
+ }
839
+ return thread;
840
+ }
841
+ /**
842
+ * 恢复角色:角色 + 被连带删除的会话 + 群成员位置 + 记忆/唤醒摘要一起还原。
843
+ * 如果某个会话/群在角色删除后又被删掉,跳过并如实回报(不假装全部恢复)。
844
+ */
845
+ restorePersona(payload) {
846
+ const source = payload.persona;
847
+ if (!source)
848
+ throw new Error('回收站记录里没有角色数据,不能恢复');
849
+ if (this.state.personas.some((persona) => persona.id === source.id)) {
850
+ throw new Error('这个角色已经恢复过了');
851
+ }
852
+ const persona = cloneJson(source);
853
+ this.state.personas.push(persona);
854
+ const restoredThreads = [];
855
+ const skippedThreadIds = [];
856
+ for (const snapshot of payload.threads ?? []) {
857
+ if (this.state.threads.some((thread) => thread.id === snapshot.id)) {
858
+ skippedThreadIds.push(snapshot.id);
859
+ continue;
860
+ }
861
+ const others = snapshot.memberIds.filter((id) => id !== persona.id);
862
+ if (others.some((id) => !this.state.personas.some((item) => item.id === id))) {
863
+ skippedThreadIds.push(snapshot.id);
864
+ continue;
865
+ }
866
+ const thread = cloneJson(snapshot);
867
+ thread.speakingPersonaId = undefined;
868
+ thread.blocked = undefined;
869
+ thread.floorDecisions = [];
870
+ thread.roundMode = 'idle';
871
+ thread.unread = 0;
872
+ thread.updatedAt = Date.now();
873
+ this.state.threads.push(thread);
874
+ restoredThreads.push(thread);
875
+ }
876
+ const skippedMembershipThreadIds = [];
877
+ for (const membership of payload.memberships ?? []) {
878
+ const thread = this.state.threads.find((item) => item.id === membership.threadId);
879
+ if (!thread || thread.kind !== 'group') {
880
+ skippedMembershipThreadIds.push(membership.threadId);
881
+ continue;
882
+ }
883
+ if (thread.memberIds.includes(persona.id))
884
+ continue;
885
+ const index = Math.max(0, Math.min(membership.index, thread.memberIds.length));
886
+ thread.memberIds.splice(index, 0, persona.id);
887
+ thread.members.splice(index, 0, {
888
+ personaId: persona.id,
889
+ activity: membership.activity ?? persona.defaultActivity,
890
+ completedRound: false,
891
+ passedRound: false,
892
+ });
893
+ this.pushMessage(thread, {
894
+ kind: 'system',
895
+ authorName: '系统主持',
896
+ text: `角色「${persona.name}」已从回收站恢复,重新加入本群。`,
897
+ });
898
+ }
899
+ for (const memory of payload.memories ?? []) {
900
+ if (!this.state.memories.some((item) => item.id === memory.id))
901
+ this.state.memories.push(cloneJson(memory));
902
+ }
903
+ for (const [key, value] of Object.entries(payload.wakeExcerpts ?? {})) {
904
+ if (!this.state.wakeExcerpts[key])
905
+ this.state.wakeExcerpts[key] = [...value];
906
+ }
907
+ repairDerivedThreadTitles(this.state);
908
+ return { persona, threads: restoredThreads, skippedThreadIds, skippedMembershipThreadIds };
909
+ }
910
+ /** 删掉一个会话后,把只属于它的引用(线程记忆 / 唤醒摘要 / 跨场召回)清干净。 */
911
+ dropThreadReferences(threadId) {
912
+ this.state.memories = this.state.memories.filter((memory) => !(memory.scope === 'thread' && memory.threadId === threadId));
913
+ for (const key of Object.keys(this.state.wakeExcerpts)) {
914
+ if (key.endsWith(`:${threadId}`))
915
+ delete this.state.wakeExcerpts[key];
916
+ }
917
+ const recall = this.state.pendingRecall;
918
+ if (recall && (recall.threadId === threadId || recall.targetThreadId === threadId)) {
919
+ this.state.pendingRecall = null;
920
+ }
921
+ }
922
+ /** 客户端 UI:自动打开私聊时切到那个小窗。 */
923
+ onDmOpened;
924
+ async sendUser(threadId, text, opts) {
925
+ const thread = this.requireThread(threadId);
926
+ this.abortSpeaking(thread, '已被打断');
927
+ this.resetRound(thread);
928
+ thread.speakingPersonaId = undefined;
929
+ thread.nextHint = undefined;
930
+ const msg = this.pushMessage(thread, {
931
+ kind: 'user',
932
+ authorName: '你',
933
+ text,
934
+ ...(opts?.attachments?.length ? { attachments: opts.attachments } : {}),
935
+ });
936
+ const mentioned = parseMentions(text, this.personasIn(thread));
937
+ // 用户明确要求“私聊/小窗”时,不再在群里排队发言,直接开小窗并让被点的人在小窗里回复。
938
+ const dmTarget = this.privateChatTarget(thread, text, mentioned);
939
+ if (dmTarget) {
940
+ thread.unread = 0;
941
+ this.pushMessage(thread, {
942
+ kind: 'system',
943
+ authorName: '系统主持',
944
+ text: `已为你打开和「${dmTarget.name}」的私聊,接下来的话在小窗里说。`,
945
+ });
946
+ this.refreshDigest(thread);
947
+ this.recordFloorMetric(thread);
948
+ refreshThreadSummary(thread);
949
+ const dm = this.openDm(dmTarget.id, thread.projectRoot);
950
+ const replied = await this.sendUser(dm.id, text, opts?.attachments?.length ? { attachments: opts.attachments } : undefined);
951
+ dm.unread = 0;
952
+ this.onDmOpened?.(dm.id);
953
+ return replied;
954
+ }
955
+ if (shouldEnterReview(text, Boolean(opts?.startReview))) {
956
+ thread.roundMode = 'review';
957
+ this.resetRound(thread);
958
+ this.pushMessage(thread, {
959
+ kind: 'system',
960
+ authorName: '系统主持',
961
+ text: '本轮开始。',
962
+ });
963
+ }
964
+ // 开始前体检/token 失败时点“本轮移除”的成员:这一轮不参与(只影响本轮)。
965
+ for (const personaId of opts?.excludePersonaIds ?? []) {
966
+ const member = this.memberOf(thread, personaId);
967
+ if (member) {
968
+ member.completedRound = true;
969
+ member.passedRound = false;
970
+ }
971
+ }
972
+ thread.unread = 0;
973
+ await this.advanceFloor(thread, mentioned, msg.id);
974
+ this.refreshDigest(thread);
975
+ this.recordFloorMetric(thread);
976
+ refreshThreadSummary(thread);
977
+ const extraction = this.scheduleFactExtraction(thread);
978
+ if (this.consensusEnabled)
979
+ void extraction.then(() => this.scheduleConsensus(thread));
980
+ return thread;
981
+ }
982
+ async confirmRecall(allow) {
983
+ const pending = this.state.pendingRecall;
984
+ if (!pending)
985
+ return null;
986
+ this.state.pendingRecall = null;
987
+ const thread = this.requireThread(pending.threadId);
988
+ if (!allow) {
989
+ this.pushMessage(thread, {
990
+ kind: 'system',
991
+ authorName: '系统主持',
992
+ text: '已拒绝跨场召回,不拉另一场正文。',
993
+ });
994
+ return thread;
995
+ }
996
+ const target = this.requireThread(pending.targetThreadId);
997
+ this.pushMessage(thread, {
998
+ kind: 'system',
999
+ authorName: '系统主持',
1000
+ text: `来自「${target.title}」,先当参考:${target.shortSummary || target.topic}`,
1001
+ });
1002
+ return thread;
1003
+ }
1004
+ pauseRound(threadId) {
1005
+ const thread = this.requireThread(threadId);
1006
+ thread.roundMode = 'idle';
1007
+ thread.speakingPersonaId = undefined;
1008
+ thread.nextHint = undefined;
1009
+ this.pushMessage(thread, {
1010
+ kind: 'system',
1011
+ authorName: '系统主持',
1012
+ text: '已全员暂停。',
1013
+ });
1014
+ }
1015
+ async requestSummary(threadId) {
1016
+ const thread = this.requireThread(threadId);
1017
+ const body = this.buildSummary(thread);
1018
+ const dest = await this.files.writeThreadFile(thread.projectRoot, thread.id, summaryRelPath(), body);
1019
+ this.pushMessage(thread, {
1020
+ kind: 'system',
1021
+ authorName: '系统主持',
1022
+ text: `详细去重汇总已写入 ${dest}。回到干活台让主 Agent 读这个文件即可。另一场文档请自行粘贴。`,
1023
+ });
1024
+ this.state.memories.push(appendThreadMemory(this.state.memories, thread.id, `汇总:${body.slice(0, 200)}`));
1025
+ thread.roundMode = 'idle';
1026
+ return dest;
1027
+ }
1028
+ createThread(input) {
1029
+ const projectRoot = input.projectRoot.trim();
1030
+ if (!projectRoot)
1031
+ throw new Error('关联项目不能为空');
1032
+ for (const id of input.memberIds)
1033
+ this.requirePersona(id);
1034
+ const now = Date.now();
1035
+ const thread = {
1036
+ id: createId('t'),
1037
+ kind: input.kind,
1038
+ title: input.title,
1039
+ topic: input.title,
1040
+ shortSummary: '',
1041
+ memberIds: input.memberIds,
1042
+ members: input.memberIds.map((personaId) => ({
1043
+ personaId,
1044
+ activity: this.requirePersona(personaId).defaultActivity,
1045
+ completedRound: false,
1046
+ passedRound: false,
1047
+ })),
1048
+ projectRoot,
1049
+ messages: [],
1050
+ unread: 0,
1051
+ roundMode: 'idle',
1052
+ createdAt: now,
1053
+ updatedAt: now,
1054
+ };
1055
+ this.state.threads.push(thread);
1056
+ return thread;
1057
+ }
1058
+ /**
1059
+ * 发言权仲裁地板:
1060
+ * 资格门(谁能进候选,含点名独占)→ 仲裁器决定 speak/wait/pass → 执行。
1061
+ * 决策写进 `thread.floorDecisions`(随 state.json 落盘,事件类型下一步补)。
1062
+ */
1063
+ async advanceFloor(thread, mentionedIds, wakeMessageId) {
1064
+ const max = 8;
1065
+ // 用户点名时只让被点名的人发言;没点名才走资格门。
1066
+ const pinMentions = mentionedIds.length > 0;
1067
+ const spokenIds = [];
1068
+ let spoken = 0;
1069
+ while (spoken < max) {
1070
+ const now = Date.now();
1071
+ const ids = pinMentions
1072
+ ? thread.members.map((m) => m.personaId).filter((id) => mentionedIds.includes(id))
1073
+ : eligiblePersonaIds(thread, mentionedIds);
1074
+ const candidates = ids.map((id) => this.requirePersona(id));
1075
+ if (candidates.length === 0) {
1076
+ this.recordFloorDecision(thread, '', 'pass', '本轮没有可发言的角色(已答/弃权/资格之外)', now);
1077
+ if (thread.roundMode === 'review' && thread.members.every((m) => m.completedRound || m.passedRound)) {
1078
+ await this.requestSummary(thread.id);
1079
+ }
1080
+ thread.speakingPersonaId = undefined;
1081
+ thread.nextHint = undefined;
1082
+ return;
1083
+ }
1084
+ const states = {};
1085
+ for (const candidate of candidates)
1086
+ states[candidate.id] = this.stateOf(candidate.id, now);
1087
+ const latest = thread.messages.at(-1)?.text ?? '';
1088
+ let pick;
1089
+ if (candidates.length === 1) {
1090
+ // 唯一候选没必要过仲裁器,但“正在处理”时要等他,不能硬插话。
1091
+ const only = candidates[0];
1092
+ const gate = canSpeak(states[only.id] ?? createRuntimeState(only.id, now), now);
1093
+ if (!gate.ok) {
1094
+ this.recordFloorDecision(thread, only.id, 'wait', `${only.name} 正在处理(${gate.reason ?? '忙'})`, now);
1095
+ thread.speakingPersonaId = undefined;
1096
+ thread.nextHint = only.name;
1097
+ return;
1098
+ }
1099
+ const mentioned = pinMentions && mentionedIds.includes(only.id);
1100
+ this.recordFloorDecision(thread, only.id, 'speak', `${mentioned ? '被点名' : '唯一候选'}:${only.name}`, now);
1101
+ pick = { personaId: only.id, focus: this.focusFor(only, candidates, latest, pinMentions) };
1102
+ }
1103
+ else {
1104
+ const decision = decideNext({
1105
+ latestText: latest,
1106
+ mentionedIds,
1107
+ members: candidates.map((candidate) => {
1108
+ const member = this.memberOf(thread, candidate.id);
1109
+ return {
1110
+ personaId: candidate.id,
1111
+ name: candidate.name,
1112
+ duties: candidate.duties,
1113
+ activity: member?.activity ?? candidate.defaultActivity,
1114
+ answered: Boolean(member?.completedRound || member?.passedRound),
1115
+ };
1116
+ }),
1117
+ states,
1118
+ spokenIds,
1119
+ now,
1120
+ });
1121
+ if (decision.action === 'wait') {
1122
+ this.recordFloorDecision(thread, decision.personaId ?? '', 'wait', decision.reason, now);
1123
+ thread.speakingPersonaId = undefined;
1124
+ thread.nextHint = decision.waitingOn ? this.nameOf(decision.waitingOn) : undefined;
1125
+ return;
1126
+ }
1127
+ if (decision.action === 'pass' || !decision.personaId) {
1128
+ this.recordFloorDecision(thread, decision.personaId ?? '', 'pass', decision.reason, now);
1129
+ if (thread.roundMode === 'review' && thread.members.every((m) => m.completedRound || m.passedRound)) {
1130
+ await this.requestSummary(thread.id);
1131
+ }
1132
+ thread.speakingPersonaId = undefined;
1133
+ thread.nextHint = undefined;
1134
+ return;
1135
+ }
1136
+ this.recordFloorDecision(thread, decision.personaId, 'speak', decision.reason, now);
1137
+ const chosen = this.requirePersona(decision.personaId);
1138
+ pick = { personaId: chosen.id, focus: this.focusFor(chosen, candidates, latest, pinMentions) };
1139
+ }
1140
+ const persona = this.requirePersona(pick.personaId);
1141
+ this.setAgentState(persona.id, applyDecision(this.stateOf(persona.id, now), 'speak', Date.now()));
1142
+ thread.speakingPersonaId = persona.id;
1143
+ const next = candidates.find((c) => c.id !== persona.id);
1144
+ thread.nextHint = next ? next.name : undefined;
1145
+ const visible = this.visibleFor(thread, persona, wakeMessageId);
1146
+ const decisionsAtStart = thread.floorDecisions;
1147
+ const memberNames = thread.memberIds.map((id) => this.requirePersona(id).name);
1148
+ let result;
1149
+ let staleFlag = false;
1150
+ let attempts = 0;
1151
+ while (true) {
1152
+ const turnVisible = attempts === 0 ? visible : this.visibleFor(thread, persona, wakeMessageId);
1153
+ const agentState = this.stateOf(persona.id, Date.now());
1154
+ const roleState = buildRoleState({
1155
+ personaName: persona.name,
1156
+ facts: this.localFacts(thread),
1157
+ ...(agentState.waitingOn ? { waitingOn: this.nameOf(agentState.waitingOn) } : {}),
1158
+ lastSeq: this.lastMessageSeq(thread),
1159
+ });
1160
+ try {
1161
+ result = await this.speaker.complete({
1162
+ persona,
1163
+ thread,
1164
+ focus: pick.focus,
1165
+ visibleMessages: turnVisible,
1166
+ identity: identityText(persona),
1167
+ userGlobal: userGlobals(this.state.memories).map((m) => m.text),
1168
+ threadMemory: this.memoryTexts(persona, thread),
1169
+ catalog: catalogFor(persona.id, this.state.threads),
1170
+ roleState,
1171
+ memberNames,
1172
+ retrievalMode: this.retrievalMode,
1173
+ memoryContextMode: this.memoryContextMode,
1174
+ });
1175
+ }
1176
+ catch (err) {
1177
+ const detail = err instanceof Error ? err.message : String(err);
1178
+ const code = /^([A-Z][A-Z0-9_]{2,}):/.exec(detail)?.[1];
1179
+ this.setAgentIdle(persona.id, Date.now());
1180
+ thread.blocked = {
1181
+ personaId: persona.id,
1182
+ name: persona.name,
1183
+ ...(code ? { code } : {}),
1184
+ message: detail,
1185
+ at: Date.now(),
1186
+ };
1187
+ this.pushMessage(thread, {
1188
+ kind: 'system',
1189
+ authorName: '系统主持',
1190
+ text: `${persona.name}(模型 ${persona.model})调用失败:${detail}。本轮已暂停,等你决定继续还是移除它;不会用假回复顶上。`,
1191
+ });
1192
+ thread.speakingPersonaId = undefined;
1193
+ thread.nextHint = undefined;
1194
+ return;
1195
+ }
1196
+ // 因果校验:生成期间有新消息 → 回复基于旧视图。
1197
+ const currentSeq = this.lastMessageSeq(thread);
1198
+ const basedOnSeq = result.basedOnSeq;
1199
+ if (typeof basedOnSeq !== 'number' || currentSeq <= basedOnSeq)
1200
+ break;
1201
+ // 生成期间用户又发了消息(resetRound 换了决策数组):旧回复一律丢弃,不能污染新一轮。
1202
+ const aborted = thread.floorDecisions !== decisionsAtStart;
1203
+ const policy = aborted ? 'drop' : this.stalePolicy;
1204
+ const lag = currentSeq - basedOnSeq;
1205
+ if (!aborted && policy === 'regenerate' && attempts < 1) {
1206
+ attempts += 1;
1207
+ this.recordMetric(thread, {
1208
+ at: Date.now(),
1209
+ kind: 'stale',
1210
+ value: lag,
1211
+ fields: { action: 'regenerate', personaId: persona.id, basedOnSeq, currentSeq },
1212
+ });
1213
+ continue;
1214
+ }
1215
+ this.recordMetric(thread, {
1216
+ at: Date.now(),
1217
+ kind: 'stale',
1218
+ value: lag,
1219
+ fields: { action: aborted ? 'aborted' : policy, personaId: persona.id, basedOnSeq, currentSeq },
1220
+ });
1221
+ if (policy === 'drop') {
1222
+ const dropped = thread.members.find((m) => m.personaId === persona.id);
1223
+ if (dropped)
1224
+ dropped.completedRound = true;
1225
+ this.setAgentIdle(persona.id, Date.now());
1226
+ result = undefined;
1227
+ if (!aborted) {
1228
+ this.pushMessage(thread, {
1229
+ kind: 'system',
1230
+ authorName: '系统主持',
1231
+ text: `${persona.name} 的回复基于旧版本(生成期间有更新的消息),已丢弃。`,
1232
+ });
1233
+ }
1234
+ break;
1235
+ }
1236
+ staleFlag = true;
1237
+ break;
1238
+ }
1239
+ if (!result) {
1240
+ // 旧版本回复被丢弃:如果期间已经开了新一轮,旧一轮直接让位。
1241
+ if (thread.floorDecisions !== decisionsAtStart)
1242
+ return;
1243
+ thread.speakingPersonaId = undefined;
1244
+ thread.nextHint = undefined;
1245
+ spoken += 1;
1246
+ mentionedIds = mentionedIds.filter((id) => id !== persona.id);
1247
+ continue;
1248
+ }
1249
+ const member = thread.members.find((m) => m.personaId === persona.id);
1250
+ if (this.blockForeignLeak(thread, persona, result.text)) {
1251
+ if (member)
1252
+ member.completedRound = true;
1253
+ this.settleSpeak(persona.id, Date.now());
1254
+ spokenIds.push(persona.id);
1255
+ if (result.proposeRecallThreadId) {
1256
+ this.noteRecall(thread.id, persona.id, result.proposeRecallThreadId);
1257
+ thread.speakingPersonaId = undefined;
1258
+ return;
1259
+ }
1260
+ spoken += 1;
1261
+ mentionedIds = mentionedIds.filter((id) => id !== persona.id);
1262
+ continue;
1263
+ }
1264
+ if (member) {
1265
+ member.completedRound = !result.pass;
1266
+ member.passedRound = Boolean(result.pass);
1267
+ }
1268
+ const spokenMessage = this.pushMessage(thread, {
1269
+ kind: 'persona',
1270
+ authorId: persona.id,
1271
+ authorName: persona.name,
1272
+ text: result.text,
1273
+ pass: result.pass,
1274
+ ...(staleFlag ? { stale: true } : {}),
1275
+ ...(typeof result.basedOnSeq === 'number' ? { basedOnSeq: result.basedOnSeq } : {}),
1276
+ windowReply: this.memberOf(thread, persona.id)?.activity === 'muted',
1277
+ });
1278
+ if (result.trace?.length)
1279
+ this.recordTrace(thread, persona, result.trace, spokenMessage.id);
1280
+ if (result.pass) {
1281
+ this.setAgentState(persona.id, applyDecision(this.stateOf(persona.id, Date.now()), 'pass', Date.now()));
1282
+ this.pushMessage(thread, {
1283
+ kind: 'system',
1284
+ authorName: '系统主持',
1285
+ text: `${persona.name} 本轮弃权(只代表自己没增量)。`,
1286
+ });
1287
+ }
1288
+ else {
1289
+ this.settleSpeak(persona.id, Date.now());
1290
+ }
1291
+ spokenIds.push(persona.id);
1292
+ if (result.proposeRecallThreadId) {
1293
+ this.noteRecall(thread.id, persona.id, result.proposeRecallThreadId);
1294
+ thread.speakingPersonaId = undefined;
1295
+ return;
1296
+ }
1297
+ this.maybeRemember(thread, persona, result.text);
1298
+ await this.maybeProactive(thread, persona, result.text);
1299
+ spoken += 1;
1300
+ mentionedIds = mentionedIds.filter((id) => id !== persona.id);
1301
+ if (pinMentions) {
1302
+ if (mentionedIds.length === 0) {
1303
+ thread.speakingPersonaId = undefined;
1304
+ return;
1305
+ }
1306
+ continue;
1307
+ }
1308
+ if (thread.roundMode !== 'review' && mentionedIds.length === 0 && this.memberOf(thread, persona.id)?.activity !== 'high') {
1309
+ thread.speakingPersonaId = undefined;
1310
+ return;
1311
+ }
1312
+ }
1313
+ }
1314
+ /**
1315
+ * 发言焦点仍由椅子按职责决定(人物选择已交给仲裁器,这里只算 focus)。
1316
+ */
1317
+ focusFor(persona, candidates, latestText, pinMentions) {
1318
+ const mentioned = pinMentions && candidates.some((candidate) => candidate.id === persona.id);
1319
+ const pick = this.chair.pickNext({
1320
+ candidates: [persona],
1321
+ dutiesLeft: candidates.flatMap((candidate) => candidate.duties),
1322
+ latestText,
1323
+ mentionedIds: mentioned ? [persona.id] : [],
1324
+ });
1325
+ return pick?.focus || persona.duties[0] || '增量补充';
1326
+ }
1327
+ /**
1328
+ * 解除中断:skip = 本轮移除该角色继续;retry = 已修好,重试本轮。
1329
+ */
1330
+ /** 开始前体检不通过:把指定成员从本轮候选移除(只影响本轮,不踢出群)。 */
1331
+ excludeFromRound(threadId, personaIds) {
1332
+ const thread = this.state.threads.find((item) => item.id === threadId);
1333
+ if (!thread)
1334
+ throw new Error('群不存在');
1335
+ const names = [];
1336
+ for (const personaId of personaIds) {
1337
+ const member = thread.members.find((item) => item.personaId === personaId);
1338
+ if (!member)
1339
+ continue;
1340
+ member.completedRound = true;
1341
+ member.passedRound = false;
1342
+ names.push(this.state.personas.find((persona) => persona.id === personaId)?.name ?? personaId);
1343
+ }
1344
+ if (names.length) {
1345
+ this.pushMessage(thread, {
1346
+ kind: 'system',
1347
+ authorName: '系统主持',
1348
+ text: `本轮已移除 ${names.join('、')}(开始前体检不通过)。`,
1349
+ });
1350
+ }
1351
+ }
1352
+ async resolveBlocked(threadId, action) {
1353
+ const thread = this.state.threads.find((item) => item.id === threadId);
1354
+ if (!thread)
1355
+ throw new Error('群不存在');
1356
+ const blocked = thread.blocked;
1357
+ if (!blocked)
1358
+ return;
1359
+ thread.blocked = undefined;
1360
+ if (action === 'skip') {
1361
+ const member = thread.members.find((item) => item.personaId === blocked.personaId);
1362
+ if (member)
1363
+ member.completedRound = true;
1364
+ this.pushMessage(thread, {
1365
+ kind: 'system',
1366
+ authorName: '系统主持',
1367
+ text: `本轮已移除 ${blocked.name}(${blocked.message}),继续。`,
1368
+ });
1369
+ }
1370
+ else {
1371
+ this.pushMessage(thread, {
1372
+ kind: 'system',
1373
+ authorName: '系统主持',
1374
+ text: `${blocked.name} 已恢复,重试本轮。`,
1375
+ });
1376
+ }
1377
+ await this.advanceFloor(thread, []);
1378
+ this.refreshDigest(thread);
1379
+ this.recordFloorMetric(thread);
1380
+ }
1381
+ noteRecall(threadId, personaId, targetThreadId) {
1382
+ if (!this.state.threads.some((t) => t.id === targetThreadId))
1383
+ return;
1384
+ this.state.pendingRecall = { threadId, personaId, targetThreadId };
1385
+ }
1386
+ blockForeignLeak(thread, persona, text) {
1387
+ const leaked = speechLeaksOtherThread(text, this.otherThreadBodies(thread.id), this.allowedSpeech(thread, persona.id));
1388
+ if (!leaked)
1389
+ return false;
1390
+ this.pushMessage(thread, {
1391
+ kind: 'system',
1392
+ authorName: '系统主持',
1393
+ text: `${persona.name} 的回复含另一场正文,未同意前已整段拦住。`,
1394
+ });
1395
+ return true;
1396
+ }
1397
+ otherThreadBodies(threadId) {
1398
+ const out = [];
1399
+ for (const t of this.state.threads) {
1400
+ if (t.id === threadId)
1401
+ continue;
1402
+ for (const m of t.messages) {
1403
+ if (m.kind === 'system')
1404
+ continue;
1405
+ out.push(m.text);
1406
+ }
1407
+ }
1408
+ for (const m of this.state.memories) {
1409
+ if (m.scope === 'thread' && m.threadId && m.threadId !== threadId)
1410
+ out.push(m.text);
1411
+ }
1412
+ return out;
1413
+ }
1414
+ allowedSpeech(thread, personaId) {
1415
+ const local = [
1416
+ ...thread.messages.map((m) => m.text),
1417
+ ...threadMemories(this.state.memories, thread.id).map((m) => m.text),
1418
+ ];
1419
+ const catalog = catalogFor(personaId, this.state.threads)
1420
+ .filter((c) => c.threadId !== thread.id)
1421
+ .flatMap((c) => [c.title, c.topic, c.shortSummary]);
1422
+ return [...local, ...catalog];
1423
+ }
1424
+ visibleFor(thread, persona, wakeMessageId) {
1425
+ const member = this.memberOf(thread, persona.id);
1426
+ if (member?.activity === 'muted') {
1427
+ const around = wakeMessageId ?? thread.messages.at(-1)?.id;
1428
+ const windowed = around ? windowMessages(thread.messages, around, 6) : thread.messages.slice(-6);
1429
+ const key = wakeKey(persona.id, thread.id);
1430
+ const old = this.state.wakeExcerpts[key] ?? [];
1431
+ const excerpt = windowed.map((m) => `${m.authorName}: ${m.text}`).join('\n');
1432
+ this.state.wakeExcerpts[key] = [...old.slice(-5), excerpt];
1433
+ return windowed;
1434
+ }
1435
+ return thread.messages;
1436
+ }
1437
+ memoryTexts(persona, thread) {
1438
+ const own = threadMemories(this.state.memories, thread.id).map((m) => m.text);
1439
+ const member = this.memberOf(thread, persona.id);
1440
+ if (member?.activity === 'muted') {
1441
+ const wakes = this.state.wakeExcerpts[wakeKey(persona.id, thread.id)] ?? [];
1442
+ return [...wakes, ...own];
1443
+ }
1444
+ return own;
1445
+ }
1446
+ /** 记录一轮执行轨迹(最多保留最近 40 轮,steps 截断)。 */
1447
+ recordTrace(thread, persona, steps, messageId) {
1448
+ const first = steps[0]?.at ?? Date.now();
1449
+ const last = steps[steps.length - 1]?.at ?? first;
1450
+ thread.traces = [
1451
+ ...(thread.traces ?? []),
1452
+ {
1453
+ id: createId('tr'),
1454
+ personaId: persona.id,
1455
+ personaName: persona.name,
1456
+ ...(messageId ? { messageId } : {}),
1457
+ at: first,
1458
+ ms: Math.max(0, last - first),
1459
+ steps: steps.slice(0, 40),
1460
+ },
1461
+ ].slice(-40);
1462
+ }
1463
+ maybeRemember(thread, persona, text) {
1464
+ if (text.length < 8)
1465
+ return;
1466
+ this.state.memories.push(appendThreadMemory(this.state.memories, thread.id, `${persona.name}:${text.slice(0, 120)}`));
1467
+ }
1468
+ async maybeProactive(thread, persona, lastText) {
1469
+ if (!persona.proactiveDm)
1470
+ return;
1471
+ if (!/不宜公开|私下| discreet|薪资|人事/.test(lastText) && !/私下/.test(lastText))
1472
+ return;
1473
+ const last = this.state.lastProactiveAt[persona.id] ?? 0;
1474
+ if (Date.now() - last < HOUR)
1475
+ return;
1476
+ if (thread.roundMode === 'review')
1477
+ return;
1478
+ const dm = this.openDm(persona.id, thread.projectRoot);
1479
+ this.pushMessage(dm, {
1480
+ kind: 'persona',
1481
+ authorId: persona.id,
1482
+ authorName: persona.name,
1483
+ text: `有一点不宜在「${thread.title}」里公开:${lastText.slice(0, 80)}`,
1484
+ proactive: true,
1485
+ });
1486
+ dm.unread += 1;
1487
+ this.state.lastProactiveAt[persona.id] = Date.now();
1488
+ }
1489
+ /**
1490
+ * 客户端定时器调用:挑一个可触发的角色,生成一条主动私聊(一次 tick 最多一条)。
1491
+ * 判定是纯函数(proactive.ts),这里只负责生成/投递/计数;失败静默,不影响主流程。
1492
+ */
1493
+ async tickProactive(now = Date.now()) {
1494
+ for (const persona of this.state.personas) {
1495
+ if (!persona.proactiveDm)
1496
+ continue;
1497
+ const verdict = proactiveEligibility({
1498
+ persona,
1499
+ now,
1500
+ threads: this.state.threads,
1501
+ agentStatus: this.stateOf(persona.id, now).status,
1502
+ limits: this.proactiveLimits,
1503
+ });
1504
+ if (!verdict.ok)
1505
+ continue;
1506
+ const group = this.state.threads.find((thread) => thread.kind === 'group' && thread.memberIds.includes(persona.id));
1507
+ const dm = this.openDm(persona.id, group?.projectRoot ?? this.defaultProjectRoot());
1508
+ const roleState = group
1509
+ ? buildRoleState({
1510
+ personaName: persona.name,
1511
+ facts: this.localFacts(group),
1512
+ lastSeq: group.messages.reduce((max, message) => Math.max(max, message.seq ?? 0), 0),
1513
+ })
1514
+ : undefined;
1515
+ try {
1516
+ const result = await this.speaker.complete({
1517
+ persona,
1518
+ thread: dm,
1519
+ focus: '主动私聊',
1520
+ visibleMessages: dm.messages,
1521
+ identity: identityText(persona),
1522
+ userGlobal: userGlobals(this.state.memories).map((entry) => entry.text),
1523
+ threadMemory: this.memoryTexts(persona, dm),
1524
+ catalog: catalogFor(persona.id, this.state.threads),
1525
+ memberNames: [persona.name],
1526
+ proactive: true,
1527
+ ...(roleState ? { roleState } : {}),
1528
+ });
1529
+ const text = result.text.trim();
1530
+ if (!text || result.pass)
1531
+ return { fired: false, personaId: persona.id, reason: 'empty' };
1532
+ this.pushMessage(dm, {
1533
+ kind: 'persona',
1534
+ authorId: persona.id,
1535
+ authorName: persona.name,
1536
+ text,
1537
+ proactive: true,
1538
+ }, now);
1539
+ dm.unread += 1;
1540
+ this.state.lastProactiveAt[persona.id] = now;
1541
+ return { fired: true, personaId: persona.id, reason: 'ok' };
1542
+ }
1543
+ catch {
1544
+ // 主动私聊失败不打扰用户(也不进中断卡),下一轮再试。
1545
+ return { fired: false, personaId: persona.id, reason: 'error' };
1546
+ }
1547
+ }
1548
+ return { fired: false, reason: 'none-eligible' };
1549
+ }
1550
+ defaultProjectRoot() {
1551
+ return this.state.threads.find((thread) => thread.projectRoot)?.projectRoot ?? '.';
1552
+ }
1553
+ abortSpeaking(thread, label) {
1554
+ const last = [...thread.messages].reverse().find((m) => m.kind === 'persona' && !m.pass);
1555
+ if (thread.speakingPersonaId && last && !last.interrupted) {
1556
+ last.interrupted = true;
1557
+ last.text = `${last.text}\n(${label})`;
1558
+ }
1559
+ thread.speakingPersonaId = undefined;
1560
+ for (const m of thread.members) {
1561
+ if (!m.completedRound && !m.passedRound)
1562
+ continue;
1563
+ }
1564
+ const speaking = thread.members.find((m) => m.personaId && !m.completedRound);
1565
+ if (speaking) {
1566
+ speaking.completedRound = false;
1567
+ speaking.passedRound = false;
1568
+ }
1569
+ }
1570
+ resetRound(thread) {
1571
+ const now = Date.now();
1572
+ for (const m of thread.members) {
1573
+ m.completedRound = false;
1574
+ m.passedRound = false;
1575
+ // 新一轮开始:弃权/等待/冷却清零;正在生成的不动(等它自己回 idle 或 TTL 过期)。
1576
+ const current = this.agentStates.get(m.personaId);
1577
+ if (!current || current.status === 'thinking')
1578
+ continue;
1579
+ this.agentStates.set(m.personaId, {
1580
+ ...current,
1581
+ status: 'idle',
1582
+ since: now,
1583
+ waitingOn: undefined,
1584
+ lastSpokeAt: undefined,
1585
+ });
1586
+ }
1587
+ thread.floorDecisions = [];
1588
+ }
1589
+ buildSummary(thread) {
1590
+ const lines = thread.messages
1591
+ .filter((m) => m.kind === 'persona' && !m.pass)
1592
+ .map((m) => `- ${m.authorName}:${m.text}`);
1593
+ return [
1594
+ `# ${thread.title} 本轮汇总`,
1595
+ '',
1596
+ `主题:${thread.topic}`,
1597
+ '',
1598
+ '## 观点(已去重合并同发言人)',
1599
+ ...lines,
1600
+ '',
1601
+ '## 建议',
1602
+ '不改已有源码;产物仅写在本目录。回到干活台让主 Agent 阅读本文件。',
1603
+ '',
1604
+ ].join('\n');
1605
+ }
1606
+ pushMessage(thread, partial, at = Date.now()) {
1607
+ const seq = thread.messages.reduce((max, message) => Math.max(max, message.seq ?? 0), thread.messages.length) + 1;
1608
+ const msg = {
1609
+ id: createId('m'),
1610
+ threadId: thread.id,
1611
+ seq,
1612
+ createdAt: at,
1613
+ ...partial,
1614
+ };
1615
+ thread.messages.push(msg);
1616
+ thread.updatedAt = msg.createdAt;
1617
+ return msg;
1618
+ }
1619
+ personasIn(thread) {
1620
+ return thread.memberIds.map((id) => this.requirePersona(id));
1621
+ }
1622
+ memberOf(thread, personaId) {
1623
+ return thread.members.find((m) => m.personaId === personaId);
1624
+ }
1625
+ requirePersona(id) {
1626
+ const p = this.state.personas.find((x) => x.id === id);
1627
+ if (!p)
1628
+ throw new Error(`persona not found: ${id}`);
1629
+ return p;
1630
+ }
1631
+ requireThread(id) {
1632
+ const t = this.state.threads.find((x) => x.id === id);
1633
+ if (!t)
1634
+ throw new Error(`thread not found: ${id}`);
1635
+ return t;
1636
+ }
1637
+ addMemory(entry) {
1638
+ this.state.memories.push(entry);
1639
+ }
1640
+ }