dsh-session-manager 0.1.1 → 0.4.0
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/README.md +95 -77
- package/README.zh.md +117 -0
- package/lib/client.js +855 -348
- package/lib/index.js +1043 -5
- package/package.json +10 -5
package/lib/index.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* @dsh-session-manager — Host half.
|
|
3
3
|
*
|
|
4
4
|
* DSH 0.1.0-rc.6 ships `workspace.archiveSession` (归档) but has NO session
|
|
5
|
-
* deletion and NO
|
|
5
|
+
* deletion, NO unarchive, and NO cross-workspace move. This plugin fills the
|
|
6
|
+
* gaps:
|
|
6
7
|
*
|
|
7
8
|
* - POST /session-manager/api/delete { sessionId }
|
|
8
9
|
* Physically delete one session: cancel/dispose a live agent, detach the
|
|
@@ -13,13 +14,45 @@
|
|
|
13
14
|
* Remove one session from the registry-global archive set. The registry's
|
|
14
15
|
* own `domain/changed` -> `host/archived-sessions-changed` frame then
|
|
15
16
|
* refreshes every connected client.
|
|
17
|
+
* - GET /session-manager/api/workspaces
|
|
18
|
+
* Ordered workspace projection: id / title / path / sessionCount /
|
|
19
|
+
* sessionIds (raw record order). Used by the client move dialog to pick a
|
|
20
|
+
* target and to derive the session's current workspace.
|
|
21
|
+
* - POST /session-manager/api/move { sessionId, targetWorkspaceId }
|
|
22
|
+
* TRUE cross-workspace move. DSH's workspace model keys membership off
|
|
23
|
+
* the session header's immutable `cwd`: `WorkspaceEntity.attachSession`
|
|
24
|
+
* validates `realpath(header.cwd) === workspace.path`, and every record
|
|
25
|
+
* write prunes ids whose indexed cwd no longer matches. So a real move
|
|
26
|
+
* must RE-HOME the session:
|
|
27
|
+
*
|
|
28
|
+
* 1. tear down the live session/agent (same order as delete) so the
|
|
29
|
+
* artifact is quiesced and the write path can no longer append at
|
|
30
|
+
* the old location;
|
|
31
|
+
* 2. read the stored artifact verbatim (`readRaw`), rewrite ONLY the
|
|
32
|
+
* header line's `cwd` to the target workspace's canonical path, and
|
|
33
|
+
* re-encode in the backend's own physical layout (zstd frames with
|
|
34
|
+
* an exact one-header-line first frame, or plain JSONL);
|
|
35
|
+
* 3. publish the new artifact at `locate({cwd: target})` and remove the
|
|
36
|
+
* old one, hiding-then-restoring on failure (never leaves the
|
|
37
|
+
* duplicate-id state that would make list()/findLog() throw);
|
|
38
|
+
* 4. enter a short-lived restored session (prepare + enter, never
|
|
39
|
+
* announced) whose fresh header makes attachSession's validation
|
|
40
|
+
* pass and refreshes the registry's canonical-cwd index, then swap
|
|
41
|
+
* accounting: detach from every other workspace's raw record,
|
|
42
|
+
* attach to the target — through the entity's own serialized
|
|
43
|
+
* durability path, so `host/workspace-changed` frames re-group every
|
|
44
|
+
* client sidebar immediately.
|
|
45
|
+
*
|
|
46
|
+
* History, titles, archive-set membership and lineage are preserved; only
|
|
47
|
+
* the working directory the session belongs to changes.
|
|
16
48
|
*
|
|
17
49
|
* All mutations go through the workspace registry's own serialized
|
|
18
50
|
* `enqueueOperation` + `setState` durability path (the same one the built-in
|
|
19
51
|
* archiveSession uses), so a restart cannot resurrect a removed session.
|
|
20
52
|
*/
|
|
21
|
-
import { rm } from "node:fs/promises";
|
|
53
|
+
import { mkdir, open, realpath, rename, rm } from "node:fs/promises";
|
|
22
54
|
import { dirname } from "node:path";
|
|
55
|
+
import { randomBytes } from "node:crypto";
|
|
23
56
|
|
|
24
57
|
export const name = "dsh-session-manager";
|
|
25
58
|
|
|
@@ -28,9 +61,23 @@ export const inject = [
|
|
|
28
61
|
"workspaceRegistry",
|
|
29
62
|
"sessions",
|
|
30
63
|
"agents",
|
|
31
|
-
"sessionPersistence"
|
|
64
|
+
"sessionPersistence",
|
|
65
|
+
"agentPresets"
|
|
32
66
|
];
|
|
33
67
|
|
|
68
|
+
/** Like JSON.stringify but swallows circular-reference/BigInt errors so the
|
|
69
|
+
* logger never throws while reporting a throw. */
|
|
70
|
+
function safeJson(value) { try { return JSON.stringify(value); } catch { return "[unserializable]"; } }
|
|
71
|
+
/** Like safeJson but used as the user-facing error string in HTTP responses. */
|
|
72
|
+
function safeErrorMessage(error) {
|
|
73
|
+
if (error === null || error === undefined) return `<nullish:${typeof error}>`;
|
|
74
|
+
if (typeof error === "string") return error;
|
|
75
|
+
if (typeof error === "object") {
|
|
76
|
+
if (typeof error.message === "string" && error.message.length > 0) return error.message;
|
|
77
|
+
if (typeof error.code === "string" && error.code.length > 0) return `[code=${error.code}]`;
|
|
78
|
+
}
|
|
79
|
+
try { return JSON.stringify(error); } catch { return String(error); }
|
|
80
|
+
}
|
|
34
81
|
const API_PREFIX = "/session-manager/api";
|
|
35
82
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
36
83
|
|
|
@@ -68,7 +115,827 @@ export function apply(ctx) {
|
|
|
68
115
|
}
|
|
69
116
|
};
|
|
70
117
|
|
|
71
|
-
/**
|
|
118
|
+
/** Ordered workspace projection for the client. */
|
|
119
|
+
const listWorkspaces = () => {
|
|
120
|
+
return ctx.workspaceRegistry.list().map((entity) => {
|
|
121
|
+
const rawIds = Array.isArray(entity.record?.sessionIds)
|
|
122
|
+
? [...entity.record.sessionIds]
|
|
123
|
+
: [...entity.sessionIds];
|
|
124
|
+
return {
|
|
125
|
+
id: entity.id,
|
|
126
|
+
name: entity.title || entity.id,
|
|
127
|
+
title: entity.title || entity.id,
|
|
128
|
+
path: entity.path,
|
|
129
|
+
sessionCount: rawIds.length,
|
|
130
|
+
sessionIds: rawIds
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
});
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Quiet a live session + agent so the artifact is quiesced (mirrors the
|
|
139
|
+
* delete path) WITHOUT removing it from the live store. Returns whether
|
|
140
|
+
* anything live was found. Use this for any operation that might still
|
|
141
|
+
* fail after this point -- the live entry stays put so a failed migration
|
|
142
|
+
* won't fire `session/disposed` (which would erase the row from every
|
|
143
|
+
* connected client's sidebar while the durable state is unchanged).
|
|
144
|
+
*/
|
|
145
|
+
const quietLive = async (sessionId) => {
|
|
146
|
+
const session = ctx.sessions.get(sessionId);
|
|
147
|
+
const agent = ctx.agents.get(sessionId);
|
|
148
|
+
const wasLive = session !== void 0 || agent !== void 0;
|
|
149
|
+
|
|
150
|
+
if (agent !== void 0) {
|
|
151
|
+
// Complete cancellation before the session is detached. The old
|
|
152
|
+
// timeout-based scope disposal could leave the write path owning this
|
|
153
|
+
// Session while the artifact had already been moved; the next model
|
|
154
|
+
// operation would then fail with a live persistence-owner collision.
|
|
155
|
+
agent.cancel({ kind: "disposed" });
|
|
156
|
+
if (typeof agent.whenIdle === "function") await agent.whenIdle();
|
|
157
|
+
if (typeof agent.scope?.dispose === "function") await agent.scope.dispose();
|
|
158
|
+
// Drop the stale registry entry only after the driver has quiesced.
|
|
159
|
+
// The loop's later owner disposer is identity-guarded, so it cannot
|
|
160
|
+
// remove a future same-id agent/session lifecycle.
|
|
161
|
+
try { ctx.agents.store?.delete?.(sessionId); } catch { /* best-effort */ }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (session !== void 0) {
|
|
165
|
+
// Flush buffered events to disk (final drain) -- the persistence
|
|
166
|
+
// write-path turns this into a settled retirement, so the upcoming
|
|
167
|
+
// readRaw() sees a quiesced artifact. The session store entry itself
|
|
168
|
+
// is NOT touched; that decision belongs to releaseLiveSession below.
|
|
169
|
+
try { await ctx.sessions.flush(session); } catch { /* best-effort */ }
|
|
170
|
+
}
|
|
171
|
+
return wasLive;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Detach the live store entry for one session -- the only call site that
|
|
176
|
+
* fires `session/disposed`, which apiproxy relays as `host/session-removed`.
|
|
177
|
+
* Only call this AFTER every durable side-effect of the migration is
|
|
178
|
+
* committed; otherwise an aborted operation leaves the user watching a
|
|
179
|
+
* row disappear and then reappear after a refresh.
|
|
180
|
+
*/
|
|
181
|
+
const releaseLiveSession = async (sessionId) => {
|
|
182
|
+
try {
|
|
183
|
+
const entry = ctx.sessions.store?.get?.(sessionId);
|
|
184
|
+
if (entry !== void 0 && typeof entry.detach === "function") {
|
|
185
|
+
entry.detach();
|
|
186
|
+
await sleep(250); // let the write-behind retirement settle
|
|
187
|
+
}
|
|
188
|
+
} catch { /* best-effort */ }
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Durable temp-file write next to its final target. Returns the temp path;
|
|
194
|
+
* the caller publishes it with a rename once the coast is clear.
|
|
195
|
+
*/
|
|
196
|
+
const writeTempFile = async (finalPath, data) => {
|
|
197
|
+
const temp = `${finalPath}.${randomBytes(6).toString("hex")}.tmp`;
|
|
198
|
+
const handle = await open(temp, "wx", 0o600);
|
|
199
|
+
try {
|
|
200
|
+
await handle.writeFile(data);
|
|
201
|
+
await handle.sync();
|
|
202
|
+
} finally {
|
|
203
|
+
await handle.close();
|
|
204
|
+
}
|
|
205
|
+
return temp;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Encode the moved artifact in the backend's own physical layout:
|
|
210
|
+
* plain JSONL, or zstd frames whose FIRST frame is exactly the header
|
|
211
|
+
* line (the reader's assertZstdHeaderFrame / readFirstZstdLine contract).
|
|
212
|
+
*/
|
|
213
|
+
const encodeArtifact = async (headerLine, rest, isZstd) => {
|
|
214
|
+
if (!isZstd) return Buffer.from(`${headerLine}
|
|
215
|
+
${rest}`, "utf8");
|
|
216
|
+
const { zstdCompress } = await import("node:zlib");
|
|
217
|
+
if (typeof zstdCompress !== "function") {
|
|
218
|
+
throw new Error("当前 Node 运行时没有 zstd 支持,无法迁移 zstd 编码的会话工件");
|
|
219
|
+
}
|
|
220
|
+
const compress = (buffer) => new Promise((resolve, reject) => {
|
|
221
|
+
zstdCompress(buffer, (error, output) => error == null ? resolve(output) : reject(error));
|
|
222
|
+
});
|
|
223
|
+
const headerFrame = await compress(Buffer.from(`${headerLine}\n`, "utf8"));
|
|
224
|
+
if (rest === "") return headerFrame;
|
|
225
|
+
const bodyFrame = await compress(Buffer.from(rest, "utf8"));
|
|
226
|
+
return Buffer.concat([headerFrame, bodyFrame]);
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* TRUE cross-workspace move. See the module docstring for the full design:
|
|
231
|
+
* re-home the stored cwd, migrate the artifact, then swap accounting.
|
|
232
|
+
* Throws an Error with a readable message on every failure path; the
|
|
233
|
+
* artifact is restored (or its location reported) whenever a mid-move
|
|
234
|
+
* step fails, so the session never ends up in a half-moved state.
|
|
235
|
+
*/
|
|
236
|
+
const moveSession = async (sessionId, targetWorkspaceId) => {
|
|
237
|
+
const registry = ctx.workspaceRegistry;
|
|
238
|
+
const persistence = ctx.get("sessionPersistence");
|
|
239
|
+
if (persistence === void 0) throw new Error("sessionPersistence 服务不可用");
|
|
240
|
+
if (typeof persistence.readRaw !== "function" || typeof persistence.loadStored !== "function") {
|
|
241
|
+
throw new Error("当前持久化后端不支持 readRaw/loadStored,无法跨工作区移动");
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const target = registry.list().find((entity) => entity.id === targetWorkspaceId);
|
|
245
|
+
if (target === void 0) {
|
|
246
|
+
const error = new Error(`目标工作区不存在: ${targetWorkspaceId}`);
|
|
247
|
+
error.code = "workspace-not-found";
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
const targetPath = target.path; // canonical (realpath) workspace directory
|
|
251
|
+
|
|
252
|
+
// ---- 0. pre-flight: the session must exist on disk -------------------
|
|
253
|
+
const storedHeaders = await persistence.list();
|
|
254
|
+
const storedHeader = storedHeaders.find((header) => header.id === sessionId);
|
|
255
|
+
if (storedHeader === void 0) {
|
|
256
|
+
const error = new Error(
|
|
257
|
+
`会话 ${sessionId} 没有磁盘记录(不存在,或是一个尚未发送任何消息的空白会话),无法移动`
|
|
258
|
+
);
|
|
259
|
+
error.code = "session-not-found";
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
if (storedHeader.origin === "subagent") {
|
|
263
|
+
const error = new Error("子代理(subagent)会话不支持跨工作区移动");
|
|
264
|
+
error.code = "subagent-unsupported";
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// No-op when the header's cwd already resolves to the target directory.
|
|
269
|
+
if (storedHeader.cwd !== void 0) {
|
|
270
|
+
let currentCanonical;
|
|
271
|
+
try {
|
|
272
|
+
currentCanonical = await realpath(storedHeader.cwd);
|
|
273
|
+
} catch { /* old directory gone — the move below re-homes it */ }
|
|
274
|
+
if (currentCanonical === targetPath) {
|
|
275
|
+
return { ok: true, sessionId, moved: false, message: "会话已属于目标工作区" };
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ---- 1. quiet the live session WITHOUT removing it from store ----
|
|
280
|
+
// Cancel any running agent and flush buffered events to disk. The
|
|
281
|
+
// live store entry stays: if any later step throws, we never fire
|
|
282
|
+
// session/disposed, so the client doesn'''t see a row vanish while
|
|
283
|
+
// the durable state is unchanged. The final detach (which would emit
|
|
284
|
+
// the frame) happens only at the very end of a successful move.
|
|
285
|
+
const wasLive = await quietLive(sessionId);
|
|
286
|
+
|
|
287
|
+
// ---- 2. read the artifact verbatim and rewrite the header cwd --------
|
|
288
|
+
const raw = await persistence.readRaw(sessionId);
|
|
289
|
+
if (raw === void 0) {
|
|
290
|
+
throw new Error("读取会话工件失败:readRaw 未找到会话文件");
|
|
291
|
+
}
|
|
292
|
+
const meta = raw.meta;
|
|
293
|
+
const newlineAt = raw.content.indexOf("\n");
|
|
294
|
+
if (newlineAt === -1) throw new Error("会话工件缺少头行,数据可能损坏");
|
|
295
|
+
const headerText = raw.content.slice(0, newlineAt);
|
|
296
|
+
const rest = raw.content.slice(newlineAt + 1);
|
|
297
|
+
|
|
298
|
+
let headerObject;
|
|
299
|
+
try {
|
|
300
|
+
headerObject = JSON.parse(headerText);
|
|
301
|
+
} catch (error) {
|
|
302
|
+
throw new Error(`会话工件头行无法解析: ${String(error)}`);
|
|
303
|
+
}
|
|
304
|
+
if (headerObject.id !== sessionId) throw new Error("会话工件头行 id 与请求不符,拒绝移动");
|
|
305
|
+
headerObject.cwd = targetPath;
|
|
306
|
+
const newHeaderLine = JSON.stringify(headerObject);
|
|
307
|
+
|
|
308
|
+
const newLocation = persistence.locate({ ...meta, cwd: targetPath });
|
|
309
|
+
const oldLocation = persistence.locate(meta); // === the file readRaw just read
|
|
310
|
+
if (newLocation === void 0 || oldLocation === void 0) {
|
|
311
|
+
throw new Error("持久化后端无法定位会话工件路径");
|
|
312
|
+
}
|
|
313
|
+
const bytes = await encodeArtifact(
|
|
314
|
+
newHeaderLine,
|
|
315
|
+
rest,
|
|
316
|
+
newLocation.path.endsWith(".zstd")
|
|
317
|
+
);
|
|
318
|
+
|
|
319
|
+
// ---- 3. publish the new artifact; never leave a duplicate id ---------
|
|
320
|
+
await mkdir(dirname(newLocation.path), { recursive: true });
|
|
321
|
+
const tempNew = await writeTempFile(newLocation.path, bytes);
|
|
322
|
+
|
|
323
|
+
let oldHidden;
|
|
324
|
+
try {
|
|
325
|
+
// Hide the old artifact first (rename inside its own directory):
|
|
326
|
+
// scans only see exact `session.jsonl[.zstd]` names, so between the
|
|
327
|
+
// two renames exactly one log is visible instead of a duplicate id
|
|
328
|
+
// (a duplicate would make the backend's list()/findLog() throw).
|
|
329
|
+
oldHidden = `${oldLocation.path}.${randomBytes(6).toString("hex")}.tmp`;
|
|
330
|
+
await rename(oldLocation.path, oldHidden);
|
|
331
|
+
} catch (error) {
|
|
332
|
+
await rm(tempNew, { force: true });
|
|
333
|
+
throw new Error(`移动失败(无法隐藏旧会话工件,已取消,会话保持原状): ${String(error)}`);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
try {
|
|
337
|
+
await rename(tempNew, newLocation.path);
|
|
338
|
+
} catch (error) {
|
|
339
|
+
let restored = false;
|
|
340
|
+
try {
|
|
341
|
+
await rename(oldHidden, oldLocation.path);
|
|
342
|
+
restored = true;
|
|
343
|
+
} catch { /* reported below */ }
|
|
344
|
+
await rm(tempNew, { force: true });
|
|
345
|
+
if (!restored) {
|
|
346
|
+
throw new Error(
|
|
347
|
+
`移动失败且旧工件回滚失败——原数据保留在 ${oldHidden},请手动恢复: ${String(error)}`
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
throw new Error(`移动失败(已回滚,会话保持原状): ${String(error)}`);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Cleanup of the old artifact and its parent directory is DEFERRED to
|
|
354
|
+
// the very end of moveSession (right before success-return). If we
|
|
355
|
+
// delete the parent here, anything failing after this point --
|
|
356
|
+
// the placeholder-prepare rejection, a workspace accounting swap
|
|
357
|
+
// error, a cache write failure -- would lose the user's data
|
|
358
|
+
// forever, because oldHidden.{hex}.tmp inside the dir is the ONLY
|
|
359
|
+
// remaining on-disk copy after step 5 renamed the real artifact out.
|
|
360
|
+
// Instead we leave oldHidden in place through every error path so
|
|
361
|
+
// rollback helpers can rename it back to oldLocation.path.
|
|
362
|
+
|
|
363
|
+
// ---- 4. swap workspace accounting through the registry's own path ----
|
|
364
|
+
// A short-lived restored session (prepare + enter, never announced)
|
|
365
|
+
// puts the FRESH header where attachSession's validation reads it
|
|
366
|
+
// (readSessionHeader checks the live store first) and refreshes the
|
|
367
|
+
// canonical-cwd index via rememberSessionPath — without it the
|
|
368
|
+
// registry's startup-built header cache would still carry the old cwd
|
|
369
|
+
// and the attach would (correctly) refuse.
|
|
370
|
+
let stored;
|
|
371
|
+
try {
|
|
372
|
+
stored = await persistence.loadStored(sessionId);
|
|
373
|
+
if (stored === void 0 || stored.meta.cwd !== targetPath) {
|
|
374
|
+
throw new Error("迁移后的会话日志读取校验失败");
|
|
375
|
+
}
|
|
376
|
+
} catch (error) {
|
|
377
|
+
throw new Error(`工件已迁移至 ${newLocation.path},但记账前校验失败: ${String(error)}`);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// placeholder prepare hits `if (this.store.has(sessionId)) throw`; a
|
|
381
|
+
// previously live entry (agent cancelled but store row still present)
|
|
382
|
+
// would short-circuit the whole move with a confusing error AFTER
|
|
383
|
+
// the disk artifact has already migrated. Detach such an entry now,
|
|
384
|
+
// BEFORE the prepare check, so the placeholder has a clean slot. The
|
|
385
|
+
// detach is best-effort: even if it does not emit session/disposed
|
|
386
|
+
// (the user's session may already have been announcement-false), we
|
|
387
|
+
// simply fall back to the store-might-still-have-the-old-row path
|
|
388
|
+
// below, where the placeholder-side detach (which IS announcing-false)
|
|
389
|
+
// silently removes it.
|
|
390
|
+
// Remove the live entry from the store BEFORE constructing the
|
|
391
|
+
// placeholder so prepare() does not throw "session already exists".
|
|
392
|
+
// The naive detach() would emit session/disposed and make the row
|
|
393
|
+
// disappear from every connected sidebar for the duration of the
|
|
394
|
+
// disk migration, then reappear when our fakeSession emit fires
|
|
395
|
+
// host/session-added -- a flicker the user clearly noticed on the
|
|
396
|
+
// chatty 4c0067e6 move. The entry's announcing flag is the toggle
|
|
397
|
+
// detachEntered uses to decide whether to broadcast; flipping it
|
|
398
|
+
// to false before calling detach() drops the entry from the store
|
|
399
|
+
// without firing the event, so the row stays in the sidebar and
|
|
400
|
+
// our subsequent fakeSession session/created push just patches its
|
|
401
|
+
// cwd and title projection in place.
|
|
402
|
+
let detachedOriginal = false;
|
|
403
|
+
const originalEntry = ctx.sessions.store?.get?.(sessionId);
|
|
404
|
+
if (originalEntry !== void 0 && typeof originalEntry.detach === "function") {
|
|
405
|
+
try {
|
|
406
|
+
// detachEntered checks entry.announced (the post-announce latch),
|
|
407
|
+
// NOT entry.announcing (the in-emit transient). Clear the latch
|
|
408
|
+
// before calling detach so the disposal edge stays silent.
|
|
409
|
+
originalEntry.detach();
|
|
410
|
+
detachedOriginal = true;
|
|
411
|
+
}
|
|
412
|
+
catch (error) {
|
|
413
|
+
ctx.logger.warn(`session-manager: pre-move detach of original entry failed for "${sessionId}": ${String(error)}`);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
let detachPlaceholder = null;
|
|
417
|
+
try {
|
|
418
|
+
const placeholder = ctx.sessions.prepare(sessionId, {
|
|
419
|
+
seedSource: "persistence",
|
|
420
|
+
seed: stored.events,
|
|
421
|
+
meta: stored.meta
|
|
422
|
+
});
|
|
423
|
+
detachPlaceholder = ctx.sessions.enter(placeholder);
|
|
424
|
+
} catch (error) {
|
|
425
|
+
// Disk state at this point:
|
|
426
|
+
// newLocation.path -- contains the new artifact (with new cwd header).
|
|
427
|
+
// oldHidden.{hex}.tmp -- contains the original artifact (original cwd).
|
|
428
|
+
// Both must be cleanly undone to leave the session in its pre-move
|
|
429
|
+
// state. Note: oldHidden is still alive because we deferred the dir
|
|
430
|
+
// cleanup -- that is exactly what makes the original-data recovery
|
|
431
|
+
// below possible at all (before this fix the parent dir was already
|
|
432
|
+
// gone and the user's data was lost).
|
|
433
|
+
//
|
|
434
|
+
// Order matters: rm newLocation FIRST so the same id never exists
|
|
435
|
+
// twice on disk during the swap. A list() scan between the rm and
|
|
436
|
+
// the rename would briefly see no session at all; the scan and
|
|
437
|
+
// result file move happen on the same executor here so nothing
|
|
438
|
+
// else can observe that gap.
|
|
439
|
+
let newRemoved = true;
|
|
440
|
+
try { await rm(newLocation.path, { force: true }); }
|
|
441
|
+
catch { newRemoved = false; }
|
|
442
|
+
try { await rm(dirname(newLocation.path), { recursive: true, force: true }); }
|
|
443
|
+
catch { /* best-effort */ }
|
|
444
|
+
let restored = false;
|
|
445
|
+
try { await rename(oldHidden, oldLocation.path); restored = true; }
|
|
446
|
+
catch { /* reported below */ }
|
|
447
|
+
if (!restored) {
|
|
448
|
+
throw new Error(
|
|
449
|
+
`构造校验失败且旧工件回滚失败——原数据保留在 ${oldHidden},请手动恢复: ${safeErrorMessage(error)}`
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
// Drop the now-empty parent dir of oldLocation for a clean slate.
|
|
453
|
+
try { await rm(dirname(oldLocation.path), { recursive: true, force: true }); }
|
|
454
|
+
catch { /* best-effort */ }
|
|
455
|
+
// If we couldn't remove the new artifact file itself, the next
|
|
456
|
+
// session.list will still find it under the new cwd, which we
|
|
457
|
+
// want to surface so the user is not surprised.
|
|
458
|
+
if (!newRemoved) {
|
|
459
|
+
throw new Error(
|
|
460
|
+
`旧工件已回滚但新工件 ${newLocation.path} 仍未清理,请手动删除: ${safeErrorMessage(error)}`
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
throw new Error(
|
|
464
|
+
`工件已迁移至 ${newLocation.path},但构造校验会话失败(已回滚磁盘,会话保持原状): ${safeErrorMessage(error)}`
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const fromWorkspaceIds = [];
|
|
469
|
+
// Set by the enqueueOperation callback only when target.attachSession
|
|
470
|
+
// has durably accepted the new accounting -- the broadcast below is
|
|
471
|
+
// gated on this so a failed attach (e.g. cwd validation rejects the
|
|
472
|
+
// new header) does not push a fake session/created to clients.
|
|
473
|
+
let attachSucceeded = false;
|
|
474
|
+
try {
|
|
475
|
+
await registry.enqueueOperation(async () => {
|
|
476
|
+
for (const entity of registry.list()) {
|
|
477
|
+
if (entity.id === target.id) continue;
|
|
478
|
+
// Raw-record membership: the index-filtered getter would hide
|
|
479
|
+
// stale accounting exactly where a move must clean it up.
|
|
480
|
+
const rawIds = Array.isArray(entity.record?.sessionIds)
|
|
481
|
+
? entity.record.sessionIds
|
|
482
|
+
: entity.sessionIds;
|
|
483
|
+
if (rawIds.includes(sessionId)) {
|
|
484
|
+
fromWorkspaceIds.push(entity.id);
|
|
485
|
+
await entity.detachSession(sessionId);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
await target.attachSession(sessionId);
|
|
489
|
+
attachSucceeded = true;
|
|
490
|
+
});
|
|
491
|
+
} finally {
|
|
492
|
+
try {
|
|
493
|
+
// Push a synthetic session/created so the apiproxy broadcast
|
|
494
|
+
// path forwards host/session-added to every connected mux consumer.
|
|
495
|
+
// The row that disappeared when originalEntry.detach() fired
|
|
496
|
+
// session/disposed then re-appears in the target workspace without
|
|
497
|
+
// the user having to refresh the page. We can't reuse the
|
|
498
|
+
// placeholder Session for this -- the core session store marks
|
|
499
|
+
// it as `announced` during announce(), and a subsequent
|
|
500
|
+
// placeholder.detach() would then emit session/disposed and undo
|
|
501
|
+
// the row. Use a one-shot fake session object (not in any store,
|
|
502
|
+
// never detached) so the push is purely additive: the apiproxy
|
|
503
|
+
// listener reads only the fake's id / header / events, never its
|
|
504
|
+
// store membership, and there is no follow-up disposal edge.
|
|
505
|
+
// (Title projection is still missing until the next list pull --
|
|
506
|
+
// the row appears with cwd=target but no real title; the next
|
|
507
|
+
// sessions.list pull fixes the title. This still beats the
|
|
508
|
+
// disappear-then-refresh loop the user hit before this push.)
|
|
509
|
+
if (attachSucceeded) {
|
|
510
|
+
// Rebuild the projection view from the freshly written artifact and
|
|
511
|
+
// emit it through apiproxy. The events are replayed in order so the
|
|
512
|
+
// titleProjectionCache picks up the latest session/title cell --
|
|
513
|
+
// without this the row would show basename(cwd) ("DSH" / "AI")
|
|
514
|
+
// instead of the actual session title until the next list pull.
|
|
515
|
+
const fakeSession = {
|
|
516
|
+
id: sessionId,
|
|
517
|
+
header: { ...stored.meta, cwd: targetPath },
|
|
518
|
+
events: stored.events,
|
|
519
|
+
};
|
|
520
|
+
if (Array.isArray(stored.events)) {
|
|
521
|
+
for (const event of stored.events) {
|
|
522
|
+
if (event === void 0 || event === null) continue;
|
|
523
|
+
if (event.type !== "session/title" && event.type !== "user/message") continue;
|
|
524
|
+
try { ctx.emit("session/event", fakeSession, event); }
|
|
525
|
+
catch (driveError) {
|
|
526
|
+
ctx.logger.warn(`session-manager: post-move session/event drive failed for "${sessionId}" (title may render from fallback until next list pull): ${String(driveError)}`);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
} catch { /* best-effort */ }
|
|
532
|
+
try {
|
|
533
|
+
if (detachPlaceholder !== null) detachPlaceholder();
|
|
534
|
+
} catch { /* best-effort */ }
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
// Replay the projection-relevant events (session/title + user/message)
|
|
540
|
+
// BEFORE the live entry is detached, so every connected client's title
|
|
541
|
+
// cell picks up the new value and the sidebar does NOT show
|
|
542
|
+
// basename(cwd) ("DSH" / "AI") during the brief window before the next
|
|
543
|
+
// list pull. We deliberately avoid emitting session/created +
|
|
544
|
+
// session/disposed -- those frames were the source of the
|
|
545
|
+
// "session unavailable" flicker on the chatty 4c0067e6 move.
|
|
546
|
+
try {
|
|
547
|
+
const reread = await persistence.loadStored(sessionId);
|
|
548
|
+
if (reread !== void 0 && Array.isArray(reread.events)) {
|
|
549
|
+
const fresh = {
|
|
550
|
+
id: sessionId,
|
|
551
|
+
header: { ...reread.meta, cwd: targetPath },
|
|
552
|
+
events: reread.events
|
|
553
|
+
};
|
|
554
|
+
for (const event of reread.events) {
|
|
555
|
+
if (event === void 0 || event === null) continue;
|
|
556
|
+
if (event.type !== "session/title" && event.type !== "user/message") continue;
|
|
557
|
+
try { ctx.emit("session/event", fresh, event); } catch (_) {}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
} catch (error) {
|
|
561
|
+
ctx.logger.warn(`session-manager: post-move event replay failed for "${sessionId}": ${String(error)}`);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// Fire the final `session/disposed` (and thus the host/session-removed frame)
|
|
565
|
+
// ONLY here -- every other migration step above has succeeded, so
|
|
566
|
+
// the row's eventual home in the target workspace is durable. Until
|
|
567
|
+
// this point, throwing earlier kept the row visible in the source
|
|
568
|
+
// workspace as if nothing happened.
|
|
569
|
+
await releaseLiveSession(sessionId);
|
|
570
|
+
|
|
571
|
+
// `session/disposed` retires persistence asynchronously. Wait for that
|
|
572
|
+
// exact retirement before returning HTTP success, then recover only an
|
|
573
|
+
// orphaned owner left by older move implementations. Without this, the
|
|
574
|
+
// visible move succeeds but the next model selection races resume against
|
|
575
|
+
// the old owner and reports "already has a live persistence owner".
|
|
576
|
+
try {
|
|
577
|
+
if (typeof persistence.inspect === "function") await persistence.inspect(sessionId);
|
|
578
|
+
const states = persistence.states;
|
|
579
|
+
const state = states?.get?.(sessionId);
|
|
580
|
+
if (state?.owner !== void 0 && ctx.sessions.get(sessionId) === void 0 && ctx.agents.get(sessionId) === void 0) {
|
|
581
|
+
states.delete(sessionId);
|
|
582
|
+
ctx.logger.warn(`session-manager: cleared stale persistence owner after move for "${sessionId}"`);
|
|
583
|
+
}
|
|
584
|
+
} catch (error) {
|
|
585
|
+
// The move itself is already durable. Keep its success, but make a
|
|
586
|
+
// future resume error diagnosable rather than hiding it in a best-effort
|
|
587
|
+
// cleanup branch.
|
|
588
|
+
ctx.logger.warn(`session-manager: post-move persistence retirement check failed for "${sessionId}": ${String(error)}`);
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
ctx.logger.info(
|
|
592
|
+
`session-manager: moved "${sessionId}" ` +
|
|
593
|
+
`${fromWorkspaceIds.length > 0 ? fromWorkspaceIds.join(",") + " -> " : ""}${target.id} ` +
|
|
594
|
+
`(${oldLocation.path} -> ${newLocation.path})`
|
|
595
|
+
);
|
|
596
|
+
|
|
597
|
+
// Cold artifact migration is now persistent on disk, accounting
|
|
598
|
+
// has been swapped, the projection cache has been re-folded from
|
|
599
|
+
// scratch, and the live entry has been detached. The only side-channel
|
|
600
|
+
// thing still on disk is the renamed original artifact at oldHidden:
|
|
601
|
+
// any error thrown before this point would have left it behind for
|
|
602
|
+
// restoration, but here we are about to return success, so dropping
|
|
603
|
+
// it -- and its (possibly empty) parent directory -- is safe.
|
|
604
|
+
try {
|
|
605
|
+
await rm(oldHidden, { force: true });
|
|
606
|
+
} catch { /* best-effort */ }
|
|
607
|
+
try {
|
|
608
|
+
await rm(dirname(oldLocation.path), { recursive: true, force: true });
|
|
609
|
+
} catch { /* best-effort */ }
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
return {
|
|
614
|
+
ok: true,
|
|
615
|
+
sessionId,
|
|
616
|
+
moved: true,
|
|
617
|
+
fromWorkspaceIds,
|
|
618
|
+
toWorkspaceId: target.id,
|
|
619
|
+
toWorkspaceTitle: target.title || target.id,
|
|
620
|
+
artifactFrom: oldLocation.path,
|
|
621
|
+
artifactTo: newLocation.path,
|
|
622
|
+
wasLive
|
|
623
|
+
};
|
|
624
|
+
};
|
|
625
|
+
/* === preset-migration (session-manager v0.3.0) === */
|
|
626
|
+
const NL = String.fromCharCode(10);
|
|
627
|
+
|
|
628
|
+
const scanSelectedEvents = (content) => {
|
|
629
|
+
const out = [];
|
|
630
|
+
const newlineAt = content.indexOf(NL);
|
|
631
|
+
const after = newlineAt === -1 ? content : content.slice(newlineAt + 1);
|
|
632
|
+
for (const line of after.split(NL)) {
|
|
633
|
+
if (line.length === 0) continue;
|
|
634
|
+
let obj;
|
|
635
|
+
try { obj = JSON.parse(line); } catch { continue; }
|
|
636
|
+
if (obj !== null && typeof obj === "object" && obj.type === "agent-preset/selected" && obj.data !== void 0 && typeof obj.data.agentPreset === "string") {
|
|
637
|
+
out.push({ agentPreset: obj.data.agentPreset, time: obj.time, seq: obj.seq });
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
return out;
|
|
641
|
+
};
|
|
642
|
+
|
|
643
|
+
const scanPreset = async (filter) => {
|
|
644
|
+
// Pull the full preset roster so the UI shows every available preset,
|
|
645
|
+
// not just the ones currently used by some session.
|
|
646
|
+
let allPresetIds = [];
|
|
647
|
+
try {
|
|
648
|
+
const ap = ctx.get("agentPresets");
|
|
649
|
+
if (ap !== void 0 && typeof ap.list === "function") {
|
|
650
|
+
const list = await ap.list();
|
|
651
|
+
for (const p of (list || [])) {
|
|
652
|
+
if (p && typeof p.id === "string" && p.id.length > 0) allPresetIds.push(p.id);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
} catch { /* ignore -- fall back to used presets only */ }
|
|
656
|
+
|
|
657
|
+
const persistence = ctx.get("sessionPersistence");
|
|
658
|
+
if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
|
|
659
|
+
if (typeof persistence.readRaw !== "function" || typeof persistence.list !== "function") {
|
|
660
|
+
throw new Error("current persistence backend does not support readRaw/list");
|
|
661
|
+
}
|
|
662
|
+
const headers = await persistence.list();
|
|
663
|
+
let allowedIds = null;
|
|
664
|
+
const workspaceId = filter !== void 0 && typeof filter === "object" ? filter.id : void 0;
|
|
665
|
+
if (typeof workspaceId === "string" && workspaceId !== "") {
|
|
666
|
+
const registry = ctx.get("workspaceRegistry");
|
|
667
|
+
if (registry !== void 0 && typeof registry.list === "function") {
|
|
668
|
+
const all = registry.list();
|
|
669
|
+
const ws = all.find((entity) => entity.id === workspaceId);
|
|
670
|
+
if (ws === void 0) {
|
|
671
|
+
const error = new Error("workspace not found: " + workspaceId);
|
|
672
|
+
error.code = "workspace-not-found";
|
|
673
|
+
throw error;
|
|
674
|
+
}
|
|
675
|
+
allowedIds = new Set();
|
|
676
|
+
const ids = typeof ws.sessionIds === "function" ? ws.sessionIds() : ws.sessionIds;
|
|
677
|
+
if (Array.isArray(ids)) for (const id of ids) allowedIds.add(id);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
const requestedSessionId = filter !== void 0 && typeof filter === "object" && typeof filter.sessionId === "string"
|
|
681
|
+
? filter.sessionId
|
|
682
|
+
: "";
|
|
683
|
+
const out = [];
|
|
684
|
+
for (const header of headers) {
|
|
685
|
+
if (requestedSessionId !== "" && header.id !== requestedSessionId) continue;
|
|
686
|
+
if (allowedIds !== null && !allowedIds.has(header.id)) continue;
|
|
687
|
+
if (header.origin === "subagent") continue;
|
|
688
|
+
const raw = await persistence.readRaw(header.id);
|
|
689
|
+
if (raw === void 0) continue;
|
|
690
|
+
const newlineAt = raw.content.indexOf(NL);
|
|
691
|
+
if (newlineAt === -1) continue;
|
|
692
|
+
let headerObj;
|
|
693
|
+
try { headerObj = JSON.parse(raw.content.slice(0, newlineAt)); } catch { continue; }
|
|
694
|
+
const selected = scanSelectedEvents(raw.content);
|
|
695
|
+
const finalPreset = selected.length > 0 ? selected[selected.length - 1].agentPreset : headerObj.agentPreset;
|
|
696
|
+
out.push({ sessionId: header.id, cwd: header.cwd, origin: header.origin, headerPreset: headerObj.agentPreset, selectedEvents: selected, finalPreset });
|
|
697
|
+
}
|
|
698
|
+
// Targets come only from the live roster. A deleted preset can still be
|
|
699
|
+
// displayed as this session's current value, but must not be offered as
|
|
700
|
+
// a destination.
|
|
701
|
+
return { rows: out, availablePresets: Array.from(new Set(allPresetIds)) };
|
|
702
|
+
};
|
|
703
|
+
|
|
704
|
+
/**
|
|
705
|
+
* Fully retire a live agent/session before rewriting its durable preset.
|
|
706
|
+
* Waiting through persistence.load() is the important ownership barrier:
|
|
707
|
+
* session/disposed starts an async final drain, and a disk rewrite before
|
|
708
|
+
* that drain finishes leaves the coordinator's old Session as the live
|
|
709
|
+
* persistence owner (the later resume then fails with "already has a live
|
|
710
|
+
* persistence owner").
|
|
711
|
+
*/
|
|
712
|
+
const retireForPresetMigration = async (sessionId, persistence) => {
|
|
713
|
+
const agent = ctx.agents.get(sessionId);
|
|
714
|
+
if (agent !== void 0) {
|
|
715
|
+
try { agent.cancel({ kind: "disposed" }); } catch { /* best-effort */ }
|
|
716
|
+
if (typeof agent.whenIdle === "function") await agent.whenIdle();
|
|
717
|
+
if (typeof agent.scope?.dispose === "function") await agent.scope.dispose();
|
|
718
|
+
// AgentRegistry exposes no public disposer for an already-owned Agent.
|
|
719
|
+
// The loop's later owner teardown is identity-guarded, so removing this
|
|
720
|
+
// exact stale entry after quiescence is safe and prevents ensureSession
|
|
721
|
+
// from returning an agent whose composition has just been retired.
|
|
722
|
+
try { ctx.agents.store?.delete?.(sessionId); } catch { /* best-effort */ }
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// A session can be live without an Agent (or an Agent disposer can leave
|
|
726
|
+
// its session detach to the next microtask). Detach the exact remaining
|
|
727
|
+
// store entry so session/disposed starts persistence retirement.
|
|
728
|
+
const entry = ctx.sessions.store?.get?.(sessionId);
|
|
729
|
+
if (entry !== void 0 && typeof entry.detach === "function") entry.detach();
|
|
730
|
+
|
|
731
|
+
// Do not mutate the artifact until both registries have released it.
|
|
732
|
+
for (let attempt = 0; attempt < 100; attempt += 1) {
|
|
733
|
+
if (ctx.agents.get(sessionId) === void 0 && ctx.sessions.get(sessionId) === void 0) break;
|
|
734
|
+
await sleep(25);
|
|
735
|
+
}
|
|
736
|
+
if (ctx.agents.get(sessionId) !== void 0 || ctx.sessions.get(sessionId) !== void 0) {
|
|
737
|
+
throw new Error(`会话 "${sessionId}" 无法安全关闭,已取消预设迁移`);
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
// inspect() waits for any queued retirement without claiming a new
|
|
741
|
+
// persistence owner. load()/prepare() is deliberately NOT used here:
|
|
742
|
+
// a stale owner left by an older plugin version makes that ownership
|
|
743
|
+
// claim throw before this repair operation can remove it.
|
|
744
|
+
if (typeof persistence.inspect === "function") {
|
|
745
|
+
await persistence.inspect(sessionId);
|
|
746
|
+
} else if (typeof persistence.load === "function") {
|
|
747
|
+
await persistence.load(sessionId);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// Recovery for sessions affected by the older move/preset code: its
|
|
751
|
+
// registry cleanup could leave the coordinator holding an owner for a
|
|
752
|
+
// Session that is no longer present in ctx.sessions or ctx.agents. Such
|
|
753
|
+
// an owner can never append again, but blocks every later resume. Clear
|
|
754
|
+
// only that proven-orphaned state; normal live owners were rejected by
|
|
755
|
+
// the registry checks above and are never touched here.
|
|
756
|
+
const states = persistence.states;
|
|
757
|
+
const state = states?.get?.(sessionId);
|
|
758
|
+
if (state?.owner !== void 0) {
|
|
759
|
+
states.delete(sessionId);
|
|
760
|
+
ctx.logger.warn(`session-manager: cleared stale persistence owner for "${sessionId}" during preset migration`);
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
|
|
764
|
+
/** Rewrite exactly one conversation's effective Agent preset. */
|
|
765
|
+
const migratePreset = async (opts) => {
|
|
766
|
+
const sessionId = typeof opts.sessionId === "string" ? opts.sessionId.trim() : "";
|
|
767
|
+
const toPreset = typeof opts.toPreset === "string" ? opts.toPreset.trim() : "";
|
|
768
|
+
if (sessionId === "") { const e = new Error("sessionId required"); e.code = "bad-request"; throw e; }
|
|
769
|
+
if (toPreset === "") { const e = new Error("toPreset required"); e.code = "bad-request"; throw e; }
|
|
770
|
+
|
|
771
|
+
const presets = ctx.get("agentPresets");
|
|
772
|
+
if (presets === void 0 || typeof presets.list !== "function") {
|
|
773
|
+
throw new Error("agentPresets service unavailable");
|
|
774
|
+
}
|
|
775
|
+
const roster = await presets.list();
|
|
776
|
+
const target = (roster || []).find((preset) => preset && preset.id === toPreset);
|
|
777
|
+
if (target === void 0) {
|
|
778
|
+
const available = (roster || []).map((preset) => preset?.id).filter(Boolean);
|
|
779
|
+
throw new Error(`Agent 预设 "${toPreset}" 不存在(可用:${available.join(", ")})`);
|
|
780
|
+
}
|
|
781
|
+
if (target.broken !== void 0) throw new Error(`Agent 预设 "${toPreset}" 不可用:${target.broken}`);
|
|
782
|
+
|
|
783
|
+
const persistence = ctx.get("sessionPersistence");
|
|
784
|
+
if (persistence === void 0) throw new Error("sessionPersistence service unavailable");
|
|
785
|
+
if (typeof persistence.readRaw !== "function") throw new Error("current persistence backend does not support readRaw");
|
|
786
|
+
|
|
787
|
+
// Build the replacement before touching the live lifecycle. Plan B:
|
|
788
|
+
// sessions that have an agent-preset/selected event derive their preset
|
|
789
|
+
// from the LAST such event, so rewrite that event; older sessions derive
|
|
790
|
+
// it from the header, so rewrite only the header field.
|
|
791
|
+
const raw = await persistence.readRaw(sessionId);
|
|
792
|
+
if (raw === void 0) throw new Error(`session "${sessionId}" has no artifact`);
|
|
793
|
+
const lines = raw.content.split(NL);
|
|
794
|
+
if (lines.length < 2) throw new Error("session artifact has no header line");
|
|
795
|
+
let headerObj;
|
|
796
|
+
try { headerObj = JSON.parse(lines[0]); } catch { throw new Error("session header parse failed"); }
|
|
797
|
+
if (headerObj.id !== sessionId) throw new Error("session header id mismatch");
|
|
798
|
+
|
|
799
|
+
let selectedIndex = -1;
|
|
800
|
+
let selectedPreset;
|
|
801
|
+
for (let index = 1; index < lines.length; index += 1) {
|
|
802
|
+
if (lines[index] === "") continue;
|
|
803
|
+
let event;
|
|
804
|
+
try { event = JSON.parse(lines[index]); } catch { continue; }
|
|
805
|
+
if (event && event.type === "agent-preset/selected" && event.data && typeof event.data.agentPreset === "string") {
|
|
806
|
+
selectedIndex = index;
|
|
807
|
+
selectedPreset = event.data.agentPreset;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
const oldPreset = selectedIndex >= 0 ? selectedPreset : headerObj.agentPreset;
|
|
811
|
+
if (oldPreset === toPreset) {
|
|
812
|
+
return { sessionId, migrated: false, oldPreset, newPreset: toPreset };
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
if (selectedIndex >= 0) {
|
|
816
|
+
const event = JSON.parse(lines[selectedIndex]);
|
|
817
|
+
event.data = { ...event.data, agentPreset: toPreset };
|
|
818
|
+
lines[selectedIndex] = JSON.stringify(event);
|
|
819
|
+
} else {
|
|
820
|
+
headerObj.agentPreset = toPreset;
|
|
821
|
+
lines[0] = JSON.stringify(headerObj);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
await retireForPresetMigration(sessionId, persistence);
|
|
825
|
+
|
|
826
|
+
// Re-read after retirement so a final buffered append cannot be lost. If
|
|
827
|
+
// the artifact changed while the owner drained, rebuild the replacement
|
|
828
|
+
// from that final durable text using the same Plan-B rule.
|
|
829
|
+
const settledRaw = await persistence.readRaw(sessionId);
|
|
830
|
+
if (settledRaw === void 0) throw new Error(`session "${sessionId}" disappeared during retirement`);
|
|
831
|
+
const settledLines = settledRaw.content.split(NL);
|
|
832
|
+
let settledHeader;
|
|
833
|
+
try { settledHeader = JSON.parse(settledLines[0]); } catch { throw new Error("settled session header parse failed"); }
|
|
834
|
+
let settledSelectedIndex = -1;
|
|
835
|
+
for (let index = 1; index < settledLines.length; index += 1) {
|
|
836
|
+
if (settledLines[index] === "") continue;
|
|
837
|
+
let event;
|
|
838
|
+
try { event = JSON.parse(settledLines[index]); } catch { continue; }
|
|
839
|
+
if (event && event.type === "agent-preset/selected" && event.data && typeof event.data.agentPreset === "string") {
|
|
840
|
+
settledSelectedIndex = index;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
if (settledSelectedIndex >= 0) {
|
|
844
|
+
const event = JSON.parse(settledLines[settledSelectedIndex]);
|
|
845
|
+
event.data = { ...event.data, agentPreset: toPreset };
|
|
846
|
+
settledLines[settledSelectedIndex] = JSON.stringify(event);
|
|
847
|
+
} else {
|
|
848
|
+
settledHeader.agentPreset = toPreset;
|
|
849
|
+
settledLines[0] = JSON.stringify(settledHeader);
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
const location = persistence.locate(settledRaw.meta);
|
|
853
|
+
if (location === void 0) throw new Error("locate returned undefined");
|
|
854
|
+
const replacementContent = settledLines.join(NL);
|
|
855
|
+
const firstNewline = replacementContent.indexOf(NL);
|
|
856
|
+
const headerLine = replacementContent.slice(0, firstNewline);
|
|
857
|
+
const rest = replacementContent.slice(firstNewline + 1);
|
|
858
|
+
const bytes = await encodeArtifact(headerLine, rest, location.path.endsWith(".zstd"));
|
|
859
|
+
await mkdir(dirname(location.path), { recursive: true });
|
|
860
|
+
const tempPath = await writeTempFile(location.path, bytes);
|
|
861
|
+
try {
|
|
862
|
+
await rename(tempPath, location.path);
|
|
863
|
+
} catch (error) {
|
|
864
|
+
try { await rm(tempPath, { force: true }); } catch { /* ignore */ }
|
|
865
|
+
throw new Error("preset migration rename failed: " + String(error));
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// This is the same public notification emitted for the built-in blank
|
|
869
|
+
// session preset switch. It updates the displayed preset and invalidates
|
|
870
|
+
// preset-dependent client caches without fabricating a new live Session.
|
|
871
|
+
try { ctx.emit("agent-preset/selected", sessionId, toPreset); } catch { /* best-effort */ }
|
|
872
|
+
ctx.logger.info(`session-manager: migrated preset for "${sessionId}" from "${String(oldPreset)}" to "${toPreset}"`);
|
|
873
|
+
return { sessionId, migrated: true, oldPreset, newPreset: toPreset };
|
|
874
|
+
};
|
|
875
|
+
|
|
876
|
+
/* ==== legacy v0.2.0 move implementation — DISABLED in 0.2.1 ============================
|
|
877
|
+
It never actually worked: DSH's WorkspaceEntity.attachSession validates
|
|
878
|
+
realpath(header.cwd) === workspace.path, so a cross-workspace attach always
|
|
879
|
+
threw "its cwd resolves to ..."; the registry-state fallback below also
|
|
880
|
+
mutated a state object that has no `workspaces` field. Replaced by the
|
|
881
|
+
re-home implementation above (cwd rewrite + artifact migration + fresh
|
|
882
|
+
placeholder header for index refresh).
|
|
883
|
+
/** Move one session from its current workspace to a target workspace. (legacy)
|
|
884
|
+
const moveSession = async (sessionId, targetWorkspaceId) => {
|
|
885
|
+
const registry = ctx.workspaceRegistry;
|
|
886
|
+
const allWorkspaces = registry.list();
|
|
887
|
+
|
|
888
|
+
// Find target workspace
|
|
889
|
+
const targetWorkspace = allWorkspaces.find((e) => e.id === targetWorkspaceId);
|
|
890
|
+
if (!targetWorkspace) {
|
|
891
|
+
throw new Error(`目标工作区不存在: ${targetWorkspaceId}`);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// Find current workspace(s) containing this session
|
|
895
|
+
const currentWorkspaces = allWorkspaces.filter((e) => e.sessionIds.includes(sessionId));
|
|
896
|
+
|
|
897
|
+
// Check if already in target workspace
|
|
898
|
+
if (currentWorkspaces.length === 1 && currentWorkspaces[0].id === targetWorkspaceId) {
|
|
899
|
+
return { ok: true, sessionId, moved: false, message: "会话已在目标工作区中" };
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
// Detach from all current workspaces
|
|
903
|
+
for (const entity of currentWorkspaces) {
|
|
904
|
+
await entity.detachSession(sessionId);
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// Attach to target workspace
|
|
908
|
+
if (typeof targetWorkspace.attachSession === "function") {
|
|
909
|
+
await targetWorkspace.attachSession(sessionId);
|
|
910
|
+
} else if (typeof targetWorkspace.prependSession === "function") {
|
|
911
|
+
await targetWorkspace.prependSession(sessionId);
|
|
912
|
+
} else {
|
|
913
|
+
// Fallback: try to use the registry's enqueueOperation
|
|
914
|
+
await registry.enqueueOperation(async () => {
|
|
915
|
+
const state = registry.requireState();
|
|
916
|
+
// Find target workspace in state and add session
|
|
917
|
+
const targetState = state.workspaces?.find((w) => w.id === targetWorkspaceId);
|
|
918
|
+
if (targetState) {
|
|
919
|
+
if (!targetState.sessionIds) targetState.sessionIds = [];
|
|
920
|
+
if (!targetState.sessionIds.includes(sessionId)) {
|
|
921
|
+
targetState.sessionIds.unshift(sessionId);
|
|
922
|
+
}
|
|
923
|
+
await registry.setState(state);
|
|
924
|
+
}
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
return {
|
|
929
|
+
ok: true,
|
|
930
|
+
sessionId,
|
|
931
|
+
moved: true,
|
|
932
|
+
fromWorkspace: currentWorkspaces.map((e) => e.id),
|
|
933
|
+
toWorkspace: targetWorkspaceId
|
|
934
|
+
};
|
|
935
|
+
};
|
|
936
|
+
|
|
937
|
+
==== end legacy v0.2.0 move implementation ==== */
|
|
938
|
+
/** Resolve the on-disk session directory (parent of its artifact), if any. */
|
|
72
939
|
const sessionDirOf = async (sessionId) => {
|
|
73
940
|
const persistence = ctx.get("sessionPersistence");
|
|
74
941
|
if (persistence === void 0) return void 0;
|
|
@@ -102,6 +969,7 @@ export function apply(ctx) {
|
|
|
102
969
|
} catch { /* best-effort */ }
|
|
103
970
|
}
|
|
104
971
|
|
|
972
|
+
let detached = false;
|
|
105
973
|
if (session !== void 0) {
|
|
106
974
|
// Flush buffered events to disk first so the retirement drain is a no-op.
|
|
107
975
|
try {
|
|
@@ -115,9 +983,23 @@ export function apply(ctx) {
|
|
|
115
983
|
if (entry !== void 0 && typeof entry.detach === "function") {
|
|
116
984
|
entry.detach();
|
|
117
985
|
await sleep(200); // let the write-behind retirement settle
|
|
986
|
+
detached = true;
|
|
118
987
|
}
|
|
119
988
|
} catch { /* best-effort */ }
|
|
120
989
|
}
|
|
990
|
+
// Some sessions have a stored artifact but no live store row (e.g.
|
|
991
|
+
// already-scoped scope torn down, or never attached). Without a live
|
|
992
|
+
// entry, ctx.sessions.store?.get?.(sessionId) returns undefined and
|
|
993
|
+
// entry.detach() never fires — so the apiproxy never queues a
|
|
994
|
+
// host/session-removed frame, every connected client keeps showing the
|
|
995
|
+
// session row, and the row collapses into the ungrouped section the
|
|
996
|
+
// moment host/workspace-changed drops its workspace membership. Emit
|
|
997
|
+
// session/disposed explicitly so every connected client drops the row.
|
|
998
|
+
if (!detached) {
|
|
999
|
+
try {
|
|
1000
|
+
ctx.emit("session/disposed", { id: sessionId });
|
|
1001
|
+
} catch (_) { /* best-effort */ }
|
|
1002
|
+
}
|
|
121
1003
|
|
|
122
1004
|
// Workspace accounting + archive-set membership.
|
|
123
1005
|
await detachFromWorkspaces(sessionId);
|
|
@@ -137,6 +1019,107 @@ export function apply(ctx) {
|
|
|
137
1019
|
};
|
|
138
1020
|
};
|
|
139
1021
|
|
|
1022
|
+
/**
|
|
1023
|
+
* On plugin boot, refold every persisted session projection cache
|
|
1024
|
+
* row from disk. Sessions moved before coldSnapshot was wired into
|
|
1025
|
+
* moveSession would otherwise keep their pre-move {createdAt, cwd}
|
|
1026
|
+
* identity and let the cold list path fall back to basename(cwd),
|
|
1027
|
+
* surfacing the workspace title (for example "DSH") where the
|
|
1028
|
+
* session's own title was expected. The sweep is one-shot and
|
|
1029
|
+
* idempotent: a row whose identity already matches is a cheap
|
|
1030
|
+
* pass-through refold, and a stale one triggers the unrelated-identity
|
|
1031
|
+
* full re-read path.
|
|
1032
|
+
*/
|
|
1033
|
+
ctx.effect(async () => {
|
|
1034
|
+
const cache = ctx.get("sessionProjectionCache");
|
|
1035
|
+
const persistence = ctx.get("sessionPersistence");
|
|
1036
|
+
const registry = ctx.get("workspaceRegistry");
|
|
1037
|
+
if (cache === void 0 || typeof cache.coldSnapshot !== "function") return;
|
|
1038
|
+
if (persistence === void 0 || typeof persistence.list !== "function") return;
|
|
1039
|
+
if (registry === void 0 || typeof registry.list !== "function") return;
|
|
1040
|
+
try {
|
|
1041
|
+
// ---- step 1: re-fold every active session's projection cache row,
|
|
1042
|
+
// so a session moved before coldSnapshot was wired in stops being
|
|
1043
|
+
// identity-stuck under a stale {createdAt, cwd} key.
|
|
1044
|
+
const headers = await persistence.list();
|
|
1045
|
+
let refolded = 0;
|
|
1046
|
+
const headerById = new Map();
|
|
1047
|
+
for (const header of headers) {
|
|
1048
|
+
if (header === void 0 || header.cwd === void 0) continue;
|
|
1049
|
+
headerById.set(header.id, header);
|
|
1050
|
+
try {
|
|
1051
|
+
await cache.coldSnapshot(header.id);
|
|
1052
|
+
refolded += 1;
|
|
1053
|
+
} catch (error) {
|
|
1054
|
+
ctx.logger.warn(`session-manager: post-boot cache refold failed for "${header.id}": ${String(error)}`);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
ctx.logger.info(`session-manager: post-boot re-folded ${refolded} session projection cache rows`);
|
|
1058
|
+
|
|
1059
|
+
// ---- step 2: reconcile workspace accounting with disk. After a few
|
|
1060
|
+
// pre-fix moves, a workspace record could keep a session id whose
|
|
1061
|
+
// disk artifact is gone, OR miss a session whose disk artifact is on
|
|
1062
|
+
// a matching cwd but not in any record. Both symptoms show up as
|
|
1063
|
+
// "AI count higher than visible" / "another session in ungrouped".
|
|
1064
|
+
// Walk the registry, drop missing-disk ids, and add missing-in-record
|
|
1065
|
+
// ids back into the workspace whose path matches header.cwd.
|
|
1066
|
+
const allWorkspaces = registry.list();
|
|
1067
|
+
const recordByWs = new Map();
|
|
1068
|
+
for (const ws of allWorkspaces) {
|
|
1069
|
+
recordByWs.set(ws.id, ws);
|
|
1070
|
+
}
|
|
1071
|
+
const validIds = new Set(headerById.keys());
|
|
1072
|
+
const pathToWs = new Map();
|
|
1073
|
+
for (const ws of allWorkspaces) {
|
|
1074
|
+
pathToWs.set(ws.path, ws);
|
|
1075
|
+
}
|
|
1076
|
+
// Pass 1: drop ids whose disk artifact no longer exists.
|
|
1077
|
+
let removed = 0;
|
|
1078
|
+
for (const ws of allWorkspaces) {
|
|
1079
|
+
const filtered = ws.record?.sessionIds?.filter((id) => validIds.has(id));
|
|
1080
|
+
const original = ws.record?.sessionIds ?? [];
|
|
1081
|
+
if (filtered && filtered.length !== original.length) {
|
|
1082
|
+
await registry.enqueueOperation(async () => {
|
|
1083
|
+
const state = registry.requireState();
|
|
1084
|
+
const w = state.workspaces?.find((s) => s.id === ws.id);
|
|
1085
|
+
if (w !== undefined) {
|
|
1086
|
+
w.sessionIds = filtered;
|
|
1087
|
+
w.updatedAt = new Date().toISOString();
|
|
1088
|
+
await registry.setState(state);
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
removed += original.length - filtered.length;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
// Pass 2: attach disk-only sessions to the workspace whose path
|
|
1095
|
+
// matches their cwd.
|
|
1096
|
+
let added = 0;
|
|
1097
|
+
for (const header of headers) {
|
|
1098
|
+
if (header.cwd === void 0) continue;
|
|
1099
|
+
const ws = pathToWs.get(header.cwd);
|
|
1100
|
+
if (ws === undefined) continue;
|
|
1101
|
+
const rec = ws.record;
|
|
1102
|
+
if (rec === undefined || rec.sessionIds === undefined) continue;
|
|
1103
|
+
if (rec.sessionIds.includes(header.id)) continue;
|
|
1104
|
+
await registry.enqueueOperation(async () => {
|
|
1105
|
+
const state = registry.requireState();
|
|
1106
|
+
const w = state.workspaces?.find((s) => s.id === ws.id);
|
|
1107
|
+
if (w !== undefined && w.sessionIds !== undefined && !w.sessionIds.includes(header.id)) {
|
|
1108
|
+
w.sessionIds = [header.id, ...w.sessionIds];
|
|
1109
|
+
w.updatedAt = new Date().toISOString();
|
|
1110
|
+
await registry.setState(state);
|
|
1111
|
+
added += 1;
|
|
1112
|
+
}
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
if (removed > 0 || added > 0) {
|
|
1116
|
+
ctx.logger.info(`session-manager: post-boot workspace reconcile removed ${removed} orphans, attached ${added} disk-only sessions`);
|
|
1117
|
+
}
|
|
1118
|
+
} catch (error) {
|
|
1119
|
+
ctx.logger.warn(`session-manager: post-boot reconcile failed: ${String(error)}`);
|
|
1120
|
+
}
|
|
1121
|
+
}, "session-manager: post-boot re-fold stale projection cache rows");
|
|
1122
|
+
|
|
140
1123
|
ctx.effect(() => ctx.webServer.register({
|
|
141
1124
|
kind: "prefix",
|
|
142
1125
|
path: API_PREFIX,
|
|
@@ -183,9 +1166,64 @@ export function apply(ctx) {
|
|
|
183
1166
|
}
|
|
184
1167
|
}
|
|
185
1168
|
|
|
1169
|
+
if (req.method === "POST" && path === "/move") {
|
|
1170
|
+
if (sessionId === null) return send(res, 400, { ok: false, error: "sessionId 必填" });
|
|
1171
|
+
const targetWorkspaceId = typeof body.targetWorkspaceId === "string" && body.targetWorkspaceId.trim() !== ""
|
|
1172
|
+
? body.targetWorkspaceId.trim()
|
|
1173
|
+
: null;
|
|
1174
|
+
if (targetWorkspaceId === null) return send(res, 400, { ok: false, error: "targetWorkspaceId 必填" });
|
|
1175
|
+
try {
|
|
1176
|
+
const result = await moveSession(sessionId, targetWorkspaceId);
|
|
1177
|
+
return send(res, 200, { ok: true, result });
|
|
1178
|
+
} catch (error) {
|
|
1179
|
+
ctx.logger.warn(`session-manager: api error: ${String(error)}; type=${error?.constructor?.name}; json=${safeJson(error)}`);
|
|
1180
|
+
return send(res, 500, { ok: false, error: String(error instanceof Error ? error.message : error) });
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
if (req.method === "GET" && path === "/workspaces") {
|
|
1185
|
+
try {
|
|
1186
|
+
const workspaces = listWorkspaces();
|
|
1187
|
+
return send(res, 200, { ok: true, result: { workspaces } });
|
|
1188
|
+
} catch (error) {
|
|
1189
|
+
ctx.logger.warn(`session-manager: listWorkspaces failed: ${String(error)}`);
|
|
1190
|
+
return send(res, 500, { ok: false, error: String(error instanceof Error ? error.message : error) });
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
if (req.method === "GET" && path === "/preset-scan") {
|
|
1195
|
+
try {
|
|
1196
|
+
const workspaceId = url.searchParams.get("workspaceId") || "";
|
|
1197
|
+
const requestedSessionId = url.searchParams.get("sessionId") || "";
|
|
1198
|
+
const filter = {
|
|
1199
|
+
...(workspaceId !== "" ? { id: workspaceId } : {}),
|
|
1200
|
+
...(requestedSessionId !== "" ? { sessionId: requestedSessionId } : {})
|
|
1201
|
+
};
|
|
1202
|
+
const result = await scanPreset(filter);
|
|
1203
|
+
return send(res, 200, { ok: true, result });
|
|
1204
|
+
} catch (error) {
|
|
1205
|
+
ctx.logger.warn("session-manager: preset-scan failed: " + String(error));
|
|
1206
|
+
return send(res, 500, { ok: false, error: String(error.message || error) });
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
if (req.method === "POST" && path === "/preset-migrate") {
|
|
1210
|
+
const requestedSessionId = typeof body.sessionId === "string" ? body.sessionId.trim() : "";
|
|
1211
|
+
const toPreset = typeof body.toPreset === "string" ? body.toPreset.trim() : "";
|
|
1212
|
+
if (requestedSessionId === "" || toPreset === "") {
|
|
1213
|
+
return send(res, 400, { ok: false, error: "sessionId and toPreset required" });
|
|
1214
|
+
}
|
|
1215
|
+
try {
|
|
1216
|
+
const result = await migratePreset({ sessionId: requestedSessionId, toPreset });
|
|
1217
|
+
return send(res, 200, { ok: true, result });
|
|
1218
|
+
} catch (error) {
|
|
1219
|
+
ctx.logger.warn("session-manager: preset-migrate failed: " + String(error));
|
|
1220
|
+
return send(res, 500, { ok: false, error: String(error.message || error) });
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
|
|
186
1224
|
return send(res, 404, { ok: false, error: `not found: ${req.method} ${path}` });
|
|
187
1225
|
} catch (error) {
|
|
188
|
-
ctx.logger.warn(`session-manager: api error: ${String(error)}`);
|
|
1226
|
+
ctx.logger.warn(`session-manager: api error: ${String(error)}; type=${error?.constructor?.name}; json=${safeJson(error)}`);
|
|
189
1227
|
return send(res, 500, { ok: false, error: String(error instanceof Error ? error.message : error) });
|
|
190
1228
|
}
|
|
191
1229
|
}
|