dsh-session-relocate 0.0.0-stage → 0.2.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/src/plugin.js ADDED
@@ -0,0 +1,884 @@
1
+ /**
2
+ * dsh-session-relocate —— 主机侧。
3
+ *
4
+ * 提供 /api/dsh-session-relocate/{describe,move,status} 桥接给网页端,并在启动时补完
5
+ * 上次没做完的迁移。
6
+ *
7
+ * 刻意**不 import 任何 @deepseek-ai/* 包**:
8
+ * - 需要的服务全部从 cordis ctx 上取(workspaceRegistry / sessionPersistence / sessions);
9
+ * - dsh home 自己按 DSH_HOME > ~/.dsh 的顺序解析。
10
+ * 这样即使 profile 的 node_modules 布局和预期不同,插件也能加载。
11
+ *
12
+ * @module dsh-session-relocate
13
+ */
14
+ import { existsSync } from 'node:fs';
15
+ import { createRequire } from 'node:module';
16
+ import { mkdir, readdir, realpath, rm } from 'node:fs/promises';
17
+ import { randomBytes } from 'node:crypto';
18
+ import { homedir } from 'node:os';
19
+ import { dirname, join } from 'node:path';
20
+ import { encodeSegment, sessionDir } from './paths.js';
21
+ import { commitMoves, createMoveStore, MoveError, recoverPendingMoves, relocateSession, samePath } from './relocate.js';
22
+
23
+ /** 插件名(必须与 package.json 的 name 一致)。 */
24
+ export const name = 'dsh-session-relocate';
25
+
26
+ /**
27
+ * 需要的工作区注册表与会话持久层。两者都是 web 组合里的常规成员;
28
+ * 缺任一个就说明这个部署没有「工作区」概念,插件不应该加载。
29
+ */
30
+ export const inject = ['workspaceRegistry', 'sessionPersistence'];
31
+
32
+ /** 桥接默认前缀。 */
33
+ const DEFAULT_PREFIX = '/api/dsh-session-relocate';
34
+ /**
35
+ * 插件版本:**唯一来源是 package.json**(发布规程 §1.1:版本号只能写一处,
36
+ * 写两处就会漂移 —— 这个常量曾经是硬编码的 '0.4.0',package.json 升到 0.5.0 后
37
+ * 运行时自报的版本就骗人了)。读不到才退化成显眼的 unknown。
38
+ */
39
+ const PLUGIN_VERSION = (() => {
40
+ try {
41
+ return createRequire(import.meta.url)('../package.json').version;
42
+ } catch {
43
+ return '0.0.0-unknown';
44
+ }
45
+ })();
46
+ /** 允许挂在 window 上的引导全局名,供客户端读前缀。 */
47
+ const BOOT_GLOBAL = '__DSH_SESSION_RELOCATE__';
48
+ /** 请求体上限。 */
49
+ const MAX_BODY_BYTES = 64 * 1024;
50
+
51
+ /** 解析 DSH home:显式配置 > $DSH_HOME > ~/.dsh(与 dsh-home-paths 的优先级一致)。 */
52
+ function resolveHome(settings) {
53
+ if (typeof settings.home === 'string' && settings.home.trim().length > 0) return settings.home.trim();
54
+ const env = process.env.DSH_HOME;
55
+ if (typeof env === 'string' && env.trim().length > 0) return env.trim();
56
+ return join(homedir(), '.dsh');
57
+ }
58
+
59
+ /** 请求体解析失败。映射成 400 + code: 'bad-request',而不是 500 internal。 */
60
+ class BadRequestBodyError extends Error {
61
+ constructor(message) {
62
+ super(message);
63
+ this.name = 'BadRequestBodyError';
64
+ this.code = 'bad-request';
65
+ }
66
+ }
67
+
68
+ /** 读一个 JSON 请求体。 */
69
+ function readJsonBody(req) {
70
+ return new Promise((resolve, reject) => {
71
+ const chunks = [];
72
+ let size = 0;
73
+ req.on('data', (chunk) => {
74
+ size += chunk.length;
75
+ if (size > MAX_BODY_BYTES) {
76
+ reject(new BadRequestBodyError('请求体过大'));
77
+ req.destroy();
78
+ return;
79
+ }
80
+ chunks.push(chunk);
81
+ });
82
+ req.on('end', () => {
83
+ if (chunks.length === 0) {
84
+ resolve({});
85
+ return;
86
+ }
87
+ try {
88
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
89
+ } catch {
90
+ reject(new BadRequestBodyError('请求体不是合法 JSON'));
91
+ }
92
+ });
93
+ req.on('error', reject);
94
+ });
95
+ }
96
+
97
+ /** 写一个 JSON 响应。 */
98
+ function writeJson(res, status, payload) {
99
+ const body = Buffer.from(JSON.stringify(payload), 'utf8');
100
+ res.statusCode = status;
101
+ res.setHeader('content-type', 'application/json; charset=utf-8');
102
+ res.setHeader('cache-control', 'no-store');
103
+ res.end(body);
104
+ }
105
+
106
+ /** 把内部错误转成稳定的失败载荷。 */
107
+ function failure(error) {
108
+ if (error instanceof MoveError) {
109
+ return { ok: false, code: error.code, message: error.message, details: error.details };
110
+ }
111
+ if (error instanceof BadRequestBodyError) {
112
+ return { ok: false, code: error.code, message: error.message };
113
+ }
114
+ return { ok: false, code: 'internal', message: String(error && error.message ? error.message : error) };
115
+ }
116
+
117
+ /**
118
+ * 挂载插件。
119
+ *
120
+ * @param ctx - cordis 上下文。
121
+ * @param config - profile 里这一行的 config。
122
+ */
123
+ export function apply(ctx, config) {
124
+ const settings = config !== null && typeof config === 'object' ? config : {};
125
+ const home = resolveHome(settings);
126
+ const prefix = typeof settings.bridgePrefix === 'string' && settings.bridgePrefix.trim().length > 0
127
+ ? settings.bridgePrefix.trim().replace(/\/+$/, '')
128
+ : DEFAULT_PREFIX;
129
+ const journalsDir = typeof settings.journalsDir === 'string' && settings.journalsDir.trim().length > 0
130
+ ? settings.journalsDir.trim()
131
+ : join(home, 'session-move');
132
+ // 默认会自动释放「打开中但空闲」的会话,好让它能被搬走。releaseLive=false 恢复旧行为。
133
+ const releaseLive = settings.releaseLive !== false;
134
+ // 「就地接管」:打开中且**还在跑活**的会话也能搬 —— 换掉 live 写句柄的 header,
135
+ // 在持有写链的情况下搬文件,正在跑的 turn 不中断。默认开;关掉就退回「正在跑活的拒绝」。
136
+ const moveLive = settings.moveLive !== false;
137
+ // 侧边栏拖动搬移(客户端读引导全局里的 drag 开关)。DSH 改了 DOM 约定时可以一键关掉。
138
+ const dragMove = settings.dragMove !== false;
139
+ /** 每次就地接管的窗口,供自测断言「搬迁期间没有写入插进来」。 */
140
+ const handoffLog = [];
141
+ const releaseRetries = Number.isSafeInteger(settings.releaseRetries) && settings.releaseRetries >= 0
142
+ ? settings.releaseRetries
143
+ : 24;
144
+ const releaseRetryDelayMs = Number.isFinite(settings.releaseRetryDelayMs) && settings.releaseRetryDelayMs > 0
145
+ ? settings.releaseRetryDelayMs
146
+ : 150;
147
+ // 自测接口默认关闭;打开后会多出 __selftest/* 路由(用来造一个 live 会话做验证)。
148
+ const selftest = settings.selftest === true;
149
+ const selftestLeases = new Map();
150
+ /** 自测用的「写入压力」循环状态。 */
151
+ const selftestPressure = { timer: null, sessionId: null, marks: [] };
152
+
153
+ /** 等一小会儿(释放租约是异步的,靠重试确认)。 */
154
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
155
+
156
+ /**
157
+ * 找到某个会话的 live 写句柄。
158
+ *
159
+ * 它在后端的 **tracker** 上(JsonlBackendTracker.writers),不在持久化服务本身;
160
+ * 顺手也认直接挂在服务上的写法,免得换个 rc 版本就静默失效。
161
+ * writers 里可能是 null(已创建但未物化的占位),那也当成「没有句柄」。
162
+ */
163
+ function findWriteHandle(sessionId) {
164
+ const persistence = ctx.sessionPersistence;
165
+ const maps = [
166
+ persistence.writers,
167
+ persistence.tracker !== undefined ? persistence.tracker.writers : undefined,
168
+ ];
169
+ for (const map of maps) {
170
+ if (map === undefined || map === null || typeof map.get !== 'function') continue;
171
+ const handle = map.get(sessionId);
172
+ if (handle !== undefined && handle !== null && typeof handle.enqueueChain === 'function') return handle;
173
+ }
174
+ return undefined;
175
+ }
176
+
177
+ const logger = ctx.logger;
178
+ const log = (level, message) => {
179
+ const sink = logger !== undefined && typeof logger[level] === 'function' ? logger[level].bind(logger) : undefined;
180
+ if (sink !== undefined) {
181
+ sink('[dsh-session-relocate] ' + message);
182
+ return;
183
+ }
184
+ if (level === 'warn') console.warn('[dsh-session-relocate] ' + message);
185
+ else console.log('[dsh-session-relocate] ' + message);
186
+ };
187
+
188
+ /** 会话存储根目录。后端把 root 作为私有字段持有,取不到就按 home 惯例回退。 */
189
+ function sessionsRoot() {
190
+ if (typeof settings.sessionsRoot === 'string' && settings.sessionsRoot.trim().length > 0) {
191
+ return settings.sessionsRoot.trim();
192
+ }
193
+ const root = ctx.sessionPersistence.root;
194
+ if (typeof root === 'string' && root.length > 0) return root;
195
+ return join(home, 'sessions');
196
+ }
197
+
198
+ /**
199
+ * 一个会话在某个 cwd 下的目录。优先问后端自己(locate 返回的是当前 generation
200
+ * 的路径,取父目录即会话目录),这样 projectKey 的细节永远与后端保持一致。
201
+ */
202
+ function sessionDirFor(sessionId, cwd) {
203
+ const persistence = ctx.sessionPersistence;
204
+ if (typeof persistence.locate === 'function') {
205
+ try {
206
+ const located = persistence.locate({ id: sessionId, cwd });
207
+ if (located !== undefined && typeof located.path === 'string' && located.path.length > 0) {
208
+ return dirname(located.path);
209
+ }
210
+ } catch {
211
+ // 落到回退实现
212
+ }
213
+ }
214
+ return sessionDir(sessionsRoot(), cwd, sessionId);
215
+ }
216
+
217
+ const store = createMoveStore({
218
+ sessionsRoot: sessionsRoot(),
219
+ journalsDir,
220
+ sessionDirFor,
221
+ log,
222
+ // 校验强度:auto(小日志全文解码,大日志帧级抽样)或 full(永远全文解码)。
223
+ verify: settings.verify === 'full' ? 'full' : 'auto',
224
+ fullVerifyLimit: Number.isSafeInteger(settings.fullVerifyLimit) && settings.fullVerifyLimit > 0
225
+ ? settings.fullVerifyLimit
226
+ : undefined,
227
+ });
228
+
229
+ /** 组装一次迁移需要的 DSH 运行时能力。 */
230
+ function buildHost() {
231
+ const registry = ctx.workspaceRegistry;
232
+ return {
233
+ async statSession(sessionId) {
234
+ return await ctx.sessionPersistence.stat(sessionId);
235
+ },
236
+ getWorkspace(workspaceId) {
237
+ return registry.get(workspaceId);
238
+ },
239
+ async createWorkspace(path) {
240
+ // 注册表内部会先 realpath 目标路径,所以「目录不存在会被创建」这条承诺
241
+ // 必须由我们先把目录建出来,否则 realpath 会直接 ENOENT。
242
+ await mkdir(path, { recursive: true });
243
+ return await registry.create(path);
244
+ },
245
+ findWorkspaceByPath(canonicalPath) {
246
+ for (const entity of registry.list()) {
247
+ if (samePath(entity.path, canonicalPath)) return entity;
248
+ }
249
+ return undefined;
250
+ },
251
+ isSessionLive(sessionId) {
252
+ const sessions = ctx.get('sessions');
253
+ if (sessions === undefined || typeof sessions.get !== 'function') return false;
254
+ try {
255
+ return sessions.get(sessionId) !== undefined;
256
+ } catch {
257
+ return false;
258
+ }
259
+ },
260
+ async listActivity(sessionId) {
261
+ if (typeof ctx.waterfall !== 'function') return [];
262
+ try {
263
+ const activity = await ctx.waterfall(
264
+ 'workspace/session-activity',
265
+ { sessionId },
266
+ () => Promise.resolve([]),
267
+ );
268
+ return Array.isArray(activity) ? activity : [];
269
+ } catch (error) {
270
+ log('warn', '查询会话活动失败,按「无活动」继续:' + String(error && error.message));
271
+ return [];
272
+ }
273
+ },
274
+ describeActivity(activity) {
275
+ return activity.map((entry) => (entry !== null && typeof entry === 'object' ? entry.kind : '?')).join('、');
276
+ },
277
+ /**
278
+ * 释放一个「活着」的会话:flush → 摘掉 entered 记录 → 用写打开探针确认写租约真的没了。
279
+ *
280
+ * 为什么需要它:会话日志是**单写者**的,写所有权由 agent-loop 的写句柄持有
281
+ * (它调 persistence.open(id,'write')),只在 DSH 进程退出时才释放。不释放就搬文件,
282
+ * 那个句柄会继续往旧路径写、并在旧位置重建一个空壳目录。
283
+ *
284
+ * 摘除走的是 SessionStore 的私有缝 sessions.store.get(id).detach() —— 同一版本里
285
+ * dsh-delete-session 也在生产里用它。它会派发 session/disposed,持久层据此
286
+ * close 写句柄、释放 session.lock 租约;释放是异步的(fire-and-forget),
287
+ * 所以这里用「写打开探针 + 重试」来确认。
288
+ */
289
+ /**
290
+ * 就地接管一个正在运行的会话:**不释放它**,而是换掉它的 live 写句柄的 header,
291
+ * 并在持有该句柄写链的情况下跑文件事务 —— 这样搬迁期间任何写入都排在我们后面,
292
+ * 落地时已经指向新路径,正在跑的 turn 不会断。
293
+ *
294
+ * 依据(都在源码里核过):
295
+ * - JsonlSessionHandle 的写入路径是每次从 this.header 现算的:
296
+ * persistContiguous → storage.persistBatch(header) → logPath(root, header.cwd, …);
297
+ * - this.header 是**可写槽位**(deepFreeze 冻的是那个对象,不是这个属性);
298
+ * - 内核写锁 this.lease 懒获取(ensureLease 用 ??=):先释放再置空,
299
+ * 下一次写入就会在新路径重新获取;
300
+ * - enqueueChain 是该句柄唯一的串行点,append/flush/drain 都走它;
301
+ * - drainLive 自己会往 chain 上排队,所以必须在进入临界区**之前**调用,否则死锁。
302
+ */
303
+ /** 现在能不能就地接管:有 live 写句柄才算能(没句柄就走释放路径)。 */
304
+ canHandoff(sessionId) {
305
+ return findWriteHandle(sessionId) !== undefined;
306
+ },
307
+ async handoffLive(sessionId, targetCwd, runTransaction) {
308
+ const handle = findWriteHandle(sessionId);
309
+ if (handle === undefined) {
310
+ // 探测不到写句柄就**绝不静默搬** —— 那会留下「文件已搬、句柄还指着旧路径」
311
+ // 的坏状态(下一次写入就把旧目录重建出来)。整体放弃,让调用方改走释放路径。
312
+ return { ok: false, code: 'no-writer', detail: '找不到这个会话的 live 写句柄' };
313
+ }
314
+ if (typeof handle.drainLive === 'function') await handle.drainLive();
315
+ if (typeof handle.flush === 'function') await handle.flush();
316
+
317
+ const start = Date.now();
318
+ let detail = '';
319
+ const transaction = await handle.enqueueChain(async () => {
320
+ if (typeof handle.ensureLease === 'function') await handle.ensureLease();
321
+ const originalHeader = handle.header;
322
+ try {
323
+ if (handle.lease !== undefined && handle.lease !== null && typeof handle.lease.release === 'function') {
324
+ await handle.lease.release();
325
+ }
326
+ handle.lease = null;
327
+ handle.header = { ...originalHeader, cwd: targetCwd };
328
+ const result = await runTransaction();
329
+ detail = '写链已接管:header.cwd -> ' + targetCwd;
330
+ result.writerRetargeted = true;
331
+ return result;
332
+ } catch (error) {
333
+ // 回滚:恢复 header 与锁状态,让后续写入继续落在原路径。
334
+ handle.header = originalHeader;
335
+ handle.lease = null;
336
+ throw error;
337
+ }
338
+ });
339
+ const end = Date.now();
340
+ handoffLog.push({ sessionId, start, end });
341
+ return { ok: true, detail, transaction, window: { start, end } };
342
+ },
343
+ /**
344
+ * 就地接管后的归属写入:**绕开 attachSession 的 cwd 校验**,直接走注册表自己的
345
+ * 写路径(entity.mutate → table.update),并同步它的路径/header 索引。
346
+ *
347
+ * 为什么要绕:注册表校验归属时会 readSessionHeader(id),而它优先取内存里的
348
+ * live Session —— 那个 header 是 deep-frozen 的旧 cwd,改不了,所以校验必然失败。
349
+ *
350
+ * 顺序很关键:entity.mutate 内部会用 host.sessionPath(id) 过滤 sessionIds,
351
+ * 所以必须**先**把 sessionPaths 指到新 cwd,否则刚加进去的 id 会被它自己滤掉。
352
+ */
353
+ async adoptSession(sessionId, targetEntity, sourceEntity, targetCwd) {
354
+ const registry = ctx.workspaceRegistry;
355
+ try {
356
+ const liveSession = ctx.get('sessions')?.get(sessionId);
357
+ const existing = registry.headers instanceof Map ? registry.headers.get(sessionId) : undefined;
358
+ const base = liveSession !== undefined && liveSession.header !== undefined
359
+ ? liveSession.header
360
+ : (existing !== undefined ? existing : { version: 4, id: sessionId, createdAt: Date.now(), isSeeded: false });
361
+ if (registry.sessionPaths instanceof Map) registry.sessionPaths.set(sessionId, targetCwd);
362
+ if (registry.invalidSessionPaths instanceof Map) registry.invalidSessionPaths.delete(sessionId);
363
+ if (registry.headers instanceof Map) registry.headers.set(sessionId, { ...base, cwd: targetCwd });
364
+ if (typeof targetEntity.mutate !== 'function') {
365
+ return { applied: false, refreshed: false, reason: '目标工作区实体没有 mutate 接口(DSH 版本变了)' };
366
+ }
367
+ await targetEntity.mutate((record) => (record.sessionIds.includes(sessionId)
368
+ ? record
369
+ : { ...record, sessionIds: [sessionId, ...record.sessionIds] }));
370
+ if (sourceEntity !== undefined && sourceEntity.id !== targetEntity.id && typeof sourceEntity.mutate === 'function') {
371
+ await sourceEntity.mutate((record) => (record.sessionIds.includes(sessionId)
372
+ ? { ...record, sessionIds: record.sessionIds.filter((entry) => entry !== sessionId) }
373
+ : record));
374
+ }
375
+ return { applied: true, refreshed: false };
376
+ } catch (error) {
377
+ return { applied: false, refreshed: false, reason: '直接写注册表归属失败:' + String(error && error.message) };
378
+ }
379
+ },
380
+ /**
381
+ * 批量归属写入(commitMoves 用):先把这批会话的 header 缓存/路径索引一次性指到
382
+ * 目标 cwd,再**一次 mutate** 把整批加进目标工作区 —— 注册表只落盘一次。
383
+ * 和 adoptSession 同一条旁路,区别只是按批做。
384
+ */
385
+ async adoptSessions(sessionIds, targetEntity, targetCwd) {
386
+ const registry = ctx.workspaceRegistry;
387
+ try {
388
+ if (typeof targetEntity.mutate !== 'function') {
389
+ return { applied: false, refreshed: false, reason: '目标工作区实体没有 mutate 接口(DSH 版本变了)' };
390
+ }
391
+ for (const sessionId of sessionIds) {
392
+ const liveSession = ctx.get('sessions')?.get(sessionId);
393
+ const existing = registry.headers instanceof Map ? registry.headers.get(sessionId) : undefined;
394
+ const base = liveSession !== undefined && liveSession.header !== undefined
395
+ ? liveSession.header
396
+ : (existing !== undefined ? existing : { version: 4, id: sessionId, createdAt: Date.now(), isSeeded: false });
397
+ if (registry.sessionPaths instanceof Map) registry.sessionPaths.set(sessionId, targetCwd);
398
+ if (registry.invalidSessionPaths instanceof Map) registry.invalidSessionPaths.delete(sessionId);
399
+ if (registry.headers instanceof Map) registry.headers.set(sessionId, { ...base, cwd: targetCwd });
400
+ }
401
+ await targetEntity.mutate((record) => {
402
+ const add = sessionIds.filter((id) => !record.sessionIds.includes(id));
403
+ return add.length === 0 ? record : { ...record, sessionIds: [...add, ...record.sessionIds] };
404
+ });
405
+ return { applied: true, refreshed: false };
406
+ } catch (error) {
407
+ return { applied: false, refreshed: false, reason: '批量写目标归属失败:' + String(error && error.message) };
408
+ }
409
+ },
410
+ /** 批量摘除(commitMoves 用):一次 mutate 把整批从源工作区拿掉。 */
411
+ async detachSessions(sessionIds, sourceEntity) {
412
+ if (sourceEntity === undefined || sourceEntity === null || typeof sourceEntity.mutate !== 'function') {
413
+ return { applied: true };
414
+ }
415
+ try {
416
+ const drop = new Set(sessionIds);
417
+ await sourceEntity.mutate((record) => {
418
+ const keep = record.sessionIds.filter((id) => !drop.has(id));
419
+ return keep.length === record.sessionIds.length ? record : { ...record, sessionIds: keep };
420
+ });
421
+ return { applied: true };
422
+ } catch (error) {
423
+ return { applied: false, reason: '批量摘除源归属失败:' + String(error && error.message) };
424
+ }
425
+ },
426
+ async releaseSession(sessionId) {
427
+ const sessions = ctx.get('sessions');
428
+ if (sessions === undefined || typeof sessions.get !== 'function') {
429
+ return { released: true, attempts: 0, detail: '没有 sessions 服务,视为无需释放' };
430
+ }
431
+ const live = sessions.get(sessionId);
432
+ if (live === undefined) return { released: true, attempts: 0, detail: '本来就不在内存里' };
433
+
434
+ if (typeof sessions.flush === 'function') {
435
+ try {
436
+ await sessions.flush(live);
437
+ } catch (error) {
438
+ log('warn', '释放前 flush 失败(继续释放):' + String(error && error.message));
439
+ }
440
+ }
441
+
442
+ const entries = sessions.store;
443
+ const entered = entries !== undefined && typeof entries.get === 'function' ? entries.get(sessionId) : undefined;
444
+ if (entered === undefined || typeof entered.detach !== 'function') {
445
+ return { released: false, attempts: 0, detail: '拿不到可释放的 entered 记录(DSH 版本可能变了)' };
446
+ }
447
+ entered.detach();
448
+
449
+ const persistence = ctx.sessionPersistence;
450
+ if (typeof persistence.open !== 'function') return { released: true, attempts: 0, detail: '已从内存摘除(没有 open 可探测)' };
451
+ // 前几次探得很快(正常情况 detach 完立刻就能拿到租约),之后退回常规间隔。
452
+ // 这样"正常情况"几乎零等待,"被 GUI 抢着"时也仍然能等到,且总时长不变。
453
+ const quickDelays = [0, 10, 25, 50, 100];
454
+ let last = 'unknown';
455
+ for (let attempt = 0; attempt <= releaseRetries; attempt++) {
456
+ let handle;
457
+ try {
458
+ handle = await persistence.open(sessionId, 'write');
459
+ } catch (error) {
460
+ last = String(error && error.message !== undefined ? error.message : error);
461
+ if (attempt === releaseRetries) break;
462
+ const delay = attempt < quickDelays.length ? quickDelays[attempt] : releaseRetryDelayMs;
463
+ if (delay > 0) await sleep(delay);
464
+ continue;
465
+ }
466
+ try {
467
+ await handle.close();
468
+ } catch (error) {
469
+ log('warn', '探针句柄关闭失败(不影响结论):' + String(error && error.message));
470
+ }
471
+ return { released: true, attempts: attempt + 1, detail: '写租约已释放(第 ' + String(attempt + 1) + ' 次探测拿到写所有权)' };
472
+ }
473
+ return { released: false, attempts: releaseRetries + 1, detail: '写所有权仍被占用(试了 ' + String(releaseRetries + 1) + ' 次):' + last };
474
+ },
475
+ /**
476
+ * 重建注册表的 header 缓存。
477
+ *
478
+ * 这是**必需**的一步:注册表的 header 索引是启动时建的,磁盘上的 cwd 被我们改
479
+ * 了以后它并不知道,不刷新的话 attachSession 会拿旧 cwd 去比目标路径然后拒掉。
480
+ * 这两个成员是包私有实现,所以此处 feature-detect;取不到就返回 false,
481
+ * 迁移会在下次启动时自动补齐归属。
482
+ */
483
+ async refreshHeaderIndex() {
484
+ const listStored = registry.listStoredHeaders;
485
+ const replace = registry.replaceHeaderIndex;
486
+ if (typeof listStored !== 'function' || typeof replace !== 'function') return false;
487
+ const rebuild = async () => {
488
+ await replace.call(registry, await listStored.call(registry));
489
+ };
490
+ if (typeof registry.enqueueOperation === 'function') await registry.enqueueOperation(rebuild);
491
+ else await rebuild();
492
+ return true;
493
+ },
494
+ async invalidateProjection(sessionId) {
495
+ const file = join(home, 'storages', 'session_projcache', 'sessions', sessionId + '.json');
496
+ await rm(file, { force: true }).catch((error) => {
497
+ log('warn', '清理投影缓存失败(不影响迁移):' + String(error && error.message));
498
+ });
499
+ },
500
+ log,
501
+ };
502
+ }
503
+
504
+ // ---- 未完成迁移的恢复 ----------------------------------------------------
505
+
506
+ let recovery = null;
507
+
508
+ /** 单飞地补完未完成的迁移。启动时调用一次,之后每次桥接调用都会再兜一次。 */
509
+ function kickRecovery() {
510
+ if (recovery !== null) return recovery;
511
+ recovery = (async () => {
512
+ try {
513
+ const results = await recoverPendingMoves(buildHost(), store);
514
+ for (const result of results) {
515
+ log(result.status === 'failed' || result.status === 'lost' ? 'warn' : 'info',
516
+ '恢复未完成的迁移 ' + result.opId + ':' + result.status
517
+ + (result.message !== undefined ? '(' + result.message + ')' : '')
518
+ + (result.to !== undefined ? ' -> ' + result.to : ''));
519
+ }
520
+ return results;
521
+ } catch (error) {
522
+ log('warn', '恢复未完成的迁移失败:' + String(error && error.message));
523
+ return [];
524
+ } finally {
525
+ recovery = null;
526
+ }
527
+ })();
528
+ return recovery;
529
+ }
530
+
531
+ // 启动后跑一次(不阻塞启动)。
532
+ setTimeout(() => { void kickRecovery(); }, 0);
533
+
534
+ // ---- HTTP 桥接 ----------------------------------------------------------
535
+
536
+ /** 描述当前状态:可选带一个 sessionId,用来告诉界面「能不能搬、为什么不能」。 */
537
+ async function describe(body) {
538
+ const registry = ctx.workspaceRegistry;
539
+ const workspaces = registry.list().map((entity) => ({ id: entity.id, title: entity.title, path: entity.path }));
540
+ const payload = {
541
+ ok: true,
542
+ version: PLUGIN_VERSION,
543
+ prefix,
544
+ home,
545
+ releaseLive,
546
+ workspaces,
547
+ session: null,
548
+ };
549
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId : '';
550
+ if (sessionId.length === 0) return payload;
551
+
552
+ const host = buildHost();
553
+ let snapshot;
554
+ try {
555
+ snapshot = await ctx.sessionPersistence.stat(sessionId);
556
+ } catch (error) {
557
+ payload.session = { id: sessionId, unreadable: true, message: String(error && error.message) };
558
+ return payload;
559
+ }
560
+ if (snapshot === undefined) {
561
+ payload.session = { id: sessionId, missing: true };
562
+ return payload;
563
+ }
564
+ const cwd = snapshot.header.cwd;
565
+ let canonical;
566
+ if (typeof cwd === 'string' && cwd.length > 0) {
567
+ try {
568
+ canonical = await realpath(cwd);
569
+ } catch {
570
+ canonical = undefined;
571
+ }
572
+ }
573
+ const current = canonical === undefined
574
+ ? undefined
575
+ : workspaces.find((workspace) => samePath(workspace.path, canonical));
576
+ const activity = await host.listActivity(sessionId);
577
+ const live = host.isSessionLive(sessionId);
578
+ // 就地接管可用时,连「正在跑活」都能搬(换掉 live 写句柄的 header,turn 不断)。
579
+ const handoffAvailable = live && moveLive && typeof host.handoffLive === 'function';
580
+ const reason = canonical === undefined
581
+ ? '这个对话记录的目录已不存在,无法安全迁移'
582
+ : (activity.length > 0 && !handoffAvailable
583
+ ? '这个对话还有正在运行的工作,请先停止'
584
+ : (live && !handoffAvailable && !releaseLive
585
+ ? '这个对话正打开着,而 releaseLive=false 禁止自动释放它;请重启 DSH 后再移动'
586
+ : null));
587
+ payload.session = {
588
+ id: sessionId,
589
+ cwd: cwd ?? null,
590
+ canonicalCwd: canonical ?? null,
591
+ currentWorkspaceId: current === undefined ? null : current.id,
592
+ live,
593
+ willHandoff: handoffAvailable && reason === null,
594
+ willRelease: live && !handoffAvailable && reason === null,
595
+ activity,
596
+ activityText: host.describeActivity(activity),
597
+ canMove: reason === null,
598
+ reason,
599
+ };
600
+ payload.workspaces = workspaces.map((workspace) => ({
601
+ ...workspace,
602
+ current: workspace.id === payload.session.currentWorkspaceId,
603
+ }));
604
+ return payload;
605
+ }
606
+
607
+ /** 执行一次迁移。 */
608
+ async function move(body) {
609
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : '';
610
+ if (sessionId.length === 0) return { ok: false, code: 'bad-request', message: '缺少 sessionId' };
611
+ const targetWorkspaceId = typeof body.targetWorkspaceId === 'string' ? body.targetWorkspaceId : '';
612
+ const targetPath = typeof body.targetPath === 'string' ? body.targetPath.trim() : '';
613
+ try {
614
+ const receipt = await relocateSession(buildHost(), store, {
615
+ sessionId,
616
+ targetWorkspaceId,
617
+ targetPath,
618
+ releaseLive,
619
+ moveLive,
620
+ // 批量搬移时客户端逐条 defer:文件事务各自做完,注册表最后一次性写。
621
+ deferRegistry: body.deferRegistry === true,
622
+ });
623
+ return { ok: true, ...receipt };
624
+ } catch (error) {
625
+ log('warn', '迁移失败:' + String(error && error.message));
626
+ return failure(error);
627
+ }
628
+ }
629
+
630
+ /** 批量收尾:把一串 defer 过的迁移的归属一次性写进注册表。 */
631
+ async function moveCommit(body) {
632
+ const ids = Array.isArray(body.sessionIds)
633
+ ? body.sessionIds.filter((entry) => typeof entry === 'string' && entry.length > 0)
634
+ : [];
635
+ if (ids.length === 0) return { ok: false, code: 'bad-request', message: '缺少 sessionIds' };
636
+ try {
637
+ const result = await commitMoves(buildHost(), store, ids);
638
+ return { ok: result.ok !== false, ...result };
639
+ } catch (error) {
640
+ log('warn', '批量结算失败:' + String(error && error.message));
641
+ return failure(error);
642
+ }
643
+ }
644
+
645
+ /** 报告还有哪些迁移没收尾。 */
646
+ async function status() {
647
+ await kickRecovery();
648
+ const journals = await store.readJournals();
649
+ return {
650
+ ok: true,
651
+ version: PLUGIN_VERSION,
652
+ prefix,
653
+ home,
654
+ releaseLive,
655
+ moveLive,
656
+ dragMove,
657
+ selftest,
658
+ // 批量搬移的两段式(defer 文件事务 + 一次 commit 写注册表)由客户端按这个能力位决定是否启用。
659
+ bulkDefer: true,
660
+ verify: settings.verify === 'full' ? 'full' : 'auto',
661
+ sessionsRoot: store.sessionsRoot,
662
+ journalsDir: store.journalsDir,
663
+ pending: journals.map((journal) => ({
664
+ opId: journal.opId,
665
+ sessionId: journal.sessionId,
666
+ from: journal.fromCwd,
667
+ to: journal.toCwd,
668
+ phase: journal.phase,
669
+ startedAt: journal.startedAt,
670
+ })),
671
+ };
672
+ }
673
+
674
+ // ---- 自测辅助(默认关闭,config.selftest=true 才挂路由)------------------------
675
+ // 用来在**真实进程**里造一个「已打开(live)且持有写租约」的会话,验证「释放后再搬」,
676
+ // 而不必碰任何真实对话。
677
+
678
+ /** 造一个 live 会话;lease=true 时同时持有写租约(等价于被 DSH 打开)。 */
679
+ async function selftestCreateLive(body) {
680
+ const sessions = ctx.get('sessions');
681
+ if (sessions === undefined || typeof sessions.create !== 'function') {
682
+ return { ok: false, code: 'no-sessions', message: '这个组合没有 sessions 服务' };
683
+ }
684
+ const workspacePath = typeof body.workspacePath === 'string' && body.workspacePath.trim().length > 0
685
+ ? body.workspacePath.trim()
686
+ : join(home, 'session-move-selftest');
687
+ await mkdir(workspacePath, { recursive: true });
688
+ const workspace = await ctx.workspaceRegistry.create(workspacePath);
689
+ const sessionId = typeof body.sessionId === 'string' && body.sessionId.trim().length > 0
690
+ ? body.sessionId.trim()
691
+ : 'session-' + randomBytes(4).toString('hex') + '-0000-4000-8000-' + randomBytes(6).toString('hex');
692
+ // 按 agent-loop 的真实顺序:先取得持久化写所有权(= 物化日志 + 持有 session.lock
693
+ // 租约),再把它发布成 live 会话。这样自测出来的状态与「DSH 真的打开了这个会话」一致。
694
+ let leaseHeld = false;
695
+ let leaseError = null;
696
+ if (body.lease !== false) {
697
+ try {
698
+ selftestLeases.set(sessionId, await ctx.sessionPersistence.create({
699
+ version: 4,
700
+ id: sessionId,
701
+ createdAt: Date.now(),
702
+ cwd: workspace.path,
703
+ isSeeded: false,
704
+ delegationDepth: 0,
705
+ agentPreset: 'standard',
706
+ }));
707
+ leaseHeld = true;
708
+ } catch (error) {
709
+ leaseError = String(error && error.message !== undefined ? error.message : error);
710
+ }
711
+ }
712
+ const session = sessions.create(sessionId, { meta: { cwd: workspace.path } });
713
+ if (typeof sessions.flush === 'function') await sessions.flush(session);
714
+ await workspace.attachSession(sessionId);
715
+
716
+ // pressure=true:起一个循环,持续往这个会话的**写链**上排队 —— 等价于「正在跑的
717
+ // turn 不断产生写入」。搬迁期间如果有任何一次插进来,就会被自测断言抓到。
718
+ let pressure = false;
719
+ if (body.pressure === true && leaseHeld) {
720
+ const handle = selftestLeases.get(sessionId);
721
+ selftestPressure.sessionId = sessionId;
722
+ selftestPressure.marks = [];
723
+ if (selftestPressure.timer !== null) clearInterval(selftestPressure.timer);
724
+ selftestPressure.timer = setInterval(() => {
725
+ try {
726
+ void Promise.resolve(handle.enqueueChain(async () => {
727
+ selftestPressure.marks.push(Date.now());
728
+ })).catch(() => {});
729
+ } catch {
730
+ // 句柄关了就算了
731
+ }
732
+ }, 4);
733
+ pressure = true;
734
+ }
735
+
736
+ return {
737
+ ok: true,
738
+ sessionId,
739
+ workspaceId: workspace.id,
740
+ workspacePath: workspace.path,
741
+ live: sessions.get(sessionId) !== undefined,
742
+ leaseHeld,
743
+ leaseError,
744
+ pressure,
745
+ };
746
+ }
747
+
748
+ /** 自测观察窗:压力循环记录的时间戳 + 每次就地接管的窗口。 */
749
+ async function selftestState() {
750
+ const handle = selftestPressure.sessionId !== null ? selftestLeases.get(selftestPressure.sessionId) : undefined;
751
+ return {
752
+ ok: true,
753
+ pressure: {
754
+ sessionId: selftestPressure.sessionId,
755
+ running: selftestPressure.timer !== null,
756
+ marks: selftestPressure.marks,
757
+ },
758
+ handoffs: handoffLog,
759
+ writer: handle === undefined ? null : {
760
+ headerCwd: handle.header !== undefined ? handle.header.cwd : null,
761
+ leaseHeld: handle.lease !== undefined && handle.lease !== null,
762
+ },
763
+ };
764
+ }
765
+
766
+ /**
767
+ * 强制自测句柄重新获取内核锁 —— 用来**证明**它现在把路径算到新目录去了。
768
+ *
769
+ * 注意:写锁在 Windows 上是**由路径派生的命名内核信号量**(没有锁文件);
770
+ * 只在 POSIX 上才有一个 <sessionDir>/session.lock。所以这里的判据是
771
+ * sessionDir/headerCwd,而不是文件是否存在。
772
+ */
773
+ async function selftestEnsureLease() {
774
+ const id = selftestPressure.sessionId;
775
+ const handle = id !== null ? selftestLeases.get(id) : undefined;
776
+ if (handle === undefined) return { ok: false, code: 'no-handle', message: '没有可用的自测句柄' };
777
+ await handle.ensureLease();
778
+ const dir = sessionDirFor(id, handle.header.cwd);
779
+ return {
780
+ ok: true,
781
+ headerCwd: handle.header.cwd,
782
+ sessionDir: dir,
783
+ platform: process.platform,
784
+ // 只有 POSIX 才有锁文件;Windows 是路径派生的命名信号量。
785
+ lockFile: process.platform === 'win32' ? null : join(dir, 'session.lock'),
786
+ lockFileExists: process.platform === 'win32' ? null : existsSync(join(dir, 'session.lock')),
787
+ leaseHeld: handle.lease !== undefined && handle.lease !== null,
788
+ };
789
+ }
790
+
791
+ /** 停掉压力循环(清理用)。 */
792
+ async function selftestStopPressure() {
793
+ if (selftestPressure.timer !== null) {
794
+ clearInterval(selftestPressure.timer);
795
+ selftestPressure.timer = null;
796
+ }
797
+ return { ok: true, stopped: true };
798
+ }
799
+
800
+ /** 清掉自测造出来的会话:释放 + 摘归属 + 删目录 + 清投影缓存。 */
801
+ async function selftestDrop(body) {
802
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : '';
803
+ if (sessionId.length === 0) return { ok: false, code: 'bad-request', message: '需要 sessionId' };
804
+ const host = buildHost();
805
+ const release = await host.releaseSession(sessionId).catch((error) => ({
806
+ released: false,
807
+ detail: String(error && error.message),
808
+ }));
809
+ for (const entity of ctx.workspaceRegistry.list()) {
810
+ if (Array.isArray(entity.sessionIds) && entity.sessionIds.includes(sessionId)) {
811
+ await entity.detachSession(sessionId).catch(() => {});
812
+ }
813
+ }
814
+ const enc = encodeSegment(sessionId);
815
+ const removed = [];
816
+ const root = store.sessionsRoot;
817
+ const projects = await readdir(root, { withFileTypes: true }).catch(() => []);
818
+ for (const project of projects) {
819
+ if (!project.isDirectory()) continue;
820
+ const dir = join(root, project.name, enc);
821
+ if (!existsSync(dir)) continue;
822
+ await rm(dir, { recursive: true, force: true });
823
+ removed.push(dir);
824
+ }
825
+ await host.invalidateProjection(sessionId);
826
+ selftestLeases.delete(sessionId);
827
+ const deletedWorkspaces = [];
828
+ const paths = Array.isArray(body.deleteWorkspacePaths) ? body.deleteWorkspacePaths : [];
829
+ for (const entity of ctx.workspaceRegistry.list()) {
830
+ if (!paths.some((path) => samePath(entity.path, path))) continue;
831
+ await ctx.workspaceRegistry.delete(entity.id).catch(() => {});
832
+ deletedWorkspaces.push(entity.path);
833
+ }
834
+ return { ok: true, sessionId, release, removed, deletedWorkspaces };
835
+ }
836
+
837
+ function route(path, methods, handler) {
838
+ return {
839
+ kind: 'exact',
840
+ path,
841
+ handler: async (req, res) => {
842
+ const method = String(req.method ?? 'GET').toUpperCase();
843
+ if (!methods.includes(method)) {
844
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: '只接受 ' + methods.join('/') });
845
+ return;
846
+ }
847
+ try {
848
+ const body = method === 'POST' ? await readJsonBody(req) : {};
849
+ writeJson(res, 200, await handler(body));
850
+ } catch (error) {
851
+ writeJson(res, 400, failure(error instanceof Error ? error : new Error(String(error))));
852
+ }
853
+ },
854
+ };
855
+ }
856
+
857
+ ctx.inject(['webServer'], (sctx) => {
858
+ sctx.effect(() => {
859
+ const routes = [
860
+ route(prefix + '/describe', ['POST'], describe),
861
+ route(prefix + '/move', ['POST'], move),
862
+ route(prefix + '/move-commit', ['POST'], moveCommit),
863
+ route(prefix + '/status', ['GET', 'POST'], status),
864
+ ];
865
+ if (selftest) {
866
+ routes.push(route(prefix + '/__selftest/create-live', ['POST'], selftestCreateLive));
867
+ routes.push(route(prefix + '/__selftest/drop', ['POST'], selftestDrop));
868
+ routes.push(route(prefix + '/__selftest/state', ['GET', 'POST'], selftestState));
869
+ routes.push(route(prefix + '/__selftest/ensure-lease', ['POST'], selftestEnsureLease));
870
+ routes.push(route(prefix + '/__selftest/stop-pressure', ['POST'], selftestStopPressure));
871
+ }
872
+ const disposers = routes.map((entry) => sctx.webServer.register(entry));
873
+ const offInject = sctx.on('webserver/index-inject', (table) => {
874
+ table.push({ kind: 'global', name: BOOT_GLOBAL, value: { prefix, version: PLUGIN_VERSION, drag: dragMove } });
875
+ });
876
+ return () => {
877
+ for (const dispose of disposers) dispose();
878
+ offInject();
879
+ };
880
+ }, 'dsh-session-relocate: bridge');
881
+ });
882
+
883
+ log('info', '就绪:' + prefix + '(会话存储 ' + store.sessionsRoot + ',迁移日志 ' + store.journalsDir + ')');
884
+ }