dsh-session-manager 0.4.10 → 0.5.1

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/lib/index.js CHANGED
@@ -1,1247 +1,1111 @@
1
- /**
2
- * @dsh-session-manager — Host half.
3
- *
4
- * Cordis plugin that fills three gaps in DSH:
5
- * - delete / unarchive (DSH ships `workspace.archiveSession` but not its inverse);
6
- * - cross-workspace move (DSH indexes workspace membership off the session
7
- * header's immutable `cwd`, so a real move must re-home the artifact);
8
- * - per-conversation Agent-preset migration (rewrite the effective preset
9
- * in place so the next event fold sees the new value).
10
- *
11
- * All durable rewrites go through DSH's own persistence seam (readRaw /
12
- * create / append / flush on the jsonl backend); the JSONL codec chain
13
- * migrates v2 -> v3 transparently, so the emitted artifact is always valid
14
- * for the running DSH build. The plugin never reaches into private DSH
15
- * module paths.
16
- *
17
- * The move and migrate paths do NOT tear down the live agent or session.
18
- * The in-memory session stays alive, the file is rewritten in place under
19
- * a new cwd (move) or a new event is appended to the existing log
20
- * (migrate), and the workspace registry is updated. The api-gateway's
21
- * chat panel therefore remains "available" throughout; the user does not
22
- * have to refresh.
23
- *
24
- * Compat boundary (lib/compat/) is loaded only because the test suite
25
- * asserts a static import; the apply() body inlines the DSH services it
26
- * uses and never instantiates the adapter.
27
- */
28
- import { mkdir, open, readdir, readFile, realpath, rename, rm, stat } from "node:fs/promises";
29
- import { dirname, join } from "node:path";
30
- import { randomBytes } from "node:crypto";
31
- import { createDshAdapter } from "./compat/dsh-adapter.js";
32
- import { decompressAllZstdFrames } from "./compat/zstd-frames.js";
33
-
34
- export const name = "dsh-session-manager";
35
-
36
- export const inject = [
37
- "webServer",
38
- "workspaceRegistry",
39
- "sessions",
40
- "agents",
41
- "sessionPersistence",
42
- "agentPresets"
43
- ];
44
-
45
- /** Like JSON.stringify but swallows circular-reference/BigInt errors so the
46
- * logger never throws while reporting a throw. */
47
- function safeJson(value) { try { return JSON.stringify(value); } catch { return "[unserializable]"; } }
48
- /** Like safeJson but used as the user-facing error string in HTTP responses. */
49
- function safeErrorMessage(error) {
50
- if (error === null || error === undefined) return `<nullish:${typeof error}>`;
51
- if (typeof error === "string") return error;
52
- if (typeof error === "object") {
53
- if (typeof error.message === "string" && error.message.length > 0) return error.message;
54
- if (typeof error.code === "string" && error.code.length > 0) return `[code=${error.code}]`;
55
- }
56
- try { return JSON.stringify(error); } catch { return String(error); }
57
- }
58
- const API_PREFIX = "/session-manager/api";
59
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
60
- function liveWriterOf(persistence, sessionId) {
61
- const writers = persistence?.tracker?.writers;
62
- return typeof writers?.get === "function" ? writers.get(sessionId) : undefined;
63
- }
64
-
65
- /**
66
- * Retarget the existing live JSONL writer after its artifact is relocated.
67
- * The agent loop retains the original SessionHandle until the agent is
68
- * disposed; replacing the tracker entry with a newly opened handle leaves
69
- * that retained handle stale and can make later teardown delete the new
70
- * tracker entry. The compiled DSH handle exposes a writable runtime
71
- * header property even though the TypeScript declaration is readonly.
72
- * Mutating that property keeps the same handle, queue, cursor, and lease.
73
- */
74
- function rebindLiveWriter(persistence, sessionId, newHeader) {
75
- const writer = liveWriterOf(persistence, sessionId);
76
- if (writer === undefined || writer === null) {
77
- throw new Error("当前 DSH 运行时未暴露可重绑定的 live persistence writer,无法安全迁移运行中的会话;请先关闭会话后重试");
78
- }
79
- if (typeof writer.header !== "object" || writer.header === null) {
80
- throw new Error("当前持久化后端的 live writer 不支持安全重绑定;请先关闭会话后重试");
81
- }
82
- const reboundHeader = Object.freeze({ ...newHeader });
83
- writer.header = reboundHeader;
84
- return writer;
85
- }
86
-
87
-
88
- /**
89
- * Encode a session id the way DSH's persistence layer stores its project
90
- * directory: separators and unsafe code units become "--<encoded>--" markers.
91
- * This mirrors the projectKey helper inside the JSONL persistence backend.
92
- * (The name encodeSessionSegment is a leftover from an earlier refactor;
93
- * the function encodes a session id, which DSH derives from a workspace
94
- * path; "project" + "segment" both refer to that same mapping.)
95
- */
96
- const encodeSessionSegment = (id) => {
97
- let readable = "";
98
- let separatorRun = false;
99
- for (let i = 0; i < id.length; i++) {
100
- const ch = id[i];
101
- const code = id.charCodeAt(i);
102
- if (ch === "/" || ch === "\\" || ch === ":") {
103
- if (!separatorRun) readable += "-";
104
- separatorRun = true;
105
- } else if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) {
106
- readable += ch;
107
- separatorRun = false;
108
- } else {
109
- readable += "~" + code.toString(16).toUpperCase().padStart(4, "0");
110
- separatorRun = false;
111
- }
112
- }
113
- return "--" + (readable.replace(/^-+/, "") || "root").slice(0, 251) + "--";
114
- };
115
-
116
- /** List every persisted session header visible to the configured persistence
117
- * backend, supplemented by raw-id sessions written by older DSH builds.
118
- *
119
- * Performance (issue #6): the disk loop previously opened and zstd-decoded
120
- * every candidate file in <dshHome>/sessions/<proj>/<dir>/ even when the
121
- * persistence layer had already returned those ids. On a healthy index
122
- * that wasted O(N * file_size) read+inflate per call -- the reporter
123
- * measured +17s CPU / +254 MB read per DSH startup on an 80-session /
124
- * 249 MB library. We now pre-build a `knownDirs` set from the persisted
125
- * ids (both `[id]` and `[encodeSessionSegment(id)]`) and skip matching
126
- * directories before any fopen. Orphan raw-id directories that the
127
- * index does not know about still fall through to the file read so the
128
- * disk fallback semantics are preserved -- the orphan is the whole
129
- * reason this loop exists.
130
- *
131
- * @param {object|undefined} persistence DSH's sessionPersistence service
132
- * @param {((segment: string) => string)|undefined} dshHome Resolver for
133
- * DSH home sub-paths; only "sessions" is read.
134
- */
135
- const listSessionHeaders = async (persistence, dshHome) => {
136
- const seen = new Set();
137
- const out = [];
138
- if (persistence !== void 0 && typeof persistence.list === "function") {
139
- try {
140
- for (const header of await persistence.list()) {
141
- if (header === void 0 || typeof header.id !== "string") continue;
142
- seen.add(header.id);
143
- out.push(header);
144
- }
145
- } catch { /* fall through to disk */ }
146
- }
147
-
148
- // Early-skip set for the disk fallback. For every id already in `seen`,
149
- // both candidate directory names ([encodeSessionSegment(id), id]) are
150
- // guaranteed to map back to that header; opening those files would only
151
- // re-decode a payload we already have. Mark them up-front and skip with
152
- // an O(1) Set lookup instead of an fopen + inflate + JSON.parse
153
- // roundtrip. Genuine orphans (raw-id sessions the index does not
154
- // surface) are not in `knownDirs` and still fall through to the file
155
- // read below -- the disk fallback semantics are preserved.
156
- const knownDirs = new Set();
157
- for (const id of seen) {
158
- knownDirs.add(id);
159
- knownDirs.add(encodeSessionSegment(id));
160
- }
161
-
162
- if (typeof dshHome !== "function") return out;
163
- const root = dshHome("sessions");
164
- let projects;
165
- try { projects = await readdir(root, { withFileTypes: true }); }
166
- catch { return out; }
167
- for (const proj of projects) {
168
- if (!proj.isDirectory()) continue;
169
- let dirs;
170
- try { dirs = await readdir(join(root, proj.name), { withFileTypes: true }); }
171
- catch { continue; }
172
- for (const entry of dirs) {
173
- if (!entry.isDirectory()) continue;
174
- // Cheap directory-name skip -- the issue #6 hot path fix.
175
- if (knownDirs.has(entry.name)) continue;
176
- for (const filename of ["session.v3.jsonl.zstd", "session.v2.jsonl.zstd", "session.jsonl.zstd", "session.jsonl"]) {
177
- const filePath = join(root, proj.name, entry.name, filename);
178
- try {
179
- const buf = await readFile(filePath);
180
- let content;
181
- if (filename.endsWith(".zstd")) {
182
- // lib/compat/zstd-frames.js#decompressAllZstdFrames walks every
183
- // complete concatenated frame (one frame per DSH batch) and
184
- // concatenates the plaintexts. Throws on empty/header-less
185
- // buffers and on corrupt headers; the outer catch swallows
186
- // both so we move on to the next candidate filename.
187
- try {
188
- const { content: decoded } = await decompressAllZstdFrames(buf);
189
- content = decoded.toString("utf8");
190
- } catch {
191
- continue;
192
- }
193
- } else {
194
- content = buf.toString("utf8");
195
- }
196
- const headerLine = content.split("\n", 1)[0];
197
- const meta = JSON.parse(headerLine);
198
- if (typeof meta?.id !== "string" || seen.has(meta.id)) continue;
199
- seen.add(meta.id);
200
- out.push({ id: meta.id, cwd: meta.cwd, createdAt: meta.createdAt, version: meta.version, origin: meta.origin });
201
- } catch { /* skip */ }
202
- }
203
- }
204
- }
205
- return out;
206
- };
207
- export function apply(ctx) {
208
- const readBody = async (req) => {
209
- const chunks = [];
210
- for await (const chunk of req) chunks.push(Buffer.from(chunk));
211
- return Buffer.concat(chunks).toString("utf8");
212
- };
213
-
214
- const send = (res, code, obj) => {
215
- res.writeHead(code, { "content-type": "application/json; charset=utf-8" });
216
- res.end(JSON.stringify(obj));
217
- };
218
-
219
- /** Remove one id from the registry-global archive set (durable, serialized). */
220
- const unarchiveSession = async (sessionId) => {
221
- const registry = ctx.workspaceRegistry;
222
- await registry.enqueueOperation(async () => {
223
- const state = registry.requireState();
224
- if (!state.archivedSessionIds.includes(sessionId)) return;
225
- await registry.setState({
226
- ...state,
227
- archivedSessionIds: state.archivedSessionIds.filter((id) => id !== sessionId)
228
- });
229
- });
230
- };
231
-
232
- /** Detach one session from every workspace's ordered accounting. */
233
- const detachFromWorkspaces = async (sessionId) => {
234
- for (const entity of ctx.workspaceRegistry.list()) {
235
- if (entity.sessionIds.includes(sessionId)) {
236
- await entity.detachSession(sessionId);
237
- }
238
- }
239
- };
240
-
241
- /** Ordered workspace projection for the client. */
242
- const listWorkspaces = () => {
243
- return ctx.workspaceRegistry.list().map((entity) => {
244
- const rawIds = Array.isArray(entity.record?.sessionIds)
245
- ? [...entity.record.sessionIds]
246
- : [...entity.sessionIds];
247
- return {
248
- id: entity.id,
249
- name: entity.title || entity.id,
250
- title: entity.title || entity.id,
251
- path: entity.path,
252
- sessionCount: rawIds.length,
253
- sessionIds: rawIds
254
- };
255
-
256
- });
257
- };
258
-
259
-
260
- /**
261
- * Durable temp-file write next to its final target. Returns the temp path;
262
- * the caller publishes it with a rename once the coast is clear.
263
- */
264
- const writeTempFile = async (finalPath, data) => {
265
- const temp = `${finalPath}.${randomBytes(6).toString("hex")}.tmp`;
266
- const handle = await open(temp, "wx", 0o600);
267
- try {
268
- await handle.writeFile(data);
269
- await handle.sync();
270
- } finally {
271
- await handle.close();
272
- }
273
- return temp;
274
- };
275
-
276
- /**
277
- * Encode the moved artifact in the backend's own physical layout:
278
- * plain JSONL, or zstd frames whose FIRST frame is exactly the header
279
- * line (the reader's assertZstdHeaderFrame / readFirstZstdLine contract).
280
- */
281
- const encodeArtifact = async (headerLine, rest, isZstd) => {
282
- if (!isZstd) return Buffer.from(`${headerLine}
283
- ${rest}`, "utf8");
284
- const { zstdCompress } = await import("node:zlib");
285
- if (typeof zstdCompress !== "function") {
286
- throw new Error("当前 Node 运行时没有 zstd 支持,无法迁移 zstd 编码的会话工件");
287
- }
288
- const compress = (buffer) => new Promise((resolve, reject) => {
289
- zstdCompress(buffer, (error, output) => error == null ? resolve(output) : reject(error));
290
- });
291
- const headerFrame = await compress(Buffer.from(`${headerLine}\n`, "utf8"));
292
- if (rest === "") return headerFrame;
293
- const bodyFrame = await compress(Buffer.from(rest, "utf8"));
294
- return Buffer.concat([headerFrame, bodyFrame]);
295
- };
296
-
297
- /**
298
- * TRUE cross-workspace move. See the module docstring for the full design:
299
- * re-home the stored cwd, migrate the artifact, then swap accounting.
300
- * Throws an Error with a readable message on every failure path; the
301
- * artifact is restored (or its location reported) whenever a mid-move
302
- * step fails, so the session never ends up in a half-moved state.
303
- */
304
- const moveSession = async (sessionId, targetWorkspaceId) => {
305
- const registry = ctx.workspaceRegistry;
306
- const persistence = ctx.get("sessionPersistence");
307
- const dshHomePath = ctx.get("dshHomePath");
308
- if (persistence === void 0) throw new Error("sessionPersistence 服务不可用");
309
- if (typeof persistence.locate !== "function") {
310
- throw new Error("当前持久化后端无法定位会话工件,无法跨工作区移动");
311
- }
312
-
313
- const target = registry.list().find((entity) => entity.id === targetWorkspaceId);
314
- if (target === void 0) {
315
- const error = new Error(`目标工作区不存在: ${targetWorkspaceId}`);
316
- error.code = "workspace-not-found";
317
- throw error;
318
- }
319
- const targetPath = target.path;
320
-
321
- // Fast path: the common case -- the session is already in the
322
- // persistence index -- costs one .list() + .find(). The previous
323
- // code called listSessionHeaders() unconditionally, which (before
324
- // the issue #6 fix) re-read every file in the session library even
325
- // when the index already had the answer. We still fall through to
326
- // the disk fallback for raw-id orphans persistence.list() cannot
327
- // surface (older DSH builds wrote plain-id directories that the
328
- // index may not know about).
329
- let storedHeader;
330
- if (persistence !== void 0 && typeof persistence.list === "function") {
331
- try {
332
- const headers = await persistence.list();
333
- storedHeader = headers.find((header) =>
334
- header !== void 0 && typeof header.id === "string" && header.id === sessionId
335
- );
336
- } catch { /* fall through to disk fallback below */ }
337
- }
338
- if (storedHeader === void 0) {
339
- const storedHeaders = await listSessionHeaders(persistence, dshHomePath);
340
- storedHeader = storedHeaders.find((header) => header !== void 0 && header.id === sessionId);
341
- }
342
- if (storedHeader === void 0) {
343
- const error = new Error(
344
- `会话 ${sessionId} 没有磁盘记录(不存在,或是一个尚未发送任何消息的空白会话),无法移动`
345
- );
346
- error.code = "session-not-found";
347
- throw error;
348
- }
349
- if (storedHeader.origin === "subagent") {
350
- const error = new Error("子代理(subagent)会话不支持跨工作区移动");
351
- error.code = "subagent-unsupported";
352
- throw error;
353
- }
354
- if (storedHeader.cwd !== void 0) {
355
- let currentCanonical;
356
- try { currentCanonical = await realpath(storedHeader.cwd); } catch { /* re-home below */ }
357
- if (currentCanonical === targetPath) {
358
- return { ok: true, sessionId, moved: false, message: "会话已属于目标工作区" };
359
- }
360
- }
361
-
362
- const liveSession = ctx.sessions.get(sessionId);
363
- if (liveSession !== void 0 && liveWriterOf(persistence, sessionId) === undefined) {
364
- throw new Error("当前 DSH 运行时未暴露可重绑定的 live persistence writer,无法安全迁移运行中的会话;请先关闭会话后重试");
365
- }
366
- let liveAgent;
367
- try { liveAgent = ctx.agents.get(sessionId); } catch { liveAgent = void 0; }
368
- // The 0.4.6+ move path is no-teardown: the live agent/session stays
369
- // alive throughout. We only rewrite the on-disk artifact in place and
370
- // update the in-memory session header to point at the new cwd; the
371
- // api-gateway's chat panel keeps the in-memory session as active.
372
- // The persistence coordinator's per-id serialize() (if available) wraps
373
- // the rewrite so the write-behind cannot append to the hidden file.
374
- // client UI never has to re-init. Just flush pending events to
375
- // disk (still at OLD cwd), then atomically rename the artifact to
376
- // NEW cwd. The persistence coordinator's serialize() inside the
377
- // move block holds the per-id lock, so the write-behind can't append
378
- // to the hidden file. The agent's UI keeps showing the same in-memory
379
- // session -- no client state flip, no half-initialized resume, no
380
- // "session unavailable" symptoms.
381
- if (liveSession !== void 0) {
382
- try { await ctx.sessions.flush(liveSession); } catch { /* best-effort */ }
383
- }
384
-
385
- // No teardown -- the agent and session are still live and that's
386
- // intentional. Move straight to file re-home.
387
- const coordinator = persistence.coordinator;
388
- const serialize = typeof coordinator?.serialize === "function"
389
- ? (operation) => coordinator.serialize(sessionId, operation)
390
- : (operation) => operation();
391
-
392
- const result = await serialize(async () => {
393
- const raw = await readSessionArtifact(sessionId);
394
- if (raw === void 0) throw new Error("读取会话工件失败:未找到会话文件");
395
- const newlineAt = raw.content.indexOf("\n");
396
- if (newlineAt === -1) throw new Error("会话工件缺少头行,数据可能损坏");
397
- const rest = raw.content.slice(newlineAt + 1);
398
- let oldHeader;
399
- try { oldHeader = JSON.parse(raw.content.slice(0, newlineAt)); }
400
- catch (error) { throw new Error(`会话工件头行无法解析: ${String(error)}`); }
401
- if (oldHeader.id !== sessionId) throw new Error("会话工件头行 id 与请求不符,拒绝移动");
402
-
403
- // Keep the stored generation in sync with the filename selected by
404
- // persistence.locate(). Rewriting a v2 header to v0 while locating it
405
- // through the same v2 backend creates a v2 filename with v0 content,
406
- // which makes DSH reject the session on the next startup.
407
- const newHeader = { ...oldHeader, cwd: targetPath };
408
- const oldPath = raw.path ?? persistence.locate(raw.meta)?.path;
409
- const newLocation = persistence.locate(newHeader);
410
- if (typeof oldPath !== "string" || newLocation === void 0) {
411
- throw new Error("持久化后端无法定位会话工件路径");
412
- }
413
- const newPath = newLocation.path;
414
- if (oldPath === newPath) throw new Error("会话源路径与目标路径相同,但 cwd 不一致,拒绝覆盖");
415
- const bytes = await encodeArtifact(JSON.stringify(newHeader), rest, newPath.endsWith(".zstd"));
416
- await mkdir(dirname(newPath), { recursive: true });
417
- const tempNew = await writeTempFile(newPath, bytes);
418
- const oldHidden = `${oldPath}.${randomBytes(6).toString("hex")}.tmp`;
419
- try {
420
- await rename(oldPath, oldHidden);
421
- } catch (error) {
422
- await rm(tempNew, { force: true });
423
- throw new Error(`移动失败(无法隐藏旧会话工件,已取消,会话保持原状): ${String(error)}`);
424
- }
425
- try {
426
- await rename(tempNew, newPath);
427
- } catch (error) {
428
- try { await rename(oldHidden, oldPath); } catch { /* reported below */ }
429
- await rm(tempNew, { force: true });
430
- throw new Error(`移动失败(发布新会话工件失败,已尝试回滚): ${String(error)}`);
431
- }
432
-
433
- const state = coordinator?.states?.get?.(sessionId);
434
- if (state?.owner !== void 0 && liveSession !== void 0 && state.owner !== liveSession) {
435
- await rm(newPath, { force: true });
436
- await rename(oldHidden, oldPath);
437
- throw new Error(`会话 ${sessionId} 的持久化 owner 与当前 live session 不一致,已回滚`);
438
- }
439
- const oldStateMeta = state?.meta;
440
- const oldLiveHeader = liveSession?.header;
441
- const liveWriter = liveSession === void 0 ? void 0 : liveWriterOf(persistence, sessionId);
442
- const oldWriterHeader = liveWriter?.header;
443
- const oldIndexedHeader = registry.headers?.get?.(sessionId);
444
- const oldIndexedPath = registry.sessionPaths?.get?.(sessionId);
445
- const oldInvalidPath = registry.invalidSessionPaths?.get?.(sessionId);
446
- const fromWorkspaceIds = registry.list()
447
- .filter((entity) => entity.id !== target.id && (entity.record?.sessionIds ?? entity.sessionIds).includes(sessionId))
448
- .map((entity) => entity.id);
449
- let targetAttached = false;
450
- const detachedFrom = [];
451
-
452
- try {
453
- if (state !== void 0) {
454
- state.meta = { ...state.meta, ...newHeader, cwd: targetPath };
455
- state.materialized = true;
456
- }
457
- coordinator?.preparations?.invalidate?.(sessionId);
458
- if (liveSession !== void 0) {
459
- liveSession.header = Object.freeze({ ...newHeader });
460
- rebindLiveWriter(persistence, sessionId, newHeader);
461
- }
462
- registry.headers?.set?.(sessionId, { ...newHeader });
463
- registry.sessionPaths?.set?.(sessionId, targetPath);
464
- registry.invalidSessionPaths?.delete?.(sessionId);
465
-
466
- await registry.enqueueOperation(async () => {
467
- for (const id of fromWorkspaceIds) {
468
- const entity = registry.list().find((candidate) => candidate.id === id);
469
- if (entity === void 0) continue;
470
- await entity.detachSession(sessionId);
471
- detachedFrom.push(id);
472
- }
473
- await target.attachSession(sessionId);
474
- targetAttached = true;
475
- });
476
- } catch (error) {
477
- if (state !== void 0 && oldStateMeta !== void 0) state.meta = oldStateMeta;
478
- coordinator?.preparations?.invalidate?.(sessionId);
479
- if (liveSession !== void 0 && oldLiveHeader !== void 0) liveSession.header = oldLiveHeader;
480
- if (liveWriter !== void 0 && oldWriterHeader !== void 0) liveWriter.header = oldWriterHeader;
481
- if (oldIndexedHeader === void 0) registry.headers?.delete?.(sessionId);
482
- else registry.headers?.set?.(sessionId, oldIndexedHeader);
483
- if (oldIndexedPath === void 0) registry.sessionPaths?.delete?.(sessionId);
484
- else registry.sessionPaths?.set?.(sessionId, oldIndexedPath);
485
- if (oldInvalidPath === void 0) registry.invalidSessionPaths?.delete?.(sessionId);
486
- else registry.invalidSessionPaths?.set?.(sessionId, oldInvalidPath);
487
-
488
- const rollbackErrors = [];
489
- try { if (targetAttached) await target.detachSession(sessionId); } catch (e) { rollbackErrors.push(e); }
490
- for (const id of detachedFrom) {
491
- try {
492
- const entity = registry.list().find((candidate) => candidate.id === id);
493
- if (entity !== void 0) await entity.attachSession(sessionId);
494
- } catch (e) { rollbackErrors.push(e); }
495
- }
496
- try { await rm(newPath, { force: true }); } catch (e) { rollbackErrors.push(e); }
497
- try { await rename(oldHidden, oldPath); } catch (e) { rollbackErrors.push(e); }
498
- if (rollbackErrors.length > 0) {
499
- throw new AggregateError([error, ...rollbackErrors], "移动失败且回滚不完整");
500
- }
501
- throw error;
502
- }
503
-
504
- // rebindLiveWriter() above retargeted the existing writer before
505
- // cleanup, so subsequent routed events use the target cwd without
506
- // replacing the handle retained by the live agent.
507
- try { await rm(oldHidden, { force: true }); } catch { /* best-effort */ }
508
- try { await rm(dirname(oldPath), { recursive: true, force: true }); } catch { /* best-effort */ }
509
-
510
- return {
511
- ok: true,
512
- sessionId,
513
- moved: true,
514
- fromWorkspaceIds,
515
- toWorkspaceId: target.id,
516
- toWorkspaceTitle: target.title || target.id,
517
- artifactFrom: oldPath,
518
- artifactTo: newPath,
519
- wasLive: liveSession !== void 0 || liveAgent !== void 0
520
- };
521
- });
522
-
523
- const cache = ctx.get("sessionProjectionCache");
524
- if (cache !== void 0 && typeof cache.coldSnapshot === "function") {
525
- try { await cache.coldSnapshot(sessionId); }
526
- catch (error) { ctx.logger.warn(`session-manager: post-move cache refresh failed for "${sessionId}": ${String(error)}`); }
527
- }
528
- // The agent is still live (no teardown). The session's in-memory
529
- // header was rewritten above and the workspace registry updated;
530
- // future writes go through persistence.locate() against the new
531
- // cwd, so the file at the new location accumulates new events.
532
- // Re-resuming the agent here re-creates a half-initialized
533
- // Session/agent pair and leaves the client UI in a "session
534
- // unavailable" state (agent/status is only emitted on PHASE
535
- // CHANGES, never on agent construction). Leaving the live
536
- // agent/session in place avoids the broken UI entirely.
537
- ctx.logger.info(`session-manager: moved "${sessionId}" to workspace "${target.id}" (in-place file rename, live agent retained)`);
538
- return result;
539
- };
540
- /* === preset-migration (session-manager v0.3.0) === */
541
- const NL = String.fromCharCode(10);
542
-
543
- const scanSelectedEvents = (content) => {
544
- const out = [];
545
- const newlineAt = content.indexOf(NL);
546
- const after = newlineAt === -1 ? content : content.slice(newlineAt + 1);
547
- for (const line of after.split(NL)) {
548
- if (line.length === 0) continue;
549
- let obj;
550
- try { obj = JSON.parse(line); } catch { continue; }
551
- if (obj !== null && typeof obj === "object" && obj.type === "agent-preset/selected" && obj.data !== void 0 && typeof obj.data.agentPreset === "string") {
552
- out.push({ agentPreset: obj.data.agentPreset, time: obj.time, seq: obj.seq });
553
- }
554
- }
555
- return out;
556
- };
557
-
558
- const scanPreset = async (filter) => {
559
- // Pull the full preset roster so the UI shows every available preset,
560
- // not just the ones currently used by some session.
561
- let allPresetIds = [];
562
- try {
563
- const ap = ctx.get("agentPresets");
564
- if (ap !== void 0 && typeof ap.list === "function") {
565
- const list = await ap.list();
566
- for (const p of (list || [])) {
567
- if (p && typeof p.id === "string" && p.id.length > 0) allPresetIds.push(p.id);
568
- }
569
- }
570
- } catch { /* ignore -- fall back to used presets only */ }
571
-
572
- const persistence = ctx.get("sessionPersistence");
573
- if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
574
- // Don't pre-flight check readRaw/list -- the actual JSONL backend
575
- // exposes both. listSessionHeaders is wrapped in try/catch below so
576
- // any missing-method error surfaces as a useful per-session "no
577
- // artifact" message instead of a hard "backend does not support"
578
- // failure that hides which session actually failed.
579
- let headers = [];
580
- try {
581
- headers = await listSessionHeaders(persistence, ctx.get("dshHomePath"));
582
- } catch (probeError) {
583
- throw new Error("failed to enumerate sessions: " + String(probeError.message ?? probeError));
584
- }
585
- let allowedIds = null;
586
- const workspaceId = filter !== void 0 && typeof filter === "object" ? filter.id : void 0;
587
- if (typeof workspaceId === "string" && workspaceId !== "") {
588
- const registry = ctx.get("workspaceRegistry");
589
- if (registry !== void 0 && typeof registry.list === "function") {
590
- const all = registry.list();
591
- const ws = all.find((entity) => entity.id === workspaceId);
592
- if (ws === void 0) {
593
- const error = new Error("workspace not found: " + workspaceId);
594
- error.code = "workspace-not-found";
595
- throw error;
596
- }
597
- allowedIds = new Set();
598
- const ids = typeof ws.sessionIds === "function" ? ws.sessionIds() : ws.sessionIds;
599
- if (Array.isArray(ids)) for (const id of ids) allowedIds.add(id);
600
- }
601
- }
602
- const requestedSessionId = filter !== void 0 && typeof filter === "object" && typeof filter.sessionId === "string"
603
- ? filter.sessionId
604
- : "";
605
- const out = [];
606
- for (const header of headers) {
607
- if (requestedSessionId !== "" && header.id !== requestedSessionId) continue;
608
- if (allowedIds !== null && !allowedIds.has(header.id)) continue;
609
- if (header.origin === "subagent") continue;
610
- const raw = await readSessionArtifact(header.id);
611
- if (raw === void 0) continue;
612
- const newlineAt = raw.content.indexOf(NL);
613
- if (newlineAt === -1) continue;
614
- let headerObj;
615
- try { headerObj = JSON.parse(raw.content.slice(0, newlineAt)); } catch { continue; }
616
- let selected = scanSelectedEvents(raw.content);
617
- const live = ctx.sessions.get(header.id);
618
- if (live !== void 0) {
619
- const liveEvents = Array.isArray(live.events)
620
- ? live.events
621
- : Array.isArray(live.log) ? live.log : [];
622
- const liveSelected = liveEvents
623
- .filter((event) => event?.type === "agent-preset/selected" && typeof event.data?.agentPreset === "string")
624
- .map((event) => ({ agentPreset: event.data.agentPreset, time: event.time, seq: event.seq }));
625
- if (liveSelected.length > selected.length) selected = liveSelected;
626
- }
627
- const finalPreset = selected.length > 0 ? selected[selected.length - 1].agentPreset : headerObj.agentPreset;
628
- out.push({ sessionId: header.id, cwd: header.cwd, origin: header.origin, headerPreset: headerObj.agentPreset, selectedEvents: selected, finalPreset });
629
- }
630
- // Targets come only from the live roster. A deleted preset can still be
631
- // displayed as this session's current value, but must not be offered as
632
- // a destination.
633
- return { rows: out, availablePresets: Array.from(new Set(allPresetIds)) };
634
- };
635
-
636
- /**
637
- * Rewrite the effective preset of one conversation in place on disk.
638
- * The 0.4.6+ flow is no-teardown: when a live session is in store we
639
- * append the new agent-preset/selected event via Session.append() and
640
- * flush through SessionStore.flush(); for cold sessions we rewrite
641
- * the last matching event directly on the existing artifact. In both
642
- * cases the live agent/session is left intact, the api-gateway chat
643
- * panel stays available, and the projection picks up the new value
644
- * on the next event fold.
645
- */
646
- /** Cold-path preset migration: read disk, rewrite, publish. Works whether
647
- * or not the session is currently in the coordinator, and does not depend on
648
- * `coordinator.states` carrying a fresh `meta.cwd`. */
649
- const applyMigrationToArtifact = async (args) => {
650
- const sessionId = typeof args.sessionId === "string" ? args.sessionId : "";
651
- const toPreset = typeof args.toPreset === "string" ? args.toPreset : "";
652
- const liveSession = (args !== void 0 && typeof args === "object") ? args.liveSession : void 0;
653
- const persistence = ctx.get("sessionPersistence");
654
- if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
655
- const coordinator = persistence.coordinator;
656
- const serialize = typeof coordinator?.serialize === "function"
657
- ? (operation) => coordinator.serialize(sessionId, operation)
658
- : (operation) => operation();
659
- return await serialize(async () => {
660
- const raw = await readSessionArtifact(sessionId);
661
- if (raw === void 0) throw new Error(`session "${sessionId}" has no artifact`);
662
- const lines = raw.content.split(NL);
663
- if (lines.length < 2) throw new Error("session artifact has no header line");
664
- let header;
665
- try { header = JSON.parse(lines[0]); } catch { throw new Error("session header parse failed"); }
666
- if (header.id !== sessionId) throw new Error("session header id mismatch");
667
-
668
- let selectedIndex = -1;
669
- let selectedPreset;
670
- for (let index = 1; index < lines.length; index += 1) {
671
- if (lines[index] === "") continue;
672
- let event;
673
- try { event = JSON.parse(lines[index]); } catch { continue; }
674
- if (event?.type === "agent-preset/selected" && typeof event.data?.agentPreset === "string") {
675
- selectedIndex = index;
676
- selectedPreset = event.data.agentPreset;
677
- }
678
- }
679
- const oldPreset = selectedIndex >= 0 ? selectedPreset : header.agentPreset;
680
- if (oldPreset === toPreset) {
681
- return { sessionId, migrated: false, oldPreset, newPreset: toPreset };
682
- }
683
-
684
- if (selectedIndex >= 0) {
685
- const event = JSON.parse(lines[selectedIndex]);
686
- event.data = { ...event.data, agentPreset: toPreset };
687
- lines[selectedIndex] = JSON.stringify(event);
688
- } else {
689
- header.agentPreset = toPreset;
690
- lines[0] = JSON.stringify(header);
691
- }
692
-
693
- const artifactPath = raw.path ?? persistence.locate?.(raw.meta)?.path;
694
- if (typeof artifactPath !== "string") throw new Error("cannot locate session artifact");
695
- const replacementContent = lines.join(NL);
696
- const firstNewline = replacementContent.indexOf(NL);
697
- const bytes = await encodeArtifact(
698
- replacementContent.slice(0, firstNewline),
699
- replacementContent.slice(firstNewline + 1),
700
- artifactPath.endsWith(".zstd")
701
- );
702
- const tempPath = await writeTempFile(artifactPath, bytes);
703
- const hiddenPath = `${artifactPath}.${randomBytes(6).toString("hex")}.tmp`;
704
- try {
705
- await rename(artifactPath, hiddenPath);
706
- await rename(tempPath, artifactPath);
707
- } catch (error) {
708
- try { await rm(artifactPath, { force: true }); } catch { /* best-effort */ }
709
- try { await rename(hiddenPath, artifactPath); } catch { /* reported below */ }
710
- try { await rm(tempPath, { force: true }); } catch { /* best-effort */ }
711
- throw new Error(`preset migration publish failed: ${String(error)}`);
712
- }
713
- try { await rm(hiddenPath, { force: true }); } catch { /* best-effort */ }
714
-
715
- const state = coordinator?.states?.get?.(sessionId);
716
- if (state !== void 0 && selectedIndex < 0) state.meta = { ...state.meta, agentPreset: toPreset };
717
- coordinator?.preparations?.invalidate?.(sessionId);
718
- // Mirror the disk rewrite into the in-memory live session: the cold path
719
- // bypasses the persistence write controller (which is intentionally
720
- // skipped when its state is stale), so the session header, projection,
721
- // and downstream agent composition would otherwise keep reporting the old
722
- // preset. Update both the header and the in-memory event log so DSH's
723
- // `resolveSessionPreset` and any projection subscribers observe the new
724
- // preset from the same source.
725
- if (liveSession !== void 0) {
726
- try {
727
- const nextHeader = { ...(liveSession.header ?? {}), agentPreset: toPreset };
728
- try { liveSession.header = Object.freeze(nextHeader); }
729
- catch { liveSession.header = nextHeader; }
730
- } catch { /* live session may have been retired mid-flight */ }
731
- // Append the new selection to the live log so the session/store
732
- // observers (agent-presets, projections, ctx) fire their normal
733
- // `session/event` + `agent-preset/selected` pipeline. We append
734
- // unconditionally (not only when the disk had no prior selection)
735
- // because the in-memory projection reads the latest appended event
736
- // and the cold path deliberately skipped the persistence write
737
- // controller; the appended event will be persisted on the next
738
- // normal flush, keeping disk and memory consistent.
739
- if (typeof liveSession.append === "function") {
740
- try { liveSession.append("agent-preset/selected", { agentPreset: toPreset }); } catch { /* best-effort */ }
741
- }
742
- }
743
- return { sessionId, migrated: true, oldPreset, newPreset: toPreset };
744
- });
745
- };
746
- /** Rewrite exactly one conversation's effective Agent preset. */
747
- const migratePreset = async (opts) => {
748
- const sessionId = typeof opts.sessionId === "string" ? opts.sessionId.trim() : "";
749
- const toPreset = typeof opts.toPreset === "string" ? opts.toPreset.trim() : "";
750
- if (sessionId === "") { const e = new Error("sessionId required"); e.code = "bad-request"; throw e; }
751
- if (toPreset === "") { const e = new Error("toPreset required"); e.code = "bad-request"; throw e; }
752
-
753
- const presets = ctx.get("agentPresets");
754
- if (presets === void 0 || typeof presets.list !== "function") {
755
- throw new Error("agentPresets service unavailable");
756
- }
757
- const roster = await presets.list();
758
- const target = (roster || []).find((preset) => preset && preset.id === toPreset);
759
- if (target === void 0) {
760
- const available = (roster || []).map((preset) => preset?.id).filter(Boolean);
761
- throw new Error(`Agent 预设 "${toPreset}" 不存在(可用:${available.join(", ")})`);
762
- }
763
- if (target.broken !== void 0) throw new Error(`Agent 预设 "${toPreset}" 不可用:${target.broken}`);
764
-
765
- const liveSession = ctx.sessions.get(sessionId);
766
- let liveAgent;
767
- try { liveAgent = ctx.agents.get(sessionId); } catch { liveAgent = void 0; }
768
- // Resolve persistence up front so the live path can read the coordinator
769
- // without tripping JavaScript's temporal dead zone on `const persistence`.
770
- const persistence = ctx.get("sessionPersistence");
771
- if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
772
-
773
- if (liveSession !== void 0) {
774
- const coordinator = persistence.coordinator;
775
- const states = coordinator?.states;
776
- const beforeState = states?.get?.(sessionId);
777
- const liveCwd = liveSession.header?.cwd;
778
- // A just-completed moveSession mutates `liveSession.header.cwd` in place,
779
- // but the persistence coordinator's tracked state may not see the new cwd
780
- // until its serialize chain drains. If we hand the migration to the
781
- // coordinator now, its `state.meta.cwd` may still be the pre-move cwd and
782
- // appendBatch will open the old (now deleted) artifact path, producing the
783
- // "ENOENT ... session.v2.jsonl.zstd" regression. Falling back to the cold
784
- // path is always correct: the disk copy already reflects the new cwd.
785
- const stateStale = beforeState === void 0
786
- || beforeState.meta?.cwd === void 0
787
- || (liveCwd !== void 0 && beforeState.meta.cwd !== liveCwd);
788
- if (stateStale) {
789
- const raw = await readSessionArtifact(sessionId);
790
- if (raw !== void 0) {
791
- const result = await applyMigrationToArtifact({ sessionId, toPreset, liveSession });
792
- if (result.migrated) { try { ctx.emit("agent-preset/selected", sessionId, toPreset); } catch { /* best-effort */ } }
793
- ctx.logger.info(`session-manager: migrated live preset for "${sessionId}" via cold path (state was stale, live cwd=${String(liveCwd)}, state cwd=${String(beforeState?.meta?.cwd)})`);
794
- return { sessionId, migrated: true, oldPreset: result.oldPreset, newPreset: toPreset };
795
- }
796
- // No artifact yet; fall through to the in-memory + flush path below,
797
- // which materializes the empty file using the live cwd.
798
- }
799
- let oldPreset = liveSession.header?.agentPreset;
800
- // SessionStore implementations from older DSH builds may expose the
801
- // history as `log` rather than the newer `events` snapshot getter.
802
- // Do not dereference `.length` on an absent compatibility surface.
803
- const liveEvents = Array.isArray(liveSession.events)
804
- ? liveSession.events
805
- : Array.isArray(liveSession.log) ? liveSession.log : [];
806
- for (let index = liveEvents.length - 1; index >= 0; index -= 1) {
807
- const event = liveEvents[index];
808
- if (event?.type === "agent-preset/selected" && typeof event.data?.agentPreset === "string") {
809
- oldPreset = event.data.agentPreset;
810
- break;
811
- }
812
- }
813
- if (oldPreset === toPreset) {
814
- return { sessionId, migrated: false, oldPreset, newPreset: toPreset };
815
- }
816
- if (liveAgent !== void 0 && typeof presets?.recompose === "function" && liveAgent.ctx) {
817
- try { await presets.recompose(liveAgent.ctx, toPreset); } catch { /* best-effort */ }
818
- }
819
- liveSession.append("agent-preset/selected", { agentPreset: toPreset });
820
- await ctx.sessions.flush(liveSession);
821
- ctx.logger.info(`session-manager: migrated live preset for "${sessionId}" from "${String(oldPreset)}" to "${toPreset}"`);
822
- return { sessionId, migrated: true, oldPreset, newPreset: toPreset };
823
- }
824
-
825
- // A session absent from SessionStore is cold. If an older plugin left its
826
- // exact Session object in the coordinator, retire that proven orphan by
827
- // the coordinator's own drain path instead of deleting owner bookkeeping.
828
- const coordinator = persistence.coordinator;
829
- let tracked = coordinator?.states?.get?.(sessionId);
830
- if (tracked?.owner !== void 0 && ctx.sessions.get(sessionId) === void 0) {
831
- coordinator.retire?.(tracked.owner);
832
- const retirement = coordinator.retirements?.get?.(sessionId);
833
- if (retirement !== void 0) await retirement;
834
- tracked = coordinator.states?.get?.(sessionId);
835
- if (tracked?.owner !== void 0) {
836
- throw new Error(`会话 ${sessionId} 仍有未释放的持久化 owner,已停止迁移以保护数据`);
837
- }
838
- }
839
-
840
- const result = await applyMigrationToArtifact({ sessionId, toPreset, liveSession });
841
-
842
- if (result.migrated) {
843
- try { ctx.emit("agent-preset/selected", sessionId, toPreset); } catch { /* best-effort */ }
844
- ctx.logger.info(`session-manager: migrated cold preset for "${sessionId}" from "${String(result.oldPreset)}" to "${toPreset}"`);
845
- }
846
- return result;
847
- };
848
-
849
- /** Read one session artifact verbatim, falling back to direct disk access when the
850
- * configured persistence backend cannot see the id (e.g. an older DSH build
851
- * wrote a "session.v2.jsonl.zstd" file under the raw-id directory).
852
- */
853
- const readSessionArtifact = async (sessionId, signal) => {
854
- const persistence = ctx.get("sessionPersistence");
855
- if (persistence !== void 0 && typeof persistence.readRaw === "function") {
856
- try {
857
- const raw = await persistence.readRaw(sessionId, signal);
858
- if (raw !== void 0) {
859
- const located = typeof persistence.locate === "function" ? persistence.locate(raw.meta) : void 0;
860
- // After a cross-workspace move, a backend may return a raw artifact
861
- // whose metadata cache still points at the pre-move cwd. Do not
862
- // hand that stale path to a mutator; verify it and fall through to
863
- // the id-based filesystem scan when it no longer exists.
864
- if (located?.path !== void 0) {
865
- try {
866
- if ((await stat(located.path)).isFile()) {
867
- return { ...raw, path: located.path };
868
- }
869
- } catch { /* stale locate result; scan the durable files below */ }
870
- } else {
871
- return { ...raw };
872
- }
873
- }
874
- } catch { /* fall through to direct disk */ }
875
- }
876
- const dshHomePath = ctx.get("dshHomePath");
877
- if (typeof dshHomePath !== "function") return void 0;
878
- const root = dshHomePath("sessions");
879
- let projects;
880
- try { projects = await readdir(root, { withFileTypes: true }); }
881
- catch { return void 0; }
882
- const encoded = encodeSessionSegment(sessionId);
883
- const { createRequire } = await import("node:module"); const require_ = createRequire(import.meta.url); const { zstdDecompressSync } = require_("node:zlib");
884
- for (const proj of projects) {
885
- if (!proj.isDirectory()) continue;
886
- for (const candidate of [encoded, sessionId]) {
887
- const dir = join(root, proj.name, candidate);
888
- for (const filename of ["session.jsonl.zstd", "session.v2.jsonl.zstd", "session.v3.jsonl.zstd", "session.jsonl"]) {
889
- const filePath = join(dir, filename);
890
- try {
891
- const buf = await readFile(filePath);
892
- let content;
893
- if (filename.endsWith(".zstd")) {
894
- // Node's zstdDecompressSync only decodes the FIRST frame in a
895
- // multi-frame file; DSH writes one frame per batch, so a real
896
- // artifact contains many concatenated frames and the rest is
897
- // otherwise silently lost. Walk every magic-prefixed frame and
898
- // concatenate their plaintexts.
899
- const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
900
- const plaintexts = [];
901
- let pos = 0;
902
- while (pos < buf.length) {
903
- const next = buf.indexOf(ZSTD_MAGIC, pos);
904
- if (next < 0) break;
905
- try {
906
- plaintexts.push(zstdDecompressSync(buf.subarray(next)));
907
- } catch {
908
- break;
909
- }
910
- pos = next + 4;
911
- }
912
- if (plaintexts.length === 0) continue;
913
- content = Buffer.concat(plaintexts).toString("utf8");
914
- } else {
915
- content = buf.toString("utf8");
916
- }
917
- const headerLine = content.split("\n", 1)[0];
918
- let meta;
919
- try { meta = JSON.parse(headerLine); } catch { continue; }
920
- if (typeof meta?.id !== "string" || meta.id !== sessionId) continue;
921
- return { meta, filename, content, path: filePath };
922
- } catch { /* keep scanning */ }
923
- }
924
- }
925
- }
926
- return void 0;
927
- };
928
- const sessionDirOf = async (sessionId) => {
929
- const persistence = ctx.get("sessionPersistence");
930
- if (persistence !== void 0) {
931
- try {
932
- const headers = await persistence.list();
933
- const meta = headers.find((header) => header.id === sessionId);
934
- if (meta !== void 0) {
935
- const location = persistence.locate(meta);
936
- if (location !== void 0) return dirname(location.path);
937
- }
938
- } catch { /* fall through to filesystem scan */ }
939
- }
940
- const dshHomePath = ctx.get("dshHomePath");
941
- if (typeof dshHomePath !== "function") return void 0;
942
- const root = dshHomePath("sessions");
943
- let projects;
944
- try { projects = await readdir(root, { withFileTypes: true }); }
945
- catch { return void 0; }
946
- const encoded = encodeSessionSegment(sessionId);
947
- const candidates = [encoded, sessionId];
948
- for (const proj of projects) {
949
- if (!proj.isDirectory()) continue;
950
- for (const candidate of candidates) {
951
- const dir = join(root, proj.name, candidate);
952
- try {
953
- if ((await stat(dir)).isDirectory()) return dir;
954
- } catch { /* keep scanning */ }
955
- }
956
- }
957
- return void 0;
958
- };
959
-
960
- /**
961
- * Delete one session end to end. Returns a summary of what was torn down.
962
- * Idempotent-ish: unknown sessions resolve to { ok: true, deleted: false }.
963
- */
964
- const deleteSession = async (sessionId) => {
965
- const session = ctx.sessions.get(sessionId);
966
- // 0.1.1-rc.2 throws ApiRemoteSessionNotFound for cold sessions here.
967
- let agent;try{agent=ctx.agents.get(sessionId)}catch{agent=void 0}
968
-
969
- if (agent !== void 0) {
970
- // Stop any running turn (disposed-kind suppresses re-wake).
971
- agent.cancel({ kind: "disposed" });
972
- // Quiesce the agent's own fiber (idempotent; bounded in case teardown stalls).
973
- if (typeof agent.scope?.dispose === "function") {
974
- await Promise.race([agent.scope.dispose(), sleep(3000)]);
975
- }
976
- // Drop the zombie from the registry so a later session.create/open with
977
- // the same id cannot resurrect it.
978
- try {
979
- ctx.agents.store?.delete?.(sessionId);
980
- } catch { /* best-effort */ }
981
- }
982
-
983
- let detached = false;
984
- if (session !== void 0) {
985
- // Flush buffered events to disk first so the retirement drain is a no-op.
986
- try {
987
- await ctx.sessions.flush(session);
988
- } catch { /* best-effort */ }
989
- // Detach the session store entry: emits session/disposed, which the
990
- // persistence write-path answers with a final drain, and the API proxy
991
- // relays as host/session-removed so every connected client drops the row.
992
- try {
993
- const entry = ctx.sessions.store?.get?.(sessionId);
994
- if (entry !== void 0 && typeof entry.detach === "function") {
995
- entry.detach();
996
- await sleep(200); // let the write-behind retirement settle
997
- detached = true;
998
- }
999
- } catch { /* best-effort */ }
1000
- }
1001
- // Some sessions have a stored artifact but no live store row (e.g.
1002
- // already-scoped scope torn down, or never attached). Without a live
1003
- // entry, ctx.sessions.store?.get?.(sessionId) returns undefined and
1004
- // entry.detach() never fires — so the apiproxy never queues a
1005
- // host/session-removed frame, every connected client keeps showing the
1006
- // session row, and the row collapses into the ungrouped section the
1007
- // moment host/workspace-changed drops its workspace membership. Emit
1008
- // session/disposed explicitly so every connected client drops the row.
1009
- if (!detached) {
1010
- try {
1011
- ctx.emit("session/disposed", { id: sessionId });
1012
- } catch (_) { /* best-effort */ }
1013
- }
1014
-
1015
- // Workspace accounting + archive-set membership.
1016
- await detachFromWorkspaces(sessionId);
1017
- await unarchiveSession(sessionId);
1018
-
1019
- // Physical artifact (session.jsonl / session.jsonl.zstd) + any extras.
1020
- const dir = await sessionDirOf(sessionId);
1021
- if (dir !== void 0) {
1022
- await rm(dir, { recursive: true, force: true });
1023
- }
1024
-
1025
- return {
1026
- ok: true,
1027
- sessionId,
1028
- wasLive: session !== void 0 || agent !== void 0,
1029
- filesRemoved: dir !== void 0
1030
- };
1031
- };
1032
-
1033
- /**
1034
- * On plugin boot, refold every persisted session projection cache
1035
- * row from disk. Sessions moved before coldSnapshot was wired into
1036
- * moveSession would otherwise keep their pre-move {createdAt, cwd}
1037
- * identity and let the cold list path fall back to basename(cwd),
1038
- * surfacing the workspace title (for example "DSH") where the
1039
- * session's own title was expected. The sweep is one-shot and
1040
- * idempotent: a row whose identity already matches is a cheap
1041
- * pass-through refold, and a stale one triggers the unrelated-identity
1042
- * full re-read path.
1043
- */
1044
- ctx.effect(async () => {
1045
- const cache = ctx.get("sessionProjectionCache");
1046
- const persistence = ctx.get("sessionPersistence");
1047
- const registry = ctx.get("workspaceRegistry");
1048
- if (cache === void 0 || typeof cache.coldSnapshot !== "function") return;
1049
- if (persistence === void 0 || typeof persistence.list !== "function") return;
1050
- if (registry === void 0 || typeof registry.list !== "function") return;
1051
- try {
1052
- // ---- step 1: re-fold every active session's projection cache row,
1053
- // so a session moved before coldSnapshot was wired in stops being
1054
- // identity-stuck under a stale {createdAt, cwd} key.
1055
- const headers = await listSessionHeaders(persistence, ctx.get("dshHomePath"));
1056
- let refolded = 0;
1057
- const headerById = new Map();
1058
- for (const header of headers) {
1059
- if (header === void 0 || header.cwd === void 0) continue;
1060
- headerById.set(header.id, header);
1061
- try {
1062
- await cache.coldSnapshot(header.id);
1063
- refolded += 1;
1064
- } catch (error) {
1065
- ctx.logger.warn(`session-manager: post-boot cache refold failed for "${header.id}": ${String(error)}`);
1066
- }
1067
- }
1068
- ctx.logger.info(`session-manager: post-boot re-folded ${refolded} session projection cache rows`);
1069
-
1070
- // ---- step 2: reconcile workspace accounting with disk. After a few
1071
- // pre-fix moves, a workspace record could keep a session id whose
1072
- // disk artifact is gone, OR miss a session whose disk artifact is on
1073
- // a matching cwd but not in any record. Both symptoms show up as
1074
- // "AI count higher than visible" / "another session in ungrouped".
1075
- // Walk the registry, drop missing-disk ids, and add missing-in-record
1076
- // ids back into the workspace whose path matches header.cwd.
1077
- const allWorkspaces = registry.list();
1078
- const recordByWs = new Map();
1079
- for (const ws of allWorkspaces) {
1080
- recordByWs.set(ws.id, ws);
1081
- }
1082
- const validIds = new Set(headerById.keys());
1083
- const pathToWs = new Map();
1084
- for (const ws of allWorkspaces) {
1085
- pathToWs.set(ws.path, ws);
1086
- }
1087
- // Pass 1: drop ids whose disk artifact no longer exists.
1088
- let removed = 0;
1089
- for (const ws of allWorkspaces) {
1090
- const filtered = ws.record?.sessionIds?.filter((id) => validIds.has(id));
1091
- const original = ws.record?.sessionIds ?? [];
1092
- if (filtered && filtered.length !== original.length) {
1093
- await registry.enqueueOperation(async () => {
1094
- const state = registry.requireState();
1095
- const w = state.workspaces?.find((s) => s.id === ws.id);
1096
- if (w !== undefined) {
1097
- w.sessionIds = filtered;
1098
- w.updatedAt = new Date().toISOString();
1099
- await registry.setState(state);
1100
- }
1101
- });
1102
- removed += original.length - filtered.length;
1103
- }
1104
- }
1105
- // Pass 2: attach disk-only sessions to the workspace whose path
1106
- // matches their cwd.
1107
- let added = 0;
1108
- for (const header of headers) {
1109
- if (header.cwd === void 0) continue;
1110
- const ws = pathToWs.get(header.cwd);
1111
- if (ws === undefined) continue;
1112
- const rec = ws.record;
1113
- if (rec === undefined || rec.sessionIds === undefined) continue;
1114
- if (rec.sessionIds.includes(header.id)) continue;
1115
- await registry.enqueueOperation(async () => {
1116
- const state = registry.requireState();
1117
- const w = state.workspaces?.find((s) => s.id === ws.id);
1118
- if (w !== undefined && w.sessionIds !== undefined && !w.sessionIds.includes(header.id)) {
1119
- w.sessionIds = [header.id, ...w.sessionIds];
1120
- w.updatedAt = new Date().toISOString();
1121
- await registry.setState(state);
1122
- added += 1;
1123
- }
1124
- });
1125
- }
1126
- if (removed > 0 || added > 0) {
1127
- ctx.logger.info(`session-manager: post-boot workspace reconcile removed ${removed} orphans, attached ${added} disk-only sessions`);
1128
- }
1129
- } catch (error) {
1130
- ctx.logger.warn(`session-manager: post-boot reconcile failed: ${String(error)}`);
1131
- }
1132
- }, "session-manager: post-boot re-fold stale projection cache rows");
1133
-
1134
- ctx.effect(() => ctx.webServer.register({
1135
- kind: "prefix",
1136
- path: API_PREFIX,
1137
- handler: async (req, res) => {
1138
- try {
1139
- const url = new URL(req.url ?? "/", "http://localhost");
1140
- const path = url.pathname.startsWith(API_PREFIX)
1141
- ? url.pathname.slice(API_PREFIX.length) || "/"
1142
- : "/";
1143
- let body = {};
1144
- if (req.method === "POST") {
1145
- const raw = await readBody(req);
1146
- if (raw.trim() !== "") {
1147
- try {
1148
- body = JSON.parse(raw);
1149
- } catch {
1150
- return send(res, 400, { ok: false, error: "请求体不是合法 JSON" });
1151
- }
1152
- }
1153
- }
1154
- const sessionId = typeof body.sessionId === "string" && body.sessionId.trim() !== ""
1155
- ? body.sessionId.trim()
1156
- : null;
1157
-
1158
- if (req.method === "POST" && path === "/delete") {
1159
- if (sessionId === null) return send(res, 400, { ok: false, error: "sessionId 必填" });
1160
- try {
1161
- const result = await deleteSession(sessionId);
1162
- return send(res, 200, { ok: true, result });
1163
- } catch (error) {
1164
- ctx.logger.warn(`session-manager: delete "${sessionId}" failed: ${String(error)}`);
1165
- return send(res, 500, { ok: false, error: String(error instanceof Error ? error.message : error) });
1166
- }
1167
- }
1168
-
1169
- if (req.method === "POST" && path === "/unarchive") {
1170
- if (sessionId === null) return send(res, 400, { ok: false, error: "sessionId 必填" });
1171
- try {
1172
- await unarchiveSession(sessionId);
1173
- return send(res, 200, { ok: true, result: { sessionId } });
1174
- } catch (error) {
1175
- ctx.logger.warn(`session-manager: unarchive "${sessionId}" failed: ${String(error)}`);
1176
- return send(res, 500, { ok: false, error: String(error instanceof Error ? error.message : error) });
1177
- }
1178
- }
1179
-
1180
- if (req.method === "POST" && path === "/move") {
1181
- if (sessionId === null) return send(res, 400, { ok: false, error: "sessionId 必填" });
1182
- const targetWorkspaceId = typeof body.targetWorkspaceId === "string" && body.targetWorkspaceId.trim() !== ""
1183
- ? body.targetWorkspaceId.trim()
1184
- : null;
1185
- if (targetWorkspaceId === null) return send(res, 400, { ok: false, error: "targetWorkspaceId 必填" });
1186
- try {
1187
- const result = await moveSession(sessionId, targetWorkspaceId);
1188
- return send(res, 200, { ok: true, result });
1189
- } catch (error) {
1190
- ctx.logger.warn(`session-manager: api error: ${String(error)}; type=${error?.constructor?.name}; json=${safeJson(error)}`);
1191
- return send(res, 500, { ok: false, error: String(error instanceof Error ? error.message : error) });
1192
- }
1193
- }
1194
-
1195
- if (req.method === "GET" && path === "/workspaces") {
1196
- try {
1197
- const workspaces = listWorkspaces();
1198
- return send(res, 200, { ok: true, result: { workspaces } });
1199
- } catch (error) {
1200
- ctx.logger.warn(`session-manager: listWorkspaces failed: ${String(error)}`);
1201
- return send(res, 500, { ok: false, error: String(error instanceof Error ? error.message : error) });
1202
- }
1203
- }
1204
-
1205
-
1206
-
1207
- if (req.method === "GET" && path === "/preset-scan") {
1208
- try {
1209
- const workspaceId = url.searchParams.get("workspaceId") || "";
1210
- const requestedSessionId = url.searchParams.get("sessionId") || "";
1211
- const filter = {
1212
- ...(workspaceId !== "" ? { id: workspaceId } : {}),
1213
- ...(requestedSessionId !== "" ? { sessionId: requestedSessionId } : {})
1214
- };
1215
- const result = await scanPreset(filter);
1216
- return send(res, 200, { ok: true, result });
1217
- } catch (error) {
1218
- ctx.logger.warn("session-manager: preset-scan failed: " + String(error));
1219
- return send(res, 500, { ok: false, error: String(error.message || error) });
1220
- }
1221
- }
1222
- if (req.method === "POST" && path === "/preset-migrate") {
1223
- const requestedSessionId = typeof body.sessionId === "string" ? body.sessionId.trim() : "";
1224
- const toPreset = typeof body.toPreset === "string" ? body.toPreset.trim() : "";
1225
- if (requestedSessionId === "" || toPreset === "") {
1226
- return send(res, 400, { ok: false, error: "sessionId and toPreset required" });
1227
- }
1228
- try {
1229
- const result = await migratePreset({ sessionId: requestedSessionId, toPreset });
1230
- return send(res, 200, { ok: true, result });
1231
- } catch (error) {
1232
- ctx.logger.warn("session-manager: preset-migrate failed: " + String(error));
1233
- return send(res, 500, { ok: false, error: String(error.message || error) });
1234
- }
1235
- }
1236
-
1237
- return send(res, 404, { ok: false, error: `not found: ${req.method} ${path}` });
1238
- } catch (error) {
1239
- ctx.logger.warn(`session-manager: api error: ${String(error)}; type=${error?.constructor?.name}; json=${safeJson(error)}`);
1240
- return send(res, 500, { ok: false, error: String(error instanceof Error ? error.message : error) });
1241
- }
1242
- } }), "session-manager: http api");
1243
-
1244
-
1245
- }
1246
-
1247
- export { listSessionHeaders, encodeSessionSegment };
1
+ /**
2
+ * @dsh-session-manager — Host half.
3
+ *
4
+ * Cordis plugin that fills three gaps in DSH:
5
+ * - delete / unarchive (DSH ships `workspace.archiveSession` but not its inverse);
6
+ * - cross-workspace move (DSH indexes workspace membership off the session
7
+ * header's immutable `cwd`, so a real move must re-home the artifact);
8
+ * - per-conversation Agent-preset migration (rewrite the effective preset
9
+ * in place so the next event fold sees the new value).
10
+ *
11
+ * Live preset updates use the DSH session store. Cold rewrites and moves
12
+ * validate the durable JSONL/Zstd artifact and preserve its stored format.
13
+ * File mutations are restricted to verified session directories.
14
+ *
15
+ * The move and migrate paths do NOT tear down the live agent or session.
16
+ * The in-memory session stays alive, the file is rewritten in place under
17
+ * a new cwd (move) or a new event is appended to the existing log
18
+ * (migrate), and the workspace registry is updated. The api-gateway's
19
+ * chat panel therefore remains "available" throughout; the user does not
20
+ * have to refresh.
21
+ *
22
+ * The compatibility adapter normalizes service access and list snapshots.
23
+ * Optional live-writer/coordinator internals are guarded before mutation.
24
+ */
25
+ import { lstat, mkdir, readdir, realpath, rename, rm } from "node:fs/promises";
26
+ import { dirname, join } from "node:path";
27
+ import { randomBytes } from "node:crypto";
28
+ import { createAnnotationStore } from "./annotation-store.js";
29
+ import { createDshAdapter, normalizeSessionHeader } from "./compat/dsh-adapter.js";
30
+ import { ARTIFACT_NAMES, assertSessionId, assertSessionDirectory, encodeSessionSegment, readSessionHeader, readSessionFile, writeTempFile, replaceSessionFile } from "./session-files.js";
31
+
32
+ export const name = "dsh-session-manager";
33
+
34
+ export const inject = [
35
+ "webServer",
36
+ "workspaceRegistry",
37
+ "sessions",
38
+ "agents",
39
+ "sessionPersistence",
40
+ "agentPresets"
41
+ ];
42
+
43
+ /** Like JSON.stringify but swallows circular-reference/BigInt errors so the
44
+ * logger never throws while reporting a throw. */
45
+ function safeJson(value) { try { return JSON.stringify(value); } catch { return "[unserializable]"; } }
46
+ /** Like safeJson but used as the user-facing error string in HTTP responses. */
47
+ function safeErrorMessage(error) {
48
+ if (error === null || error === undefined) return `<nullish:${typeof error}>`;
49
+ if (typeof error === "string") return error;
50
+ if (typeof error === "object") {
51
+ if (typeof error.message === "string" && error.message.length > 0) return error.message;
52
+ if (typeof error.code === "string" && error.code.length > 0) return `[code=${error.code}]`;
53
+ }
54
+ try { return JSON.stringify(error); } catch { return String(error); }
55
+ }
56
+ const API_PREFIX = "/session-manager/api";
57
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
58
+ function liveWriterOf(persistence, sessionId) {
59
+ const writers = persistence?.tracker?.writers;
60
+ return typeof writers?.get === "function" ? writers.get(sessionId) : undefined;
61
+ }
62
+
63
+ /**
64
+ * Retarget the existing live JSONL writer after its artifact is relocated.
65
+ * The agent loop retains the original SessionHandle until the agent is
66
+ * disposed; replacing the tracker entry with a newly opened handle leaves
67
+ * that retained handle stale and can make later teardown delete the new
68
+ * tracker entry. The compiled DSH handle exposes a writable runtime
69
+ * header property even though the TypeScript declaration is readonly.
70
+ * Mutating that property keeps the same handle, queue, cursor, and lease.
71
+ */
72
+ function rebindLiveWriter(persistence, sessionId, newHeader) {
73
+ const writer = liveWriterOf(persistence, sessionId);
74
+ if (writer === undefined || writer === null) {
75
+ throw new Error("当前 DSH 运行时未暴露可重绑定的 live persistence writer,无法安全迁移运行中的会话;请先关闭会话后重试");
76
+ }
77
+ if (typeof writer.header !== "object" || writer.header === null) {
78
+ throw new Error("当前持久化后端的 live writer 不支持安全重绑定;请先关闭会话后重试");
79
+ }
80
+ const reboundHeader = Object.freeze({ ...newHeader });
81
+ writer.header = reboundHeader;
82
+ return writer;
83
+ }
84
+
85
+
86
+ /** List every persisted session header visible to the configured persistence
87
+ * backend, supplemented by raw-id sessions written by older DSH builds.
88
+ *
89
+ * Performance (issue #6): the disk loop previously opened and zstd-decoded
90
+ * every candidate file in <dshHome>/sessions/<proj>/<dir>/ even when the
91
+ * persistence layer had already returned those ids. On a healthy index
92
+ * that wasted O(N * file_size) read+inflate per call -- the reporter
93
+ * measured +17s CPU / +254 MB read per DSH startup on an 80-session /
94
+ * 249 MB library. We now pre-build a `knownDirs` set from the persisted
95
+ * ids (both `[id]` and `[encodeSessionSegment(id)]`) and skip matching
96
+ * directories before any fopen. Orphan raw-id directories that the
97
+ * index does not know about still fall through to the file read so the
98
+ * disk fallback semantics are preserved -- the orphan is the whole
99
+ * reason this loop exists.
100
+ *
101
+ * @param {object|undefined} persistence DSH's sessionPersistence service
102
+ * @param {((segment: string) => string)|undefined} dshHome Resolver for
103
+ * DSH home sub-paths; only "sessions" is read.
104
+ */
105
+ const scanSessionHeaders = async (persistence, dshHome) => {
106
+ const seen = new Set();
107
+ const headers = [];
108
+ const errors = [];
109
+ let listed = false;
110
+ if (typeof persistence?.list === "function") {
111
+ try {
112
+ const rows = await persistence.list();
113
+ if (!Array.isArray(rows)) throw new Error("会话列表返回了无效数据");
114
+ for (const row of rows) {
115
+ const header = normalizeSessionHeader(row);
116
+ if (!header) { errors.push(new Error("会话列表包含无效 header")); continue; }
117
+ try { assertSessionId(header.id); }
118
+ catch (error) { errors.push(error); continue; }
119
+ if (!seen.has(header.id)) { seen.add(header.id); headers.push(header); }
120
+ }
121
+ listed = true;
122
+ } catch (error) { errors.push(error); }
123
+ }
124
+ const result = () => ({ headers, complete: listed && errors.length === 0, errors });
125
+ // Skip known files before fopen; retain the orphan/raw-id compatibility path.
126
+ const knownDirs = new Set();
127
+ for (const id of seen) {
128
+ knownDirs.add(id);
129
+ knownDirs.add(encodeSessionSegment(id));
130
+ }
131
+ if (typeof dshHome !== "function") return result();
132
+ const root = dshHome("sessions");
133
+ let projects;
134
+ try { projects = await readdir(root, { withFileTypes: true }); }
135
+ catch (error) { errors.push(error); return result(); }
136
+ listed = true;
137
+ for (const proj of projects) {
138
+ if (proj.isSymbolicLink()) { errors.push(new Error("跳过符号链接项目目录")); continue; }
139
+ if (!proj.isDirectory()) continue;
140
+ let dirs;
141
+ try { dirs = await readdir(join(root, proj.name), { withFileTypes: true }); }
142
+ catch (error) { errors.push(error); continue; }
143
+ for (const entry of dirs) {
144
+ if (entry.isSymbolicLink()) { errors.push(new Error("跳过符号链接会话目录")); continue; }
145
+ if (!entry.isDirectory()) continue;
146
+ if (knownDirs.has(entry.name)) continue;
147
+ let found = false;
148
+ for (const filename of ARTIFACT_NAMES) {
149
+ try {
150
+ const header = await readSessionHeader(join(root, proj.name, entry.name, filename));
151
+ if (![header.id, encodeSessionSegment(header.id)].includes(entry.name)) {
152
+ throw new Error("会话目录与 header id 不一致");
153
+ }
154
+ if (!seen.has(header.id)) { seen.add(header.id); headers.push(header); }
155
+ found = true;
156
+ break;
157
+ } catch (error) {
158
+ if (error.code !== "ENOENT") { errors.push(error); break; }
159
+ }
160
+ }
161
+ if (!found) errors.push(new Error("无法完整读取会话目录: " + join(root, proj.name, entry.name)));
162
+ }
163
+ }
164
+ return result();
165
+ };
166
+
167
+ const listSessionHeaders = async (persistence, dshHome) => (await scanSessionHeaders(persistence, dshHome)).headers;
168
+
169
+ export function apply(ctx) {
170
+ const adapter = createDshAdapter(ctx);
171
+ let annotationStore;
172
+ const annotations = () => {
173
+ if (!annotationStore) {
174
+ const home = adapter.homePath;
175
+ if (typeof home !== "function") throw Object.assign(new Error("会话标记存储不可用"), { code: "annotations-unavailable" });
176
+ annotationStore = createAnnotationStore(home("dsh-session-manager"));
177
+ }
178
+ return annotationStore;
179
+ };
180
+ const assertAnnotatable = id => {
181
+ const registry = adapter.workspaceRegistry;
182
+ if (adapter.getSession(id) !== undefined || registry?.headers?.has?.(id)
183
+ || adapter.workspaceList().some(ws => (ws.record?.sessionIds ?? ws.sessionIds ?? []).includes(id))) return;
184
+ throw Object.assign(new Error("会话不存在或尚未加载,请先打开该会话后重试"), { code: "session-not-found" });
185
+ };
186
+ const operations = new Map();
187
+ const mutate = (id, operation) => {
188
+ const pending = (operations.get(id) ?? Promise.resolve()).then(operation);
189
+ const settled = pending.catch(() => {}).finally(() => {
190
+ if (operations.get(id) === settled) operations.delete(id);
191
+ });
192
+ operations.set(id, settled);
193
+ return pending;
194
+ };
195
+ const readBody = async (req) => {
196
+ const chunks = [];
197
+ let size = 0;
198
+ for await (const chunk of req) {
199
+ const bytes = Buffer.from(chunk);
200
+ size += bytes.length;
201
+ if (size > 64 * 1024) throw Object.assign(new Error("请求体超过 64 KiB"), { code: "body-too-large" });
202
+ chunks.push(bytes);
203
+ }
204
+ return Buffer.concat(chunks).toString("utf8");
205
+ };
206
+
207
+ const send = (res, code, obj) => {
208
+ res.writeHead(code, { "content-type": "application/json; charset=utf-8" });
209
+ res.end(JSON.stringify(obj));
210
+ };
211
+
212
+ /** Remove one id from the registry-global archive set (durable, serialized). */
213
+ const unarchiveSession = async (sessionId) => {
214
+ const registry = ctx.workspaceRegistry;
215
+ await registry.enqueueOperation(async () => {
216
+ const state = registry.requireState();
217
+ if (!state.archivedSessionIds.includes(sessionId)) return;
218
+ await registry.setState({
219
+ ...state,
220
+ archivedSessionIds: state.archivedSessionIds.filter((id) => id !== sessionId)
221
+ });
222
+ });
223
+ };
224
+
225
+ /** Detach one session from every workspace's ordered accounting. */
226
+ const detachFromWorkspaces = async (sessionId) => {
227
+ for (const entity of ctx.workspaceRegistry.list()) {
228
+ if (entity.sessionIds.includes(sessionId)) {
229
+ await entity.detachSession(sessionId);
230
+ }
231
+ }
232
+ };
233
+
234
+ /** Ordered workspace projection for the client. */
235
+ const listWorkspaces = () => {
236
+ return ctx.workspaceRegistry.list().map((entity) => {
237
+ const rawIds = Array.isArray(entity.record?.sessionIds)
238
+ ? [...entity.record.sessionIds]
239
+ : [...entity.sessionIds];
240
+ return {
241
+ id: entity.id,
242
+ name: entity.title || entity.id,
243
+ title: entity.title || entity.id,
244
+ path: entity.path,
245
+ sessionCount: rawIds.length,
246
+ sessionIds: rawIds
247
+ };
248
+
249
+ });
250
+ };
251
+
252
+
253
+ /**
254
+ * Encode the moved artifact in the backend's own physical layout:
255
+ * plain JSONL, or zstd frames whose FIRST frame is exactly the header
256
+ * line (the reader's assertZstdHeaderFrame / readFirstZstdLine contract).
257
+ */
258
+ const encodeArtifact = async (headerLine, rest, isZstd) => {
259
+ if (!isZstd) return Buffer.from(`${headerLine}
260
+ ${rest}`, "utf8");
261
+ const { zstdCompress } = await import("node:zlib");
262
+ if (typeof zstdCompress !== "function") {
263
+ throw new Error("当前 Node 运行时没有 zstd 支持,无法迁移 zstd 编码的会话工件");
264
+ }
265
+ const compress = (buffer) => new Promise((resolve, reject) => {
266
+ zstdCompress(buffer, (error, output) => error == null ? resolve(output) : reject(error));
267
+ });
268
+ const headerFrame = await compress(Buffer.from(`${headerLine}\n`, "utf8"));
269
+ if (rest === "") return headerFrame;
270
+ const bodyFrame = await compress(Buffer.from(rest, "utf8"));
271
+ return Buffer.concat([headerFrame, bodyFrame]);
272
+ };
273
+
274
+ /**
275
+ * TRUE cross-workspace move. See the module docstring for the full design:
276
+ * re-home the stored cwd, migrate the artifact, then swap accounting.
277
+ * Throws an Error with a readable message on every failure path; the
278
+ * artifact is restored (or its location reported) whenever a mid-move
279
+ * step fails, so the session never ends up in a half-moved state.
280
+ */
281
+ const moveSession = async (sessionId, targetWorkspaceId) => {
282
+ assertSessionId(sessionId);
283
+ const registry = ctx.workspaceRegistry;
284
+ const persistence = adapter.persistence;
285
+ const dshHomePath = adapter.homePath;
286
+ if (persistence === void 0) throw new Error("sessionPersistence 服务不可用");
287
+ if (typeof persistence.locate !== "function") {
288
+ throw new Error("当前持久化后端无法定位会话工件,无法跨工作区移动");
289
+ }
290
+
291
+ const target = registry.list().find((entity) => entity.id === targetWorkspaceId);
292
+ if (target === void 0) {
293
+ const error = new Error(`目标工作区不存在: ${targetWorkspaceId}`);
294
+ error.code = "workspace-not-found";
295
+ throw error;
296
+ }
297
+ const targetPath = target.path;
298
+
299
+ // Fast path: the common case -- the session is already in the
300
+ // persistence index -- costs one .list() + .find(). The previous
301
+ // code called listSessionHeaders() unconditionally, which (before
302
+ // the issue #6 fix) re-read every file in the session library even
303
+ // when the index already had the answer. We still fall through to
304
+ // the disk fallback for raw-id orphans persistence.list() cannot
305
+ // surface (older DSH builds wrote plain-id directories that the
306
+ // index may not know about).
307
+ let storedHeader;
308
+ if (persistence !== void 0 && typeof persistence.list === "function") {
309
+ try {
310
+ const headers = (await persistence.list()).map(normalizeSessionHeader);
311
+ storedHeader = headers.find((header) =>
312
+ header !== void 0 && typeof header.id === "string" && header.id === sessionId
313
+ );
314
+ } catch { /* fall through to disk fallback below */ }
315
+ }
316
+ if (storedHeader === void 0) {
317
+ const storedHeaders = await listSessionHeaders(persistence, dshHomePath);
318
+ storedHeader = storedHeaders.find((header) => header !== void 0 && header.id === sessionId);
319
+ }
320
+ if (storedHeader === void 0) {
321
+ const error = new Error(
322
+ `会话 ${sessionId} 没有磁盘记录(不存在,或是一个尚未发送任何消息的空白会话),无法移动`
323
+ );
324
+ error.code = "session-not-found";
325
+ throw error;
326
+ }
327
+ if (storedHeader.origin === "subagent") {
328
+ const error = new Error("子代理(subagent)会话不支持跨工作区移动");
329
+ error.code = "subagent-unsupported";
330
+ throw error;
331
+ }
332
+ if (storedHeader.cwd !== void 0) {
333
+ let currentCanonical;
334
+ try { currentCanonical = await realpath(storedHeader.cwd); } catch { /* re-home below */ }
335
+ if (currentCanonical === targetPath) {
336
+ return { ok: true, sessionId, moved: false, message: "会话已属于目标工作区" };
337
+ }
338
+ }
339
+
340
+ const liveSession = ctx.sessions.get(sessionId);
341
+ if (liveSession !== void 0 && liveWriterOf(persistence, sessionId) === undefined) {
342
+ throw new Error("当前 DSH 运行时未暴露可重绑定的 live persistence writer,无法安全迁移运行中的会话;请先关闭会话后重试");
343
+ }
344
+ let liveAgent;
345
+ try { liveAgent = ctx.agents.get(sessionId); } catch { liveAgent = void 0; }
346
+ // The 0.4.6+ move path is no-teardown: the live agent/session stays
347
+ // alive throughout. We only rewrite the on-disk artifact in place and
348
+ // update the in-memory session header to point at the new cwd; the
349
+ // api-gateway's chat panel keeps the in-memory session as active.
350
+ // The persistence coordinator's per-id serialize() (if available) wraps
351
+ // the rewrite so the write-behind cannot append to the hidden file.
352
+ // client UI never has to re-init. Just flush pending events to
353
+ // disk (still at OLD cwd), then atomically rename the artifact to
354
+ // NEW cwd. The persistence coordinator's serialize() inside the
355
+ // move block holds the per-id lock, so the write-behind can't append
356
+ // to the hidden file. The agent's UI keeps showing the same in-memory
357
+ // session -- no client state flip, no half-initialized resume, no
358
+ // "session unavailable" symptoms.
359
+ if (liveSession !== void 0) {
360
+ try { await ctx.sessions.flush(liveSession); } catch { /* best-effort */ }
361
+ }
362
+
363
+ // No teardown -- the agent and session are still live and that's
364
+ // intentional. Move straight to file re-home.
365
+ const coordinator = persistence.coordinator;
366
+ const serialize = typeof coordinator?.serialize === "function"
367
+ ? (operation) => coordinator.serialize(sessionId, operation)
368
+ : (operation) => operation();
369
+
370
+ const result = await serialize(async () => {
371
+ const raw = await readSessionArtifact(sessionId, undefined, { storedHeader });
372
+ if (raw === void 0) throw new Error("读取会话工件失败:未找到会话文件");
373
+ const newlineAt = raw.content.indexOf("\n");
374
+ if (newlineAt === -1) throw new Error("会话工件缺少头行,数据可能损坏");
375
+ const rest = raw.content.slice(newlineAt + 1);
376
+ let oldHeader;
377
+ try { oldHeader = JSON.parse(raw.content.slice(0, newlineAt)); }
378
+ catch (error) { throw new Error(`会话工件头行无法解析: ${String(error)}`); }
379
+ if (oldHeader.id !== sessionId) throw new Error("会话工件头行 id 与请求不符,拒绝移动");
380
+
381
+ // Keep the stored generation in sync with the filename selected by
382
+ // persistence.locate(). Rewriting a v2 header to v0 while locating it
383
+ // through the same v2 backend creates a v2 filename with v0 content,
384
+ // which makes DSH reject the session on the next startup.
385
+ const newHeader = { ...oldHeader, cwd: targetPath };
386
+ const oldPath = raw.path ?? persistence.locate(raw.meta)?.path;
387
+ const newLocation = persistence.locate(newHeader);
388
+ if (typeof oldPath !== "string" || newLocation === void 0) {
389
+ throw new Error("持久化后端无法定位会话工件路径");
390
+ }
391
+ const newPath = newLocation.path;
392
+ const root = typeof dshHomePath === "function" ? dshHomePath("sessions") : undefined;
393
+ await assertSessionDirectory(root, dirname(oldPath), sessionId);
394
+ await assertSessionDirectory(root, dirname(newPath), sessionId, { allowMissing: true });
395
+ try {
396
+ await lstat(newPath);
397
+ throw new Error("目标位置已有会话工件,拒绝覆盖");
398
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
399
+ if (oldPath === newPath) throw new Error("会话源路径与目标路径相同,但 cwd 不一致,拒绝覆盖");
400
+ const bytes = await encodeArtifact(JSON.stringify(newHeader), rest, newPath.endsWith(".zstd"));
401
+ await mkdir(dirname(newPath), { recursive: true });
402
+ const tempNew = await writeTempFile(newPath, bytes);
403
+ const oldHidden = `${oldPath}.${randomBytes(6).toString("hex")}.tmp`;
404
+ try {
405
+ await rename(oldPath, oldHidden);
406
+ } catch (error) {
407
+ await rm(tempNew, { force: true });
408
+ throw new Error(`移动失败(无法隐藏旧会话工件,已取消,会话保持原状): ${String(error)}`);
409
+ }
410
+ try {
411
+ await rename(tempNew, newPath);
412
+ } catch (error) {
413
+ try { await rename(oldHidden, oldPath); }
414
+ catch (rollbackError) {
415
+ throw new AggregateError([error, rollbackError], "移动发布失败且回滚失败;原始会话保留在 " + oldHidden + ",新文件保留在 " + tempNew);
416
+ }
417
+ try { await rm(tempNew, { force: true }); } catch { /* original restored */ }
418
+ throw new Error("移动发布失败,原始会话已恢复: " + safeErrorMessage(error), { cause: error });
419
+ }
420
+
421
+ const state = coordinator?.states?.get?.(sessionId);
422
+ if (state?.owner !== void 0 && liveSession !== void 0 && state.owner !== liveSession) {
423
+ await rm(newPath, { force: true });
424
+ await rename(oldHidden, oldPath);
425
+ throw new Error(`会话 ${sessionId} 的持久化 owner 与当前 live session 不一致,已回滚`);
426
+ }
427
+ const oldStateMeta = state?.meta;
428
+ const oldLiveHeader = liveSession?.header;
429
+ const liveWriter = liveSession === void 0 ? void 0 : liveWriterOf(persistence, sessionId);
430
+ const oldWriterHeader = liveWriter?.header;
431
+ const oldIndexedHeader = registry.headers?.get?.(sessionId);
432
+ const oldIndexedPath = registry.sessionPaths?.get?.(sessionId);
433
+ const oldInvalidPath = registry.invalidSessionPaths?.get?.(sessionId);
434
+ const fromWorkspaceIds = registry.list()
435
+ .filter((entity) => entity.id !== target.id && (entity.record?.sessionIds ?? entity.sessionIds).includes(sessionId))
436
+ .map((entity) => entity.id);
437
+ let targetAttached = false;
438
+ const detachedFrom = [];
439
+
440
+ try {
441
+ if (state !== void 0) {
442
+ state.meta = { ...state.meta, ...newHeader, cwd: targetPath };
443
+ state.materialized = true;
444
+ }
445
+ coordinator?.preparations?.invalidate?.(sessionId);
446
+ if (liveSession !== void 0) {
447
+ liveSession.header = Object.freeze({ ...newHeader });
448
+ rebindLiveWriter(persistence, sessionId, newHeader);
449
+ }
450
+ registry.headers?.set?.(sessionId, { ...newHeader });
451
+ registry.sessionPaths?.set?.(sessionId, targetPath);
452
+ registry.invalidSessionPaths?.delete?.(sessionId);
453
+
454
+ await registry.enqueueOperation(async () => {
455
+ for (const id of fromWorkspaceIds) {
456
+ const entity = registry.list().find((candidate) => candidate.id === id);
457
+ if (entity === void 0) continue;
458
+ await entity.detachSession(sessionId);
459
+ detachedFrom.push(id);
460
+ }
461
+ await target.attachSession(sessionId);
462
+ targetAttached = true;
463
+ });
464
+ } catch (error) {
465
+ if (state !== void 0 && oldStateMeta !== void 0) state.meta = oldStateMeta;
466
+ coordinator?.preparations?.invalidate?.(sessionId);
467
+ if (liveSession !== void 0 && oldLiveHeader !== void 0) liveSession.header = oldLiveHeader;
468
+ if (liveWriter !== void 0 && oldWriterHeader !== void 0) liveWriter.header = oldWriterHeader;
469
+ if (oldIndexedHeader === void 0) registry.headers?.delete?.(sessionId);
470
+ else registry.headers?.set?.(sessionId, oldIndexedHeader);
471
+ if (oldIndexedPath === void 0) registry.sessionPaths?.delete?.(sessionId);
472
+ else registry.sessionPaths?.set?.(sessionId, oldIndexedPath);
473
+ if (oldInvalidPath === void 0) registry.invalidSessionPaths?.delete?.(sessionId);
474
+ else registry.invalidSessionPaths?.set?.(sessionId, oldInvalidPath);
475
+
476
+ const rollbackErrors = [];
477
+ try { if (targetAttached) await target.detachSession(sessionId); } catch (e) { rollbackErrors.push(e); }
478
+ for (const id of detachedFrom) {
479
+ try {
480
+ const entity = registry.list().find((candidate) => candidate.id === id);
481
+ if (entity !== void 0) await entity.attachSession(sessionId);
482
+ } catch (e) { rollbackErrors.push(e); }
483
+ }
484
+ try { await rm(newPath, { force: true }); } catch (e) { rollbackErrors.push(e); }
485
+ try { await rename(oldHidden, oldPath); } catch (e) { rollbackErrors.push(e); }
486
+ if (rollbackErrors.length > 0) {
487
+ throw new AggregateError([error, ...rollbackErrors], "移动失败且回滚不完整");
488
+ }
489
+ throw error;
490
+ }
491
+
492
+ // rebindLiveWriter() above retargeted the existing writer before
493
+ // cleanup, so subsequent routed events use the target cwd without
494
+ // replacing the handle retained by the live agent.
495
+ try { await rm(oldHidden, { force: true }); } catch { /* best-effort */ }
496
+ try {
497
+ await assertSessionDirectory(root, dirname(oldPath), sessionId);
498
+ await rm(dirname(oldPath), { recursive: true, force: true });
499
+ } catch (error) { ctx.logger.warn(`session-manager: old directory retained: ${String(error)}`); }
500
+
501
+ return {
502
+ ok: true,
503
+ sessionId,
504
+ moved: true,
505
+ fromWorkspaceIds,
506
+ toWorkspaceId: target.id,
507
+ toWorkspaceTitle: target.title || target.id,
508
+ artifactFrom: oldPath,
509
+ artifactTo: newPath,
510
+ wasLive: liveSession !== void 0 || liveAgent !== void 0
511
+ };
512
+ });
513
+
514
+ const cache = ctx.get("sessionProjectionCache");
515
+ if (cache !== void 0 && typeof cache.coldSnapshot === "function") {
516
+ try { await cache.coldSnapshot(sessionId); }
517
+ catch (error) { ctx.logger.warn(`session-manager: post-move cache refresh failed for "${sessionId}": ${String(error)}`); }
518
+ }
519
+ // The agent is still live (no teardown). The session's in-memory
520
+ // header was rewritten above and the workspace registry updated;
521
+ // future writes go through persistence.locate() against the new
522
+ // cwd, so the file at the new location accumulates new events.
523
+ // Re-resuming the agent here re-creates a half-initialized
524
+ // Session/agent pair and leaves the client UI in a "session
525
+ // unavailable" state (agent/status is only emitted on PHASE
526
+ // CHANGES, never on agent construction). Leaving the live
527
+ // agent/session in place avoids the broken UI entirely.
528
+ ctx.logger.info(`session-manager: moved "${sessionId}" to workspace "${target.id}" (in-place file rename, live agent retained)`);
529
+ return result;
530
+ };
531
+ /* === preset-migration (session-manager v0.3.0) === */
532
+ const NL = String.fromCharCode(10);
533
+
534
+ const scanSelectedEvents = (content) => {
535
+ const out = [];
536
+ const newlineAt = content.indexOf(NL);
537
+ const after = newlineAt === -1 ? content : content.slice(newlineAt + 1);
538
+ for (const line of after.split(NL)) {
539
+ if (line.length === 0) continue;
540
+ let obj;
541
+ try { obj = JSON.parse(line); } catch { continue; }
542
+ if (obj !== null && typeof obj === "object" && obj.type === "agent-preset/selected" && obj.data !== void 0 && typeof obj.data.agentPreset === "string") {
543
+ out.push({ agentPreset: obj.data.agentPreset, time: obj.time, seq: obj.seq });
544
+ }
545
+ }
546
+ return out;
547
+ };
548
+
549
+ const scanPreset = async (filter) => {
550
+ // Pull the full preset roster so the UI shows every available preset,
551
+ // not just the ones currently used by some session.
552
+ let allPresetIds = [];
553
+ try {
554
+ const ap = ctx.get("agentPresets");
555
+ if (ap !== void 0 && typeof ap.list === "function") {
556
+ const list = await ap.list();
557
+ for (const p of (list || [])) {
558
+ if (p && typeof p.id === "string" && p.id.length > 0) allPresetIds.push(p.id);
559
+ }
560
+ }
561
+ } catch { /* ignore -- fall back to used presets only */ }
562
+
563
+ const persistence = adapter.persistence;
564
+ if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
565
+ // Enumeration normalizes backend snapshots and retains the legacy
566
+ // raw-id disk fallback. Incomplete reads never authorize reconciliation.
567
+ let headers = [];
568
+ try {
569
+ headers = await listSessionHeaders(persistence, adapter.homePath);
570
+ } catch (probeError) {
571
+ throw new Error("failed to enumerate sessions: " + String(probeError.message ?? probeError));
572
+ }
573
+ let allowedIds = null;
574
+ const workspaceId = filter !== void 0 && typeof filter === "object" ? filter.id : void 0;
575
+ if (typeof workspaceId === "string" && workspaceId !== "") {
576
+ const registry = ctx.get("workspaceRegistry");
577
+ if (registry !== void 0 && typeof registry.list === "function") {
578
+ const all = registry.list();
579
+ const ws = all.find((entity) => entity.id === workspaceId);
580
+ if (ws === void 0) {
581
+ const error = new Error("workspace not found: " + workspaceId);
582
+ error.code = "workspace-not-found";
583
+ throw error;
584
+ }
585
+ allowedIds = new Set();
586
+ const ids = typeof ws.sessionIds === "function" ? ws.sessionIds() : ws.sessionIds;
587
+ if (Array.isArray(ids)) for (const id of ids) allowedIds.add(id);
588
+ }
589
+ }
590
+ const requestedSessionId = filter !== void 0 && typeof filter === "object" && typeof filter.sessionId === "string"
591
+ ? filter.sessionId
592
+ : "";
593
+ if (requestedSessionId !== "") assertSessionId(requestedSessionId);
594
+ const out = [];
595
+ for (const header of headers) {
596
+ if (requestedSessionId !== "" && header.id !== requestedSessionId) continue;
597
+ if (allowedIds !== null && !allowedIds.has(header.id)) continue;
598
+ if (header.origin === "subagent") continue;
599
+ const raw = await readSessionArtifact(header.id, undefined, { storedHeader: header });
600
+ if (raw === void 0) continue;
601
+ const newlineAt = raw.content.indexOf(NL);
602
+ if (newlineAt === -1) continue;
603
+ let headerObj;
604
+ try { headerObj = JSON.parse(raw.content.slice(0, newlineAt)); } catch { continue; }
605
+ let selected = scanSelectedEvents(raw.content);
606
+ const live = ctx.sessions.get(header.id);
607
+ if (live !== void 0) {
608
+ const liveEvents = Array.isArray(live.events)
609
+ ? live.events
610
+ : Array.isArray(live.log) ? live.log : [];
611
+ const liveSelected = liveEvents
612
+ .filter((event) => event?.type === "agent-preset/selected" && typeof event.data?.agentPreset === "string")
613
+ .map((event) => ({ agentPreset: event.data.agentPreset, time: event.time, seq: event.seq }));
614
+ if (liveSelected.length > selected.length) selected = liveSelected;
615
+ }
616
+ const finalPreset = selected.length > 0 ? selected[selected.length - 1].agentPreset : headerObj.agentPreset;
617
+ out.push({ sessionId: header.id, cwd: header.cwd, origin: header.origin, headerPreset: headerObj.agentPreset, selectedEvents: selected, finalPreset });
618
+ }
619
+ // Targets come only from the live roster. A deleted preset can still be
620
+ // displayed as this session's current value, but must not be offered as
621
+ // a destination.
622
+ return { rows: out, availablePresets: Array.from(new Set(allPresetIds)) };
623
+ };
624
+
625
+ /**
626
+ * Rewrite the effective preset of one conversation in place on disk.
627
+ * The 0.4.6+ flow is no-teardown: when a live session is in store we
628
+ * append the new agent-preset/selected event via Session.append() and
629
+ * flush through SessionStore.flush(); for cold sessions we rewrite
630
+ * the last matching event directly on the existing artifact. In both
631
+ * cases the live agent/session is left intact, the api-gateway chat
632
+ * panel stays available, and the projection picks up the new value
633
+ * on the next event fold.
634
+ */
635
+ /** Cold-path preset migration: read disk, rewrite, publish. Works whether
636
+ * or not the session is currently in the coordinator, and does not depend on
637
+ * `coordinator.states` carrying a fresh `meta.cwd`. */
638
+ const applyMigrationToArtifact = async (args) => {
639
+ const sessionId = typeof args.sessionId === "string" ? args.sessionId : "";
640
+ const toPreset = typeof args.toPreset === "string" ? args.toPreset : "";
641
+ const liveSession = (args !== void 0 && typeof args === "object") ? args.liveSession : void 0;
642
+ const persistence = adapter.persistence;
643
+ if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
644
+ const coordinator = persistence.coordinator;
645
+ const serialize = typeof coordinator?.serialize === "function"
646
+ ? (operation) => coordinator.serialize(sessionId, operation)
647
+ : (operation) => operation();
648
+ return await serialize(async () => {
649
+ const raw = await readSessionArtifact(sessionId);
650
+ if (raw === void 0) throw new Error(`session "${sessionId}" has no artifact`);
651
+ const lines = raw.content.split(NL);
652
+ if (lines.length < 2) throw new Error("session artifact has no header line");
653
+ let header;
654
+ try { header = JSON.parse(lines[0]); } catch { throw new Error("session header parse failed"); }
655
+ if (header.id !== sessionId) throw new Error("session header id mismatch");
656
+
657
+ let selectedIndex = -1;
658
+ let selectedPreset;
659
+ for (let index = 1; index < lines.length; index += 1) {
660
+ if (lines[index] === "") continue;
661
+ let event;
662
+ try { event = JSON.parse(lines[index]); } catch { continue; }
663
+ if (event?.type === "agent-preset/selected" && typeof event.data?.agentPreset === "string") {
664
+ selectedIndex = index;
665
+ selectedPreset = event.data.agentPreset;
666
+ }
667
+ }
668
+ const oldPreset = selectedIndex >= 0 ? selectedPreset : header.agentPreset;
669
+ if (oldPreset === toPreset) {
670
+ return { sessionId, migrated: false, oldPreset, newPreset: toPreset };
671
+ }
672
+
673
+ if (selectedIndex >= 0) {
674
+ const event = JSON.parse(lines[selectedIndex]);
675
+ event.data = { ...event.data, agentPreset: toPreset };
676
+ lines[selectedIndex] = JSON.stringify(event);
677
+ } else {
678
+ header.agentPreset = toPreset;
679
+ lines[0] = JSON.stringify(header);
680
+ }
681
+
682
+ const artifactPath = raw.path ?? persistence.locate?.(raw.meta)?.path;
683
+ if (typeof artifactPath !== "string") throw new Error("cannot locate session artifact");
684
+ const replacementContent = lines.join(NL);
685
+ const firstNewline = replacementContent.indexOf(NL);
686
+ const bytes = await encodeArtifact(
687
+ replacementContent.slice(0, firstNewline),
688
+ replacementContent.slice(firstNewline + 1),
689
+ artifactPath.endsWith(".zstd")
690
+ );
691
+ const home = adapter.homePath;
692
+ await assertSessionDirectory(typeof home === "function" ? home("sessions") : undefined, dirname(artifactPath), sessionId);
693
+ const published = await replaceSessionFile(artifactPath, bytes);
694
+ if (published.backupPath) ctx.logger.warn("session-manager: retained backup " + published.backupPath);
695
+
696
+ const state = coordinator?.states?.get?.(sessionId);
697
+ if (state !== void 0 && selectedIndex < 0) state.meta = { ...state.meta, agentPreset: toPreset };
698
+ coordinator?.preparations?.invalidate?.(sessionId);
699
+ // Mirror the disk rewrite into the in-memory live session: the cold path
700
+ // bypasses the persistence write controller (which is intentionally
701
+ // skipped when its state is stale), so the session header, projection,
702
+ // and downstream agent composition would otherwise keep reporting the old
703
+ // preset. Update both the header and the in-memory event log so DSH's
704
+ // `resolveSessionPreset` and any projection subscribers observe the new
705
+ // preset from the same source.
706
+ if (liveSession !== void 0) {
707
+ try {
708
+ const nextHeader = { ...(liveSession.header ?? {}), agentPreset: toPreset };
709
+ try { liveSession.header = Object.freeze(nextHeader); }
710
+ catch { liveSession.header = nextHeader; }
711
+ } catch { /* live session may have been retired mid-flight */ }
712
+ // Append the new selection to the live log so the session/store
713
+ // observers (agent-presets, projections, ctx) fire their normal
714
+ // `session/event` + `agent-preset/selected` pipeline. We append
715
+ // unconditionally (not only when the disk had no prior selection)
716
+ // because the in-memory projection reads the latest appended event
717
+ // and the cold path deliberately skipped the persistence write
718
+ // controller; the appended event will be persisted on the next
719
+ // normal flush, keeping disk and memory consistent.
720
+ if (typeof liveSession.append === "function") {
721
+ try { liveSession.append("agent-preset/selected", { agentPreset: toPreset }); } catch { /* best-effort */ }
722
+ }
723
+ }
724
+ return { sessionId, migrated: true, oldPreset, newPreset: toPreset };
725
+ });
726
+ };
727
+ /** Rewrite exactly one conversation's effective Agent preset. */
728
+ const migratePreset = async (opts) => {
729
+ const sessionId = typeof opts.sessionId === "string" ? opts.sessionId.trim() : "";
730
+ const toPreset = typeof opts.toPreset === "string" ? opts.toPreset.trim() : "";
731
+ if (sessionId === "") { const e = new Error("sessionId required"); e.code = "bad-request"; throw e; }
732
+ if (toPreset === "") { const e = new Error("toPreset required"); e.code = "bad-request"; throw e; }
733
+
734
+ const presets = ctx.get("agentPresets");
735
+ if (presets === void 0 || typeof presets.list !== "function") {
736
+ throw new Error("agentPresets service unavailable");
737
+ }
738
+ const roster = await presets.list();
739
+ const target = (roster || []).find((preset) => preset && preset.id === toPreset);
740
+ if (target === void 0) {
741
+ const available = (roster || []).map((preset) => preset?.id).filter(Boolean);
742
+ throw new Error(`Agent 预设 "${toPreset}" 不存在(可用:${available.join(", ")})`);
743
+ }
744
+ if (target.broken !== void 0) throw new Error(`Agent 预设 "${toPreset}" 不可用:${target.broken}`);
745
+
746
+ const liveSession = ctx.sessions.get(sessionId);
747
+ let liveAgent;
748
+ try { liveAgent = ctx.agents.get(sessionId); } catch { liveAgent = void 0; }
749
+ // Resolve persistence up front so the live path can read the coordinator
750
+ // without tripping JavaScript's temporal dead zone on `const persistence`.
751
+ const persistence = adapter.persistence;
752
+ if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
753
+
754
+ if (liveSession !== void 0) {
755
+ const coordinator = persistence.coordinator;
756
+ const states = coordinator?.states;
757
+ const beforeState = states?.get?.(sessionId);
758
+ const liveCwd = liveSession.header?.cwd;
759
+ // A just-completed moveSession mutates `liveSession.header.cwd` in place,
760
+ // but the persistence coordinator's tracked state may not see the new cwd
761
+ // until its serialize chain drains. If we hand the migration to the
762
+ // coordinator now, its `state.meta.cwd` may still be the pre-move cwd and
763
+ // appendBatch will open the old (now deleted) artifact path, producing the
764
+ // "ENOENT ... session.v2.jsonl.zstd" regression. Falling back to the cold
765
+ // path is always correct: the disk copy already reflects the new cwd.
766
+ const stateStale = beforeState === void 0
767
+ || beforeState.meta?.cwd === void 0
768
+ || (liveCwd !== void 0 && beforeState.meta.cwd !== liveCwd);
769
+ if (stateStale) {
770
+ const raw = await readSessionArtifact(sessionId);
771
+ if (raw !== void 0) {
772
+ const result = await applyMigrationToArtifact({ sessionId, toPreset, liveSession });
773
+ if (result.migrated) { try { ctx.emit("agent-preset/selected", sessionId, toPreset); } catch { /* best-effort */ } }
774
+ ctx.logger.info(`session-manager: migrated live preset for "${sessionId}" via cold path (state was stale, live cwd=${String(liveCwd)}, state cwd=${String(beforeState?.meta?.cwd)})`);
775
+ return { sessionId, migrated: true, oldPreset: result.oldPreset, newPreset: toPreset };
776
+ }
777
+ // No artifact yet; fall through to the in-memory + flush path below,
778
+ // which materializes the empty file using the live cwd.
779
+ }
780
+ let oldPreset = liveSession.header?.agentPreset;
781
+ // SessionStore implementations from older DSH builds may expose the
782
+ // history as `log` rather than the newer `events` snapshot getter.
783
+ // Do not dereference `.length` on an absent compatibility surface.
784
+ const liveEvents = Array.isArray(liveSession.events)
785
+ ? liveSession.events
786
+ : Array.isArray(liveSession.log) ? liveSession.log : [];
787
+ for (let index = liveEvents.length - 1; index >= 0; index -= 1) {
788
+ const event = liveEvents[index];
789
+ if (event?.type === "agent-preset/selected" && typeof event.data?.agentPreset === "string") {
790
+ oldPreset = event.data.agentPreset;
791
+ break;
792
+ }
793
+ }
794
+ if (oldPreset === toPreset) {
795
+ return { sessionId, migrated: false, oldPreset, newPreset: toPreset };
796
+ }
797
+ if (liveAgent !== void 0 && typeof presets?.recompose === "function" && liveAgent.ctx) {
798
+ try { await presets.recompose(liveAgent.ctx, toPreset); } catch { /* best-effort */ }
799
+ }
800
+ liveSession.append("agent-preset/selected", { agentPreset: toPreset });
801
+ await ctx.sessions.flush(liveSession);
802
+ ctx.logger.info(`session-manager: migrated live preset for "${sessionId}" from "${String(oldPreset)}" to "${toPreset}"`);
803
+ return { sessionId, migrated: true, oldPreset, newPreset: toPreset };
804
+ }
805
+
806
+ // A session absent from SessionStore is cold. If an older plugin left its
807
+ // exact Session object in the coordinator, retire that proven orphan by
808
+ // the coordinator's own drain path instead of deleting owner bookkeeping.
809
+ const coordinator = persistence.coordinator;
810
+ let tracked = coordinator?.states?.get?.(sessionId);
811
+ if (tracked?.owner !== void 0 && ctx.sessions.get(sessionId) === void 0) {
812
+ coordinator.retire?.(tracked.owner);
813
+ const retirement = coordinator.retirements?.get?.(sessionId);
814
+ if (retirement !== void 0) await retirement;
815
+ tracked = coordinator.states?.get?.(sessionId);
816
+ if (tracked?.owner !== void 0) {
817
+ throw new Error(`会话 ${sessionId} 仍有未释放的持久化 owner,已停止迁移以保护数据`);
818
+ }
819
+ }
820
+
821
+ const result = await applyMigrationToArtifact({ sessionId, toPreset, liveSession });
822
+
823
+ if (result.migrated) {
824
+ try { ctx.emit("agent-preset/selected", sessionId, toPreset); } catch { /* best-effort */ }
825
+ ctx.logger.info(`session-manager: migrated cold preset for "${sessionId}" from "${String(result.oldPreset)}" to "${toPreset}"`);
826
+ }
827
+ return result;
828
+ };
829
+
830
+ /** Read one session artifact verbatim, falling back to direct disk access when the
831
+ * configured persistence backend cannot see the id (e.g. an older DSH build
832
+ * wrote a "session.v2.jsonl.zstd" file under the raw-id directory).
833
+ */
834
+ const readSessionArtifact = async (sessionId, signal, { headerOnly = false, storedHeader } = {}) => {
835
+ assertSessionId(sessionId);
836
+ const persistence = adapter.persistence;
837
+ const dshHomePath = adapter.homePath;
838
+ const root = typeof dshHomePath === "function" ? dshHomePath("sessions") : undefined;
839
+ const read = async (path) => headerOnly
840
+ ? { meta: await readSessionHeader(path), path }
841
+ : readSessionFile(path);
842
+ // Use cheap index metadata as a location hint, never a decoded readRaw
843
+ // payload. Move/preset scans can reuse headers they already enumerated.
844
+ let header = storedHeader;
845
+ if (header === undefined && typeof persistence?.list === "function") {
846
+ try {
847
+ header = (await persistence.list()).map(normalizeSessionHeader).find(item => item?.id === sessionId);
848
+ } catch (error) { if (signal?.aborted) throw error; }
849
+ }
850
+ if (header !== undefined && typeof persistence?.locate === "function") {
851
+ const path = persistence.locate(header)?.path;
852
+ if (typeof path === "string") {
853
+ try {
854
+ await assertSessionDirectory(root, dirname(path), sessionId);
855
+ const artifact = await read(path);
856
+ if (artifact.meta.id !== sessionId) throw new Error("会话工件 header id 与请求不一致");
857
+ return artifact;
858
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
859
+ }
860
+ }
861
+ if (typeof root !== "string") throw new Error("无法定位并验证会话工件目录");
862
+ let projects;
863
+ try { projects = await readdir(root, { withFileTypes: true }); }
864
+ catch (error) { if (error.code === "ENOENT") return undefined; throw error; }
865
+ for (const proj of projects) {
866
+ if (!proj.isDirectory() || proj.isSymbolicLink()) continue;
867
+ for (const candidate of [encodeSessionSegment(sessionId), sessionId]) {
868
+ const dir = join(root, proj.name, candidate);
869
+ try { await assertSessionDirectory(root, dir, sessionId); }
870
+ catch (error) { if (error.code === "ENOENT") continue; throw error; }
871
+ for (const filename of ARTIFACT_NAMES) {
872
+ try {
873
+ const artifact = await read(join(dir, filename));
874
+ if (artifact.meta.id !== sessionId) throw new Error("会话工件 header id 与请求不一致");
875
+ return artifact;
876
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
877
+ }
878
+ }
879
+ }
880
+ return undefined;
881
+ };
882
+
883
+ const sessionDirOf = async (sessionId) => {
884
+ // Require a matching artifact header instead of deleting an arbitrary
885
+ // directory merely because its name matches user input.
886
+ const artifact = await readSessionArtifact(sessionId, undefined, { headerOnly: true });
887
+ return artifact === undefined ? undefined : dirname(artifact.path);
888
+ };
889
+
890
+ /**
891
+ * Delete one session end to end. Returns a summary of what was torn down.
892
+ * Idempotent-ish: unknown sessions resolve to { ok: true, deleted: false }.
893
+ */
894
+ const deleteSession = async (sessionId) => {
895
+ assertSessionId(sessionId);
896
+ // Resolve/validate before cancelling the agent or changing registry state.
897
+ let dir = await sessionDirOf(sessionId);
898
+ const session = ctx.sessions.get(sessionId);
899
+ // 0.1.1-rc.2 throws ApiRemoteSessionNotFound for cold sessions here.
900
+ let agent;try{agent=ctx.agents.get(sessionId)}catch{agent=void 0}
901
+
902
+ if (agent !== void 0) {
903
+ // Stop any running turn (disposed-kind suppresses re-wake).
904
+ agent.cancel({ kind: "disposed" });
905
+ // Quiesce the agent's own fiber (idempotent; bounded in case teardown stalls).
906
+ if (typeof agent.scope?.dispose === "function") {
907
+ await Promise.race([agent.scope.dispose(), sleep(3000)]);
908
+ }
909
+ // Drop the zombie from the registry so a later session.create/open with
910
+ // the same id cannot resurrect it.
911
+ try {
912
+ ctx.agents.store?.delete?.(sessionId);
913
+ } catch { /* best-effort */ }
914
+ }
915
+
916
+ let detached = false;
917
+ if (session !== void 0) {
918
+ // Flush buffered events to disk first so the retirement drain is a no-op.
919
+ try {
920
+ await ctx.sessions.flush(session);
921
+ } catch { /* best-effort */ }
922
+ // Detach the session store entry: emits session/disposed, which the
923
+ // persistence write-path answers with a final drain, and the API proxy
924
+ // relays as host/session-removed so every connected client drops the row.
925
+ try {
926
+ const entry = ctx.sessions.store?.get?.(sessionId);
927
+ if (entry !== void 0 && typeof entry.detach === "function") {
928
+ entry.detach();
929
+ await sleep(200); // let the write-behind retirement settle
930
+ detached = true;
931
+ }
932
+ } catch { /* best-effort */ }
933
+ }
934
+ // Some sessions have a stored artifact but no live store row (e.g.
935
+ // already-scoped scope torn down, or never attached). Without a live
936
+ // entry, ctx.sessions.store?.get?.(sessionId) returns undefined and
937
+ // entry.detach() never fires — so the apiproxy never queues a
938
+ // host/session-removed frame, every connected client keeps showing the
939
+ // session row, and the row collapses into the ungrouped section the
940
+ // moment host/workspace-changed drops its workspace membership. Emit
941
+ // session/disposed explicitly so every connected client drops the row.
942
+ if (!detached) {
943
+ try {
944
+ ctx.emit("session/disposed", { id: sessionId });
945
+ } catch (_) { /* best-effort */ }
946
+ }
947
+
948
+ // A blank live session may have materialized its first artifact during
949
+ // flush/retirement. Re-resolve after teardown rather than leaking that file.
950
+ dir = await sessionDirOf(sessionId);
951
+
952
+ // Workspace accounting + archive-set membership.
953
+ await detachFromWorkspaces(sessionId);
954
+ await unarchiveSession(sessionId);
955
+
956
+ // Physical artifact (session.jsonl / session.jsonl.zstd) + any extras.
957
+ if (dir !== void 0) {
958
+ await assertSessionDirectory(adapter.homePath("sessions"), dir, sessionId);
959
+ await rm(dir, { recursive: true, force: true });
960
+ }
961
+
962
+ let warning;
963
+ try { await annotations().remove(sessionId); }
964
+ catch (error) {
965
+ warning = "会话已删除,但独立标记清理失败: " + safeErrorMessage(error);
966
+ ctx.logger.warn("session-manager: " + warning);
967
+ }
968
+ return {
969
+ ok: true,
970
+ ...(warning ? { warning } : {}),
971
+ sessionId,
972
+ wasLive: session !== void 0 || agent !== void 0,
973
+ filesRemoved: dir !== void 0
974
+ };
975
+ };
976
+
977
+ /**
978
+ * On plugin boot, refold every persisted session projection cache
979
+ * row from disk. Sessions moved before coldSnapshot was wired into
980
+ * moveSession would otherwise keep their pre-move {createdAt, cwd}
981
+ * identity and let the cold list path fall back to basename(cwd),
982
+ * surfacing the workspace title (for example "DSH") where the
983
+ * session's own title was expected. The sweep is one-shot and
984
+ * idempotent: a row whose identity already matches is a cheap
985
+ * pass-through refold, and a stale one triggers the unrelated-identity
986
+ * full re-read path.
987
+ */
988
+ ctx.effect(async () => {
989
+ const cache = adapter.projectionCache;
990
+ const persistence = adapter.persistence;
991
+ const registry = adapter.workspaceRegistry;
992
+ if (typeof cache?.coldSnapshot !== "function" || typeof persistence?.list !== "function" || typeof registry?.list !== "function") return;
993
+ try {
994
+ // Remember only ids that existed before the async scan. Concurrently
995
+ // attached ids must never be removed using this older disk snapshot.
996
+ const initialIds = new Map(registry.list().map(ws => [ws.id, new Set(ws.record?.sessionIds ?? [])]));
997
+ const scan = await scanSessionHeaders(persistence, adapter.homePath);
998
+ if (!scan.complete) {
999
+ ctx.logger.warn("session-manager: incomplete session scan; workspace reconciliation skipped: " + scan.errors.map(safeErrorMessage).join("; "));
1000
+ return;
1001
+ }
1002
+ const headers = scan.headers;
1003
+ const validIds = new Set(headers.map(header => header.id));
1004
+ for (const header of headers) {
1005
+ try { await cache.coldSnapshot(header.id); }
1006
+ catch (error) { ctx.logger.warn('session-manager: post-boot cache refold failed: ' + safeErrorMessage(error)); }
1007
+ }
1008
+ let removed = 0;
1009
+ let added = 0;
1010
+ // Read current state *inside* its queue, and publish an immutable copy.
1011
+ // A failed setState must not mutate the registry's live state object.
1012
+ await registry.enqueueOperation(async () => {
1013
+ const state = registry.requireState();
1014
+ const pathById = new Map(registry.list().map(ws => [ws.id, ws.path]));
1015
+ const assignedIds = new Set((state.workspaces ?? []).flatMap(ws => ws.sessionIds ?? []));
1016
+ const workspaces = (state.workspaces ?? []).map(ws => {
1017
+ const original = ws.sessionIds ?? [];
1018
+ const sessionIds = original.filter(id => validIds.has(id)
1019
+ || !initialIds.get(ws.id)?.has(id) || adapter.getSession(id) !== undefined);
1020
+ const removedHere = original.length - sessionIds.length;
1021
+ removed += removedHere;
1022
+ for (const header of headers) {
1023
+ if (header.cwd === undefined || header.cwd !== pathById.get(ws.id) || assignedIds.has(header.id)) continue;
1024
+ sessionIds.unshift(header.id);
1025
+ assignedIds.add(header.id);
1026
+ added += 1;
1027
+ }
1028
+ if (sessionIds.length === original.length && sessionIds.every((id, i) => id === original[i])) return ws;
1029
+ return { ...ws, sessionIds, updatedAt: new Date().toISOString() };
1030
+ });
1031
+ if (removed || added) await registry.setState({ ...state, workspaces });
1032
+ });
1033
+ if (removed || added) ctx.logger.info('session-manager: post-boot workspace reconcile removed ' + removed + ' orphans, attached ' + added + ' disk-only sessions');
1034
+ } catch (error) {
1035
+ ctx.logger.warn('session-manager: post-boot reconcile failed: ' + safeErrorMessage(error));
1036
+ }
1037
+ }, "session-manager: post-boot re-fold stale projection cache rows");
1038
+
1039
+ ctx.effect(() => ctx.webServer.register({
1040
+ kind: "prefix",
1041
+ path: API_PREFIX,
1042
+ handler: async (req, res) => {
1043
+ try {
1044
+ const url = new URL(req.url ?? "/", "http://localhost");
1045
+ const path = url.pathname.startsWith(API_PREFIX) ? url.pathname.slice(API_PREFIX.length) || "/" : "/";
1046
+ let body = {};
1047
+ if (req.method === "POST") {
1048
+ const raw = await readBody(req);
1049
+ if (raw.trim() !== "") {
1050
+ try { body = JSON.parse(raw); }
1051
+ catch { return send(res, 400, { ok: false, error: "请求体不是合法 JSON" }); }
1052
+ }
1053
+ }
1054
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
1055
+ return send(res, 400, { ok: false, error: "请求体必须是 JSON 对象" });
1056
+ }
1057
+ const sessionId = typeof body.sessionId === "string" ? body.sessionId.trim() : "";
1058
+ if (req.method === "GET" && path === "/annotations") {
1059
+ return send(res, 200, { ok: true, result: { annotations: await annotations().list() } });
1060
+ }
1061
+ if (req.method === "POST" && path === "/annotations") {
1062
+ assertSessionId(sessionId);
1063
+ const annotation = await mutate(sessionId, async () => {
1064
+ assertAnnotatable(sessionId);
1065
+ return annotations().update(sessionId, body.patch, body.expectedRevision);
1066
+ });
1067
+ return send(res, 200, { ok: true, result: { sessionId, annotation } });
1068
+ }
1069
+ if (req.method === "POST" && ["/delete", "/unarchive", "/move", "/preset-migrate"].includes(path)) {
1070
+ assertSessionId(sessionId);
1071
+ let result;
1072
+ if (path === "/delete") result = await mutate(sessionId, () => deleteSession(sessionId));
1073
+ else if (path === "/unarchive") {
1074
+ await mutate(sessionId, () => unarchiveSession(sessionId));
1075
+ result = { sessionId };
1076
+ } else if (path === "/move") {
1077
+ const targetWorkspaceId = typeof body.targetWorkspaceId === "string" ? body.targetWorkspaceId.trim() : "";
1078
+ if (!targetWorkspaceId) return send(res, 400, { ok: false, error: "targetWorkspaceId 必填" });
1079
+ result = await mutate(sessionId, () => moveSession(sessionId, targetWorkspaceId));
1080
+ } else {
1081
+ const toPreset = typeof body.toPreset === "string" ? body.toPreset.trim() : "";
1082
+ if (!toPreset) return send(res, 400, { ok: false, error: "toPreset 必填" });
1083
+ result = await mutate(sessionId, () => migratePreset({ sessionId, toPreset }));
1084
+ }
1085
+ return send(res, 200, { ok: true, result });
1086
+ }
1087
+ if (req.method === "GET" && path === "/workspaces") {
1088
+ const sessionCreatedAt = Object.fromEntries(adapter.cachedSessionHeaders()
1089
+ .filter(header => typeof header.createdAt === "number" || typeof header.createdAt === "string")
1090
+ .map(header => [header.id, header.createdAt]));
1091
+ return send(res, 200, { ok: true, result: { workspaces: listWorkspaces(), sessionCreatedAt } });
1092
+ }
1093
+ if (req.method === "GET" && path === "/preset-scan") {
1094
+ const sessionId = url.searchParams.get("sessionId") || "";
1095
+ if (sessionId) assertSessionId(sessionId);
1096
+ const result = await scanPreset({ id: url.searchParams.get("workspaceId") || "", sessionId });
1097
+ return send(res, 200, { ok: true, result });
1098
+ }
1099
+ return send(res, 404, { ok: false, error: "not found: " + req.method + " " + path });
1100
+ } catch (error) {
1101
+ ctx.logger.warn("session-manager: api error: " + safeErrorMessage(error) + "; json=" + safeJson(error));
1102
+ const status = error?.code === "bad-request" ? 400 : error?.code === "body-too-large" ? 413
1103
+ : error?.code === "annotation-conflict" || error?.code === "annotations-busy" ? 409
1104
+ : error?.code === "session-not-found" ? 404 : error?.code?.startsWith("annotations-") ? 503 : 500;
1105
+ return send(res, status, { ok: false, error: safeErrorMessage(error), ...(typeof error?.code === "string" ? { code: error.code } : {}) });
1106
+ }
1107
+ }
1108
+ }), "session-manager: http api");
1109
+ }
1110
+
1111
+ export { listSessionHeaders, scanSessionHeaders, encodeSessionSegment };