@wwwfz/dsh-agent-bridge 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,153 +2,87 @@
2
2
 
3
3
  # Agent Bridge
4
4
 
5
- **换个 Agent,接着做。**
5
+ ### 换个 Agent,接着做。
6
6
 
7
- 把本机其他 Agent 的旧对话、项目记忆和 Skills 带进 DeepSeek Harness,在原工作目录继续开发。
7
+ 把本机其他 Agent 的对话、项目记忆和 Skills 带进 DeepSeek Harness,在熟悉的工作目录继续。
8
8
 
9
- [下载 Desktop 安装包](https://github.com/wfz2006/dsh-agent-bridge/releases/latest/download/dsh-agent-bridge.tgz) · [快速开始](#快速开始) · [看上手演示](#使用) · [图文介绍](https://wfz2006.github.io/dsh-agent-bridge/)
9
+ [下载 Desktop 插件](https://github.com/wfz2006/dsh-agent-bridge/releases/latest/download/dsh-agent-bridge.tgz) · [安装](#安装) · [使用指南](#使用) · [图文介绍](https://wfz2006.github.io/dsh-agent-bridge/)
10
10
 
11
- <a href="https://raw.githubusercontent.com/wfz2006/dsh-agent-bridge/main/docs/screenshots/v0.9.0/workspace.png">
12
- <img src="https://raw.githubusercontent.com/wfz2006/dsh-agent-bridge/main/docs/screenshots/v0.9.0/workspace.png" width="900" alt="Agent Bridge 的项目首屏。左侧可筛选项目,右侧可选最近对话或用项目资料开新对话。">
13
- </a>
14
-
15
- <sub>示例项目「接口调试台」 · v0.9.0 实际界面 · 点击查看大图</sub>
11
+ <img src="docs/screenshots/v0.10.0/workspace.png" width="900" alt="Agent Bridge 项目工作台">
16
12
 
17
13
  </div>
18
14
 
19
- ## 快速开始
20
-
21
- ### DSH Desktop
22
-
23
- 1. 下载 [GitHub 安装包 v0.9.0](https://github.com/wfz2006/dsh-agent-bridge/releases/latest/download/dsh-agent-bridge.tgz)。
24
- 2. 在 DSH 的 **插件 → 安装插件** 选择下载的 `.tgz`。
25
- 3. 完全退出再打开 DSH,从侧栏进入 **Agent 工作接续**。
15
+ ## 这次更新
26
16
 
27
- ### DSH Web
17
+ v0.10.0 重新整理了项目工作台和来源记录。迁入后可以在 DSH 原生对话中按原顺序查看正文、思考和工具过程,也可以通过来源记录按回合查看附件和原始信息。
28
18
 
29
- 在已安装 DSH CLI 的环境里运行。当前 npm 版本为 [v0.9.0](https://www.npmjs.com/package/@wwwfz/dsh-agent-bridge)。
19
+ - **继续旧对话**。预览后迁入,工具调用和结果关联到原回合,历史工具不会重新执行。
20
+ - **查看来源记录**。按回合浏览消息、过程和附件,图片可预览,已保存的文件可下载。
21
+ - **带上项目资料**。选择记忆、交接文档与 Skills,预览草稿后打开新会话。
22
+ - **启用项目 Skills**。核对技能包和目标项目后启用,脚本与参考资料随快照保存。
23
+ - **导出 Markdown**。本机版支持核验后的本机文件链接,分享版使用可读路径。代码围栏和原始空行得到保留。
30
24
 
31
- ~~~sh
32
- dsh plugin --profile web add @wwwfz/dsh-agent-bridge
33
- dsh web
34
- ~~~
35
-
36
- > [!NOTE]
37
- > 下方演示的原对话统计、项目级原生 Skills 和新版 Markdown 预览来自 v0.9.0。
38
-
39
- Windows DSH Desktop 0.2.2-rc.3 和 DSH Web 已完成隔离验收。原生会话和 Skills 需要宿主提供对应服务。macOS 和 Linux 的数据路径规则有测试覆盖。 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)
40
-
41
- ## 使用
25
+ <img src="docs/screenshots/v0.10.0/source-history.png" width="850" alt="按回合浏览来源记录,显示图片缩略图、附件和可展开的工具过程">
42
26
 
43
- 从侧栏打开 **Agent 工作接续**,按 Agent、项目名或路径找到原项目。不同 Git worktree 会独立显示。
27
+ ## 安装
44
28
 
45
- ### 继续旧对话
29
+ ### DSH Desktop
46
30
 
47
- 1. 在项目首屏点开一条最近对话,或用 **查看全部对话** 搜索。
48
- 2. 核对用户和助手的消息,再点 **迁入并继续**。
49
- 3. DSH 会在原工作目录打开一条带历史的新会话,输入下一句就能接着聊。
31
+ 1. 从 [GitHub Release](https://github.com/wfz2006/dsh-agent-bridge/releases/latest/download/dsh-agent-bridge.tgz) 下载 `dsh-agent-bridge.tgz`。
32
+ 2. 在 DSH 中打开 **插件 → 安装插件**,选择下载的文件。
33
+ 3. 完全退出并重新打开 DSH,在侧栏选择 **Agent 工作接续**。
50
34
 
51
- #### 在哪里看原对话统计
35
+ ### DSH Web
52
36
 
53
- 点新会话头部的 **来源记录**。顶部显示已读轮次、消息数和已保存的工具调用。原日志有足够的时间戳或累计 Token 时,也会显示相应数据。继续聊天后仍可查阅迁入时保存的统计。
37
+ npm 当前发布版本为 v0.9.0。使用本仓库源码可构建 v0.10.0 安装包。
54
38
 
55
- <a href="https://raw.githubusercontent.com/wfz2006/dsh-agent-bridge/main/docs/screenshots/v0.9.0/source-record.png">
56
- <img src="https://raw.githubusercontent.com/wfz2006/dsh-agent-bridge/main/docs/screenshots/v0.9.0/source-record.png" width="700" alt="原对话统计显示轮次、消息、工具调用、时间跨度与 Token。第二轮展开后可见失败和未记录结果的工具条目。">
57
- </a>
39
+ ```sh
40
+ git clone https://github.com/wfz2006/dsh-agent-bridge.git
41
+ cd dsh-agent-bridge
42
+ npm install
43
+ npm pack
44
+ dsh plugin --profile web add ./wwwfz-dsh-agent-bridge-0.10.0.tgz
45
+ dsh web
46
+ ```
58
47
 
59
- *逐轮记录默认折叠。图中展开了第二轮,便于核对哪些工具失败或缺少结果。*
48
+ ## 使用
60
49
 
61
- <details>
62
- <summary>可迁入的历史范围</summary>
50
+ ### 迁入旧对话
63
51
 
64
- - 文字保留可读取的顺序和角色。较长历史按预算保留近期问答,预览会标记截取。Codex 的压缩会话 `.jsonl.zst` 也可发现和读取。
65
- - 来源记录可保存 Codex 的可见思考摘要和工具调用,以及 Claude Code 的工具调用与结果。结果按调用 ID 归到原回合。历史工具数据以只读记录保存,后续请求按 DSH 当前权限执行。
66
- - 宿主没有会话头部入口时,可在 Agent Bridge 的 **导出 DSH 会话** 中查看已保存的来源记录。旧版迁入的会话按当时保存的内容显示。
52
+ 1. 在项目列表中按名称、路径或 Agent 查找项目。
53
+ 2. 打开最近对话或查看全部对话,检查预览和来源记录。
54
+ 3. 选择 **迁入并继续**。原目录离线时可选择新的本机目录。
55
+ 4. 在 DSH 对话中查看消息和过程。打开会话头部的 **来源记录** 可按回合查看档案和附件。
67
56
 
68
- </details>
57
+ 续聊使用预览保留的近期问答正文。历史思考、工具与附件可在对话和来源记录中查阅,需要带入时可引用到草稿。
69
58
 
70
59
  ### 用项目资料开新对话
71
60
 
72
- 展开 **用项目资料开新对话**,从「上次做到哪」「项目约定」「Skills」等分组挑选资料。**全局资料库**默认折叠。打开 **接续清单** 可核对勾选,再用 **预览草稿** 打开一条新对话或导出交接。
73
-
74
- #### 为本项目启用原生 Skill
75
-
76
- 看到 **可为此项目启用** 时,可点 **启用** 核对目标项目和包内容。在会话预览里也可以通过 **沿用技能(可选)** 勾选本次要带入的技能。在确认界面核对范围、脚本和同名冲突后,才会保存完整包。
77
-
78
- <a href="https://raw.githubusercontent.com/wfz2006/dsh-agent-bridge/main/docs/screenshots/v0.9.0/skill-review.png">
79
- <img src="https://raw.githubusercontent.com/wfz2006/dsh-agent-bridge/main/docs/screenshots/v0.9.0/skill-review.png" width="509" alt="verify-endpoint 启用前的核对界面,列出目标项目、来源与四个包内文件。">
80
- </a>
81
-
82
- *脚本、参考资料和资源随包保存。打开「已启用的项目 Skills」可管理和停用技能,有上一版时也可恢复。*
61
+ 展开 **用项目资料开新对话**,选择项目记忆、交接或 Skills,点击 **预览草稿**。确认后打开新会话,草稿可在发送前编辑。启用原生 Skill 时,会先显示来源、项目范围和包内文件。
83
62
 
84
- <details>
85
- <summary>各类 Skill 状态和生效范围</summary>
86
-
87
- - **DSH 已发现**表示当前项目能读到原生定义。入口的可用状态以实际生效副本和 DSH 调用策略为准。「待确认」「当前模式不可调用」表示当前检查结果。
88
- - **可为此项目启用**表示可以为项目保存私有快照。快照位于 DSH 主目录的 `agent-bridge-skills/`,登记写入 `state.sqlite`。项目范围取最近的 `.git` 祖先,找不到时用原工作目录。
89
- - **同名,待核对**时保留原技能,内容指纹一致才复用。预览后来源或项目位置改变,需要重新核对。
90
- - **仅可带入说明**时使用 `SKILL.md` 正文摘录。指向包外的链接、包内特殊文件或疑似凭证文件会阻止整包启用。
91
- - 启用确认的是快照和项目登记。执行脚本、使用专有工具、加载外部依赖仍取决于当前 DSH 环境。来源消失后,已有快照仍可管理。
92
-
93
- </details>
94
-
95
- ## 导出交接
96
-
97
- - **导出项目资料**。在 **预览草稿** 中选择 **导出本机版** 或 **导出分享版**。
98
- - **导出 DSH 会话**。在面板右上角选择会话。需要工具名和结果摘录时,再勾选 **附带来源记录**。
99
- - **接收一份交接**。把下载的 Markdown 放进接收项目的 `.agent-bridge/handoffs/`,刷新后从「上次做到哪」选用。
63
+ ### 导出与接收交接
100
64
 
101
- <a href="https://raw.githubusercontent.com/wfz2006/dsh-agent-bridge/main/docs/screenshots/v0.9.0/markdown-preview.png">
102
- <img src="https://raw.githubusercontent.com/wfz2006/dsh-agent-bridge/main/docs/screenshots/v0.9.0/markdown-preview.png" width="509" alt="Markdown 预览保留标题、编号列表和检查项表格,可点开文档内的接口检查清单。">
103
- </a>
104
-
105
- *预览可打开经过核对的项目内文件,也可以复制路径。*
106
-
107
- <details>
108
- <summary>本机版、分享版和路径规则</summary>
109
-
110
- - 本机版将核实的本机来源写为 `file:` 链接,由阅读器决定能否打开。分享版使用文件名或项目相对路径,也可根据 Markdown 保存位置生成相对链接。
111
- - 预览从原文档目录解析相对链接,Host 核对项目范围和文件身份后让 DSH 打开。脚本等可执行文件提供定位。失效路径以文字保留。Markdown 的标题、代码块、表格和引用会排版,原始 HTML 按文字展示。
112
- - 原工作目录离线时,可导出仍能读取的归档资料。
113
-
114
- </details>
65
+ 在草稿预览或 DSH 会话导出中选择本机版或分享版。接收项目可将交接 Markdown 放入 `.agent-bridge/handoffs/`,刷新后选择使用。
115
66
 
116
67
  ## 支持来源
117
68
 
118
- 打开面板底部的 **本机来源** 查看可读取的数据。扫描会监听文件变化,也可点 **刷新来源** 立即复扫。
119
-
120
- | 来源 | 常见可读取内容 |
121
- | --- | --- |
122
- | Codex、Claude Code、OpenCode、Qoder、WorkBuddy、Gemini CLI、Qwen Code | 本地工作目录和可识别的会话,含有记录的 Skill 使用 |
123
- | VS Code 系列的 Copilot | 可识别的工作区和工作区会话 |
124
- | Antigravity、TRAE | 本机工作区与可关联记录,另外可读配置的 AgentsView 归档 |
125
- | 项目资料、WorkspaceHub、手动来源 | 可读 Markdown、共享记忆、交接和 Skill 目录 |
126
-
127
- 插件通过本机 DSH 所有者身份读取。源文件和 Agent 数据库以只读方式访问,加密或服务端记忆可先导出为 Markdown。
128
-
129
- <details>
130
- <summary>搜索、归档和主题</summary>
131
-
132
- - 按 <kbd>/</kbd> 定位项目搜索,按 <kbd>↓</kbd> 选中首项,按 <kbd>Enter</kbd> 打开。项目的勾选和近期对话选项会分别保存。
133
- - **置顶**常用项目。在 **最近接续** 可找回刚打开的项目。用 **整理 → 归档所选** 批量整理,在 **已归档** 恢复或撤销操作。
134
- - 支持蓝、白、黑三套主题,自动记住选择。正在预览时,列表会等预览关闭后再更新。 [Agent 图标来源](web/agent-icons/NOTICE.md)
69
+ 可读取的本机来源包括 Codex、Claude Code、OpenCode、Qoder、WorkBuddy、Gemini CLI、Qwen Code 和 VS Code Copilot。Antigravity 与 TRAE 的部分工作区记录及配置的 AgentsView 档案也可发现。
135
70
 
136
- </details>
71
+ 不同来源保存的信息不同。预览会标出可读取的内容和缺失项,加密或服务端记忆可先导出为 Markdown。Windows DSH Desktop 0.2.2-rc.3 已做隔离实机验收,其他平台的路径规则有自动测试覆盖。
137
72
 
138
73
  ## 在项目里存放共享记忆
139
74
 
140
- 在已发现的项目目录里放入 Markdown,刷新后即可选择。
141
-
142
- ~~~text
75
+ ```text
143
76
  my-project/
144
77
  .agent-bridge/
145
78
  memory/
146
79
  current-state.md
147
80
  handoffs/
148
81
  latest-handoff.md
149
- ~~~
82
+ ```
83
+
84
+ 刷新项目后即可选择第一层 Markdown 文件。
150
85
 
151
- 用 `current-state.md` 记当前目标、分支状态与待办,用 `latest-handoff.md` 记已完成事项、验证结果和下一步。两个目录的第一层 Markdown 会进入项目资料。
152
86
 
153
87
  ## 自定义来源
154
88
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wwwfz/dsh-agent-bridge",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Standalone DeepSeek Harness plugin for live local agent discovery, context import, and Markdown handoff export.",
5
5
  "keywords": ["dsh", "dsh-plugin", "deepseek-harness", "agent", "handoff", "skills"],
6
6
  "repository": { "type": "git", "url": "git+https://github.com/wfz2006/dsh-agent-bridge.git" },
package/src/catalog.js CHANGED
@@ -1,13 +1,17 @@
1
1
  import { execFile } from 'node:child_process'
2
2
  import { createHash, randomUUID } from 'node:crypto'
3
- import { realpath, stat } from 'node:fs/promises'
3
+ import { open, realpath, stat } from 'node:fs/promises'
4
4
  import path, { win32 } from 'node:path'
5
5
  import { promisify } from 'node:util'
6
6
  import { authorizeProjectReference, listProjectAssets, readAsset, verifyAssetSource, verifySourceAuthorization } from './assets.js'
7
- import { dateMillis, readConversationHistory, readProjectHistory, scanProjects } from './projects.js'
7
+ import { dateMillis, probeConversation, readProjectHistory, readSourceEvents, scanProjects } from './projects.js'
8
+ import {
9
+ approveConversation, discardConversation, finishConversation, readConversationSnapshot,
10
+ readHistoryPage, readPendingConversation, rebindConversation, stageConversation,
11
+ } from './conversation-store.js'
8
12
  import { createSourceMonitor } from './watch.js'
9
13
  import { makeExport } from './export.js'
10
- import { countTrace, normalizeTrace } from './session-trace.js'
14
+ import { countTrace, isSessionId, normalizeTrace } from './session-trace.js'
11
15
  import { isMarkdownFile, relativeMarkdownLinks } from '../web/markdown.js'
12
16
  import {
13
17
  ProjectArchiveError, readProjectSelection, readProjectState, writeProjectArchive,
@@ -19,7 +23,6 @@ const limit = 32_000
19
23
  const fallbackScanInterval = 15_000
20
24
  const ticketLifetime = 10 * 60_000
21
25
  const catalogId = /^[0-9a-f]{24}$/
22
- const conversationTicketLimit = 12
23
26
  const traceBudget = { items: 200, bytes: 48 * 1024, resultBytes: 4 * 1024 }
24
27
 
25
28
  class RequestError extends Error {
@@ -215,6 +218,51 @@ async function currentDirectory(cwd) {
215
218
  return null
216
219
  }
217
220
 
221
+ async function conversationDirectory(cwd) {
222
+ if (typeof cwd !== 'string' || cwd.length > 4096 || !path.isAbsolute(cwd) || /[\u0000-\u001f]/u.test(cwd)) return
223
+ const canonical = await currentDirectory(cwd)
224
+ if (!canonical || canonical === path.parse(canonical).root) return
225
+ const info = await stat(canonical, { bigint: true }).catch(() => undefined)
226
+ if (info?.isDirectory()) return { path: canonical, identity: `${info.dev}:${info.ino}` }
227
+ }
228
+
229
+ async function readConversationAttachment(project, archive, item) {
230
+ if (!item.path) return
231
+ const candidate = path.isAbsolute(item.path) ? path.normalize(item.path) : path.resolve(project.cwd, item.path)
232
+ let withinScope = false
233
+ for (const root of [project.cwd, path.join(path.dirname(archive.file), 'attachments')]) {
234
+ if (!root || !path.isAbsolute(root)) continue
235
+ const relative = path.relative(root, candidate)
236
+ if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) continue
237
+ withinScope = true
238
+ const href = relative.split(path.sep).map(encodeURIComponent).join('/')
239
+ const proof = await authorizeProjectReference(root, path.join(root, '.conversation'), href)
240
+ if (!proof.authorization) continue
241
+ const handle = await open(candidate, 'r').catch(() => undefined)
242
+ if (!handle) continue
243
+ try {
244
+ const initial = await handle.stat({ bigint: true })
245
+ const current = await verifySourceAuthorization(proof.authorization)
246
+ if (initial.dev !== current.fileInfo.dev || initial.ino !== current.fileInfo.ino) continue
247
+ if (initial.size > 32n * 1024n * 1024n) return { details: { status: 'attachment-too-large' } }
248
+ const bytes = Buffer.alloc(Number(initial.size))
249
+ let offset = 0
250
+ while (offset < bytes.length) {
251
+ const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset)
252
+ if (!bytesRead) break
253
+ offset += bytesRead
254
+ }
255
+ const end = await handle.stat({ bigint: true })
256
+ await verifySourceAuthorization(proof.authorization)
257
+ if (offset === bytes.length && end.size === initial.size && end.mtimeNs === initial.mtimeNs && end.ctimeNs === initial.ctimeNs) {
258
+ return { bytes, details: { name: redact(path.basename(candidate)) } }
259
+ }
260
+ } catch { /* Source identity changed during the read. */ }
261
+ finally { await handle.close() }
262
+ }
263
+ return { details: { status: withinScope ? 'attachment-unavailable' : 'outside-project' } }
264
+ }
265
+
218
266
  function sortProjects(a, b) {
219
267
  return Number(b.online) - Number(a.online)
220
268
  || (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '')
@@ -330,7 +378,7 @@ export function createCatalog(loadConfig, { importConversation, skillHandoff, lo
330
378
  const online = new Set([...resolved.values()].filter(Boolean).map(value => pathKey(value)))
331
379
  for (const project of projects) {
332
380
  project.online = online.has(pathKey(project.cwd))
333
- if (watched.has(project.cwd)) watched.set(project.cwd, { cwd: project.cwd, projectIds: project.projectIds })
381
+ if (watched.has(project.cwd)) watched.set(project.cwd, { cwd: project.cwd, projectIds: project.projectIds, archives: project.archives })
334
382
  }
335
383
  projects.sort(sortProjects)
336
384
  const fingerprint = keyFor(projects, result.sources)
@@ -338,7 +386,7 @@ export function createCatalog(loadConfig, { importConversation, skillHandoff, lo
338
386
  const changed = refresh || snapshot?.epoch !== scanEpoch || snapshot?.fingerprint !== fingerprint
339
387
  || snapshot?.stateFingerprint !== stateFingerprint
340
388
  details.clear()
341
- snapshot = { config, projects, sources: result.sources, scannedAt: Date.now(), fingerprint, stateFingerprint, epoch: scanEpoch }
389
+ snapshot = { config, projects, sources: result.sources, scannedAt: Date.now(), fingerprint, stateFingerprint, epoch: scanEpoch, conversationLists: new Map() }
342
390
  await monitor.update(config, [...watched.values()])
343
391
  if (changed) {
344
392
  revision++
@@ -422,7 +470,7 @@ export function createCatalog(loadConfig, { importConversation, skillHandoff, lo
422
470
  const pending = (async () => {
423
471
  if (!watched.has(project.cwd)) {
424
472
  if (watched.size >= 4) watched.delete(watched.keys().next().value)
425
- watched.set(project.cwd, { cwd: project.cwd, projectIds: project.projectIds })
473
+ watched.set(project.cwd, { cwd: project.cwd, projectIds: project.projectIds, archives: project.archives })
426
474
  await monitor.update(config, [...watched.values()])
427
475
  }
428
476
  const [{ memories, skills }, history] = await Promise.all([
@@ -666,98 +714,132 @@ export function createCatalog(loadConfig, { importConversation, skillHandoff, lo
666
714
  return { path: source.file, kind: 'file', name: item.name }
667
715
  }
668
716
 
669
- async function listConversations(projectId, recent) {
670
- const current = await scan()
671
- const project = requireProject(current, projectId)
717
+ async function readableConversations(project, config) {
672
718
  const archives = project.archives
673
719
  .filter(canReadConversation)
674
720
  .sort((a, b) => dateMillis(b.date) - dateMillis(a.date))
675
- const seen = new Set()
676
- const sessions = []
721
+ const unique = new Map()
677
722
  for (const archive of archives) {
678
723
  const id = conversationId(archive)
679
- if (seen.has(id)) continue
680
- seen.add(id)
681
- if (recent && sessions.length === 3) continue
682
- sessions.push({
683
- id, agent: archive.agent ?? archive.kind, date: dateMillis(archive.date),
684
- title: conversationTitle(archive.title), archivedSource: archive.kind === 'agentsview',
685
- })
724
+ if (!unique.has(id)) unique.set(id, archive)
725
+ }
726
+ const candidates = [...unique]
727
+ const sessions = []
728
+ for (let offset = 0; offset < candidates.length; offset += 8) {
729
+ const batch = await Promise.all(candidates.slice(offset, offset + 8).map(async ([id, archive]) => {
730
+ const probe = await probeConversation(archive, { sourceCwd: project.cwd, config })
731
+ if (probe.state === 'empty') return undefined
732
+ return {
733
+ id, agent: archive.agent ?? archive.kind, date: dateMillis(archive.date),
734
+ title: conversationTitle(archive.title), archivedSource: archive.kind === 'agentsview',
735
+ ...(probe.state === 'unknown' ? { unavailable: true, reason: probe.reason } : {}),
736
+ }
737
+ }))
738
+ sessions.push(...batch.filter(Boolean))
686
739
  }
687
- return recent ? { sessions, total: seen.size } : { sessions }
740
+ return sessions
688
741
  }
689
742
 
690
- async function previewConversation({ projectId, sessionId }) {
743
+ async function listConversations(projectId, recent, cursor) {
744
+ const current = await scan()
745
+ const project = requireProject(current, projectId)
746
+ const { conversationLists, config } = current
747
+ if (!conversationLists.has(projectId)) {
748
+ conversationLists.set(projectId, readableConversations(project, config))
749
+ }
750
+ const sessions = await conversationLists.get(projectId)
751
+ const ready = sessions.filter(session => !session.unavailable)
752
+ const unavailable = sessions.filter(session => session.unavailable)
753
+ if (recent) return { sessions: ready.slice(0, 3), total: ready.length,
754
+ ...(unavailable.length ? { unavailable: unavailable.slice(0, 20) } : {}) }
755
+ const marker = keyFor(ready.map(({ id }) => id))
756
+ const parsed = typeof cursor === 'string' && /^([0-9a-f]{24}):(\d{1,9})$/.exec(cursor)
757
+ if (cursor && (!parsed || parsed[1] !== marker)) throw new RequestError('会话列表已更新,请从第一页重新打开。', 409)
758
+ const offset = parsed ? Number(parsed[2]) : 0
759
+ const end = offset + 100
760
+ return { sessions: ready.slice(offset, end), ...(end < ready.length ? { nextCursor: `${marker}:${end}` } : {}),
761
+ ...(!offset && unavailable.length ? { unavailable: unavailable.slice(0, 100) } : {}) }
762
+ }
763
+
764
+ async function previewConversation({ projectId, sessionId, targetCwd, snapshotId, signal }) {
691
765
  if (!isCatalogId(sessionId)) throw new RequestError('会话标识无效。')
692
766
  const current = await scan()
693
767
  const project = requireProject(current, projectId)
694
768
  const { config } = current
695
769
  const archive = project.archives.find(item => canReadConversation(item) && conversationId(item) === sessionId)
696
- if (!archive) throw new RequestError('找不到这条会话,请刷新项目。', 404)
697
- const history = await readConversationHistory(archive, project.cwd, config).catch(() => {
698
- throw new RequestError('会话已移动或无法读取,请刷新后重试。', 409)
699
- })
700
- if (!history.messages.length) throw new RequestError('这条会话没有可迁入的文字问答。', 409)
701
- const messages = history.messages.map(({ role, text, time }) => ({ role, text: redact(text), time }))
702
- const { trace, indexOf, truncated: traceTruncated } = conversationTrace(history.trace ?? [], messages.length)
770
+ const previous = snapshotId && await readConversationSnapshot(config, snapshotId)
771
+ if (snapshotId && (!previous || previous.projectId !== projectId || previous.sourceId !== sessionId || previous.state !== 'preview')) {
772
+ throw new RequestError('会话预览已变化,请重新打开。', 409)
773
+ }
774
+ if (!archive && !previous) throw new RequestError('找不到这条会话,请刷新项目。', 404)
775
+ const target = await conversationDirectory(targetCwd ?? project.cwd)
776
+ if (targetCwd !== undefined && !target) throw new RequestError('目标目录不可访问,请选择本机工作目录。', 409)
777
+ const ready = target && await readPendingConversation(config, projectId, sessionId, target.path)
778
+ const metadata = {
779
+ id: randomUUID(), sessionId: randomUUID(), projectId, sourceId: sessionId,
780
+ sourceCwd: project.cwd, targetCwd: target?.path, targetIdentity: target?.identity,
781
+ title: previous?.title ?? conversationTitle(archive.title, 80),
782
+ }
783
+ const record = ready ?? (previous
784
+ ? await rebindConversation(config, previous, metadata)
785
+ : await stageConversation(config, metadata, readSourceEvents(archive, { config, sourceCwd: project.cwd, signal }), redact,
786
+ item => readConversationAttachment(project, archive, item)))
787
+ if (!record) throw new RequestError('会话预览已变化,请重新打开。', 409)
788
+ const messages = record.messages.map(({ role, text, time }) => ({ role, text, time }))
789
+ const { trace, indexOf, truncated: traceTruncated } = conversationTrace(record.trace, messages.length)
703
790
  for (let index = 0; index < messages.length; index++) {
704
791
  if (indexOf.has(index)) messages[index].traceIds = indexOf.get(index)
705
792
  }
706
793
  const traceCounts = countTrace(trace)
707
- const { sourceStats } = history
708
- const title = conversationTitle(archive.title || messages[0].text, 80) || '迁入的 Agent 会话'
709
- const path = await currentDirectory(project.cwd)
710
- const canImport = Boolean(path && pathKey(path) === pathKey(project.cwd))
711
- const ticket = randomUUID()
712
- for (const [key, record] of conversationTickets) {
713
- if (!record.pending && Date.now() - record.created > ticketLifetime) conversationTickets.delete(key)
714
- }
715
- if (canImport && conversationTickets.size >= conversationTicketLimit) {
716
- const oldest = [...conversationTickets].find(([, record]) => !record.pending)
717
- if (!oldest) throw new RequestError('其他会话正在迁入,请稍后重试。', 409)
718
- conversationTickets.delete(oldest[0])
719
- }
720
- if (canImport) conversationTickets.set(ticket, {
721
- created: Date.now(), projectId, sessionId: randomUUID(), path, config, messages, title, trace, sourceStats,
722
- })
723
- const entry = await detail(projectId)
794
+ const { sourceStats, history } = record
795
+ const title = record.title || conversationTitle(messages[0]?.text, 80) || '迁入的 Agent 会话'
796
+ const canImport = Boolean(target && messages.length && record.targetIdentity === target.identity)
724
797
  const skillCandidates = skillHandoff
725
- ? await skillHandoff.conversationCandidates(project, history.usedSkills, entry.skills)
798
+ && (!target || pathKey(target.path) === pathKey(project.cwd))
799
+ ? await skillHandoff.conversationCandidates(project, record.usedSkills, (await detail(projectId)).skills)
726
800
  : []
727
801
  return {
728
- title, messages, ticket: canImport ? ticket : null, canImport, cwd: project.cwd,
729
- truncated: history.truncated || traceTruncated, skillCandidates, trace, traceCounts, sourceStats,
802
+ title, messages, ticket: canImport ? record.id : null, canImport, cwd: project.cwd,
803
+ sourceCwd: project.cwd, targetCwd: target?.path, history, resumePending: record.state === 'approved',
804
+ truncated: record.truncated || traceTruncated, skillCandidates, trace, traceCounts, sourceStats,
730
805
  }
731
806
  }
732
807
 
733
808
  async function commitConversation(ticket) {
734
- const record = conversationTickets.get(ticket)
735
- if (!record || Date.now() - record.created > ticketLifetime) {
736
- throw new RequestError('会话预览已过期,请重新打开。', 409)
737
- }
738
- if (record.result) return record.result
739
- if (record.pending) return record.pending
740
- record.pending = (async () => {
741
- const cwd = await currentDirectory(record.path)
742
- if (!cwd || pathKey(cwd) !== pathKey(record.path)) {
743
- throw new RequestError('原工作目录已变化,请刷新项目。', 409)
809
+ if (!isSessionId(ticket)) throw new RequestError('会话预览已过期,请重新打开。', 409)
810
+ if (conversationTickets.has(ticket)) return conversationTickets.get(ticket)
811
+ const pending = (async () => {
812
+ const config = await loadConfig()
813
+ const record = await readConversationSnapshot(config, ticket)
814
+ if (!record?.targetCwd || !record.messages.length) throw new RequestError('会话预览已过期或不能迁入,请重新打开。', 409)
815
+ if (record.state === 'done') return { sessionId: record.sessionId }
816
+ const target = await conversationDirectory(record.targetCwd)
817
+ if (!target || pathKey(target.path) !== pathKey(record.targetCwd) || target.identity !== record.targetIdentity) {
818
+ throw new RequestError('目标目录已变化,请重新选择目录。', 409)
819
+ }
820
+ if (record.state === 'preview' && !await approveConversation(config, ticket)) {
821
+ throw new RequestError('会话预览已过期或正在迁入,请重新打开。', 409)
744
822
  }
823
+ record.config = config
824
+ record.title ||= conversationTitle(record.messages[0].text, 80) || '迁入的 Agent 会话'
825
+ record.trace = conversationTrace(record.trace, record.messages.length).trace
826
+ let result
745
827
  try {
746
- record.result = await importConversation(record, cwd)
828
+ result = await importConversation(record, target.path)
829
+ await finishConversation(config, ticket, record.nativeTimeline)
747
830
  } catch (error) {
748
831
  if (error.status) throw error
749
832
  const message = record.stored ? '会话历史已写入,暂时无法加入工作区。可重试打开。' : '无法将会话写入 DSH。请检查工作区和会话存储后重试。'
750
833
  throw new RequestError(message, 503)
751
834
  }
752
- delete record.messages
753
- delete record.stored
754
835
  try {
755
836
  await writeProjectContinuation(record.config, record.projectId)
756
837
  await synchronizeProjectState()
757
838
  } catch { /* A saved session remains usable even if the recents index cannot be updated. */ }
758
- return record.result
759
- })().finally(() => { delete record.pending })
760
- return record.pending
839
+ return result
840
+ })().finally(() => conversationTickets.delete(ticket))
841
+ conversationTickets.set(ticket, pending)
842
+ return pending
761
843
  }
762
844
 
763
845
  async function exportSession({ conversation, format, includeTrace, sessionId }) {
@@ -801,6 +883,17 @@ export function createCatalog(loadConfig, { importConversation, skillHandoff, lo
801
883
  if (action === 'set-project-pin') return setProjectPin(input)
802
884
  if (action === 'set-project-selection') return setProjectSelection(input)
803
885
  if (action === 'record-project-continuation') return recordProjectContinuation(input.ticket)
886
+ if (action === 'conversation-history' || action === 'discard-conversation-preview') {
887
+ const config = await loadConfig()
888
+ const id = input.snapshotId ?? input.ticket
889
+ if (action === 'discard-conversation-preview') {
890
+ await discardConversation(config, id)
891
+ return {}
892
+ }
893
+ const page = await readHistoryPage(config, id, input.cursor, input.turn)
894
+ if (!page) throw new RequestError('来源历史已过期,请重新打开预览。', 404)
895
+ return page
896
+ }
804
897
  if (action === 'preview-skill-activation') {
805
898
  if (!skillHandoff) throw new RequestError('当前 DSH 未提供原生技能启用服务。', 409)
806
899
  if (!isCatalogId(input.projectId) || !Array.isArray(input.assetIds)
@@ -843,7 +936,7 @@ export function createCatalog(loadConfig, { importConversation, skillHandoff, lo
843
936
  }
844
937
  if (action === 'list-conversations' || action === 'preview-conversation' || action === 'import-conversation') {
845
938
  if (!importConversation) throw new RequestError('当前 DSH 未提供会话迁入服务。', 409)
846
- if (action === 'list-conversations') return listConversations(input.projectId, input.recent === true)
939
+ if (action === 'list-conversations') return listConversations(input.projectId, input.recent === true, input.cursor)
847
940
  if (action === 'preview-conversation') return previewConversation(input)
848
941
  return commitConversation(input.ticket)
849
942
  }