dsh-topic-split 0.0.0-stage → 0.12.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.
@@ -0,0 +1,4 @@
1
+ # dsh-topic-split:挂载插件(host 半 + client 半)
2
+ - insert:
3
+ - id: dsh-topic-split
4
+ name: dsh-topic-split
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" role="img" aria-label="Split a conversation into two sessions">
2
+ <rect x="6" y="10" width="52" height="44" rx="10" fill="#1f6feb" opacity="0.18"/>
3
+ <rect x="12" y="16" width="18" height="32" rx="5" fill="#1f6feb"/>
4
+ <rect x="34" y="16" width="18" height="32" rx="5" fill="#58a6ff"/>
5
+ <rect x="31" y="16" width="2" height="32" rx="1" fill="#0b1220" opacity="0.55"/>
6
+ </svg>
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Topic split for conversations",
4
+ "description": "Pick content by topic or exact turns from a long conversation and export it as independent, resumable sessions. Adds a Split control above the composer, with coverage checks, preview, and optional remove-and-archive. Not a split-screen view."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "对话主题拆分",
4
+ "description": "从长会话中按主题或任意轮次挑选内容,导出为可继续的独立会话;在输入框上方提供「拆分」入口,支持覆盖率校验、预览,以及导出后剪除并归档;不是分屏。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "dsh-topic-split",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.12.0",
4
+ "description": "从长会话中按主题或任意轮次挑选内容,导出为可继续的独立会话;支持覆盖率核对、导出后剪除并归档;不是分屏。",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./client": "./client/index.js",
10
+ "./locale/*.json": "./locale/*.json",
11
+ "./icon": "./icon.svg"
12
+ },
13
+ "files": [
14
+ "src",
15
+ "client",
16
+ "locale",
17
+ "icon.svg",
18
+ "cordis.patch.yml",
19
+ "README.md",
20
+ "CHANGELOG.md",
21
+ "SECURITY.md",
22
+ "LICENSE"
23
+ ],
24
+ "scripts": {
25
+ "test": "node scripts/test-all.mjs",
26
+ "lint": "node scripts/style-check.mjs",
27
+ "validate": "node scripts/validate-manifest.mjs",
28
+ "check": "npm run lint && npm run validate && npm test",
29
+ "test:node": "node --test"
30
+ },
31
+ "engines": {
32
+ "node": ">=22",
33
+ "dsh": ">=0.2.2-rc.5 <0.3.0"
34
+ },
35
+ "keywords": [
36
+ "dsh",
37
+ "dsh-plugin",
38
+ "deepseek-harness",
39
+ "session",
40
+ "topic",
41
+ "split",
42
+ "export"
43
+ ],
44
+ "author": "qq666-star",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/qq666-star/dsh-topic-split.git"
48
+ },
49
+ "homepage": "https://github.com/qq666-star/dsh-topic-split#readme",
50
+ "bugs": {
51
+ "url": "https://github.com/qq666-star/dsh-topic-split/issues"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "license": "GPL-3.0-only",
57
+ "dsh": {
58
+ "bundle": {
59
+ "patch": "./cordis.patch.yml"
60
+ },
61
+ "client": {
62
+ "platform": "web",
63
+ "inject": [
64
+ "@deepseek-ai/dsh-client-ui-conversation"
65
+ ]
66
+ }
67
+ }
68
+ }
package/src/config.js ADDED
@@ -0,0 +1,141 @@
1
+ import { ERR, SessionSplitError } from './errors.js'
2
+
3
+ /** 默认配置:所有可调项集中于此。 */
4
+ export const DEFAULTS = Object.freeze({
5
+ maxCompressedBytes: 80 * 1024 * 1024,
6
+ maxInflatedBytes: 300 * 1024 * 1024,
7
+ cacheEntries: 8,
8
+ minSegmentTurns: 3,
9
+ minSegmentChars: 4000,
10
+ maxRanges: 50,
11
+ httpRoutes: 'token',
12
+ httpToken: '',
13
+ httpRateLimitPerMin: 60,
14
+ httpExportPerMin: 6,
15
+ exposeTitles: true,
16
+ semantic: Object.freeze({
17
+ backend: 'auto',
18
+ provider: 'deepseek-official',
19
+ model: 'deepseek-flash',
20
+ maxOutputTokens: 900,
21
+ timeoutMs: 25000,
22
+ retries: 1,
23
+ summaryChars: 120,
24
+ maxTurnsInPrompt: 600,
25
+ httpBaseUrl: '',
26
+ httpModel: '',
27
+ httpKeyEnv: 'DSH_SESSION_SPLIT_JUDGE_KEY',
28
+ }),
29
+ topics: Object.freeze([
30
+ ['桌宠/形象/语音', '桌宠|美杜莎|动作|形象|立绘|抠图|语音|音色|台词|表情包'],
31
+ ['网页背景', '背景图|聊天背景|侧栏背景|注入|CSS|样式|去水印|虚化'],
32
+ ['视频生成', '视频|通义万相|抽帧|帧率|mp4|gif|播放器'],
33
+ ['参赛方案', '参赛|大赛|创意组|方案[ABCD]|奖项|成本|具身|MuJoCo|机器人|仿真'],
34
+ ['会话管理/插件', '会话|分叉|独立对话|插件|profile|schema|工具注册'],
35
+ ['系统维护', '磁盘|C盘|D盘|软件|卸载|迁移|junction|VS|Ollama|豆包'],
36
+ ['密钥/隐私', '密钥|API ?Key|额度|账单|环境变量|权限|隐私'],
37
+ ]),
38
+ })
39
+
40
+ const NUMERIC_KEYS = [
41
+ ['maxCompressedBytes', 1, 2 ** 40],
42
+ ['maxInflatedBytes', 1, 2 ** 40],
43
+ ['cacheEntries', 1, 64],
44
+ ['minSegmentTurns', 1, 1000],
45
+ ['minSegmentChars', 1, 10 ** 7],
46
+ ['maxRanges', 1, 1000],
47
+ ]
48
+
49
+ const SEMANTIC_NUMERIC_KEYS = [
50
+ ['maxOutputTokens', 64, 8192],
51
+ ['timeoutMs', 1000, 120000],
52
+ ['retries', 0, 3],
53
+ ['summaryChars', 20, 500],
54
+ ['maxTurnsInPrompt', 10, 5000],
55
+ ]
56
+
57
+ const BACKENDS = ['auto', 'kernel', 'http', 'off']
58
+ const HTTP_ROUTE_MODES = ['off', 'token']
59
+
60
+ /** 从环境变量读取 HTTP 面板开关(未设置的保持原值)。 */
61
+ function applyHttpEnv(cfg) {
62
+ const env = process.env
63
+ if (env.DSH_SESSION_SPLIT_HTTP) cfg.httpRoutes = env.DSH_SESSION_SPLIT_HTTP
64
+ return cfg
65
+ }
66
+
67
+ /** 从环境变量读取判断模型覆盖项(未设置的保持原值)。 */
68
+ function applySemanticEnv(semantic) {
69
+ const env = process.env
70
+ if (env.DSH_SESSION_SPLIT_JUDGE) semantic.backend = env.DSH_SESSION_SPLIT_JUDGE
71
+ if (env.DSH_SESSION_SPLIT_JUDGE_PROVIDER) semantic.provider = env.DSH_SESSION_SPLIT_JUDGE_PROVIDER
72
+ if (env.DSH_SESSION_SPLIT_JUDGE_MODEL) semantic.model = env.DSH_SESSION_SPLIT_JUDGE_MODEL
73
+ if (env.DSH_SESSION_SPLIT_JUDGE_URL) semantic.httpBaseUrl = env.DSH_SESSION_SPLIT_JUDGE_URL
74
+ if (env.DSH_SESSION_SPLIT_JUDGE_HTTP_MODEL) semantic.httpModel = env.DSH_SESSION_SPLIT_JUDGE_HTTP_MODEL
75
+ if (env.DSH_SESSION_SPLIT_JUDGE_KEY_ENV) semantic.httpKeyEnv = env.DSH_SESSION_SPLIT_JUDGE_KEY_ENV
76
+ return semantic
77
+ }
78
+
79
+ /**
80
+ * 合并并校验配置;非法值直接抛 CONFIG_INVALID(启动即失败,避免带病运行)。
81
+ * @param {Record<string, unknown>} [input]
82
+ */
83
+ export function resolveConfig(input) {
84
+ const raw = input ?? {}
85
+ const semanticInput = raw.semantic && typeof raw.semantic === 'object' ? raw.semantic : {}
86
+ const cfg = applyHttpEnv({
87
+ ...DEFAULTS,
88
+ ...raw,
89
+ semantic: applySemanticEnv({ ...DEFAULTS.semantic, ...semanticInput }),
90
+ })
91
+ const fail = (key, why) => {
92
+ throw new SessionSplitError(ERR.CONFIG_INVALID, `配置项 ${key} 非法:${why}`, { key })
93
+ }
94
+ for (const [key, min, max] of NUMERIC_KEYS) {
95
+ const v = cfg[key]
96
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < min || v > max) {
97
+ fail(key, `需要 ${min}..${max} 的数字,收到 ${String(v)}`)
98
+ }
99
+ }
100
+ const sem = cfg.semantic
101
+ if (!BACKENDS.includes(sem.backend)) fail('semantic.backend', `需要 ${BACKENDS.join('/')},收到 ${String(sem.backend)}`)
102
+ for (const [key, min, max] of SEMANTIC_NUMERIC_KEYS) {
103
+ const v = sem[key]
104
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < min || v > max) {
105
+ fail(`semantic.${key}`, `需要 ${min}..${max} 的整数,收到 ${String(v)}`)
106
+ }
107
+ }
108
+ for (const key of ['provider', 'model', 'httpBaseUrl', 'httpModel', 'httpKeyEnv']) {
109
+ if (typeof sem[key] !== 'string') fail(`semantic.${key}`, '需要字符串')
110
+ }
111
+ if (sem.backend === 'kernel' && (!sem.provider || !sem.model)) {
112
+ fail('semantic.provider', 'kernel 后端需要 provider 与 model')
113
+ }
114
+ if (!HTTP_ROUTE_MODES.includes(cfg.httpRoutes)) {
115
+ fail('httpRoutes', `需要 ${HTTP_ROUTE_MODES.join('/')},收到 ${String(cfg.httpRoutes)}`)
116
+ }
117
+ if (typeof cfg.httpToken !== 'string') fail('httpToken', '需要字符串')
118
+ for (const [key, min, max] of [
119
+ ['httpRateLimitPerMin', 1, 10000],
120
+ ['httpExportPerMin', 1, 1000],
121
+ ]) {
122
+ const v = cfg[key]
123
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < min || v > max) {
124
+ fail(key, `需要 ${min}..${max} 的整数,收到 ${String(v)}`)
125
+ }
126
+ }
127
+ if (typeof cfg.exposeTitles !== 'boolean') fail('exposeTitles', '需要布尔值')
128
+ if (!Array.isArray(cfg.topics) || cfg.topics.length === 0) fail('topics', '需要非空数组')
129
+ cfg.topicRules = cfg.topics.map((entry, i) => {
130
+ const pair = Array.isArray(entry) ? entry : [entry?.label, entry?.pattern]
131
+ const [label, pattern] = pair
132
+ if (typeof label !== 'string' || !label) fail(`topics[${i}].label`, '需要非空字符串')
133
+ if (typeof pattern !== 'string' || !pattern) fail(`topics[${i}].pattern`, '需要正则字符串')
134
+ try {
135
+ return { label, re: new RegExp(pattern, 'u') }
136
+ } catch (err) {
137
+ return fail(`topics[${i}].pattern`, `无法编译正则:${err.message}`)
138
+ }
139
+ })
140
+ return cfg
141
+ }
package/src/cut.js ADDED
@@ -0,0 +1,54 @@
1
+ /** 剪除:把指定轮次从会话中移除,用剩余轮次重建新会话;可选归档原会话。
2
+ *
3
+ * DSH 会话是 append-only 事件流,不能从中间物理删除事件,
4
+ * 因此这里用「剩余轮次重建」的方式实现剪除。
5
+ *
6
+ * 归档只登记到 workspace 注册表的 `archivedSessionIds`(见 registry.archive),
7
+ * **绝不重命名会话目录**:DSH 读取会话列表时,会用每个会话文件头里的 id 与 cwd
8
+ * 重新推导它应该在的路径,并要求与实际路径一致;目录一旦被改名,整份会话列表
9
+ * 读取都会失败,侧边栏的会话列表会整块消失(重启后才暴露)。
10
+ */
11
+
12
+ /**
13
+ * 判断某一轮是否落在区间内。
14
+ * @param {number} turn 0 基轮次
15
+ * @param {Array<[number, number]>} ranges
16
+ * @returns {boolean}
17
+ */
18
+ export function inRanges(turn, ranges) {
19
+ return ranges.some(([from, to]) => turn >= from && turn <= to)
20
+ }
21
+
22
+ /**
23
+ * 计算剪除计划:被剪掉多少、剩下多少。
24
+ * @param {Array<{user:string, assistant:string}>} items
25
+ * @param {Array<[number, number]>} ranges
26
+ */
27
+ export function planCut(items, ranges) {
28
+ let removedTurns = 0
29
+ let removedChars = 0
30
+ let remainingTurns = 0
31
+ let remainingChars = 0
32
+ const keep = []
33
+ items.forEach((item, index) => {
34
+ const chars = item.user.length + item.assistant.length
35
+ if (inRanges(index, ranges)) {
36
+ removedTurns += 1
37
+ removedChars += chars
38
+ } else {
39
+ remainingTurns += 1
40
+ remainingChars += chars
41
+ keep.push({ turn: index, user: item.user, assistant: item.assistant })
42
+ }
43
+ })
44
+ return { keep, removedTurns, removedChars, remainingTurns, remainingChars }
45
+ }
46
+
47
+ /**
48
+ * 把 (用户, 助手) 配对列表转成 createSession 需要的元组。
49
+ * @param {Array<{user:string, assistant:string}>} keep
50
+ * @returns {Array<[string, string]>}
51
+ */
52
+ export function toPairs(keep) {
53
+ return keep.map((item) => [item.user, item.assistant])
54
+ }
@@ -0,0 +1,71 @@
1
+ /** 诊断信息:路径、缓存命中、配置、运行环境。用于 session_diag 工具与排障。 */
2
+ import { existsSync } from 'node:fs'
3
+ import { hostname } from 'node:os'
4
+
5
+ import { dshHome, registryPath, sessionsRoot } from './store.js'
6
+ import { listArchivedDirs } from './repair.js'
7
+
8
+ /**
9
+ * @param {object} input 诊断输入
10
+ * @param {Record<string, any>} input.cfg 已校验配置
11
+ * @param {() => Record<string, number>} input.readerStats 读取器统计
12
+ * @param {string[]} input.toolNames 已注册工具名
13
+ * @param {string} [input.judge] 判断模型描述
14
+ * @param {boolean} [input.redact] 是否隐去主机名与本机路径(HTTP 接口默认脱敏)
15
+ */
16
+ export function buildDiagnostics({ cfg, readerStats, toolNames, judge, redact = false }) {
17
+ const stats = readerStats ? readerStats() : {}
18
+ const host = redact ? '<已隐藏>' : hostname()
19
+ const home = redact ? '<已隐藏>' : dshHome()
20
+ const root = redact ? '<已隐藏>' : sessionsRoot()
21
+ const registry = redact ? '<已隐藏>' : registryPath()
22
+ const lines = [
23
+ '会话独立插件 · 诊断',
24
+ '',
25
+ `运行环境:Node ${process.version} · ${host}`,
26
+ `DSH_HOME:${home}`,
27
+ `会话目录:${root}(${redact ? '已隐藏' : existsSync(sessionsRoot()) ? '存在' : '不存在'})`,
28
+ `注册表:${registry}(${redact ? '已隐藏' : existsSync(registryPath()) ? '存在' : '不存在'})`,
29
+ '',
30
+ '工具:' + (toolNames.length ? toolNames.join(', ') : '(未注册)'),
31
+ '',
32
+ '配置:',
33
+ ` 压缩上限 ${(cfg.maxCompressedBytes / 1024 / 1024).toFixed(0)} MB`
34
+ + ` · 解压上限 ${(cfg.maxInflatedBytes / 1024 / 1024).toFixed(0)} MB`,
35
+ ` 缓存 ${cfg.cacheEntries} 条 · 区间上限 ${cfg.maxRanges} 段`,
36
+ ` 分段阈值 ${cfg.minSegmentTurns} 轮 / ${cfg.minSegmentChars} 字`,
37
+ ` 主题规则 ${cfg.topicRules.length} 组`,
38
+ ` HTTP 面板 ${cfg.httpRoutes === 'token' ? '已启用(需令牌)' : '已关闭(配置)'}`
39
+ + ` · 标题 ${cfg.exposeTitles ? '可见' : '隐藏'}`,
40
+ '',
41
+ '判断模型:',
42
+ ` 后端 ${cfg.semantic.backend} · ${judge ?? '不可用(回退关键词规则)'}`,
43
+ ` 内核路由 ${cfg.semantic.provider}/${cfg.semantic.model}`
44
+ + ` · 超时 ${cfg.semantic.timeoutMs} ms · 重试 ${cfg.semantic.retries}`,
45
+ '',
46
+ '缓存统计:',
47
+ ` 命中 ${stats.hits ?? 0} 次 · 未命中 ${stats.misses ?? 0} 次 · 最近解析 ${stats.lastParseMs ?? 0} ms`,
48
+ '',
49
+ '归档目录:',
50
+ archivedDirLine(redact),
51
+ '',
52
+ '开关:',
53
+ ` DSH_SESSION_SPLIT_DISABLE=${process.env.DSH_SESSION_SPLIT_DISABLE ?? '(未设置)'}`,
54
+ ` DSH_SESSION_SPLIT_DEBUG=${process.env.DSH_SESSION_SPLIT_DEBUG ?? '(未设置)'}`,
55
+ ` DSH_SESSION_SPLIT_JUDGE=${process.env.DSH_SESSION_SPLIT_JUDGE ?? '(未设置)'}`,
56
+ ` DSH_SESSION_SPLIT_HTTP=${process.env.DSH_SESSION_SPLIT_HTTP ?? '(未设置)'}`,
57
+ ]
58
+ return lines.join('\n')
59
+ }
60
+
61
+ /**
62
+ * 归档目录一行:残留的 `.archived-*` 会让 DSH 的会话列表整份读不出来。
63
+ * @param {boolean} redact 是否脱敏(不列本机目录名)
64
+ * @returns {string}
65
+ */
66
+ function archivedDirLine(redact) {
67
+ if (redact) return ' 已隐藏'
68
+ const stray = listArchivedDirs()
69
+ if (stray.length === 0) return ' 无残留(.archived-* 目录会让 DSH 会话列表整份读不出来)'
70
+ return ` ⚠ 发现 ${stray.length} 个被改名的目录:${stray.map((entry) => entry.name).join(', ')}`
71
+ }
package/src/errors.js ADDED
@@ -0,0 +1,43 @@
1
+ /** 错误码:所有失败路径都带 code,便于日志过滤与调用方判断。 */
2
+ export const ERR = Object.freeze({
3
+ SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',
4
+ SESSION_ID_INVALID: 'SESSION_ID_INVALID',
5
+ FILE_TOO_LARGE: 'FILE_TOO_LARGE',
6
+ FILE_CORRUPT: 'FILE_CORRUPT',
7
+ RANGE_INVALID: 'RANGE_INVALID',
8
+ RANGE_TOO_MANY: 'RANGE_TOO_MANY',
9
+ TURNS_INVALID: 'TURNS_INVALID',
10
+ EMPTY_RESULT: 'EMPTY_RESULT',
11
+ CONFIG_INVALID: 'CONFIG_INVALID',
12
+ PATH_OUTSIDE_ROOT: 'PATH_OUTSIDE_ROOT',
13
+ IO_FAILED: 'IO_FAILED',
14
+ JUDGE_UNAVAILABLE: 'JUDGE_UNAVAILABLE',
15
+ JUDGE_TIMEOUT: 'JUDGE_TIMEOUT',
16
+ JUDGE_BAD_OUTPUT: 'JUDGE_BAD_OUTPUT',
17
+ ABORTED: 'ABORTED',
18
+ })
19
+
20
+ /**
21
+ * 带错误码的插件异常。
22
+ * @extends Error
23
+ */
24
+ export class SessionSplitError extends Error {
25
+ /**
26
+ * @param {string} code 错误码(见 ERR)
27
+ * @param {string} message 面向用户的说明
28
+ * @param {Record<string, unknown>} [details] 附加上下文
29
+ */
30
+ constructor(code, message, details) {
31
+ super(message)
32
+ this.name = 'SessionSplitError'
33
+ this.code = code
34
+ this.details = details ?? {}
35
+ }
36
+ }
37
+
38
+ /** 把任意异常规整成 SessionSplitError。 */
39
+ export function asSplitError(err, fallbackCode = ERR.IO_FAILED) {
40
+ if (err instanceof SessionSplitError) return err
41
+ const message = err && err.message ? err.message : String(err)
42
+ return new SessionSplitError(fallbackCode, message)
43
+ }
@@ -0,0 +1,149 @@
1
+ /** 导出:把 (用户, 助手) 配对构造成合法的 DSH 会话文件并登记。
2
+ *
3
+ * 结构对齐真实会话(否则被 GUI resume 追加时会因缺少保护头而损坏):
4
+ * permission/preset → sandbox/mode → approval/policy → session/end-seed
5
+ * 每轮:agent/inbox/spliced(insert) → turn/start → agent/inbox/spliced(remove)
6
+ * → step/start → [仅第 1 轮] system/message → user/message
7
+ * → assistant/message → step/end → turn/end
8
+ */
9
+ import { randomUUID } from 'node:crypto'
10
+ import { mkdirSync } from 'node:fs'
11
+ import { join } from 'node:path'
12
+
13
+ import { ERR, SessionSplitError } from './errors.js'
14
+ import { atomicWrite, sessionsRoot, slugFor } from './store.js'
15
+ import { encodeSession } from './zstd.js'
16
+
17
+ const MODEL_SOURCE = Object.freeze({ kind: 'model', provider: 'deepseek-official', model: 'deepseek-flash' })
18
+ const SYSTEM_PROMPT = 'You are an AI agent powered by DeepSeek Harness.'
19
+
20
+ /** 真实会话的固定头部(缺了它,追加事件会报 "protected first surface head")。 */
21
+ export function headEvents(createdAt = Date.now()) {
22
+ return [
23
+ { type: 'permission/preset', time: createdAt, data: { preset: 'workspace-write' } },
24
+ { type: 'sandbox/mode', time: createdAt + 1, data: { mode: 'workspace-write' } },
25
+ { type: 'approval/policy', time: createdAt + 2, data: { policy: 'ask' } },
26
+ { type: 'session/end-seed', time: createdAt + 3, data: {} },
27
+ ]
28
+ }
29
+
30
+ function userObject(text) {
31
+ const rpcId = randomUUID()
32
+ return {
33
+ content: [{ type: 'text', text }],
34
+ source: { kind: 'user', rpcId, clientTimeZone: 'Asia/Shanghai' },
35
+ role: 'user',
36
+ id: randomUUID(),
37
+ }
38
+ }
39
+
40
+ /**
41
+ * 生成事件序列。turn 从 1 开始、seq 从 0 连续递增——DSH 校验硬要求。
42
+ * @param {Array<[string,string]>} pairs
43
+ * @param {number} [createdAt]
44
+ */
45
+ export function buildEvents(pairs, createdAt = Date.now()) {
46
+ const events = []
47
+ const push = (ev) => {
48
+ events.push({ ...ev, seq: events.length })
49
+ }
50
+
51
+ for (const ev of headEvents(createdAt)) push(ev)
52
+
53
+ pairs.forEach(([user, assistant], index) => {
54
+ const turn = index + 1
55
+ const at = createdAt + 10 + index * 60_000
56
+ const userObj = userObject(user)
57
+
58
+ // 轮前注入(真实会话里用户消息先进入 next-turn 队列)
59
+ push({
60
+ type: 'agent/inbox/spliced',
61
+ time: at,
62
+ data: { target: 'next-turn', start: 0, inserted: [userObj] },
63
+ })
64
+ push({ type: 'turn/start', time: at + 3, data: { turn } })
65
+ push({
66
+ type: 'agent/inbox/spliced',
67
+ time: at + 6,
68
+ data: { target: 'next-turn', start: 0, removedCount: 1, inserted: [] },
69
+ })
70
+ push({ type: 'step/start', time: at + 9, data: { turn, step: 1 } })
71
+
72
+ // 只有第 1 轮带 system/message(受保护的首次 surface)
73
+ if (turn === 1) {
74
+ push({
75
+ type: 'system/message',
76
+ time: at + 12,
77
+ surfaceOp: 'append',
78
+ data: {
79
+ turn: 1,
80
+ step: 1,
81
+ message: {
82
+ role: 'system',
83
+ content: [{ type: 'text', text: SYSTEM_PROMPT }],
84
+ source: { kind: 'system-prompt' },
85
+ id: randomUUID(),
86
+ },
87
+ },
88
+ })
89
+ }
90
+
91
+ push({ type: 'user/message', time: at + 15, surfaceOp: 'append', data: userObj })
92
+
93
+ if (assistant) {
94
+ push({
95
+ type: 'assistant/message',
96
+ time: at + 18,
97
+ surfaceOp: 'append',
98
+ data: {
99
+ turn,
100
+ step: 1,
101
+ message: {
102
+ role: 'assistant',
103
+ content: [{ type: 'text', text: assistant }],
104
+ source: MODEL_SOURCE,
105
+ id: randomUUID(),
106
+ },
107
+ usage: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, totalTokens: 0 },
108
+ stream: [],
109
+ },
110
+ })
111
+ }
112
+
113
+ push({ type: 'step/end', time: at + 21, data: { turn, step: 1 } })
114
+ push({ type: 'turn/end', time: at + 24, data: { turn, reason: { kind: 'completed' } } })
115
+ })
116
+
117
+ return events
118
+ }
119
+
120
+ /**
121
+ * 创建独立会话。
122
+ * @param {{cwd:string, pairs:Array<[string,string]>, title?:string}} input
123
+ * @returns {{id:string, file:string, turns:number}}
124
+ */
125
+ export function createSession({ cwd, pairs, title }) {
126
+ if (!Array.isArray(pairs) || pairs.length === 0) {
127
+ throw new SessionSplitError(ERR.EMPTY_RESULT, '没有可导出的对话内容')
128
+ }
129
+ // 空 cwd 回退到当前目录:DSH 的 projectKey 不接受空路径
130
+ const projectCwd = String(cwd ?? '').trim() ? cwd : process.cwd()
131
+ const id = 'session-' + randomUUID()
132
+ const createdAt = Date.now()
133
+ const header = {
134
+ type: 'session',
135
+ version: 4,
136
+ id,
137
+ createdAt,
138
+ cwd: projectCwd,
139
+ isSeeded: false,
140
+ delegationDepth: 0,
141
+ agentPreset: 'standard',
142
+ }
143
+ const events = buildEvents(pairs, createdAt)
144
+ const dir = join(sessionsRoot(), slugFor(projectCwd), id)
145
+ mkdirSync(dir, { recursive: true })
146
+ const file = join(dir, 'session.v4.jsonl.zstd')
147
+ atomicWrite(file, encodeSession(header, events))
148
+ return { id, file, turns: pairs.length, title: title ?? '' }
149
+ }