yukari-dsh-plugin 0.0.0-stage → 0.7.2

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 (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -2
  3. package/client.js +8340 -0
  4. package/cordis.patch.yml +95 -0
  5. package/host/browser/index.js +397 -0
  6. package/host/browser/lib/browser.js +885 -0
  7. package/host/browser/lib/cdp.js +302 -0
  8. package/host/browser/lib/libraries.js +309 -0
  9. package/host/browser/lib/page-scripts.js +243 -0
  10. package/host/browser/lib/runtime.js +351 -0
  11. package/host/browser/lib/url-guard.js +122 -0
  12. package/host/browser/locale/en.json +6 -0
  13. package/host/browser/locale/zh.json +6 -0
  14. package/host/chats/index.js +254 -0
  15. package/host/chats/lib/admin.js +893 -0
  16. package/host/chats/lib/cleanup.js +272 -0
  17. package/host/chats/lib/paths.js +108 -0
  18. package/host/chats/lib/preview.js +74 -0
  19. package/host/chats/locale/en.json +6 -0
  20. package/host/chats/locale/zh.json +6 -0
  21. package/host/files/index.js +403 -0
  22. package/host/files/locale/en.json +6 -0
  23. package/host/files/locale/zh.json +6 -0
  24. package/host/github/index.js +121 -0
  25. package/host/github/lib/api.js +310 -0
  26. package/host/github/lib/atomic.js +42 -0
  27. package/host/github/lib/controller.js +450 -0
  28. package/host/github/lib/git.js +389 -0
  29. package/host/github/lib/redact.js +22 -0
  30. package/host/github/lib/signing.js +124 -0
  31. package/host/github/lib/store.js +181 -0
  32. package/host/github/locale/en.json +6 -0
  33. package/host/github/locale/zh.json +6 -0
  34. package/host/presets/index.js +450 -0
  35. package/host/presets/lib/definition.js +267 -0
  36. package/host/presets/lib/sources.js +278 -0
  37. package/host/presets/lib/store.js +136 -0
  38. package/host/presets/locale/en.json +6 -0
  39. package/host/presets/locale/zh.json +6 -0
  40. package/host/proxy/index.js +236 -0
  41. package/host/proxy/lib/controller.js +1151 -0
  42. package/host/proxy/lib/egress.js +120 -0
  43. package/host/proxy/lib/local-proxy.js +422 -0
  44. package/host/proxy/lib/shadowsocks.js +335 -0
  45. package/host/proxy/lib/ss-uri.js +501 -0
  46. package/host/proxy/lib/subscriptions.js +140 -0
  47. package/host/proxy/locale/en.json +6 -0
  48. package/host/proxy/locale/zh.json +6 -0
  49. package/host/purge/index.js +538 -0
  50. package/host/purge/lib/preset.js +140 -0
  51. package/host/purge/lib/prompts.js +95 -0
  52. package/host/purge/lib/retry-gate.js +97 -0
  53. package/host/purge/lib/rewriter.js +322 -0
  54. package/host/purge/lib/settings.js +54 -0
  55. package/host/purge/lib/stream-retry.js +255 -0
  56. package/host/purge/locale/en.json +6 -0
  57. package/host/purge/locale/zh.json +6 -0
  58. package/host/purge/presets/unrestricted/agent.cordis.yml +273 -0
  59. package/host/purge/presets/unrestricted/preset.json +75 -0
  60. package/host/purge/presets/unrestricted/preset.yml +3 -0
  61. package/host/rewind/index.js +127 -0
  62. package/host/rewind/lib/controller.js +449 -0
  63. package/host/rewind/lib/marker.js +53 -0
  64. package/host/rewind/lib/safe-path.js +47 -0
  65. package/host/rewind/lib/store.js +585 -0
  66. package/host/rewind/lib/surface.js +108 -0
  67. package/host/rewind/locale/en.json +6 -0
  68. package/host/rewind/locale/zh.json +6 -0
  69. package/host/rules/index.js +624 -0
  70. package/host/rules/lib/paths.js +87 -0
  71. package/host/rules/lib/render.js +92 -0
  72. package/host/rules/lib/scope.js +146 -0
  73. package/host/rules/lib/settings.js +55 -0
  74. package/host/rules/lib/store.js +222 -0
  75. package/host/rules/locale/en.json +6 -0
  76. package/host/rules/locale/zh.json +6 -0
  77. package/host/runtime/index.js +577 -0
  78. package/host/runtime/lib/npm.js +293 -0
  79. package/host/runtime/lib/restart.js +105 -0
  80. package/host/runtime/lib/update-guard.js +70 -0
  81. package/host/runtime/lib/versions.js +188 -0
  82. package/host/runtime/locale/en.json +6 -0
  83. package/host/runtime/locale/zh.json +6 -0
  84. package/host/shared/busy.js +40 -0
  85. package/host/shared/home.js +27 -0
  86. package/host/shared/http.js +159 -0
  87. package/host/shared/migrate.js +60 -0
  88. package/host/shared/mounted.js +54 -0
  89. package/host/shared/zip-writer.js +319 -0
  90. package/host/shared/zip.js +180 -0
  91. package/host/sites/index.js +258 -0
  92. package/host/sites/lib/sites.js +630 -0
  93. package/host/sites/locale/en.json +6 -0
  94. package/host/sites/locale/zh.json +6 -0
  95. package/host/skills/index.js +176 -0
  96. package/host/skills/lib/frontmatter.js +149 -0
  97. package/host/skills/lib/library.js +408 -0
  98. package/host/skills/lib/upload.js +115 -0
  99. package/host/skills/locale/en.json +6 -0
  100. package/host/skills/locale/zh.json +6 -0
  101. package/icon.png +0 -0
  102. package/index.js +702 -0
  103. package/locale/en.json +5 -0
  104. package/locale/zh.json +5 -0
  105. package/package.json +113 -4
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Clean-up that goes beyond the chat log itself: files a chat created, and a
3
+ * whole workspace directory.
4
+ *
5
+ * Both are destructive, so every candidate passes several independent gates
6
+ * before anything is unlinked:
7
+ *
8
+ * - generated files come only from `tool/call` events whose tool reported
9
+ * creating a new file (`write` answering "Created file", or
10
+ * `str_replace_editor` with `command: create`, which refuses to overwrite);
11
+ * shell commands are not tracked;
12
+ * - the file must still be a regular file inside the chat's working directory
13
+ * (or a registered workspace), outside DSH_HOME, and — when the filesystem
14
+ * records it — born after the chat started;
15
+ * - a workspace directory is only removed when it is a registered workspace
16
+ * or the working directory of a chat being deleted, and never when it is or
17
+ * contains a system directory, the home directory, or DSH_HOME.
18
+ * @module @local/chat-manager/cleanup
19
+ */
20
+ import nodeFs from 'node:fs/promises'
21
+ import os from 'node:os'
22
+ import path from 'node:path'
23
+ import zlib from 'node:zlib'
24
+ import { isInside } from './paths.js'
25
+
26
+ /** Directories that are never removed, nor anything containing them. */
27
+ const SYSTEM_DIRS = [
28
+ '/bin', '/boot', '/data', '/dev', '/etc', '/home', '/lib', '/lib64', '/media', '/mnt', '/opt',
29
+ '/proc', '/root', '/run', '/sbin', '/srv', '/sys', '/tmp', '/usr', '/var',
30
+ ]
31
+
32
+ /** DSH_HOME of this process. */
33
+ function dshHome() {
34
+ const value = process.env.DSH_HOME
35
+ return path.resolve(typeof value === 'string' && value !== '' ? value : path.join(os.homedir(), '.dsh'))
36
+ }
37
+
38
+ /**
39
+ * Why a directory must not be removed recursively, or null when it may be.
40
+ * @param directory - candidate directory.
41
+ * @param extraProtected - more directories to keep (e.g. the session root).
42
+ */
43
+ export function unsafeDirectoryReason(directory, extraProtected = []) {
44
+ if (typeof directory !== 'string' || directory.trim() === '') return 'empty path'
45
+ const resolved = path.resolve(directory)
46
+ if (resolved === path.parse(resolved).root) return 'filesystem root'
47
+ const keep = [...SYSTEM_DIRS, os.homedir(), dshHome(), ...extraProtected]
48
+ .filter((entry) => typeof entry === 'string' && entry !== '')
49
+ .map((entry) => path.resolve(entry))
50
+ for (const entry of keep) {
51
+ if (resolved === entry) return `protected directory ${entry}`
52
+ if (isInside(resolved, entry)) return `contains protected directory ${entry}`
53
+ }
54
+ if (isInside(dshHome(), resolved)) return 'inside DSH_HOME'
55
+ return null
56
+ }
57
+
58
+ /* ------------------------------------------------------------ event reading */
59
+
60
+ /** Read every event of one stored chat through the persistence backend. */
61
+ async function eventsFromPersistence(persistence, id) {
62
+ if (persistence === undefined || typeof persistence.open !== 'function') return null
63
+ let handle = null
64
+ try {
65
+ handle = await persistence.open(id, 'read')
66
+ const result = await handle.read()
67
+ return Array.isArray(result?.events) ? result.events : null
68
+ } catch {
69
+ return null
70
+ } finally {
71
+ try {
72
+ await handle?.close?.()
73
+ } catch {
74
+ // closing a read handle cannot lose data
75
+ }
76
+ }
77
+ }
78
+
79
+ /** Fallback: decode the newest log file in an artifact directory directly. */
80
+ async function eventsFromDirectory(directory, fs) {
81
+ let names = []
82
+ try {
83
+ names = await fs.readdir(directory)
84
+ } catch {
85
+ return []
86
+ }
87
+ const generation = (name) => Number(/session(?:\.v(\d+))?\.jsonl/.exec(name)?.[1] ?? 0)
88
+ const logs = names.filter((name) => /^session(\.v\d+)?\.jsonl(\.zstd)?$/.test(name)).sort((a, b) => generation(b) - generation(a))
89
+ for (const name of logs) {
90
+ try {
91
+ let bytes = await fs.readFile(path.join(directory, name))
92
+ if (name.endsWith('.zstd')) {
93
+ if (typeof zlib.zstdDecompressSync !== 'function') continue
94
+ bytes = zlib.zstdDecompressSync(bytes)
95
+ }
96
+ const events = []
97
+ for (const line of bytes.toString('utf8').split('\n')) {
98
+ if (line.trim() === '') continue
99
+ try {
100
+ events.push(JSON.parse(line))
101
+ } catch {
102
+ // a torn final line
103
+ }
104
+ }
105
+ return events
106
+ } catch {
107
+ // try an older generation
108
+ }
109
+ }
110
+ return []
111
+ }
112
+
113
+ /** Plain text of one tool result message, whatever its content shape. */
114
+ function resultText(message) {
115
+ if (message === null || typeof message !== 'object') return ''
116
+ const content = message.content
117
+ if (typeof content === 'string') return content
118
+ if (Array.isArray(content)) {
119
+ return content.map((part) => (typeof part === 'string' ? part : typeof part?.text === 'string' ? part.text : '')).join('\n')
120
+ }
121
+ return ''
122
+ }
123
+
124
+ /** The tool call id a result message answers. */
125
+ function resultCallId(message) {
126
+ if (message === null || typeof message !== 'object') return null
127
+ for (const key of ['toolCallId', 'callId', 'tool_call_id', 'toolUseId', 'id']) {
128
+ if (typeof message[key] === 'string' && message[key] !== '') return message[key]
129
+ }
130
+ return null
131
+ }
132
+
133
+ /**
134
+ * Paths of files one chat created through file tools, in the order created.
135
+ * @param events - the chat's logical event stream.
136
+ * @param cwd - the chat's starting working directory.
137
+ * @returns absolute paths.
138
+ */
139
+ export function createdFilesFromEvents(events, cwd) {
140
+ const calls = new Map()
141
+ const results = new Map()
142
+ let directory = typeof cwd === 'string' && cwd !== '' ? cwd : process.cwd()
143
+ for (const event of events ?? []) {
144
+ const type = event?.type
145
+ const data = event?.data
146
+ if (data === null || typeof data !== 'object') continue
147
+ if (type === 'working-directory/change') {
148
+ const next = [data.cwd, data.path, data.to, data.directory].find((value) => typeof value === 'string' && value !== '')
149
+ if (next !== undefined) directory = next
150
+ continue
151
+ }
152
+ if (type === 'tool/call' && typeof data.callId === 'string') {
153
+ let args = data.arguments
154
+ if (typeof args === 'string') {
155
+ try {
156
+ args = JSON.parse(args)
157
+ } catch {
158
+ args = null
159
+ }
160
+ }
161
+ calls.set(data.callId, { name: String(data.name ?? ''), args, cwd: directory })
162
+ continue
163
+ }
164
+ if (type === 'tool/result') {
165
+ const id = resultCallId(data.message)
166
+ if (id !== null) results.set(id, { text: resultText(data.message), isError: data.message?.isError === true || data.error !== undefined })
167
+ }
168
+ }
169
+
170
+ const created = []
171
+ for (const [id, call] of calls) {
172
+ const args = call.args
173
+ if (args === null || typeof args !== 'object') continue
174
+ const result = results.get(id)
175
+ if (result === undefined || result.isError) continue
176
+ let target = null
177
+ if (call.name === 'str_replace_editor' && args.command === 'create') target = args.path
178
+ else if ((call.name === 'write' || call.name === 'Write') && /Created file/i.test(result.text)) target = args.file_path
179
+ if (typeof target !== 'string' || target.trim() === '') continue
180
+ const absolute = path.isAbsolute(target) ? path.resolve(target) : path.resolve(call.cwd, target)
181
+ if (!created.includes(absolute)) created.push(absolute)
182
+ }
183
+ return created
184
+ }
185
+
186
+ /**
187
+ * Remove the files one chat created.
188
+ * @param args - persistence backend, chat header, artifact directory, allowed roots, fs seam.
189
+ * @returns how many files went, and notes for the ones that stayed.
190
+ */
191
+ export async function removeCreatedFiles({ persistence, header, directory, roots = [], fs = nodeFs }) {
192
+ const notes = []
193
+ let removed = 0
194
+ const events = (await eventsFromPersistence(persistence, String(header.id))) ?? (directory === null ? [] : await eventsFromDirectory(directory, fs))
195
+ const candidates = createdFilesFromEvents(events, header.cwd)
196
+ const allowed = [header.cwd, ...roots].filter((entry) => typeof entry === 'string' && entry !== '').map((entry) => path.resolve(entry))
197
+ const createdAt = Number(header.createdAt) || 0
198
+ const home = dshHome()
199
+ const emptied = new Set()
200
+
201
+ for (const file of candidates) {
202
+ const base = allowed.find((root) => isInside(root, file))
203
+ if (base === undefined || isInside(home, file)) {
204
+ notes.push(`跳过工作区外的文件:${file}`)
205
+ continue
206
+ }
207
+ let info
208
+ try {
209
+ info = await fs.lstat(file)
210
+ } catch {
211
+ continue // already gone
212
+ }
213
+ if (!info.isFile() && !info.isSymbolicLink()) continue
214
+ // A file born before the chat existed was not created by it (rewritten at most).
215
+ const born = Number(info.birthtimeMs) || 0
216
+ if (born > 0 && createdAt > 0 && born < createdAt - 5000) {
217
+ notes.push(`保留会话前已存在的文件:${file}`)
218
+ continue
219
+ }
220
+ try {
221
+ await fs.unlink(file)
222
+ removed += 1
223
+ emptied.add(JSON.stringify([path.dirname(file), base]))
224
+ } catch (error) {
225
+ notes.push(`删除文件失败 ${file}:${error instanceof Error ? error.message : String(error)}`)
226
+ }
227
+ }
228
+
229
+ // Drop directories the deletes left empty, never the base directory itself.
230
+ for (const pair of emptied) {
231
+ let [current, base] = JSON.parse(pair)
232
+ while (isInside(base, current)) {
233
+ try {
234
+ await fs.rmdir(current)
235
+ } catch {
236
+ break // not empty, or already gone
237
+ }
238
+ current = path.dirname(current)
239
+ }
240
+ }
241
+ return { removed, notes }
242
+ }
243
+
244
+ /**
245
+ * Remove a workspace directory, the directory itself included. A mount point
246
+ * (e.g. the `/workspace` volume) cannot be removed from inside the container:
247
+ * its contents are deleted and the empty mount point stays.
248
+ * @param directory - the directory.
249
+ * @param extraProtected - more directories to keep.
250
+ * @param fs - fs seam.
251
+ * @returns whether the directory is gone, and a note describing what happened.
252
+ */
253
+ export async function removeWorkspaceDirectory(directory, extraProtected = [], fs = nodeFs) {
254
+ const reason = unsafeDirectoryReason(directory, extraProtected)
255
+ if (reason !== null) return { removed: false, note: `删除工作区目录失败 ${directory}(${reason})` }
256
+ const resolved = path.resolve(directory)
257
+ try {
258
+ await fs.rm(resolved, { recursive: true, force: true, maxRetries: 2 })
259
+ // The success flag already says this; an empty note keeps the response from
260
+ // repeating it in prose the caller would then have to recognise.
261
+ return { removed: true, note: '' }
262
+ } catch (error) {
263
+ if (error?.code === 'EBUSY' || error?.code === 'EPERM' || error?.code === 'EACCES') {
264
+ // The children went first; only the directory entry itself was refused.
265
+ const left = await fs.readdir(resolved).catch(() => null)
266
+ if (Array.isArray(left) && left.length === 0) {
267
+ return { removed: true, note: `已清空 ${resolved}(它是挂载点,目录本身无法在容器内删除)` }
268
+ }
269
+ }
270
+ return { removed: false, note: `删除工作区目录失败 ${resolved}:${error instanceof Error ? error.message : String(error)}` }
271
+ }
272
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Filesystem address helpers for stored Session artifacts.
3
+ *
4
+ * The JSONL Session backend keeps one directory per Session under
5
+ * `<root>/<project>/<encoded session id>/`. Deleting a chat therefore means
6
+ * removing that directory, and resolving it safely means reproducing the
7
+ * backend's own two encoders instead of trusting a raw id in a path.
8
+ *
9
+ * Both encoders are byte-for-byte the layout the backend documents: safe code
10
+ * units stay literal, everything else becomes `~XXXX`. A Session id that
11
+ * carries `../`, an absolute path, or a NUL cannot escape its project
12
+ * directory after {@link encodeSegment}.
13
+ *
14
+ * @module @local/chat-manager/paths
15
+ */
16
+ import path from 'node:path'
17
+
18
+ /** Project directory the backend uses for Sessions without a working directory. */
19
+ export const NO_CWD_PROJECT = '_no-cwd'
20
+
21
+ /**
22
+ * Encode one raw string as a single safe path segment.
23
+ * @param raw - the string to encode; must be non-empty.
24
+ * @returns the escaped segment.
25
+ */
26
+ export function encodeSegment(raw) {
27
+ if (typeof raw !== 'string' || raw.length === 0) throw new Error('cannot encode an empty path segment')
28
+ if (raw === '.') return '~002E'
29
+ if (raw === '..') return '~002E~002E'
30
+ let out = ''
31
+ for (let i = 0; i < raw.length; i += 1) {
32
+ const code = raw.charCodeAt(i)
33
+ const ch = String.fromCharCode(code)
34
+ if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) out += ch
35
+ else out += `~${code.toString(16).toUpperCase().padStart(4, '0')}`
36
+ }
37
+ return out
38
+ }
39
+
40
+ /**
41
+ * Build the human-navigable project directory key for a working directory.
42
+ * @param cwd - the Session's absolute working directory.
43
+ * @returns the project directory name.
44
+ */
45
+ export function projectKey(cwd) {
46
+ if (typeof cwd !== 'string' || cwd.length === 0) throw new Error('cannot encode an empty project path')
47
+ let readable = ''
48
+ let separatorRun = false
49
+ for (let i = 0; i < cwd.length; i += 1) {
50
+ const code = cwd.charCodeAt(i)
51
+ const ch = String.fromCharCode(code)
52
+ if (ch === '/' || ch === '\\' || ch === ':') {
53
+ if (!separatorRun) readable += '-'
54
+ separatorRun = true
55
+ } else if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) {
56
+ readable += ch
57
+ separatorRun = false
58
+ } else {
59
+ readable += `~${code.toString(16).toUpperCase().padStart(4, '0')}`
60
+ separatorRun = false
61
+ }
62
+ }
63
+ return `--${(readable.replace(/^-+/, '') || 'root').slice(0, 251)}--`
64
+ }
65
+
66
+ /**
67
+ * Compute one Session's artifact directory from its header fields.
68
+ * @param root - the backend's Session root directory.
69
+ * @param cwd - the Session's working directory, when it had one.
70
+ * @param id - the Session id.
71
+ * @returns the absolute artifact directory.
72
+ */
73
+ export function artifactDirectory(root, cwd, id) {
74
+ const project = typeof cwd === 'string' && cwd !== '' ? projectKey(cwd) : NO_CWD_PROJECT
75
+ return path.join(path.resolve(root), project, encodeSegment(id))
76
+ }
77
+
78
+ /**
79
+ * Whether one path sits strictly inside another directory.
80
+ * @param root - container directory.
81
+ * @param candidate - path to test.
82
+ * @returns true when candidate is a descendant of root.
83
+ */
84
+ export function isInside(root, candidate) {
85
+ if (typeof root !== 'string' || root === '' || typeof candidate !== 'string' || candidate === '') return false
86
+ const relative = path.relative(path.resolve(root), path.resolve(candidate))
87
+ return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative)
88
+ }
89
+
90
+ /**
91
+ * Whether one directory is a plausible artifact directory for a Session: a
92
+ * descendant of the root whose own name is the encoded Session id. This is the
93
+ * last gate before a recursive delete.
94
+ * @param root - the backend's Session root directory.
95
+ * @param directory - candidate artifact directory.
96
+ * @param id - the Session id the delete claims to remove.
97
+ * @returns true when the directory may be removed.
98
+ */
99
+ export function isArtifactDirectoryOf(root, directory, id) {
100
+ if (!isInside(root, directory)) return false
101
+ let expected
102
+ try {
103
+ expected = encodeSegment(id)
104
+ } catch {
105
+ return false
106
+ }
107
+ return path.basename(path.resolve(directory)) === expected
108
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * 会话悬停预览的日志投影。
3
+ *
4
+ * 只取当前对话面上的真人消息与助手正文:注入上下文、工具调用、已被回撤的
5
+ * 区间都不进入卡片。消息正文限量返回,预览不是完整日志导出。
6
+ * @module @local/chat-manager/preview
7
+ */
8
+
9
+ /** 一张卡片最多携带的对话条数。 */
10
+ const DEFAULT_MESSAGES = 6
11
+
12
+ /** 单条正文上限;界面另有行数截断。 */
13
+ const MAX_TEXT_CHARS = 2000
14
+
15
+ /** 参与 surface 替换计算的事件。 */
16
+ const SURFACE_TYPES = new Set(['system/message', 'developer/message', 'user/message', 'assistant/message', 'tool/result'])
17
+
18
+ /** 当前对话面上的事件序号。 */
19
+ function activeSeqs(events) {
20
+ const nodes = []
21
+ for (const event of events) {
22
+ if (!SURFACE_TYPES.has(event?.type)) continue
23
+ if (event.surfaceOp === 'append') {
24
+ nodes.push(event.seq)
25
+ continue
26
+ }
27
+ if (event.surfaceOp === undefined) continue
28
+ const start = nodes.indexOf(event.surfaceOp.startSeq)
29
+ const end = nodes.indexOf(event.surfaceOp.endSeq)
30
+ if (start === -1 || end === -1 || start > end) continue
31
+ nodes.splice(start, end - start + 1, event.seq)
32
+ }
33
+ return new Set(nodes)
34
+ }
35
+
36
+ /** 一条用户或助手消息的纯文本。 */
37
+ function messageOf(event) {
38
+ if (event?.type === 'user/message') {
39
+ if (event.data?.source?.kind !== 'user' || event.data?.role !== 'user') return null
40
+ return { role: 'user', content: event.data.content }
41
+ }
42
+ if (event?.type === 'assistant/message') return { role: 'assistant', content: event.data?.message?.content }
43
+ return null
44
+ }
45
+
46
+ /** 拼接文本块,忽略图片与思考块。 */
47
+ function textOf(content) {
48
+ if (!Array.isArray(content)) return ''
49
+ const text = content.map((block) => (block?.type === 'text' && typeof block.text === 'string' ? block.text : '')).join('\n').trim()
50
+ return text.length <= MAX_TEXT_CHARS ? text : `${text.slice(0, MAX_TEXT_CHARS)}…`
51
+ }
52
+
53
+ /**
54
+ * 提取当前对话的轮数与末尾几条消息。
55
+ * @param events - 按 seq 连续排列的日志事件。
56
+ * @param limit - 返回消息条数,最多 20。
57
+ * @returns `{ turns, messages }`。
58
+ */
59
+ export function previewOf(events, limit = DEFAULT_MESSAGES) {
60
+ const list = Array.isArray(events) ? events : []
61
+ const count = Number.isSafeInteger(limit) && limit > 0 ? Math.min(limit, 20) : DEFAULT_MESSAGES
62
+ const active = activeSeqs(list)
63
+ const visible = []
64
+ let turns = 0
65
+ for (const event of list) {
66
+ if (!active.has(event?.seq)) continue
67
+ const message = messageOf(event)
68
+ if (message === null) continue
69
+ if (message.role === 'user') turns += 1
70
+ const text = textOf(message.content)
71
+ if (text !== '') visible.push({ role: message.role, text })
72
+ }
73
+ return { turns, messages: visible.slice(-count) }
74
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Chats",
4
+ "description": "Browse, archive and delete chats"
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "会话",
4
+ "description": "按工作区浏览、归档、删除会话"
5
+ }
6
+ }