dsh-seal-scripts 0.5.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +185 -167
- package/README.md +179 -186
- package/lib/client.js +34 -4
- package/lib/core/index.js +8 -1
- package/lib/host/compact-delete.js +188 -24
- package/lib/host/delete.js +32 -4
- package/package.json +4 -3
package/lib/client.js
CHANGED
|
@@ -178,8 +178,11 @@ window.__ModuleLoader__.load({
|
|
|
178
178
|
'note.memDeleted': function (f) { return '已删除回顾 ' + f },
|
|
179
179
|
'note.deleteConfirm': '再点一次确认删除(不可恢复)',
|
|
180
180
|
'note.deleted': '已删除',
|
|
181
|
+
'note.deletedWarn': "已删除(引擎重启前可能还记着它)",
|
|
181
182
|
'note.deletedLost': '已删除(响应中断,列表已确认消失)',
|
|
182
183
|
'note.compactConfirm': '再点一次确认:先压缩改写历史再删除,两者都不可逆',
|
|
184
|
+
'note.compacting': "压缩中…(要调用模型,可能要几十秒,别关这个页面)",
|
|
185
|
+
'btn.compacting': "压缩中…",
|
|
183
186
|
'note.compacted': function (m) { return '已压缩并删除,回顾 ' + m },
|
|
184
187
|
'err.request': function (p) { return '请求没送回结果(' + p + ')' },
|
|
185
188
|
'cal.hint': '点两天选区间,再点一次清空',
|
|
@@ -307,8 +310,11 @@ window.__ModuleLoader__.load({
|
|
|
307
310
|
'note.memDeleted': function (f) { return 'Deleted review ' + f },
|
|
308
311
|
'note.deleteConfirm': 'Click again to confirm delete (cannot be undone)',
|
|
309
312
|
'note.deleted': 'Deleted',
|
|
313
|
+
'note.deletedWarn': "Deleted (the engine may still hold a reference until it restarts)",
|
|
310
314
|
'note.deletedLost': 'Deleted (the response was lost; the list confirms it is gone)',
|
|
311
315
|
'note.compactConfirm': 'Click again: compact the history first, then delete — neither can be undone',
|
|
316
|
+
'note.compacting': "Compacting… (this calls the model and can take a while; keep this page open)",
|
|
317
|
+
'btn.compacting': "Compacting…",
|
|
312
318
|
'note.compacted': function (m) { return 'Compacted and deleted; review ' + m },
|
|
313
319
|
'err.request': function (p) { return 'No response from ' + p },
|
|
314
320
|
'cal.hint': 'Click two days to pick a range; click again to clear',
|
|
@@ -436,8 +442,11 @@ window.__ModuleLoader__.load({
|
|
|
436
442
|
'note.memDeleted': function (f) { return 'レビューを削除しました ' + f },
|
|
437
443
|
'note.deleteConfirm': 'もう一度クリックで削除を確定(元に戻せません)',
|
|
438
444
|
'note.deleted': '削除しました',
|
|
445
|
+
'note.deletedWarn': "削除しました(再起動までエンジンがまだ参照している可能性があります)",
|
|
439
446
|
'note.deletedLost': '削除しました(応答が途切れましたが、一覧から消えたことを確認しました)',
|
|
440
447
|
'note.compactConfirm': 'もう一度クリックで確定:先に履歴を圧縮してから削除します。どちらも元に戻せません',
|
|
448
|
+
'note.compacting': "圧縮中…(モデル呼び出しのため数十秒かかることがあります。このページを閉じないでください)",
|
|
449
|
+
'btn.compacting': "圧縮中…",
|
|
441
450
|
'note.compacted': function (m) { return '圧縮して削除しました。レビュー ' + m },
|
|
442
451
|
'err.request': function (p) { return 'リクエストの結果が返ってきません(' + p + ')' },
|
|
443
452
|
'cal.hint': '2 日をクリックで範囲選択、もう一度クリックで解除',
|
|
@@ -563,8 +572,11 @@ window.__ModuleLoader__.load({
|
|
|
563
572
|
'note.memDeleted': function (f) { return 'Revisión eliminada ' + f },
|
|
564
573
|
'note.deleteConfirm': 'Haz clic otra vez para confirmar la eliminación (no se puede deshacer)',
|
|
565
574
|
'note.deleted': 'Eliminado',
|
|
575
|
+
'note.deletedWarn': "Eliminado (el motor puede seguir teniéndolo referenciado hasta reiniciar)",
|
|
566
576
|
'note.deletedLost': 'Eliminado (se perdió la respuesta; la lista confirma que ya no está)',
|
|
567
577
|
'note.compactConfirm': 'Haz clic otra vez: primero se comprime la historia y luego se elimina; nada de eso se puede deshacer',
|
|
578
|
+
'note.compacting': "Comprimiendo… (llama al modelo y puede tardar; no cierres esta página)",
|
|
579
|
+
'btn.compacting': "Comprimiendo…",
|
|
568
580
|
'note.compacted': function (m) { return 'Comprimido y eliminado; revisión ' + m },
|
|
569
581
|
'err.request': function (p) { return 'No hubo respuesta de ' + p },
|
|
570
582
|
'cal.hint': 'Haz clic en dos días para elegir un rango; otro clic para borrarlo',
|
|
@@ -692,8 +704,11 @@ window.__ModuleLoader__.load({
|
|
|
692
704
|
'note.memDeleted': function (f) { return 'Revue supprimée ' + f },
|
|
693
705
|
'note.deleteConfirm': 'Cliquez encore pour confirmer la suppression (irréversible)',
|
|
694
706
|
'note.deleted': 'Supprimé',
|
|
707
|
+
'note.deletedWarn': "Supprimé (le moteur peut encore le référencer jusqu’au redémarrage)",
|
|
695
708
|
'note.deletedLost': 'Supprimé (la réponse s’est perdue ; la liste confirme qu’elle a disparu)',
|
|
696
709
|
'note.compactConfirm': 'Cliquez encore : l’historique est d’abord compressé, puis supprimé — les deux sont irréversibles',
|
|
710
|
+
'note.compacting': "Compactage… (appel au modèle, cela peut prendre du temps ; gardez cette page ouverte)",
|
|
711
|
+
'btn.compacting': "Compactage…",
|
|
697
712
|
'note.compacted': function (m) { return 'Compressé puis supprimé ; revue ' + m },
|
|
698
713
|
'err.request': function (p) { return 'Aucune réponse de ' + p },
|
|
699
714
|
'cal.hint': 'Cliquez sur deux jours pour choisir une plage ; cliquez encore pour effacer',
|
|
@@ -821,8 +836,11 @@ window.__ModuleLoader__.load({
|
|
|
821
836
|
'note.memDeleted': function (f) { return 'Review gelöscht: ' + f },
|
|
822
837
|
'note.deleteConfirm': 'Noch einmal klicken, um das Löschen zu bestätigen (nicht rückgängig zu machen)',
|
|
823
838
|
'note.deleted': 'Gelöscht',
|
|
839
|
+
'note.deletedWarn': "Gelöscht (der Motor kann bis zum Neustart noch darauf verweisen)",
|
|
824
840
|
'note.deletedLost': 'Gelöscht (die Antwort ging verloren; die Liste bestätigt, dass sie weg ist)',
|
|
825
841
|
'note.compactConfirm': 'Noch einmal klicken: erst wird der Verlauf komprimiert, dann gelöscht — beides ist unumkehrbar',
|
|
842
|
+
'note.compacting': "Komprimiere… (Modellaufruf, kann dauern; diese Seite bitte offen lassen)",
|
|
843
|
+
'btn.compacting': "Komprimiere…",
|
|
826
844
|
'note.compacted': function (m) { return 'Komprimiert und gelöscht; Review ' + m },
|
|
827
845
|
'err.request': function (p) { return 'Keine Antwort von ' + p },
|
|
828
846
|
'cal.hint': 'Zwei Tage anklicken, um einen Bereich zu wählen; erneut klicken zum Leeren',
|
|
@@ -950,8 +968,11 @@ window.__ModuleLoader__.load({
|
|
|
950
968
|
'note.memDeleted': function (f) { return 'Обзор удалён: ' + f },
|
|
951
969
|
'note.deleteConfirm': 'Нажмите ещё раз, чтобы подтвердить удаление (необратимо)',
|
|
952
970
|
'note.deleted': 'Удалено',
|
|
971
|
+
'note.deletedWarn': "Удалено (движок может помнить о нём до перезапуска)",
|
|
953
972
|
'note.deletedLost': 'Удалено (ответ потерялся; список подтверждает, что его больше нет)',
|
|
954
973
|
'note.compactConfirm': 'Нажмите ещё раз: сначала сжимается история, затем удаление — оба шага необратимы',
|
|
974
|
+
'note.compacting': "Сжатие… (вызов модели, это может занять время; не закрывайте страницу)",
|
|
975
|
+
'btn.compacting': "Сжатие…",
|
|
955
976
|
'note.compacted': function (m) { return 'Сжато и удалено; обзор ' + m },
|
|
956
977
|
'err.request': function (p) { return 'Нет ответа от ' + p },
|
|
957
978
|
'cal.hint': 'Нажмите на два дня, чтобы выбрать диапазон; ещё раз — чтобы сбросить',
|
|
@@ -1079,8 +1100,11 @@ window.__ModuleLoader__.load({
|
|
|
1079
1100
|
'note.memDeleted': function (f) { return 'Revisão excluída ' + f },
|
|
1080
1101
|
'note.deleteConfirm': 'Clique de novo para confirmar a exclusão (não dá para desfazer)',
|
|
1081
1102
|
'note.deleted': 'Excluído',
|
|
1103
|
+
'note.deletedWarn': "Excluído (o motor pode ainda referenciá-lo até reiniciar)",
|
|
1082
1104
|
'note.deletedLost': 'Excluído (a resposta se perdeu; a lista confirma que sumiu)',
|
|
1083
1105
|
'note.compactConfirm': 'Clique de novo: primeiro o histórico é compactado e depois excluído — nada disso pode ser desfeito',
|
|
1106
|
+
'note.compacting': "Comprimindo… (chama o modelo e pode demorar; mantenha esta página aberta)",
|
|
1107
|
+
'btn.compacting': "Comprimindo…",
|
|
1084
1108
|
'note.compacted': function (m) { return 'Compactado e excluído; revisão ' + m },
|
|
1085
1109
|
'err.request': function (p) { return 'Sem resposta de ' + p },
|
|
1086
1110
|
'cal.hint': 'Clique em dois dias para escolher um intervalo; clique de novo para limpar',
|
|
@@ -1524,6 +1548,8 @@ window.__ModuleLoader__.load({
|
|
|
1524
1548
|
var mp = React.useState(null); var memPick = mp[0], setMemPick = mp[1]
|
|
1525
1549
|
var mc = React.useState(''); var memConfirm = mc[0], setMemConfirm = mc[1]
|
|
1526
1550
|
var busy = React.useState(false); var isBusy = busy[0], setBusy = busy[1]
|
|
1551
|
+
// 0.5.3 本地修复:压缩要调模型、几十秒起步,界面上必须有「压缩中…」,否则看起来像没反应。
|
|
1552
|
+
var compactRun = React.useState(false); var isCompacting = compactRun[0], setCompactRun = compactRun[1]
|
|
1527
1553
|
var confirm = React.useState(''); var confirming = confirm[0], setConfirming = confirm[1]
|
|
1528
1554
|
// 已经请求过上下文的工作区。用它当守卫,不依赖服务器回传的 cwd,避免来回重试。
|
|
1529
1555
|
var ctxCwd = React.useRef('')
|
|
@@ -1890,8 +1916,10 @@ window.__ModuleLoader__.load({
|
|
|
1890
1916
|
setBusy(true); setErr(''); setNote(null); setConfirming('')
|
|
1891
1917
|
var target = selected.id
|
|
1892
1918
|
try {
|
|
1893
|
-
await post('delete', { sessionId: target })
|
|
1894
|
-
|
|
1919
|
+
var del = await post('delete', { sessionId: target })
|
|
1920
|
+
// 服务端带 warnings 时说明「删掉了,但引擎重启前可能还记着它」,别让提示骗人。
|
|
1921
|
+
showNote(del && Array.isArray(del.warnings) && del.warnings.length ? tr('note.deletedWarn') : tr('note.deleted'))
|
|
1922
|
+
setSelected(null)
|
|
1895
1923
|
await load()
|
|
1896
1924
|
} catch (e) {
|
|
1897
1925
|
var fresh = await load()
|
|
@@ -1907,19 +1935,21 @@ window.__ModuleLoader__.load({
|
|
|
1907
1935
|
if (!selected) return
|
|
1908
1936
|
if (confirming !== 'compact') { setConfirming('compact'); showNote(tr('note.compactConfirm')); return }
|
|
1909
1937
|
setBusy(true); setErr(''); setNote(null); setConfirming('')
|
|
1938
|
+
setCompactRun(true); showNote(tr('note.compacting'))
|
|
1910
1939
|
var target = selected.id
|
|
1911
1940
|
try {
|
|
1912
1941
|
var res = await post('compact-delete', { sessionId: target })
|
|
1913
1942
|
showNote(tr('note.compacted', res.memory)); setSelected(null)
|
|
1914
1943
|
await load()
|
|
1915
1944
|
} catch (e) {
|
|
1945
|
+
setNote(null)
|
|
1916
1946
|
var fresh2 = await load()
|
|
1917
1947
|
var alive2 = fresh2 !== null && (fresh2.workspaces || []).some(function (w) {
|
|
1918
1948
|
return (w.sessions || []).some(function (x) { return x.id === target })
|
|
1919
1949
|
})
|
|
1920
1950
|
if (fresh2 !== null && !alive2) { showNote(tr('note.deletedLost')); setSelected(null) }
|
|
1921
1951
|
else setErr(String(e.message || e))
|
|
1922
|
-
} finally { setBusy(false) }
|
|
1952
|
+
} finally { setBusy(false); setCompactRun(false) }
|
|
1923
1953
|
}
|
|
1924
1954
|
|
|
1925
1955
|
/**
|
|
@@ -2260,7 +2290,7 @@ window.__ModuleLoader__.load({
|
|
|
2260
2290
|
h('button', { style: !selected || isBusy ? S.btnOff : S.btnDanger, disabled: !selected || isBusy, onClick: doDelete },
|
|
2261
2291
|
confirming === 'delete' ? tr('btn.confirm') : tr('btn.delete')),
|
|
2262
2292
|
h('button', { style: !selected || isBusy ? S.btnOff : S.btn, disabled: !selected || isBusy, onClick: doCompactDelete },
|
|
2263
|
-
confirming === 'compact' ? tr('btn.confirmCompact') : tr('btn.deleteCompact'))
|
|
2293
|
+
isCompacting ? tr('btn.compacting') : (confirming === 'compact' ? tr('btn.confirmCompact') : tr('btn.deleteCompact')))
|
|
2264
2294
|
) : null
|
|
2265
2295
|
|
|
2266
2296
|
// 会话、回顾两页内容可能很长,仍走 .recall-scroll;选项页只四行,不要滚动框。
|
package/lib/core/index.js
CHANGED
|
@@ -475,7 +475,14 @@ export function apply(ctx, config = {}) {
|
|
|
475
475
|
sessions: webCtx.get('sessions'),
|
|
476
476
|
agents: webCtx.get('agents'),
|
|
477
477
|
workspaceRegistry: webCtx.get('workspaceRegistry'),
|
|
478
|
-
compaction: webCtx.get('compaction')
|
|
478
|
+
compaction: webCtx.get('compaction'),
|
|
479
|
+
// 0.5.3 本地修复:会话不在内存里时要 resume,宿主自己的组合入口才挂得上预设(含压缩)与模型。
|
|
480
|
+
sessionController: webCtx.get('sessionController'),
|
|
481
|
+
// 「删除并回顾」走 /compact 命令:压缩后端在预设隔离作用域里,只有命令处理器的 ctx 看得到。
|
|
482
|
+
commands: webCtx.get('commands'),
|
|
483
|
+
// 删完目录要让宿主索引忘掉它,否则设置页列表和搜索留幽灵。
|
|
484
|
+
sessionProjectionCache: webCtx.get('sessionProjectionCache'),
|
|
485
|
+
sessionQuery: webCtx.get('sessionQuery')
|
|
479
486
|
})
|
|
480
487
|
// 0.4.1:选项一落盘就同步工具,赶在下一次 systemPrompt.assemble() 之前。
|
|
481
488
|
// 0.4.6:切「清单词刷新时刻」那一下,把所有已记住的会话刷新成此刻的现词。
|
|
@@ -3,12 +3,47 @@
|
|
|
3
3
|
*
|
|
4
4
|
* 任何一步失败都不删,所以最坏情况是「压缩成功、拆失败、会话还在」——
|
|
5
5
|
* 代价是 compactNow 已经改写了历史,这一步不可逆。
|
|
6
|
+
*
|
|
7
|
+
* 0.5.3 本地修复(三处,都是 0.2.2 web profile 的部署形状逼出来的):
|
|
8
|
+
* 1. 压缩后端按预设隔离:profile 根上下文没有 compaction,「delete」以前必抛。
|
|
9
|
+
* 现在先问 agent 自己的上下文(预设插件是挂进 agent 作用域的)。
|
|
10
|
+
* 2. 会话不在内存里时要 resume;裸 resume 不会挂预设插件,也不带模型,
|
|
11
|
+
* 压缩会失败。优先走宿主自己的组合入口 sessionController.agents.resume(),
|
|
12
|
+
* 它会把预设(含压缩)挂进 agent 作用域并装上模型选择。
|
|
13
|
+
* 3. 每一步失败都留一行到 session-memory/_compact-delete.log,
|
|
14
|
+
* 否则设置页只有一句英文,谁也看不出卡在哪。
|
|
6
15
|
*/
|
|
7
16
|
|
|
17
|
+
import { appendFile, mkdir, readFile, stat, writeFile } from 'node:fs/promises'
|
|
18
|
+
import { join } from 'node:path'
|
|
8
19
|
import { listMemories } from '../core/tool.js'
|
|
20
|
+
import { captureCompaction } from '../core/store.js'
|
|
21
|
+
import { readLocaleSync } from '../core/locale.js'
|
|
9
22
|
import { deleteSessionPermanently } from './delete.js'
|
|
10
23
|
|
|
11
24
|
const TIMEOUT_MS = 120_000
|
|
25
|
+
const LOG_NAME = '_compact-delete.log'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 找出会话里最新的一条压缩事件(0.5.3 本地修复)。
|
|
29
|
+
*
|
|
30
|
+
* 事件监听挂在 profile 根上,压缩却在预设的隔离作用域里发生——那边发出来的
|
|
31
|
+
* session/event 未必传到根插件,于是「等拆解」会一直等到超时、什么都拆不出来。
|
|
32
|
+
* 与其猜监听收不收得到,不如压缩完自己回会话里把那条事件捞出来,直接拆。
|
|
33
|
+
* @param {object|undefined} session
|
|
34
|
+
* @returns {object|undefined}
|
|
35
|
+
*/
|
|
36
|
+
function latestCompactionEvent(session) {
|
|
37
|
+
try {
|
|
38
|
+
const end = typeof session?.seq === 'number' ? session.seq : undefined
|
|
39
|
+
if (end === undefined || typeof session.eventAt !== 'function') return undefined
|
|
40
|
+
for (let seq = end - 1; seq >= 0 && seq > end - 2000; seq--) {
|
|
41
|
+
const event = session.eventAt(seq)
|
|
42
|
+
if (event?.type === 'compaction/summary') return event
|
|
43
|
+
}
|
|
44
|
+
} catch { /* 读不到就不拆,交给后面「没有新回顾」的报错 */ }
|
|
45
|
+
return undefined
|
|
46
|
+
}
|
|
12
47
|
|
|
13
48
|
function withTimeout(promise, ms, text) {
|
|
14
49
|
return new Promise((yes, no) => {
|
|
@@ -17,8 +52,63 @@ function withTimeout(promise, ms, text) {
|
|
|
17
52
|
})
|
|
18
53
|
}
|
|
19
54
|
|
|
55
|
+
const message = (e) => (e instanceof Error ? e.message : String(e))
|
|
56
|
+
|
|
57
|
+
/** 一行诊断,失败也不遮住真正的报错。 */
|
|
58
|
+
async function note(dshHome, sessionId, text) {
|
|
59
|
+
try {
|
|
60
|
+
const dir = join(dshHome, 'session-memory')
|
|
61
|
+
await mkdir(dir, { recursive: true })
|
|
62
|
+
const file = join(dir, LOG_NAME)
|
|
63
|
+
// 日志不能无限长:超过 256 KB 就只留最后 64 KB(按整行切)。
|
|
64
|
+
try {
|
|
65
|
+
const info = await stat(file)
|
|
66
|
+
if (info.size > 256 * 1024) {
|
|
67
|
+
const kept = (await readFile(file, 'utf8')).slice(-64 * 1024)
|
|
68
|
+
const cut = kept.indexOf('\n')
|
|
69
|
+
await writeFile(file, cut >= 0 ? kept.slice(cut + 1) : kept)
|
|
70
|
+
}
|
|
71
|
+
} catch { /* 文件还没有就算了 */ }
|
|
72
|
+
await appendFile(file, new Date().toISOString() + ' ' + sessionId + ' ' + text + '\n')
|
|
73
|
+
} catch { /* 诊断写不出来就算了 */ }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 关掉我们自己拉起来的 agent;宿主没钩子就用拿到的句柄。 */
|
|
77
|
+
async function release(agent, handle) {
|
|
78
|
+
// 1) 插件自己抓到的句柄
|
|
79
|
+
try { if (handle !== undefined) return await handle.dispose() } catch { /* 落到自造 */ }
|
|
80
|
+
// 2) 没有句柄(例如经 sessionController 恢复的 agent):自己造一把,和删除路径同一套
|
|
81
|
+
try {
|
|
82
|
+
if (typeof agent?.cancel === 'function' && typeof agent.whenIdle === 'function'
|
|
83
|
+
&& typeof agent.scope?.dispose === 'function') {
|
|
84
|
+
agent.cancel({ kind: 'disposed' }, { keepInbox: true })
|
|
85
|
+
await agent.whenIdle()
|
|
86
|
+
await agent.scope.dispose()
|
|
87
|
+
}
|
|
88
|
+
} catch { /* 关不掉也不遮住真正的报错 */ }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 找一个能用的压缩后端。宿主把它挂在预设作用域里,根上下文看不见。
|
|
93
|
+
* @param {object} deps
|
|
94
|
+
* @param {object|undefined} agent
|
|
95
|
+
* @returns {{source:string, service:object}|null}
|
|
96
|
+
*/
|
|
97
|
+
function findCompaction(deps, agent) {
|
|
98
|
+
const seen = []
|
|
99
|
+
const tryOne = (source, service) => {
|
|
100
|
+
const usable = typeof service?.compactNow === 'function'
|
|
101
|
+
seen.push(source + (usable ? '' : '(no compactNow)'))
|
|
102
|
+
return usable ? { source, service } : null
|
|
103
|
+
}
|
|
104
|
+
const found = tryOne('deps.compaction', deps.compaction)
|
|
105
|
+
?? tryOne('agent.ctx', agent?.ctx?.get?.('compaction'))
|
|
106
|
+
?? tryOne('agent.loopCtx', agent?.loopCtx?.get?.('compaction'))
|
|
107
|
+
return found === null ? { seen } : found
|
|
108
|
+
}
|
|
109
|
+
|
|
20
110
|
/**
|
|
21
|
-
* @param {object} deps 含 persistence / sessions / agents / workspaceRegistry / compaction
|
|
111
|
+
* @param {object} deps 含 persistence / sessions / agents / workspaceRegistry / compaction / sessionController
|
|
22
112
|
* @param {string} dshHome
|
|
23
113
|
* @param {string} sessionId
|
|
24
114
|
* @param {(id:string, ms:number) => Promise<object>} waitForSplit 等这一轮拆解落盘
|
|
@@ -26,7 +116,6 @@ function withTimeout(promise, ms, text) {
|
|
|
26
116
|
*/
|
|
27
117
|
export async function compactThenDelete(deps, dshHome, sessionId, waitForSplit) {
|
|
28
118
|
if (typeof sessionId !== 'string' || sessionId === '') throw new Error('sessionId must be a non-empty string')
|
|
29
|
-
if (deps.compaction === undefined) throw new Error('the compaction service is unavailable; cannot delete')
|
|
30
119
|
|
|
31
120
|
const header = (await deps.persistence.list()).map((r) => r.header ?? r).find((h) => h.id === sessionId)
|
|
32
121
|
if (header === undefined) throw new Error('no such session: ' + sessionId)
|
|
@@ -38,39 +127,114 @@ export async function compactThenDelete(deps, dshHome, sessionId, waitForSplit)
|
|
|
38
127
|
let handle
|
|
39
128
|
let agent = deps.agents?.get(sessionId)
|
|
40
129
|
if (agent === undefined) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
if (
|
|
130
|
+
// 宿主自己的组合入口:预设插件(含压缩)与模型选择都挂进 agent 作用域。
|
|
131
|
+
const controller = deps.sessionController?.agents
|
|
132
|
+
if (typeof controller?.resume === 'function') {
|
|
133
|
+
try {
|
|
134
|
+
agent = await controller.resume(sessionId)
|
|
135
|
+
await note(dshHome, sessionId, 'resumed via sessionController')
|
|
136
|
+
} catch (error) {
|
|
137
|
+
await note(dshHome, sessionId, 'sessionController.resume failed: ' + message(error))
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (agent === undefined || agent === null) {
|
|
141
|
+
handle = await deps.agents.resume({ resumeSessionId: sessionId })
|
|
142
|
+
agent = handle?.agent
|
|
143
|
+
await note(dshHome, sessionId, 'resumed via agents.resume (bare, no preset mounted)')
|
|
144
|
+
if (agent === undefined) throw new Error('failed to resume the session; cannot delete')
|
|
145
|
+
}
|
|
146
|
+
} else {
|
|
147
|
+
await note(dshHome, sessionId, 'agent was already live')
|
|
44
148
|
}
|
|
45
149
|
|
|
150
|
+
// 压缩后端在预设的隔离作用域里,外面任何 ctx.get 都看不到。
|
|
151
|
+
// 但预设里那份 command-compact 是挂在全局命令表上的:让它替我们调,
|
|
152
|
+
// 它闭包里的 ctx 就在隔离作用域内,能看到 compaction。
|
|
153
|
+
void waitForSplit // 不再依赖事件监听:压缩完自己拆(见 latestCompactionEvent)
|
|
46
154
|
const controller = new AbortController()
|
|
47
|
-
const
|
|
155
|
+
const commands = deps.commands
|
|
48
156
|
|
|
49
|
-
let
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
157
|
+
let compacted = null
|
|
158
|
+
let result = null
|
|
159
|
+
if (typeof commands?.execute === 'function') {
|
|
160
|
+
try {
|
|
161
|
+
compacted = await withTimeout(
|
|
162
|
+
Promise.resolve(commands.execute(agent, '/compact', [], controller.signal)),
|
|
163
|
+
TIMEOUT_MS,
|
|
164
|
+
'compaction timed out'
|
|
165
|
+
)
|
|
166
|
+
} catch (error) {
|
|
167
|
+
controller.abort()
|
|
168
|
+
await note(dshHome, sessionId, '/compact threw: ' + message(error))
|
|
169
|
+
throw new Error('compaction failed, session not deleted: ' + message(error))
|
|
170
|
+
}
|
|
171
|
+
if (compacted === undefined) {
|
|
172
|
+
await note(dshHome, sessionId, '/compact is not registered for this session')
|
|
173
|
+
throw new Error('compaction is unavailable for this session (/compact is not registered), session not deleted')
|
|
174
|
+
}
|
|
175
|
+
const outcome = compacted.result ?? {}
|
|
176
|
+
await note(dshHome, sessionId, '/compact -> ' + outcome.kind + ': ' + (outcome.text ?? ''))
|
|
177
|
+
if (outcome.kind !== 'success') {
|
|
178
|
+
throw new Error('compaction failed, session not deleted: ' + (outcome.text ?? 'unknown error'))
|
|
179
|
+
}
|
|
180
|
+
if (/no compactable history/i.test(outcome.text ?? '')) {
|
|
181
|
+
throw new Error('no compactable history left, so there is nothing to review; use plain delete instead (session not deleted)')
|
|
182
|
+
}
|
|
183
|
+
} else {
|
|
184
|
+
const found = findCompaction(deps, agent)
|
|
185
|
+
if (found.service === undefined) {
|
|
186
|
+
await note(dshHome, sessionId, 'no compaction backend; looked at: ' + (found.seen ?? []).join(', '))
|
|
187
|
+
await release(agent, handle)
|
|
188
|
+
throw new Error('the compaction service is unavailable; cannot delete (no compaction backend is reachable from this session)')
|
|
189
|
+
}
|
|
190
|
+
await note(dshHome, sessionId, 'compaction from ' + found.source)
|
|
191
|
+
try {
|
|
192
|
+
result = await withTimeout(
|
|
193
|
+
Promise.resolve(found.service.compactNow(agent, controller.signal, 'session-seal-scripts-delete')),
|
|
194
|
+
TIMEOUT_MS,
|
|
195
|
+
'compaction timed out'
|
|
196
|
+
)
|
|
197
|
+
} catch (error) {
|
|
198
|
+
controller.abort()
|
|
199
|
+
await note(dshHome, sessionId, 'compactNow threw: ' + message(error))
|
|
200
|
+
throw new Error('compaction failed, session not deleted: ' + message(error))
|
|
201
|
+
}
|
|
202
|
+
if (result === null) {
|
|
203
|
+
await note(dshHome, sessionId, 'compactNow returned null (nothing to compact)')
|
|
204
|
+
throw new Error('no compactable history left, so there is nothing to review; use plain delete instead (session not deleted)')
|
|
205
|
+
}
|
|
59
206
|
}
|
|
60
|
-
|
|
207
|
+
await note(dshHome, sessionId, 'compaction finished')
|
|
61
208
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
209
|
+
// 自己拆:会话里那条 compaction/summary 就是回顾的原料。
|
|
210
|
+
const session = agent?.session
|
|
211
|
+
const event = latestCompactionEvent(session)
|
|
212
|
+
if (event === undefined) {
|
|
213
|
+
await note(dshHome, sessionId, 'no compaction/summary event on the session after compaction')
|
|
214
|
+
} else {
|
|
215
|
+
try {
|
|
216
|
+
const captured = await captureCompaction({ dshHome, cwd, session, event, lang: readLocaleSync(dshHome) })
|
|
217
|
+
await note(dshHome, sessionId, captured?.file
|
|
218
|
+
? 'captured review ourselves: ' + captured.file
|
|
219
|
+
: 'capture skipped: ' + (captured?.reason ?? 'no file'))
|
|
220
|
+
} catch (error) {
|
|
221
|
+
await note(dshHome, sessionId, 'self capture failed: ' + message(error))
|
|
222
|
+
}
|
|
66
223
|
}
|
|
67
224
|
|
|
68
225
|
const after = await listMemories(dshHome, cwd)
|
|
69
226
|
const fresh = after.entries.filter((e) => !before.has(e.file))
|
|
70
|
-
if (fresh.length === 0)
|
|
227
|
+
if (fresh.length === 0) {
|
|
228
|
+
await note(dshHome, sessionId, 'no new review file appeared')
|
|
229
|
+
throw new Error('compaction finished but produced no new review, session not deleted (nothing was removed)')
|
|
230
|
+
}
|
|
71
231
|
|
|
72
232
|
const target = fresh[fresh.length - 1]
|
|
73
233
|
const deleted = await deleteSessionPermanently(deps, sessionId)
|
|
74
|
-
if (!deleted.ok)
|
|
234
|
+
if (!deleted.ok) {
|
|
235
|
+
await note(dshHome, sessionId, 'delete after review failed: ' + deleted.error.message)
|
|
236
|
+
throw new Error('review was captured (' + target.file + ') but the delete failed: ' + deleted.error.message)
|
|
237
|
+
}
|
|
238
|
+
await note(dshHome, sessionId, 'deleted, review ' + target.file)
|
|
75
239
|
return { ok: true, deleted: sessionId, memory: target.file }
|
|
76
|
-
}
|
|
240
|
+
}
|
package/lib/host/delete.js
CHANGED
|
@@ -58,15 +58,38 @@ async function plainDirectory(dir) {
|
|
|
58
58
|
}
|
|
59
59
|
|
|
60
60
|
/**
|
|
61
|
-
*
|
|
61
|
+
* 关掉活会话。只用宿主公开的能力:agents.create/resume 返回的句柄 + cancel/whenIdle/flush。
|
|
62
|
+
* 拿不到句柄就拒绝,不猜——这是插件原本的语义,也是上游 DSH 唯一能保证的路径。
|
|
62
63
|
* @returns {Promise<{ok:true} | {ok:false, code:string, message:string}>}
|
|
63
64
|
*/
|
|
64
65
|
async function closeLive(deps, sessionId) {
|
|
65
66
|
const live = deps.sessions?.get(sessionId)
|
|
66
67
|
const agent = deps.agents?.get(sessionId)
|
|
67
68
|
if (live === undefined && agent === undefined) return { ok: true }
|
|
68
|
-
|
|
69
|
-
|
|
69
|
+
if (agent === undefined) {
|
|
70
|
+
return { ok: false, code: 'session-busy', message: 'this session is live in the engine but has no agent attached; close it in the app first, then delete' }
|
|
71
|
+
}
|
|
72
|
+
// 1) 宿主自带 teardown:够用时一步到底(cancel → whenIdle → 关作用域 → 落盘句柄 → detach)。
|
|
73
|
+
// 1) 插件在 agents.create/resume 上抓到的句柄。
|
|
74
|
+
const handle = ownedHandlesOf(agent);
|
|
75
|
+
if (handle === undefined) {
|
|
76
|
+
// 2) 没句柄就自己造一把:cancel → whenIdle → 关掉 agent 自己的作用域,全用 agent 上公开的成员。
|
|
77
|
+
// 摘注册表是宿主闭包里的动作,外面拿不到,所以删完可能留一条残留,用 leftover 标记回给调用方。
|
|
78
|
+
if (typeof agent.cancel !== 'function' || typeof agent.whenIdle !== 'function'
|
|
79
|
+
|| typeof agent.scope?.dispose !== 'function') {
|
|
80
|
+
return { ok: false, code: 'session-busy', message: 'the live session has no public handle available; let its owner stop it first, then delete' }
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
agent.cancel({ kind: 'disposed' }, { keepInbox: true })
|
|
84
|
+
await withTimeout(agent.whenIdle(), 'the agent did not become idle')
|
|
85
|
+
await withTimeout(agent.scope.dispose(), 'the agent scope did not close')
|
|
86
|
+
} catch (error) {
|
|
87
|
+
return { ok: false, code: 'session-busy', message: 'cannot shut this session down: ' + message(error) + '; the original logs are kept' }
|
|
88
|
+
}
|
|
89
|
+
const leftover = deps.agents.get(sessionId) !== undefined || deps.sessions.get(sessionId) !== undefined
|
|
90
|
+
return { ok: true, leftover }
|
|
91
|
+
}
|
|
92
|
+
if (agent.session !== live || typeof agent.cancel !== 'function'
|
|
70
93
|
|| typeof agent.whenIdle !== 'function' || typeof deps.sessions?.flush !== 'function') {
|
|
71
94
|
return { ok: false, code: 'session-busy', message: 'the live session has no public handle available; let its owner stop it first, then delete' }
|
|
72
95
|
}
|
|
@@ -112,6 +135,10 @@ export async function deleteSessionPermanently(deps, sessionId) {
|
|
|
112
135
|
|
|
113
136
|
const closed = await closeLive(deps, sessionId)
|
|
114
137
|
if (!closed.ok) return failure(409, closed.code, closed.message)
|
|
138
|
+
// 自己造的那把钥匙只能停住 agent;注册表摘除是宿主闭包里的动作,外面做不到。
|
|
139
|
+
const stopNote = closed.leftover === true
|
|
140
|
+
? 'the engine still holds a live reference to this session until it restarts'
|
|
141
|
+
: ''
|
|
115
142
|
|
|
116
143
|
const dir = sessionDirOf(root, header.cwd, sessionId)
|
|
117
144
|
if (!inside(resolve(root), dir)) return failure(500, 'delete-failed', 'the session directory escaped the storage root')
|
|
@@ -124,7 +151,8 @@ export async function deleteSessionPermanently(deps, sessionId) {
|
|
|
124
151
|
return failure(500, 'delete-failed', 'cannot delete the session log: ' + message(error))
|
|
125
152
|
}
|
|
126
153
|
|
|
127
|
-
const warnings = []
|
|
154
|
+
const warnings = stopNote === '' ? [] : [stopNote]
|
|
155
|
+
// 目录已删,让工作区把它从列表里摘掉(公开接口只有这一条)。
|
|
128
156
|
for (const workspace of workspaces) {
|
|
129
157
|
try { await workspace.detachSession(sessionId) }
|
|
130
158
|
catch (error) { warnings.push('workspace ' + workspace.id + ' still holds this session: ' + message(error)) }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-seal-scripts",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
|
@@ -16,10 +16,11 @@
|
|
|
16
16
|
"cordis.patch.yml",
|
|
17
17
|
"lib",
|
|
18
18
|
"README.md",
|
|
19
|
-
"LICENSE"
|
|
19
|
+
"LICENSE",
|
|
20
|
+
"README.en.md"
|
|
20
21
|
],
|
|
21
22
|
"peerDependencies": {
|
|
22
|
-
"@deepseek-ai/dsh": ">=0.2.
|
|
23
|
+
"@deepseek-ai/dsh": ">=0.2.2-rc.1 <1.0.0"
|
|
23
24
|
},
|
|
24
25
|
"peerDependenciesMeta": {
|
|
25
26
|
"@deepseek-ai/dsh": {
|