@twinsearth/dsh-fang 3.1.21 → 3.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/LICENSES/LICENSES/cordis-MIT.txt +39 -0
  2. package/client.js +197 -3
  3. package/defaults/defaults/umbrella-rules.yaml +113 -0
  4. package/package.json +2 -2
  5. package/sdk/sdk/README.md +65 -0
  6. package/sdk/sdk/examples/status-badge/README.md +16 -0
  7. package/sdk/sdk/examples/status-badge/client.js +60 -0
  8. package/sdk/sdk/examples/status-badge/cordis.patch.yml +7 -0
  9. package/sdk/sdk/examples/status-badge/index.js +12 -0
  10. package/sdk/sdk/examples/status-badge/package.json +24 -0
  11. package/sdk/sdk/templates/plugin/README.md +36 -0
  12. package/sdk/sdk/templates/plugin/client.js +35 -0
  13. package/sdk/sdk/templates/plugin/cordis.patch.yml +8 -0
  14. package/sdk/sdk/templates/plugin/icon.svg +5 -0
  15. package/sdk/sdk/templates/plugin/index.js +23 -0
  16. package/sdk/sdk/templates/plugin/locale/en.json +6 -0
  17. package/sdk/sdk/templates/plugin/package.json +36 -0
  18. package/src/kernel/types.mjs +1 -1
  19. package/src/src/compose.mjs +67 -0
  20. package/src/src/contract/client.js +86 -0
  21. package/src/src/contract/constants.js +79 -0
  22. package/src/src/contract/envelope.js +83 -0
  23. package/src/src/contract/index.js +19 -0
  24. package/src/src/contract/negotiate.js +106 -0
  25. package/src/src/contract/server.js +77 -0
  26. package/src/src/contract/transports.js +301 -0
  27. package/src/src/index.mjs +11 -0
  28. package/src/src/kernel/core.mjs +100 -0
  29. package/src/src/kernel/extensions.mjs +61 -0
  30. package/src/src/kernel/fsx.mjs +349 -0
  31. package/src/src/kernel/index.mjs +21 -0
  32. package/src/src/kernel/ledger.mjs +94 -0
  33. package/src/src/kernel/paths.mjs +182 -0
  34. package/src/src/kernel/role.mjs +68 -0
  35. package/src/src/kernel/rounds.mjs +172 -0
  36. package/src/src/kernel/schema.mjs +5 -0
  37. package/src/src/kernel/types.mjs +264 -0
  38. package/src/src/kernel/vendor/cosmokit.mjs +421 -0
  39. package/src/src/kernel/vendor/schemastery.mjs +638 -0
  40. package/src/src/lib/adapter-client.mjs +383 -0
  41. package/src/src/lib/adapter-protocol.mjs +243 -0
  42. package/src/src/lib/ai-secret-store.mjs +202 -0
  43. package/src/src/lib/boot-guard.mjs +182 -0
  44. package/src/src/lib/branch-store.mjs +84 -0
  45. package/src/src/lib/branch.mjs +74 -0
  46. package/src/src/lib/bridge-client.mjs +133 -0
  47. package/src/src/lib/broker-adapter.mjs +67 -0
  48. package/src/src/lib/broker.mjs +45 -0
  49. package/src/src/lib/business-producers.mjs +109 -0
  50. package/src/src/lib/command-cache.mjs +209 -0
  51. package/src/src/lib/compat.mjs +170 -0
  52. package/src/src/lib/composer-journal.mjs +128 -0
  53. package/src/src/lib/container/index.mjs +806 -0
  54. package/src/src/lib/decision-events.mjs +129 -0
  55. package/src/src/lib/decision-ingest-client.mjs +41 -0
  56. package/src/src/lib/decision-outbox.mjs +129 -0
  57. package/src/src/lib/default-essence.mjs +61 -0
  58. package/src/src/lib/desktop-launch.mjs +138 -0
  59. package/src/src/lib/essence.mjs +1211 -0
  60. package/src/src/lib/fork-client.mjs +410 -0
  61. package/src/src/lib/fork-config-lock.mjs +153 -0
  62. package/src/src/lib/fork-seed.mjs +304 -0
  63. package/src/src/lib/fork-supervision-settings.mjs +58 -0
  64. package/src/src/lib/fork-supervisor.mjs +122 -0
  65. package/src/src/lib/fs-guard.mjs +28 -0
  66. package/src/src/lib/http-auth.mjs +162 -0
  67. package/src/src/lib/idle-audit.mjs +178 -0
  68. package/src/src/lib/interaction-poke.mjs +61 -0
  69. package/src/src/lib/mirror-etag.mjs +92 -0
  70. package/src/src/lib/mirror-official-source.mjs +93 -0
  71. package/src/src/lib/mirror.mjs +478 -0
  72. package/src/src/lib/mother-link.mjs +156 -0
  73. package/src/src/lib/mutex.mjs +31 -0
  74. package/src/src/lib/permissions.mjs +115 -0
  75. package/src/src/lib/pnpm-store.mjs +189 -0
  76. package/src/src/lib/preferences.mjs +212 -0
  77. package/src/src/lib/producer-contract.mjs +162 -0
  78. package/src/src/lib/reflow.mjs +41 -0
  79. package/src/src/lib/remote.mjs +408 -0
  80. package/src/src/lib/restart-contract.mjs +650 -0
  81. package/src/src/lib/roots.mjs +30 -0
  82. package/src/src/lib/rule-registry.mjs +1101 -0
  83. package/src/src/lib/runtime-capture.mjs +307 -0
  84. package/src/src/lib/semaphore.mjs +34 -0
  85. package/src/src/lib/session-bundle.mjs +138 -0
  86. package/src/src/lib/session-format.mjs +658 -0
  87. package/src/src/lib/sse-parser.mjs +102 -0
  88. package/src/src/lib/ssrf-guard.mjs +170 -0
  89. package/src/src/lib/status-store.mjs +257 -0
  90. package/src/src/lib/task-handle.mjs +622 -0
  91. package/src/src/lib/ui-actions.mjs +55 -0
  92. package/src/src/lib/umbrella.mjs +1661 -0
  93. package/src/src/lib/upgrade-coordinator.mjs +107 -0
  94. package/src/src/lib/upgrade-status.mjs +43 -0
  95. package/src/src/plugins/adapter.mjs +1468 -0
  96. package/src/src/plugins/approver.mjs +1210 -0
  97. package/src/src/plugins/auditor.mjs +330 -0
  98. package/src/src/plugins/buffer-keeper.mjs +522 -0
  99. package/src/src/plugins/decision-center.mjs +2265 -0
  100. package/src/src/plugins/forker.mjs +1594 -0
  101. package/src/src/plugins/healer.mjs +664 -0
  102. package/src/src/plugins/hot-reloader.mjs +274 -0
  103. package/src/src/plugins/imports.mjs +247 -0
  104. package/src/src/plugins/orchestrator.mjs +3806 -0
  105. package/src/src/plugins/restart-guard.mjs +948 -0
  106. package/src/src/plugins/router.mjs +714 -0
  107. package/src/src/plugins/scorer.mjs +624 -0
  108. package/src/src/plugins/session-bridge.mjs +166 -0
  109. package/src/src/plugins/session-catalog.mjs +771 -0
  110. package/src/src/plugins/session-router.mjs +125 -0
  111. package/src/src/plugins/session-sync.mjs +171 -0
  112. package/src/src/plugins/umbrella.mjs +419 -0
  113. package/tools/recover-queue.mjs +133 -0
@@ -0,0 +1,658 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang v2.1.0 — 会话格式库(T10,母体只读会话目录的纯函数核心)。
4
+ //
5
+ // 本模块**零 import**:不依赖 node:fs / node:path / node:zlib / node:buffer。
6
+ // 所有 IO 与 zstd 解码通过参数注入(fsApi / zstdDecompressSync),因此可以在
7
+ // 单测里用假 fs、在浏览器兼容层里复用;只有文本解码用了 Web 标准 TextDecoder。
8
+ //
9
+ // 格式(本机实测 $DSH_HOME,2026-11-01):
10
+ // $DSH_HOME/storages/workspace.json
11
+ // { unit, global:{ archivedSessionIds[], pinnedSessionIds[], workspaceIds[], defaultWorkspaceId },
12
+ // tables:{ workspaces:{ <workspaceId>:{ path, title, sessionIds[], createdAt, updatedAt } } } }
13
+ // $DSH_HOME/sessions/<workspaceKey>/<sessionId>/session.v4.jsonl.zstd
14
+ // workspaceKey 由工作区绝对路径编码(`E:\GPT` → `--E-GPT--`,只用于显示/定位,不可反解);
15
+ // 日志是**多帧 zstd 拼接**:第一帧通常只有一行 session 头,后续帧是事件。
16
+ //
17
+ // 安全规则:任何来自前端的值只当 sessionId 用(正则校验,拒绝路径元字符),绝不拼路径。
18
+
19
+ /** 允许作为会话目录名的 id:`session-<uuid>` 或裸 `<uuid>`(本机 v4 两种都存在)。 */
20
+ export const SESSION_ID_RE = /^(?:session-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
21
+
22
+ /** 会话日志文件名(v4 格式)。 */
23
+ export const SESSION_LOG_FILE = 'session.v4.jsonl.zstd'
24
+
25
+ /** 工作区索引文件名。 */
26
+ export const WORKSPACE_INDEX_FILE = 'workspace.json'
27
+
28
+ /** zstd 帧 magic 28 B5 2F FD。 */
29
+ export const ZSTD_MAGIC = Object.freeze([0x28, 0xb5, 0x2f, 0xfd])
30
+
31
+ /** 头读默认预算(契约 §T10)。 */
32
+ export const HEAD_DEFAULTS = Object.freeze({
33
+ maxCompressedBytes: 262144,
34
+ maxLines: 50,
35
+ maxChars: 65536,
36
+ })
37
+
38
+ /** digest 上限:32 KiB(超限 halt,不静默截断)。 */
39
+ export const DIGEST_MAX_BYTES = 32 * 1024
40
+
41
+ let sharedDecoder = null
42
+ function decodeUtf8(bytes) {
43
+ if (typeof TextDecoder !== 'function') {
44
+ // 极端宿主没有 TextDecoder:逐字节 Latin-1 兜底(不抛,可能非 UTF-8 文本降级)
45
+ let s = ''
46
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i])
47
+ return s
48
+ }
49
+ if (!sharedDecoder) sharedDecoder = new TextDecoder('utf-8', { fatal: false })
50
+ return sharedDecoder.decode(bytes)
51
+ }
52
+
53
+ function clampInt(value, min, max, fallback) {
54
+ const n = Math.floor(Number(value))
55
+ if (!Number.isFinite(n)) return fallback
56
+ return Math.min(max, Math.max(min, n))
57
+ }
58
+
59
+ /** workspace 目录名只接受单段名字(readdir 已保证,但外部传入也挡一层)。 */
60
+ function isSingleSegmentName(name) {
61
+ return typeof name === 'string' && name !== '' && name !== '.' && name !== '..'
62
+ && !name.includes('/') && !name.includes('\\') && !name.includes('\0')
63
+ }
64
+
65
+ /** 宽松的 sessionId 校验:只允许 `session-` + 36 个 hex/'-' 或裸 uuid。 */
66
+ export function isValidSessionId(value) {
67
+ return typeof value === 'string' && value.length > 0 && value.length <= 64 && SESSION_ID_RE.test(value)
68
+ }
69
+
70
+ /** 返回空工作区索引(错误路径也保持同一形状)。 */
71
+ export function emptyWorkspaceIndex(degraded = []) {
72
+ return {
73
+ workspaces: [],
74
+ global: {
75
+ archivedSessionIds: [],
76
+ pinnedSessionIds: [],
77
+ workspaceIds: [],
78
+ defaultWorkspaceId: null,
79
+ initialized: false,
80
+ },
81
+ degraded: [...degraded],
82
+ }
83
+ }
84
+
85
+ /** 字符串数组归一化:trim、去空、去重(可选正则过滤)。 */
86
+ function cleanList(value, filter = null) {
87
+ if (!Array.isArray(value)) return []
88
+ const seen = new Set()
89
+ const out = []
90
+ for (const item of value) {
91
+ if (typeof item !== 'string') continue
92
+ const s = item.trim()
93
+ if (!s || seen.has(s)) continue
94
+ if (filter && !filter(s)) continue
95
+ seen.add(s)
96
+ out.push(s)
97
+ }
98
+ return out
99
+ }
100
+
101
+ /**
102
+ * 容错解析 workspace.json。
103
+ * @param {string|object} raw JSON 文本或已解析对象
104
+ * @returns {{workspaces:{id,path,title,sessionIds}[], global:{archivedSessionIds,pinnedSessionIds,workspaceIds,defaultWorkspaceId,initialized}, degraded:string[]}}
105
+ */
106
+ export function parseWorkspaceIndex(raw) {
107
+ if (raw === undefined || raw === null) return emptyWorkspaceIndex(['empty'])
108
+ let doc = raw
109
+ if (typeof raw === 'string') {
110
+ const text = raw.replace(/^\uFEFF/, '').trim()
111
+ if (!text) return emptyWorkspaceIndex(['empty'])
112
+ try {
113
+ doc = JSON.parse(text)
114
+ } catch {
115
+ return emptyWorkspaceIndex(['invalid-json'])
116
+ }
117
+ }
118
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return emptyWorkspaceIndex(['invalid-shape'])
119
+
120
+ const degraded = []
121
+ const tables = doc.tables && typeof doc.tables === 'object' && doc.tables.workspaces
122
+ ? doc.tables.workspaces
123
+ : null
124
+ const rawWorkspaces = tables && typeof tables === 'object' && !Array.isArray(tables)
125
+ ? tables
126
+ : (doc.workspaces && typeof doc.workspaces === 'object' && !Array.isArray(doc.workspaces) ? doc.workspaces : null)
127
+ if (!rawWorkspaces) degraded.push('no-workspaces-table')
128
+
129
+ const workspaces = []
130
+ const seenPaths = new Set()
131
+ for (const [id, rec] of Object.entries(rawWorkspaces ?? {})) {
132
+ if (!rec || typeof rec !== 'object') continue
133
+ const workspacePath = typeof rec.path === 'string' ? rec.path.trim() : ''
134
+ if (!workspacePath) continue
135
+ if (seenPaths.has(workspacePath)) continue
136
+ seenPaths.add(workspacePath)
137
+ workspaces.push({
138
+ id: String(id),
139
+ path: workspacePath,
140
+ title: typeof rec.title === 'string' && rec.title.trim() ? rec.title.trim() : workspacePath,
141
+ sessionIds: cleanList(rec.sessionIds),
142
+ createdAt: typeof rec.createdAt === 'string' ? rec.createdAt : null,
143
+ updatedAt: typeof rec.updatedAt === 'string' ? rec.updatedAt : null,
144
+ })
145
+ }
146
+ workspaces.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
147
+
148
+ const g = doc.global && typeof doc.global === 'object' ? doc.global : {}
149
+ return {
150
+ workspaces,
151
+ global: {
152
+ archivedSessionIds: cleanList(g.archivedSessionIds, isValidSessionId),
153
+ pinnedSessionIds: cleanList(g.pinnedSessionIds, isValidSessionId),
154
+ workspaceIds: cleanList(g.workspaceIds),
155
+ defaultWorkspaceId: typeof g.defaultWorkspaceId === 'string' ? g.defaultWorkspaceId : null,
156
+ initialized: g.initialized === true,
157
+ },
158
+ degraded,
159
+ }
160
+ }
161
+
162
+ /**
163
+ * 工作区绝对路径 → 会话目录名(仅显示/定位,**不可反解**)。
164
+ * 实测 `E:\GPT` → `--E-GPT--`,`C:\Users\a\b\c` → `--C-Users-a-b-c--`:
165
+ * 非 [A-Za-z0-9_-] 的连续字符折叠为单个 '-',首尾各包 '--'。
166
+ */
167
+ export function encodeWorkspaceKey(workspacePath) {
168
+ const raw = String(workspacePath ?? '').trim().replace(/[\\/]+$/, '')
169
+ if (!raw) return ''
170
+ const body = raw.replace(/[^A-Za-z0-9_-]+/g, '-')
171
+ return `--${body}--`
172
+ }
173
+
174
+ /** 'a/b' 拼接(不引入 node:path;Windows 也接受正斜杠)。 */
175
+ function joinRel(base, ...rest) {
176
+ const parts = [String(base ?? '').replace(/[\\/]+$/, ''), ...rest.map((p) => String(p ?? '').replace(/^[\\/]+/g, '').replace(/[\\/]+$/, ''))]
177
+ return parts.filter((p) => p !== '').join('/')
178
+ }
179
+
180
+ /** 帧边界:从 buf 里找 zstd magic 出现的位置。 */
181
+ function findMagicOffsets(bytes) {
182
+ const offsets = []
183
+ const b0 = ZSTD_MAGIC[0]
184
+ const b1 = ZSTD_MAGIC[1]
185
+ const b2 = ZSTD_MAGIC[2]
186
+ const b3 = ZSTD_MAGIC[3]
187
+ for (let i = 0; i + 3 < bytes.length; i++) {
188
+ if (bytes[i] === b0 && bytes[i + 1] === b1 && bytes[i + 2] === b2 && bytes[i + 3] === b3) offsets.push(i)
189
+ if (offsets.length >= 64) break // 头读预算内 64 帧足够;再多也只解第一帧
190
+ }
191
+ return offsets
192
+ }
193
+
194
+ /**
195
+ * 取第一帧的字节切片(多帧 zstd 只解第一帧;不得整文件解压)。
196
+ * 候选边界 = 第 2 个及之后的 magic 位置;按升序尝试单帧解压,第一个成功者即第一帧边界。
197
+ * 没有候选 / 候选都失败 → 返回整段(由调用方单帧解压,通常是真第一帧或会抛错降级)。
198
+ * @returns {{slice:Uint8Array, hasMoreFrames:boolean, boundary:number|null}}
199
+ */
200
+ function firstFrameSlice(bytes, zstdDecompressSync) {
201
+ const offsets = findMagicOffsets(bytes)
202
+ const candidates = offsets.filter((off) => off > 0)
203
+ for (const off of candidates) {
204
+ try {
205
+ zstdDecompressSync(bytes.subarray(0, off))
206
+ return { slice: bytes.subarray(0, off), hasMoreFrames: true, boundary: off }
207
+ } catch {
208
+ /* 这个 magic 是压缩数据里的巧合,试下一个候选 */
209
+ }
210
+ }
211
+ return { slice: bytes, hasMoreFrames: false, boundary: null }
212
+ }
213
+
214
+ /**
215
+ * 有界头读:只读文件前 maxCompressedBytes 字节,只解第一帧 zstd,返回文本行。
216
+ * @param {object} options
217
+ * @param {string} options.file 会话日志绝对路径
218
+ * @param {number} [options.maxCompressedBytes=262144] 读取/解压预算(压缩字节)
219
+ * @param {number} [options.maxLines=50] 最多返回的行数
220
+ * @param {number} [options.maxChars=65536] 最多返回的字符数
221
+ * @param {object} options.fsApi 注入的 fs:{statSync?, openSync, readSync, closeSync}
222
+ * @param {Function} options.zstdDecompressSync 注入的 zlib.zstdDecompressSync
223
+ * @returns {{lines:string[], degraded:string[], bytesRead:number}}
224
+ */
225
+ export function readBoundedHead(options = {}) {
226
+ const {
227
+ file,
228
+ maxCompressedBytes = HEAD_DEFAULTS.maxCompressedBytes,
229
+ maxLines = HEAD_DEFAULTS.maxLines,
230
+ maxChars = HEAD_DEFAULTS.maxChars,
231
+ fsApi,
232
+ zstdDecompressSync,
233
+ } = options ?? {}
234
+ const degraded = []
235
+ const out = { lines: [], degraded, bytesRead: 0 }
236
+ const note = (tag) => {
237
+ if (!degraded.includes(tag)) degraded.push(tag)
238
+ }
239
+
240
+ if (typeof file !== 'string' || !file) {
241
+ note('no-file')
242
+ return out
243
+ }
244
+ if (!fsApi || typeof fsApi.openSync !== 'function' || typeof fsApi.readSync !== 'function' || typeof fsApi.closeSync !== 'function') {
245
+ note('no-fs-api')
246
+ return out
247
+ }
248
+ const budget = clampInt(maxCompressedBytes, 4, 64 * 1024 * 1024, HEAD_DEFAULTS.maxCompressedBytes)
249
+ const lineBudget = clampInt(maxLines, 1, 100000, HEAD_DEFAULTS.maxLines)
250
+ const charBudget = clampInt(maxChars, 0, 16 * 1024 * 1024, HEAD_DEFAULTS.maxChars)
251
+
252
+ let fd = null
253
+ try {
254
+ let fileSize = null
255
+ if (typeof fsApi.statSync === 'function') {
256
+ try {
257
+ const st = fsApi.statSync(file)
258
+ if (st && Number.isFinite(st.size)) fileSize = st.size
259
+ } catch {
260
+ /* stat 失败会在 open 阶段再次暴露 */
261
+ }
262
+ }
263
+ if (fileSize === 0) {
264
+ note('empty')
265
+ return out
266
+ }
267
+ fd = fsApi.openSync(file, 'r')
268
+ const toRead = fileSize === null ? budget : Math.min(fileSize, budget)
269
+ if (!(toRead > 0)) {
270
+ note('empty')
271
+ return out
272
+ }
273
+ const buffer = new Uint8Array(toRead)
274
+ const read = fsApi.readSync(fd, buffer, 0, toRead, 0)
275
+ out.bytesRead = Number.isFinite(read) ? read : 0
276
+ if (out.bytesRead <= 0) {
277
+ note('empty')
278
+ return out
279
+ }
280
+ if (fileSize !== null && out.bytesRead < fileSize) note('compressed-limit')
281
+ if (out.bytesRead < toRead) note('short-read')
282
+ const view = buffer.subarray(0, out.bytesRead)
283
+
284
+ const looksZstd = view.length >= 4
285
+ && view[0] === ZSTD_MAGIC[0] && view[1] === ZSTD_MAGIC[1]
286
+ && view[2] === ZSTD_MAGIC[2] && view[3] === ZSTD_MAGIC[3]
287
+ let text = ''
288
+ let moreBytesOnDisk = fileSize !== null && fileSize > out.bytesRead
289
+ if (looksZstd) {
290
+ if (typeof zstdDecompressSync !== 'function') {
291
+ note('no-zstd')
292
+ return out
293
+ }
294
+ const frame = firstFrameSlice(view, zstdDecompressSync)
295
+ if (frame.hasMoreFrames) moreBytesOnDisk = true
296
+ if (moreBytesOnDisk) note('first-frame-only')
297
+ try {
298
+ const decoded = zstdDecompressSync(frame.slice)
299
+ // 注意:Node 的 zstdDecompressSync 对「被截断的帧」不抛错,而是返回 0 字节。
300
+ // 会话日志帧不会是空内容,因此 0 字节 + 非空输入一律按解压失败降级,绝不假装成功。
301
+ const bytes = decoded instanceof Uint8Array ? decoded : new Uint8Array(decoded)
302
+ if (bytes.length === 0 && frame.slice.length > 0) {
303
+ note('decompress-failed')
304
+ return out
305
+ }
306
+ text = decodeUtf8(bytes)
307
+ } catch {
308
+ note('decompress-failed')
309
+ return out
310
+ }
311
+ } else {
312
+ // 非 zstd(例如测试人造纯文本):按 UTF-8 文本读,如实标记降级而不是假装成功。
313
+ note('not-zstd')
314
+ text = decodeUtf8(view)
315
+ }
316
+
317
+ let lines = text.split('\n')
318
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()
319
+ if (lines.length > lineBudget) {
320
+ lines = lines.slice(0, lineBudget)
321
+ note('line-limit')
322
+ }
323
+ const kept = []
324
+ let chars = 0
325
+ for (const line of lines) {
326
+ if (charBudget <= 0) {
327
+ note('char-limit')
328
+ break
329
+ }
330
+ if (chars + line.length + 1 <= charBudget) {
331
+ kept.push(line)
332
+ chars += line.length + 1
333
+ continue
334
+ }
335
+ const remain = charBudget - chars
336
+ kept.push(remain > 1 ? line.slice(0, remain - 1) : '')
337
+ note('char-limit')
338
+ break
339
+ }
340
+ out.lines = kept
341
+ return out
342
+ } catch {
343
+ note('read-failed')
344
+ return out
345
+ } finally {
346
+ if (fd !== null) {
347
+ try {
348
+ fsApi.closeSync(fd)
349
+ } catch {
350
+ /* close 失败不影响已读结果 */
351
+ }
352
+ }
353
+ }
354
+ }
355
+
356
+ export const TITLE_DEFAULTS = Object.freeze({
357
+ maxFrames: 64,
358
+ maxCompressedBytes: 2 * 1024 * 1024,
359
+ maxEvents: 4000,
360
+ })
361
+
362
+ /**
363
+ * 有界多帧事件读:一次只读文件前 maxCompressedBytes 字节,逐帧解压直到 maxFrames 帧。
364
+ * 会话标题(session/title 事件)与首条用户消息通常在前几十帧内;**绝不整文件解压**。
365
+ * @returns {{events:object[], lines:string[], degraded:string[], framesDecoded:number, bytesRead:number}}
366
+ */
367
+ export function readBoundedEvents(options = {}) {
368
+ const {
369
+ file,
370
+ maxFrames = TITLE_DEFAULTS.maxFrames,
371
+ maxCompressedBytes = TITLE_DEFAULTS.maxCompressedBytes,
372
+ maxEvents = TITLE_DEFAULTS.maxEvents,
373
+ fsApi,
374
+ zstdDecompressSync,
375
+ } = options ?? {}
376
+ const degraded = []
377
+ const out = { events: [], lines: [], degraded, framesDecoded: 0, bytesRead: 0 }
378
+ const note = (tag) => { if (!degraded.includes(tag)) degraded.push(tag) }
379
+ if (typeof file !== 'string' || !file) { note('no-file'); return out }
380
+ if (!fsApi || typeof fsApi.openSync !== 'function') { note('no-fs-api'); return out }
381
+ if (typeof zstdDecompressSync !== 'function') { note('no-zstd'); return out }
382
+ const frameBudget = clampInt(maxFrames, 1, 4096, TITLE_DEFAULTS.maxFrames)
383
+ const byteBudget = clampInt(maxCompressedBytes, 4096, 64 * 1024 * 1024, TITLE_DEFAULTS.maxCompressedBytes)
384
+ const eventBudget = clampInt(maxEvents, 1, 200000, TITLE_DEFAULTS.maxEvents)
385
+ let fd = null
386
+ try {
387
+ let fileSize = null
388
+ try {
389
+ const st = fsApi.statSync(file)
390
+ if (st && Number.isFinite(st.size)) fileSize = st.size
391
+ } catch { /* open 阶段会再次暴露 */ }
392
+ if (fileSize === 0) { note('empty'); return out }
393
+ fd = fsApi.openSync(file, 'r')
394
+ const toRead = fileSize === null ? byteBudget : Math.min(fileSize, byteBudget)
395
+ if (!(toRead > 0)) { note('empty'); return out }
396
+ const buffer = new Uint8Array(toRead)
397
+ const got = fsApi.readSync(fd, buffer, 0, toRead, 0)
398
+ out.bytesRead = Number.isFinite(got) ? got : 0
399
+ if (out.bytesRead <= 0) { note('empty'); return out }
400
+ if (fileSize !== null && out.bytesRead < fileSize) note('compressed-limit')
401
+ const view = buffer.subarray(0, out.bytesRead)
402
+ const looksZstd = view.length >= 4
403
+ && view[0] === ZSTD_MAGIC[0] && view[1] === ZSTD_MAGIC[1]
404
+ && view[2] === ZSTD_MAGIC[2] && view[3] === ZSTD_MAGIC[3]
405
+ let text = ''
406
+ if (!looksZstd) {
407
+ note('not-zstd')
408
+ text = decodeUtf8(view)
409
+ } else {
410
+ const offsets = findMagicOffsets(view)
411
+ const bounds = [...new Set((offsets.length > 0 && offsets[0] === 0) ? offsets : [0, ...offsets])].sort((a, b) => a - b)
412
+ for (let i = 0; i < bounds.length && out.framesDecoded < frameBudget; i++) {
413
+ const frame = view.subarray(bounds[i], i + 1 < bounds.length ? bounds[i + 1] : view.length)
414
+ if (frame.length < 4) continue
415
+ try {
416
+ const decoded = zstdDecompressSync(frame)
417
+ const bytes = decoded instanceof Uint8Array ? decoded : new Uint8Array(decoded)
418
+ if (bytes.length === 0) { note('frame-empty'); continue }
419
+ text += decodeUtf8(bytes)
420
+ out.framesDecoded += 1
421
+ } catch {
422
+ note('frame-decode-failed')
423
+ break
424
+ }
425
+ }
426
+ if (out.framesDecoded < bounds.length) note('frame-limit')
427
+ }
428
+ const lines = text.split('\n')
429
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()
430
+ for (const line of lines) {
431
+ if (!line.trim()) continue
432
+ let parsed = null
433
+ try { parsed = JSON.parse(line) } catch { note('line-unparsable'); continue }
434
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue
435
+ out.events.push(parsed)
436
+ out.lines.push(line)
437
+ if (out.events.length >= eventBudget) { note('event-limit'); break }
438
+ }
439
+ return out
440
+ } catch {
441
+ note('read-failed')
442
+ return out
443
+ } finally {
444
+ if (fd !== null) { try { fsApi.closeSync(fd) } catch { /* ignore */ } }
445
+ }
446
+ }
447
+
448
+ /**
449
+ * 从事件里提取会话标题:最新 session/title > 首条用户消息(截断)> null。
450
+ * titleSource 让调用方如实标注标题来源(不假装有原生标题)。
451
+ */
452
+ export function extractSessionTitle(events = []) {
453
+ let title = null
454
+ let titleSource = null
455
+ let messageSeq = null
456
+ let preview = null
457
+ for (const event of (Array.isArray(events) ? events : [])) {
458
+ if (!event || typeof event !== 'object') continue
459
+ if (event.type === 'session/title') {
460
+ const data = event.data && typeof event.data === 'object' ? event.data : {}
461
+ const raw = typeof data.title === 'string' ? data.title.trim().replace(/\s+/g, ' ') : ''
462
+ if (raw) {
463
+ title = raw
464
+ titleSource = 'session/title'
465
+ const seqs = Array.isArray(data.messageSeqs) ? data.messageSeqs : []
466
+ messageSeq = Number.isFinite(seqs[0]) ? seqs[0] : null
467
+ }
468
+ }
469
+ if (!preview && event.type === 'user/message') {
470
+ const data = event.data && typeof event.data === 'object' ? event.data : event
471
+ const content = Array.isArray(data.content) ? data.content : []
472
+ const text = content
473
+ .filter((b) => b && b.type === 'text' && typeof b.text === 'string')
474
+ .map((b) => b.text)
475
+ .join(' ')
476
+ .trim()
477
+ .replace(/\s+/g, ' ')
478
+ if (text) preview = text.slice(0, 160)
479
+ }
480
+ }
481
+ if (!title && preview) {
482
+ title = preview.slice(0, 80)
483
+ titleSource = 'first-user'
484
+ }
485
+ return { title, titleSource, preview, messageSeq }
486
+ }
487
+
488
+ export const SEED_DEFAULTS = Object.freeze({
489
+ maxFrames: 512,
490
+ maxCompressedBytes: 16 * 1024 * 1024,
491
+ maxChars: 48 * 1024,
492
+ })
493
+
494
+ function messageTextOf(data) {
495
+ const content = Array.isArray(data?.content) ? data.content : []
496
+ return content
497
+ .filter((block) => block && block.type === 'text' && typeof block.text === 'string')
498
+ .map((block) => block.text.trim())
499
+ .filter(Boolean)
500
+ .join('\n\n')
501
+ }
502
+
503
+ /**
504
+ * 有界对话摘录:只取 user/assistant 的文本内容,按字符预算截断。
505
+ * 用于派生分身时的会话交接种子(不是完整日志转储)。
506
+ */
507
+ export function extractConversation(events = [], options = {}) {
508
+ const maxChars = clampInt(options.maxChars ?? SEED_DEFAULTS.maxChars, 1024, 256 * 1024, SEED_DEFAULTS.maxChars)
509
+ const parts = []
510
+ let used = 0
511
+ let messages = 0
512
+ let truncated = false
513
+ for (const event of (Array.isArray(events) ? events : [])) {
514
+ if (!event || typeof event !== 'object') continue
515
+ const role = event.type === 'user/message' ? '用户' : event.type === 'assistant/message' ? '助手' : null
516
+ if (!role) continue
517
+ const text = messageTextOf(event.data ?? event)
518
+ if (!text) continue
519
+ const block = `**${role}**:${text}\n\n`
520
+ if (used + block.length > maxChars) { truncated = true; break }
521
+ parts.push(block)
522
+ used += block.length
523
+ messages += 1
524
+ }
525
+ return { markdown: parts.join(''), messages, truncated, chars: used }
526
+ }
527
+
528
+ // ── 脱敏 ────────────────────────────────────────────────────────────────────
529
+ // 顺序有意义:先凭证类,再联系方式,最后绝对路径;每类替换后计数。
530
+ const REDACTION_RULES = [
531
+ // Bearer <token>
532
+ { re: /(\bBearer\s+)([A-Za-z0-9._~+/=-]{8,})/gi, to: (_m, p1) => `${p1}<redacted>` },
533
+ // token / password / secret / api_key = value(含 JSON 的 "key":"value" 形式)
534
+ {
535
+ re: /(\b(?:access[_-]?token|refresh[_-]?token|token|api[_-]?key|secret|password|passwd)\b["']?\s*[:=]\s*["']?)([^"'\s,&}]{3,})/gi,
536
+ to: (_m, p1) => `${p1}<redacted>`,
537
+ },
538
+ // OpenAI 风格 sk- 键
539
+ { re: /\bsk-[A-Za-z0-9_-]{8,}/g, to: () => '<redacted>' },
540
+ // 邮箱(本地/域名段都限长:避免在超长无 @ 字符串上退化成 O(n²) 回溯)
541
+ { re: /[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9][A-Za-z0-9.-]{0,253}\.[A-Za-z]{2,24}/g, to: () => '<email>' },
542
+ // 手机号(中国大陆 11 位 / +86 前缀)
543
+ { re: /(?<![\w.])(?:\+?86[-\s]?)?1[3-9]\d{9}(?![\w.])/g, to: () => '<phone>' },
544
+ // 国际号码
545
+ { re: /(?<![\w.])\+\d{1,3}[-\s]?\d{6,14}(?![\w.])/g, to: () => '<phone>' },
546
+ // Windows 绝对路径(必须先于 UNC:JSON 里的 `E:\\work\\x` 双反斜杠前缀也像 UNC)
547
+ { re: /[A-Za-z]:[\\/](?:[^\s"'<>|,;:]+[\\/])*[^\s"'<>|,;:]+/g, to: () => '<path>' },
548
+ // UNC 绝对路径
549
+ { re: /\\\\[A-Za-z0-9._$-]+\\[^\s"'<>|,;]+/g, to: () => '<path>' },
550
+ // POSIX 绝对路径(至少两段,避免误伤单段路由)
551
+ { re: /(?<=[\s"'(=:])\/(?:[A-Za-z0-9._-]+\/)+[A-Za-z0-9._-]+/g, to: () => '<path>' },
552
+ ]
553
+
554
+ /**
555
+ * 文本脱敏:token/Bearer/sk-/password/secret/api_key 值、邮箱、手机号、绝对路径。
556
+ * @param {string} text
557
+ * @returns {{text:string, redactions:number}}
558
+ */
559
+ export function redact(text) {
560
+ const input = String(text ?? '')
561
+ if (!input) return { text: input, redactions: 0 }
562
+ let current = input
563
+ let redactions = 0
564
+ for (const rule of REDACTION_RULES) {
565
+ current = current.replace(rule.re, (...args) => {
566
+ redactions += 1
567
+ return rule.to(...args)
568
+ })
569
+ }
570
+ return { text: current, redactions }
571
+ }
572
+
573
+ /**
574
+ * 只 stat 扫描会话目录(不解压、不写):返回会话元数据列表。
575
+ * @param {object} options
576
+ * @param {string} options.sessionsDir
577
+ * @param {string[]} [options.workspaceIds] 限定扫描的工作区目录名;空/缺省 = 扫描全部
578
+ * @param {string[]} [options.archivedSessionIds]
579
+ * @param {string[]} [options.pinnedSessionIds]
580
+ * @param {object} options.fsApi 注入的 fs:{readdirSync, statSync}
581
+ * @returns {{sessionId:string, workspaceId:string, updatedAt:number, bytes:number, archived:boolean, pinned:boolean, relPath:string}[]}
582
+ */
583
+ export function scanSessionDirs(options = {}) {
584
+ const {
585
+ sessionsDir,
586
+ workspaceIds = [],
587
+ archivedSessionIds = [],
588
+ pinnedSessionIds = [],
589
+ fsApi,
590
+ } = options ?? {}
591
+ if (typeof sessionsDir !== 'string' || !sessionsDir) return []
592
+ if (!fsApi || typeof fsApi.readdirSync !== 'function' || typeof fsApi.statSync !== 'function') return []
593
+
594
+ const archived = new Set(Array.isArray(archivedSessionIds) ? archivedSessionIds : [])
595
+ const pinned = new Set(Array.isArray(pinnedSessionIds) ? pinnedSessionIds : [])
596
+ const wanted = Array.isArray(workspaceIds)
597
+ ? workspaceIds.filter(isSingleSegmentName)
598
+ : []
599
+ const result = []
600
+
601
+ const readDir = (dir) => {
602
+ try {
603
+ return fsApi.readdirSync(dir, { withFileTypes: true })
604
+ } catch {
605
+ return []
606
+ }
607
+ }
608
+
609
+ const workspaceKeys = wanted.length > 0
610
+ ? wanted
611
+ : readDir(sessionsDir)
612
+ .filter((entry) => entry && entry.isDirectory && entry.isDirectory())
613
+ .map((entry) => entry.name)
614
+ .filter(isSingleSegmentName)
615
+
616
+ for (const workspaceKey of workspaceKeys) {
617
+ const wsDir = joinRel(sessionsDir, workspaceKey)
618
+ for (const entry of readDir(wsDir)) {
619
+ const sessionId = entry && entry.name
620
+ if (!entry || !entry.isDirectory || !entry.isDirectory()) continue
621
+ if (!isValidSessionId(sessionId)) continue
622
+ const relPath = joinRel(workspaceKey, sessionId, SESSION_LOG_FILE)
623
+ const logFile = joinRel(sessionsDir, workspaceKey, sessionId, SESSION_LOG_FILE)
624
+ let stat
625
+ try {
626
+ stat = fsApi.statSync(logFile)
627
+ } catch {
628
+ continue // 没有 v4 日志的目录不可恢复,不列进目录
629
+ }
630
+ if (!stat || !Number.isFinite(stat.size)) continue
631
+ result.push({
632
+ sessionId,
633
+ workspaceId: workspaceKey,
634
+ updatedAt: Number.isFinite(stat.mtimeMs) ? Math.round(stat.mtimeMs) : 0,
635
+ bytes: stat.size,
636
+ archived: archived.has(sessionId),
637
+ pinned: pinned.has(sessionId),
638
+ relPath,
639
+ })
640
+ }
641
+ }
642
+ result.sort((a, b) => b.updatedAt - a.updatedAt || (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0))
643
+ return result
644
+ }
645
+
646
+ export const _internals = {
647
+ extractConversation,
648
+ SEED_DEFAULTS,
649
+ readBoundedEvents,
650
+ extractSessionTitle,
651
+ TITLE_DEFAULTS,
652
+ findMagicOffsets,
653
+ firstFrameSlice,
654
+ joinRel,
655
+ cleanList,
656
+ decodeUtf8,
657
+ REDACTION_RULES,
658
+ }