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.
- package/LICENSE +21 -0
- package/README.md +17 -2
- package/client.js +8340 -0
- package/cordis.patch.yml +95 -0
- package/host/browser/index.js +397 -0
- package/host/browser/lib/browser.js +885 -0
- package/host/browser/lib/cdp.js +302 -0
- package/host/browser/lib/libraries.js +309 -0
- package/host/browser/lib/page-scripts.js +243 -0
- package/host/browser/lib/runtime.js +351 -0
- package/host/browser/lib/url-guard.js +122 -0
- package/host/browser/locale/en.json +6 -0
- package/host/browser/locale/zh.json +6 -0
- package/host/chats/index.js +254 -0
- package/host/chats/lib/admin.js +893 -0
- package/host/chats/lib/cleanup.js +272 -0
- package/host/chats/lib/paths.js +108 -0
- package/host/chats/lib/preview.js +74 -0
- package/host/chats/locale/en.json +6 -0
- package/host/chats/locale/zh.json +6 -0
- package/host/files/index.js +403 -0
- package/host/files/locale/en.json +6 -0
- package/host/files/locale/zh.json +6 -0
- package/host/github/index.js +121 -0
- package/host/github/lib/api.js +310 -0
- package/host/github/lib/atomic.js +42 -0
- package/host/github/lib/controller.js +450 -0
- package/host/github/lib/git.js +389 -0
- package/host/github/lib/redact.js +22 -0
- package/host/github/lib/signing.js +124 -0
- package/host/github/lib/store.js +181 -0
- package/host/github/locale/en.json +6 -0
- package/host/github/locale/zh.json +6 -0
- package/host/presets/index.js +450 -0
- package/host/presets/lib/definition.js +267 -0
- package/host/presets/lib/sources.js +278 -0
- package/host/presets/lib/store.js +136 -0
- package/host/presets/locale/en.json +6 -0
- package/host/presets/locale/zh.json +6 -0
- package/host/proxy/index.js +236 -0
- package/host/proxy/lib/controller.js +1151 -0
- package/host/proxy/lib/egress.js +120 -0
- package/host/proxy/lib/local-proxy.js +422 -0
- package/host/proxy/lib/shadowsocks.js +335 -0
- package/host/proxy/lib/ss-uri.js +501 -0
- package/host/proxy/lib/subscriptions.js +140 -0
- package/host/proxy/locale/en.json +6 -0
- package/host/proxy/locale/zh.json +6 -0
- package/host/purge/index.js +538 -0
- package/host/purge/lib/preset.js +140 -0
- package/host/purge/lib/prompts.js +95 -0
- package/host/purge/lib/retry-gate.js +97 -0
- package/host/purge/lib/rewriter.js +322 -0
- package/host/purge/lib/settings.js +54 -0
- package/host/purge/lib/stream-retry.js +255 -0
- package/host/purge/locale/en.json +6 -0
- package/host/purge/locale/zh.json +6 -0
- package/host/purge/presets/unrestricted/agent.cordis.yml +273 -0
- package/host/purge/presets/unrestricted/preset.json +75 -0
- package/host/purge/presets/unrestricted/preset.yml +3 -0
- package/host/rewind/index.js +127 -0
- package/host/rewind/lib/controller.js +449 -0
- package/host/rewind/lib/marker.js +53 -0
- package/host/rewind/lib/safe-path.js +47 -0
- package/host/rewind/lib/store.js +585 -0
- package/host/rewind/lib/surface.js +108 -0
- package/host/rewind/locale/en.json +6 -0
- package/host/rewind/locale/zh.json +6 -0
- package/host/rules/index.js +624 -0
- package/host/rules/lib/paths.js +87 -0
- package/host/rules/lib/render.js +92 -0
- package/host/rules/lib/scope.js +146 -0
- package/host/rules/lib/settings.js +55 -0
- package/host/rules/lib/store.js +222 -0
- package/host/rules/locale/en.json +6 -0
- package/host/rules/locale/zh.json +6 -0
- package/host/runtime/index.js +577 -0
- package/host/runtime/lib/npm.js +293 -0
- package/host/runtime/lib/restart.js +105 -0
- package/host/runtime/lib/update-guard.js +70 -0
- package/host/runtime/lib/versions.js +188 -0
- package/host/runtime/locale/en.json +6 -0
- package/host/runtime/locale/zh.json +6 -0
- package/host/shared/busy.js +40 -0
- package/host/shared/home.js +27 -0
- package/host/shared/http.js +159 -0
- package/host/shared/migrate.js +60 -0
- package/host/shared/mounted.js +54 -0
- package/host/shared/zip-writer.js +319 -0
- package/host/shared/zip.js +180 -0
- package/host/sites/index.js +258 -0
- package/host/sites/lib/sites.js +630 -0
- package/host/sites/locale/en.json +6 -0
- package/host/sites/locale/zh.json +6 -0
- package/host/skills/index.js +176 -0
- package/host/skills/lib/frontmatter.js +149 -0
- package/host/skills/lib/library.js +408 -0
- package/host/skills/lib/upload.js +115 -0
- package/host/skills/locale/en.json +6 -0
- package/host/skills/locale/zh.json +6 -0
- package/icon.png +0 -0
- package/index.js +702 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +5 -0
- package/package.json +113 -4
|
@@ -0,0 +1,893 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The chat inventory and its destructive half.
|
|
3
|
+
*
|
|
4
|
+
* One listing merges the Session corpus (`sessionQuery`), the durability
|
|
5
|
+
* snapshots (`sessionPersistence`), the Workspace registry's archive and pin
|
|
6
|
+
* sets, and — for artifacts on disk — the JSONL backend's own `locate()`.
|
|
7
|
+
*
|
|
8
|
+
* A delete is a process action, not a filesystem one: the chat is flushed,
|
|
9
|
+
* detached from the Session store and announced as removed, because a Host
|
|
10
|
+
* that keeps a loaded chat whose log was unlinked goes on accepting messages
|
|
11
|
+
* that are then lost without a trace. Only after that does the artifact go and
|
|
12
|
+
* the id leave workspace accounting, the archive set, and the pin set.
|
|
13
|
+
*
|
|
14
|
+
* Everything that touches the filesystem is injected, so the module is
|
|
15
|
+
* exercised by `test/admin.test.mjs` without a Harness.
|
|
16
|
+
* @module @local/chat-manager/admin
|
|
17
|
+
*/
|
|
18
|
+
import { createHash } from 'node:crypto'
|
|
19
|
+
import nodeFs from 'node:fs/promises'
|
|
20
|
+
import path from 'node:path'
|
|
21
|
+
import { appError } from '../../shared/http.js'
|
|
22
|
+
import { removeCreatedFiles, removeWorkspaceDirectory } from './cleanup.js'
|
|
23
|
+
import { artifactDirectory, isArtifactDirectoryOf, isInside } from './paths.js'
|
|
24
|
+
import { previewOf } from './preview.js'
|
|
25
|
+
|
|
26
|
+
/** HTTP prefix the panel and the tools share. */
|
|
27
|
+
export const API_PATH = '/chat-manager/api'
|
|
28
|
+
|
|
29
|
+
/** Largest id batch one delete request may carry. */
|
|
30
|
+
export const MAX_DELETE_IDS = 500
|
|
31
|
+
|
|
32
|
+
/** Longest parent chain a delete cascade follows before the lineage counts as corrupt. */
|
|
33
|
+
export const MAX_LINEAGE_DEPTH = 64
|
|
34
|
+
|
|
35
|
+
/** Warning used when the Host cannot be asked whether a chat is still working. */
|
|
36
|
+
const NO_ACTIVITY_WATERFALL = '宿主未提供 workspace/session-activity,删除与归档前未询问会话活动状态。'
|
|
37
|
+
|
|
38
|
+
/** Directory stats run at most this many at a time. */
|
|
39
|
+
const STAT_CONCURRENCY = 8
|
|
40
|
+
|
|
41
|
+
/** Most titles one listing folds from cold logs. */
|
|
42
|
+
export const DEFAULT_TITLE_BUDGET = 160
|
|
43
|
+
|
|
44
|
+
/** Turn any thrown value into a message. */
|
|
45
|
+
export const messageOf = (error) => (error instanceof Error ? error.message : String(error))
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The parent a chat really belongs to.
|
|
49
|
+
*
|
|
50
|
+
* Only a subagent owns a parent session. A historical fork keeps its source id
|
|
51
|
+
* in `parentSession` without being a child of it, and treating that field as
|
|
52
|
+
* lineage deletes an independent branch along with the chat the user picked.
|
|
53
|
+
* @param header - one Session header.
|
|
54
|
+
* @returns the parent id, or null when this chat is a root.
|
|
55
|
+
*/
|
|
56
|
+
export function lineageParentOf(header) {
|
|
57
|
+
if (header?.origin !== 'subagent') return null
|
|
58
|
+
const parent = header.parentSession
|
|
59
|
+
return typeof parent === 'string' && parent !== '' ? parent : null
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Resolve every chat's parent into a forest the panel can recurse over.
|
|
64
|
+
*
|
|
65
|
+
* The panel nests and cascades on `parentSession` alone, so what it receives
|
|
66
|
+
* has to be the Host's own definition of a child chat, and it has to be
|
|
67
|
+
* acyclic: a header pair that names each other would otherwise recurse until
|
|
68
|
+
* the panel dies. A link that closes a cycle is cut here and reported, so the
|
|
69
|
+
* cut is visible instead of silently reshaping the tree.
|
|
70
|
+
* @param headers - Session headers.
|
|
71
|
+
* @returns parents by id (null for a root) and the ids whose link had to be cut.
|
|
72
|
+
*/
|
|
73
|
+
export function lineageForest(headers) {
|
|
74
|
+
const parents = new Map()
|
|
75
|
+
for (const header of headers) parents.set(String(header.id), lineageParentOf(header))
|
|
76
|
+
const broken = []
|
|
77
|
+
for (const start of parents.keys()) {
|
|
78
|
+
const chain = []
|
|
79
|
+
const seen = new Set()
|
|
80
|
+
let current = start
|
|
81
|
+
while (current !== null && !seen.has(current)) {
|
|
82
|
+
seen.add(current)
|
|
83
|
+
chain.push(current)
|
|
84
|
+
current = parents.get(current) ?? null
|
|
85
|
+
}
|
|
86
|
+
// `current` is on this chain again: the last link closes the cycle.
|
|
87
|
+
if (current !== null && seen.has(current)) {
|
|
88
|
+
parents.set(chain[chain.length - 1], null)
|
|
89
|
+
broken.push(chain[chain.length - 1])
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return { parents, broken }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Every subagent descendant of the given roots, depth first.
|
|
97
|
+
*
|
|
98
|
+
* The panel expands a parent selection into its children before asking; the
|
|
99
|
+
* Host does the same so a child filed under another workspace — or created
|
|
100
|
+
* between the listing and the delete — cannot be left behind as an orphan.
|
|
101
|
+
* `visited` keeps a malformed header pair from looping, and the depth cap
|
|
102
|
+
* refuses a chain too long to be real instead of walking it.
|
|
103
|
+
* @param headers - Session headers.
|
|
104
|
+
* @param roots - ids the request named.
|
|
105
|
+
* @returns descendant ids, roots excluded.
|
|
106
|
+
*/
|
|
107
|
+
export function subagentDescendants(headers, roots) {
|
|
108
|
+
const children = new Map()
|
|
109
|
+
for (const header of headers) {
|
|
110
|
+
const parent = lineageParentOf(header)
|
|
111
|
+
if (parent === null) continue
|
|
112
|
+
const id = String(header.id)
|
|
113
|
+
if (!children.has(parent)) children.set(parent, [])
|
|
114
|
+
children.get(parent).push(id)
|
|
115
|
+
}
|
|
116
|
+
const found = []
|
|
117
|
+
const visited = new Set(roots)
|
|
118
|
+
const walk = (id, depth) => {
|
|
119
|
+
if (depth > MAX_LINEAGE_DEPTH) {
|
|
120
|
+
throw appError(`会话血统超过 ${MAX_LINEAGE_DEPTH} 层,已停止删除,请先核对会话血统`, 'chats-lineage-deep', { depth: MAX_LINEAGE_DEPTH })
|
|
121
|
+
}
|
|
122
|
+
for (const child of children.get(id) ?? []) {
|
|
123
|
+
if (visited.has(child)) continue
|
|
124
|
+
visited.add(child)
|
|
125
|
+
found.push(child)
|
|
126
|
+
walk(child, depth + 1)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const root of roots) walk(root, 1)
|
|
130
|
+
return found
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Compare two paths by where they really point.
|
|
135
|
+
*
|
|
136
|
+
* A workspace directory and a chat's `cwd` can name the same place in two
|
|
137
|
+
* spellings (a symlinked home, `/tmp` on macOS, a case-insensitive volume), and
|
|
138
|
+
* the guard that stops a folder delete from taking unselected chats compares
|
|
139
|
+
* them. String comparison silently matched nothing there and the guard let the
|
|
140
|
+
* whole directory go.
|
|
141
|
+
* @param fs - filesystem seam.
|
|
142
|
+
* @param target - path to canonicalize.
|
|
143
|
+
* @returns the real path, or the resolved one when it cannot be resolved.
|
|
144
|
+
*/
|
|
145
|
+
export async function canonicalPath(fs, target) {
|
|
146
|
+
if (typeof target !== 'string' || target === '') return null
|
|
147
|
+
try {
|
|
148
|
+
return await fs.realpath(target)
|
|
149
|
+
} catch {
|
|
150
|
+
return path.resolve(target)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Session-scoped directory the local spill backend keeps one session's files in.
|
|
156
|
+
* @param root - the spill root.
|
|
157
|
+
* @param id - the Session id.
|
|
158
|
+
* @returns the absolute directory.
|
|
159
|
+
*/
|
|
160
|
+
export function spillDirectory(root, id) {
|
|
161
|
+
return path.join(root, `session-${createHash('sha256').update(id).digest('hex').slice(0, 12)}`)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Read one optional Host service without requiring it in `inject`.
|
|
166
|
+
* @param ctx - plugin context.
|
|
167
|
+
* @param name - service key.
|
|
168
|
+
* @returns the service, or undefined in compositions without it.
|
|
169
|
+
*/
|
|
170
|
+
export function optionalService(ctx, name) {
|
|
171
|
+
try {
|
|
172
|
+
if (typeof ctx.get === 'function') {
|
|
173
|
+
const value = ctx.get(name)
|
|
174
|
+
if (value !== undefined) return value
|
|
175
|
+
}
|
|
176
|
+
return ctx[name]
|
|
177
|
+
} catch {
|
|
178
|
+
return undefined
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Resolve the directory holding Session artifacts.
|
|
184
|
+
* @param args - persistence service, plugin config, and process environment.
|
|
185
|
+
* @returns the absolute Session root.
|
|
186
|
+
*/
|
|
187
|
+
export function resolveRoot({ persistence, config = {}, env = process.env } = {}) {
|
|
188
|
+
const configured = typeof config.sessionsRoot === 'string' ? config.sessionsRoot.trim() : ''
|
|
189
|
+
if (configured !== '') return path.resolve(configured)
|
|
190
|
+
const backendRoot = persistence !== undefined && typeof persistence.root === 'string' ? persistence.root : ''
|
|
191
|
+
if (backendRoot !== '') return path.resolve(backendRoot)
|
|
192
|
+
const home = typeof env.DSH_HOME === 'string' && env.DSH_HOME !== '' ? env.DSH_HOME : path.join(env.HOME ?? '', '.dsh')
|
|
193
|
+
return path.join(home, 'sessions')
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Ask a JSONL backend where it keeps one Session, when the backend can say.
|
|
198
|
+
* @param persistence - the persistence service.
|
|
199
|
+
* @param header - the Session header.
|
|
200
|
+
* @returns the artifact directory, or null when the backend cannot locate it.
|
|
201
|
+
*/
|
|
202
|
+
export function locatedDirectory(persistence, header) {
|
|
203
|
+
if (persistence === undefined || typeof persistence.locate !== 'function') return null
|
|
204
|
+
try {
|
|
205
|
+
const location = persistence.locate({ id: header.id, cwd: header.cwd })
|
|
206
|
+
if (location !== null && typeof location === 'object' && typeof location.path === 'string' && location.path !== '') {
|
|
207
|
+
return path.dirname(location.path)
|
|
208
|
+
}
|
|
209
|
+
} catch {
|
|
210
|
+
/* a backend without a filesystem location simply falls through */
|
|
211
|
+
}
|
|
212
|
+
return null
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Build the admin surface over one plugin context.
|
|
217
|
+
* @param args - plugin context, plugin config, and filesystem seams.
|
|
218
|
+
* @returns listing, delete, and archive operations plus the resolved root.
|
|
219
|
+
*/
|
|
220
|
+
export function createAdmin({ ctx, config = {}, fs = nodeFs } = {}) {
|
|
221
|
+
if (ctx === undefined || ctx === null) throw new Error('chat-manager: a plugin context is required')
|
|
222
|
+
|
|
223
|
+
const query = optionalService(ctx, 'sessionQuery')
|
|
224
|
+
const persistence = optionalService(ctx, 'sessionPersistence')
|
|
225
|
+
if (query === undefined || typeof query.listSessions !== 'function') {
|
|
226
|
+
throw new Error('chat-manager: sessionQuery is required')
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Optional services are resolved per call, never captured once: a Service that
|
|
230
|
+
* is still initializing while this row loads reads as undefined here and is
|
|
231
|
+
* present a moment later. Capturing that undefined disabled archiving for the
|
|
232
|
+
* whole process ("这个组合里没有 workspaceRegistry").
|
|
233
|
+
*/
|
|
234
|
+
const optional = (name) => optionalService(ctx, name)
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Ids whose artifact was deleted while the chat was still loaded in this
|
|
238
|
+
* process. The Session store keeps such a chat until its Agent is released,
|
|
239
|
+
* and `sessionQuery.listSessions()` merges live sessions into its listing, so
|
|
240
|
+
* without this the row would come straight back as a missing record.
|
|
241
|
+
* Process-local on purpose: after a restart the store holds neither.
|
|
242
|
+
*/
|
|
243
|
+
const removed = new Set()
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Titles already folded from cold logs, keyed by id and remembered revision.
|
|
247
|
+
*
|
|
248
|
+
* The listing folds a bounded number of logs per call, so without this memory
|
|
249
|
+
* the same 160 chats were re-read on every request while the rest never got a
|
|
250
|
+
* title at all. A null title is remembered too: a chat with no logged title
|
|
251
|
+
* must not keep spending the budget that the others need.
|
|
252
|
+
*/
|
|
253
|
+
const titleMemory = new Map()
|
|
254
|
+
|
|
255
|
+
const titleBudget = Number.isFinite(Number(config.titleBudget)) && Number(config.titleBudget) >= 0
|
|
256
|
+
? Math.floor(Number(config.titleBudget))
|
|
257
|
+
: DEFAULT_TITLE_BUDGET
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* The JSONL root this deployment stores artifacts under.
|
|
261
|
+
* @returns the absolute root directory.
|
|
262
|
+
*/
|
|
263
|
+
function root() {
|
|
264
|
+
return resolveRoot({ persistence, config, env: process.env })
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Cached title of one cold Session, without re-reading its log. */
|
|
268
|
+
function cachedTitle(header) {
|
|
269
|
+
const cache = optional('sessionProjectionCache')
|
|
270
|
+
if (cache === undefined || typeof cache.cachedSnapshot !== 'function') return null
|
|
271
|
+
try {
|
|
272
|
+
const snapshot = cache.cachedSnapshot(header, ['title'])
|
|
273
|
+
const value = snapshot?.values?.title
|
|
274
|
+
return typeof value === 'string' && value !== '' ? value : null
|
|
275
|
+
} catch {
|
|
276
|
+
return null
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Latest title of one live Session. */
|
|
281
|
+
function liveTitle(session) {
|
|
282
|
+
const titleService = optional('sessionTitle')
|
|
283
|
+
if (session === undefined || titleService === undefined || typeof titleService.get !== 'function') return null
|
|
284
|
+
try {
|
|
285
|
+
const snapshot = titleService.get(session)
|
|
286
|
+
return typeof snapshot?.title === 'string' && snapshot.title !== '' ? snapshot.title : null
|
|
287
|
+
} catch {
|
|
288
|
+
return null
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function archivedSet() {
|
|
293
|
+
try {
|
|
294
|
+
return new Set(optional('workspaceRegistry')?.archivedSessionIds ?? [])
|
|
295
|
+
} catch {
|
|
296
|
+
return new Set()
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function pinnedSet() {
|
|
301
|
+
try {
|
|
302
|
+
return new Set(optional('workspaceRegistry')?.pinnedSessionIds ?? [])
|
|
303
|
+
} catch {
|
|
304
|
+
return new Set()
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function workspaceList() {
|
|
309
|
+
const registry = optional('workspaceRegistry')
|
|
310
|
+
if (registry === undefined || typeof registry.list !== 'function') return []
|
|
311
|
+
try {
|
|
312
|
+
return registry.list().map((workspace) => ({
|
|
313
|
+
id: String(workspace.id),
|
|
314
|
+
title: String(workspace.title ?? ''),
|
|
315
|
+
path: String(workspace.path ?? ''),
|
|
316
|
+
sessionIds: Array.isArray(workspace.sessionIds) ? workspace.sessionIds.map(String) : [],
|
|
317
|
+
}))
|
|
318
|
+
} catch {
|
|
319
|
+
return []
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Artifact directory for one header, preferring the backend's own answer. */
|
|
324
|
+
function directoryOf(header) {
|
|
325
|
+
const located = locatedDirectory(persistence, header)
|
|
326
|
+
if (located !== null) return located
|
|
327
|
+
try {
|
|
328
|
+
return artifactDirectory(root(), header.cwd, header.id)
|
|
329
|
+
} catch {
|
|
330
|
+
return null
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Read one artifact directory's own metadata.
|
|
336
|
+
* @returns byte size and last-modified instant, when the directory exists.
|
|
337
|
+
*/
|
|
338
|
+
async function pathStat(target) {
|
|
339
|
+
if (target === null) return null
|
|
340
|
+
try {
|
|
341
|
+
const info = await fs.stat(target)
|
|
342
|
+
return { mtimeMs: Number(info.mtimeMs), isDirectory: info.isDirectory(), isFile: info.isFile() }
|
|
343
|
+
} catch {
|
|
344
|
+
return null
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Fold titles for the chats whose projection cache carried none.
|
|
350
|
+
*
|
|
351
|
+
* Every answer is remembered against the log revision it was folded from, so
|
|
352
|
+
* the next listing reads no log again until that revision changes; the budget
|
|
353
|
+
* then advances through the chats that still have no title instead of
|
|
354
|
+
* re-reading the same first ones.
|
|
355
|
+
* @param entries - `{ id, revision }`, in listing order.
|
|
356
|
+
* @returns the titles this call; a warning when the fold failed outright.
|
|
357
|
+
*/
|
|
358
|
+
async function foldTitles(entries) {
|
|
359
|
+
const found = new Map()
|
|
360
|
+
if (entries.length === 0 || titleBudget === 0) return { found, warning: null }
|
|
361
|
+
const batch = entries.slice(0, titleBudget)
|
|
362
|
+
try {
|
|
363
|
+
const results = await query.readTitleSnapshots(batch.map((entry) => entry.id))
|
|
364
|
+
const answered = new Map()
|
|
365
|
+
for (const result of results ?? []) {
|
|
366
|
+
if (result?.status !== 'fulfilled') continue
|
|
367
|
+
const title = result.value?.title?.title
|
|
368
|
+
answered.set(String(result.sessionId), typeof title === 'string' && title !== '' ? title : null)
|
|
369
|
+
}
|
|
370
|
+
for (const entry of batch) {
|
|
371
|
+
// A rejected read is a failing log, not a chat without a title: leave it
|
|
372
|
+
// out of the memory so the next listing tries it again.
|
|
373
|
+
if (!answered.has(entry.id)) continue
|
|
374
|
+
const title = answered.get(entry.id)
|
|
375
|
+
if (entry.revision !== null) titleMemory.set(entry.id, { revision: entry.revision, title })
|
|
376
|
+
if (title !== null) found.set(entry.id, title)
|
|
377
|
+
}
|
|
378
|
+
return { found, warning: null }
|
|
379
|
+
} catch (error) {
|
|
380
|
+
return { found, warning: `标题回放失败:${messageOf(error)}` }
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Every chat this Host can see, newest activity first.
|
|
386
|
+
* @returns a JSON-safe state document for the panel.
|
|
387
|
+
*/
|
|
388
|
+
async function snapshot() {
|
|
389
|
+
const warnings = []
|
|
390
|
+
const store = optional('sessions')
|
|
391
|
+
const records = await query.listSessions()
|
|
392
|
+
|
|
393
|
+
const durable = new Map()
|
|
394
|
+
if (persistence !== undefined && typeof persistence.list === 'function') {
|
|
395
|
+
try {
|
|
396
|
+
for (const item of await persistence.list()) durable.set(String(item.header.id), item)
|
|
397
|
+
} catch (error) {
|
|
398
|
+
warnings.push(`读取会话存储失败:${messageOf(error)}`)
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const archived = archivedSet()
|
|
403
|
+
const pinned = pinnedSet()
|
|
404
|
+
const workspaces = workspaceList()
|
|
405
|
+
const byPath = new Map(workspaces.map((workspace) => [workspace.path, workspace]))
|
|
406
|
+
const byMember = new Map()
|
|
407
|
+
for (const workspace of workspaces) {
|
|
408
|
+
for (const sessionId of workspace.sessionIds) byMember.set(sessionId, workspace)
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const { parents, broken } = lineageForest(records.map((record) => record.header))
|
|
412
|
+
for (const id of broken) warnings.push(`会话 ${id} 的父会话关系存在环,已按根会话展示。`)
|
|
413
|
+
|
|
414
|
+
const rows = []
|
|
415
|
+
const pendingTitles = []
|
|
416
|
+
for (const record of records) {
|
|
417
|
+
const header = record.header
|
|
418
|
+
const id = String(header.id)
|
|
419
|
+
if (removed.has(id)) continue
|
|
420
|
+
const session = store !== undefined && typeof store.get === 'function' ? store.get(id) : undefined
|
|
421
|
+
const live = session !== undefined || record.live === true
|
|
422
|
+
const item = durable.get(id)
|
|
423
|
+
const revision = typeof item?.revision === 'string' && item.revision !== '' ? item.revision : null
|
|
424
|
+
const agents = optional('agents')
|
|
425
|
+
const running = agents !== undefined && typeof agents.get === 'function'
|
|
426
|
+
? agents.get(id)?.status === 'running'
|
|
427
|
+
: false
|
|
428
|
+
const remembered = revision === null ? undefined : titleMemory.get(id)
|
|
429
|
+
const title = liveTitle(session)
|
|
430
|
+
?? cachedTitle(header)
|
|
431
|
+
?? (remembered !== undefined && remembered.revision === revision ? remembered.title : null)
|
|
432
|
+
if (title === null) pendingTitles.push({ id, revision })
|
|
433
|
+
const workspace = byMember.get(id) ?? (header.cwd === undefined ? undefined : byPath.get(header.cwd))
|
|
434
|
+
const directory = directoryOf(header)
|
|
435
|
+
// The store names the artifact it actually reads; the directory only dates
|
|
436
|
+
// creation and rotation, so activity has to come from the file itself.
|
|
437
|
+
const artifact = typeof item?.location?.path === 'string' && item.location.path !== '' ? item.location.path : null
|
|
438
|
+
rows.push({
|
|
439
|
+
id,
|
|
440
|
+
title,
|
|
441
|
+
cwd: header.cwd ?? null,
|
|
442
|
+
workspaceId: workspace !== undefined ? workspace.id : null,
|
|
443
|
+
workspaceTitle: workspace !== undefined ? workspace.title : null,
|
|
444
|
+
createdAt: header.createdAt,
|
|
445
|
+
artifact,
|
|
446
|
+
bytes: typeof item?.sizeBytes === 'number' ? item.sizeBytes : null,
|
|
447
|
+
live,
|
|
448
|
+
running,
|
|
449
|
+
persisted: record.persisted === true,
|
|
450
|
+
archived: archived.has(id),
|
|
451
|
+
pinned: pinned.has(id),
|
|
452
|
+
origin: header.origin ?? null,
|
|
453
|
+
parentSession: parents.get(id) ?? null,
|
|
454
|
+
delegationDepth: Number.isInteger(header.delegationDepth) ? header.delegationDepth : 0,
|
|
455
|
+
agentPreset: header.agentPreset ?? null,
|
|
456
|
+
directory,
|
|
457
|
+
})
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const { found, warning } = await foldTitles(pendingTitles)
|
|
461
|
+
if (warning !== null) warnings.push(warning)
|
|
462
|
+
|
|
463
|
+
// Bounded concurrency: one stat per row, at most eight in flight, so a
|
|
464
|
+
// thousand chats cost a few hundred milliseconds instead of a minute.
|
|
465
|
+
let cursor = 0
|
|
466
|
+
const worker = async () => {
|
|
467
|
+
while (cursor < rows.length) {
|
|
468
|
+
const row = rows[cursor]
|
|
469
|
+
cursor += 1
|
|
470
|
+
if (row.title === null) row.title = found.get(row.id) ?? null
|
|
471
|
+
const info = await pathStat(row.artifact ?? row.directory)
|
|
472
|
+
row.stored = info !== null && (info.isFile || info.isDirectory)
|
|
473
|
+
row.updatedAt = Math.max(row.createdAt, info?.mtimeMs ?? 0)
|
|
474
|
+
delete row.artifact
|
|
475
|
+
delete row.directory
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
await Promise.all(Array.from({ length: Math.min(STAT_CONCURRENCY, rows.length) }, worker))
|
|
479
|
+
|
|
480
|
+
rows.sort((left, right) => {
|
|
481
|
+
if (right.updatedAt !== left.updatedAt) return right.updatedAt - left.updatedAt
|
|
482
|
+
if (right.createdAt !== left.createdAt) return right.createdAt - left.createdAt
|
|
483
|
+
return left.id < right.id ? -1 : 1
|
|
484
|
+
})
|
|
485
|
+
|
|
486
|
+
// 子会话在面板里折在父会话下面,只是父会话的一部分:把它们的条数与体积
|
|
487
|
+
// 算进总数会出现"共 27 个会话"而界面上只有 12 条。计数的口径与界面上
|
|
488
|
+
// 的一级会话保持一致,`sessions` 里仍然带着子会话,删除照样能级联。
|
|
489
|
+
const roots = rows.filter((row) => row.parentSession === null)
|
|
490
|
+
const totals = {
|
|
491
|
+
all: roots.length,
|
|
492
|
+
active: roots.filter((row) => !row.archived).length,
|
|
493
|
+
archived: roots.filter((row) => row.archived).length,
|
|
494
|
+
live: roots.filter((row) => row.live).length,
|
|
495
|
+
running: roots.filter((row) => row.running).length,
|
|
496
|
+
bytes: roots.reduce((sum, row) => sum + (typeof row.bytes === 'number' ? row.bytes : 0), 0),
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
return {
|
|
500
|
+
generatedAt: new Date().toISOString(),
|
|
501
|
+
root: root(),
|
|
502
|
+
sessions: rows,
|
|
503
|
+
workspaces,
|
|
504
|
+
totals,
|
|
505
|
+
warnings,
|
|
506
|
+
// Whether archive/unarchive can work here at all; the panel hides the
|
|
507
|
+
// control instead of letting a click fail.
|
|
508
|
+
canArchive: typeof optional('workspaceRegistry')?.archiveSession === 'function',
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** Drop one id from the registry's accounting, archive, and pin bookkeeping. */
|
|
513
|
+
async function forget(id, notes) {
|
|
514
|
+
const registry = optional('workspaceRegistry')
|
|
515
|
+
if (registry === undefined) return
|
|
516
|
+
if (typeof registry.list === 'function') {
|
|
517
|
+
let entities = []
|
|
518
|
+
try {
|
|
519
|
+
entities = registry.list()
|
|
520
|
+
} catch {
|
|
521
|
+
entities = []
|
|
522
|
+
}
|
|
523
|
+
for (const workspace of entities) {
|
|
524
|
+
let member = false
|
|
525
|
+
try {
|
|
526
|
+
member = Array.isArray(workspace.sessionIds) && workspace.sessionIds.includes(id)
|
|
527
|
+
} catch {
|
|
528
|
+
member = false
|
|
529
|
+
}
|
|
530
|
+
if (!member || typeof workspace.detachSession !== 'function') continue
|
|
531
|
+
try {
|
|
532
|
+
await workspace.detachSession(id)
|
|
533
|
+
} catch (error) {
|
|
534
|
+
notes.push(`工作区记账未清理(${messageOf(error)})`)
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
for (const method of ['unarchiveSession', 'unpinSession']) {
|
|
539
|
+
if (typeof registry[method] !== 'function') continue
|
|
540
|
+
try {
|
|
541
|
+
await registry[method](id)
|
|
542
|
+
} catch {
|
|
543
|
+
/* an id that was neither archived nor pinned is a no-op, not a failure */
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Ask the Host's own admission waterfall whether a chat still has work.
|
|
550
|
+
*
|
|
551
|
+
* `agents.status` only knows about a running turn of the chat itself; a
|
|
552
|
+
* subagent, a job, or a schedule keeps working without it, and the Host asks
|
|
553
|
+
* this same waterfall before its own archive action. Deleting on the Agent
|
|
554
|
+
* status alone left those chats writing into a log nobody would read again.
|
|
555
|
+
* @param id - the Session id.
|
|
556
|
+
* @param notes - warnings collected for this request.
|
|
557
|
+
* @returns the reported activity; empty when the chat is idle.
|
|
558
|
+
*/
|
|
559
|
+
async function activityOf(id, notes) {
|
|
560
|
+
if (typeof ctx.waterfall !== 'function') {
|
|
561
|
+
// 没有 waterfall 就只剩智能体状态可问;降级本身要说出来,不能当作已确认空闲。
|
|
562
|
+
if (!notes.includes(NO_ACTIVITY_WATERFALL)) notes.push(NO_ACTIVITY_WATERFALL)
|
|
563
|
+
const agents = optional('agents')
|
|
564
|
+
const running = agents !== undefined && typeof agents.get === 'function' && agents.get(id)?.status === 'running'
|
|
565
|
+
return running ? [{ kind: 'turn' }] : []
|
|
566
|
+
}
|
|
567
|
+
const activity = await ctx.waterfall('workspace/session-activity', { sessionId: id }, () => Promise.resolve([]))
|
|
568
|
+
return Array.isArray(activity) ? activity : []
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Take one loaded chat out of this process before its artifact goes away.
|
|
573
|
+
*
|
|
574
|
+
* Flushing first drains what is still buffered, detaching closes the write
|
|
575
|
+
* handle, and the store then emits `session/disposed` — which is what the
|
|
576
|
+
* Host's sidebar listens to. Without the detach the next append writes into an
|
|
577
|
+
* unlinked inode: the message is accepted and gone.
|
|
578
|
+
* @param id - the Session id.
|
|
579
|
+
* @param notes - warnings collected for this request.
|
|
580
|
+
* @returns whether a loaded chat was released.
|
|
581
|
+
*/
|
|
582
|
+
async function releaseLive(id, notes) {
|
|
583
|
+
const store = optional('sessions')
|
|
584
|
+
if (store === undefined || typeof store.get !== 'function') return false
|
|
585
|
+
const live = store.get(id)
|
|
586
|
+
if (live === undefined) return false
|
|
587
|
+
if (typeof store.flush === 'function') {
|
|
588
|
+
try {
|
|
589
|
+
await store.flush(live)
|
|
590
|
+
} catch (error) {
|
|
591
|
+
// 转录已经写不下去时这里会失败;删除仍要继续,但失败要出现在 warnings 里。
|
|
592
|
+
notes.push(`会话缓冲区未能写盘(${messageOf(error)})`)
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
if (typeof store.liveEntryFor !== 'function' || typeof store.detachEntered !== 'function') {
|
|
596
|
+
throw new Error('会话服务未提供 liveEntryFor/detachEntered,无法在删除前分离会话')
|
|
597
|
+
}
|
|
598
|
+
store.detachEntered(store.liveEntryFor(live))
|
|
599
|
+
return true
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** Tell every connected client that this chat no longer exists. */
|
|
603
|
+
function announceRemoval(id, notes) {
|
|
604
|
+
if (typeof ctx.emit !== 'function') {
|
|
605
|
+
notes.push('宿主未提供事件总线,会话移除通知未发出。')
|
|
606
|
+
return
|
|
607
|
+
}
|
|
608
|
+
try {
|
|
609
|
+
ctx.emit('api-session/removed', id)
|
|
610
|
+
} catch (error) {
|
|
611
|
+
notes.push(`会话移除通知未发出(${messageOf(error)})`)
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/** Drop one session's projection-cache row; it is derived data, so a failure is a warning. */
|
|
616
|
+
async function dropProjection(id, notes) {
|
|
617
|
+
const cache = optional('sessionProjectionCache')
|
|
618
|
+
if (cache === undefined || typeof cache.requireTable !== 'function') return
|
|
619
|
+
try {
|
|
620
|
+
await cache.requireTable().delete(id)
|
|
621
|
+
} catch (error) {
|
|
622
|
+
notes.push(`投影缓存行未清理(${messageOf(error)})`)
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** Best-effort removal of the spill directory the local backend keeps for one session. */
|
|
627
|
+
async function dropSpill(id, notes) {
|
|
628
|
+
const spill = optional('spillStore')
|
|
629
|
+
if (spill === undefined || typeof spill.root !== 'string' || spill.root === '') return
|
|
630
|
+
try {
|
|
631
|
+
await fs.rm(spillDirectory(spill.root, id), { recursive: true, force: true })
|
|
632
|
+
} catch (error) {
|
|
633
|
+
notes.push(`临时转储目录未清理(${messageOf(error)})`)
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Delete stored chats. A chat that is merely loaded goes too; only one the
|
|
639
|
+
* Host reports as still working stays, because its remaining events would
|
|
640
|
+
* have nowhere to land.
|
|
641
|
+
* @param request - ids, plus the optional file and workspace cleanup flags.
|
|
642
|
+
* @returns how many artifacts were removed, and why the rest stayed.
|
|
643
|
+
*/
|
|
644
|
+
async function remove(request = {}) {
|
|
645
|
+
const requested = Array.isArray(request.ids) ? request.ids : []
|
|
646
|
+
const ids = [...new Set(
|
|
647
|
+
requested
|
|
648
|
+
.filter((id) => typeof id === 'string')
|
|
649
|
+
.map((id) => id.trim())
|
|
650
|
+
.filter((id) => id !== ''),
|
|
651
|
+
)]
|
|
652
|
+
const deleteFiles = request.deleteFiles === true
|
|
653
|
+
const deleteWorkspaceDir = request.deleteWorkspaceDir === true
|
|
654
|
+
const workspaceId = typeof request.workspaceId === 'string' ? request.workspaceId.trim() : ''
|
|
655
|
+
const workspacePath = typeof request.workspacePath === 'string' ? request.workspacePath.trim() : ''
|
|
656
|
+
// `deleteWorkspace`: the request removes a whole workspace (its registration too).
|
|
657
|
+
const deleteWorkspace = request.deleteWorkspace === true || deleteWorkspaceDir
|
|
658
|
+
if (ids.length === 0 && !deleteWorkspace) throw appError('未指定要删除的会话', 'chats-no-selection')
|
|
659
|
+
|
|
660
|
+
const records = await query.listSessions()
|
|
661
|
+
const headers = new Map(records.map((record) => [String(record.header.id), record.header]))
|
|
662
|
+
const sessionRoot = root()
|
|
663
|
+
const workspaces = workspaceList()
|
|
664
|
+
|
|
665
|
+
// Subagent chats go with their parent; fork branches do not, because
|
|
666
|
+
// `parentSession` on those names a source rather than a parent.
|
|
667
|
+
const targets = new Set(ids)
|
|
668
|
+
for (const id of subagentDescendants(headers.values(), ids)) targets.add(id)
|
|
669
|
+
|
|
670
|
+
// The directory a workspace delete may remove: a registered workspace, or
|
|
671
|
+
// the working directory of a chat in this very request. Never a client path alone.
|
|
672
|
+
let workspaceDir = null
|
|
673
|
+
const registered = deleteWorkspace ? workspaces.find((workspace) => workspace.id === workspaceId) ?? null : null
|
|
674
|
+
if (deleteWorkspace && registered === null && ids.length === 0) throw new Error('找不到要删除的工作区')
|
|
675
|
+
if (deleteWorkspaceDir) {
|
|
676
|
+
if (registered !== null && registered.path !== '') {
|
|
677
|
+
workspaceDir = registered.path
|
|
678
|
+
} else if (workspacePath !== '' && [...targets].some((id) => headers.get(id)?.cwd === workspacePath)) {
|
|
679
|
+
workspaceDir = workspacePath
|
|
680
|
+
} else {
|
|
681
|
+
throw new Error('找不到要删除的工作区目录')
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
// 守护与后续的逐文件清理都要用同一个真实路径,否则符号链接或大小写不同的
|
|
685
|
+
// 两种写法会让"目录里还有未选中会话"这条判断看到零个。
|
|
686
|
+
const workspaceTarget = workspaceDir === null ? null : await canonicalPath(fs, workspaceDir)
|
|
687
|
+
if (workspaceTarget !== null) {
|
|
688
|
+
// Removing the folder takes every chat living in it, so refuse when some of
|
|
689
|
+
// them were not part of this request: the caller can select them and retry.
|
|
690
|
+
const cwdAliases = new Map()
|
|
691
|
+
const canonicalCwd = async (cwd) => {
|
|
692
|
+
if (!cwdAliases.has(cwd)) cwdAliases.set(cwd, await canonicalPath(fs, cwd))
|
|
693
|
+
return cwdAliases.get(cwd)
|
|
694
|
+
}
|
|
695
|
+
let survivors = 0
|
|
696
|
+
for (const record of records) {
|
|
697
|
+
const cwd = record.header?.cwd
|
|
698
|
+
if (typeof cwd !== 'string' || targets.has(String(record.header.id))) continue
|
|
699
|
+
if (await canonicalCwd(cwd) === workspaceTarget) survivors += 1
|
|
700
|
+
}
|
|
701
|
+
if (survivors > 0) {
|
|
702
|
+
throw appError(`该目录中还有 ${survivors} 个未选中的会话,请一并选中后再删除目录`, 'chats-unselected-remain', { count: survivors })
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
// 截断要发生在校验之后:静默少删会留下用户以为已经删掉的会话。
|
|
706
|
+
if (targets.size > MAX_DELETE_IDS) {
|
|
707
|
+
const error = new Error(`本次请求包含 ${targets.size} 个会话(含子会话),一次最多删除 ${MAX_DELETE_IDS} 个,请分批删除`)
|
|
708
|
+
error.appCode = 'delete-too-many'
|
|
709
|
+
error.params = { count: targets.size, limit: MAX_DELETE_IDS }
|
|
710
|
+
throw error
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const deleted = []
|
|
714
|
+
const failed = []
|
|
715
|
+
const notes = []
|
|
716
|
+
let filesDeleted = 0
|
|
717
|
+
|
|
718
|
+
for (const id of targets) {
|
|
719
|
+
const header = headers.get(id)
|
|
720
|
+
if (header === undefined) {
|
|
721
|
+
failed.push({ id, reason: 'unknown' })
|
|
722
|
+
continue
|
|
723
|
+
}
|
|
724
|
+
let activity
|
|
725
|
+
try {
|
|
726
|
+
activity = await activityOf(id, notes)
|
|
727
|
+
} catch (error) {
|
|
728
|
+
failed.push({ id, reason: 'activity-error', detail: `无法确认会话是否仍在工作:${messageOf(error)}` })
|
|
729
|
+
continue
|
|
730
|
+
}
|
|
731
|
+
if (activity.length > 0) {
|
|
732
|
+
failed.push({ id, reason: 'running' })
|
|
733
|
+
continue
|
|
734
|
+
}
|
|
735
|
+
const directory = directoryOf(header)
|
|
736
|
+
const info = directory === null ? null : await pathStat(directory)
|
|
737
|
+
if (info !== null && (!isInside(sessionRoot, directory) || !isArtifactDirectoryOf(sessionRoot, directory, id))) {
|
|
738
|
+
failed.push({ id, reason: 'unsafe-path' })
|
|
739
|
+
continue
|
|
740
|
+
}
|
|
741
|
+
const store = optional('sessions')
|
|
742
|
+
const session = store !== undefined && typeof store.get === 'function' ? store.get(id) : undefined
|
|
743
|
+
if (info === null && session === undefined) {
|
|
744
|
+
// 既没有工件也不在本进程里,没有可删的东西。
|
|
745
|
+
failed.push({ id, reason: 'no-artifact' })
|
|
746
|
+
continue
|
|
747
|
+
}
|
|
748
|
+
// The workspace directory goes as a whole below; file-by-file is only for the rest.
|
|
749
|
+
if (info !== null && deleteFiles
|
|
750
|
+
&& !(workspaceTarget !== null && header.cwd !== undefined && await canonicalPath(fs, header.cwd) === workspaceTarget)) {
|
|
751
|
+
const cleaned = await removeCreatedFiles({
|
|
752
|
+
persistence,
|
|
753
|
+
header,
|
|
754
|
+
directory,
|
|
755
|
+
roots: workspaces.map((workspace) => workspace.path),
|
|
756
|
+
fs,
|
|
757
|
+
})
|
|
758
|
+
filesDeleted += cleaned.removed
|
|
759
|
+
notes.push(...cleaned.notes)
|
|
760
|
+
}
|
|
761
|
+
try {
|
|
762
|
+
await releaseLive(id, notes)
|
|
763
|
+
} catch (error) {
|
|
764
|
+
failed.push({ id, reason: 'detach-failed', detail: `会话无法从存储分离:${messageOf(error)}` })
|
|
765
|
+
continue
|
|
766
|
+
}
|
|
767
|
+
await dropProjection(id, notes)
|
|
768
|
+
if (info !== null) {
|
|
769
|
+
try {
|
|
770
|
+
await fs.rm(directory, { recursive: true, force: true, maxRetries: 2 })
|
|
771
|
+
} catch (error) {
|
|
772
|
+
failed.push({ id, reason: 'io-error', detail: messageOf(error) })
|
|
773
|
+
continue
|
|
774
|
+
}
|
|
775
|
+
await dropSpill(id, notes)
|
|
776
|
+
}
|
|
777
|
+
deleted.push(id)
|
|
778
|
+
if (session !== undefined) removed.add(id)
|
|
779
|
+
titleMemory.delete(id)
|
|
780
|
+
// Forget the id immediately: a crash between removing the artifact and
|
|
781
|
+
// dropping its references would otherwise leave an invisible leftover.
|
|
782
|
+
await forget(id, notes)
|
|
783
|
+
announceRemoval(id, notes)
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
let workspaceDirDeleted = false
|
|
787
|
+
let workspaceRemoved = false
|
|
788
|
+
if (deleteWorkspace && failed.length > 0) {
|
|
789
|
+
notes.push(`有 ${failed.length} 个会话删除失败,工作区${workspaceDir === null ? '' : `和目录 ${workspaceDir} `}已保留`)
|
|
790
|
+
} else if (deleteWorkspace) {
|
|
791
|
+
if (workspaceDir !== null) {
|
|
792
|
+
// 用规范化后的路径删除:同一目录的另一种写法在符号链接下并不指向同一处。
|
|
793
|
+
const outcome = await removeWorkspaceDirectory(workspaceTarget ?? workspaceDir, [sessionRoot], fs)
|
|
794
|
+
workspaceDirDeleted = outcome.removed
|
|
795
|
+
if (outcome.note) notes.push(outcome.note)
|
|
796
|
+
}
|
|
797
|
+
// Drop the registration so the sidebar forgets the workspace, unless its directory was kept by a failure.
|
|
798
|
+
const registry = optional('workspaceRegistry')
|
|
799
|
+
if (registered !== null && (workspaceDir === null || workspaceDirDeleted) && registry !== undefined && typeof registry.delete === 'function') {
|
|
800
|
+
try {
|
|
801
|
+
workspaceRemoved = (await registry.delete(registered.id)) !== false
|
|
802
|
+
} catch (error) {
|
|
803
|
+
notes.push(`工作区登记未移除(${messageOf(error)})`)
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
const state = await snapshot()
|
|
809
|
+
return {
|
|
810
|
+
deleted: deleted.length,
|
|
811
|
+
ids: deleted,
|
|
812
|
+
failed,
|
|
813
|
+
filesDeleted,
|
|
814
|
+
workspaceDirDeleted,
|
|
815
|
+
workspaceRemoved,
|
|
816
|
+
notes,
|
|
817
|
+
state,
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* Move one chat in or out of the registry archive set.
|
|
823
|
+
*
|
|
824
|
+
* Archiving asks the same admission waterfall the delete does. The registry
|
|
825
|
+
* refuses an active session on its own, in the Host's English words, which the
|
|
826
|
+
* panel would then show verbatim; asking first lets this answer in the panel's
|
|
827
|
+
* language, and lets a caller that asked for it stop the work instead.
|
|
828
|
+
* @param request - the id, the desired archive state, and whether running work may be stopped.
|
|
829
|
+
* @returns the accepted state, plus any warning the admission check produced.
|
|
830
|
+
*/
|
|
831
|
+
async function setArchived(request = {}) {
|
|
832
|
+
const registry = optional('workspaceRegistry')
|
|
833
|
+
if (registry === undefined || typeof registry.archiveSession !== 'function') {
|
|
834
|
+
throw new Error('当前组合未提供归档能力(缺少 workspaceRegistry 服务),无法归档或取消归档')
|
|
835
|
+
}
|
|
836
|
+
const id = typeof request.id === 'string' ? request.id.trim() : ''
|
|
837
|
+
if (id === '') throw new Error('未指定会话')
|
|
838
|
+
const archived = request.archived === true
|
|
839
|
+
const notes = []
|
|
840
|
+
if (!archived) {
|
|
841
|
+
await registry.unarchiveSession(id)
|
|
842
|
+
} else {
|
|
843
|
+
const activity = await activityOf(id, notes)
|
|
844
|
+
if (activity.length > 0 && request.stopActivity !== true) {
|
|
845
|
+
const kinds = activity.map((entry) => entry?.kind).filter((kind) => typeof kind === 'string')
|
|
846
|
+
throw new Error(`会话仍有未结束的工作${kinds.length === 0 ? '' : `(${kinds.join('、')})`},请先停止后再归档`)
|
|
847
|
+
}
|
|
848
|
+
// 归档集合本身就是 stopActivity 停止后那些唤醒要读的准入凭据,所以先写集合再停。
|
|
849
|
+
await registry.archiveSession(id, activity.length > 0 ? { stopActivity: true } : undefined)
|
|
850
|
+
}
|
|
851
|
+
const state = await snapshot()
|
|
852
|
+
return { id, archived, notes, state }
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* 一条会话的最后几条对话,供面板的悬停卡片使用。
|
|
857
|
+
*
|
|
858
|
+
* 优先读进程里那份,没加载过才去翻磁盘:预览是只读的,读不到就当 404,不能
|
|
859
|
+
* 让它把别的操作拖住。
|
|
860
|
+
* @param request - `{ sessionId, limit }`。
|
|
861
|
+
* @returns `{ id, turns, messages, live }`。
|
|
862
|
+
*/
|
|
863
|
+
async function preview({ sessionId, limit } = {}) {
|
|
864
|
+
const id = typeof sessionId === 'string' ? sessionId.trim() : ''
|
|
865
|
+
if (id === '') throw appError('未指定要预览的会话', 'chats-preview-no-session')
|
|
866
|
+
if (id === '.' || id === '..' || !/^[A-Za-z0-9._-]+$/.test(id)) throw appError('会话 id 不合法', 'chats-preview-bad-id')
|
|
867
|
+
const count = Number.isFinite(Number(limit)) && Number(limit) > 0 ? Math.min(Math.floor(Number(limit)), 20) : undefined
|
|
868
|
+
const sessionsService = optional('sessions')
|
|
869
|
+
const live = sessionsService !== undefined && typeof sessionsService.get === 'function' ? sessionsService.get(id) : undefined
|
|
870
|
+
if (live !== undefined && typeof live.snapshotEvents === 'function') {
|
|
871
|
+
return { id, live: true, ...previewOf(live.snapshotEvents(), count) }
|
|
872
|
+
}
|
|
873
|
+
if (persistence === undefined || typeof persistence.open !== 'function') {
|
|
874
|
+
throw appError('找不到会话。', 'chats-preview-missing', undefined, 404)
|
|
875
|
+
}
|
|
876
|
+
let handle = null
|
|
877
|
+
try {
|
|
878
|
+
handle = await persistence.open(id, 'read')
|
|
879
|
+
const read = await handle.read()
|
|
880
|
+
return { id, live: false, ...previewOf(read?.events ?? [], count) }
|
|
881
|
+
} catch (error) {
|
|
882
|
+
throw appError(`找不到会话:${messageOf(error)}`, 'chats-preview-missing', undefined, 404)
|
|
883
|
+
} finally {
|
|
884
|
+
try {
|
|
885
|
+
await handle?.close()
|
|
886
|
+
} catch {
|
|
887
|
+
/* 读句柄关不掉不影响结果 */
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
return { root, snapshot, remove, setArchived, preview }
|
|
893
|
+
}
|