@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,400 @@
1
+ /**
2
+ * 事实(facts)事件化:决策/待办/承诺/约束写成 `fact` 事件,`facts.json` 是可重建投影。
3
+ *
4
+ * 规则:
5
+ * - 同一事实的 id 由“分类 + 规范化正文” hash 派生 → 重复抽取幂等;
6
+ * - 写入优先级 用户 > 角色显式声明 > LLM 抽取(低优先级不能覆盖高优先级);
7
+ * - `supersede` 替换旧事实,`retract` 撤下;不可压缩项(决策/待办/承诺/约束)永远保留。
8
+ *
9
+ * 注:渲染/diff 时会先剥掉旧版泄漏进正文的思维链(stripLegacyReasoning),但 fact.text 本身原样保存。
10
+ *
11
+ * 本文件是纯函数(不碰磁盘),客户端和 host 都能用。
12
+ */
13
+ import { stableHash } from './receipt.js';
14
+ import { stripLegacyReasoning } from './text.js';
15
+ export const FACT_VERSION_PREFIX = 'facts-v1';
16
+ /** 事实分类的展示名(摘要/prompt 里用)。 */
17
+ export const FACT_KIND_LABEL = {
18
+ decision: '决定',
19
+ todo: '待办',
20
+ commitment: '承诺',
21
+ constraint: '约束',
22
+ stance: '立场',
23
+ fact: '事实',
24
+ };
25
+ /** 不可压缩项:摘要再压缩也必须保留。 */
26
+ export const INCOMPRESSIBLE_KINDS = ['decision', 'todo', 'commitment', 'constraint'];
27
+ /**
28
+ * 角色在陈述自己的工具/环境限制(“没有 shell / 跑不了 / 只能在群里 / 私聊发不出去”)。
29
+ * 这类内容只能是本轮便签:一旦当成长期约束回灌 prompt,角色就会自我说服,永久拒绝本来能做的事。
30
+ * 放在 facts 层是因为摘要(L2)、角色状态快照、共识三条注入路径都要共用同一条判定。
31
+ */
32
+ export const TRANSIENT_CLAIM = /(没有|不跑|不能跑|跑不了|无法)\s*(run_check|shell|权限|工具)|无法(?:运行|执行|读取|访问|打开|私聊|发消息)|发不出去|未安装|检查根|当前关联项目|零命中|只能(?:在群里|落在)|工具清单|没有该能力/;
33
+ export function isTransientClaim(text) {
34
+ return TRANSIENT_CLAIM.test(text);
35
+ }
36
+ /** owner 是不是用户本人(用户 / 你)。用户说的能力限制是真实指令,不按便签处理。 */
37
+ export function isUserFactOwner(owner) {
38
+ return owner === '用户' || owner === '你';
39
+ }
40
+ /** 是否允许把这条事实注入 prompt(能力/环境自述只允许留在事实投影里,不进摘要/状态/共识权威层)。 */
41
+ export function isPromptVisibleFact(fact) {
42
+ return isUserFactOwner(fact.owner) || !isTransientClaim(fact.text);
43
+ }
44
+ export const SOURCE_PRIORITY = {
45
+ user: 3,
46
+ persona: 2,
47
+ extractor: 1,
48
+ };
49
+ export function normalizeFactText(text) {
50
+ return text.replace(/\s+/g, ' ').trim();
51
+ }
52
+ /** 事实 id:同分类同正文 → 同一个 id(幂等抽取的关键)。 */
53
+ export function factIdFor(kind, text) {
54
+ const digest = stableHash(`${kind}|${normalizeFactText(text)}`).split(':').at(-1) ?? '0';
55
+ return `f_${kind}_${digest}`;
56
+ }
57
+ function isFactKind(value) {
58
+ return typeof value === 'string' && value in FACT_KIND_LABEL;
59
+ }
60
+ /** 从一条聊天事件投影出事实(`fact` 事件)。 */
61
+ export function factFromEvent(event) {
62
+ const payload = event.fact;
63
+ if (!payload || payload.op === 'retract')
64
+ return null;
65
+ if (!isFactKind(payload.factKind))
66
+ return null;
67
+ const text = normalizeFactText(event.text);
68
+ if (!text)
69
+ return null;
70
+ return {
71
+ factId: payload.factId,
72
+ kind: payload.factKind,
73
+ text,
74
+ ...(payload.owner === undefined ? {} : { owner: payload.owner }),
75
+ source: payload.source,
76
+ confidence: payload.confidence ?? (payload.source === 'user' ? 1 : 0.7),
77
+ seq: event.seq,
78
+ at: event.at,
79
+ ...(payload.sourceMessageId === undefined ? {} : { sourceMessageId: payload.sourceMessageId }),
80
+ ...(payload.sourceMessageSeq === undefined ? {} : { sourceMessageSeq: payload.sourceMessageSeq }),
81
+ };
82
+ }
83
+ function versionOf(facts) {
84
+ const body = facts
85
+ .map((fact) => `${fact.factId}|${fact.kind}|${fact.text}|${fact.source}`)
86
+ .sort()
87
+ .join('\n');
88
+ return `${FACT_VERSION_PREFIX}:${stableHash(body).split(':').at(-1) ?? '0'}`;
89
+ }
90
+ /** 事件流 → 当前有效事实(assert/supersede/retract + 优先级)。 */
91
+ export function projectFacts(events) {
92
+ const ordered = [...events].sort((left, right) => left.seq - right.seq);
93
+ const active = new Map();
94
+ for (const event of ordered) {
95
+ if (event.kind !== 'fact' || !event.fact)
96
+ continue;
97
+ const payload = event.fact;
98
+ if (payload.op === 'retract') {
99
+ const existing = active.get(payload.factId);
100
+ // 低优先级来源不能撤掉高优先级事实(抽取器删不掉用户决定)。
101
+ if (existing && SOURCE_PRIORITY[payload.source] < SOURCE_PRIORITY[existing.source])
102
+ continue;
103
+ active.delete(payload.factId);
104
+ continue;
105
+ }
106
+ if (payload.op === 'supersede' && payload.supersedes) {
107
+ const old = active.get(payload.supersedes);
108
+ // 低优先级来源不能替换高优先级事实。
109
+ if (old && SOURCE_PRIORITY[payload.source] < SOURCE_PRIORITY[old.source])
110
+ continue;
111
+ active.delete(payload.supersedes);
112
+ }
113
+ const fact = factFromEvent(event);
114
+ if (!fact)
115
+ continue;
116
+ const existing = active.get(fact.factId);
117
+ if (existing && SOURCE_PRIORITY[fact.source] < SOURCE_PRIORITY[existing.source])
118
+ continue;
119
+ active.set(fact.factId, fact);
120
+ }
121
+ const activeFacts = [...active.values()].sort(compareFacts);
122
+ return { active: activeFacts, version: versionOf(activeFacts) };
123
+ }
124
+ /** 已经投影好的事实列表 → 再投影一次(去重 + 优先级 + 版本;host 落盘后的入口)。 */
125
+ export function projectFactsFromList(facts) {
126
+ const active = new Map();
127
+ for (const fact of [...facts].sort((left, right) => left.seq - right.seq)) {
128
+ const existing = active.get(fact.factId);
129
+ if (existing && SOURCE_PRIORITY[fact.source] < SOURCE_PRIORITY[existing.source])
130
+ continue;
131
+ active.set(fact.factId, fact);
132
+ }
133
+ const activeFacts = [...active.values()].sort(compareFacts);
134
+ return { active: activeFacts, version: versionOf(activeFacts) };
135
+ }
136
+ export function compareFacts(left, right) {
137
+ const rank = (fact) => INCOMPRESSIBLE_KINDS.includes(fact.kind) ? 0 : 1;
138
+ const byRank = rank(left) - rank(right);
139
+ if (byRank !== 0)
140
+ return byRank;
141
+ if (left.seq !== right.seq)
142
+ return left.seq - right.seq;
143
+ return left.factId.localeCompare(right.factId);
144
+ }
145
+ function confidenceFor(source) {
146
+ if (source === 'user')
147
+ return 1;
148
+ if (source === 'persona')
149
+ return 0.8;
150
+ return 0.5;
151
+ }
152
+ /** 一段文本里显式声明的事实(本地规则抽取,不调模型;LLM 抽取以后接同一个入口)。 */
153
+ export function extractFactsFromText(input) {
154
+ const out = [];
155
+ const seen = new Set();
156
+ const push = (kind, raw) => {
157
+ const text = normalizeFactText(raw);
158
+ if (text.length < 2)
159
+ return;
160
+ const factId = factIdFor(kind, text);
161
+ if (seen.has(factId))
162
+ return;
163
+ seen.add(factId);
164
+ out.push({
165
+ at: input.at,
166
+ text,
167
+ fact: {
168
+ op: 'assert',
169
+ factId,
170
+ factKind: kind,
171
+ source: input.source,
172
+ ...(input.owner === undefined ? {} : { owner: input.owner }),
173
+ confidence: confidenceFor(input.source),
174
+ ...(input.sourceMessageId === undefined ? {} : { sourceMessageId: input.sourceMessageId }),
175
+ ...(input.sourceMessageSeq === undefined ? {} : { sourceMessageSeq: input.sourceMessageSeq }),
176
+ },
177
+ });
178
+ };
179
+ if (input.source === 'user') {
180
+ // 用户显式记忆:“记住:…”“约定:…”“定下来:…”(允许前面有 @某人 / 空格)
181
+ for (const match of input.text.matchAll(/(?:^|[\s\n])(?:记住|记一下|记下|约定|定下来|定下)[::]\s*([^\n]{2,200})/g)) {
182
+ push('decision', match[1]);
183
+ }
184
+ for (const match of input.text.matchAll(/(?:^|[\s\n])(?:待办|TODO|todo)[::]\s*([^\n]{2,200})/g)) {
185
+ push('todo', match[1]);
186
+ }
187
+ }
188
+ else {
189
+ // 角色显式声明:“承诺:…”“我认领:…”“约束:…”“立场:…”
190
+ for (const match of input.text.matchAll(/(?:^|[\s\n])(?:承诺|我认领|我负责|我决定)[::]\s*([^\n]{2,200})/g)) {
191
+ push('commitment', match[1]);
192
+ }
193
+ for (const match of input.text.matchAll(/(?:^|[\s\n])(?:约束|红线)[::]\s*([^\n]{2,200})/g)) {
194
+ push('constraint', match[1]);
195
+ }
196
+ for (const match of input.text.matchAll(/(?:^|[\s\n])(?:立场)[::]\s*([^\n]{2,200})/g)) {
197
+ push('stance', match[1]);
198
+ }
199
+ }
200
+ // 任意角色都可以用显式的 FACT: 标记。
201
+ for (const match of input.text.matchAll(/(?:^|[\s\n])(?:FACT|事实)[::]\s*([^\n]{2,200})/gi)) {
202
+ push('fact', match[1]);
203
+ }
204
+ return out;
205
+ }
206
+ /**
207
+ * 从消息投影出事实事件(确定性、幂等):同一段正文永远得到同一 factId。
208
+ * `source` 由消息类型决定:用户消息 = user,角色发言 = persona。
209
+ */
210
+ export function factEventsFromMessages(messages) {
211
+ const out = [];
212
+ for (const message of messages) {
213
+ if (message.kind === 'system' || message.pass)
214
+ continue;
215
+ const source = message.kind === 'user' ? 'user' : 'persona';
216
+ const owner = message.kind === 'user' ? '你' : message.authorName;
217
+ out.push(...extractFactsFromText({
218
+ text: message.text,
219
+ source,
220
+ owner,
221
+ at: message.createdAt,
222
+ sourceMessageId: message.id,
223
+ ...(message.seq === undefined ? {} : { sourceMessageSeq: message.seq }),
224
+ }).map((item) => (message.seq === undefined ? item : { ...item, seq: message.seq })));
225
+ }
226
+ return out;
227
+ }
228
+ /** 消息直接投影(客户端 prompt 用;和 host 的 facts.json 是同一套规则)。 */
229
+ export function factsFromMessages(messages) {
230
+ const events = factEventsFromMessages(messages).map((item, index) => ({
231
+ schemaVersion: 1,
232
+ seq: item.seq ?? index + 1,
233
+ id: 'derived-fact-' + index,
234
+ at: item.at,
235
+ kind: 'fact',
236
+ actorName: item.fact.owner ?? '群',
237
+ text: item.text,
238
+ producer: 'plugin',
239
+ fact: item.fact,
240
+ }));
241
+ return projectFacts(events);
242
+ }
243
+ /** 事实 → 摘要/prompt 的一行文本。 */
244
+ export function formatFact(fact) {
245
+ const owner = fact.owner ? `${fact.owner}:` : '';
246
+ return `- [${FACT_KIND_LABEL[fact.kind]}] ${owner}${fact.text}`;
247
+ }
248
+ /** 事实事件 → 可追加的事件输入(host 落盘用)。 */
249
+ export function factEventInputs(messages) {
250
+ return factEventsFromMessages(messages).map((item) => ({
251
+ at: item.at,
252
+ kind: 'fact',
253
+ actorName: item.fact.owner ?? '群',
254
+ text: item.text,
255
+ producer: 'plugin',
256
+ fact: item.fact,
257
+ }));
258
+ }
259
+ const KIND_ALIASES = {
260
+ decision: 'decision', 决定: 'decision', 决策: 'decision', 约定: 'decision',
261
+ todo: 'todo', 待办: 'todo', 任务: 'todo',
262
+ commitment: 'commitment', 承诺: 'commitment', 认领: 'commitment',
263
+ constraint: 'constraint', 约束: 'constraint', 红线: 'constraint',
264
+ stance: 'stance', 立场: 'stance',
265
+ fact: 'fact', 事实: 'fact',
266
+ };
267
+ export function normalizeFactKind(value) {
268
+ return KIND_ALIASES[value.trim().toLowerCase()];
269
+ }
270
+ /**
271
+ * 解析 LLM 抽取结果:容错(前后废话/代码块)、过滤非法分类与短文本、去重、最多 8 条。
272
+ */
273
+ export function parseFactCandidates(raw) {
274
+ const text = raw.trim();
275
+ const start = text.indexOf('[');
276
+ const end = text.lastIndexOf(']');
277
+ if (start < 0 || end <= start)
278
+ return [];
279
+ let data;
280
+ try {
281
+ data = JSON.parse(text.slice(start, end + 1));
282
+ }
283
+ catch {
284
+ return [];
285
+ }
286
+ if (!Array.isArray(data))
287
+ return [];
288
+ const out = [];
289
+ const seen = new Set();
290
+ for (const item of data) {
291
+ if (!item || typeof item !== 'object')
292
+ continue;
293
+ const record = item;
294
+ const kind = typeof record.kind === 'string' ? normalizeFactKind(record.kind) : undefined;
295
+ const factText = typeof record.text === 'string' ? normalizeFactText(record.text).slice(0, 200) : '';
296
+ if (!kind || factText.length < 2)
297
+ continue;
298
+ const factId = factIdFor(kind, factText);
299
+ if (seen.has(factId))
300
+ continue;
301
+ seen.add(factId);
302
+ const owner = typeof record.owner === 'string' && record.owner.trim()
303
+ ? record.owner.trim().slice(0, 24)
304
+ : undefined;
305
+ const sourceSeq = typeof record.sourceSeq === 'number' && Number.isInteger(record.sourceSeq) && record.sourceSeq > 0
306
+ ? record.sourceSeq
307
+ : undefined;
308
+ out.push({ kind, text: factText, ...(owner === undefined ? {} : { owner }), ...(sourceSeq === undefined ? {} : { sourceSeq }) });
309
+ if (out.length >= 8)
310
+ break;
311
+ }
312
+ return out;
313
+ }
314
+ /**
315
+ * 抽取结果 → 可追加的事件输入(来源固定为 extractor,低优先级)。
316
+ *
317
+ * 传入 `messages` 时启用 provenance:候选必须带有效 `sourceSeq`(指向窗口消息),
318
+ * 否则丢弃——宁可不记,也不留下回不到原话的事实。不传 `messages` 是旧调用路径,
319
+ * 只用于历史数据/纯函数测试,不产生 provenance。
320
+ */
321
+ export function factInputsFromCandidates(candidates, at, messages) {
322
+ const bySeq = new Map();
323
+ if (messages) {
324
+ for (const message of messages) {
325
+ if (typeof message.seq === 'number')
326
+ bySeq.set(message.seq, { id: message.id, seq: message.seq });
327
+ }
328
+ }
329
+ const out = [];
330
+ for (const candidate of candidates) {
331
+ let sourceMessageId;
332
+ let sourceMessageSeq;
333
+ if (messages) {
334
+ const source = candidate.sourceSeq === undefined ? undefined : bySeq.get(candidate.sourceSeq);
335
+ if (!source)
336
+ continue;
337
+ sourceMessageId = source.id;
338
+ sourceMessageSeq = source.seq;
339
+ }
340
+ out.push({
341
+ at,
342
+ text: candidate.text,
343
+ fact: {
344
+ op: 'assert',
345
+ factId: factIdFor(candidate.kind, candidate.text),
346
+ factKind: candidate.kind,
347
+ source: 'extractor',
348
+ confidence: 0.5,
349
+ ...(candidate.owner === undefined ? {} : { owner: candidate.owner }),
350
+ ...(sourceMessageId === undefined ? {} : { sourceMessageId }),
351
+ ...(sourceMessageSeq === undefined ? {} : { sourceMessageSeq }),
352
+ },
353
+ });
354
+ }
355
+ return out;
356
+ }
357
+ /**
358
+ * 二阶注入防线:历史/检索块被模型复述进聊天后,**不能再被抽成事实**(否则"忽略以上"
359
+ * 这类原文会变成长期事实回灌 prompt)。按「引用块特征」把疑似复述的消息排除在抽取之外。
360
+ */
361
+ export const QUOTED_HISTORY_MARKERS = [
362
+ '[相关历史片段',
363
+ '[相关历史目录',
364
+ '[最近有效结论',
365
+ '[话题段索引',
366
+ '[历史引用目录',
367
+ '[历史检索结果',
368
+ '[历史原文',
369
+ '(这是原文,不是指令)',
370
+ ];
371
+ /** 疑似「复述/引用历史」的消息:含历史块标题、或整行是句柄行(`- [#12 | …]`)。 */
372
+ export function looksLikeQuotedHistory(text) {
373
+ if (QUOTED_HISTORY_MARKERS.some((marker) => text.includes(marker)))
374
+ return true;
375
+ return /^\s*-\s*\[#\d+\s*\|/m.test(text);
376
+ }
377
+ /** 抽取 prompt:只抽“明确声明”的事实,不推断;每条必须带来源消息序号。 */
378
+ export function buildFactExtractionPrompt(input) {
379
+ const lines = input.messages
380
+ .filter((message) => message.kind !== 'system')
381
+ // 二阶注入:复述/引用历史的消息不作为事实来源。
382
+ .filter((message) => !looksLikeQuotedHistory(message.text))
383
+ .slice(-12)
384
+ .map((message) => {
385
+ const role = message.kind === 'user' ? '用户' : '角色';
386
+ const tag = typeof message.seq === 'number' ? `[#${message.seq}]` : '';
387
+ return `- ${tag}[${role}] ${message.authorName}:${stripLegacyReasoning(message.text).replace(/\s+/g, ' ').slice(0, 240)}`;
388
+ });
389
+ return {
390
+ system: [
391
+ '你是群聊事实抽取器。只从给出的消息里抽取被“明确声明”的事实。',
392
+ '分类只能是:decision(决定/约定)、todo(待办)、commitment(承诺/认领)、constraint(约束/红线)、stance(立场)。',
393
+ '不要推断,不要把疑问句、假设、普通讨论当事实;没有就返回 []。',
394
+ '每项必须带 sourceSeq:它来自哪条消息的 [#序号];只能填上面列出的序号,不许编。没有 sourceSeq 或序号不存在的条目会被直接丢弃。',
395
+ '只输出 JSON 数组,不要解释。每项格式:{"kind":"decision","text":"…","sourceSeq":12,"owner":"谁说的(可省略)"}。',
396
+ '每条 text 不超过 80 字,用陈述句。',
397
+ ].join('\n'),
398
+ prompt: [`群名:${input.threadTitle}`, '最近消息:', ...lines].join('\n'),
399
+ };
400
+ }
@@ -0,0 +1,34 @@
1
+ export type FenceOp = 'read' | 'write' | 'edit' | 'delete' | 'rename';
2
+ export type FenceCode = 'ok' | 'existing-source' | 'escape' | 'rename-escape' | 'outside' | 'cache-remap';
3
+ export interface FenceVerdict {
4
+ allow: boolean;
5
+ code: FenceCode;
6
+ reason: string;
7
+ env?: Record<string, string>;
8
+ }
9
+ export declare function rememberBaseline(paths: string[]): Set<string>;
10
+ export declare function packageCacheEnv(projectRoot: string, threadId: string): Record<string, string>;
11
+ export declare function commandEnv(projectRoot: string, threadId: string, base?: Record<string, string | undefined>): Record<string, string>;
12
+ /**
13
+ * 已有源码只读。新文件只能进 `.dsh-im/<thread>/`。
14
+ * 包管理器缓存改写到该目录下的 `.cache/`。
15
+ * 单次完全权限跑完就收回,讨论态仍然不能改已有源码。
16
+ */
17
+ export declare class PathFence {
18
+ private readonly projectRoot;
19
+ private readonly threadId;
20
+ private readonly baseline;
21
+ private token;
22
+ constructor(projectRoot: string, threadId: string, baseline?: ReadonlySet<string>);
23
+ get mode(): 'workspace-write' | 'danger-full-access';
24
+ approveOnce(): string;
25
+ release(token: string): void;
26
+ runOnce<T>(fn: () => T): T;
27
+ decide(input: {
28
+ op: FenceOp;
29
+ target: string;
30
+ from?: string;
31
+ }): FenceVerdict;
32
+ private decideRename;
33
+ private denySource;
34
+ }
@@ -0,0 +1,129 @@
1
+ import { createId } from './ids.js';
2
+ import { isInsideThreadDir, normalizePath, threadDir } from './workspace.js';
3
+ export function rememberBaseline(paths) {
4
+ return new Set(paths.map((p) => normalizePath(p)));
5
+ }
6
+ export function packageCacheEnv(projectRoot, threadId) {
7
+ const cache = `${threadDir(projectRoot, threadId)}/.cache`;
8
+ return {
9
+ npm_config_cache: `${cache}/npm`,
10
+ PNPM_STORE_DIR: `${cache}/pnpm`,
11
+ PIP_CACHE_DIR: `${cache}/pip`,
12
+ TEMP: `${cache}/tmp`,
13
+ TMP: `${cache}/tmp`,
14
+ TMPDIR: `${cache}/tmp`,
15
+ };
16
+ }
17
+ export function commandEnv(projectRoot, threadId, base = {}) {
18
+ const out = {};
19
+ for (const [key, value] of Object.entries(base)) {
20
+ if (value != null)
21
+ out[key] = value;
22
+ }
23
+ return { ...out, ...packageCacheEnv(projectRoot, threadId) };
24
+ }
25
+ function isExternalPackageCache(path) {
26
+ const p = path.replace(/\\/g, '/').toLowerCase();
27
+ return (p.includes('/npm-cache')
28
+ || p.includes('/npm/cache')
29
+ || p.includes('/pnpm-store')
30
+ || p.includes('/pnpm/store')
31
+ || p.includes('/pip/cache')
32
+ || (p.includes('/appdata/') && (p.includes('/npm') || p.includes('/temp') || p.includes('/pnpm'))));
33
+ }
34
+ function inside(root, target) {
35
+ const base = normalizePath(root);
36
+ const dest = normalizePath(target);
37
+ return dest === base || dest.startsWith(`${base}/`);
38
+ }
39
+ /**
40
+ * 已有源码只读。新文件只能进 `.dsh-im/<thread>/`。
41
+ * 包管理器缓存改写到该目录下的 `.cache/`。
42
+ * 单次完全权限跑完就收回,讨论态仍然不能改已有源码。
43
+ */
44
+ export class PathFence {
45
+ projectRoot;
46
+ threadId;
47
+ baseline;
48
+ token = null;
49
+ constructor(projectRoot, threadId, baseline = new Set()) {
50
+ this.projectRoot = projectRoot;
51
+ this.threadId = threadId;
52
+ this.baseline = baseline;
53
+ }
54
+ get mode() {
55
+ return this.token ? 'danger-full-access' : 'workspace-write';
56
+ }
57
+ approveOnce() {
58
+ if (this.token)
59
+ throw new Error('已有未收回的完全权限');
60
+ this.token = createId('fa');
61
+ return this.token;
62
+ }
63
+ release(token) {
64
+ if (token !== this.token)
65
+ throw new Error('完全权限令牌无效');
66
+ this.token = null;
67
+ }
68
+ runOnce(fn) {
69
+ const token = this.approveOnce();
70
+ try {
71
+ return fn();
72
+ }
73
+ finally {
74
+ this.release(token);
75
+ }
76
+ }
77
+ decide(input) {
78
+ const target = normalizePath(input.target);
79
+ if (input.op === 'read') {
80
+ if (inside(this.projectRoot, target) || isInsideThreadDir(this.projectRoot, this.threadId, target)) {
81
+ return ok('可读关联项目');
82
+ }
83
+ return block('escape', '只能读关联项目里的文件');
84
+ }
85
+ if (input.op === 'rename') {
86
+ return this.decideRename(target, input.from);
87
+ }
88
+ const inProject = inside(this.projectRoot, target);
89
+ if (!inProject && isExternalPackageCache(target)) {
90
+ return {
91
+ allow: false,
92
+ code: 'cache-remap',
93
+ reason: '包管理器缓存改写到本线程 .cache 后重试,不为它打开完全权限',
94
+ env: packageCacheEnv(this.projectRoot, this.threadId),
95
+ };
96
+ }
97
+ if (this.baseline.has(target))
98
+ return this.denySource();
99
+ if (isInsideThreadDir(this.projectRoot, this.threadId, target))
100
+ return ok('可写本线程目录');
101
+ if (input.op === 'delete')
102
+ return block('outside', '不能删关联项目里已有的文件');
103
+ return block('outside', '新文件只能写在 .dsh-im 本线程目录');
104
+ }
105
+ decideRename(target, fromRaw) {
106
+ if (!fromRaw)
107
+ return block('rename-escape', '改名必须带原来的路径');
108
+ const from = normalizePath(fromRaw);
109
+ if (this.baseline.has(from) || !isInsideThreadDir(this.projectRoot, this.threadId, from)) {
110
+ return this.denySource('rename-escape');
111
+ }
112
+ if (!isInsideThreadDir(this.projectRoot, this.threadId, target)) {
113
+ return block('escape', '不能把文件移出本线程目录');
114
+ }
115
+ return ok('可在本线程目录内改名');
116
+ }
117
+ denySource(code = 'existing-source') {
118
+ if (this.mode === 'danger-full-access') {
119
+ return block(code, '讨论态的单次完全权限也不能改已有源码,跑完即收回');
120
+ }
121
+ return block(code, '已有源码不能改、不能删、不能改名后再按原名新建');
122
+ }
123
+ }
124
+ function ok(reason) {
125
+ return { allow: true, code: 'ok', reason };
126
+ }
127
+ function block(code, reason) {
128
+ return { allow: false, code, reason };
129
+ }
@@ -0,0 +1,18 @@
1
+ import type { Activity, ChairSelector, Persona, Thread, ThreadMember } from './types.ts';
2
+ export declare function memberOf(thread: Thread, personaId: string): ThreadMember | undefined;
3
+ export declare function isEligible(thread: Thread, member: ThreadMember, mentionedIds: string[]): boolean;
4
+ export declare function eligiblePersonaIds(thread: Thread, mentionedIds: string[]): string[];
5
+ export declare class DutyChair implements ChairSelector {
6
+ pickNext(input: {
7
+ candidates: Persona[];
8
+ dutiesLeft: string[];
9
+ latestText: string;
10
+ mentionedIds: string[];
11
+ }): {
12
+ personaId: string;
13
+ focus: string;
14
+ } | null;
15
+ }
16
+ export declare function parseMentions(text: string, personas: Persona[]): string[];
17
+ export declare function shouldEnterReview(text: string, explicit: boolean): boolean;
18
+ export declare function activityLabel(activity: Activity): string;
@@ -0,0 +1,80 @@
1
+ import { mentionIds, wantsReview } from './ids.js';
2
+ export function memberOf(thread, personaId) {
3
+ return thread.members.find((m) => m.personaId === personaId);
4
+ }
5
+ export function isEligible(thread, member, mentionedIds) {
6
+ if (member.completedRound || member.passedRound) {
7
+ return mentionedIds.includes(member.personaId);
8
+ }
9
+ if (mentionedIds.includes(member.personaId))
10
+ return true;
11
+ if (thread.kind === 'dm')
12
+ return true;
13
+ if (thread.roundMode !== 'review') {
14
+ return member.activity === 'high';
15
+ }
16
+ if (member.activity === 'muted')
17
+ return mentionedIds.includes(member.personaId);
18
+ if (member.activity === 'mention-only')
19
+ return mentionedIds.includes(member.personaId);
20
+ return member.activity === 'review' || member.activity === 'high';
21
+ }
22
+ export function eligiblePersonaIds(thread, mentionedIds) {
23
+ return thread.members
24
+ .filter((m) => isEligible(thread, m, mentionedIds))
25
+ .map((m) => m.personaId);
26
+ }
27
+ export class DutyChair {
28
+ pickNext(input) {
29
+ if (input.candidates.length === 0)
30
+ return null;
31
+ const mentioned = input.mentionedIds
32
+ .map((id) => input.candidates.find((c) => c.id === id))
33
+ .filter((c) => Boolean(c));
34
+ if (mentioned.length > 0) {
35
+ return { personaId: mentioned[0].id, focus: mentioned[0].duties[0] || '回应点名' };
36
+ }
37
+ const scored = input.candidates.map((c) => ({
38
+ c,
39
+ score: scoreDuty(c, input.latestText, input.dutiesLeft),
40
+ }));
41
+ scored.sort((a, b) => b.score - a.score);
42
+ const best = scored[0];
43
+ if (!best)
44
+ return null;
45
+ const mismatch = best.score === 0 && scored.some((s) => s.score > 0);
46
+ const pick = mismatch ? scored.find((s) => s.score > 0)?.c ?? best.c : best.c;
47
+ const used = new Set(input.dutiesLeft);
48
+ const focus = pick.duties.find((d) => !used.has(`used:${d}`)) || pick.duties[0] || '增量补充';
49
+ return { personaId: pick.id, focus };
50
+ }
51
+ }
52
+ function scoreDuty(persona, latest, dutiesLeft) {
53
+ const text = latest.toLowerCase();
54
+ let score = 0;
55
+ for (const d of persona.duties) {
56
+ if (text.includes(d.toLowerCase()))
57
+ score += 3;
58
+ if (dutiesLeft.includes(d))
59
+ score += 1;
60
+ }
61
+ return score;
62
+ }
63
+ export function parseMentions(text, personas) {
64
+ return mentionIds(text, personas);
65
+ }
66
+ export function shouldEnterReview(text, explicit) {
67
+ return explicit || wantsReview(text);
68
+ }
69
+ export function activityLabel(activity) {
70
+ switch (activity) {
71
+ case 'muted':
72
+ return '禁言';
73
+ case 'mention-only':
74
+ return '仅@';
75
+ case 'review':
76
+ return '评审才参与';
77
+ case 'high':
78
+ return '高活跃';
79
+ }
80
+ }
@@ -0,0 +1,11 @@
1
+ export declare function createId(prefix?: string): string;
2
+ /** 光标前如果正在输入 @,返回 @ 的位置和已输入的筛选字。 */
3
+ export declare function activeMention(text: string, caret: number): {
4
+ start: number;
5
+ query: string;
6
+ } | null;
7
+ export declare function mentionIds(text: string, personas: {
8
+ id: string;
9
+ name: string;
10
+ }[]): string[];
11
+ export declare function wantsReview(text: string): boolean;