dsh-session-manager 0.4.11 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,1247 +1,1243 @@
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
+ try {
171
+ const buildId = "dsh-session-manager v0.5.2+release-17 (clearSelection-keeps-bulk-mode-on)";
172
+ if (typeof ctx?.logger?.info === "function") ctx.logger.info(buildId);
173
+ else if (typeof console !== "undefined" && console?.info) console.info(buildId);
174
+ } catch (_) { /* ignore logging failures */ }
175
+ const adapter = createDshAdapter(ctx);
176
+ let annotationStore;
177
+ const annotations = () => {
178
+ if (!annotationStore) {
179
+ const home = adapter.homePath;
180
+ if (typeof home !== "function") throw Object.assign(new Error("会话标记存储不可用"), { code: "annotations-unavailable" });
181
+ annotationStore = createAnnotationStore(home("dsh-session-manager"));
182
+ }
183
+ return annotationStore;
184
+ };
185
+ const assertAnnotatable = id => {
186
+ const registry = adapter.workspaceRegistry;
187
+ if (adapter.getSession(id) !== undefined || registry?.headers?.has?.(id)
188
+ || adapter.workspaceList().some(ws => (ws.record?.sessionIds ?? ws.sessionIds ?? []).includes(id))) return;
189
+ throw Object.assign(new Error("会话不存在或尚未加载,请先打开该会话后重试"), { code: "session-not-found" });
190
+ };
191
+ const operations = new Map();
192
+ const mutate = (id, operation) => {
193
+ const pending = (operations.get(id) ?? Promise.resolve()).then(operation);
194
+ const settled = pending.catch(() => {}).finally(() => {
195
+ if (operations.get(id) === settled) operations.delete(id);
196
+ });
197
+ operations.set(id, settled);
198
+ return pending;
199
+ };
200
+ const readBody = async (req) => {
201
+ const chunks = [];
202
+ let size = 0;
203
+ for await (const chunk of req) {
204
+ const bytes = Buffer.from(chunk);
205
+ size += bytes.length;
206
+ if (size > 64 * 1024) throw Object.assign(new Error("请求体超过 64 KiB"), { code: "body-too-large" });
207
+ chunks.push(bytes);
208
+ }
209
+ return Buffer.concat(chunks).toString("utf8");
210
+ };
211
+
212
+ const send = (res, code, obj) => {
213
+ res.writeHead(code, { "content-type": "application/json; charset=utf-8" });
214
+ res.end(JSON.stringify(obj));
215
+ };
216
+
217
+ /** Remove one id from the registry-global archive set (durable, serialized). */
218
+ const unarchiveSession = async (sessionId) => {
219
+ const registry = ctx.workspaceRegistry;
220
+ await registry.enqueueOperation(async () => {
221
+ const state = registry.requireState();
222
+ if (!state.archivedSessionIds.includes(sessionId)) return;
223
+ await registry.setState({
224
+ ...state,
225
+ archivedSessionIds: state.archivedSessionIds.filter((id) => id !== sessionId)
226
+ });
227
+ });
228
+ };
229
+
230
+ /** Add one id to the registry-global archive set (durable, serialized).
231
+ * Mirror of unarchiveSession; both touch workspaceRegistry state directly
232
+ * because the host-side ctx.workspaces service is not available inside
233
+ * the per-request dispatch (Cordis throws "cannot get property
234
+ * 'workspaces' without inject" otherwise). */
235
+ const archiveSession = async (sessionId) => {
236
+ const registry = ctx.workspaceRegistry;
237
+ await registry.enqueueOperation(async () => {
238
+ const state = registry.requireState();
239
+ if (state.archivedSessionIds.includes(sessionId)) return;
240
+ await registry.setState({
241
+ ...state,
242
+ archivedSessionIds: [...state.archivedSessionIds, sessionId]
243
+ });
244
+ });
245
+ };
246
+
247
+ /** Detach one session from every workspace's ordered accounting. */
248
+ const detachFromWorkspaces = async (sessionId) => {
249
+ for (const entity of ctx.workspaceRegistry.list()) {
250
+ if (entity.sessionIds.includes(sessionId)) {
251
+ await entity.detachSession(sessionId);
252
+ }
253
+ }
254
+ };
255
+
256
+ /** Ordered workspace projection for the client. */
257
+ const listWorkspaces = () => {
258
+ return ctx.workspaceRegistry.list().map((entity) => {
259
+ const rawIds = Array.isArray(entity.record?.sessionIds)
260
+ ? [...entity.record.sessionIds]
261
+ : [...entity.sessionIds];
262
+ return {
263
+ id: entity.id,
264
+ name: entity.title || entity.id,
265
+ title: entity.title || entity.id,
266
+ path: entity.path,
267
+ sessionCount: rawIds.length,
268
+ sessionIds: rawIds
269
+ };
270
+
271
+ });
272
+ };
273
+
274
+
275
+ /**
276
+ * Encode the moved artifact in the backend's own physical layout:
277
+ * plain JSONL, or zstd frames whose FIRST frame is exactly the header
278
+ * line (the reader's assertZstdHeaderFrame / readFirstZstdLine contract).
279
+ */
280
+ const encodeArtifact = async (headerLine, rest, isZstd) => {
281
+ if (!isZstd) return Buffer.from(`${headerLine}
282
+ ${rest}`, "utf8");
283
+ const { zstdCompress } = await import("node:zlib");
284
+ if (typeof zstdCompress !== "function") {
285
+ throw new Error("当前 Node 运行时没有 zstd 支持,无法迁移 zstd 编码的会话工件");
286
+ }
287
+ const compress = (buffer) => new Promise((resolve, reject) => {
288
+ zstdCompress(buffer, (error, output) => error == null ? resolve(output) : reject(error));
289
+ });
290
+ const headerFrame = await compress(Buffer.from(`${headerLine}\n`, "utf8"));
291
+ if (rest === "") return headerFrame;
292
+ const bodyFrame = await compress(Buffer.from(rest, "utf8"));
293
+ return Buffer.concat([headerFrame, bodyFrame]);
294
+ };
295
+
296
+ /**
297
+ * TRUE cross-workspace move. See the module docstring for the full design:
298
+ * re-home the stored cwd, migrate the artifact, then swap accounting.
299
+ * Throws an Error with a readable message on every failure path; the
300
+ * artifact is restored (or its location reported) whenever a mid-move
301
+ * step fails, so the session never ends up in a half-moved state.
302
+ */
303
+ const moveSession = async (sessionId, targetWorkspaceId) => {
304
+ assertSessionId(sessionId);
305
+ const registry = ctx.workspaceRegistry;
306
+ const persistence = adapter.persistence;
307
+ const dshHomePath = adapter.homePath;
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()).map(normalizeSessionHeader);
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, undefined, { storedHeader });
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
+ const root = typeof dshHomePath === "function" ? dshHomePath("sessions") : undefined;
415
+ await assertSessionDirectory(root, dirname(oldPath), sessionId);
416
+ await assertSessionDirectory(root, dirname(newPath), sessionId, { allowMissing: true });
417
+ try {
418
+ await lstat(newPath);
419
+ throw new Error("目标位置已有会话工件,拒绝覆盖");
420
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
421
+ if (oldPath === newPath) throw new Error("会话源路径与目标路径相同,但 cwd 不一致,拒绝覆盖");
422
+ const bytes = await encodeArtifact(JSON.stringify(newHeader), rest, newPath.endsWith(".zstd"));
423
+ await mkdir(dirname(newPath), { recursive: true });
424
+ const tempNew = await writeTempFile(newPath, bytes);
425
+ const oldHidden = `${oldPath}.${randomBytes(6).toString("hex")}.tmp`;
426
+ try {
427
+ await rename(oldPath, oldHidden);
428
+ } catch (error) {
429
+ await rm(tempNew, { force: true });
430
+ throw new Error(`移动失败(无法隐藏旧会话工件,已取消,会话保持原状): ${String(error)}`);
431
+ }
432
+ try {
433
+ await rename(tempNew, newPath);
434
+ } catch (error) {
435
+ try { await rename(oldHidden, oldPath); }
436
+ catch (rollbackError) {
437
+ throw new AggregateError([error, rollbackError], "移动发布失败且回滚失败;原始会话保留在 " + oldHidden + ",新文件保留在 " + tempNew);
438
+ }
439
+ try { await rm(tempNew, { force: true }); } catch { /* original restored */ }
440
+ throw new Error("移动发布失败,原始会话已恢复: " + safeErrorMessage(error), { cause: error });
441
+ }
442
+
443
+ const state = coordinator?.states?.get?.(sessionId);
444
+ if (state?.owner !== void 0 && liveSession !== void 0 && state.owner !== liveSession) {
445
+ await rm(newPath, { force: true });
446
+ await rename(oldHidden, oldPath);
447
+ throw new Error(`会话 ${sessionId} 的持久化 owner 与当前 live session 不一致,已回滚`);
448
+ }
449
+ const oldStateMeta = state?.meta;
450
+ const oldLiveHeader = liveSession?.header;
451
+ const liveWriter = liveSession === void 0 ? void 0 : liveWriterOf(persistence, sessionId);
452
+ const oldWriterHeader = liveWriter?.header;
453
+ const oldIndexedHeader = registry.headers?.get?.(sessionId);
454
+ const oldIndexedPath = registry.sessionPaths?.get?.(sessionId);
455
+ const oldInvalidPath = registry.invalidSessionPaths?.get?.(sessionId);
456
+ const fromWorkspaceIds = registry.list()
457
+ .filter((entity) => entity.id !== target.id && (entity.record?.sessionIds ?? entity.sessionIds).includes(sessionId))
458
+ .map((entity) => entity.id);
459
+ let targetAttached = false;
460
+ const detachedFrom = [];
461
+
462
+ try {
463
+ if (state !== void 0) {
464
+ state.meta = { ...state.meta, ...newHeader, cwd: targetPath };
465
+ state.materialized = true;
466
+ }
467
+ coordinator?.preparations?.invalidate?.(sessionId);
468
+ if (liveSession !== void 0) {
469
+ liveSession.header = Object.freeze({ ...newHeader });
470
+ rebindLiveWriter(persistence, sessionId, newHeader);
471
+ }
472
+ registry.headers?.set?.(sessionId, { ...newHeader });
473
+ registry.sessionPaths?.set?.(sessionId, targetPath);
474
+ registry.invalidSessionPaths?.delete?.(sessionId);
475
+
476
+ await registry.enqueueOperation(async () => {
477
+ for (const id of fromWorkspaceIds) {
478
+ const entity = registry.list().find((candidate) => candidate.id === id);
479
+ if (entity === void 0) continue;
480
+ await entity.detachSession(sessionId);
481
+ detachedFrom.push(id);
482
+ }
483
+ await target.attachSession(sessionId);
484
+ targetAttached = true;
485
+ });
486
+ } catch (error) {
487
+ if (state !== void 0 && oldStateMeta !== void 0) state.meta = oldStateMeta;
488
+ coordinator?.preparations?.invalidate?.(sessionId);
489
+ if (liveSession !== void 0 && oldLiveHeader !== void 0) liveSession.header = oldLiveHeader;
490
+ if (liveWriter !== void 0 && oldWriterHeader !== void 0) liveWriter.header = oldWriterHeader;
491
+ if (oldIndexedHeader === void 0) registry.headers?.delete?.(sessionId);
492
+ else registry.headers?.set?.(sessionId, oldIndexedHeader);
493
+ if (oldIndexedPath === void 0) registry.sessionPaths?.delete?.(sessionId);
494
+ else registry.sessionPaths?.set?.(sessionId, oldIndexedPath);
495
+ if (oldInvalidPath === void 0) registry.invalidSessionPaths?.delete?.(sessionId);
496
+ else registry.invalidSessionPaths?.set?.(sessionId, oldInvalidPath);
497
+
498
+ const rollbackErrors = [];
499
+ try { if (targetAttached) await target.detachSession(sessionId); } catch (e) { rollbackErrors.push(e); }
500
+ for (const id of detachedFrom) {
501
+ try {
502
+ const entity = registry.list().find((candidate) => candidate.id === id);
503
+ if (entity !== void 0) await entity.attachSession(sessionId);
504
+ } catch (e) { rollbackErrors.push(e); }
505
+ }
506
+ try { await rm(newPath, { force: true }); } catch (e) { rollbackErrors.push(e); }
507
+ try { await rename(oldHidden, oldPath); } catch (e) { rollbackErrors.push(e); }
508
+ if (rollbackErrors.length > 0) {
509
+ throw new AggregateError([error, ...rollbackErrors], "移动失败且回滚不完整");
510
+ }
511
+ throw error;
512
+ }
513
+
514
+ // rebindLiveWriter() above retargeted the existing writer before
515
+ // cleanup, so subsequent routed events use the target cwd without
516
+ // replacing the handle retained by the live agent.
517
+ try { await rm(oldHidden, { force: true }); } catch { /* best-effort */ }
518
+ try {
519
+ await assertSessionDirectory(root, dirname(oldPath), sessionId);
520
+ await rm(dirname(oldPath), { recursive: true, force: true });
521
+ } catch (error) { ctx.logger.warn(`session-manager: old directory retained: ${String(error)}`); }
522
+
523
+ return {
524
+ ok: true,
525
+ sessionId,
526
+ moved: true,
527
+ fromWorkspaceIds,
528
+ toWorkspaceId: target.id,
529
+ toWorkspaceTitle: target.title || target.id,
530
+ artifactFrom: oldPath,
531
+ artifactTo: newPath,
532
+ wasLive: liveSession !== void 0 || liveAgent !== void 0
533
+ };
534
+ });
535
+
536
+ const cache = ctx.get("sessionProjectionCache");
537
+ if (cache !== void 0 && typeof cache.coldSnapshot === "function") {
538
+ try { await cache.coldSnapshot(sessionId); }
539
+ catch (error) { ctx.logger.warn(`session-manager: post-move cache refresh failed for "${sessionId}": ${String(error)}`); }
540
+ }
541
+ // The agent is still live (no teardown). The session's in-memory
542
+ // header was rewritten above and the workspace registry updated;
543
+ // future writes go through persistence.locate() against the new
544
+ // cwd, so the file at the new location accumulates new events.
545
+ // Re-resuming the agent here re-creates a half-initialized
546
+ // Session/agent pair and leaves the client UI in a "session
547
+ // unavailable" state (agent/status is only emitted on PHASE
548
+ // CHANGES, never on agent construction). Leaving the live
549
+ // agent/session in place avoids the broken UI entirely.
550
+ ctx.logger.info(`session-manager: moved "${sessionId}" to workspace "${target.id}" (in-place file rename, live agent retained)`);
551
+ return result;
552
+ };
553
+ /* === preset-migration (session-manager v0.3.0) === */
554
+ const NL = String.fromCharCode(10);
555
+
556
+ const scanSelectedEvents = (content) => {
557
+ const out = [];
558
+ const newlineAt = content.indexOf(NL);
559
+ const after = newlineAt === -1 ? content : content.slice(newlineAt + 1);
560
+ for (const line of after.split(NL)) {
561
+ if (line.length === 0) continue;
562
+ let obj;
563
+ try { obj = JSON.parse(line); } catch { continue; }
564
+ if (obj !== null && typeof obj === "object" && obj.type === "agent-preset/selected" && obj.data !== void 0 && typeof obj.data.agentPreset === "string") {
565
+ out.push({ agentPreset: obj.data.agentPreset, time: obj.time, seq: obj.seq });
566
+ }
567
+ }
568
+ return out;
569
+ };
570
+
571
+ const scanPreset = async (filter) => {
572
+ // Pull the full preset roster so the UI shows every available preset,
573
+ // not just the ones currently used by some session.
574
+ let allPresetIds = [];
575
+ try {
576
+ const ap = ctx.get("agentPresets");
577
+ if (ap !== void 0 && typeof ap.list === "function") {
578
+ const list = await ap.list();
579
+ for (const p of (list || [])) {
580
+ if (p && typeof p.id === "string" && p.id.length > 0) allPresetIds.push(p.id);
581
+ }
582
+ }
583
+ } catch { /* ignore -- fall back to used presets only */ }
584
+
585
+ const persistence = adapter.persistence;
586
+ if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
587
+ // Enumeration normalizes backend snapshots and retains the legacy
588
+ // raw-id disk fallback. Incomplete reads never authorize reconciliation.
589
+ let headers = [];
590
+ try {
591
+ headers = await listSessionHeaders(persistence, adapter.homePath);
592
+ } catch (probeError) {
593
+ throw new Error("failed to enumerate sessions: " + String(probeError.message ?? probeError));
594
+ }
595
+ let allowedIds = null;
596
+ const workspaceId = filter !== void 0 && typeof filter === "object" ? filter.id : void 0;
597
+ if (typeof workspaceId === "string" && workspaceId !== "") {
598
+ const registry = ctx.get("workspaceRegistry");
599
+ if (registry !== void 0 && typeof registry.list === "function") {
600
+ const all = registry.list();
601
+ const ws = all.find((entity) => entity.id === workspaceId);
602
+ if (ws === void 0) {
603
+ const error = new Error("workspace not found: " + workspaceId);
604
+ error.code = "workspace-not-found";
605
+ throw error;
606
+ }
607
+ allowedIds = new Set();
608
+ const ids = typeof ws.sessionIds === "function" ? ws.sessionIds() : ws.sessionIds;
609
+ if (Array.isArray(ids)) for (const id of ids) allowedIds.add(id);
610
+ }
611
+ }
612
+ const requestedSessionId = filter !== void 0 && typeof filter === "object" && typeof filter.sessionId === "string"
613
+ ? filter.sessionId
614
+ : "";
615
+ if (requestedSessionId !== "") assertSessionId(requestedSessionId);
616
+ const out = [];
617
+ for (const header of headers) {
618
+ if (requestedSessionId !== "" && header.id !== requestedSessionId) continue;
619
+ if (allowedIds !== null && !allowedIds.has(header.id)) continue;
620
+ if (header.origin === "subagent") continue;
621
+ const raw = await readSessionArtifact(header.id, undefined, { storedHeader: header });
622
+ if (raw === void 0) continue;
623
+ const newlineAt = raw.content.indexOf(NL);
624
+ if (newlineAt === -1) continue;
625
+ let headerObj;
626
+ try { headerObj = JSON.parse(raw.content.slice(0, newlineAt)); } catch { continue; }
627
+ let selected = scanSelectedEvents(raw.content);
628
+ const live = ctx.sessions.get(header.id);
629
+ if (live !== void 0) {
630
+ const liveEvents = Array.isArray(live.events)
631
+ ? live.events
632
+ : Array.isArray(live.log) ? live.log : [];
633
+ const liveSelected = liveEvents
634
+ .filter((event) => event?.type === "agent-preset/selected" && typeof event.data?.agentPreset === "string")
635
+ .map((event) => ({ agentPreset: event.data.agentPreset, time: event.time, seq: event.seq }));
636
+ if (liveSelected.length > selected.length) selected = liveSelected;
637
+ }
638
+ const finalPreset = selected.length > 0 ? selected[selected.length - 1].agentPreset : headerObj.agentPreset;
639
+ out.push({ sessionId: header.id, cwd: header.cwd, origin: header.origin, headerPreset: headerObj.agentPreset, selectedEvents: selected, finalPreset });
640
+ }
641
+ // Targets come only from the live roster. A deleted preset can still be
642
+ // displayed as this session's current value, but must not be offered as
643
+ // a destination.
644
+ return { rows: out, availablePresets: Array.from(new Set(allPresetIds)) };
645
+ };
646
+
647
+ /**
648
+ * Rewrite the effective preset of one conversation in place on disk.
649
+ * The 0.4.6+ flow is no-teardown: when a live session is in store we
650
+ * append the new agent-preset/selected event via Session.append() and
651
+ * flush through SessionStore.flush(); for cold sessions we rewrite
652
+ * the last matching event directly on the existing artifact. In both
653
+ * cases the live agent/session is left intact, the api-gateway chat
654
+ * panel stays available, and the projection picks up the new value
655
+ * on the next event fold.
656
+ */
657
+ /** Cold-path preset migration: read disk, rewrite, publish. Works whether
658
+ * or not the session is currently in the coordinator, and does not depend on
659
+ * `coordinator.states` carrying a fresh `meta.cwd`. */
660
+ const applyMigrationToArtifact = async (args) => {
661
+ const sessionId = typeof args.sessionId === "string" ? args.sessionId : "";
662
+ const toPreset = typeof args.toPreset === "string" ? args.toPreset : "";
663
+ const liveSession = (args !== void 0 && typeof args === "object") ? args.liveSession : void 0;
664
+ const persistence = adapter.persistence;
665
+ if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
666
+ const coordinator = persistence.coordinator;
667
+ const serialize = typeof coordinator?.serialize === "function"
668
+ ? (operation) => coordinator.serialize(sessionId, operation)
669
+ : (operation) => operation();
670
+ return await serialize(async () => {
671
+ const raw = await readSessionArtifact(sessionId);
672
+ if (raw === void 0) throw new Error(`session "${sessionId}" has no artifact`);
673
+ const lines = raw.content.split(NL);
674
+ if (lines.length < 2) throw new Error("session artifact has no header line");
675
+ let header;
676
+ try { header = JSON.parse(lines[0]); } catch { throw new Error("session header parse failed"); }
677
+ if (header.id !== sessionId) throw new Error("session header id mismatch");
678
+
679
+ let selectedIndex = -1;
680
+ let selectedPreset;
681
+ for (let index = 1; index < lines.length; index += 1) {
682
+ if (lines[index] === "") continue;
683
+ let event;
684
+ try { event = JSON.parse(lines[index]); } catch { continue; }
685
+ if (event?.type === "agent-preset/selected" && typeof event.data?.agentPreset === "string") {
686
+ selectedIndex = index;
687
+ selectedPreset = event.data.agentPreset;
688
+ }
689
+ }
690
+ const oldPreset = selectedIndex >= 0 ? selectedPreset : header.agentPreset;
691
+ if (oldPreset === toPreset) {
692
+ return { sessionId, migrated: false, oldPreset, newPreset: toPreset };
693
+ }
694
+
695
+ if (selectedIndex >= 0) {
696
+ const event = JSON.parse(lines[selectedIndex]);
697
+ event.data = { ...event.data, agentPreset: toPreset };
698
+ lines[selectedIndex] = JSON.stringify(event);
699
+ } else {
700
+ header.agentPreset = toPreset;
701
+ lines[0] = JSON.stringify(header);
702
+ }
703
+
704
+ const artifactPath = raw.path ?? persistence.locate?.(raw.meta)?.path;
705
+ if (typeof artifactPath !== "string") throw new Error("cannot locate session artifact");
706
+ const replacementContent = lines.join(NL);
707
+ const firstNewline = replacementContent.indexOf(NL);
708
+ const bytes = await encodeArtifact(
709
+ replacementContent.slice(0, firstNewline),
710
+ replacementContent.slice(firstNewline + 1),
711
+ artifactPath.endsWith(".zstd")
712
+ );
713
+ const home = adapter.homePath;
714
+ await assertSessionDirectory(typeof home === "function" ? home("sessions") : undefined, dirname(artifactPath), sessionId);
715
+ const published = await replaceSessionFile(artifactPath, bytes);
716
+ if (published.backupPath) ctx.logger.warn("session-manager: retained backup " + published.backupPath);
717
+
718
+ const state = coordinator?.states?.get?.(sessionId);
719
+ if (state !== void 0 && selectedIndex < 0) state.meta = { ...state.meta, agentPreset: toPreset };
720
+ coordinator?.preparations?.invalidate?.(sessionId);
721
+ // Mirror the disk rewrite into the in-memory live session: the cold path
722
+ // bypasses the persistence write controller (which is intentionally
723
+ // skipped when its state is stale), so the session header, projection,
724
+ // and downstream agent composition would otherwise keep reporting the old
725
+ // preset. Update both the header and the in-memory event log so DSH's
726
+ // `resolveSessionPreset` and any projection subscribers observe the new
727
+ // preset from the same source.
728
+ if (liveSession !== void 0) {
729
+ try {
730
+ const nextHeader = { ...(liveSession.header ?? {}), agentPreset: toPreset };
731
+ try { liveSession.header = Object.freeze(nextHeader); }
732
+ catch { liveSession.header = nextHeader; }
733
+ } catch { /* live session may have been retired mid-flight */ }
734
+ // Append the new selection to the live log so the session/store
735
+ // observers (agent-presets, projections, ctx) fire their normal
736
+ // `session/event` + `agent-preset/selected` pipeline. We append
737
+ // unconditionally (not only when the disk had no prior selection)
738
+ // because the in-memory projection reads the latest appended event
739
+ // and the cold path deliberately skipped the persistence write
740
+ // controller; the appended event will be persisted on the next
741
+ // normal flush, keeping disk and memory consistent.
742
+ if (typeof liveSession.append === "function") {
743
+ try { liveSession.append("agent-preset/selected", { agentPreset: toPreset }); } catch { /* best-effort */ }
744
+ }
745
+ }
746
+ return { sessionId, migrated: true, oldPreset, newPreset: toPreset };
747
+ });
748
+ };
749
+ /** Rewrite exactly one conversation's effective Agent preset. */
750
+ const migratePreset = async (opts) => {
751
+ const sessionId = typeof opts.sessionId === "string" ? opts.sessionId.trim() : "";
752
+ const toPreset = typeof opts.toPreset === "string" ? opts.toPreset.trim() : "";
753
+ if (sessionId === "") { const e = new Error("sessionId required"); e.code = "bad-request"; throw e; }
754
+ if (toPreset === "") { const e = new Error("toPreset required"); e.code = "bad-request"; throw e; }
755
+
756
+ const presets = ctx.get("agentPresets");
757
+ if (presets === void 0 || typeof presets.list !== "function") {
758
+ throw new Error("agentPresets service unavailable");
759
+ }
760
+ const roster = await presets.list();
761
+ const target = (roster || []).find((preset) => preset && preset.id === toPreset);
762
+ if (target === void 0) {
763
+ const available = (roster || []).map((preset) => preset?.id).filter(Boolean);
764
+ throw new Error(`Agent 预设 "${toPreset}" 不存在(可用:${available.join(", ")})`);
765
+ }
766
+ if (target.broken !== void 0) throw new Error(`Agent 预设 "${toPreset}" 不可用:${target.broken}`);
767
+
768
+ const liveSession = ctx.sessions.get(sessionId);
769
+ let liveAgent;
770
+ try { liveAgent = ctx.agents.get(sessionId); } catch { liveAgent = void 0; }
771
+ // Resolve persistence up front so the live path can read the coordinator
772
+ // without tripping JavaScript's temporal dead zone on `const persistence`.
773
+ const persistence = adapter.persistence;
774
+ if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
775
+
776
+ if (liveSession !== void 0) {
777
+ const coordinator = persistence.coordinator;
778
+ const states = coordinator?.states;
779
+ const beforeState = states?.get?.(sessionId);
780
+ const liveCwd = liveSession.header?.cwd;
781
+ // A just-completed moveSession mutates `liveSession.header.cwd` in place,
782
+ // but the persistence coordinator's tracked state may not see the new cwd
783
+ // until its serialize chain drains. If we hand the migration to the
784
+ // coordinator now, its `state.meta.cwd` may still be the pre-move cwd and
785
+ // appendBatch will open the old (now deleted) artifact path, producing the
786
+ // "ENOENT ... session.v2.jsonl.zstd" regression. Falling back to the cold
787
+ // path is always correct: the disk copy already reflects the new cwd.
788
+ const stateStale = beforeState === void 0
789
+ || beforeState.meta?.cwd === void 0
790
+ || (liveCwd !== void 0 && beforeState.meta.cwd !== liveCwd);
791
+ if (stateStale) {
792
+ const raw = await readSessionArtifact(sessionId);
793
+ if (raw !== void 0) {
794
+ const result = await applyMigrationToArtifact({ sessionId, toPreset, liveSession });
795
+ if (result.migrated) { try { ctx.emit("agent-preset/selected", sessionId, toPreset); } catch { /* best-effort */ } }
796
+ 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)})`);
797
+ return { sessionId, migrated: true, oldPreset: result.oldPreset, newPreset: toPreset };
798
+ }
799
+ // No artifact yet; fall through to the in-memory + flush path below,
800
+ // which materializes the empty file using the live cwd.
801
+ }
802
+ let oldPreset = liveSession.header?.agentPreset;
803
+ // SessionStore implementations from older DSH builds may expose the
804
+ // history as `log` rather than the newer `events` snapshot getter.
805
+ // Do not dereference `.length` on an absent compatibility surface.
806
+ const liveEvents = Array.isArray(liveSession.events)
807
+ ? liveSession.events
808
+ : Array.isArray(liveSession.log) ? liveSession.log : [];
809
+ for (let index = liveEvents.length - 1; index >= 0; index -= 1) {
810
+ const event = liveEvents[index];
811
+ if (event?.type === "agent-preset/selected" && typeof event.data?.agentPreset === "string") {
812
+ oldPreset = event.data.agentPreset;
813
+ break;
814
+ }
815
+ }
816
+ if (oldPreset === toPreset) {
817
+ return { sessionId, migrated: false, oldPreset, newPreset: toPreset };
818
+ }
819
+ if (liveAgent !== void 0 && typeof presets?.recompose === "function" && liveAgent.ctx) {
820
+ try { await presets.recompose(liveAgent.ctx, toPreset); } catch { /* best-effort */ }
821
+ }
822
+ liveSession.append("agent-preset/selected", { agentPreset: toPreset });
823
+ await ctx.sessions.flush(liveSession);
824
+ ctx.logger.info(`session-manager: migrated live preset for "${sessionId}" from "${String(oldPreset)}" to "${toPreset}"`);
825
+ return { sessionId, migrated: true, oldPreset, newPreset: toPreset };
826
+ }
827
+
828
+ // A session absent from SessionStore is cold. If an older plugin left its
829
+ // exact Session object in the coordinator, retire that proven orphan by
830
+ // the coordinator's own drain path instead of deleting owner bookkeeping.
831
+ const coordinator = persistence.coordinator;
832
+ let tracked = coordinator?.states?.get?.(sessionId);
833
+ if (tracked?.owner !== void 0 && ctx.sessions.get(sessionId) === void 0) {
834
+ coordinator.retire?.(tracked.owner);
835
+ const retirement = coordinator.retirements?.get?.(sessionId);
836
+ if (retirement !== void 0) await retirement;
837
+ tracked = coordinator.states?.get?.(sessionId);
838
+ if (tracked?.owner !== void 0) {
839
+ throw new Error(`会话 ${sessionId} 仍有未释放的持久化 owner,已停止迁移以保护数据`);
840
+ }
841
+ }
842
+
843
+ const result = await applyMigrationToArtifact({ sessionId, toPreset, liveSession });
844
+
845
+ if (result.migrated) {
846
+ try { ctx.emit("agent-preset/selected", sessionId, toPreset); } catch { /* best-effort */ }
847
+ ctx.logger.info(`session-manager: migrated cold preset for "${sessionId}" from "${String(result.oldPreset)}" to "${toPreset}"`);
848
+ }
849
+ return result;
850
+ };
851
+
852
+ /** Read one session artifact verbatim, falling back to direct disk access when the
853
+ * configured persistence backend cannot see the id (e.g. an older DSH build
854
+ * wrote a "session.v2.jsonl.zstd" file under the raw-id directory).
855
+ */
856
+ const readSessionArtifact = async (sessionId, signal, { headerOnly = false, storedHeader } = {}) => {
857
+ assertSessionId(sessionId);
858
+ const persistence = adapter.persistence;
859
+ const dshHomePath = adapter.homePath;
860
+ const root = typeof dshHomePath === "function" ? dshHomePath("sessions") : undefined;
861
+ const read = async (path) => headerOnly
862
+ ? { meta: await readSessionHeader(path), path }
863
+ : readSessionFile(path);
864
+ // Use cheap index metadata as a location hint, never a decoded readRaw
865
+ // payload. Move/preset scans can reuse headers they already enumerated.
866
+ let header = storedHeader;
867
+ if (header === undefined && typeof persistence?.list === "function") {
868
+ try {
869
+ header = (await persistence.list()).map(normalizeSessionHeader).find(item => item?.id === sessionId);
870
+ } catch (error) { if (signal?.aborted) throw error; }
871
+ }
872
+ if (header !== undefined && typeof persistence?.locate === "function") {
873
+ const path = persistence.locate(header)?.path;
874
+ if (typeof path === "string") {
875
+ try {
876
+ await assertSessionDirectory(root, dirname(path), sessionId);
877
+ const artifact = await read(path);
878
+ if (artifact.meta.id !== sessionId) throw new Error("会话工件 header id 与请求不一致");
879
+ return artifact;
880
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
881
+ }
882
+ }
883
+ if (typeof root !== "string") throw new Error("无法定位并验证会话工件目录");
884
+ let projects;
885
+ try { projects = await readdir(root, { withFileTypes: true }); }
886
+ catch (error) { if (error.code === "ENOENT") return undefined; throw error; }
887
+ for (const proj of projects) {
888
+ if (!proj.isDirectory() || proj.isSymbolicLink()) continue;
889
+ for (const candidate of [encodeSessionSegment(sessionId), sessionId]) {
890
+ const dir = join(root, proj.name, candidate);
891
+ try { await assertSessionDirectory(root, dir, sessionId); }
892
+ catch (error) { if (error.code === "ENOENT") continue; throw error; }
893
+ for (const filename of ARTIFACT_NAMES) {
894
+ try {
895
+ const artifact = await read(join(dir, filename));
896
+ if (artifact.meta.id !== sessionId) throw new Error("会话工件 header id 与请求不一致");
897
+ return artifact;
898
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
899
+ }
900
+ }
901
+ }
902
+ return undefined;
903
+ };
904
+
905
+ const sessionDirOf = async (sessionId) => {
906
+ // Require a matching artifact header instead of deleting an arbitrary
907
+ // directory merely because its name matches user input.
908
+ const artifact = await readSessionArtifact(sessionId, undefined, { headerOnly: true });
909
+ return artifact === undefined ? undefined : dirname(artifact.path);
910
+ };
911
+
912
+ /**
913
+ * Delete one session end to end. Returns a summary of what was torn down.
914
+ * Idempotent-ish: unknown sessions resolve to { ok: true, deleted: false }.
915
+ */
916
+ const deleteSession = async (sessionId) => {
917
+ assertSessionId(sessionId);
918
+ // Resolve/validate before cancelling the agent or changing registry state.
919
+ let dir = await sessionDirOf(sessionId);
920
+ const session = ctx.sessions.get(sessionId);
921
+ // 0.1.1-rc.2 throws ApiRemoteSessionNotFound for cold sessions here.
922
+ let agent;try{agent=ctx.agents.get(sessionId)}catch{agent=void 0}
923
+
924
+ if (agent !== void 0) {
925
+ // Stop any running turn (disposed-kind suppresses re-wake).
926
+ agent.cancel({ kind: "disposed" });
927
+ // Quiesce the agent's own fiber (idempotent; bounded in case teardown stalls).
928
+ if (typeof agent.scope?.dispose === "function") {
929
+ await Promise.race([agent.scope.dispose(), sleep(3000)]);
930
+ }
931
+ // Drop the zombie from the registry so a later session.create/open with
932
+ // the same id cannot resurrect it.
933
+ try {
934
+ ctx.agents.store?.delete?.(sessionId);
935
+ } catch { /* best-effort */ }
936
+ }
937
+
938
+ let detached = false;
939
+ if (session !== void 0) {
940
+ // Flush buffered events to disk first so the retirement drain is a no-op.
941
+ try {
942
+ await ctx.sessions.flush(session);
943
+ } catch { /* best-effort */ }
944
+ // Detach the session store entry: emits session/disposed, which the
945
+ // persistence write-path answers with a final drain, and the API proxy
946
+ // relays as host/session-removed so every connected client drops the row.
947
+ try {
948
+ const entry = ctx.sessions.store?.get?.(sessionId);
949
+ if (entry !== void 0 && typeof entry.detach === "function") {
950
+ entry.detach();
951
+ await sleep(200); // let the write-behind retirement settle
952
+ detached = true;
953
+ }
954
+ } catch { /* best-effort */ }
955
+ }
956
+ // Some sessions have a stored artifact but no live store row (e.g.
957
+ // already-scoped scope torn down, or never attached). Without a live
958
+ // entry, ctx.sessions.store?.get?.(sessionId) returns undefined and
959
+ // entry.detach() never fires — so the apiproxy never queues a
960
+ // host/session-removed frame, every connected client keeps showing the
961
+ // session row, and the row collapses into the ungrouped section the
962
+ // moment host/workspace-changed drops its workspace membership. Emit
963
+ // session/disposed explicitly so every connected client drops the row.
964
+ if (!detached) {
965
+ try {
966
+ ctx.emit("session/disposed", { id: sessionId });
967
+ } catch (_) { /* best-effort */ }
968
+ }
969
+
970
+ // A blank live session may have materialized its first artifact during
971
+ // flush/retirement. Re-resolve after teardown rather than leaking that file.
972
+ dir = await sessionDirOf(sessionId);
973
+
974
+ // Workspace accounting + archive-set membership.
975
+ await detachFromWorkspaces(sessionId);
976
+ await unarchiveSession(sessionId);
977
+
978
+ // Physical artifact (session.jsonl / session.jsonl.zstd) + any extras.
979
+ if (dir !== void 0) {
980
+ await assertSessionDirectory(adapter.homePath("sessions"), dir, sessionId);
981
+ await rm(dir, { recursive: true, force: true });
982
+ }
983
+
984
+ let warning;
985
+ try { await annotations().remove(sessionId); }
986
+ catch (error) {
987
+ warning = "会话已删除,但独立标记清理失败: " + safeErrorMessage(error);
988
+ ctx.logger.warn("session-manager: " + warning);
989
+ }
990
+ return {
991
+ ok: true,
992
+ ...(warning ? { warning } : {}),
993
+ sessionId,
994
+ wasLive: session !== void 0 || agent !== void 0,
995
+ filesRemoved: dir !== void 0
996
+ };
997
+ };
998
+
999
+ /**
1000
+ * On plugin boot, refold every persisted session projection cache
1001
+ * row from disk. Sessions moved before coldSnapshot was wired into
1002
+ * moveSession would otherwise keep their pre-move {createdAt, cwd}
1003
+ * identity and let the cold list path fall back to basename(cwd),
1004
+ * surfacing the workspace title (for example "DSH") where the
1005
+ * session's own title was expected. The sweep is one-shot and
1006
+ * idempotent: a row whose identity already matches is a cheap
1007
+ * pass-through refold, and a stale one triggers the unrelated-identity
1008
+ * full re-read path.
1009
+ */
1010
+ ctx.effect(async () => {
1011
+ const cache = adapter.projectionCache;
1012
+ const persistence = adapter.persistence;
1013
+ const registry = adapter.workspaceRegistry;
1014
+ if (typeof cache?.coldSnapshot !== "function" || typeof persistence?.list !== "function" || typeof registry?.list !== "function") return;
1015
+ try {
1016
+ // Remember only ids that existed before the async scan. Concurrently
1017
+ // attached ids must never be removed using this older disk snapshot.
1018
+ const initialIds = new Map(registry.list().map(ws => [ws.id, new Set(ws.record?.sessionIds ?? [])]));
1019
+ const scan = await scanSessionHeaders(persistence, adapter.homePath);
1020
+ if (!scan.complete) {
1021
+ ctx.logger.warn("session-manager: incomplete session scan; workspace reconciliation skipped: " + scan.errors.map(safeErrorMessage).join("; "));
1022
+ return;
1023
+ }
1024
+ const headers = scan.headers;
1025
+ const validIds = new Set(headers.map(header => header.id));
1026
+ for (const header of headers) {
1027
+ try { await cache.coldSnapshot(header.id); }
1028
+ catch (error) { ctx.logger.warn('session-manager: post-boot cache refold failed: ' + safeErrorMessage(error)); }
1029
+ }
1030
+ let removed = 0;
1031
+ let added = 0;
1032
+ // Read current state *inside* its queue, and publish an immutable copy.
1033
+ // A failed setState must not mutate the registry's live state object.
1034
+ await registry.enqueueOperation(async () => {
1035
+ const state = registry.requireState();
1036
+ const pathById = new Map(registry.list().map(ws => [ws.id, ws.path]));
1037
+ const assignedIds = new Set((state.workspaces ?? []).flatMap(ws => ws.sessionIds ?? []));
1038
+ const workspaces = (state.workspaces ?? []).map(ws => {
1039
+ const original = ws.sessionIds ?? [];
1040
+ const sessionIds = original.filter(id => validIds.has(id)
1041
+ || !initialIds.get(ws.id)?.has(id) || adapter.getSession(id) !== undefined);
1042
+ const removedHere = original.length - sessionIds.length;
1043
+ removed += removedHere;
1044
+ for (const header of headers) {
1045
+ if (header.cwd === undefined || header.cwd !== pathById.get(ws.id) || assignedIds.has(header.id)) continue;
1046
+ sessionIds.unshift(header.id);
1047
+ assignedIds.add(header.id);
1048
+ added += 1;
1049
+ }
1050
+ if (sessionIds.length === original.length && sessionIds.every((id, i) => id === original[i])) return ws;
1051
+ return { ...ws, sessionIds, updatedAt: new Date().toISOString() };
1052
+ });
1053
+ if (removed || added) await registry.setState({ ...state, workspaces });
1054
+ });
1055
+ if (removed || added) ctx.logger.info('session-manager: post-boot workspace reconcile removed ' + removed + ' orphans, attached ' + added + ' disk-only sessions');
1056
+ } catch (error) {
1057
+ ctx.logger.warn('session-manager: post-boot reconcile failed: ' + safeErrorMessage(error));
1058
+ }
1059
+ }, "session-manager: post-boot re-fold stale projection cache rows");
1060
+
1061
+ /** Build a normalized annotation patch from one bulk action + payload.
1062
+ * Returns null when the payload is missing or malformed so the caller can
1063
+ * surface a 400 instead of letting the store throw on a bad value.
1064
+ */
1065
+ const annotationPatchFromBatchAction = (action, payload) => {
1066
+ if (!payload || typeof payload !== "object") return null;
1067
+ if (action === "favorite" || action === "unfavorite") return { favorite: action === "favorite" };
1068
+ if (action === "review" || action === "unreview") return { reviewLater: action === "review" };
1069
+ if (action === "set-priority") {
1070
+ const p = Number(payload.priority);
1071
+ if (!Number.isInteger(p) || p < 1 || p > 5) return null;
1072
+ return { priority: p };
1073
+ }
1074
+ if (action === "add-tags" || action === "remove-tags") {
1075
+ if (!Array.isArray(payload.tags)) return null;
1076
+ return action === "add-tags" ? { tags: payload.tags } : { tags: [] };
1077
+ }
1078
+ return null;
1079
+ };
1080
+
1081
+ /** Run one batch action against a single session id. Annotation-affecting
1082
+ * actions resolve the annotation accessor from the surrounding closure
1083
+ * so it can never be silently undefined. Session-management actions reuse
1084
+ * the existing helpers verbatim so move/preset-migrate validation and
1085
+ * live-session handling stay identical to the per-row buttons.
1086
+ */
1087
+ const runBatchAction = async ({ action, sessionId, payload, mutate, deleteSession, unarchiveSession, moveSession, migratePreset, adapter }) => {
1088
+ const annotationsAccessor = annotations;
1089
+ if (action === "favorite" || action === "unfavorite" || action === "review" || action === "unreview" || action === "set-priority" || action === "add-tags" || action === "remove-tags") {
1090
+ const patch = annotationPatchFromBatchAction(action, payload);
1091
+ if (patch === null) {
1092
+ const e = new Error("invalid batch payload for " + action); e.code = "bad-request"; throw e;
1093
+ }
1094
+ try {
1095
+ await annotationsAccessor().batchUpdate([sessionId], patch);
1096
+ } catch (error) {
1097
+ throw error;
1098
+ }
1099
+ return;
1100
+ }
1101
+ if (action === "archive") { await mutate(sessionId, () => archiveSession(sessionId)); return; }
1102
+ if (action === "unarchive") { await mutate(sessionId, () => unarchiveSession(sessionId)); return; }
1103
+ if (action === "delete") { await mutate(sessionId, () => deleteSession(sessionId)); return; }
1104
+ if (action === "move") {
1105
+ const targetWorkspaceId = typeof payload?.targetWorkspaceId === "string" ? payload.targetWorkspaceId.trim() : "";
1106
+ if (!targetWorkspaceId) { const e = new Error("targetWorkspaceId required"); e.code = "bad-request"; throw e; }
1107
+ await mutate(sessionId, () => moveSession(sessionId, targetWorkspaceId));
1108
+ return;
1109
+ }
1110
+ if (action === "preset-migrate") {
1111
+ const toPreset = typeof payload?.toPreset === "string" ? payload.toPreset.trim() : "";
1112
+ if (!toPreset) { const e = new Error("toPreset required"); e.code = "bad-request"; throw e; }
1113
+ await mutate(sessionId, () => migratePreset({ sessionId, toPreset }));
1114
+ return;
1115
+ }
1116
+ const snapshot = adapter.workspaceRegistry?.headers?.get?.(sessionId)
1117
+ ?? adapter.sessions?.list?.()?.find(s => s?.id === sessionId)?.header
1118
+ ?? null;
1119
+ const isSubagent = snapshot?.origin === "subagent";
1120
+ const isBlank = snapshot?.blank === true;
1121
+ if (isSubagent) { const e = new Error("subagent"); e.code = "subagent-skip"; throw e; }
1122
+ if (isBlank) { const e = new Error("blank"); e.code = "blank-skip"; throw e; }
1123
+ };
1124
+
1125
+ ctx.effect(() => ctx.webServer.register({ kind: "prefix",
1126
+ path: API_PREFIX,
1127
+ handler: async (req, res) => {
1128
+ try {
1129
+ const url = new URL(req.url ?? "/", "http://localhost");
1130
+ const path = url.pathname.startsWith(API_PREFIX) ? url.pathname.slice(API_PREFIX.length) || "/" : "/";
1131
+ let body = {};
1132
+ if (req.method === "POST") {
1133
+ const raw = await readBody(req);
1134
+ if (raw.trim() !== "") {
1135
+ try { body = JSON.parse(raw); }
1136
+ catch { return send(res, 400, { ok: false, error: "请求体不是合法 JSON" }); }
1137
+ }
1138
+ }
1139
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
1140
+ return send(res, 400, { ok: false, error: "请求体必须是 JSON 对象" });
1141
+ }
1142
+ const sessionId = typeof body.sessionId === "string" ? body.sessionId.trim() : "";
1143
+ if (req.method === "GET" && path === "/annotations") {
1144
+ return send(res, 200, { ok: true, result: { annotations: await annotations().list() } });
1145
+ }
1146
+ if (req.method === "POST" && path === "/annotations") {
1147
+ assertSessionId(sessionId);
1148
+ const annotation = await mutate(sessionId, async () => {
1149
+ assertAnnotatable(sessionId);
1150
+ return annotations().update(sessionId, body.patch, body.expectedRevision);
1151
+ });
1152
+ return send(res, 200, { ok: true, result: { sessionId, annotation } });
1153
+ }
1154
+ if (req.method === "POST" && ["/delete", "/unarchive", "/move", "/preset-migrate"].includes(path)) {
1155
+ assertSessionId(sessionId);
1156
+ let result;
1157
+ if (path === "/delete") result = await mutate(sessionId, () => deleteSession(sessionId));
1158
+ else if (path === "/unarchive") {
1159
+ await mutate(sessionId, () => unarchiveSession(sessionId));
1160
+ result = { sessionId };
1161
+ } else if (path === "/move") {
1162
+ const targetWorkspaceId = typeof body.targetWorkspaceId === "string" ? body.targetWorkspaceId.trim() : "";
1163
+ if (!targetWorkspaceId) return send(res, 400, { ok: false, error: "targetWorkspaceId 必填" });
1164
+ result = await mutate(sessionId, () => moveSession(sessionId, targetWorkspaceId));
1165
+ } else {
1166
+ const toPreset = typeof body.toPreset === "string" ? body.toPreset.trim() : "";
1167
+ if (!toPreset) return send(res, 400, { ok: false, error: "toPreset 必填" });
1168
+ result = await mutate(sessionId, () => migratePreset({ sessionId, toPreset }));
1169
+ }
1170
+ return send(res, 200, { ok: true, result });
1171
+ }
1172
+ if (req.method === "POST" && path === "/batch") {
1173
+ // Per-action body shape (each action validates its own payload):
1174
+ // archive : no payload
1175
+ // unarchive : no payload
1176
+ // delete : no payload
1177
+ // move : { targetWorkspaceId }
1178
+ // preset-migrate: { toPreset }
1179
+ // favorite : no payload (defaults to true)
1180
+ // unfavorite : no payload
1181
+ // review : no payload
1182
+ // unreview : no payload
1183
+ // set-priority : { priority: 1..5 }
1184
+ // add-tags : { tags: string[] }
1185
+ // remove-tags : { tags: string[] }
1186
+ const rawAction = typeof body.action === "string" ? body.action : "";
1187
+ const rawIds = Array.isArray(body.sessionIds) ? body.sessionIds : [];
1188
+ const ids = Array.from(new Set(rawIds.filter(id => typeof id === "string" && id.trim() !== "").map(id => id.trim())));
1189
+ for (const id of ids) assertSessionId(id);
1190
+ if (ids.length === 0) return send(res, 400, { ok: false, error: "sessionIds 必须是非空数组", code: "bad-request" });
1191
+ if (ids.length > 200) return send(res, 400, { ok: false, error: "单次批量最多 200 条,请缩小筛选范围后重试", code: "batch-too-large" });
1192
+ const payload = body.payload && typeof body.payload === "object" ? body.payload : {};
1193
+ const BATCH_ACTIONS = new Set(["archive", "unarchive", "delete", "move", "preset-migrate", "favorite", "unfavorite", "review", "unreview", "set-priority", "add-tags", "remove-tags"]);
1194
+ if (!BATCH_ACTIONS.has(rawAction)) return send(res, 400, { ok: false, error: "action 不支持: " + rawAction, code: "bad-request" });
1195
+ const items = [];
1196
+ let success = 0, failed = 0, skipped = 0;
1197
+ for (const sessionId of ids) {
1198
+ try {
1199
+ await runBatchAction({ action: rawAction, sessionId, payload, mutate, deleteSession, unarchiveSession, moveSession, migratePreset, adapter });
1200
+ items.push({ sessionId, status: "success" });
1201
+ success++;
1202
+ } catch (error) {
1203
+ const code = error && typeof error.code === "string" ? error.code : undefined;
1204
+ if (code === "subagent-skip" || code === "blank-skip") {
1205
+ items.push({ sessionId, status: "skipped", reason: code });
1206
+ skipped++;
1207
+ } else {
1208
+ items.push({ sessionId, status: "failed", code, error: safeErrorMessage(error) });
1209
+ failed++;
1210
+ }
1211
+ }
1212
+ }
1213
+ return send(res, 200, { ok: true, result: {
1214
+ summary: { total: ids.length, success, failed, skipped },
1215
+ items,
1216
+ aborted: false,
1217
+ } });
1218
+ }
1219
+ if (req.method === "GET" && path === "/workspaces") {
1220
+ const sessionCreatedAt = Object.fromEntries(adapter.cachedSessionHeaders()
1221
+ .filter(header => typeof header.createdAt === "number" || typeof header.createdAt === "string")
1222
+ .map(header => [header.id, header.createdAt]));
1223
+ return send(res, 200, { ok: true, result: { workspaces: listWorkspaces(), sessionCreatedAt } });
1224
+ }
1225
+ if (req.method === "GET" && path === "/preset-scan") {
1226
+ const sessionId = url.searchParams.get("sessionId") || "";
1227
+ if (sessionId) assertSessionId(sessionId);
1228
+ const result = await scanPreset({ id: url.searchParams.get("workspaceId") || "", sessionId });
1229
+ return send(res, 200, { ok: true, result });
1230
+ }
1231
+ return send(res, 404, { ok: false, error: "not found: " + req.method + " " + path });
1232
+ } catch (error) {
1233
+ ctx.logger.warn("session-manager: api error: " + safeErrorMessage(error) + "; json=" + safeJson(error));
1234
+ const status = error?.code === "bad-request" ? 400 : error?.code === "body-too-large" ? 413
1235
+ : error?.code === "annotation-conflict" || error?.code === "annotations-busy" ? 409
1236
+ : error?.code === "session-not-found" ? 404 : error?.code?.startsWith("annotations-") ? 503 : 500;
1237
+ return send(res, status, { ok: false, error: safeErrorMessage(error), ...(typeof error?.code === "string" ? { code: error.code } : {}) });
1238
+ }
1239
+ }
1240
+ }), "session-manager: http api");
1241
+ }
1242
+
1243
+ export { listSessionHeaders, scanSessionHeaders, encodeSessionSegment };