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