dsh-seal-scripts 0.0.0-stage → 0.4.8

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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +318 -0
  3. package/README.md +342 -2
  4. package/cordis.patch.yml +6 -0
  5. package/index.js +12 -0
  6. package/lib/client.js +1465 -0
  7. package/lib/core/assembly.js +321 -0
  8. package/lib/core/catalog-snapshot.js +78 -0
  9. package/lib/core/diary.js +100 -0
  10. package/lib/core/health.js +72 -0
  11. package/lib/core/index.js +491 -0
  12. package/lib/core/inject.js +146 -0
  13. package/lib/core/lang.js +251 -0
  14. package/lib/core/locale.js +56 -0
  15. package/lib/core/memory-file.js +214 -0
  16. package/lib/core/migrate.js +97 -0
  17. package/lib/core/path-guard.js +43 -0
  18. package/lib/core/project-key.js +52 -0
  19. package/lib/core/render.js +228 -0
  20. package/lib/core/schema-runner.js +281 -0
  21. package/lib/core/schema-tools.js +794 -0
  22. package/lib/core/schema.js +493 -0
  23. package/lib/core/search.js +254 -0
  24. package/lib/core/settings.js +158 -0
  25. package/lib/core/store.js +408 -0
  26. package/lib/core/tool-transfer.js +249 -0
  27. package/lib/core/tool.js +602 -0
  28. package/lib/core/zip.js +226 -0
  29. package/lib/core/zstd-js.js +705 -0
  30. package/lib/core/zstd.js +103 -0
  31. package/lib/host/api.js +9 -0
  32. package/lib/host/capabilities.js +155 -0
  33. package/lib/host/compact-delete.js +76 -0
  34. package/lib/host/delete.js +136 -0
  35. package/lib/host/host-contract.js +73 -0
  36. package/lib/host/http-util.js +82 -0
  37. package/lib/host/lifecycle.js +66 -0
  38. package/lib/host/register.js +63 -0
  39. package/lib/host/routes/memories.js +102 -0
  40. package/lib/host/routes/options.js +46 -0
  41. package/lib/host/routes/sessions.js +194 -0
  42. package/lib/host/routes/tools.js +103 -0
  43. package/lib/host/summary.js +71 -0
  44. package/package.json +71 -4
@@ -0,0 +1,66 @@
1
+ /**
2
+ * 抓住 agents.create / agents.resume 返回的句柄。
3
+ *
4
+ * 删活会话要先 cancel → whenIdle → flush → dispose,而 dispose 能力只在
5
+ * agents.create/resume 返回的 handle 上。这里在公共边界上截一份,别的什么都不碰。
6
+ *
7
+ * 幂等:已经被别的插件(比如 dsh-web-mobile)打过标记就不再包一层。
8
+ *
9
+ * E5:缺方法不再抛。以前这里 throw,而它跑在 webCtx.effect() 里——
10
+ * 宿主一改 agents 的形状,症状是「设置页那半块整个没加载」。
11
+ * 现在缺了就 warn 并返回空卸载函数:只是「删除活会话」不可用,其余照常。
12
+ *
13
+ * 也确认过没有更窄的公开路:handle 只从 create/resume 的返回值来,
14
+ * agent/created 事件里只有 agent 与 source,没有 dispose 句柄。
15
+ */
16
+
17
+ const ownedHandles = new WeakMap()
18
+ const ownedHandlesOf = (agent) => ownedHandles.get(agent)
19
+ const MARK = '__dshSessionRecallLifecycle'
20
+ const METHODS = ['create', 'resume']
21
+
22
+ /**
23
+ * 安装生命周期捕获。
24
+ * @param {object|undefined} agents
25
+ * @param {{warn?:Function}} [logger]
26
+ * @returns {() => void} 卸载函数(未安装/已安装过则返回空函数)
27
+ */
28
+ export function installLifecycle(agents, logger) {
29
+ if (agents === undefined || agents === null) return () => {}
30
+ if (agents[MARK] === true) return () => {}
31
+ const proto = Object.getPrototypeOf(agents)
32
+ if (proto === null || typeof proto !== 'object') {
33
+ logger?.warn?.('宿主 agents 没有可用的原型,删除活会话已关闭')
34
+ return () => {}
35
+ }
36
+ // 先把两条都验完再动手:验一条补一条的话,第二条缺了会留下半套补丁。
37
+ for (const method of METHODS) {
38
+ if (typeof proto[method] !== 'function') {
39
+ logger?.warn?.('宿主缺 agents.' + method + '(),删除活会话已关闭')
40
+ return () => {}
41
+ }
42
+ }
43
+ const originals = new Map()
44
+ for (const method of METHODS) {
45
+ const original = proto[method]
46
+ if (original[MARK] === true) continue
47
+ const patched = async function (...args) {
48
+ const handle = await Reflect.apply(original, this, args)
49
+ if (handle?.agent !== undefined && typeof handle.dispose === 'function') ownedHandles.set(handle.agent, handle)
50
+ return handle
51
+ }
52
+ patched[MARK] = true
53
+ proto[method] = patched
54
+ originals.set(method, { original, patched })
55
+ }
56
+ agents[MARK] = true
57
+ return () => {
58
+ // 只还原自己那一层:别人后来又包了一层的话,保持他的包装不动。
59
+ for (const [method, { original, patched }] of originals) {
60
+ if (proto[method] === patched) proto[method] = original
61
+ }
62
+ agents[MARK] = false
63
+ }
64
+ }
65
+
66
+ export { ownedHandlesOf }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * 设置页 HTTP 端点的注册入口。
3
+ *
4
+ * 只做三件事:建路表(登录态 + 同源 + 错误码映射)、把四组路由装上、结束。
5
+ * 具体端点按域放在 routes/ 下,一个文件一组。
6
+ */
7
+
8
+ import { respond, sameOrigin } from './http-util.js'
9
+ import { routesSessions } from './routes/sessions.js'
10
+ import { routesMemories } from './routes/memories.js'
11
+ import { routesOptions } from './routes/options.js'
12
+ import { routesTools } from './routes/tools.js'
13
+
14
+ /**
15
+ * 共用外壳:登录态检查 + 同源检查 + 错误码映射(413 / path-outside / 500)。
16
+ * @param {object} webCtx
17
+ * @returns {(path:string, handler:Function) => void}
18
+ */
19
+ export function makeRoute(webCtx) {
20
+ return (path, handler) => webCtx.effect(() => webCtx.webServer.register({
21
+ kind: 'exact',
22
+ path,
23
+ handler: async (req, res) => {
24
+ try {
25
+ const rejection = webCtx.connection?.requestRejection?.(req)
26
+ if (rejection !== undefined) {
27
+ respond(res, rejection, { error: { code: 'access-denied', message: '需要先登录' } })
28
+ return
29
+ }
30
+ if (!sameOrigin(req)) {
31
+ respond(res, 403, { error: { code: 'cross-origin', message: '拒绝跨域请求' } })
32
+ return
33
+ }
34
+ await handler(req, res)
35
+ } catch (error) {
36
+ if (error?.code === 'body-too-large') {
37
+ respond(res, 413, { error: { code: 'body-too-large', message: error.message } })
38
+ return
39
+ }
40
+ // 路径越界是调用方给错了参数,不是服务端坏了:回 400 + 可识别的错误码。
41
+ // 判据在 path-guard.js 里,靠它那句固定开头认人。
42
+ if (/^只能操作/.test(error?.message ?? '')) {
43
+ respond(res, 400, { error: { code: 'path-outside', message: error.message } })
44
+ return
45
+ }
46
+ respond(res, 500, { error: { code: 'internal', message: error?.message ?? String(error) } })
47
+ }
48
+ }
49
+ }), 'dsh-seal-scripts: ' + path)
50
+ }
51
+
52
+ /**
53
+ * 装 10 个端点。
54
+ * @param {object} webCtx
55
+ * @param {{dshHome:string, getDeps:Function, waitForSplit?:Function, onOptionsChanged?:Function, canLifecycle?:boolean, probe?:Function}} deps
56
+ */
57
+ export function registerApi(webCtx, deps) {
58
+ const route = makeRoute(webCtx)
59
+ routesSessions(route, deps)
60
+ routesMemories(route, deps)
61
+ routesOptions(route, deps)
62
+ routesTools(route, deps)
63
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * 回顾文件本身:memory(读一份)/ memory-delete(删一份)/ annotate(改关键词与日记)。
3
+ * 写侧两道闸门都在 core/tool.js 的 applyWrite 里,这里只负责过路径闸门与回状态码。
4
+ */
5
+
6
+ import { join, basename } from 'node:path'
7
+ import { stat, readFile, rm, mkdir } from 'node:fs/promises'
8
+ import { memoryDir, removeEntry, writeFileAtomic } from '../../core/store.js'
9
+ import { parseMemory } from '../../core/memory-file.js'
10
+ import { applyWrite } from '../../core/tool.js'
11
+ import { assertInside, assertMarkdown } from '../../core/path-guard.js'
12
+ import { dialogueOnly } from '../../core/render.js'
13
+ import { respond, readBody } from '../http-util.js'
14
+
15
+ const PREFIX = '/api/session-recall.'
16
+
17
+ /**
18
+ * 删掉一条回顾:先删正文,再删它的边车。路径必须在回顾目录内。
19
+ *
20
+ * 没有共享清单了,所以这里不需要锁:两个文件各自删各自的。
21
+ */
22
+ async function deleteMemory(dshHome, cwd, file) {
23
+ const dir = memoryDir(dshHome, cwd)
24
+ // 判据只留 path-guard 一份(以前这里自带一份,用 startsWith('..') 会把 ..foo.md 误拦)。
25
+ const abs = assertMarkdown(assertInside(dir, file, { label: '本工作区的回顾目录' }), file)
26
+ const exists = await stat(abs).then(() => true, () => false)
27
+ if (!exists) throw new Error('这份回顾不存在:' + file)
28
+ // 顺序不能反:先删正文、再删边车。中间崩溃 → 边车成了孤儿,readAssembly 会自己清掉。
29
+ // 反过来(先删边车)而正文还在,下一次读会按 mtime 把边车补回来——等于没删掉索引。
30
+ await rm(abs, { force: true })
31
+ await removeEntry(dir, basename(abs))
32
+ return { ok: true, file: basename(abs), removed: 1 }
33
+ }
34
+
35
+ /**
36
+ * 读一份回顾。
37
+ *
38
+ * 路径闸门只管写(annotate / delete):读按用户裁定 (b) 保持可跨工作区——
39
+ * 设置页翻看别的工作区的回顾是正常用途,改不了别人的记忆就够。
40
+ */
41
+ async function readMemory(dshHome, cwd, file) {
42
+ const dir = memoryDir(dshHome, cwd)
43
+ const text = await readFile(join(dir, file), 'utf8')
44
+ const parsed = parseMemory(text)
45
+ return { file, meta: parsed.meta, sections: parsed.sections, dialogue: dialogueOnly(parsed.sections.body ?? '') }
46
+ }
47
+
48
+ /** @param {(path:string, handler:Function) => void} route @param {{dshHome:string}} deps */
49
+ export function routesMemories(route, { dshHome }) {
50
+ route(PREFIX + 'memory-delete', async (req, res) => {
51
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
52
+ const body = JSON.parse(await readBody(req) || '{}')
53
+ if (typeof body.cwd !== 'string' || typeof body.file !== 'string') {
54
+ respond(res, 400, { error: { code: 'invalid-body', message: '需要 cwd 与 file' } }); return
55
+ }
56
+ respond(res, 200, await deleteMemory(dshHome, body.cwd, body.file))
57
+ })
58
+
59
+ route(PREFIX + 'memory', async (req, res) => {
60
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
61
+ const body = JSON.parse(await readBody(req) || '{}')
62
+ if (typeof body.cwd !== 'string' || typeof body.file !== 'string') {
63
+ respond(res, 400, { error: { code: 'invalid-body', message: '需要 cwd 与 file' } }); return
64
+ }
65
+ respond(res, 200, await readMemory(dshHome, body.cwd, body.file))
66
+ })
67
+
68
+ route(PREFIX + 'annotate', async (req, res) => {
69
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
70
+ const body = JSON.parse(await readBody(req) || '{}')
71
+ if (typeof body.cwd !== 'string' || typeof body.file !== 'string') {
72
+ respond(res, 400, { error: { code: 'invalid-body', message: '需要 cwd 与 file' } }); return
73
+ }
74
+ const hasKeywords = Array.isArray(body.keywords)
75
+ const hasDiary = typeof body.diary === 'string'
76
+ if (!hasKeywords && !hasDiary) {
77
+ respond(res, 400, { error: { code: 'invalid-body', message: 'keywords 与 diary 至少给一个' } }); return
78
+ }
79
+ // 写侧必须过闸门:以前这里直接 join + 手写 tmp/rename,能改别的工作区的回顾,
80
+ // 也不受「日记 ≤ 摘要、关键词 < 日记」约束,写不进去时还回 ok:true。
81
+ const dir = memoryDir(dshHome, body.cwd)
82
+ await mkdir(dir, { recursive: true })
83
+ const abs = assertMarkdown(assertInside(dir, body.file, { label: '本工作区的回顾目录' }), body.file)
84
+ const before = await readFile(abs, 'utf8')
85
+ // 和 session_mem_write 走同一个 applyWrite:两道闸门、只动目标区、改完校验。
86
+ // 它抛什么就回什么——设置页和模型看到的是同一句话。
87
+ let applied
88
+ try {
89
+ applied = applyWrite(before, {
90
+ file: basename(abs),
91
+ keywords: hasKeywords ? body.keywords : undefined,
92
+ diary: hasDiary ? body.diary : undefined
93
+ })
94
+ } catch (error) {
95
+ // 闸门拦下来的写:原样透传那句多行中文诊断,状态用 400(调用方参数不合格,不是服务端坏了)。
96
+ respond(res, 400, { error: { code: 'write-rejected', message: error?.message ?? String(error) } })
97
+ return
98
+ }
99
+ await writeFileAtomic(abs, applied.next)
100
+ respond(res, 200, { ok: true, changed: applied.changed, diary: applied.diary, keywords: applied.keywords })
101
+ })
102
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * 设置项的读写:options(选项)/ locale(语言)。
3
+ * 两边都是「读一半写一半」:注入路径直接读核心里的同步函数,这里只管 HTTP。
4
+ */
5
+
6
+ import { readOptionsSync, writeOptions } from '../../core/settings.js'
7
+ import { readLocaleSync, writeLocale } from '../../core/locale.js'
8
+ import { respond, readBody } from '../http-util.js'
9
+
10
+ const PREFIX = '/api/session-recall.'
11
+
12
+ /** @param {(path:string, handler:Function) => void} route @param {{dshHome:string, onOptionsChanged?:Function, onToolListRefreshChanged?:Function}} deps */
13
+ export function routesOptions(route, { dshHome, onOptionsChanged, onToolListRefreshChanged }) {
14
+ route(PREFIX + 'options', async (req, res) => {
15
+ if (req.method === 'GET') {
16
+ respond(res, 200, { options: readOptionsSync(dshHome) })
17
+ return
18
+ }
19
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'GET / POST' } }); return }
20
+ const body = JSON.parse(await readBody(req) || '{}')
21
+ // 0.4.6:切档前后各读一次「清单词刷新时刻」。只有它真的变了才刷新清单快照——
22
+ // 改别的选项(全量加载、停止降低之类)不该把冻住的清单顺手换掉。
23
+ const refreshBefore = readOptionsSync(dshHome).toolListRefresh
24
+ // 收紧在 writeOptions 里做:「停止降低」开启时载入数值一律回退到跟随深度。
25
+ const options = await writeOptions(dshHome, body)
26
+ // 0.4.1:写完立刻按新选项装卸工具。这一步必须发生在返回之前——
27
+ // 下一轮开头 systemPrompt.assemble() 会拍工具表快照,晚一步就要多等一轮。
28
+ try { onOptionsChanged?.() } catch { /* 装卸失败不影响选项落盘,下一轮 pre-step 还会再对一次 */ }
29
+ // 0.4.6:切档那一下把所有已记住的会话刷新成此刻的现词(两个方向都刷)。
30
+ if (options.toolListRefresh !== refreshBefore) {
31
+ try { onToolListRefreshChanged?.(options.toolListRefresh) } catch { /* 刷新失败不影响选项落盘 */ }
32
+ }
33
+ respond(res, 200, { options })
34
+ })
35
+
36
+ // 语言:设置页那一半读 DSH 的 locale 服务,每次切换就记到这里;注入这一半只读这个文件。
37
+ route(PREFIX + 'locale', async (req, res) => {
38
+ if (req.method === 'GET') {
39
+ respond(res, 200, { locale: readLocaleSync(dshHome) })
40
+ return
41
+ }
42
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'GET / POST' } }); return }
43
+ const body = JSON.parse(await readBody(req) || '{}')
44
+ respond(res, 200, { locale: await writeLocale(dshHome, body.locale) })
45
+ })
46
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * 会话与会话级动作:state / delete / compact-delete / memory-context。
3
+ * 装配 /state 的那一套也在这里(它是这份列表唯一的读者)。
4
+ */
5
+
6
+ import { join } from 'node:path'
7
+ import { stat } from 'node:fs/promises'
8
+ import { memoryDir, readAssembly } from '../../core/store.js'
9
+ import { healthOf, harnessHealthOf } from '../../core/health.js'
10
+ import { effectiveCount, loadLevel, isLevelForced, dayIndex, describeLoad, describeEntry } from '../../core/assembly.js'
11
+ import { diaryReminder } from '../../core/diary.js'
12
+ import { readOptionsSync, REMINDER_SYSTEM } from '../../core/settings.js'
13
+ import { deleteSessionPermanently, sessionDirOf } from '../delete.js'
14
+ import { readDigest } from '../summary.js'
15
+ import { compactThenDelete } from '../compact-delete.js'
16
+ import { respond, readBody } from '../http-util.js'
17
+
18
+ const PREFIX = '/api/session-recall.'
19
+ const digestCache = new Map()
20
+
21
+ /** 会话 id 的短尾巴:标题读不出来时当占位。 */
22
+ function shortId(id) {
23
+ const text = typeof id === 'string' ? id : String(id ?? '')
24
+ return text.length > 8 ? text.slice(0, 8) : text
25
+ }
26
+
27
+ async function cachedDigest(dir) {
28
+ const log = join(dir, 'session.v4.jsonl.zstd')
29
+ let info
30
+ try { info = await stat(log) } catch { return null }
31
+ const key = dir + '|' + info.size + '|' + Math.round(info.mtimeMs)
32
+ const hit = digestCache.get(key)
33
+ if (hit !== undefined) return hit
34
+ const value = readDigest(dir)
35
+ if (digestCache.size > 300) digestCache.clear()
36
+ digestCache.set(key, value)
37
+ return value
38
+ }
39
+
40
+ /**
41
+ * 装配 /state。
42
+ * @param {object} deps
43
+ * @param {string} dshHome
44
+ * @param {{ok:boolean, missing:{block:string,why:string}[], table:object}|null} [snapshot]
45
+ * 启动期能力探测的快照(档 3 E1);没探过就是 null。
46
+ */
47
+ export async function buildState(deps, dshHome, snapshot = null) {
48
+ const options = readOptionsSync(dshHome)
49
+ const persistence = deps.persistence
50
+ if (persistence === undefined) throw new Error('会话持久化不可用')
51
+ const root = persistence.config?.root
52
+ if (typeof root !== 'string' || root === '') throw new Error('会话持久化没有存储根目录')
53
+ // 子代理会话不列:它们的 cwd 与主会话相同,混进来只会是一堆同名行。
54
+ const headers = (await persistence.list())
55
+ .map((row) => row.header ?? row)
56
+ .filter((header) => !(typeof header?.delegationDepth === 'number' && header.delegationDepth > 0))
57
+ const archived = new Set(deps.workspaceRegistry?.archivedSessionIds ?? [])
58
+
59
+ const byCwd = new Map()
60
+ for (const header of headers) {
61
+ const cwd = typeof header.cwd === 'string' ? header.cwd : '(无工作区)'
62
+ if (!byCwd.has(cwd)) byCwd.set(cwd, [])
63
+ byCwd.get(cwd).push(header)
64
+ }
65
+
66
+ const workspaces = []
67
+ for (const [cwd, list] of byCwd) {
68
+ const sessions = []
69
+ for (const header of list) {
70
+ const dir = sessionDirOf(root, header.cwd, header.id)
71
+ const digest = await cachedDigest(dir)
72
+ const title = (digest?.title ?? '').trim()
73
+ // E3:读不出来 ≠ 空会话。没有 zstd / 解不开时不要显示「空会话」(那是假话),
74
+ // 用 id 尾巴占位,并在列表顶部由 digestCode 触发一句说明。
75
+ const digestCode = digest === null ? 'no-log' : (digest.ok === false ? digest.code : '')
76
+ sessions.push({
77
+ id: header.id,
78
+ title: title || (digestCode === 'no-zstd' || digestCode === 'unreadable' ? shortId(header.id) : '空会话'),
79
+ hasTitle: title !== '',
80
+ digestCode,
81
+ userMessages: digest?.userMessages ?? 0,
82
+ createdAt: header.createdAt,
83
+ cwd: header.cwd ?? null,
84
+ archived: archived.has(header.id)
85
+ })
86
+ }
87
+ sessions.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0))
88
+
89
+ // 只从载入文件算:以前这里为每份回顾整份 readFile,只为算几个界面从不显示的字段。
90
+ let memories = []
91
+ if (typeof cwd === 'string' && cwd !== '(无工作区)') {
92
+ const dir = memoryDir(dshHome, cwd)
93
+ const data = await readAssembly(dir, cwd)
94
+ const now = new Date()
95
+ const forced = isLevelForced(options)
96
+ memories = data.entries
97
+ .filter((entry) => entry && typeof entry.file === 'string' && typeof entry.compactedAt === 'string')
98
+ .map((entry) => {
99
+ // 级别每次现算:记号深度会跟着日期与选项一起变,不能缓存。
100
+ const probe = { compactedAt: entry.compactedAt, count: entry.count, pinned: entry.pinned }
101
+ return {
102
+ file: entry.file,
103
+ compactedAt: entry.compactedAt,
104
+ count: entry.count,
105
+ pinned: entry.pinned === true,
106
+ level: loadLevel(probe, now, options),
107
+ markedLevel: effectiveCount(probe, now, options),
108
+ loadForced: forced,
109
+ age: dayIndex(entry.compactedAt, now)
110
+ }
111
+ })
112
+ .sort((a, b) => String(b.compactedAt).localeCompare(String(a.compactedAt)))
113
+ }
114
+ // health:拆回顾最近一次成功/失败(F6)。没有记录就是 null,界面不显示那一行。
115
+ const health = typeof cwd === 'string' && cwd !== '(无工作区)' ? healthOf(dshHome, cwd) : null
116
+ workspaces.push({ cwd, sessions, memories, health })
117
+ }
118
+ workspaces.sort((a, b) => a.cwd.localeCompare(b.cwd))
119
+ return {
120
+ workspaces,
121
+ options,
122
+ // 失败与降级只有一个入口:缺什么能力、本机能力表、宿主层面最近一次失败。
123
+ // 拆回顾失败按工作区记在 workspaces[].health 里,这里只放宿主自己的那条。
124
+ status: {
125
+ ok: snapshot?.ok ?? true,
126
+ missing: snapshot?.missing ?? [],
127
+ capabilities: snapshot?.table ?? {},
128
+ harness: harnessHealthOf(dshHome)
129
+ }
130
+ }
131
+ }
132
+
133
+ /**
134
+ * @param {(path:string, handler:Function) => void} route
135
+ * @param {{dshHome:string, getDeps:Function, waitForSplit?:Function, canLifecycle?:boolean, probe?:Function}} deps
136
+ */
137
+ export function routesSessions(route, { dshHome, getDeps, waitForSplit, canLifecycle, probe }) {
138
+ route(PREFIX + 'state', async (req, res) => {
139
+ if (req.method !== 'GET') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'GET' } }); return }
140
+ const snapshot = typeof probe === 'function' ? probe() : null
141
+ const state = await buildState(getDeps(), dshHome, snapshot)
142
+ // 顶层 capabilities 是档 3 的形状,设置页与档 3 的测试还在读它;新代码只读 status。
143
+ if (snapshot !== null) state.capabilities = snapshot
144
+ respond(res, 200, state)
145
+ })
146
+
147
+ route(PREFIX + 'delete', async (req, res) => {
148
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
149
+ const body = JSON.parse(await readBody(req) || '{}')
150
+ const result = await deleteSessionPermanently(getDeps(), body.sessionId)
151
+ respond(res, result.status, result.ok ? { ok: true, deleted: result.deleted, warnings: result.warnings } : { error: result.error })
152
+ })
153
+
154
+ route(PREFIX + 'memory-context', async (req, res) => {
155
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
156
+ const body = JSON.parse(await readBody(req) || '{}')
157
+ if (typeof body.cwd !== 'string' || body.cwd === '') {
158
+ respond(res, 400, { error: { code: 'invalid-body', message: '需要 cwd' } }); return
159
+ }
160
+ // 选项每一次现读:设置页改完立刻重新取,框里的内容与下一轮注入是同一套装配。
161
+ const options = readOptionsSync(dshHome)
162
+ const now = new Date()
163
+ const disabled = options.injectEnabled === false
164
+ // 带了 file 就只回这一条:设置页选中某条回顾时用它,不必拼整段。
165
+ if (typeof body.file === 'string' && body.file !== '') {
166
+ const one = describeEntry(dshHome, body.cwd, body.file, now, options)
167
+ respond(res, 200, disabled
168
+ ? { cwd: body.cwd, ...one, text: '', chars: 0, disabled: true }
169
+ : { cwd: body.cwd, ...one })
170
+ return
171
+ }
172
+ // 「在上下文提醒」档的提醒并进同一条消息,预览也得带上,否则框里比实况少一段。
173
+ // 注入总开关关着时什么提醒都不算(0.2.8)。
174
+ const reminder = disabled || options.reminderChannel === REMINDER_SYSTEM
175
+ ? ''
176
+ : diaryReminder(dshHome, body.cwd, now, options)
177
+ respond(res, 200, describeLoad(dshHome, body.cwd, now, options, reminder))
178
+ })
179
+
180
+ route(PREFIX + 'compact-delete', async (req, res) => {
181
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
182
+ const body = JSON.parse(await readBody(req) || '{}')
183
+ if (canLifecycle === false) {
184
+ respond(res, 503, { error: { code: 'host-capability', message: '本宿主缺 agents.create/resume,「删除并回顾」已关闭' } })
185
+ return
186
+ }
187
+ try {
188
+ const result = await compactThenDelete(getDeps(), dshHome, body.sessionId, waitForSplit)
189
+ respond(res, 200, result)
190
+ } catch (error) {
191
+ respond(res, 400, { error: { code: 'compact-delete-failed', message: error?.message ?? String(error) } })
192
+ }
193
+ })
194
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * 「自创工具」页的数据:工具组清单的那一段原文,以及导入 / 导出(0.4.3)。
3
+ */
4
+
5
+ import { readOptionsSync } from '../../core/settings.js'
6
+ import { readLocaleSync } from '../../core/locale.js'
7
+ import { catalogText, toolSequenceRoot } from '../../core/schema.js'
8
+ import { exportToolSequence, importToolSequence, MAX_EXPORT_BYTES } from '../../core/tool-transfer.js'
9
+ import { MAX_IMPORT_BODY_BYTES, readBody, respond } from '../http-util.js'
10
+
11
+ const PREFIX = '/api/session-recall.'
12
+
13
+ /** @param {(path:string, handler:Function) => void} route @param {{dshHome:string, onOptionsChanged?:Function}} deps */
14
+ export function routesTools(route, { dshHome, onOptionsChanged }) {
15
+ // 「自创工具」页(0.3.1):工具组清单要注入的那一段原文。
16
+ // 和装配时用的是同一个 catalogText,所以框里看到的就是真的会进系统提示词的那几行。
17
+ // 0.3.10 起再带上工具组目录:设置页在清单标题下面显示「工具路径」,
18
+ // 就是 session_tool_call 去取脚本的那个目录(模型/人都能照着去翻)。
19
+ route(PREFIX + 'toolSequence', async (req, res) => {
20
+ if (req.method !== 'GET') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'GET' } }); return }
21
+ const options = readOptionsSync(dshHome)
22
+ const text = catalogText(dshHome, readLocaleSync(dshHome))
23
+ respond(res, 200, {
24
+ enabled: options.toolListEnabled !== false,
25
+ path: toolSequenceRoot(dshHome),
26
+ text,
27
+ bytes: Buffer.byteLength(text, 'utf8')
28
+ })
29
+ })
30
+
31
+ /**
32
+ * 导出(0.4.3):把工具组目录下的内容打成 toolSequence.zip,**压缩率 0**(store),
33
+ * 直接写进请求里指定的那个工作区文件夹,不走浏览器下载。
34
+ *
35
+ * cwd 只接受已经存在的绝对目录(并且不是磁盘根),写完把真实落点回给界面,
36
+ * 界面把那句话显示出来——用户要的是「文件在哪」,不是一个消失在下载管理里的 zip。
37
+ */
38
+ route(PREFIX + 'toolSequence/export', async (req, res) => {
39
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
40
+ const raw = await readBody(req)
41
+ let body
42
+ try { body = JSON.parse(raw || '{}') } catch { respond(res, 400, { error: { code: 'bad-json', message: '请求体不是 JSON' } }); return }
43
+ let packed
44
+ try {
45
+ packed = await exportToolSequence({ dshHome, dir: body && body.cwd })
46
+ } catch (error) {
47
+ respond(res, 400, { error: { code: 'export-failed', message: error && error.message ? error.message : String(error) } })
48
+ return
49
+ }
50
+ respond(res, 200, {
51
+ ok: true,
52
+ name: packed.name,
53
+ file: packed.file,
54
+ dir: packed.dir,
55
+ method: 'store',
56
+ compressionLevel: 0,
57
+ size: packed.size,
58
+ files: packed.files,
59
+ dirs: packed.dirs,
60
+ overwritten: packed.overwritten,
61
+ path: toolSequenceRoot(dshHome)
62
+ })
63
+ })
64
+
65
+ /**
66
+ * 导入(0.4.3):收一个 zip(base64),先解包校验,再按工具脚本目录逐个落地。
67
+ * dryRun 为真时只报「会装哪些、会盖哪些」,不写盘——设置页要用户点一次确认。
68
+ */
69
+ route(PREFIX + 'toolSequence/import', async (req, res) => {
70
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
71
+ const raw = await readBody(req, MAX_IMPORT_BODY_BYTES)
72
+ let body
73
+ try { body = JSON.parse(raw || '{}') } catch { respond(res, 400, { error: { code: 'bad-json', message: '请求体不是 JSON' } }); return }
74
+ const data = typeof body.data === 'string' ? body.data : ''
75
+ if (data === '') { respond(res, 400, { error: { code: 'missing-file', message: '没有收到包内容' } }); return }
76
+ let buffer
77
+ try { buffer = Buffer.from(data, 'base64') } catch { respond(res, 400, { error: { code: 'bad-base64', message: '包内容不是合法的 base64' } }); return }
78
+ if (buffer.length === 0) { respond(res, 400, { error: { code: 'empty-file', message: '包是空的' } }); return }
79
+
80
+ const dryRun = body.dryRun === true
81
+ let result
82
+ try {
83
+ result = await importToolSequence({ dshHome, buffer, dryRun })
84
+ } catch (error) {
85
+ respond(res, 400, { error: { code: 'import-failed', message: error?.message ?? String(error) } })
86
+ return
87
+ }
88
+ // 真装上了就把工具表立刻对一次;和选项那条路由同一个道理:赶在下一轮 assemble() 之前。
89
+ if (!dryRun) {
90
+ try { onOptionsChanged?.() } catch { /* 同步失败不影响已经落地的文件,下一轮 pre-step 还会再对一次 */ }
91
+ }
92
+ respond(res, 200, {
93
+ ok: true,
94
+ dryRun,
95
+ name: typeof body.name === 'string' ? body.name : 'toolSequence.zip',
96
+ size: buffer.length,
97
+ path: toolSequenceRoot(dshHome),
98
+ imported: result.imported,
99
+ overwritten: result.overwritten,
100
+ skipped: result.skipped
101
+ })
102
+ })
103
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * 会话摘要:标题、条数、最后活动时间。全部从会话日志解出来。
3
+ *
4
+ * E3:把「读不出来」与「没有日志」分开。
5
+ * 以前没有 zstd 的 Node(18/20)上这里静默返回全空,设置页每个会话都叫
6
+ * 「空会话」——那是假话。现在返回 {ok:false, code:'unreadable'|'no-log'},
7
+ * 由界面决定怎么显示;回顾功能本身不经过这里,照常可用。
8
+ * 档 5 起缺原生 zstd 不再是一种错误:core/zstd.js 会走内置解码器。
9
+ */
10
+
11
+ import fs from 'node:fs'
12
+ import { join } from 'node:path'
13
+ import { readSessionEvents, canDecodeZstd } from '../core/zstd.js'
14
+
15
+ const LOG_NAME = 'session.v4.jsonl.zstd'
16
+
17
+ /**
18
+ * 本机能不能解 zstd。档 5 起恒为 true:缺原生 zlib.zstdDecompressSync 时
19
+ * core/zstd.js 会走内置解码器(zstd-js.js),不再需要在这里提前放弃。
20
+ */
21
+ export const CAN_ZSTD = canDecodeZstd()
22
+
23
+ /** 从事件里找标题(session/title 事件优先,其次第一条用户消息)。 */
24
+ function titleOf(events) {
25
+ let title = ''
26
+ for (const e of events) {
27
+ if (e && e.type === 'session/title' && typeof e.data?.title === 'string' && e.data.title.trim() !== '') {
28
+ title = e.data.title.trim()
29
+ }
30
+ }
31
+ if (title !== '') return title
32
+ for (const e of events) {
33
+ if (!e || e.type !== 'user/message') continue
34
+ if (e.data?.source?.kind !== 'user') continue
35
+ const text = (e.data.content ?? []).filter((b) => b && b.type === 'text').map((b) => b.text).join(' ')
36
+ const flat = text.replace(/\s+/g, ' ').trim()
37
+ if (flat !== '') return flat.length > 40 ? flat.slice(0, 40) + '…' : flat
38
+ }
39
+ return ''
40
+ }
41
+
42
+ const EMPTY = { title: '', messages: 0, userMessages: 0, toolCalls: 0, lastAt: null }
43
+
44
+ /**
45
+ * 读一个会话的摘要。
46
+ * @param {string} dir
47
+ * @returns {{ok:true, title:string, messages:number, userMessages:number, toolCalls:number, lastAt:number|null}
48
+ * | {ok:false, code:'no-zstd'|'unreadable'|'no-log', title:string, messages:0, userMessages:0, toolCalls:0, lastAt:null}}
49
+ */
50
+ export function readDigest(dir) {
51
+ const log = join(dir, LOG_NAME)
52
+ if (!fs.existsSync(log)) return { ok: false, code: 'no-log', ...EMPTY }
53
+ // 档 5 起不再有「没有 zstd 就放弃」这一步:原生不在时 readSessionEvents 走内置解码器。
54
+ try {
55
+ const { events, frames, failed } = readSessionEvents(log)
56
+ // 文件在、一帧都没解出来:这不是空会话,是读不了(坏文件/被截断/不是 zstd)。
57
+ if (frames === 0) return { ok: false, code: 'unreadable', ...EMPTY }
58
+ let userMessages = 0
59
+ let toolCalls = 0
60
+ let lastAt = null
61
+ for (const e of events) {
62
+ if (!e) continue
63
+ if (typeof e.time === 'number') lastAt = e.time
64
+ if (e.type === 'user/message' && e.data?.source?.kind === 'user') userMessages++
65
+ else if (e.type === 'assistant/message') toolCalls += (e.data?.message?.content ?? []).filter((b) => b && b.type === 'tool-call').length
66
+ }
67
+ return { ok: true, title: titleOf(events), messages: events.length, userMessages, toolCalls, lastAt }
68
+ } catch {
69
+ return { ok: false, code: 'unreadable', ...EMPTY }
70
+ }
71
+ }