@dabuliu_wsy/dsh-im 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,10 @@
3
3
  > DSH(DeepSeek Harness)插件:把多个角色拉进同一个群或私聊,让它们各自带着人设、岗位和工具协作。
4
4
  > 模型与调用全部走宿主 `ctx.llm`(或原生 session),插件不直连任何网关、不保存任何密钥。
5
5
 
6
- `版本 0.2.0` · `Node ≥ 20` · `MIT` · **可用版本(0.x:接口与数据格式可能小幅调整)**
6
+ `版本 0.3.1` · `Node ≥ 20` · `MIT` · **可用版本(0.x:接口与数据格式可能小幅调整)**
7
+
8
+ **兼容的 DSH 版本**:`0.2.0-rc.2` 与 `0.2.2-rc.3` 双版本实机验证——两版各用官方 CLI 起独立 web profile 挂载本插件,`/api/im/*` 宿主路由均返回 200,`client-modules` 均成功组装本插件客户端模块。
9
+ 两个版本的 Web 就绪服务不同——rc.2 提供 `webRuntime`,rc.3 已移除并改用 `webStartup`,插件用「`webStartup` → `webRuntime` → 仅 `webServer`」三级降级适配,不绑定任一版本私有服务。
7
10
 
8
11
  > 名称说明:仓库与品牌名为 **dsh-roundtable**;npm 包名是带 scope 的 `@dabuliu_wsy/dsh-im`,**插件 id 与数据目录仍是 `dsh-im`**(`.dsh-im/`、`DSH_IM_*` 环境变量),以兼容现有数据和已装配置。
9
12
 
@@ -36,10 +39,13 @@
36
39
  ## 功能
37
40
 
38
41
  - **群聊与私聊**:建群 / 邀请 / 关联工作区;DM;`@` 点名;模型回复里自带的"某某:"前缀会兜底剥离;附件(图片 ≤8MB、文件 ≤20MB,可粘贴/拖拽)。
42
+ - **邀请成员**:群里可以把通讯录里**还没入群**的角色拉进来(成员区「+ 邀请成员」或顶栏「…」→「邀请成员」);已在群里的自动跳过、入群留系统记录;DM/三人小窗不支持加人(固定两人语义)。
39
43
  - **发言权仲裁**:点名独占 > 回复对象 > 职责命中 > 活跃度补位;`wait` 只停本轮、不插话;默认串行地板(并发发言关闭)。
40
44
  - **上下文与记忆**:分层摘要(L1 旧消息压缩 + L2 不可压缩事实)、窗口预算按模型 `contextWindow` 分配(群级按最小成员窗口统一压)、角色状态快照(承诺 / 待办 / 决定 / 立场)、按需检索(默认 shadow:算但不进 prompt)。
41
45
  - **可寻址记忆层**:消息索引投影(派生字段,不复制正文)+ claim 弱状态(active / superseded / raw)+ 可见性谓词表;模型侧有 `memory_search` / `memory_expand` 两个记忆工具(只返回句柄,正文按需展开,两者同权);默认 shadow,需显式开启才注入 prompt。
42
46
  - **事实与共识**:规则 + LLM 双路抽取事实、哈希幂等、supersede / retract、任务板归档不复活;共识层自动生成并带生命周期状态,prompt 只注入仍然有效的条目。
47
+ - **删除与回收站(软删除)**:群可解散、会话可删除、角色可删除、聊天记录可清空;删除的东西**不物理销毁**,而是移进 `<数据根>/.dsh-im/trash/`,面板左栏「回收站」可恢复或彻底删除。删角色会连带删除它的私聊/三人小窗、并记下群成员位置(恢复时放回原位);清空聊天记录保留会话外壳。删除或清空后会释放对应原生会话,被删历史不再留在宿主 agent 内存里。
48
+ - **群文件与产物**:群右栏「文件」Tab(DM 用顶栏「…」→「会话文件」)只读浏览群工作区——角色写的文件、`本轮汇总.md`、附件;可进子目录,文本/图片内联预览,其他文件「打开原文件」。内部账本(events/facts/receipts 等)和隐藏目录不展示。角色头像(标题栏与消息流)可点开/切换右侧角色资料,关掉后点标题头像随时重开。
43
49
  - **工具与能力**:内置五能力 `read` / `search` / `write` / `check` / `memory`(**没有 shell**);宿主第三方工具(浏览器、MCP 等)按「来源组 + 单工具」显式授权,默认不授予、未授权一律硬拒绝;`run_check` 只跑本仓 vitest / tsc,参数白名单、不经 shell、60s 超时、并发与排队有上限。
44
50
  - **原生 session(默认开)**:每个「角色 × 群」一个 DSH 原生会话,角色因此能真实调工具、保留自己的会话记忆;授权或工具可见性变化时重建会话;空闲 30 分钟释放。宿主缺 `ctx.agents` / `tools.register` / `tools.guard` 任一能力时**整体回退** `ctx.llm`,不会半残运行。
45
51
  - **可观测**:执行轨迹(工具步骤与结果摘要)、两阶段回执(intent / outcome + 规范化双 hash + `basedOnSeq`)、`metrics.jsonl` 指标、失败 turn 可导出的复现包、黄金回放测试。
@@ -48,7 +54,9 @@
48
54
 
49
55
  ## 安装
50
56
 
51
- ### 方式一:从源码接入(最稳,推荐)
57
+ > 普通用户直接用 **方式四(npm,一条命令)**;想改代码/排查问题用 **方式一(源码)**。
58
+
59
+ ### 方式一:从源码接入(最稳;开发与排查用)
52
60
 
53
61
  ```sh
54
62
  git clone https://github.com/wangshouyong/dsh-roundtable.git
@@ -95,17 +103,15 @@ allowBuilds:
95
103
 
96
104
  这条 key 里的 commit 哈希要跟报错里的一致(换版本会变)。如果你不想碰 pnpm 配置,用方式一或方式二。
97
105
 
98
- ### 方式四:从 npm 安装
106
+ ### 方式四:从 npm 安装(最省事,普通用户推荐)
99
107
 
100
108
  ```sh
101
109
  dsh plugin --profile desktop add @dabuliu_wsy/dsh-im
102
110
  ```
103
111
 
104
112
  npm 包名是 `@dabuliu_wsy/dsh-im`(scope 必填),插件 id 与数据目录仍是 `dsh-im`。
105
- 发布前会跑 `npm run gate` + `npm run verify:pack`(产物齐全、无开发材料、manifest 与版本一致)。
106
-
107
- > 状态:**尚未发布到 npm**。包体已就绪(`npm pack` 校验通过),发布流程(2FA / token)还在走,
108
- > 发布后本节即刻可用。在此之前请用方式一 / 方式二 / 方式三。
113
+ 版本 **0.3.0** 已发布([npm 页面](https://www.npmjs.com/package/@dabuliu_wsy/dsh-im));
114
+ 每次发布前会跑 `npm run gate` + `npm run verify:pack`(产物齐全、无开发材料、manifest 与版本一致)。
109
115
 
110
116
  ## 配置
111
117
 
@@ -171,12 +177,16 @@ scripts/ 构建与校验脚本
171
177
 
172
178
  ## 项目状态与已知限制(如实)
173
179
 
174
- - **当前版本 `v0.2.0`**(tag + [Release 附件](https://github.com/wangshouyong/dsh-roundtable/releases)):核心功能完成,`npm run gate`(typecheck → 单测 → build → 打包内容校验)与 GitHub Actions 全绿。
180
+ - **当前版本 `v0.3.0`**(tag + [Release 附件](https://github.com/wangshouyong/dsh-roundtable/releases)):核心功能完成,`npm run gate`(typecheck → 单测 → build → 打包内容校验)与 GitHub Actions 全绿。
175
181
  - **0.x 语义**:接口、数据格式与 UI 仍可能小幅调整;破坏性变更会写进 Release 说明,不静默改契约。
176
182
  - **原生 session 是默认路径,但仍是需要门禁守着的链路**:依赖宿主提供 `ctx.agents` + `tools.register` / `tools.guard`;缺能力时整体回退 `ctx.llm`。它不是"稳定 API",宿主升级后可能要跟着改。
177
183
  - **实验特性默认 shadow**:按需检索、记忆层句柄注入、token 校准都先只观测(写进回执/样本),要显式开开关才改变行为。
178
184
  - **记忆层仍在推进**:索引、claim、可见性、句柄协议、search/expand 工具已落地,但注入默认关闭。
179
185
  - **并发发言默认关闭**(串行地板)。
186
+ - **回收站是软的、不自动清理**:删除/清空的会话、角色、聊天记录会留在 `<数据根>/.dsh-im/trash/`,只有用户点「彻底删除 / 清空回收站」才物理删除(不静默删数据)。「清空聊天记录」的条目只能在会话仍为空时恢复。
187
+ - **群文件面板只读、不实时监听**:不能改/删群文件(由角色写、由会话删除/清空清理);不显示隐藏目录与内部账本;列表 500 条 / 文本预览 20 万字符上限;文件变化要点刷新按钮。
188
+ - **host 路由改动需要重启 DSH**:`/api/im/trash*`、`/api/im/native-forget`、`/api/im/group-files*` 是新增路由,升级后需重启一次 DSH;只刷新面板会收到「请重启 DSH」的明确提示。
189
+ - **群成员只能加、不能移出**:邀请入群已支持(仅群;DM/三人小窗不支持),但没有「移出群成员」入口;新成员不补历史消息,只能看到当前的窗口/摘要上下文。
180
190
  - 目前只在 **Windows 上的 DSH Desktop** 实测通过,其它平台未验证。
181
191
  - **没有遥测 / 崩溃上报**:排查依赖本机 `metrics.jsonl`、`receipts.jsonl` 和宿主日志。
182
192
  - 单测全绿 ≠ 所有模型、所有平台都验证过;活体测试默认跳过,需要单独跑。
package/dist/core/im.d.ts CHANGED
@@ -3,6 +3,7 @@ import { type ProactiveLimits } from './proactive.ts';
3
3
  import { type GroupBudgetPolicy } from './context-budget.ts';
4
4
  import type { Activity, ChairSelector, Fact, ImState, MemoryEntry, MessageAttachment, Persona, RetrievalMode, Speaker, StalePolicy, Thread } from './types.ts';
5
5
  import { type FileSink } from './workspace.ts';
6
+ import { type ClearHistoryPlan, type DeletePersonaPlan, type DeleteThreadPlan, type RestorePersonaResult, type TrashPayload } from './trash.ts';
6
7
  export declare class ImService {
7
8
  private readonly speaker;
8
9
  private readonly chair;
@@ -108,6 +109,51 @@ export declare class ImService {
108
109
  */
109
110
  setThreadTitle(threadId: string, title: string): Thread;
110
111
  setActivity(threadId: string, personaId: string, activity: Activity): void;
112
+ /**
113
+ * 邀请角色进群(只有群支持;私聊/三人小窗请新建会话)。
114
+ * - 先校验全部 personaId 再落状态,不会"加了一半";
115
+ * - 已在群里的角色跳过并如实回报;
116
+ * - 入群写一条系统记录;活跃度沿用角色默认值,本轮未发言(下一轮完整参与)。
117
+ */
118
+ addMembers(threadId: string, personaIds: readonly string[]): {
119
+ thread: Thread;
120
+ added: Persona[];
121
+ skipped: string[];
122
+ };
123
+ /** 删除会话 / 解散群:会话从 state 移除,返回回收站快照。 */
124
+ deleteThread(threadId: string): DeleteThreadPlan;
125
+ /**
126
+ * 清空聊天记录:会话外壳(标题/成员/关联工作区/自定义小窗名)保留,
127
+ * 消息、事实、共识、摘要、执行轨迹、附件、线程记忆全部清掉;旧数据由 host 移入回收站。
128
+ */
129
+ clearThreadHistory(threadId: string): ClearHistoryPlan;
130
+ /**
131
+ * 删除角色(彻底连带口径):
132
+ * - 角色从通讯录移除;
133
+ * - 它的私聊(dm)与三人小窗(triad)整个会话一起进回收站;
134
+ * - 群里只移除成员:群历史保留,写一条系统记录说明谁被移出;
135
+ * - 线程记忆 / 唤醒摘要 / pendingRecall / 运行时状态 / 主动私聊节流一起清理。
136
+ */
137
+ deletePersona(personaId: string): DeletePersonaPlan;
138
+ /**
139
+ * 恢复会话(回收站 → 列表)。
140
+ * - 同 id 会话已在列表:拒绝(说明已经恢复过);
141
+ * - DM / 三人小窗里的角色已被删掉:拒绝并提示先恢复角色(否则恢复出一个没有成员的空壳);
142
+ * - 群里有成员已不存在:保留会话、移除失效成员并写系统记录(不静默丢成员关系)。
143
+ */
144
+ restoreThread(snapshot: Thread): Thread;
145
+ /**
146
+ * 恢复「清空聊天记录」:把快照里的消息/事实/共识/摘要/轨迹写回**同一个会话**。
147
+ * 只有当前会话一条消息都没有时才允许(否则恢复会盖掉清空后新聊的内容)。
148
+ */
149
+ restoreThreadHistory(snapshot: Thread, extras?: Pick<TrashPayload, 'memories' | 'wakeExcerpts'>): Thread;
150
+ /**
151
+ * 恢复角色:角色 + 被连带删除的会话 + 群成员位置 + 记忆/唤醒摘要一起还原。
152
+ * 如果某个会话/群在角色删除后又被删掉,跳过并如实回报(不假装全部恢复)。
153
+ */
154
+ restorePersona(payload: Pick<TrashPayload, 'persona' | 'threads' | 'memberships' | 'memories' | 'wakeExcerpts'>): RestorePersonaResult;
155
+ /** 删掉一个会话后,把只属于它的引用(线程记忆 / 唤醒摘要 / 跨场召回)清干净。 */
156
+ private dropThreadReferences;
111
157
  /** 客户端 UI:自动打开私聊时切到那个小窗。 */
112
158
  onDmOpened?: (threadId: string) => void;
113
159
  sendUser(threadId: string, text: string, opts?: {
package/dist/core/im.js CHANGED
@@ -16,6 +16,7 @@ import { appendMetric } from './metrics.js';
16
16
  import { buildRoleState } from './role-state.js';
17
17
  import { factsFromMessages, projectFactsFromList, } from './facts.js';
18
18
  import { memorySink, summaryRelPath } from './workspace.js';
19
+ import { canRestoreHistory, cloneJson, sanitizeThreadSnapshot, trashHistoryDetail, trashPersonaDetail, trashThreadDetail, } from './trash.js';
19
20
  const HOUR = 60 * 60 * 1000;
20
21
  export class ImService {
21
22
  speaker;
@@ -586,6 +587,338 @@ export class ImService {
586
587
  if (m)
587
588
  m.activity = activity;
588
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
+ }
589
922
  /** 客户端 UI:自动打开私聊时切到那个小窗。 */
590
923
  onDmOpened;
591
924
  async sendUser(threadId, text, opts) {
@@ -29,5 +29,6 @@ export * from './arbiter.ts';
29
29
  export * from './arbiter-bridge.ts';
30
30
  export * from './runtime.ts';
31
31
  export * from './im.ts';
32
+ export * from './trash.ts';
32
33
  export * from './consensus.ts';
33
34
  export * from './curator.ts';
@@ -29,5 +29,6 @@ export * from './arbiter.js';
29
29
  export * from './arbiter-bridge.js';
30
30
  export * from './runtime.js';
31
31
  export * from './im.js';
32
+ export * from './trash.js';
32
33
  export * from './consensus.js';
33
34
  export * from './curator.js';
@@ -0,0 +1,110 @@
1
+ /**
2
+ * 软删除(回收站)契约:纯类型 + 纯函数。
3
+ *
4
+ * **这里不能 import node:fs**(`src/core` 会被打进客户端 bundle)。
5
+ * 物理目录搬运在 `src/host/trash-store.ts`;状态变更在 `src/core/im.ts`。
6
+ *
7
+ * 删除口径(已和用户确认):
8
+ * - 「删除会话 / 解散群」:会话从 state 移除,数据目录移到 `<根>/.dsh-im/trash/<id>/data/<threadId>/`;
9
+ * - 「清空聊天记录」:会话保留,消息/任务板/共识/轨迹/附件移到回收站,之后还能恢复;
10
+ * - 「删除角色」:角色从通讯录移除;它的私聊/三人小窗会话一起删除;群内只移除成员、群历史保留。
11
+ *
12
+ * 快照(payload)随 trash manifest 落盘,恢复时不需要再读 state.json ——
13
+ * 删除那一刻的数据就是恢复后的数据,不靠"重建猜测"。
14
+ */
15
+ import type { Activity, MemoryEntry, Persona, Thread, ThreadKind } from './types.ts';
16
+ export declare const TRASH_KINDS: readonly ['thread', 'persona', 'history'];
17
+ export type TrashKind = (typeof TRASH_KINDS)[number];
18
+ export declare const TRASH_KIND_LABEL: Record<TrashKind, string>;
19
+ /** 回收站清单项(跨 host/client 共用;host 落 manifest,客户端只读这份元数据)。 */
20
+ export interface TrashEntryMeta {
21
+ id: string;
22
+ kind: TrashKind;
23
+ /** 列表主标题:群名 / 角色名 / 会话名。 */
24
+ label: string;
25
+ /** 副标题:类型 + 规模(如「群 · 12 条消息 · 4 人」)。 */
26
+ detail: string;
27
+ deletedAt: number;
28
+ /** 已经移到回收站的数据目录(threadId);角色记录里是被连带删除的会话。 */
29
+ threadIds: string[];
30
+ /** 数据目录字节数(0 = 没有目录或统计失败)。 */
31
+ bytes: number;
32
+ restorable: boolean;
33
+ }
34
+ /** 删除角色时,该角色在某个群里的成员位置(恢复时放回原位、恢复活跃度)。 */
35
+ export interface TrashPersonaMembership {
36
+ threadId: string;
37
+ /** 删除时在 memberIds 里的下标。 */
38
+ index: number;
39
+ activity: Activity;
40
+ }
41
+ /** 恢复一条回收站记录所需的全部状态快照。 */
42
+ export interface TrashPayload {
43
+ /** kind=thread / history:被删 / 被清空前的会话快照(含消息)。 */
44
+ thread?: Thread;
45
+ /** kind=persona:被连带删除的私聊 / 三人小窗快照。 */
46
+ threads?: Thread[];
47
+ /** kind=persona:被删除的角色。 */
48
+ persona?: Persona;
49
+ /** kind=persona:该角色原本在哪些群、什么位置。 */
50
+ memberships?: TrashPersonaMembership[];
51
+ /** 被删除/清空会话时一并清理的线程级记忆(恢复时还原)。 */
52
+ memories?: MemoryEntry[];
53
+ /** 被删除/清空会话时一并清理的唤醒摘要(key = `personaId:threadId`)。 */
54
+ wakeExcerpts?: Record<string, string[]>;
55
+ }
56
+ /** ImService.deleteThread 的结果:删完的内存状态 + 交给 host 回收站的快照。 */
57
+ export interface DeleteThreadPlan {
58
+ threadId: string;
59
+ label: string;
60
+ detail: string;
61
+ snapshot: Thread;
62
+ }
63
+ /** ImService.clearThreadHistory 的结果。 */
64
+ export interface ClearHistoryPlan {
65
+ threadId: string;
66
+ label: string;
67
+ detail: string;
68
+ snapshot: Thread;
69
+ memories: MemoryEntry[];
70
+ wakeExcerpts: Record<string, string[]>;
71
+ }
72
+ /** ImService.deletePersona 的结果。 */
73
+ export interface DeletePersonaPlan {
74
+ persona: Persona;
75
+ label: string;
76
+ detail: string;
77
+ /** 被连带删除的私聊 / 三人小窗快照。 */
78
+ threads: Thread[];
79
+ memberships: TrashPersonaMembership[];
80
+ memories: MemoryEntry[];
81
+ wakeExcerpts: Record<string, string[]>;
82
+ }
83
+ /** ImService.restorePersona 的结果;部分会话/群可能已不存在,必须如实回报。 */
84
+ export interface RestorePersonaResult {
85
+ persona: Persona;
86
+ threads: Thread[];
87
+ skippedThreadIds: string[];
88
+ skippedMembershipThreadIds: string[];
89
+ }
90
+ /** 深拷贝:快照必须与内存对象脱钩,否则删除后拖动状态会污染回收站里的数据。 */
91
+ export declare function cloneJson<T>(value: T): T;
92
+ /**
93
+ * 生成可安全落盘的会话快照。
94
+ *
95
+ * 去掉的字段都是「运行时瞬时态」或「待落盘队列」:
96
+ * - speakingPersonaId / nextHint / blocked / floorDecisions:本轮状态,恢复后重新开始更合理;
97
+ * - pendingMetrics / pendingFactOps / extractedFacts / retractedFactIds:删除前已经落过盘,
98
+ * 留在快照里会在恢复后重复写事件/指标;
99
+ * - unread:恢复后应该是未读 0(用户主动恢复,不该再弹红点)。
100
+ */
101
+ export declare function sanitizeThreadSnapshot(thread: Thread): Thread;
102
+ export declare function threadKindLabel(kind: ThreadKind): string;
103
+ /** 回收站副标题:类型 + 消息数 + 群/小窗人数。 */
104
+ export declare function trashThreadDetail(thread: Thread): string;
105
+ /** 清空记录后的副标题:写明清掉多少条,方便用户在回收站里认出来。 */
106
+ export declare function trashHistoryDetail(snapshot: Thread): string;
107
+ /** 删除角色的副标题:几个会话 + 几个群受影响。 */
108
+ export declare function trashPersonaDetail(_persona: Persona, threads: readonly Thread[], memberships: readonly TrashPersonaMembership[]): string;
109
+ /** 清空记录只有在「会话清空后没有新消息」时才能恢复(否则恢复会覆盖新记录)。 */
110
+ export declare function canRestoreHistory(thread: Thread): boolean;