dshgo-transcript-import 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 parofufu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,203 @@
1
- # Temporary Holding Version
1
+ # dsh-transcript-import
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Import an existing chat transcript into a brand-new DSH session as ordinary session events, so the model continues that history as if it had always been there.
4
+
5
+ 把一份已有的聊天记录导入成一个**全新的 DSH 会话**,让这段对话看起来原本就发生在该会话里;之后用户在那个会话里继续提问,模型会把导入的历史当作自己的上下文。
6
+
7
+ 插件本身不拼 prompt,也不伪造请求:它把记录转换成普通的 SessionEvent(`turn/start`、`user/message`、`assistant/message`……),因此派生历史、UI 渲染、上下文统计、持久化都与真实会话完全一致。
8
+
9
+ ## 安装
10
+
11
+ 发布包里带 `dsh.bundle` 清单(`cordis.patch.yml`)和预构建的 `lib/plugin.js`;源文件是 [src/plugin.ts](src/plugin.ts),不依赖任何 `@deepseek-ai/*` 运行时包(DSH 的 profile loader 只解析 profile/asar 内的模块,外部插件引用裸包会报 `ERR_MODULE_NOT_FOUND`)。
12
+
13
+ 方式 A:从 npm 安装(推荐)
14
+
15
+ ```sh
16
+ dsh plugin --profile web add dsh-transcript-import
17
+ ```
18
+
19
+ `dsh plugin add` 会把包加进 profile 的 `dsh.profile.bundles`,包的 `cordis.patch.yml` 再把插件插进组合;重启 `dsh web`(或在插件市场里热加载)后生效。
20
+
21
+ 方式 B:从 GitHub 源码安装
22
+
23
+ ```sh
24
+ dsh plugin --profile web add github:parofufu/dsh-transcript-import
25
+ ```
26
+
27
+ 方式 C:本地开发用 patch 覆盖层(改源码后立即生效,无需重新打包)
28
+
29
+ ```yaml
30
+ # dev.cordis.yml(name 必须是绝对路径)
31
+ - insert:
32
+ - id: dsh-transcript-import
33
+ name: 'd:/OPENK/dsh-transcript-plugin/src/plugin.ts'
34
+ ```
35
+
36
+ ```sh
37
+ dsh web --patch ./dev.cordis.yml
38
+ ```
39
+
40
+ ## 用法
41
+
42
+ 启动后模型会多出一个工具 `transcript_import`。典型对话:
43
+
44
+ > 用 transcript_import 导入 D:/chats/xxx.json,先 dryRun=true
45
+
46
+ 工具返回轮次、消息条数、字符数和 token 估算;确认后再 `dryRun=false`。导入完成后返回新会话 id,并明确说明历史属于新会话、当前会话不会出现这些记录。
47
+
48
+ ### 工具参数
49
+
50
+ | 参数 | 类型 | 默认 | 说明 |
51
+ | --- | --- | --- | --- |
52
+ | `path` | string | 必填 | 记录文件路径(绝对路径,或相对当前工作目录) |
53
+ | `dryRun` | boolean | false | 只解析与估算,不创建会话 |
54
+ | `reasoning` | `block` / `text` / `drop` | `block` | 思考链写成 reasoning 块 / 并入正文 / 丢弃 |
55
+ | `keepToolNotes` | boolean | true | 是否把检索、打开网页、导不进来的附件降级成正文注记 |
56
+ | `title` | string | 记录自带标题 | 会话标题 |
57
+ | `preserveTime` | boolean | false | 是否保留记录里的原始时间戳;默认用当前时间(否则会话会被排到列表底部) |
58
+ | `provider` / `model` | string | 沿用当前会话 | 写入 assistant 消息的标记,仅用于显示 |
59
+ | `cwd` | string | 沿用当前会话 | 新会话的工作目录 |
60
+ | `files` | string[] | `[]` | 用户提供的附件本地路径;按文件名自动放回记录里引用它的那条消息 |
61
+ | `allowMissingAttachments` | boolean | false | 记录引用了导出包没带的附件时是否跳过(只留文件名注记);默认先返回待确认列表 |
62
+
63
+ ## 支持的记录格式
64
+
65
+ ### 1. `dsh-transcript/1`(推荐,见 [示例](examples/minimal.dsh-transcript.json))
66
+
67
+ ```json
68
+ {
69
+ "format": "dsh-transcript/1",
70
+ "title": "可选标题",
71
+ "createdAt": "2026-03-02T09:15:00+08:00",
72
+ "messages": [
73
+ { "role": "user", "text": "提问" },
74
+ { "role": "assistant", "reasoning": "可选思考链", "text": "回答", "notes": ["可选注记"] }
75
+ ]
76
+ }
77
+ ```
78
+
79
+ ### 2. DeepSeek 客户端导出
80
+
81
+ `deepseek_data/chat_sessions/*.json` 原样传入即可。片段映射:
82
+
83
+ | 片段 | 映射 |
84
+ | --- | --- |
85
+ | `REQUEST` | 用户消息正文 |
86
+ | `THINK` | reasoning 块(或多条合并) |
87
+ | `RESPONSE` | 回答正文 |
88
+ | `TOOL_SEARCH` | 注记「联网搜索:查询词」 |
89
+ | `TOOL_OPEN` | 注记「打开网页:标题/URL」 |
90
+ | `FILE` | 注记「附件:文件名」 |
91
+
92
+ ### 3. 通用 `{messages:[{role, content}]}`
93
+
94
+ OpenAI / Claude 风格导出,`content` 可以是字符串或 `[{type:"text"|"thinking", ...}]` 块数组。
95
+
96
+ ### 4. 导出器生成的 Markdown 会话
97
+
98
+ `path` 可以直接给导出目录(`导出结果_*/`),工具会定位其中唯一的会话 `.md`(跳过 `_导出汇总.md`);也可以直接给 `<id>_<title>/<title>.md`。
99
+
100
+ ```md
101
+ # 书单
102
+ > **创建** 2026-11-04 18:26:35
103
+
104
+ ## 对话
105
+
106
+ ## 🧑 用户
107
+ *msg 1 · 2026-11-04 18:26:50 · 2 片段 · 1006 tokens*
108
+ 😂
109
+
110
+ ![截图.webp](attachments/xxx.webp)
111
+
112
+ ## 🤖 AI
113
+ <details>
114
+ <summary>🤔 思考链(耗时 4.4s)</summary>
115
+ ...
116
+ </details>
117
+
118
+ 回答正文
119
+ ```
120
+
121
+ 映射:`## 🧑 用户` / `## 🤖 AI` 切分消息,`思考链` details → reasoning 块(`reasoning:"text"` 时并入正文),`联网搜索` details 只保留查询词,`🔗 打开网页:...` → 注记,`_【CONTENT_RISK】_` 免责行和 `---` 分隔线丢弃。用户消息里的 `![名称](attachments/xxx.webp)` 会按 Markdown 所在目录解析,图片本身写成真实的 image 块(见下)。
122
+
123
+ 非图片附件会识别这三种导出写法:
124
+
125
+ | Markdown 写法 | 处理 |
126
+ | --- | --- |
127
+ | `📎 **附件**:[名称](attachments/file)(大小)` | 文件已在导出包里,直接存成 file 块 |
128
+ | `📎 **附件(导出包未包含原文件)**:`名称` · 大小 · 非图片` | 只有元数据,列入待确认列表,等用户给本地路径 |
129
+ | `📎 **附件缺失**:`名称` → `相对路径`` | 同上,列入待确认列表 |
130
+
131
+ ### 非图片附件:先问,再放
132
+
133
+ DeepSeek 客户端导出包只带图片,docx/pdf/txt 之类只有文件名和大小。工具不会静默丢掉它们:
134
+
135
+ 1. 第一次调用(含 `dryRun=true`)会在结果里返回 `needsAttachments` 和 `missingFiles`(形如 `广义生命论 (10086).docx(41.6 KB)(第 3 轮)`),并且**不会创建会话**;
136
+ 2. 模型据此询问用户:手上有这些文件吗?有的话把本地路径发过来;
137
+ 3. 带 `files: ["C:\\...\\广义生命论.docx"]` 再调用:按文件名匹配(忽略客户端加的 ` (10086)` 副本标记、大小写和空格),文件存进附件库后作为 `file` 块写入**原来那条**用户消息;
138
+ 4. 用户没有或不想放:带 `allowMissingAttachments: true` 再调用,附件降级为「附件:名称(大小)」注记后正常导入。
139
+
140
+ 匹配不上的路径会给出 warning 并忽略,不会乱塞到别的消息。
141
+
142
+ ## 导入后会发生什么
143
+
144
+ 1. 通过 agent factory 创建新会话(只有 factory 持有持久化写句柄,`ctx.sessions.create()` 创建的会话重启后会消失)。
145
+ 2. 导入的事件作为**构造种子**传入:种子在 agent 构建之前就进入日志,所以循环的轮次计数器从导入的轮数继续(否则下一轮会从 `turn=1` 重新开始,与历史重复)。
146
+ 3. 第一轮写入一个**空 system 节点**占住 surface 0 位;下一轮开始时框架会用真实系统提示词替换它,因此历史前面不会缺 system,也不会重复注入。
147
+ 4. 显式固定会话标题(种子事件不会触发 `session/event`,标题插件看不到首条提问,所以由插件直接写入 `session/title`)。
148
+ 5. 默认用「现在」给历史打时间戳:会话列表按最近活动排序、每个工作区只显示最近 10 个,用原始时间会把新会话埋到列表底部(需要原时间就传 `preserveTime:true`)。
149
+ 6. 附件图片在构建种子之前先经 `ctx.attachments.saveImages()` 存入附件仓库(`DSH_HOME/attachments/v1`),user 消息里写的是 `{type:"image", attachment:{attachmentId:"sha256:…", mediaType, width, height, bytes}}`,所以模型看到的是图片本身而不是文件名;单张图片打不开、格式不识别或超出附件限制时,降级成「附件:文件名」注记并给出 warning。
150
+ 7. 非图片文件经 `ctx.attachments.saveFile()` 原样保存(不转码),user 消息里写 `{type:"file", attachment:{attachmentId, name, bytes}}`;模型侧收到一行句柄文本(文件名、字节数、摘要前缀和只读路径),需要时用文件工具读取。
151
+ 8. `ctx.sessions.flush()` 落盘后再返回 sessionId。
152
+
153
+ ## 已验证(真实引擎,非 mock)
154
+
155
+ 用本地 `dsh web --patch` 加载插件、在 Web UI 里实际调用并续聊,确认:
156
+
157
+ - 导入会话可以被「搜索会话」按标题找到并正常渲染,标题、历史消息、思考块、工具注记都正确;
158
+ - 在导入会话里追问,模型能准确回答只有那段历史里才有的内容(说明历史确实进了请求);
159
+ - 日志中 `turn/start` 为 `[1, 2]`,续聊没有重复轮次;
160
+ - system 节点先是空的,续聊时被真实系统提示词替换(`content` 从 0 块变 1 块);
161
+ - 思考块以 reasoning 形式留在历史里,DeepSeek 账号通道接受,没有请求报错。
162
+ - 用 `导出结果_20261117_193150`(36 轮 / 72 条 / 约 84K tokens 的 Markdown 导出)实际导入并追问,回答准确落在第 36 轮的话题上,日志为 `turn/start [1…37]`。
163
+ - 同一份导出里的 3 张 `.webp` 附件被真正导入:日志里 3 条用户消息带 `image` 块(规范化后为 `image/jpeg 1373x3051`,`attachmentId` 指向 `sha256:…`),附件对象落在 `DSH_HOME/attachments/v1/objects/`;其中一条只有图片、没有文字的消息也能正常导入;追问「最后那条只发图片的消息里截图是什么界面」时,模型答出了图里的具体内容(标题栏昵称、底部输入区图标),说明图片确实进了请求。
164
+ - 「老三论三本书作者」导出(`导出结果_20261116_191738`)里只有 1 个未打包的 `广义生命论 (10086).docx`:首次调用返回 `needsAttachments` 与待确认列表且未创建会话;带上用户本地路径 `广义生命论.docx` 再调用后,第 3 轮用户消息变成单个 `file` 块,附件按原字节(42,615)存入 `DSH_HOME/attachments/v1/files/…`;续聊追问只读路径时模型准确答出该路径,说明 `file` 块在历史投影里会被转成句柄文本,DeepSeek 通道不会因此报错。
165
+
166
+ 开发期可以用 `node scripts/selfcheck.mjs <记录文件或导出目录> [附件路径]` 跑离线校验(事件结构、stream 与 content 自洽、seq 连续、JSON 可序列化、图片/文件块落位);加 `PLUGIN_ENTRY=../lib/plugin.js` 可校验构建产物。
167
+
168
+ ## 限制
169
+
170
+ - **只能新建会话**:不写当前会话,也不能把历史“塞进”一个已有会话。
171
+ - 思考链默认写 reasoning 块。它只影响 UI 展示:DeepSeek 历史里 thinking 不回传,若某个适配器拒绝无签名 thinking,改用 `reasoning:"text"`。
172
+ - 工具调用不伪造:检索/打开网页/附件只能降级为正文注记,`reasoning:"text"` 同理。
173
+ - 不伪造 `request/header`、不重复注入 system 提示词。
174
+ - 超长历史会直接占用上下文(工具会给出估算),超出模型窗口时框架侧仍会报错。
175
+ - 导入会话不会自动加入某个工作区的会话列表:它一般落在侧栏的「未分组」,或需要用「搜索会话」按标题找到(会话列表按最近活动排序且每个工作区最多 10 条)。
176
+ - 图片附件(PNG/JPEG/WebP/GIF,单图 ≤ 20MiB、单条消息 ≤ 20 张、≤ 200MiB,按附件仓库策略规范化)可以直接从导出包导入;其他类型的文件只在导出包携带原文件、或用户手动给出本地路径时才能导入——DeepSeek 客户端导出本身不带 docx/pdf/txt 的字节,这是导出数据的限制,不是插件丢数据。
177
+ - `file` 块在模型侧只是一行句柄文本(文件名、大小、摘要前缀、只读路径),模型要看内容仍需调用文件工具;这与 DSH 里正常上传文件的体验一致。
178
+ - 图片依赖 `ctx.attachments` 服务:profile 没有挂载附件服务时,图片自动降级为文件名注记(会给出 warning),不会导致导入失败。
179
+ - 导入会话的工作目录默认跟随发起导入的会话。
180
+ - DSHgo 原生卡片通过 `presentationMeta` 的 `{"dsh-go/view": …}` 提供(轮次/消息数/token 估算),`package.json` 另声明 `dshGo`(protocol v1,`contributes` 为空,因为卡片是工具输出的一部分而不是独立面板)供市场标注「兼容 DSH Go」;不装 DSHgo 时显示为普通工具卡。
181
+ - 种子事件不会广播给 `session/event` 监听者,依赖“首条消息”的自动化(如按首条提问自动起标题)对导入会话不会触发,标题已由插件显式写入。
182
+
183
+ ## 开发与发布
184
+
185
+ ```sh
186
+ npm run build # src/plugin.ts → lib/plugin.js(Node 自带的类型擦除,零依赖)
187
+ npm pack # 生成 dsh-transcript-import-0.1.0.tgz(只含 lib、patch、README、LICENSE)
188
+ ```
189
+
190
+ `lib/plugin.js` 随仓库提交:从源码安装需要 pnpm 的构建授权,预构建产物保证 npm / 市场安装开箱可用。
191
+
192
+ ### 上架 DSH Go 插件市场
193
+
194
+ [DSH Go 插件市场](https://github.com/ccch1mneyyy/dsh-go-market)只收录 **npm 上的精确版本**,不接受 `latest`、版本范围或 Git 地址。自动检查通过才会上架,硬性条件:
195
+
196
+ - 该精确版本在 npm 存在,许可证在 SPDX 的 OSI 清单里(本包 MIT);
197
+ - 压缩与展开体积都 ≤ 50 MiB;包身份、npm SHA-512 与包内 `dsh.bundle` patch 一致(本包 `cordis.patch.yml` 按包名挂载);
198
+ - 格式 1 索引有效,npm 公告里该版本没有 high/critical 级别问题;
199
+ - 条目里**不能**写 `tier`、风险等级、完整性或审核结论(这些由市场扫描生成)。
200
+
201
+ 发布 npm 后 fork 市场仓库,把 [submission/dsh-transcript-import.json](submission/dsh-transcript-import.json) 放进 `plugins/`(非 scoped 包用 `<包名>.json`,`@scope/name` 用 `@scope__name.json`),一次 PR 只增改这一个文件。检查通过后自动合并,无需人工审批;升级只改该文件里的 `version`,不追加历史版本。
202
+
203
+ `dshGo` 声明只是静态标注,不等于已在 App 上跑通;`dsh-go/view` 卡片目前只在 `dsh web` 里验证过。
@@ -0,0 +1,6 @@
1
+ # dsh bundle patch: inserts this plugin into a profile's layer stack.
2
+ # `name` is the published package name, so the same file works after
3
+ # `dsh plugin add dshgo-transcript-import`.
4
+ - insert:
5
+ - id: dshgo-transcript-import
6
+ name: 'dshgo-transcript-import'
package/lib/plugin.js ADDED
@@ -0,0 +1,1062 @@
1
+ // Generated from src/plugin.ts by scripts/build.mjs. Do not edit.
2
+ /**
3
+ * dsh-transcript-import — import an existing chat transcript into a brand new
4
+ * DSH session by appending ordinary SessionEvents, so the model continues that
5
+ * history as if it had always happened in this session.
6
+ *
7
+ * Zero runtime imports from @deepseek-ai/*: the plugin is loaded from an
8
+ * arbitrary absolute path by the profile loader, whose module resolution only
9
+ * covers the profile/app tree. Only node builtins are imported.
10
+ */
11
+
12
+ import { readFile, readdir, stat } from 'node:fs/promises'
13
+ import { dirname, isAbsolute, join } from 'node:path'
14
+ import { randomUUID } from 'node:crypto'
15
+
16
+ const PLUGIN_NAME = 'dsh-transcript-import'
17
+ const TOOL_NAME = 'transcript_import'
18
+ const DEFAULT_PROVIDER = 'deepseek-account'
19
+ const DEFAULT_MODEL = 'deepseek-flash'
20
+ const TOOL_CARD_MAX_BYTES = 8 * 1024
21
+
22
+ /** One attachment image referenced by a message, plus its stored reference once admitted. */
23
+
24
+
25
+
26
+
27
+
28
+
29
+ /**
30
+ * One non-image attachment referenced by a message. `path` is only set when the
31
+ * export actually carried the bytes; a bare name means the export kept metadata
32
+ * only, so the user has to supply the file before it can be imported.
33
+ */
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+ /** One normalized message ready for event construction. */
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+ /** A turn: one user prompt plus its recorded answer (when one exists). */
60
+
61
+
62
+
63
+
64
+
65
+ /** A referenced attachment whose bytes the export did not carry. */
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+ function isRecord(value ) {
85
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
86
+ }
87
+
88
+ function str(value ) {
89
+ return typeof value === 'string' ? value : ''
90
+ }
91
+
92
+ function trim(value ) {
93
+ return value.replace(/^\s+|\s+$/g, '')
94
+ }
95
+
96
+ function pushUnique(list , value ) {
97
+ if (list.indexOf(value) === -1) list.push(value)
98
+ }
99
+
100
+ /** Section appended to assistant text when tool/search records are kept as prose. */
101
+ function notesSection(notes ) {
102
+ if (notes.length === 0) return ''
103
+ return `\n\n(当时的检索与文件操作记录)\n${notes.map((note) => `- ${note}`).join('\n')}`
104
+ }
105
+
106
+ function joinText(parts ) {
107
+ return parts.map(trim).filter((part) => part.length > 0).join('\n\n')
108
+ }
109
+
110
+ /** Render a byte count the way the exporter does (one decimal, KiB base). */
111
+ function formatSize(bytes ) {
112
+ if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) return undefined
113
+ if (bytes < 1024) return `${bytes} B`
114
+ const kilobytes = bytes / 1024
115
+ return kilobytes < 1024 ? `${kilobytes.toFixed(1)} KB` : `${(kilobytes / 1024).toFixed(1)} MB`
116
+ }
117
+
118
+ function parseTime(value ) {
119
+ if (typeof value === 'number' && Number.isFinite(value)) return value
120
+ if (typeof value === 'string' && value.length > 0) {
121
+ const parsed = Date.parse(value)
122
+ if (Number.isFinite(parsed)) return parsed
123
+ }
124
+ return undefined
125
+ }
126
+
127
+ /* ------------------------------------------------------------------ */
128
+ /* Source formats */
129
+ /* ------------------------------------------------------------------ */
130
+
131
+ /** DeepSeek client export: chat_sessions/<id>.json (role USER/ASSISTANT + fragments). */
132
+ function fromDeepSeekExport(document , warnings ) {
133
+ const messages = []
134
+ for (const raw of Array.isArray(document.messages) ? document.messages : []) {
135
+ if (!isRecord(raw)) continue
136
+ const role = str(raw.role).toLowerCase()
137
+ const fragments = Array.isArray(raw.fragments) ? raw.fragments : []
138
+ const notes = []
139
+ const files = []
140
+ if (role === 'user') {
141
+ const text = joinText(fragments.filter((f) => f?.type === 'REQUEST').map((f) => str(f.content)))
142
+ for (const fragment of fragments) {
143
+ if (fragment?.type !== 'FILE') continue
144
+ for (const file of Array.isArray(fragment.files) ? fragment.files : []) {
145
+ const name = str(file?.file_name)
146
+ if (name.length === 0) continue
147
+ // Images in a JSON export are not carried as image blocks here, so
148
+ // they stay notes; non-image files become pending attachments.
149
+ if (file?.is_image === true) pushUnique(notes, `附件:${name}`)
150
+ else files.push({ name, size: formatSize(file?.file_size) })
151
+ }
152
+ }
153
+ if (text.length > 0 || notes.length > 0 || files.length > 0) {
154
+ messages.push({ role: 'user', text, reasoning: '', notes, images: [], files })
155
+ } else warnings.push('跳过一条空的用户消息')
156
+ continue
157
+ }
158
+ if (role === 'assistant') {
159
+ const reasoning = joinText(fragments.filter((f) => f?.type === 'THINK').map((f) => str(f.content)))
160
+ const text = joinText(fragments.filter((f) => f?.type === 'RESPONSE').map((f) => str(f.content)))
161
+ for (const fragment of fragments) {
162
+ if (fragment?.type === 'TOOL_SEARCH') {
163
+ const queries = (Array.isArray(fragment.queries) ? fragment.queries : []).map(str).filter((q) => q.length > 0)
164
+ pushUnique(notes, queries.length > 0 ? `联网搜索:${queries.join(' / ')}` : '联网搜索')
165
+ } else if (fragment?.type === 'TOOL_OPEN') {
166
+ const label = str(fragment.title) || str(fragment.url)
167
+ if (label.length > 0) pushUnique(notes, `打开网页:${label}`)
168
+ }
169
+ }
170
+ if (text.length > 0 || reasoning.length > 0 || notes.length > 0) {
171
+ messages.push({ role: 'assistant', text, reasoning, notes, images: [], files: [] })
172
+ } else {
173
+ warnings.push('跳过一条空的回答消息')
174
+ }
175
+ }
176
+ }
177
+ return messages
178
+ }
179
+
180
+ /** Native dsh-transcript/1 format. */
181
+ function fromTranscriptFormat(document , warnings ) {
182
+ const messages = []
183
+ for (const raw of Array.isArray(document.messages) ? document.messages : []) {
184
+ if (!isRecord(raw)) continue
185
+ const role = str(raw.role).toLowerCase()
186
+ if (role !== 'user' && role !== 'assistant') {
187
+ warnings.push(`跳过未知角色 "${str(raw.role)}"`)
188
+ continue
189
+ }
190
+ const text = str(raw.text)
191
+ const reasoning = str(raw.reasoning)
192
+ const notes = Array.isArray(raw.notes) ? raw.notes.map(str).filter((n) => n.length > 0) : []
193
+ if (text.length === 0 && reasoning.length === 0 && notes.length === 0) {
194
+ warnings.push('跳过一条空消息')
195
+ continue
196
+ }
197
+ messages.push({ role, text, reasoning, notes, images: [], files: [] })
198
+ }
199
+ return messages
200
+ }
201
+
202
+ /** Generic {messages:[{role,content}]} exports (OpenAI / Claude style). */
203
+ function fromGenericMessages(document , warnings ) {
204
+ const messages = []
205
+ for (const raw of Array.isArray(document.messages) ? document.messages : []) {
206
+ if (!isRecord(raw)) continue
207
+ const role = str(raw.role).toLowerCase()
208
+ if (role !== 'user' && role !== 'assistant') {
209
+ warnings.push(`跳过未知角色 "${str(raw.role)}"`)
210
+ continue
211
+ }
212
+ let text = ''
213
+ let reasoning = ''
214
+ if (typeof raw.content === 'string') {
215
+ text = raw.content
216
+ } else if (Array.isArray(raw.content)) {
217
+ const parts = []
218
+ for (const block of raw.content) {
219
+ if (!isRecord(block)) continue
220
+ if (block.type === 'text' || block.type === 'input_text' || block.type === 'output_text') parts.push(str(block.text))
221
+ else if (block.type === 'thinking' || block.type === 'reasoning') reasoning = joinText([reasoning, str(block.thinking) || str(block.text)])
222
+ }
223
+ text = joinText(parts)
224
+ }
225
+ if (text.length === 0 && reasoning.length === 0) {
226
+ warnings.push('跳过一条空消息')
227
+ continue
228
+ }
229
+ messages.push({ role, text, reasoning, notes: [], images: [], files: [] })
230
+ }
231
+ return messages
232
+ }
233
+
234
+ /** Parse one half of a Markdown export section into a normalized message. */
235
+ function markdownMessage(raw , role , baseDir ) {
236
+ const reasoning = []
237
+ const notes = []
238
+ const images = []
239
+ const files = []
240
+ let body = raw.replace(/<details>\s*<summary>(.+?)<\/summary>([\s\S]*?)<\/details>/g, (_match, summary , inner ) => {
241
+ if (summary.includes('思考链')) {
242
+ const text = trim(inner)
243
+ if (text.length > 0) reasoning.push(text)
244
+ } else if (summary.includes('联网搜索')) {
245
+ const queries = [...inner.matchAll(/- 查询:\s*`([^`]+)`/g)].map((match) => match[1])
246
+ notes.push(queries.length > 0 ? `联网搜索:${queries.join(' / ')}` : '联网搜索')
247
+ }
248
+ return ''
249
+ })
250
+ body = body.replace(/^🔗 打开网页:\[(.+?)\]\(.+?\)\s*$/gm, (_match, title ) => {
251
+ notes.push(`打开网页:${title}`)
252
+ return ''
253
+ })
254
+ // Non-image attachment lines written by the exporter:
255
+ // 📎 **附件(导出包未包含原文件)**:`name` · size · 非图片
256
+ // 📎 **附件**:[name](attachments/file)(size)
257
+ // 📎 **附件缺失**:`name` → `rel`
258
+ body = body.replace(/^📎 \*\*附件(导出包未包含原文件)\*\*:`([^`]+)` · ([^·]+?) · (图片|非图片)\s*$/gm,
259
+ (_match, name , size , kind ) => {
260
+ if (role === 'user' && kind === '非图片') files.push({ name, size: trim(size) })
261
+ else notes.push(`附件:${name}`)
262
+ return ''
263
+ })
264
+ body = body.replace(/^📎 \*\*附件\*\*:\[(.+?)\]\((.+?)\)((.+?))\s*$/gm,
265
+ (_match, name , target , size ) => {
266
+ if (role === 'user' && target.length > 0) {
267
+ files.push({ name, size: trim(size), path: isAbsolute(target) ? target : join(baseDir, target) })
268
+ } else notes.push(`附件:${name}`)
269
+ return ''
270
+ })
271
+ body = body.replace(/^📎 \*\*附件缺失\*\*:`([^`]+)` → `.+?`\s*$/gm, (_match, name ) => {
272
+ if (role === 'user') files.push({ name })
273
+ else notes.push(`附件:${name}`)
274
+ return ''
275
+ })
276
+ body = body.replace(/^!\[(.+?)\]\((.+?)\)\s*$/gm, (_match, alt , target ) => {
277
+ // A user image becomes a real image block; anything else (or an assistant
278
+ // image, which has no producer here) stays a filename note.
279
+ if (role === 'user' && target.length > 0) {
280
+ images.push({ path: isAbsolute(target) ? target : join(baseDir, target), name: alt })
281
+ } else {
282
+ notes.push(`附件:${alt}`)
283
+ }
284
+ return ''
285
+ })
286
+ body = body.replace(/^_【CONTENT_RISK】_[^\n]*$/gm, '')
287
+ body = body.replace(/^\s*---\s*$/gm, '')
288
+ body = body.replace(/^\*msg [^*]*\*\s*$/m, '')
289
+ body = body.replace(/\n{3,}/g, '\n\n')
290
+ return { role, text: trim(body), reasoning: joinText(reasoning), notes, images, files }
291
+ }
292
+
293
+ /**
294
+ * Markdown export produced by the exporter GUI (`<dir>/<id>_<title>/<title>.md`):
295
+ * `## 🧑 用户` / `## 🤖 AI` sections, thinking in `<details>`, search results and
296
+ * opened pages as inline blocks. Disclaimers and attachment images become notes.
297
+ */
298
+ function fromMarkdownExport(markdown , baseDir , warnings ) {
299
+ const lines = markdown.replace(/\r\n/g, '\n').split('\n')
300
+ const titleLine = lines.find((line) => line.startsWith('# '))
301
+ const createdAtText = markdown.match(/\*\*创建\*\*\s*(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})/)
302
+ const createdAt = createdAtText === null
303
+ ? undefined
304
+ : new Date(
305
+ Number(createdAtText[1]),
306
+ Number(createdAtText[2]) - 1,
307
+ Number(createdAtText[3]),
308
+ Number(createdAtText[4]),
309
+ Number(createdAtText[5]),
310
+ Number(createdAtText[6]),
311
+ ).getTime()
312
+ const messages = []
313
+ let role
314
+ let buffer = []
315
+ const flush = () => {
316
+ if (role === undefined) return
317
+ const message = markdownMessage(buffer.join('\n'), role, baseDir)
318
+ if (message.text.length > 0 || message.reasoning.length > 0 || message.notes.length > 0
319
+ || message.images.length > 0 || message.files.length > 0) {
320
+ messages.push(message)
321
+ } else warnings.push('跳过一条空消息')
322
+ }
323
+ let started = false
324
+ for (const line of lines) {
325
+ if (!started) {
326
+ if (line.trim() === '## 对话') started = true
327
+ continue
328
+ }
329
+ if (line.trim() === '## 🧑 用户') {
330
+ flush()
331
+ role = 'user'
332
+ buffer = []
333
+ continue
334
+ }
335
+ if (line.trim() === '## 🤖 AI') {
336
+ flush()
337
+ role = 'assistant'
338
+ buffer = []
339
+ continue
340
+ }
341
+ buffer.push(line)
342
+ }
343
+ flush()
344
+ return {
345
+ kind: 'markdown-export',
346
+ title: titleLine === undefined ? '' : trim(titleLine.slice(2)),
347
+ createdAt,
348
+ messages,
349
+ warnings,
350
+ }
351
+ }
352
+
353
+ function detectAndNormalize(document , warnings ) {
354
+ if (!isRecord(document)) throw new Error('文件内容必须是一个 JSON 对象')
355
+ const format = str(document.format)
356
+ if (format === 'dsh-transcript/1') {
357
+ return {
358
+ kind: 'dsh-transcript/1',
359
+ title: str(document.title),
360
+ createdAt: parseTime(document.createdAt),
361
+ messages: fromTranscriptFormat(document, warnings),
362
+ warnings,
363
+ }
364
+ }
365
+ const messages = Array.isArray(document.messages) ? document.messages : []
366
+ const looksDeepSeek = messages.some((m) => isRecord(m) && Array.isArray(m.fragments))
367
+ || messages.some((m) => isRecord(m) && (str(m.role) === 'USER' || str(m.role) === 'ASSISTANT'))
368
+ if (looksDeepSeek) {
369
+ return {
370
+ kind: 'deepseek-client-export',
371
+ title: str(document.title),
372
+ createdAt: parseTime(document.inserted_at) ?? parseTime(document.created_at),
373
+ messages: fromDeepSeekExport(document, warnings),
374
+ warnings,
375
+ }
376
+ }
377
+ if (messages.length > 0) {
378
+ return {
379
+ kind: 'generic-messages',
380
+ title: str(document.title),
381
+ createdAt: parseTime(document.created_at) ?? parseTime(document.createdAt),
382
+ messages: fromGenericMessages(document, warnings),
383
+ warnings,
384
+ }
385
+ }
386
+ throw new Error('无法识别的记录格式:需要 dsh-transcript/1、DeepSeek 客户端导出,或 {messages:[{role,content}]}')
387
+ }
388
+
389
+ /* ------------------------------------------------------------------ */
390
+ /* Turn planning */
391
+ /* ------------------------------------------------------------------ */
392
+
393
+ function planTurns(messages , warnings ) {
394
+ const turns = []
395
+ let pending
396
+ for (const message of messages) {
397
+ if (message.role === 'user') {
398
+ if (pending !== undefined) {
399
+ warnings.push('有用户消息没有得到回答,已按单轮保留')
400
+ turns.push({ user: pending, assistant: undefined })
401
+ }
402
+ pending = message
403
+ continue
404
+ }
405
+ if (pending === undefined) {
406
+ warnings.push('跳过开头没有提问的回答')
407
+ continue
408
+ }
409
+ turns.push({ user: pending, assistant: message })
410
+ pending = undefined
411
+ }
412
+ if (pending !== undefined) warnings.push('最后一条用户消息没有回答,已忽略')
413
+ return turns
414
+ }
415
+
416
+ /* ------------------------------------------------------------------ */
417
+ /* Attachment hydration */
418
+ /* ------------------------------------------------------------------ */
419
+
420
+ /** Attachment store batch cap per admitted message. */
421
+ const MAX_IMAGES_PER_BATCH = 20
422
+
423
+ /** Detect the encoded image type from magic bytes; the store cross-checks it. */
424
+ function sniffImageMediaType(data ) {
425
+ if (data.length >= 8 && data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) return 'image/png'
426
+ if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return 'image/jpeg'
427
+ if (data.length >= 4 && data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x38) return 'image/gif'
428
+ if (data.length >= 12 && data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46
429
+ && data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50) return 'image/webp'
430
+ return undefined
431
+ }
432
+
433
+ /**
434
+ * Replace referenced image files with durable attachment references so the
435
+ * seeded user messages carry real image blocks the model can see. Any image
436
+ * that cannot be admitted degrades back to a filename note with a warning.
437
+ * @param messages - normalized messages, mutated in place.
438
+ * @param ctx - plugin context (needs the `attachments` service).
439
+ * @param warnings - shared warning sink.
440
+ */
441
+ async function hydrateImages(messages , ctx , warnings ) {
442
+ const store = ctx?.attachments
443
+ for (const message of messages) {
444
+ if (message.images.length === 0) continue
445
+ if (store === undefined || typeof store.saveImages !== 'function') {
446
+ for (const image of message.images) pushUnique(message.notes, `附件:${image.name}`)
447
+ warnings.push('当前环境没有附件服务(attachments),图片已降级为文件名注记')
448
+ message.images = []
449
+ continue
450
+ }
451
+ const kept = []
452
+ for (let offset = 0; offset < message.images.length; offset += MAX_IMAGES_PER_BATCH) {
453
+ const batch = message.images.slice(offset, offset + MAX_IMAGES_PER_BATCH)
454
+ const inputs = []
455
+ const usable = []
456
+ for (const image of batch) {
457
+ try {
458
+ const bytes = await readFile(image.path)
459
+ const mediaType = sniffImageMediaType(bytes)
460
+ if (mediaType === undefined) throw new Error('不是可识别的 PNG/JPEG/WebP/GIF 图片')
461
+ inputs.push({ data: bytes, mediaType, name: image.name })
462
+ usable.push(image)
463
+ } catch (error ) {
464
+ pushUnique(message.notes, `附件:${image.name}`)
465
+ warnings.push(`附件 ${image.name} 未能导入:${error?.message ?? String(error)}`)
466
+ }
467
+ }
468
+ if (inputs.length === 0) continue
469
+ try {
470
+ const refs = await store.saveImages(inputs)
471
+ usable.forEach((image, index) => kept.push({ ...image, ref: refs[index] }))
472
+ } catch (error ) {
473
+ for (const image of usable) pushUnique(message.notes, `附件:${image.name}`)
474
+ warnings.push(`附件 ${usable.map((image) => image.name).join('、')} 未能导入:${error?.message ?? String(error)}`)
475
+ }
476
+ }
477
+ message.images = kept
478
+ }
479
+ }
480
+
481
+ /**
482
+ * Compare attachment names the way a person would: the DeepSeek client appends
483
+ * a duplicate marker (`广义生命论 (10086).docx`) that the local file lacks.
484
+ * @param name - a referenced name or a supplied path.
485
+ * @returns a case-folded leaf name without the duplicate marker.
486
+ */
487
+ function normalizeFileName(name ) {
488
+ const leaf = name.slice(Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')) + 1)
489
+ return leaf.replace(/\s*\(\d+\)(?=\.[^.]*$)/, '').replace(/\s+/g, ' ').trim().toLowerCase()
490
+ }
491
+
492
+ /**
493
+ * Referenced attachments that still have no local bytes.
494
+ * @param turns - planned rounds.
495
+ * @returns missing references with their 1-based turn numbers.
496
+ */
497
+ function listMissingFiles(turns ) {
498
+ const missing = []
499
+ turns.forEach((turn, index) => {
500
+ for (const file of turn.user.files) {
501
+ if (file.path === undefined) missing.push({ name: file.name, size: file.size, turn: index + 1 })
502
+ }
503
+ })
504
+ return missing
505
+ }
506
+
507
+ /**
508
+ * Match user-supplied paths to referenced attachments by filename, so a record
509
+ * that only kept metadata can still get real bytes.
510
+ * @param turns - planned rounds, mutated in place.
511
+ * @param supplied - local paths the user handed over.
512
+ * @param warnings - shared warning sink.
513
+ */
514
+ function matchSuppliedFiles(turns , supplied , warnings ) {
515
+ const pending = new Map ()
516
+ for (const path of supplied) {
517
+ const key = normalizeFileName(path)
518
+ const list = pending.get(key)
519
+ if (list === undefined) pending.set(key, [path])
520
+ else list.push(path)
521
+ }
522
+ for (const turn of turns) {
523
+ for (const file of turn.user.files) {
524
+ if (file.path !== undefined) continue
525
+ const list = pending.get(normalizeFileName(file.name))
526
+ if (list === undefined || list.length === 0) continue
527
+ file.path = list.shift()
528
+ }
529
+ }
530
+ for (const list of pending.values()) {
531
+ for (const path of list) warnings.push(`附件 ${path} 在记录里没有对应的引用,已忽略`)
532
+ }
533
+ }
534
+
535
+ /**
536
+ * Store every referenced file that has local bytes as a durable attachment so
537
+ * seeded messages carry `file` blocks. Failed reads degrade to filename notes.
538
+ * @param turns - planned rounds, mutated in place.
539
+ * @param ctx - plugin context (needs the `attachments` service).
540
+ * @param warnings - shared warning sink.
541
+ */
542
+ async function hydrateFiles(turns , ctx , warnings ) {
543
+ const files = turns.flatMap((turn) => turn.user.files).filter((file) => file.path !== undefined)
544
+ if (files.length === 0) return
545
+ const store = ctx?.attachments
546
+ if (store === undefined || typeof store.saveFile !== 'function') {
547
+ for (const turn of turns) {
548
+ for (const file of turn.user.files) {
549
+ pushUnique(turn.user.notes, `附件:${file.name}`)
550
+ file.path = undefined
551
+ }
552
+ }
553
+ warnings.push('当前环境没有附件服务(attachments),文件附件已降级为文件名注记')
554
+ return
555
+ }
556
+ for (const turn of turns) {
557
+ for (const file of turn.user.files) {
558
+ if (file.path === undefined) continue
559
+ try {
560
+ file.ref = await store.saveFile({ data: await readFile(file.path), name: file.name })
561
+ } catch (error ) {
562
+ file.path = undefined
563
+ pushUnique(turn.user.notes, `附件:${file.name}`)
564
+ warnings.push(`附件 ${file.name} 未能导入:${error?.message ?? String(error)}`)
565
+ }
566
+ }
567
+ }
568
+ }
569
+
570
+ /* ------------------------------------------------------------------ */
571
+ /* Event construction */
572
+ /* ------------------------------------------------------------------ */
573
+
574
+ /**
575
+ * Split text into stream-sized deltas so the synthetic stream stays reasonable.
576
+ * Iterates by code point (for..of), never by UTF-16 code unit: splitting an
577
+ * emoji across two deltas leaves a lone surrogate at the end of one chunk, and
578
+ * replaying that history makes the request body unparsable ("unexpected end of
579
+ * hex escape") for the whole session — a permanent, unexplainable failure.
580
+ */
581
+ function deltas(text ) {
582
+ const size = 160
583
+ const parts = []
584
+ let part = ''
585
+ for (const codePoint of text) {
586
+ if (part.length + codePoint.length > size) {
587
+ parts.push(part)
588
+ part = ''
589
+ }
590
+ part += codePoint
591
+ }
592
+ if (part.length > 0) parts.push(part)
593
+ return parts
594
+ }
595
+
596
+ function streamFor(blocks , baseTime ) {
597
+ const records = []
598
+ let time = baseTime
599
+ blocks.forEach((block, index) => {
600
+ records.push({ type: 'chunk', time, chunk: { type: 'block-start', index, blockType: block.type } })
601
+ const text = typeof block.text === 'string' ? block.text : ''
602
+ for (const delta of deltas(text)) {
603
+ time += 10
604
+ records.push({
605
+ type: 'chunk',
606
+ time,
607
+ chunk: block.type === 'text'
608
+ ? { type: 'text-delta', index, text: delta }
609
+ : { type: 'reasoning-delta', index, text: delta },
610
+ })
611
+ }
612
+ records.push({ type: 'chunk', time, chunk: { type: 'block-end', index, block: { ...block } } })
613
+ time += 10
614
+ })
615
+ records.push({ type: 'chunk', time, chunk: { type: 'finish', reason: { kind: 'stop' } } })
616
+ return records
617
+ }
618
+
619
+ function assistantContent(message , options ) {
620
+ const blocks = []
621
+ const reasoning = trim(message.reasoning)
622
+ if (reasoning.length > 0 && options.reasoning === 'block') {
623
+ blocks.push({ type: 'reasoning', text: reasoning })
624
+ } else if (reasoning.length > 0 && options.reasoning === 'text') {
625
+ blocks.push({ type: 'text', text: `(以下这段是当时的思考过程)\n${reasoning}` })
626
+ }
627
+ const body = `${trim(message.text)}${options.keepToolNotes ? notesSection(message.notes) : ''}`
628
+ if (body.length > 0) blocks.push({ type: 'text', text: body })
629
+ return blocks
630
+ }
631
+
632
+ function userContent(message ) {
633
+ const text = trim(message.text)
634
+ const notes = message.notes.length > 0 ? notesSection(message.notes) : ''
635
+ const body = `${text}${notes}`.replace(/^\s+/, '')
636
+ const blocks = message.images
637
+ .filter((image) => image.ref !== undefined)
638
+ .map((image) => ({ type: 'image', attachment: image.ref }))
639
+ for (const file of message.files) {
640
+ if (file.ref !== undefined) blocks.push({ type: 'file', attachment: file.ref })
641
+ }
642
+ if (body.length > 0) blocks.push({ type: 'text', text: body })
643
+ if (blocks.length === 0) blocks.push({ type: 'text', text: '(空消息)' })
644
+ return blocks
645
+ }
646
+
647
+ /**
648
+ * Build the complete event batch: one closed turn per recorded round, with a
649
+ * placeholder empty system node at surface 0 (the loop replaces it with the
650
+ * rendered system prompt on the next step).
651
+ * Emits full event envelopes (`seq`/`time`/`type`/`data`/`surfaceOp`) because the
652
+ * batch is handed to the agent factory as a constructor SEED: only seeded history
653
+ * exists before the loop is built, so the loop's turn counter starts at the
654
+ * imported turn count instead of 0.
655
+ * @param turns - planned rounds.
656
+ * @param options - normalization options.
657
+ * @param now - base timestamp for the synthetic stream.
658
+ */
659
+ function buildSeed(turns , options , now ) {
660
+ const seed = []
661
+ const baseTime = Math.floor(now)
662
+ let seq = 0
663
+ const emit = (type , data , surfaceOp ) => {
664
+ seed.push(surfaceOp === undefined
665
+ ? { seq: seq++, time: baseTime, type, data }
666
+ : { seq: seq++, time: baseTime, type, data, surfaceOp })
667
+ }
668
+ const systemMessage = { id: randomUUID(), role: 'system', content: [], source: { kind: 'system-prompt' } }
669
+ turns.forEach((turn, index) => {
670
+ const turnNumber = index + 1
671
+ emit('turn/start', { turn: turnNumber })
672
+ emit('step/start', { turn: turnNumber, step: 1 })
673
+ if (index === 0) {
674
+ emit('system/message', { turn: turnNumber, step: 1, message: systemMessage }, 'append')
675
+ }
676
+ emit('user/message', { id: randomUUID(), role: 'user', content: userContent(turn.user), source: { kind: 'user' } }, 'append')
677
+ let closed = false
678
+ if (turn.assistant !== undefined) {
679
+ const content = assistantContent(turn.assistant, options)
680
+ if (content.length > 0) {
681
+ emit('assistant/message', {
682
+ turn: turnNumber,
683
+ step: 1,
684
+ message: {
685
+ id: randomUUID(),
686
+ role: 'assistant',
687
+ content,
688
+ source: { kind: 'model', provider: options.provider, model: options.model },
689
+ },
690
+ stream: streamFor(content, baseTime + index * 60_000),
691
+ }, 'append')
692
+ closed = true
693
+ }
694
+ }
695
+ emit('step/end', { turn: turnNumber, step: 1 })
696
+ emit('turn/end', { turn: turnNumber, reason: { kind: closed ? 'completed' : 'blocked' } })
697
+ })
698
+ return seed
699
+ }
700
+
701
+ /* ------------------------------------------------------------------ */
702
+ /* Estimates */
703
+ /* ------------------------------------------------------------------ */
704
+
705
+ /** Coarse token estimate: CJK characters count ~1, other characters ~0.3. */
706
+ function estimateTokens(messages ) {
707
+ let total = 0
708
+ for (const message of messages) {
709
+ const text = `${message.text}${message.reasoning}${message.notes.join('')}`
710
+ for (const char of text) total += char.charCodeAt(0) > 0x2e80 ? 1 : 0.3
711
+ }
712
+ return Math.ceil(total)
713
+ }
714
+
715
+ function totalChars(messages ) {
716
+ let total = 0
717
+ for (const message of messages) total += `${message.text}${message.reasoning}${message.notes.join('')}`.length
718
+ return total
719
+ }
720
+
721
+ /* ------------------------------------------------------------------ */
722
+ /* Tool card (DSH / DSHgo) */
723
+ /* ------------------------------------------------------------------ */
724
+
725
+ /**
726
+ * Build a DSHgo-native tool card, guarding every rule that would otherwise fail
727
+ * the whole tool call (throwing builder, non-lossless JSON, 8 KiB budget).
728
+ */
729
+ function toolCard(build ) {
730
+ try {
731
+ const view = build()
732
+ const text = JSON.stringify(view)
733
+ if (text === undefined || Buffer.byteLength(text, 'utf8') > TOOL_CARD_MAX_BYTES) return {}
734
+ return { 'dsh-go/view': JSON.parse(text) }
735
+ } catch {
736
+ return {}
737
+ }
738
+ }
739
+
740
+ function importView(value ) {
741
+ const awaiting = value.needsAttachments === true && value.dryRun !== true
742
+ return {
743
+ type: 'stack',
744
+ title: awaiting
745
+ ? `需要确认附件:${value.title || '未命名记录'}`
746
+ : value.dryRun ? `预演:${value.title || '未命名记录'}` : `已导入「${value.title || '聊天记录'}」`,
747
+ children: [
748
+ {
749
+ type: 'row',
750
+ children: [
751
+ { type: 'metric', label: '轮次', value: `${value.turns}` },
752
+ { type: 'metric', label: '消息', value: `${value.messages}` },
753
+ { type: 'metric', label: '约', value: `${formatNumber(value.approxTokens)} tok` },
754
+ ],
755
+ },
756
+ {
757
+ type: 'text',
758
+ tone: 'muted',
759
+ text: awaiting
760
+ ? `记录里 ${value.missingFiles.length} 个附件不在导出包里,等待提供路径或选择跳过`
761
+ : value.dryRun ? `来源:${value.kind}` : `新会话 ${value.sessionId},打开它即可继续这段对话`,
762
+ },
763
+ ],
764
+ }
765
+ }
766
+
767
+ function formatNumber(value ) {
768
+ return value.toLocaleString('en-US')
769
+ }
770
+
771
+ /* ------------------------------------------------------------------ */
772
+ /* Tool implementation */
773
+ /* ------------------------------------------------------------------ */
774
+
775
+ function renderSummary(value ) {
776
+ const lines = []
777
+ const imageNote = value.images > 0 ? `,含 ${value.images} 张附件图片` : ''
778
+ const fileNote = value.files > 0 ? `,含 ${value.files} 个文件附件` : ''
779
+ if (value.needsAttachments === true && value.dryRun !== true) {
780
+ lines.push(`这份记录引用了 ${value.missingFiles.length} 个导出包没有携带的非图片附件,所以还没有导入:`)
781
+ for (const item of value.missingFiles) lines.push(`- ${item}`)
782
+ lines.push('先问用户手上有哪些文件:有的话让用户把本地路径发来,带上 files 参数(按文件名自动放回原来那条消息)重新调用;用户不提供或不想放的话,带上 allowMissingAttachments=true 重新调用,会只保留文件名注记后正常导入。')
783
+ if (value.warnings.length > 0) lines.push(`提示:${value.warnings.join(';')}`)
784
+ return lines.join('\n')
785
+ }
786
+ if (value.dryRun) {
787
+ lines.push(`预演完成:来源格式 ${value.kind},${value.turns} 轮 / ${value.messages} 条消息${imageNote}${fileNote},约 ${formatNumber(value.approxTokens)} tokens(${formatNumber(value.chars)} 字符)。`)
788
+ lines.push('尚未写入任何会话。确认无误后请用 dryRun=false 重新调用。')
789
+ if (value.needsAttachments === true) {
790
+ lines.push(`注意:${value.missingFiles.length} 个非图片附件不在导出包里(${value.missingFiles.join(';')})。正式导入前需要用户提供本地路径(files 参数),或明确跳过(allowMissingAttachments=true)。`)
791
+ }
792
+ } else {
793
+ lines.push(`已导入 ${value.turns} 轮 / ${value.messages} 条消息${imageNote}${fileNote}(约 ${formatNumber(value.approxTokens)} tokens)到新会话 ${value.sessionId}。`)
794
+ lines.push('这段历史属于那个新会话,不属于当前会话。请在会话列表里打开它再继续对话;当前会话不会出现这些记录。')
795
+ }
796
+ if (value.warnings.length > 0) lines.push(`提示:${value.warnings.join(';')}`)
797
+ return lines.join('\n')
798
+ }
799
+
800
+ async function resolvePath(path , exec ) {
801
+ if (/^[a-zA-Z]:[\\/]/.test(path) || path.startsWith('\\\\') || isAbsolute(path)) return path
802
+ const cwd = str(exec?.agent?.session?.header?.cwd) || process.cwd()
803
+ const separator = cwd.includes('\\') ? '\\' : '/'
804
+ return `${cwd.replace(/[\\/]$/, '')}${separator}${path.replace(/^\.?[\\/]/, '')}`
805
+ }
806
+
807
+ /** Resolve a file or an export directory to the one session record inside it. */
808
+ async function pickRecordFile(input ) {
809
+ const info = await stat(input).catch(() => null)
810
+ if (info === null) throw new Error(`路径不存在:${input}`)
811
+ if (info.isFile()) return input
812
+ if (!info.isDirectory()) throw new Error(`不是文件也不是目录:${input}`)
813
+ const entries = await readdir(input, { withFileTypes: true })
814
+ const isSessionMarkdown = (name ) => name.toLowerCase().endsWith('.md') && !name.startsWith('_')
815
+ const candidates = entries
816
+ .filter((entry) => entry.isFile() && isSessionMarkdown(entry.name))
817
+ .map((entry) => join(input, entry.name))
818
+ if (candidates.length === 0) {
819
+ for (const entry of entries) {
820
+ if (!entry.isDirectory()) continue
821
+ const nested = await readdir(join(input, entry.name), { withFileTypes: true }).catch(() => [])
822
+ for (const file of nested) {
823
+ if (file.isFile() && isSessionMarkdown(file.name)) candidates.push(join(input, entry.name, file.name))
824
+ }
825
+ }
826
+ }
827
+ if (candidates.length === 0) throw new Error('目录里没有找到导出的会话 .md 文件')
828
+ if (candidates.length > 1) throw new Error(`目录里有多个会话记录,请指定其中一个:${candidates.join(';')}`)
829
+ return candidates[0]
830
+ }
831
+
832
+ async function runImport(args , exec , ctx ) {
833
+ const warnings = []
834
+ const filePath = await resolvePath(str(args.path), exec)
835
+ const recordFile = await pickRecordFile(filePath)
836
+ let transcript
837
+ if (recordFile.toLowerCase().endsWith('.md')) {
838
+ let markdown
839
+ try {
840
+ markdown = await readFile(recordFile, 'utf8')
841
+ } catch (error ) {
842
+ throw new Error(`无法读取记录文件 ${recordFile}:${error?.message ?? String(error)}`)
843
+ }
844
+ transcript = fromMarkdownExport(markdown, dirname(recordFile), warnings)
845
+ } else {
846
+ let document
847
+ try {
848
+ document = JSON.parse(await readFile(recordFile, 'utf8'))
849
+ } catch (error ) {
850
+ throw new Error(`无法读取记录文件 ${recordFile}:${error?.message ?? String(error)}`)
851
+ }
852
+ transcript = detectAndNormalize(document, warnings)
853
+ }
854
+ const turns = planTurns(transcript.messages, warnings)
855
+ if (turns.length === 0) throw new Error('没有可导入的对话轮次(需要至少一条提问和一条回答)')
856
+ const firstLine = trim(turns[0].user.text).split('\n')[0]
857
+ const derivedTitle = firstLine.length > 24 ? `${firstLine.slice(0, 24)}…` : firstLine
858
+
859
+ const provider = str(args.provider) || str(exec?.agent?.options?.provider) || DEFAULT_PROVIDER
860
+ const model = str(args.model) || str(exec?.agent?.options?.model) || DEFAULT_MODEL
861
+ const supplied = []
862
+ for (const raw of Array.isArray(args.files) ? args.files : []) {
863
+ const value = str(raw)
864
+ if (value.length > 0) supplied.push(await resolvePath(value, exec))
865
+ }
866
+ matchSuppliedFiles(turns, supplied, warnings)
867
+ const options = {
868
+ reasoning: args.reasoning === 'text' || args.reasoning === 'drop' ? args.reasoning : 'block',
869
+ keepToolNotes: args.keepToolNotes !== false,
870
+ preserveTime: args.preserveTime === true,
871
+ provider,
872
+ model,
873
+ allowMissingAttachments: args.allowMissingAttachments === true,
874
+ files: supplied,
875
+ }
876
+
877
+ const messages = turns.flatMap((turn) => (turn.assistant === undefined ? [turn.user] : [turn.user, turn.assistant]))
878
+ const missing = listMissingFiles(turns)
879
+ const base = {
880
+ kind: transcript.kind,
881
+ title: trim(str(args.title)) || transcript.title || derivedTitle,
882
+ turns: turns.length,
883
+ messages: messages.length,
884
+ images: messages.reduce((total, message) => total + message.images.length, 0),
885
+ files: turns.reduce((total, turn) => total + turn.user.files.length, 0),
886
+ missingFiles: missing.map((file) => `${file.name}${file.size === undefined ? '' : `(${file.size})`}(第 ${file.turn} 轮)`),
887
+ needsAttachments: missing.length > 0,
888
+ chars: totalChars(messages),
889
+ approxTokens: estimateTokens(messages),
890
+ warnings,
891
+ }
892
+
893
+ if (args.dryRun === true) return { ...base, dryRun: true }
894
+
895
+ // The record names files the export did not carry. Ask before writing anything:
896
+ // the caller decides whether to hand over local paths or skip them.
897
+ if (base.needsAttachments && !options.allowMissingAttachments) return { ...base, dryRun: false }
898
+
899
+ // Store the referenced images now: the seed is built synchronously and must
900
+ // already contain the durable attachment references.
901
+ await hydrateImages(messages, ctx, warnings)
902
+ base.images = messages.reduce((total, message) => total + message.images.filter((image) => image.ref !== undefined).length, 0)
903
+ await hydrateFiles(turns, ctx, warnings)
904
+ base.files = turns.reduce((total, turn) => total + turn.user.files.filter((file) => file.ref !== undefined).length, 0)
905
+ // Skipped attachments stay visible as notes so the history does not silently
906
+ // lose something the original conversation had.
907
+ for (const turn of turns) {
908
+ for (const file of turn.user.files) {
909
+ if (file.path === undefined && file.ref === undefined) {
910
+ pushUnique(turn.user.notes, `附件:${file.name}${file.size === undefined ? '' : `(${file.size})`}`)
911
+ }
912
+ }
913
+ }
914
+
915
+ const cwd = str(args.cwd) || str(exec?.agent?.session?.header?.cwd)
916
+ // A fresh session starts on the deployment default preset. That default may
917
+ // not carry the tools the source conversation used (web_search / web_fetch),
918
+ // and the App has no preset picker, so an imported session would silently
919
+ // lose them. Inherit the preset of the importing session instead: the agent
920
+ // factory mounts it through `setup` before the agent is published.
921
+ const presets = ctx.get?.('agentPresets')
922
+ let presetId
923
+ if (presets !== undefined) {
924
+ const requested = str(args.preset) || str(presets.presetForSession?.(exec?.agent?.session)) || presets.defaultId
925
+ try {
926
+ presetId = (await presets.resolve(requested)).id
927
+ } catch (error ) {
928
+ warnings.push(`未找到会话预设 ${requested},改用默认预设:${error?.message ?? String(error)}`)
929
+ try {
930
+ presetId = (await presets.resolve()).id
931
+ } catch {
932
+ presetId = undefined
933
+ }
934
+ }
935
+ }
936
+ // Session lists sort by the newest event time. Preserving the record's old
937
+ // timestamps buries the imported session at the bottom, so by default the
938
+ // history is stamped "now"; preserveTime keeps the original clock.
939
+ const baseTime = options.preserveTime ? transcript.createdAt ?? Date.now() : Date.now()
940
+ const seed = buildSeed(turns, options, baseTime)
941
+ // Create through the agent factory, not ctx.sessions.create(): only the
942
+ // factory owns the persistence write handle, so a session created there is
943
+ // durable and survives a restart (a store-only session persists nothing).
944
+ // The imported log travels as the constructor seed so the loop is built on
945
+ // top of it and continues the turn sequence instead of restarting at turn 1.
946
+ const sessionId = `session-${randomUUID()}`
947
+ let handle
948
+ try {
949
+ const meta = {
950
+ ...(cwd.length > 0 ? { cwd } : {}),
951
+ ...(presetId === undefined ? {} : { agentPreset: presetId }),
952
+ }
953
+ handle = await ctx.agents.create({
954
+ sessionId,
955
+ seed,
956
+ agentOptions: { provider, model },
957
+ ...(presetId === undefined ? {} : {
958
+ setup: async (agentCtx) => { await presets.mount(agentCtx, presetId) },
959
+ }),
960
+ ...(Object.keys(meta).length > 0 ? { meta } : {}),
961
+ })
962
+ } catch (error ) {
963
+ throw new Error(`创建新会话失败:${error?.message ?? String(error)}`)
964
+ }
965
+ const session = (handle?.agent ?? handle)?.session
966
+ if (session === undefined) throw new Error('创建新会话失败:factory 没有返回 session')
967
+ if (base.title.length > 0) {
968
+ // Seeded events never publish on session/event, so the title plugin never
969
+ // sees the imported first prompt; pin the title explicitly instead.
970
+ try {
971
+ session.append('session/title', { title: base.title, messageSeqs: [], source: { kind: 'user' } })
972
+ } catch {
973
+ base.warnings.push('未能写入会话标题(该 profile 可能没有挂载 session-title)')
974
+ }
975
+ }
976
+ try {
977
+ await ctx.sessions.flush(session)
978
+ } catch (error ) {
979
+ warnings.push(`持久化刷新失败:${error?.message ?? String(error)}`)
980
+ }
981
+ return { ...base, dryRun: false, sessionId: String(session.id) }
982
+ }
983
+
984
+ const parameters = {
985
+ type: 'object',
986
+ properties: {
987
+ path: { type: 'string', description: '聊天记录文件的路径(绝对路径,或相对当前工作目录)' },
988
+ dryRun: { type: 'boolean', description: '只解析并估算,不写会话;默认 false' },
989
+ reasoning: { type: 'string', enum: ['block', 'text', 'drop'], description: '思考链处理:block=原生 reasoning 块,text=并入正文,drop=丢弃;默认 block' },
990
+ keepToolNotes: { type: 'boolean', description: '是否把检索/打开网页/附件记录降级为正文注记;默认 true' },
991
+ preserveTime: { type: 'boolean', description: '是否保留记录里的原始时间戳;默认 false(用当前时间,新会话才会排在列表顶部)' },
992
+ title: { type: 'string', description: '新会话标题,默认用记录自带的标题或首条消息' },
993
+ provider: { type: 'string', description: '写入 assistant 消息的 provider 标记,默认沿用当前会话' },
994
+ model: { type: 'string', description: '写入 assistant 消息的 model 标记,默认沿用当前会话' },
995
+ cwd: { type: 'string', description: '新会话的工作目录,默认沿用当前会话' },
996
+ preset: { type: 'string', description: '新会话使用的 agent 预设 id,默认继承发起导入的会话(同一预设才有 web_search/web_fetch 等工具)' },
997
+ files: {
998
+ type: 'array',
999
+ items: { type: 'string' },
1000
+ description: '用户提供的附件本地路径(绝对路径或相对当前工作目录)。按文件名匹配记录里引用、但导出包没有携带的非图片附件,放回原来那条消息',
1001
+ },
1002
+ allowMissingAttachments: {
1003
+ type: 'boolean',
1004
+ description: '记录引用了导出包没带的附件时,是否跳过它们直接导入(只保留文件名注记);默认 false,会先返回待确认列表让用户决定',
1005
+ },
1006
+ },
1007
+ required: ['path'],
1008
+ additionalProperties: false,
1009
+ }
1010
+
1011
+ const outputSchema = {
1012
+ type: 'object',
1013
+ properties: {
1014
+ dryRun: { type: 'boolean' },
1015
+ kind: { type: 'string' },
1016
+ title: { type: 'string' },
1017
+ sessionId: { type: 'string' },
1018
+ turns: { type: 'number' },
1019
+ messages: { type: 'number' },
1020
+ images: { type: 'number' },
1021
+ files: { type: 'number' },
1022
+ missingFiles: { type: 'array', items: { type: 'string' } },
1023
+ needsAttachments: { type: 'boolean' },
1024
+ chars: { type: 'number' },
1025
+ approxTokens: { type: 'number' },
1026
+ warnings: { type: 'array', items: { type: 'string' } },
1027
+ },
1028
+ required: ['dryRun', 'kind', 'title', 'turns', 'messages', 'images', 'files', 'missingFiles', 'needsAttachments', 'chars', 'approxTokens', 'warnings'],
1029
+ additionalProperties: false,
1030
+ }
1031
+
1032
+ export const name = PLUGIN_NAME
1033
+ export const inject = ['tools', 'sessions', 'agents', 'attachments']
1034
+
1035
+ export function apply(ctx ) {
1036
+ ctx.tools.register({
1037
+ name: TOOL_NAME,
1038
+ description: [
1039
+ '把一份已有的聊天记录导入成一个全新的 DSH 会话,让那段对话看起来原本就发生在这个会话里。',
1040
+ 'path 可以是 dsh-transcript/1 文件、DeepSeek 客户端导出(chat_sessions/*.json)、通用 {messages:[{role,content}]}、或导出器生成的 Markdown 会话文件及其所在目录。',
1041
+ '导入只写新会话,不写当前会话;先 dryRun=true 看轮数与 token 估算,再正式导入。',
1042
+ '记录里的思考链默认写成 reasoning 块;检索/打开网页降级为正文注记,图片附件会存成真实附件并写成 image 块(失败时才降级为文件名注记)。',
1043
+ '记录引用、但导出包没带的非图片附件(docx/pdf/txt 等)会先返回待确认列表:先问用户手上有哪些文件,把用户给的本地路径放进 files 再调用;用户不提供时用 allowMissingAttachments=true 跳过。',
1044
+ ].join(' '),
1045
+ parameters,
1046
+ output: {
1047
+ schema: outputSchema,
1048
+ render: (_args , value ) => [{ type: 'text', text: renderSummary(value) }],
1049
+ presentationMeta: (_args , value ) => toolCard(() => importView(value)),
1050
+ },
1051
+ presentCall: (args ) => ({
1052
+ card: 'generic',
1053
+ title: '导入聊天记录',
1054
+ kind: 'read',
1055
+ rawInput: str(args.path),
1056
+ locations: [{ path: str(args.path) }],
1057
+ }),
1058
+ async execute(args , exec ) {
1059
+ return runImport(args, exec, ctx)
1060
+ },
1061
+ })
1062
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "dshgo-transcript-import",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Import an existing chat transcript into a brand-new DSH session as real session events. · 把已有聊天记录导入成一个全新的 DSH 会话。",
5
+ "type": "module",
6
+ "main": "./lib/plugin.js",
7
+ "exports": {
8
+ ".": "./lib/plugin.js",
9
+ "./cordis.patch.yml": "./cordis.patch.yml",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "files": [
13
+ "lib",
14
+ "cordis.patch.yml",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "engines": {
19
+ "node": ">=22.18",
20
+ "dsh": ">=0.2.0"
21
+ },
22
+ "keywords": [
23
+ "deepseek",
24
+ "harness",
25
+ "dsh",
26
+ "dsh-plugin",
27
+ "transcript",
28
+ "import",
29
+ "chat-history",
30
+ "session",
31
+ "attachment"
32
+ ],
33
+ "license": "MIT",
34
+ "dsh": {
35
+ "bundle": {
36
+ "patch": "./cordis.patch.yml"
37
+ }
38
+ },
39
+ "dshGo": {
40
+ "v": 1,
41
+ "title": {
42
+ "zh": "聊天记录导入(修复版)",
43
+ "en": "Transcript Import (Fixed)"
44
+ },
45
+ "contributes": {}
46
+ },
47
+ "publishConfig": {
48
+ "registry": "https://registry.npmjs.org/"
49
+ }
50
+ }