@xrn1997/dsh-session-delete 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +133 -173
- package/THIRD_PARTY_NOTICES.md +4 -2
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +119 -0
- package/docs/preview.zh.svg +117 -0
- package/docs/screenshots/screenshot-01.png +0 -0
- package/lib/client.js +4244 -2086
- package/lib/index.js +1237 -336
- package/lib/types/api/archive-rows.d.ts +20 -0
- package/lib/types/api/connection-route.d.ts +1 -1
- package/lib/types/api/route-table.d.ts +100 -11
- package/lib/types/client/archive-detail.d.ts +27 -0
- package/lib/types/client/archive-pane.d.ts +60 -0
- package/lib/types/client/archive-store.d.ts +6 -0
- package/lib/types/client/attachment-view.d.ts +0 -7
- package/lib/types/client/batch-bar.d.ts +3 -2
- package/lib/types/client/batch-confirm.d.ts +13 -4
- package/lib/types/client/batch-menu-item.d.ts +1 -1
- package/lib/types/client/batch-pick.d.ts +2 -1
- package/lib/types/client/config-settings.d.ts +2 -2
- package/lib/types/client/confirm-dialog.d.ts +2 -2
- package/lib/types/client/copy.d.ts +53 -13
- package/lib/types/client/detail-ledger.d.ts +23 -0
- package/lib/types/client/detail-pane.d.ts +33 -0
- package/lib/types/client/host-archive-watch.d.ts +22 -0
- package/lib/types/client/host-rows.d.ts +7 -0
- package/lib/types/client/maintenance-parts.d.ts +4 -3
- package/lib/types/client/maintenance-settings.d.ts +4 -3
- package/lib/types/client/notice.d.ts +16 -0
- package/lib/types/client/orphan-maintenance.d.ts +1 -1
- package/lib/types/client/receipt.d.ts +4 -1
- package/lib/types/client/remote.d.ts +38 -7
- package/lib/types/client/session-detail.d.ts +94 -0
- package/lib/types/client/session-list.d.ts +112 -0
- package/lib/types/client/settings-cards.d.ts +1 -1
- package/lib/types/client/subagent-section.d.ts +45 -0
- package/lib/types/client/trash-confirm.d.ts +2 -1
- package/lib/types/client/trash-detail.d.ts +9 -60
- package/lib/types/client/trash-nav.d.ts +8 -7
- package/lib/types/client/trash-panel.d.ts +1 -1
- package/lib/types/client/trash-snapshot.d.ts +10 -23
- package/lib/types/client/trash-view.d.ts +39 -9
- package/lib/types/client/ui/ErrorBoundary.d.ts +32 -0
- package/lib/types/client/ui/icons.d.ts +10 -4
- package/lib/types/client/undo-notices.d.ts +23 -3
- package/lib/types/client/undo-toast.d.ts +4 -1
- package/lib/types/client/use-archive-detail-reader.d.ts +28 -0
- package/lib/types/client/use-archive-panel-controller.d.ts +73 -0
- package/lib/types/client/use-archive-query.d.ts +29 -0
- package/lib/types/client/use-detail-rail.d.ts +48 -0
- package/lib/types/client/use-detail-reader.d.ts +71 -0
- package/lib/types/client/use-gated-refresh.d.ts +27 -0
- package/lib/types/client/{use-trash-selection.d.ts → use-list-selection.d.ts} +16 -14
- package/lib/types/client/use-maintenance.d.ts +11 -7
- package/lib/types/client/use-panel-selection.d.ts +38 -0
- package/lib/types/client/use-prompt-rail.d.ts +1 -1
- package/lib/types/client/use-trash-detail-reader.d.ts +14 -20
- package/lib/types/client/use-trash-panel-controller.d.ts +17 -5
- package/lib/types/client/write-seats.d.ts +80 -8
- package/lib/types/deps.d.ts +7 -4
- package/lib/types/{verbs/errors.d.ts → errors.d.ts} +1 -1
- package/lib/types/index.d.ts +1 -1
- package/lib/types/log/session-log.d.ts +22 -2
- package/lib/types/log/zstd-frames.d.ts +8 -1
- package/lib/types/ports/fs-port.d.ts +16 -4
- package/lib/types/ports/host-port.d.ts +89 -5
- package/lib/types/shared/session-path.d.ts +35 -0
- package/lib/types/shared/wire.d.ts +205 -27
- package/lib/types/trash/archive-detail.d.ts +27 -0
- package/lib/types/trash/attachments.d.ts +4 -1
- package/lib/types/trash/detail.d.ts +24 -1
- package/lib/types/trash/entry.d.ts +23 -8
- package/lib/types/trash/groups.d.ts +1 -0
- package/lib/types/trash/ledger.d.ts +4 -2
- package/lib/types/trash/projection-cache.d.ts +24 -0
- package/lib/types/trash/reconcile.d.ts +5 -3
- package/lib/types/trash/session-rows.d.ts +83 -0
- package/lib/types/trash/shrinking-view.d.ts +30 -0
- package/lib/types/verbs/batch-carried.d.ts +4 -2
- package/lib/types/verbs/live-admission.d.ts +7 -2
- package/lib/types/verbs/member-journal.d.ts +1 -1
- package/lib/types/verbs/permanent-removal.d.ts +15 -5
- package/lib/types/verbs/restore-session.d.ts +6 -4
- package/lib/types/verbs/trash-scope.d.ts +14 -13
- package/locale/en.json +7 -6
- package/locale/zh.json +2 -1
- package/package.json +10 -4
- package/lib/types/client/confirm-close.d.ts +0 -14
- package/lib/types/client/write-settlement.d.ts +0 -66
- package/lib/types/client/write.d.ts +0 -66
package/lib/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import { mkdir, readFile, readdir, realpath, rename, rm, stat } from "node:fs/promises";
|
|
1
|
+
import { mkdir, open, readFile, readdir, realpath, rename, rm, stat } from "node:fs/promises";
|
|
2
2
|
import path, { join, resolve } from "node:path";
|
|
3
3
|
import zlib from "node:zlib";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
//#region src/shared/wire.ts
|
|
6
6
|
/**
|
|
7
|
-
* 跨半 wire
|
|
7
|
+
* 跨半 wire 契约:前缀、端点、请求/响应形状与失败码。
|
|
8
8
|
* Node 半(src/api/dispatch.ts)与浏览器半(src/client/remote.ts)共用这一份,不各写字面量。
|
|
9
9
|
*
|
|
10
10
|
* 构建约束:本文件零运行时依赖、无 import;浏览器半把整个文件 inline 进 bundle。
|
|
11
11
|
* 信封 {ok:true,value} / {ok:false,error:{code,message,details?}} 也是两半的共同契约。
|
|
12
12
|
*/
|
|
13
13
|
/**
|
|
14
|
-
*
|
|
14
|
+
* 插件专属前缀(段名相对它命名)。
|
|
15
15
|
*
|
|
16
16
|
* 为什么必须带插件名:宿主 `connection.fetch.register` 对**重复的精确路径**直接抛错
|
|
17
17
|
* (`connection: exact Fetch route "…" is already registered`),撞了就是整棵插件树 boot 失败——
|
|
@@ -19,27 +19,31 @@ import { homedir } from "node:os";
|
|
|
19
19
|
*/
|
|
20
20
|
const SESSION_DELETE_API_PREFIX = "/dsh-session-delete-api";
|
|
21
21
|
/**
|
|
22
|
-
* 唯一的取数基础路径:宿主 `/api` +
|
|
22
|
+
* 唯一的取数基础路径:宿主 `/api` + 插件前缀。全部段名 exact Fetch 路由、客户端探测与附件 URL
|
|
23
23
|
* 都从它起;`SESSION_DELETE_API_PREFIX` 只作为段名的相对前缀与错误原文。
|
|
24
24
|
*/
|
|
25
25
|
const OFFICIAL_SESSION_DELETE_API_PREFIX = `/api${SESSION_DELETE_API_PREFIX}`;
|
|
26
|
-
/**
|
|
27
|
-
* 形状的一部分(ADR-0003),家就在这一张表——路由记录(`src/api/route-table.ts
|
|
28
|
-
*
|
|
26
|
+
/** 段名表(相对前缀)。**每项 `{ path, method, body }` 三键**:某段用什么方法、带什么请求体也是线上
|
|
27
|
+
* 形状的一部分(ADR-0003),家就在这一张表——路由记录(`src/api/route-table.ts`)经 `defineRoute`
|
|
28
|
+
* 从这一格派生 method / body(行里不写投影),浏览器半的取数通道(`src/client/remote.ts`)从同一格
|
|
29
29
|
* 投影路径与方法,两半都不逐段手写一份字面量。
|
|
30
30
|
* 写动作统一走一段 `/apply`:一次 HTTP 带一组 id、逐条回结果;
|
|
31
31
|
* 单条就是长度为 1 的批量,仓里不留第二条执行路径。
|
|
32
32
|
* - `list`:对账并读清单(`session-trash/` 里的目录是准)。
|
|
33
33
|
* - `ping`:最便宜的在/不在(不碰清册、不碰盘、不进链),供客户端探测。
|
|
34
34
|
* - `detail`:单条详情(用 POST 表达一个读,判据在 `src/api/route-table.ts` 的 detail 行)。
|
|
35
|
-
* - `apply`:批量执行一个动作(`delete` / `restore` / `purge` / `count` / `orphan-clean`),逐条回 `ApplyOutcome`。
|
|
35
|
+
* - `apply`:批量执行一个动作(`delete` / `restore` / `purge` / `count` / `orphan-clean` / `unarchive`),逐条回 `ApplyOutcome`。
|
|
36
36
|
* - `empty`:清空回收站(聚合回执,不按条回)。
|
|
37
|
-
* - `orphans
|
|
37
|
+
* - `orphans`:无主子会话的扫描报告(纯读)。清理走 `/apply` 的 `orphan-clean` 动作,
|
|
38
38
|
* 这一段只负责"有多少、在哪、多大"。
|
|
39
39
|
* - `attachment`:附件原始字节(全仓唯一的二进制响应段;按查询串寻址,失败仍回 JSON 信封)。
|
|
40
40
|
* - `attachmentOrphans`:无引用图片对象的扫描报告(纯读;数量/字节 + 供预览的对象清单)。
|
|
41
41
|
* - `attachmentClean`:清掉报告那一刻无引用的图片对象(聚合回执 `AttachmentCleanupWire`)。
|
|
42
|
-
* - `
|
|
42
|
+
* - `projectionOrphans`:无会话痕迹的投影缓存记录扫描报告(纯读;只念条数)。
|
|
43
|
+
* - `projectionClean`:清掉清理那一刻现扫出的无会话痕迹投影缓存记录(聚合回执 `ProjectionCacheCleanupWire`)。
|
|
44
|
+
* - `config`:三只可调项的读/写共用一段——空体读当前值,带字段写回 profile 的 patch 层。
|
|
45
|
+
* - `archiveList`:归档清单(registry 归档集 ∩ 语料,服务端一次算好行投影,纯读)。
|
|
46
|
+
* - `archiveDetail`:归档单条详情(POST 表达一个读;目标自己已归档,或是已归档根的 subagent 闭包成员,寻址只认 id)。 */
|
|
43
47
|
const ROUTES = {
|
|
44
48
|
list: {
|
|
45
49
|
path: "/list",
|
|
@@ -99,6 +103,32 @@ const ROUTES = {
|
|
|
99
103
|
path: "/attachment-clean",
|
|
100
104
|
method: "POST",
|
|
101
105
|
body: "none"
|
|
106
|
+
},
|
|
107
|
+
/** 纯读:宿主 `session_projcache` 里找不到会话痕迹(语料/持久化、清册 raw 行与回收站目录都不认)的记录条数。 */
|
|
108
|
+
projectionOrphans: {
|
|
109
|
+
path: "/projection-orphans",
|
|
110
|
+
method: "GET",
|
|
111
|
+
body: "none"
|
|
112
|
+
},
|
|
113
|
+
/** 聚合清理:按 raw 行 + 目录名现扫(不对账、不改写清册),只删这一刻仍找不到会话痕迹的记录(不信任旧报告)。 */
|
|
114
|
+
projectionClean: {
|
|
115
|
+
path: "/projection-clean",
|
|
116
|
+
method: "POST",
|
|
117
|
+
body: "none"
|
|
118
|
+
},
|
|
119
|
+
/** 纯读:归档清单(registry 归档集 ∩ 语料,服务端一次算好行投影)。 */
|
|
120
|
+
archiveList: {
|
|
121
|
+
path: "/archive-list",
|
|
122
|
+
method: "GET",
|
|
123
|
+
body: "none"
|
|
124
|
+
},
|
|
125
|
+
/** 归档单条详情(POST 表达一个读,判据在 `src/api/route-table.ts` 的 archiveDetail 行):
|
|
126
|
+
* 目标自己仍在归档集,**或**目标是 `rootSessionId` 那条已归档会话的 subagent 闭包成员;
|
|
127
|
+
* 不是通用会话正文通道。 */
|
|
128
|
+
archiveDetail: {
|
|
129
|
+
path: "/archive-detail",
|
|
130
|
+
method: "POST",
|
|
131
|
+
body: "sessionId"
|
|
102
132
|
}
|
|
103
133
|
};
|
|
104
134
|
/** 三只可调项的接受范围(闭区间整数)。Node 半的归一与浏览器半的表单共用这一格:
|
|
@@ -121,6 +151,11 @@ const CONFIG_LIMITS = {
|
|
|
121
151
|
* 附件段是 **query 参数**(GET 二进制响应,没有请求体)。 */
|
|
122
152
|
const PARAMS = {
|
|
123
153
|
entryId: "entryId",
|
|
154
|
+
/** `/archive-detail` 的寻址键(红线:路径字段不过线)。 */
|
|
155
|
+
sessionId: "sessionId",
|
|
156
|
+
/** 归档详情的**只读根**:看未归档子会话时带上那条已归档父会话的 id。
|
|
157
|
+
* 目标自己已归档时不需要;给了也只用于校验目标在该根的 subagent 闭包里。 */
|
|
158
|
+
rootSessionId: "rootSessionId",
|
|
124
159
|
/** `/detail` 的分页游标:只取这个块序号之前的块。缺省 = 从尾部取。 */
|
|
125
160
|
before: "before",
|
|
126
161
|
action: "action",
|
|
@@ -136,6 +171,27 @@ const PARAMS = {
|
|
|
136
171
|
attachmentWidth: "width",
|
|
137
172
|
attachmentHeight: "height"
|
|
138
173
|
};
|
|
174
|
+
/** 段名表每格 `body` → 那一段的字段组描述。空组 = 这一层没有要拦的字段:`none` / `query` 没有
|
|
175
|
+
* JSON 字段;`config` 的三只旋钮由 `src/verbs/config.ts` 的 Standard Schema 按自己的口径校验
|
|
176
|
+
* (未知键 / 非整数 / 越界都归它),路由层的字段闸故意不覆盖它——两处都拦就是两本账。 */
|
|
177
|
+
const BODY_GROUPS = {
|
|
178
|
+
none: {},
|
|
179
|
+
query: {},
|
|
180
|
+
config: {},
|
|
181
|
+
entry: {
|
|
182
|
+
[PARAMS.entryId]: "requiredString",
|
|
183
|
+
[PARAMS.before]: "optionalCursor"
|
|
184
|
+
},
|
|
185
|
+
apply: {
|
|
186
|
+
[PARAMS.action]: "action",
|
|
187
|
+
[PARAMS.ids]: "idArray"
|
|
188
|
+
},
|
|
189
|
+
sessionId: {
|
|
190
|
+
[PARAMS.sessionId]: "requiredString",
|
|
191
|
+
[PARAMS.before]: "optionalCursor",
|
|
192
|
+
[PARAMS.rootSessionId]: "optionalString"
|
|
193
|
+
}
|
|
194
|
+
};
|
|
139
195
|
/**
|
|
140
196
|
* 进程内判别「这已经是一次失败」——**按标记位认,不按 `instanceof`**(跨 realm / 跨 bundle 都不成立)。
|
|
141
197
|
* 位名与判法取自宿主网关客户端面的原文:
|
|
@@ -145,7 +201,7 @@ const PARAMS = {
|
|
|
145
201
|
* 本仓生产侧不造它:Node 半的 `toRemoteFailure`(`src/remote/map-error.ts`)只**消费**它,产出的
|
|
146
202
|
* `RemoteFailure` 是普通过线对象;浏览器半的取数通道**不抛失败、也不补标记**——信封原样当数据交回
|
|
147
203
|
* (`RemoteOutcome`),通道自己造的诊断(打不通 / 非信封 / 401·403)是普通失败对象,不进这条判别;
|
|
148
|
-
*
|
|
204
|
+
* 测试假件同样不认标记位:用例设的 `RemoteFailure` 原样交回组件(`tests/client/support/fake-remote.ts`)。
|
|
149
205
|
*/
|
|
150
206
|
function isDSHRemoteError(value) {
|
|
151
207
|
if (typeof value !== "object" || value === null) return false;
|
|
@@ -221,9 +277,12 @@ const FS_CORE_METHODS = [
|
|
|
221
277
|
/** 删除能力(目录 / 单文件):只挂在 `RemovalDeps` 与孤儿附件清理段上。 */
|
|
222
278
|
const FS_REMOVAL_METHODS = ["removeDir", "removeFile"];
|
|
223
279
|
/** 按名单从全量端口切一片(复制方法引用;端口方法都是属性、不读 `this`)。
|
|
224
|
-
* **运行期真的只带这些方法**:ADR-0032
|
|
280
|
+
* **运行期真的只带这些方法**:ADR-0032 的收窄不是类型投影。入参按 **K 的键集**收窄(不是整份
|
|
281
|
+
* `FsPort`):本函数只会读名单里的那几个键,而 `RemovalDeps` 那样已经切过一片的面(`RemovalFsPort`)
|
|
282
|
+
* 不必先长回全量面才能再切。 */
|
|
225
283
|
function fsSlice(port, keys) {
|
|
226
|
-
|
|
284
|
+
const source = port;
|
|
285
|
+
return Object.fromEntries(keys.map((key) => [key, source[key]]));
|
|
227
286
|
}
|
|
228
287
|
/** 模块级递归:端口方法**解构出来单独调**也不能靠 `this`(`{ sizeOfDir } = port` 会让方法体的
|
|
229
288
|
* `this` 变成 undefined)。所以端口只做转发,递归在模块作用域里自调。 */
|
|
@@ -290,6 +349,25 @@ function createFsPort() {
|
|
|
290
349
|
async readFile(p) {
|
|
291
350
|
return readFile(p);
|
|
292
351
|
},
|
|
352
|
+
/** 有界头读:开一次句柄、只读开头 `maxBytes` 字节(文件更短时 `read` 自己少给)。
|
|
353
|
+
* `maxBytes` 非正数按 0 处理——"读 0 字节"是合法请求,不是参数错误;路径不在时 `open` 照
|
|
354
|
+
* ENOENT 抛(缺席与读错误的判据仍归调用方 / `exists`,ADR-0039)。 */
|
|
355
|
+
async readFileHead(p, maxBytes) {
|
|
356
|
+
const handle = await open(p, "r");
|
|
357
|
+
try {
|
|
358
|
+
const cap = Math.max(0, Math.floor(maxBytes));
|
|
359
|
+
const buffer = Buffer.alloc(cap);
|
|
360
|
+
let offset = 0;
|
|
361
|
+
while (offset < cap) {
|
|
362
|
+
const { bytesRead } = await handle.read(buffer, offset, cap - offset, offset);
|
|
363
|
+
if (bytesRead === 0) break;
|
|
364
|
+
offset += bytesRead;
|
|
365
|
+
}
|
|
366
|
+
return buffer.subarray(0, offset);
|
|
367
|
+
} finally {
|
|
368
|
+
await handle.close();
|
|
369
|
+
}
|
|
370
|
+
},
|
|
293
371
|
async statFile(p) {
|
|
294
372
|
return { size: (await stat(p)).size };
|
|
295
373
|
},
|
|
@@ -299,7 +377,7 @@ function createFsPort() {
|
|
|
299
377
|
};
|
|
300
378
|
}
|
|
301
379
|
//#endregion
|
|
302
|
-
//#region src/
|
|
380
|
+
//#region src/errors.ts
|
|
303
381
|
/** 失败的**结构与措辞**。码本身、码的前缀读法与动词词表都住在 `shared/wire.ts`(ADR-0003):
|
|
304
382
|
* 浏览器半也要认它们,它们属于两半共同的契约,不属于 Node 半。这里只做动词抛错与回滚措辞。 */
|
|
305
383
|
function verbError(code, message, cause, details) {
|
|
@@ -636,30 +714,49 @@ function claimOf(original, current, id) {
|
|
|
636
714
|
};
|
|
637
715
|
}
|
|
638
716
|
//#endregion
|
|
717
|
+
//#region src/trash/shrinking-view.ts
|
|
718
|
+
/**
|
|
719
|
+
* 开工时把整批的原始快照捕下来(三态判据的「整批开始前的样子」),当前视图从它出发、按组收缩。
|
|
720
|
+
*
|
|
721
|
+
* 调用纪律:`take` / `takeAll` 都在动作**成功之后**才调——清完才收缩,失败时视图不动、下一次
|
|
722
|
+
* 重试还能看见这一组。`takeAll` 是清空那一支的**收缩到底**(purgeAll 用它),与摘掉某一条 id
|
|
723
|
+
* 的整组是两回事。
|
|
724
|
+
*
|
|
725
|
+
* 什么时候收缩、把实例放在哪里仍归调用方:本函数只持有原始与当前两份行,不记账。
|
|
726
|
+
*/
|
|
727
|
+
function createShrinkingView(rows) {
|
|
728
|
+
const original = rows;
|
|
729
|
+
let current = [...rows];
|
|
730
|
+
return {
|
|
731
|
+
claim: (id) => claimOf(original, current, id),
|
|
732
|
+
take: (id) => {
|
|
733
|
+
current = withoutGroup(current, id);
|
|
734
|
+
},
|
|
735
|
+
takeAll: () => {
|
|
736
|
+
current = [];
|
|
737
|
+
},
|
|
738
|
+
view: () => current
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
//#endregion
|
|
639
742
|
//#region src/verbs/batch-carried.ts
|
|
640
743
|
/**
|
|
641
744
|
* **同批已带走集**(「已被同批前一条带走」的 id)的唯一实现(ADR-0002 的内部实现)。
|
|
642
745
|
*
|
|
643
746
|
* 两种 id 域各一个 adapter:
|
|
644
|
-
* - entry 适配:restore 的条目 id,`claim` 是三态(fresh / carried / absent
|
|
645
|
-
* `trash/groups.ts
|
|
646
|
-
*
|
|
747
|
+
* - entry 适配:restore 的条目 id,`claim` 是三态(fresh / carried / absent)——薄壳,接在
|
|
748
|
+
* `src/trash/shrinking-view.ts` 的 `createShrinkingView` 上(持有机制在那边,判据仍读 `src/trash/groups.ts`,
|
|
749
|
+
* 不抄第二遍);
|
|
750
|
+
* - session 适配:delete 的会话 id,`claim` 只有 fresh / carried,集合由动词结果长出——没有原始
|
|
751
|
+
* 清册视图、也没有组可收缩,与收缩视图机制无关。
|
|
647
752
|
*
|
|
648
|
-
*
|
|
649
|
-
* 收缩中的当前只读视图不再外递:purge 那一半连同视图住「清册作用域」(`src/verbs/trash-scope.ts`)。
|
|
650
|
-
* 两个 adapter 只各自**持有**那份视图;按组收缩的判据不抄第二遍,都读 `groups.withoutGroup`。
|
|
753
|
+
* 收缩中的当前只读视图不外递:purge 那一半的实例住「清册作用域」(`src/verbs/trash-scope.ts`)。
|
|
651
754
|
*/
|
|
652
|
-
/** 恢复:原始快照认得、当前视图已经空了 ⇒
|
|
755
|
+
/** 恢复:原始快照认得、当前视图已经空了 ⇒ 同批前一条带走的。这里只接 entry 域的面,
|
|
756
|
+
* 持有与收缩都是 `src/trash/shrinking-view.ts` 的 `createShrinkingView` 那一份(多出的
|
|
757
|
+
* `takeAll` / `view` 不外递,返回值只按 `EntryBatchCarried` 看)。 */
|
|
653
758
|
function createEntryCarried(original) {
|
|
654
|
-
|
|
655
|
-
return {
|
|
656
|
-
claim(id) {
|
|
657
|
-
return claimOf(original, current, id);
|
|
658
|
-
},
|
|
659
|
-
take(id) {
|
|
660
|
-
current = withoutGroup(current, id);
|
|
661
|
-
}
|
|
662
|
-
};
|
|
759
|
+
return createShrinkingView(original);
|
|
663
760
|
}
|
|
664
761
|
/** 删除:会话 id 域;`take` 只收这次真的搬走的成员(父 + 盘上的孩子)。 */
|
|
665
762
|
function createSessionCarried() {
|
|
@@ -674,6 +771,57 @@ function createSessionCarried() {
|
|
|
674
771
|
};
|
|
675
772
|
}
|
|
676
773
|
//#endregion
|
|
774
|
+
//#region src/shared/session-path.ts
|
|
775
|
+
/**
|
|
776
|
+
* 宿主会话目录的**段编码**:`sessionId` → `sessions/<projectDir>/<段>` 里那一段。
|
|
777
|
+
*
|
|
778
|
+
* 这是宿主 `@deepseek-ai/dsh-session-persistence-jsonl` 的 `encodeSegment` 的逐字镜像(出处:asar 里
|
|
779
|
+
* `dsh-session-persistence-jsonl/src/format.ts`;同一文件的 `sessionDir` 就是它的调用点)。跨插件不能
|
|
780
|
+
* import 宿主源码,宿主也没把它暴露成服务,所以这一份是**镜像**而不是共享实现——宿主换代先复核算法。
|
|
781
|
+
*
|
|
782
|
+
* 为什么必须镜像:`SessionId` 是宿主未校验的品牌字符串,宿主在**任何文件系统调用之前**把它编成一段
|
|
783
|
+
* 安全目录名;本插件按 `sessions/<projectDir>/<段>` 找同一个目录(删除搬走、恢复放回、计划量字节)。
|
|
784
|
+
* 原始 id 拼路径在常见 id 上恰好同形(`session-<uuid>` 整段都在安全字母表里),一旦 id 含 `~`、空格或
|
|
785
|
+
* 非 ASCII 就会指向一个不存在的目录——删除报 not-found、计划量 0 字节,而那条会话其实还在盘上。
|
|
786
|
+
*
|
|
787
|
+
* 口径(与宿主逐字一致,不是口味):
|
|
788
|
+
* - **空串抛**(宿主原话 `cannot encode an empty path segment`):没有"空段"这种目录名;
|
|
789
|
+
* - 整段恰为 `.` / `..` 的**特判**先于逐码元循环:编成 `~002E` / `~002E~002E`,否则目录名会变成上跳;
|
|
790
|
+
* - `[A-Za-z0-9._-]` 码元原样保留;其余每个码元(**包括字面 `~` 自己**)编成 `~` + 4 位大写十六进制
|
|
791
|
+
* ⇒ `~XXXX` 无歧义(字面 `~` 是 `~007E`),且编码可逆;
|
|
792
|
+
* - 按 **UTF-16 码元**(不是码点)处理:孤立代理项也能原样往返——宿主的 `SessionId` 不做码点校验。
|
|
793
|
+
*
|
|
794
|
+
* **唯一调用点归 `src/trash/entry.ts`**:`sessionDirForId` / `sessionDirSegmentOf` 是仓内构造宿主会话
|
|
795
|
+
* 目录的两个口(路径与"写进条目 id 的段"),其余文件只消费**已编码段**——恢复照条目 id 里记下的段回放,
|
|
796
|
+
* 不拿 `sessionId` 再编一遍。
|
|
797
|
+
*
|
|
798
|
+
* **反解只给"目录是唯一线索"的两处**:对账重建(header 没有 `id` 时拿目录段反推会话 id)与投影缓存
|
|
799
|
+
* 的目录名保护(清册行缺失时按目录保护缓存)。恢复**不用**它:条目 id 里记着的段直接接回项目目录,
|
|
800
|
+
* 多一次编解码只会多一个会漂的判据。
|
|
801
|
+
*/
|
|
802
|
+
function encodeSessionSegment(raw) {
|
|
803
|
+
if (raw.length === 0) throw new Error("会话目录段不能为空:宿主 encodeSegment 对空串直接抛");
|
|
804
|
+
if (raw === ".") return "~002E";
|
|
805
|
+
if (raw === "..") return "~002E~002E";
|
|
806
|
+
let out = "";
|
|
807
|
+
for (let i = 0; i < raw.length; i++) {
|
|
808
|
+
const code = raw.charCodeAt(i);
|
|
809
|
+
const ch = String.fromCharCode(code);
|
|
810
|
+
if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) out += ch;
|
|
811
|
+
else out += `~${code.toString(16).toUpperCase().padStart(4, "0")}`;
|
|
812
|
+
}
|
|
813
|
+
return out;
|
|
814
|
+
}
|
|
815
|
+
/** {@link encodeSessionSegment} 的逆:把 `~XXXX` 还原成 UTF-16 码元。
|
|
816
|
+
* 编码是单射且字面 `~` 自己也编成 `~007E`,所以"每个 `~` + 4 位大写十六进制"都一定是转义。
|
|
817
|
+
* **已知歧义(刻意接受)**:编码前写下的存量条目 id 第二段是原始 session id,若它本身恰好含
|
|
818
|
+
* `a~007Eb` 这类文本,反解无法与编码产物区分——但编码前的删除只可能发生在**全安全字符**的 id 上
|
|
819
|
+
* (含 `~` 的 id 当时根本找不到目录),所以真实存量里不会出现这种段;手改目录是唯一来源,按反解
|
|
820
|
+
* 结果处理并接受误判。不含 `~XXXX` 形态的旧条目原样交回。 */
|
|
821
|
+
function decodeSessionSegment(encoded) {
|
|
822
|
+
return encoded.replace(/~([0-9A-F]{4})/g, (_whole, hex) => String.fromCharCode(parseInt(hex, 16)));
|
|
823
|
+
}
|
|
824
|
+
//#endregion
|
|
677
825
|
//#region src/trash/entry.ts
|
|
678
826
|
/**
|
|
679
827
|
* 清册里**每条记录都必须有**的那几格(`TrashEntry` 的非可选字段)——运行期校验器与「文件里真有的事实」
|
|
@@ -711,13 +859,17 @@ function entryWire(row) {
|
|
|
711
859
|
};
|
|
712
860
|
}
|
|
713
861
|
const pad = (n, w = 2) => String(n).padStart(w, "0");
|
|
714
|
-
|
|
862
|
+
/** 条目 id = 删除时刻 + **已编码的会话目录段**(宿主 `encodeSegment` 的产物,不是原始 session id)。
|
|
863
|
+
* 编码的唯一实现在 `src/shared/session-path.ts`;调用方拿段的方式归 {@link sessionDirSegmentOf}。 */
|
|
864
|
+
function makeEntryId(deletedAt, encodedSessionDirName) {
|
|
715
865
|
const d = new Date(deletedAt);
|
|
716
|
-
return `${`${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}T${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}Z`}-${
|
|
866
|
+
return `${`${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}T${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}Z`}-${encodedSessionDirName}`;
|
|
717
867
|
}
|
|
718
868
|
const ENTRY_ID_RE = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z-(.+)$/;
|
|
719
|
-
/** `makeEntryId`
|
|
720
|
-
*
|
|
869
|
+
/** `makeEntryId` 的逆。交回的 `sessionDirName` 是**已编码目录段**:恢复拿它原地放回,不再解码回
|
|
870
|
+
* session id(宿主编码是单射,从这里反推原始 id 既不需要也不该做)。时间戳按 UTC 拆字段再
|
|
871
|
+
* `Date.UTC` 合回——不交给 `Date.parse` 去猜(`20260930T130500Z` 不是任何被承认的日期格式,
|
|
872
|
+
* 猜出来的是 NaN)。 */
|
|
721
873
|
function parseEntryId(id) {
|
|
722
874
|
const m = ENTRY_ID_RE.exec(id);
|
|
723
875
|
if (!m) throw new Error(`bad entry id: ${id}`);
|
|
@@ -740,12 +892,25 @@ function assertSingleSegment(value, label, allowEmpty = false) {
|
|
|
740
892
|
}
|
|
741
893
|
if (!isSinglePathSegment(value)) throw new Error(`${label} 不是单段路径:${value}`);
|
|
742
894
|
}
|
|
743
|
-
/** `
|
|
895
|
+
/** sessionId → 宿主会话目录 `sessions/<projectDir>/` 下那一段(`encodeSegment` 的**唯一调用点**)。
|
|
896
|
+
* 删除写条目 id 与 {@link sessionDirForId} 都从这里拿段:编码只发生一次,两种用途不会各编一套。 */
|
|
897
|
+
function sessionDirSegmentOf(sessionId) {
|
|
898
|
+
return encodeSessionSegment(sessionId);
|
|
899
|
+
}
|
|
900
|
+
/** `sessionDirName` 是**已编码目录段**(宿主 `encodeSegment` 的产物,`sessions/<projectDir>/` 下那一段;
|
|
901
|
+
* 不是原始 session id——拿原始 id 拼路径见 `src/shared/session-path.ts` 的头注)。
|
|
902
|
+
* 允许空串:恢复的预检用它取**项目根**(`sessions/<projectDir>`),不是会话目录。 */
|
|
744
903
|
function sessionDirOf(projectDir, sessionDirName, home) {
|
|
745
904
|
assertSingleSegment(projectDir, "项目目录名");
|
|
746
905
|
assertSingleSegment(sessionDirName, "会话目录名", true);
|
|
747
906
|
return `${home}/sessions/${projectDir}/${sessionDirName}`;
|
|
748
907
|
}
|
|
908
|
+
/** 原始 sessionId 的直接落点:先经 {@link sessionDirSegmentOf} 编成宿主目录段,再拼路径。
|
|
909
|
+
* 需要同时拿路径与条目 id 的调用方(删除成员)先取段、再分别交给 {@link sessionDirOf} /
|
|
910
|
+
* {@link makeEntryId},别编两遍。 */
|
|
911
|
+
function sessionDirForId(projectDir, sessionId, home) {
|
|
912
|
+
return sessionDirOf(projectDir, sessionDirSegmentOf(sessionId), home);
|
|
913
|
+
}
|
|
749
914
|
function trashDirOf(entryId, home) {
|
|
750
915
|
assertSingleSegment(entryId, "回收站条目 id");
|
|
751
916
|
return `${home}/${TRASH_DIR_NAME}/${entryId}`;
|
|
@@ -819,7 +984,7 @@ async function stepUndo(label, run) {
|
|
|
819
984
|
}
|
|
820
985
|
/**
|
|
821
986
|
* **组级回滚**:把已经做成的成员按相反顺序退回;某一步退不干净时把失败并进原错误的
|
|
822
|
-
* `details.rollbackFailures`,绝不让原错误独走。那些失败句子的合并与措辞住 `src/
|
|
987
|
+
* `details.rollbackFailures`,绝不让原错误独走。那些失败句子的合并与措辞住 `src/errors.ts`;
|
|
823
988
|
* 删除与恢复两个按组走的动词共用这一处。
|
|
824
989
|
*/
|
|
825
990
|
async function rollbackJournals(journals, error) {
|
|
@@ -948,14 +1113,14 @@ function deleteSession(deps) {
|
|
|
948
1113
|
const parentProjectDir = await deps.host.projectDirOf(sessionId);
|
|
949
1114
|
if (parentProjectDir === void 0) throw verbError("not-found", `宿主的持久化里没有这个会话:${sessionId}`);
|
|
950
1115
|
await assertNoLive(deps.host, [sessionId, ...kids.map((kid) => kid.sessionId)]);
|
|
951
|
-
const parentDir =
|
|
1116
|
+
const parentDir = sessionDirForId(parentProjectDir, sessionId, deps.home);
|
|
952
1117
|
if (!await deps.fs.exists(parentDir)) throw verbError("not-found", `会话目录不存在:${parentDir}`);
|
|
953
1118
|
const parent = {
|
|
954
1119
|
sessionId,
|
|
955
1120
|
projectDir: parentProjectDir
|
|
956
1121
|
};
|
|
957
1122
|
const members = [parent];
|
|
958
|
-
for (const kid of kids) if (await deps.fs.exists(
|
|
1123
|
+
for (const kid of kids) if (await deps.fs.exists(sessionDirForId(kid.projectDir, kid.sessionId, deps.home))) members.push({
|
|
959
1124
|
sessionId: kid.sessionId,
|
|
960
1125
|
projectDir: kid.projectDir
|
|
961
1126
|
});
|
|
@@ -992,11 +1157,13 @@ function deleteSession(deps) {
|
|
|
992
1157
|
async function memberMove(deps, presence, member, deletedAt, parentEntryId) {
|
|
993
1158
|
const { sessionId, projectDir } = member;
|
|
994
1159
|
const workspaceId = await deps.host.workspaceOf(sessionId);
|
|
995
|
-
const
|
|
1160
|
+
const sessionDirName = sessionDirSegmentOf(sessionId);
|
|
1161
|
+
const sessionDir = sessionDirOf(projectDir, sessionDirName, deps.home);
|
|
996
1162
|
const wasArchived = await deps.host.isArchived(sessionId);
|
|
997
|
-
const
|
|
1163
|
+
const entryId = makeEntryId(deletedAt, sessionDirName);
|
|
1164
|
+
const trashDir = trashDirOf(entryId, deps.home);
|
|
998
1165
|
const entry = {
|
|
999
|
-
id:
|
|
1166
|
+
id: entryId,
|
|
1000
1167
|
sessionId,
|
|
1001
1168
|
projectDir,
|
|
1002
1169
|
workspaceId: workspaceId ?? "",
|
|
@@ -1134,11 +1301,16 @@ function withFrameTail(raw, at) {
|
|
|
1134
1301
|
* 把 `raw` 切成帧区间。
|
|
1135
1302
|
* @throws 起始处不是 magic、或某帧算到的末位既不是下一帧帧头也不是 EOF——**一律抛**,
|
|
1136
1303
|
* 绝不"尽力往下解":切错帧的后果是把半截压缩体当解压输入,那时解出来的东西不可信。
|
|
1304
|
+
*
|
|
1305
|
+
* `tolerateTruncatedTail` 只给**前缀读**(`readFileHead` 的有界头读):输入是某个合法日志的开头
|
|
1306
|
+
* 一段,尾巴必然可能切在帧中间,这时"少最后一帧"不叫损坏。解析到切坏的尾巴就停,返回已经切出的
|
|
1307
|
+
* 完整帧;中间的损坏也会让它提前停——但头读只需要最前面那几帧(header 在第一帧),够用。
|
|
1308
|
+
* **默认仍是严格**:读整本的调用方拿到截断文件必须抛,不能把半份日志当完整日志。
|
|
1137
1309
|
*/
|
|
1138
|
-
function frameRanges(raw) {
|
|
1310
|
+
function frameRanges(raw, options = {}) {
|
|
1139
1311
|
const ranges = [];
|
|
1140
1312
|
let at = 0;
|
|
1141
|
-
while (at < raw.length) {
|
|
1313
|
+
while (at < raw.length) try {
|
|
1142
1314
|
if (!isMagicAt(raw, at)) throw new Error(`zstd 帧头缺席:偏移 ${at} 处不是 magic(前面第 ${ranges.length} 帧的边界算歪了?)`);
|
|
1143
1315
|
const descriptor = raw[at + 4];
|
|
1144
1316
|
if (descriptor === void 0) throw new Error(`zstd 帧头不完整:偏移 ${at} 之后不足 ${AFTER_DESCRIPTOR} 字节`);
|
|
@@ -1167,6 +1339,9 @@ function frameRanges(raw) {
|
|
|
1167
1339
|
end: cursor
|
|
1168
1340
|
});
|
|
1169
1341
|
at = cursor;
|
|
1342
|
+
} catch (error) {
|
|
1343
|
+
if (options.tolerateTruncatedTail === true) return ranges;
|
|
1344
|
+
throw error;
|
|
1170
1345
|
}
|
|
1171
1346
|
return ranges;
|
|
1172
1347
|
}
|
|
@@ -1189,6 +1364,19 @@ function frameRanges(raw) {
|
|
|
1189
1364
|
*/
|
|
1190
1365
|
const NEWLINE = 10;
|
|
1191
1366
|
/**
|
|
1367
|
+
* 单条会话日志**整本读取**的显式上限(256 MiB)。
|
|
1368
|
+
*
|
|
1369
|
+
* 逐帧解压把内存口径压在"最大那一帧的明文",但 `readFile` 本身仍会把整本字节读进内存;日志大小
|
|
1370
|
+
* 没有宿主上限,坏文件 / 巨型工具输出可以把它撑到任意大。凡是"读整本"的解码路(回收站详情、
|
|
1371
|
+
* 附件引用扫描)都先 stat 再读,超过这个量级就按**读不出**处理——不截断、不猜:
|
|
1372
|
+
* - 详情抛 `io` + 原文(读者至少知道它有多大、为什么打不开);
|
|
1373
|
+
* - 引用扫描按 `unreadable` 跳过(fail closed,宁可留孤儿也不删共享,ADR-0020)。
|
|
1374
|
+
*
|
|
1375
|
+
* 取值只住这一处:两个消费方引用同一个数,别各写一份。"读整本"的对立面是 `readFileHead` 那种
|
|
1376
|
+
* 有界头读(对账只读 header,不该为一行付整本内存)。
|
|
1377
|
+
*/
|
|
1378
|
+
const MAX_SESSION_LOG_BYTES = 268435456;
|
|
1379
|
+
/**
|
|
1192
1380
|
* 宿主给每一代日志的词法(逐字取自 `@deepseek-ai/dsh-session-format@0.2.0-rc.2` 的
|
|
1193
1381
|
* `CANONICAL_LOG_FILENAME`,剥掉压缩后缀那段由我们自己在正则里补上 `.zstd`):
|
|
1194
1382
|
* 裸名 `session.jsonl` 是**第 0 代**,往后是 `session.vN`;`.v0`、前导零、大写、临时名都不是规范名。
|
|
@@ -1223,8 +1411,11 @@ function pickSessionLog(names) {
|
|
|
1223
1411
|
*
|
|
1224
1412
|
* 回调返回 `false` = **提前停机**(后面的帧不再解——`readSessionHeader` 只要第一行)。
|
|
1225
1413
|
* 停机后 `stats` 只是停机前那部分,别拿来做全量对账。
|
|
1414
|
+
*
|
|
1415
|
+
* `tolerateTruncatedTail` 只给**前缀读**用(对账的有界头读):尾巴切在帧中间时丢掉不完整的那一帧,
|
|
1416
|
+
* 前面的完整帧照常走。读整本的调用方不传——截断文件必须响亮失败,见 `frameRanges` 的注释。
|
|
1226
1417
|
*/
|
|
1227
|
-
function walkSessionLog(raw, onRecord) {
|
|
1418
|
+
function walkSessionLog(raw, onRecord, options = {}) {
|
|
1228
1419
|
const stats = {
|
|
1229
1420
|
frames: 0,
|
|
1230
1421
|
records: 0,
|
|
@@ -1246,7 +1437,7 @@ function walkSessionLog(raw, onRecord) {
|
|
|
1246
1437
|
};
|
|
1247
1438
|
/** 上一帧没闭合的那一行。**存字节不存字符**:切在多字节字符中间的帧要拼回完整才解得对。 */
|
|
1248
1439
|
let carry = Buffer.alloc(0);
|
|
1249
|
-
for (const { start, end } of frameRanges(raw)) {
|
|
1440
|
+
for (const { start, end } of frameRanges(raw, options)) {
|
|
1250
1441
|
if (stopped) break;
|
|
1251
1442
|
stats.frames += 1;
|
|
1252
1443
|
let plain;
|
|
@@ -1277,13 +1468,13 @@ function walkSessionLog(raw, onRecord) {
|
|
|
1277
1468
|
* (不要求它恰是第一个可解析行:坏一行前缀不该让整条日志判不出身份)。
|
|
1278
1469
|
* 找不到(空日志 / 全是别种记录)回 `undefined`;帧坏了照抛——那是"读不出来",与"没有 header"是两件事。
|
|
1279
1470
|
*/
|
|
1280
|
-
function readSessionHeader(raw) {
|
|
1471
|
+
function readSessionHeader(raw, options = {}) {
|
|
1281
1472
|
let header;
|
|
1282
1473
|
walkSessionLog(raw, (record) => {
|
|
1283
1474
|
if (record.type !== "session") return;
|
|
1284
1475
|
header = record;
|
|
1285
1476
|
return false;
|
|
1286
|
-
});
|
|
1477
|
+
}, options);
|
|
1287
1478
|
return header;
|
|
1288
1479
|
}
|
|
1289
1480
|
//#endregion
|
|
@@ -1380,20 +1571,38 @@ function scanImageIdsInLog(raw) {
|
|
|
1380
1571
|
...damaged === void 0 ? {} : { damaged }
|
|
1381
1572
|
};
|
|
1382
1573
|
}
|
|
1383
|
-
/** 宿主写日志时的临时名:`session.vN.jsonl.zstd.<hash>.tmp`(内容写完后才 rename 成规范名)。
|
|
1574
|
+
/** 宿主写日志时的临时名:`session.vN.jsonl.zstd.<hash>.tmp`(内容写完后才 rename 成规范名)。
|
|
1575
|
+
* 出处:asar `dsh-session-persistence-jsonl/src/index.ts` 的 `writeSyncedTempFile`:
|
|
1576
|
+
* `` `${finalPath}.${randomBytes(6).toString('hex')}.tmp` ``。 */
|
|
1384
1577
|
const TEMP_LOG_NAME = /^session(?:\.v[1-9][0-9]*)?\.jsonl(?:\.zstd)?\.[0-9a-f]+\.tmp$/u;
|
|
1385
1578
|
/**
|
|
1579
|
+
* 宿主**格式迁移**的暂存名:`session.migration.<token>.jsonl[.zstd].tmp`。出处:asar
|
|
1580
|
+
* `dsh-session-persistence-jsonl/src/generation.ts` 的 `writeSyncedTemp`
|
|
1581
|
+
* (`` `session.migration.${internals.randomToken()}${suffix}.tmp` ``,`randomToken` 是十六进制;
|
|
1582
|
+
* `suffix` 是 `logSuffix(compression)` = `.jsonl.zstd` 或 `.jsonl`——**不是**裸 `.zstd`)。
|
|
1583
|
+
* 它是"把历史代迁移成当代、发布前先落盘"的那份暂存。
|
|
1584
|
+
*
|
|
1585
|
+
* 与普通临时日志的差别决定了它**可以**在有规范日志时被忽略:迁移暂存是**同一会话历史日志的完整拷贝**
|
|
1586
|
+
* (header + 全部事件),而它存在的前提是历史规范日志还在原处(宿主就是照着它迁移的)——那份可读的
|
|
1587
|
+
* 规范日志已经覆盖了它的全部引用。写盘临时日志(`TEMP_LOG_NAME`)相反:它可能装着还没进规范日志的
|
|
1588
|
+
* 新记录,非空就算不可读。**没有规范日志时它仍按不可读 fail closed**(`imageIdsOfDir` 的
|
|
1589
|
+
* "只有临时名"那条捷径只认 `TEMP_LOG_NAME`,迁移暂存不在其中)。 */
|
|
1590
|
+
const MIGRATION_TEMP_LOG_NAME = /^session\.migration\.[0-9a-f]+\.jsonl(?:\.zstd)?\.tmp$/u;
|
|
1591
|
+
/**
|
|
1386
1592
|
* 宿主的内核写锁:宿主以写方式打开它即截断、**从不写入内容**、释放也从不删除(POSIX 上是
|
|
1387
1593
|
* `flock(2)` 的目标,Windows 上没有这个文件)——所以每个已实体化的会话目录、以及跟着搬进
|
|
1388
1594
|
* 回收站的条目里,它都与日志常态并存。锁只表达"谁在写",不承载会话记录。
|
|
1389
1595
|
*/
|
|
1390
1596
|
const LOCK_NAME = "session.lock";
|
|
1391
|
-
/**
|
|
1392
|
-
*
|
|
1597
|
+
/** 规范日志之外允许并存的几类文件:更老一代的规范日志(新代包含旧代)、0 字节临时日志(没有消息),
|
|
1598
|
+
* 以及宿主的**格式迁移暂存**(同一会话历史日志的完整拷贝,可读规范日志已覆盖它的引用——判据见
|
|
1599
|
+
* {@link MIGRATION_TEMP_LOG_NAME})。其余任何文件都可能是规范日志没覆盖到的引用(例如写入中的非空
|
|
1600
|
+
* 临时日志),一律按不可读处理。
|
|
1393
1601
|
* 宿主的 `session.lock` 到不了这里——它在 `imageIdsOfDir` 挑名单时就按"不是会话内容"剥掉了。 */
|
|
1394
1602
|
async function unreadableExtraFile(deps, dir, names) {
|
|
1395
1603
|
for (const name of names) {
|
|
1396
1604
|
if (isCanonicalSessionLogName(name)) continue;
|
|
1605
|
+
if (MIGRATION_TEMP_LOG_NAME.test(name)) continue;
|
|
1397
1606
|
if (!TEMP_LOG_NAME.test(name)) return `${dir}: 规范日志旁还有无法确认的文件 ${name}`;
|
|
1398
1607
|
if ((await deps.fs.statFile(`${dir}/${name}`)).size > 0) return `${dir}: 规范日志旁还有非空临时日志 ${name}`;
|
|
1399
1608
|
}
|
|
@@ -1404,7 +1613,10 @@ async function unreadableExtraFile(deps, dir, names) {
|
|
|
1404
1613
|
* **有规范日志但目录里还有子目录也不够**:日志只覆盖本目录,子目录里的引用读它看不见——
|
|
1405
1614
|
* 同样按不可读处理(宁可留下对象等维护卡兜底,不冒"没引用")。
|
|
1406
1615
|
* **规范日志旁的文件也要过关**:老一代规范日志可以并存(新代包含旧代);0 字节临时日志是
|
|
1407
|
-
*
|
|
1616
|
+
* 写盘未完成的空产物,也没有引用;格式迁移暂存是同一历史日志的完整拷贝,规范日志可读时忽略它。
|
|
1617
|
+
* 非空临时日志、明文日志或其他任何文件仍按不可读处理(fail closed)。
|
|
1618
|
+
* **整本日志读取有上限**(`MAX_SESSION_LOG_BYTES`):超过就按不可读处理,不为一份读不完的引用源
|
|
1619
|
+
* 把整本字节压进内存,更不把它折成"没有引用"。
|
|
1408
1620
|
* **宿主的内核写锁不是会话内容**:0 字节的锁在判目录形状之前先剥掉——不然每个已实体化的会话目录
|
|
1409
1621
|
* (含搬进回收站的条目)都会被读成"读不懂",整份引用扫描在真机上恒跳过;没有日志的锁目录因此与
|
|
1410
1622
|
* 空目录同判。非空的锁说明我们对这个文件的理解失效(宿主不会往里写字节),仍按不可读处理。
|
|
@@ -1482,7 +1694,13 @@ async function imageIdsOfDir(deps, dir) {
|
|
|
1482
1694
|
ids: /* @__PURE__ */ new Set(),
|
|
1483
1695
|
unreadable: `${dir}: 目录里还有子目录,规范日志覆盖不到它们`
|
|
1484
1696
|
};
|
|
1485
|
-
const
|
|
1697
|
+
const logPath = `${dir}/${log}`;
|
|
1698
|
+
const logSize = (await deps.fs.statFile(logPath)).size;
|
|
1699
|
+
if (logSize > 268435456) return {
|
|
1700
|
+
ids: /* @__PURE__ */ new Set(),
|
|
1701
|
+
unreadable: `${logPath}: 日志 ${logSize} 字节超过整本读取上限 ${MAX_SESSION_LOG_BYTES} 字节,未扫描`
|
|
1702
|
+
};
|
|
1703
|
+
const scan = scanImageIdsInLog(await deps.fs.readFile(logPath));
|
|
1486
1704
|
if (scan.damaged !== void 0) return {
|
|
1487
1705
|
ids: /* @__PURE__ */ new Set(),
|
|
1488
1706
|
unreadable: `${dir}/${log}: ${scan.damaged}`
|
|
@@ -1763,6 +1981,228 @@ async function cleanOrphanImageAttachments(deps) {
|
|
|
1763
1981
|
};
|
|
1764
1982
|
return executeImageAttachmentRemoval(deps, plan);
|
|
1765
1983
|
}
|
|
1984
|
+
/** 批量面:三个读面各读一次、零逐行读。`ids` 是调用方要显示的那批行;大小读面抛错按策略
|
|
1985
|
+
* 折成整档缺席(null)或原样上抛(见 {@link RowReadPolicy})。 */
|
|
1986
|
+
async function readRowSurfaces(deps, ids, policy) {
|
|
1987
|
+
return {
|
|
1988
|
+
titles: await deps.host.titleSnapshots(ids),
|
|
1989
|
+
activity: await deps.host.sessionActivity(),
|
|
1990
|
+
sizes: await sizesOf(deps, policy)
|
|
1991
|
+
};
|
|
1992
|
+
}
|
|
1993
|
+
/** 逐行面:旧宿主标题回退与 label 共用同一份有界并发({@link ROW_READ_CONCURRENCY}),
|
|
1994
|
+
* 顺序与 `targets` 对齐、输出同序同长,缺席的格不落键。 */
|
|
1995
|
+
async function projectRowFacts(deps, surfaces, targets) {
|
|
1996
|
+
const cells = await mapLimit(targets, 8, async (target) => {
|
|
1997
|
+
return {
|
|
1998
|
+
title: surfaces.titles.available ? surfaces.titles.value.get(target.sessionId) ?? "" : await deps.host.titleOf(target.sessionId),
|
|
1999
|
+
label: target.wantsLabel === true ? await deps.host.labelOf(target.sessionId) : ""
|
|
2000
|
+
};
|
|
2001
|
+
});
|
|
2002
|
+
return targets.map((target, index) => {
|
|
2003
|
+
const { sessionId } = target;
|
|
2004
|
+
const promptAt = surfaces.activity.available ? surfaces.activity.value.get(sessionId) : void 0;
|
|
2005
|
+
const at = promptAt ?? target.createdAt;
|
|
2006
|
+
const sizeBytes = surfaces.sizes === null || !surfaces.sizes.available ? void 0 : surfaces.sizes.value.get(sessionId);
|
|
2007
|
+
const cell = cells[index];
|
|
2008
|
+
const label = cell?.label ?? "";
|
|
2009
|
+
return {
|
|
2010
|
+
sessionId,
|
|
2011
|
+
title: cell?.title ?? "",
|
|
2012
|
+
...label === "" ? {} : { label },
|
|
2013
|
+
...at === void 0 ? {} : {
|
|
2014
|
+
updatedAt: at,
|
|
2015
|
+
updatedAtSource: promptAt === void 0 ? "created" : "prompt"
|
|
2016
|
+
},
|
|
2017
|
+
...sizeBytes === void 0 ? {} : { sizeBytes }
|
|
2018
|
+
};
|
|
2019
|
+
});
|
|
2020
|
+
}
|
|
2021
|
+
/** 兼容包装:一次调用走「批量面 + 逐行面」(归档清单继续用它)。 */
|
|
2022
|
+
async function projectSessionRows(deps, targets, policy) {
|
|
2023
|
+
return projectRowFacts(deps, await readRowSurfaces(deps, targets.map((target) => target.sessionId), policy), targets);
|
|
2024
|
+
}
|
|
2025
|
+
/** 合计按 id 集合算(输出计划外的行也进合计):缺席按**传入的每个 id** 计数——读面缺席、
|
|
2026
|
+
* 或某 id 在表里没有值,都算缺。摘要条报的是全部孩子的和,不是已列前 N 条的。 */
|
|
2027
|
+
function sizeTotalsForIds(ids, sizes) {
|
|
2028
|
+
let totalBytes = 0;
|
|
2029
|
+
let missingSizeCount = 0;
|
|
2030
|
+
for (const id of ids) {
|
|
2031
|
+
const sizeBytes = sizes === null || !sizes.available ? void 0 : sizes.value.get(id);
|
|
2032
|
+
if (sizeBytes === void 0) missingSizeCount += 1;
|
|
2033
|
+
else totalBytes += sizeBytes;
|
|
2034
|
+
}
|
|
2035
|
+
return {
|
|
2036
|
+
totalBytes,
|
|
2037
|
+
missingSizeCount
|
|
2038
|
+
};
|
|
2039
|
+
}
|
|
2040
|
+
/** 大小的合计口径:只加已知的那几行,缺大小的行数单独报(副标题要念「N 条大小缺席」)。 */
|
|
2041
|
+
function sizeTotals(facts) {
|
|
2042
|
+
let totalBytes = 0;
|
|
2043
|
+
let missingSizeCount = 0;
|
|
2044
|
+
for (const fact of facts) if (fact.sizeBytes === void 0) missingSizeCount += 1;
|
|
2045
|
+
else totalBytes += fact.sizeBytes;
|
|
2046
|
+
return {
|
|
2047
|
+
totalBytes,
|
|
2048
|
+
missingSizeCount
|
|
2049
|
+
};
|
|
2050
|
+
}
|
|
2051
|
+
/** 读面抛错按策略折成「逐行都缺」(`absent`)或原样上抛(`throw`)。 */
|
|
2052
|
+
async function sizesOf(deps, policy) {
|
|
2053
|
+
try {
|
|
2054
|
+
return await deps.host.persistedSizes();
|
|
2055
|
+
} catch (error) {
|
|
2056
|
+
if (policy.sizeFailure === "throw") throw error;
|
|
2057
|
+
return null;
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
/** 有界并发的逐条执行器:结果与 `items` **同序同长**、同时挂起的 `fn` 不超过 `limit`、首个失败
|
|
2061
|
+
* 原样抛出(失败后不再起新活,已挂起的跑完即弃)。为什么不直接 `Promise.all`:它无界放飞,
|
|
2062
|
+
* 而各条自己 settle 的失败还会留下没人收的 rejection。
|
|
2063
|
+
*
|
|
2064
|
+
* **导出面**:逐行读数用它({@link ROW_READ_CONCURRENCY}),`/list` 的盘上测量也用它
|
|
2065
|
+
* (`src/verbs/permanent-removal.ts` 的组与 kids 两级)——"有界并发"只该有这一份实现。
|
|
2066
|
+
* 预算由调用方给:两个调用点的窗口大小不是同一个语义。 */
|
|
2067
|
+
async function mapLimit(items, limit, fn) {
|
|
2068
|
+
const results = new Array(items.length);
|
|
2069
|
+
let cursor = 0;
|
|
2070
|
+
/** 按发生顺序收失败:第一条就是「首错」;非空也让在跑的 worker 不再领新活(失败关闭)。 */
|
|
2071
|
+
const failures = [];
|
|
2072
|
+
const worker = async () => {
|
|
2073
|
+
while (failures.length === 0) {
|
|
2074
|
+
const index = cursor;
|
|
2075
|
+
if (index >= items.length) return;
|
|
2076
|
+
cursor += 1;
|
|
2077
|
+
const item = items[index];
|
|
2078
|
+
if (item === void 0) return;
|
|
2079
|
+
try {
|
|
2080
|
+
results[index] = await fn(item, index);
|
|
2081
|
+
} catch (error) {
|
|
2082
|
+
failures.push(error);
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
};
|
|
2086
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
|
|
2087
|
+
if (failures.length > 0) throw failures[0];
|
|
2088
|
+
return results;
|
|
2089
|
+
}
|
|
2090
|
+
//#endregion
|
|
2091
|
+
//#region src/trash/projection-cache.ts
|
|
2092
|
+
/**
|
|
2093
|
+
* 宿主**投影缓存**(`session_projcache`)的孤儿判定、手动清理与永久删除收尾。
|
|
2094
|
+
*
|
|
2095
|
+
* 缓存是宿主的派生数据:一条会话一份记录,按 `session id` 落盘(`storages/session_projcache/sessions/`)。
|
|
2096
|
+
* 宿主只写不删——删除会话不会让它消失,所以永久删除必须自己把对应记录带走;否则每删一个会话就
|
|
2097
|
+
* 永久多一份记录。孤儿判定与手动清理共用**同一条判据**(永久删除的收尾按实际删掉的会话 id 逐条删):
|
|
2098
|
+
*
|
|
2099
|
+
* 缓存里的 id −(会话语料/持久化 ∪ 清册 raw 行 ∪ `session-trash/` 目录)= 孤儿。
|
|
2100
|
+
*
|
|
2101
|
+
* id 按 `bareSessionId` 比较:`session-x` 与 `x` 是同一个会话的两代写法(见 `domain/closure.ts`),
|
|
2102
|
+
* 不归一就会把还在册的会话误报成孤儿。
|
|
2103
|
+
*
|
|
2104
|
+
* 判据只读调用方交来的 **raw 清册行**与**目录名**:**不对账、不写清册**。`ledger.list()` 会把目录
|
|
2105
|
+
* 不在的幽灵行摘掉,而幽灵行正是本判据要保护的面(ADR-0062);清理若先对账,就会把报告里保护住的
|
|
2106
|
+
* 缓存删掉,并顺手改写清册。失败关闭规则(缺一不可):
|
|
2107
|
+
* - 语料读面缺席或抛错 ⇒ `io`(活体只有它看得见,持久化列表不是全集);
|
|
2108
|
+
* - 持久化服务在场但列表读面回缺席/抛错 ⇒ `io`(可能有看不见的 persisted-only 会话);
|
|
2109
|
+
* - 持久化服务缺席 ⇒ 没有 persisted-only 会话,语料已是完整的保护面;
|
|
2110
|
+
* - 投影缓存域不可用 ⇒ `io`;**服务缺席不算「没有记录」**,旧版本可能留下记录。
|
|
2111
|
+
*
|
|
2112
|
+
* 删除只经宿主端口(`storageDomain.get('session_projcache').table('sessions')` 的同一条写链),
|
|
2113
|
+
* **不直接删 `storages/` 下的文件**:绕过域的内存权威会让运行中的宿主与盘上不一致。
|
|
2114
|
+
*/
|
|
2115
|
+
/**
|
|
2116
|
+
* 仍在册的会话 id(去前缀后的形状):语料(live ∪ persisted)与持久化列表**两条都并进来**——
|
|
2117
|
+
* 语料读面可能跳过冷无 cwd 的会话,只信一条会把还在盘上的会话误报成孤儿。
|
|
2118
|
+
*
|
|
2119
|
+
* 清册 raw 行与 `session-trash/` 目录都算保护面:行在、目录不在的幽灵行也保护,宁可少报一条也不误删;
|
|
2120
|
+
* 手工搬进回收站、还没对账成行的目录按目录名保护(条目 id 的 `<时间戳>-<会话目录名>` 逆推)。
|
|
2121
|
+
*
|
|
2122
|
+
* 失败关闭见模块头:语料缺席或任一读面抛错折 `io`(活体只有语料看得见);持久化服务在场但
|
|
2123
|
+
* 列表缺席折 `io`;持久化服务**确实缺席**时没有 persisted-only 会话,语料是完整保护面。
|
|
2124
|
+
*/
|
|
2125
|
+
async function protectedBareIds(deps, trash) {
|
|
2126
|
+
const protectedIds = /* @__PURE__ */ new Set();
|
|
2127
|
+
let corpus;
|
|
2128
|
+
try {
|
|
2129
|
+
corpus = await deps.host.listSessions();
|
|
2130
|
+
} catch (error) {
|
|
2131
|
+
throw verbError("io", "读取会话语料失败:sessionQuery.listSessions 抛错,无法判断投影缓存是否孤儿", error);
|
|
2132
|
+
}
|
|
2133
|
+
if (!corpus.available) throw verbError("io", "读取会话语料失败:sessionQuery 缺席,看不见活体会话,无法判断投影缓存是否孤儿");
|
|
2134
|
+
for (const session of corpus.value) protectedIds.add(bareSessionId(session.sessionId));
|
|
2135
|
+
let persisted;
|
|
2136
|
+
try {
|
|
2137
|
+
persisted = await deps.host.persistedSizes();
|
|
2138
|
+
} catch (error) {
|
|
2139
|
+
throw verbError("io", "读取持久化会话失败:sessionPersistence.list 抛错,无法判断投影缓存是否孤儿", error);
|
|
2140
|
+
}
|
|
2141
|
+
if (persisted.available) for (const sessionId of persisted.value.keys()) protectedIds.add(bareSessionId(sessionId));
|
|
2142
|
+
else if (deps.host.persistenceMounted()) throw verbError("io", "持久化服务在场但会话列表读不出,无法判断投影缓存是否孤儿");
|
|
2143
|
+
for (const row of trash) protectedIds.add(bareSessionId(row.sessionId));
|
|
2144
|
+
const trashRoot = `${deps.home}/${TRASH_DIR_NAME}`;
|
|
2145
|
+
try {
|
|
2146
|
+
if (await deps.fs.exists(trashRoot)) for (const name of await deps.fs.listDirs(trashRoot)) try {
|
|
2147
|
+
protectedIds.add(bareSessionId(decodeSessionSegment(parseEntryId(name).sessionDirName)));
|
|
2148
|
+
} catch {}
|
|
2149
|
+
} catch (error) {
|
|
2150
|
+
throw verbError("io", "读取回收站目录失败,无法判断投影缓存是否孤儿", error);
|
|
2151
|
+
}
|
|
2152
|
+
return protectedIds;
|
|
2153
|
+
}
|
|
2154
|
+
/** 当前投影缓存里没有任何会话痕迹的记录 id(原样,供删除用;比较时才归一)。 */
|
|
2155
|
+
async function orphanProjectionCacheIds(deps, trash) {
|
|
2156
|
+
const cache = await deps.host.projectionCacheIds();
|
|
2157
|
+
if (!cache.available) throw verbError("io", "投影缓存域不可用:宿主没有已打开的 session_projcache.sessions 存储域(服务缺席不算空表)");
|
|
2158
|
+
const protectedIds = await protectedBareIds(deps, trash);
|
|
2159
|
+
return cache.value.filter((sessionId) => !protectedIds.has(bareSessionId(sessionId)));
|
|
2160
|
+
}
|
|
2161
|
+
/** 维护卡的只读报告:只念条数,不算体积(缓存记录不是本插件的字节读数面)。 */
|
|
2162
|
+
async function reportProjectionCacheOrphans(deps, trash) {
|
|
2163
|
+
return { count: (await orphanProjectionCacheIds(deps, trash)).length };
|
|
2164
|
+
}
|
|
2165
|
+
/**
|
|
2166
|
+
* 维护卡的聚合清理:用路由交来的 **raw 清册行** + 目录名保护,**不先对账、不改写清册**——
|
|
2167
|
+
* `ledger.list()` 会摘掉幽灵行,让报告保护住的缓存反被删掉(ADR-0062 的边界)。
|
|
2168
|
+
*
|
|
2169
|
+
* 删除失败不抛成顶层失败:批量写链抛错回 `{ removed: 0, failed: 名单条数 }`;旧宿主逐条删除的
|
|
2170
|
+
* 部分失败由端口回真实 `{ removed, failed }`。界面清完自动重查,真实剩余量以重查为准。
|
|
2171
|
+
*/
|
|
2172
|
+
async function cleanProjectionCacheOrphans(deps, trash) {
|
|
2173
|
+
const ids = await orphanProjectionCacheIds(deps, trash);
|
|
2174
|
+
if (ids.length === 0) return {
|
|
2175
|
+
removed: 0,
|
|
2176
|
+
failed: 0
|
|
2177
|
+
};
|
|
2178
|
+
try {
|
|
2179
|
+
const receipt = await deps.host.dropProjectionCache(ids);
|
|
2180
|
+
if (receipt.failed > 0) console.warn(`[dsh-session-delete] 投影缓存清理部分失败:已清 ${receipt.removed} 条、未清 ${receipt.failed} 条`);
|
|
2181
|
+
return receipt;
|
|
2182
|
+
} catch (error) {
|
|
2183
|
+
console.warn(`[dsh-session-delete] 投影缓存清理失败:${ids.length} 条`, error);
|
|
2184
|
+
return {
|
|
2185
|
+
removed: 0,
|
|
2186
|
+
failed: ids.length
|
|
2187
|
+
};
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
/**
|
|
2191
|
+
* 永久删除的逐会话收尾:**这一条会话删掉了,就删这一条的缓存**。
|
|
2192
|
+
*
|
|
2193
|
+
* 只由 `executeRemoval` 在某个成员的目录/清册行确实处理完之后调用;不按计划名单批量扫,也不碰
|
|
2194
|
+
* 这一趟没删成的会话。缓存 key 按 `sessionIdShapes` 覆盖两代写法(`session-x` / `x` 是同一个
|
|
2195
|
+
* 会话;只删原写法会漏掉另一代的记录)。缓存是派生数据:删除失败只留 warning,不把已经完成的
|
|
2196
|
+
* 会话删除翻成失败;漏掉的记录由维护卡下一次检查兜住。
|
|
2197
|
+
*/
|
|
2198
|
+
async function dropDeletedSessionCache(deps, sessionId) {
|
|
2199
|
+
try {
|
|
2200
|
+
const receipt = await deps.host.dropProjectionCache(sessionIdShapes(sessionId));
|
|
2201
|
+
if (receipt.failed > 0) console.warn(`[dsh-session-delete] 投影缓存清理部分失败(会话已删除):${sessionId},未清 ${receipt.failed} 条`);
|
|
2202
|
+
} catch (error) {
|
|
2203
|
+
console.warn(`[dsh-session-delete] 投影缓存清理失败(会话已删除):${sessionId}`, error);
|
|
2204
|
+
}
|
|
2205
|
+
}
|
|
1766
2206
|
//#endregion
|
|
1767
2207
|
//#region src/verbs/permanent-removal.ts
|
|
1768
2208
|
/**
|
|
@@ -1802,7 +2242,7 @@ async function probeDir(deps, dir) {
|
|
|
1802
2242
|
/** 成员的盘上目录与字节(扫描、清单装配与 purge 共用这一条路径/存在性/度量口径;
|
|
1803
2243
|
* 目录缺席回 `undefined`,不拿一份"记录还在、盘上已经没了"的旧读数冒充盘上残留)。 */
|
|
1804
2244
|
async function measureMemberDir(deps, member) {
|
|
1805
|
-
const dir =
|
|
2245
|
+
const dir = sessionDirForId(member.projectDir, member.sessionId, deps.home);
|
|
1806
2246
|
const probe = await probeDir(deps, dir);
|
|
1807
2247
|
return probe.present ? {
|
|
1808
2248
|
dir,
|
|
@@ -1890,6 +2330,11 @@ async function selectStrandedMembers(host, manifest, parentIds) {
|
|
|
1890
2330
|
}
|
|
1891
2331
|
return out;
|
|
1892
2332
|
}
|
|
2333
|
+
/** `/list` 只读计划的盘上测量预算:组与组内的 kids 两级各用这一份。
|
|
2334
|
+
* 为什么要有界:`/list` 一次可能几百组、每组几百个孩子,无界 `Promise.all` 会把上千个
|
|
2335
|
+
* `exists` / `sizeOfDir` 一起挂起去抢同一个盘;预算与逐行读数(`ROW_READ_CONCURRENCY`)的旋钮
|
|
2336
|
+
* 分家——那边是宿主投影读,这边是盘上递归量尺寸,同一个数没有同一条理由。 */
|
|
2337
|
+
const VISIBLE_MEASURE_CONCURRENCY = 8;
|
|
1893
2338
|
/**
|
|
1894
2339
|
* `/list` 的只读计划:一行 = 一组。释放量与 purge 用同一条口径——回收站目录与成员目录**现测**,
|
|
1895
2340
|
* 不用清册里记的 `sizeBytes`(那是删除那一刻的事实,盘上早就变了)。
|
|
@@ -1897,12 +2342,15 @@ async function selectStrandedMembers(host, manifest, parentIds) {
|
|
|
1897
2342
|
* 盘上后代经 `selectStrandedMembers` 选出(排除全部清册 id、bare id 全局只算一次);目录不在的成员
|
|
1898
2343
|
* 不进 `members`(与 purge 计划同口径)。成员只吃 {@link measureMembers}:**零账本读**——不再为每个
|
|
1899
2344
|
* 盘上后代问一次 `workspaceOf`,`/list` 的失败面不再含账本归属读(归属只有 purge 摘账本才付)。
|
|
2345
|
+
*
|
|
2346
|
+
* 两级都有界({@link VISIBLE_MEASURE_CONCURRENCY}):组之间、组内 kids 各一扇窗;输出顺序仍按
|
|
2347
|
+
* `groups` 原序(`mapLimit` 按 index 落位),首个失败原样抛。
|
|
1900
2348
|
*/
|
|
1901
2349
|
async function planVisibleTrash(deps, rows, groups) {
|
|
1902
2350
|
const candidates = await selectStrandedMembers(deps.host, rows, groups.map((group) => group.root.sessionId));
|
|
1903
|
-
return await
|
|
2351
|
+
return await mapLimit(groups, VISIBLE_MEASURE_CONCURRENCY, async ({ root, kids }, index) => {
|
|
1904
2352
|
const rootRow = await measureTrashRow(deps, root);
|
|
1905
|
-
const kidRows = await
|
|
2353
|
+
const kidRows = await mapLimit(kids, VISIBLE_MEASURE_CONCURRENCY, (kid) => measureTrashRow(deps, kid));
|
|
1906
2354
|
const members = await measureMembers(deps, candidates[index] ?? []);
|
|
1907
2355
|
const subagentBytes = kidRows.reduce((total, row) => total + row.bytes, 0);
|
|
1908
2356
|
const strandedBytes = members.reduce((total, member) => total + member.bytes, 0);
|
|
@@ -1916,7 +2364,7 @@ async function planVisibleTrash(deps, rows, groups) {
|
|
|
1916
2364
|
strandedBytes,
|
|
1917
2365
|
strandedCount: members.length
|
|
1918
2366
|
};
|
|
1919
|
-
})
|
|
2367
|
+
});
|
|
1920
2368
|
}
|
|
1921
2369
|
function totalBytes(items) {
|
|
1922
2370
|
return items.reduce((total, item) => total + item.bytes, 0);
|
|
@@ -1939,7 +2387,7 @@ function totalBytes(items) {
|
|
|
1939
2387
|
async function planTrashRemoval(deps, rows, targets) {
|
|
1940
2388
|
const candidates = (await selectStrandedMembers(deps.host, rows, targets.map((entry) => entry.sessionId))).flat();
|
|
1941
2389
|
await assertNoLive(deps.host, [...targets.map((entry) => entry.sessionId), ...candidates.map((member) => member.sessionId)]);
|
|
1942
|
-
const trash = await
|
|
2390
|
+
const trash = await mapLimit(targets, VISIBLE_MEASURE_CONCURRENCY, (entry) => measureTrashRow(deps, entry));
|
|
1943
2391
|
const members = await planMemberRemovals(deps, candidates);
|
|
1944
2392
|
const attachments = await planImageAttachmentRemoval(deps, [...trash.map((row) => row.dir), ...members.map((member) => member.dir)]);
|
|
1945
2393
|
return {
|
|
@@ -2073,6 +2521,7 @@ async function executeRemoval(deps, plan) {
|
|
|
2073
2521
|
}
|
|
2074
2522
|
removed += 1;
|
|
2075
2523
|
await presence.memberGone(row.entry.sessionId);
|
|
2524
|
+
await dropDeletedSessionCache(deps, row.entry.sessionId);
|
|
2076
2525
|
}
|
|
2077
2526
|
const memberLabel = plan.kind === "trash" ? "删除盘上后代目录失败" : "删除会话目录失败";
|
|
2078
2527
|
for (const member of plan.members) {
|
|
@@ -2085,6 +2534,7 @@ async function executeRemoval(deps, plan) {
|
|
|
2085
2534
|
removed += 1;
|
|
2086
2535
|
freedSoFar += member.bytes;
|
|
2087
2536
|
await presence.memberGone(member.sessionId);
|
|
2537
|
+
await dropDeletedSessionCache(deps, member.sessionId);
|
|
2088
2538
|
}
|
|
2089
2539
|
const attachmentPlan = await recheckImageRemovalExclusivity(deps, plan.attachments);
|
|
2090
2540
|
const attachments = await executeImageAttachmentRemoval(deps, attachmentPlan);
|
|
@@ -2406,6 +2856,29 @@ function subagentLabelOf(value) {
|
|
|
2406
2856
|
const label = value.label;
|
|
2407
2857
|
return typeof label === "string" ? label : "";
|
|
2408
2858
|
}
|
|
2859
|
+
const PROJECTION_CACHE_DOMAIN = "session_projcache";
|
|
2860
|
+
const PROJECTION_CACHE_TABLE = "sessions";
|
|
2861
|
+
/** 取已打开的投影缓存表;域未打开 / 形状不符 ⇒ `undefined`。**缓存服务缺席不是一条判据**:
|
|
2862
|
+
* 旧版本可能留下记录,只要域已打开就照读;读面回显式缺席,删除收尾降级为 warning。 */
|
|
2863
|
+
function projectionCacheTableOf(host) {
|
|
2864
|
+
const facility = host.get("storageDomain");
|
|
2865
|
+
if (facility === void 0 || facility === null || typeof facility.get !== "function") return void 0;
|
|
2866
|
+
let domain;
|
|
2867
|
+
try {
|
|
2868
|
+
domain = facility.get(PROJECTION_CACHE_DOMAIN);
|
|
2869
|
+
} catch {
|
|
2870
|
+
return;
|
|
2871
|
+
}
|
|
2872
|
+
if (domain === void 0 || domain === null) return void 0;
|
|
2873
|
+
let table;
|
|
2874
|
+
try {
|
|
2875
|
+
table = domain.table(PROJECTION_CACHE_TABLE);
|
|
2876
|
+
} catch {
|
|
2877
|
+
return;
|
|
2878
|
+
}
|
|
2879
|
+
if (typeof table?.keys !== "function" || typeof table.delete !== "function") return void 0;
|
|
2880
|
+
return table;
|
|
2881
|
+
}
|
|
2409
2882
|
/** 官方的「这些父的孩子」那一支:`kind:'parent'` 的判据逐字是 `values.includes(record.header.parentSession ?? null)`。
|
|
2410
2883
|
* 它只按 `parentSession` 原样匹配,**不是**子会话分类器:旧宿主(≤0.2.1-rc.5)的普通 fork 也写
|
|
2411
2884
|
* `parentSession`,0.2.2-alpha.2 起才不写。子会话的判据是 `origin` 的 subagent 标记(宿主归档闸、归档
|
|
@@ -2503,6 +2976,13 @@ async function controllerItems(host) {
|
|
|
2503
2976
|
return [];
|
|
2504
2977
|
}
|
|
2505
2978
|
}
|
|
2979
|
+
/** 一条事件的形状判据:折叠要读 `type` 与 `time` 两格,判过就把原对象交出去(信封多余字段留着)。
|
|
2980
|
+
* 与 `controllerItems` 同一条——`Array.isArray` 只证明是数组,元素逐个判,不断言形状。 */
|
|
2981
|
+
function isCorpusEvent(item) {
|
|
2982
|
+
if (typeof item !== "object" || item === null) return false;
|
|
2983
|
+
const { type, time } = item;
|
|
2984
|
+
return typeof type === "string" && typeof time === "number";
|
|
2985
|
+
}
|
|
2506
2986
|
/** 账本里没有那个工作区时 {@link HostPort.attach} / {@link HostPort.detach} 抛的原话开头。
|
|
2507
2987
|
* **原话与判据同住这里**:抛它的是这个端口,认它的也是端口给的那句,调用方不许另抄一份字符串。 */
|
|
2508
2988
|
const WORKSPACE_MISSING_MESSAGE = "workspace not found";
|
|
@@ -2555,8 +3035,19 @@ function createHostPort(ctx) {
|
|
|
2555
3035
|
return "";
|
|
2556
3036
|
}
|
|
2557
3037
|
},
|
|
3038
|
+
/** 子会话 label 的单问面:`subagent` 投影行的 `label` 本体,空串 = 没有(不回落标题,见接口注释)。 */
|
|
3039
|
+
async labelOf(sessionId) {
|
|
3040
|
+
try {
|
|
3041
|
+
const header = await headerOf(host, sessionId);
|
|
3042
|
+
if (header === void 0) return "";
|
|
3043
|
+
return subagentLabelOf(projectionCacheOf(host)?.cachedSnapshot(header, ["subagent"])?.values.subagent);
|
|
3044
|
+
} catch {
|
|
3045
|
+
return "";
|
|
3046
|
+
}
|
|
3047
|
+
},
|
|
2558
3048
|
/** 活跃判据走宿主 `workspace/session-activity` waterfall:空数组 = 无活动;
|
|
2559
|
-
* 与宿主 archiveSession 的准入同源。
|
|
3049
|
+
* 与宿主 archiveSession 的准入同源。family 不止 turn(后台 job / 活动定时任务也会回条目),
|
|
3050
|
+
* 所以只判"非空",不按某一个 family 现推。 */
|
|
2560
3051
|
async isLive(sessionId) {
|
|
2561
3052
|
return (await host.waterfall("workspace/session-activity", { sessionId }, () => Promise.resolve([]))).length > 0;
|
|
2562
3053
|
},
|
|
@@ -2564,6 +3055,10 @@ function createHostPort(ctx) {
|
|
|
2564
3055
|
async isArchived(sessionId) {
|
|
2565
3056
|
return registry.archivedSessionIds.includes(sessionId);
|
|
2566
3057
|
},
|
|
3058
|
+
/** registry 全局归档集**原样**(归档清单的交集原料;与 {@link HostIdentityPort.isArchived} 同一格事实)。 */
|
|
3059
|
+
async archivedSessionIds() {
|
|
3060
|
+
return registry.archivedSessionIds;
|
|
3061
|
+
},
|
|
2567
3062
|
/**
|
|
2568
3063
|
* 从 `ctx.sessions` 摘掉会话,并关闭捕获到的 agent handle。
|
|
2569
3064
|
*
|
|
@@ -2663,7 +3158,8 @@ function createHostPort(ctx) {
|
|
|
2663
3158
|
sessionId: id,
|
|
2664
3159
|
...typeof parent === "string" && parent !== "" ? { parentSessionId: parent } : {},
|
|
2665
3160
|
projectDir: projectDirOfCwd(cwd),
|
|
2666
|
-
subagent: record.header?.origin === "subagent"
|
|
3161
|
+
subagent: record.header?.origin === "subagent",
|
|
3162
|
+
...typeof record.header?.createdAt === "number" && record.header.createdAt > 0 ? { createdAt: record.header.createdAt } : {}
|
|
2667
3163
|
});
|
|
2668
3164
|
}
|
|
2669
3165
|
return {
|
|
@@ -2684,6 +3180,147 @@ function createHostPort(ctx) {
|
|
|
2684
3180
|
available: true,
|
|
2685
3181
|
value: await membersFor(sessionQuery, parentIds)
|
|
2686
3182
|
};
|
|
3183
|
+
},
|
|
3184
|
+
/** 批量折日志标题:`readTitleSnapshots` 逐条 `fulfilled`(`value.title.title`)/ `rejected`;
|
|
3185
|
+
* 无标题与 rejected 同落「不在 map」。方法缺席或整次读抛错 ⇒ `{available:false}`——
|
|
3186
|
+
* 调用方逐条回退 `titleOf`,标题问题永不失败整档。 */
|
|
3187
|
+
async titleSnapshots(ids) {
|
|
3188
|
+
const sessionQuery = host.get("sessionQuery");
|
|
3189
|
+
if (typeof sessionQuery?.readTitleSnapshots !== "function") return { available: false };
|
|
3190
|
+
try {
|
|
3191
|
+
const out = /* @__PURE__ */ new Map();
|
|
3192
|
+
for (const item of await sessionQuery.readTitleSnapshots([...new Set(ids)])) {
|
|
3193
|
+
const row = item;
|
|
3194
|
+
if (typeof row?.sessionId !== "string" || row.status !== "fulfilled") continue;
|
|
3195
|
+
const title = (row.value?.title)?.title;
|
|
3196
|
+
if (typeof title === "string" && title !== "") out.set(row.sessionId, title);
|
|
3197
|
+
}
|
|
3198
|
+
return {
|
|
3199
|
+
available: true,
|
|
3200
|
+
value: out
|
|
3201
|
+
};
|
|
3202
|
+
} catch {
|
|
3203
|
+
return { available: false };
|
|
3204
|
+
}
|
|
3205
|
+
},
|
|
3206
|
+
/** 提问时间表:`sessionController.list()` 逐条 `sessionId`/`updatedAt`(正数才收;0 不是
|
|
3207
|
+
* 「1970 年提问过」);服务缺席或抛错 ⇒ `{available:false}`(调用方回退 `createdAt`)。 */
|
|
3208
|
+
async sessionActivity() {
|
|
3209
|
+
try {
|
|
3210
|
+
const controller = host.get("sessionController");
|
|
3211
|
+
if (controller === void 0 || controller === null || typeof controller.list !== "function") return { available: false };
|
|
3212
|
+
const listed = await controller.list();
|
|
3213
|
+
const items = Array.isArray(listed) ? listed : listed?.items;
|
|
3214
|
+
const out = /* @__PURE__ */ new Map();
|
|
3215
|
+
if (Array.isArray(items)) for (const item of items) {
|
|
3216
|
+
const row = item;
|
|
3217
|
+
if (typeof row?.sessionId !== "string") continue;
|
|
3218
|
+
if (typeof row.updatedAt !== "number" || !Number.isFinite(row.updatedAt) || row.updatedAt <= 0) continue;
|
|
3219
|
+
out.set(row.sessionId, row.updatedAt);
|
|
3220
|
+
}
|
|
3221
|
+
return {
|
|
3222
|
+
available: true,
|
|
3223
|
+
value: out
|
|
3224
|
+
};
|
|
3225
|
+
} catch {
|
|
3226
|
+
return { available: false };
|
|
3227
|
+
}
|
|
3228
|
+
},
|
|
3229
|
+
/** 持久化字节表:`sessionPersistence.list()` 的 `sizeBytes`(可选字段,缺席 = 没有可信读数)。
|
|
3230
|
+
* 服务缺席 ⇒ `{ available: false }`(调用方逐行缺大小、整档照常);`list()` 抛错照抛——
|
|
3231
|
+
* 调用方整档 `io`,不拿空表冒充"没有大小"。 */
|
|
3232
|
+
async persistedSizes() {
|
|
3233
|
+
const persistence = host.get("sessionPersistence");
|
|
3234
|
+
if (persistence === void 0 || persistence === null || typeof persistence.list !== "function") return { available: false };
|
|
3235
|
+
const out = /* @__PURE__ */ new Map();
|
|
3236
|
+
for (const snapshot of await persistence.list()) {
|
|
3237
|
+
const id = snapshot.header?.id;
|
|
3238
|
+
if (typeof id !== "string" || id === "") continue;
|
|
3239
|
+
const size = snapshot.sizeBytes;
|
|
3240
|
+
out.set(id, typeof size === "number" && Number.isFinite(size) ? size : void 0);
|
|
3241
|
+
}
|
|
3242
|
+
return {
|
|
3243
|
+
available: true,
|
|
3244
|
+
value: out
|
|
3245
|
+
};
|
|
3246
|
+
},
|
|
3247
|
+
/** 持久化服务是否在场:只探服务对象,不读列表。`persistedSizes` 的 `available:false` 把
|
|
3248
|
+
* 「服务没挂」与「服务在但列表读面坏了」折成同一形状;维护卡的孤儿判定需要把后者失败关闭。 */
|
|
3249
|
+
persistenceMounted() {
|
|
3250
|
+
try {
|
|
3251
|
+
const persistence = host.get("sessionPersistence");
|
|
3252
|
+
return persistence !== void 0 && persistence !== null;
|
|
3253
|
+
} catch {
|
|
3254
|
+
return false;
|
|
3255
|
+
}
|
|
3256
|
+
},
|
|
3257
|
+
/** 投影缓存记录键集:只认已打开的存储域,**不拿服务缺席当空表**。旧版本或另一份 composition
|
|
3258
|
+
* 可能留下记录;域取不到/形状不符/`keys()` 抛错都回显式缺席,调用方折 `io`。
|
|
3259
|
+
* `keys()` 是域内存表的快照迭代器——与缓存服务读写的是同一份状态。 */
|
|
3260
|
+
async projectionCacheIds() {
|
|
3261
|
+
const table = projectionCacheTableOf(host);
|
|
3262
|
+
if (table === void 0) return { available: false };
|
|
3263
|
+
try {
|
|
3264
|
+
return {
|
|
3265
|
+
available: true,
|
|
3266
|
+
value: [...table.keys()]
|
|
3267
|
+
};
|
|
3268
|
+
} catch {
|
|
3269
|
+
return { available: false };
|
|
3270
|
+
}
|
|
3271
|
+
},
|
|
3272
|
+
/** 删投影缓存记录:经 storage domain 的写链,内存与盘一起更新。批量写链失败原样抛(清理段
|
|
3273
|
+
* 折成整批失败);旧宿主逐条 `delete` 时单条失败收进 `failed`、继续删其余条——回执始终是
|
|
3274
|
+
* 这一趟的真实后果,永久删除的收尾自己吞成 warning。 */
|
|
3275
|
+
async dropProjectionCache(sessionIds) {
|
|
3276
|
+
if (sessionIds.length === 0) return {
|
|
3277
|
+
removed: 0,
|
|
3278
|
+
failed: 0
|
|
3279
|
+
};
|
|
3280
|
+
const table = projectionCacheTableOf(host);
|
|
3281
|
+
if (table === void 0) throw new Error("session-delete: 宿主的 session_projcache 存储域不可用");
|
|
3282
|
+
const unique = [...new Set(sessionIds)];
|
|
3283
|
+
if (typeof table.deleteMany === "function") return {
|
|
3284
|
+
removed: await table.deleteMany(unique),
|
|
3285
|
+
failed: 0
|
|
3286
|
+
};
|
|
3287
|
+
let removed = 0;
|
|
3288
|
+
let failed = 0;
|
|
3289
|
+
for (const id of unique) try {
|
|
3290
|
+
if (await table.delete(id)) removed += 1;
|
|
3291
|
+
} catch {
|
|
3292
|
+
failed += 1;
|
|
3293
|
+
}
|
|
3294
|
+
return {
|
|
3295
|
+
removed,
|
|
3296
|
+
failed
|
|
3297
|
+
};
|
|
3298
|
+
},
|
|
3299
|
+
/** 整本读:`sessionQuery.readSession`(replay 校验、不 make live)。header 只投影折叠消费的三格
|
|
3300
|
+
* (`origin` 是子会话的权威判据,但折叠认的是 `parentSession`——投影它就没有消费方);
|
|
3301
|
+
* 事件流原样交回(信封多余字段留着),**逐条判形状**:不符就抛(上层折 `io`),不静默折成空正文。
|
|
3302
|
+
* 方法缺席抛「缺席」;读失败原样抛(含 `SESSION_QUERY_SESSION_NOT_FOUND`——折 `not-found`
|
|
3303
|
+
* 归上层的 `readArchiveDetail`)。 */
|
|
3304
|
+
async readSession(sessionId) {
|
|
3305
|
+
const sessionQuery = host.get("sessionQuery");
|
|
3306
|
+
if (typeof sessionQuery?.readSession !== "function") throw new Error("session-delete: sessionQuery.readSession 缺席");
|
|
3307
|
+
const raw = await sessionQuery.readSession(sessionId);
|
|
3308
|
+
const head = raw?.session ?? {};
|
|
3309
|
+
const listed = raw?.events;
|
|
3310
|
+
if (!Array.isArray(listed)) throw new Error("session-delete: sessionQuery.readSession 的事件流形状不符");
|
|
3311
|
+
const events = [];
|
|
3312
|
+
for (const item of listed) {
|
|
3313
|
+
if (!isCorpusEvent(item)) throw new Error("session-delete: sessionQuery.readSession 的事件流形状不符");
|
|
3314
|
+
events.push(item);
|
|
3315
|
+
}
|
|
3316
|
+
return {
|
|
3317
|
+
session: {
|
|
3318
|
+
...typeof head.createdAt === "number" ? { createdAt: head.createdAt } : {},
|
|
3319
|
+
...typeof head.cwd === "string" ? { cwd: head.cwd } : {},
|
|
3320
|
+
...typeof head.parentSession === "string" ? { parentSession: head.parentSession } : {}
|
|
3321
|
+
},
|
|
3322
|
+
events
|
|
3323
|
+
};
|
|
2687
3324
|
}
|
|
2688
3325
|
};
|
|
2689
3326
|
}
|
|
@@ -2725,7 +3362,10 @@ function restoreSession(deps) {
|
|
|
2725
3362
|
return target;
|
|
2726
3363
|
};
|
|
2727
3364
|
}
|
|
2728
|
-
/** 放回哪儿:用删除时记进 entryId
|
|
3365
|
+
/** 放回哪儿:用删除时记进 entryId 的**已编码目录段**原地回放,不从 sessionId 现编。
|
|
3366
|
+
* 段是宿主 `encodeSegment` 的产物(`src/shared/session-path.ts` 是唯一编码实现),删除那一刻写进 id;
|
|
3367
|
+
* 恢复只是把它接回 `sessions/<projectDir>/` 下——不重新编码,因此宿主换编码算法也不影响旧条目回家,
|
|
3368
|
+
* 但**不等于**本插件不认宿主的目录命名约定:它认的就是宿主编出来的那一段。 */
|
|
2729
3369
|
function restoreTargetDir(deps, entry) {
|
|
2730
3370
|
return sessionDirOf(entry.projectDir, parseEntryId(entry.id).sessionDirName, deps.home);
|
|
2731
3371
|
}
|
|
@@ -2818,39 +3458,34 @@ async function memberRestore(deps, presence, entry) {
|
|
|
2818
3458
|
}
|
|
2819
3459
|
//#endregion
|
|
2820
3460
|
//#region src/verbs/trash-scope.ts
|
|
2821
|
-
function createTrashScope(deps, rows) {
|
|
2822
|
-
const
|
|
2823
|
-
let current = [...rows];
|
|
3461
|
+
function createTrashScope(deps, rows, execute) {
|
|
3462
|
+
const view = createShrinkingView(rows);
|
|
2824
3463
|
/** 拿目标、把计划交给执行器:`targets` 缺席(`undefined`)= 清空。计划只读——活体准入在**一切写
|
|
2825
3464
|
* 之前**(任一在跑就整条拒绝、零副作用)。盘上后代按**当前视图里还在的 id** 排除(跟着父进来的
|
|
2826
3465
|
* 孩子不按"盘上残留"再删一遍);`sessionQuery` 缺席时端口回 `{ available: false }` ⇒ 这次只清
|
|
2827
3466
|
* 清册里的那部分,盘上残留留给 `GET /orphans` 兜底(与 delete 的降级一致,不折成失败)。 */
|
|
2828
3467
|
async function purgeGroup(targets, requestedId) {
|
|
3468
|
+
const current = view.view();
|
|
2829
3469
|
const selected = targets ?? current;
|
|
2830
3470
|
if (targets !== void 0 && selected.length === 0) throw trashEmpty(requestedId);
|
|
2831
|
-
return await
|
|
3471
|
+
return await execute(await planTrashRemoval(deps, current, selected));
|
|
2832
3472
|
}
|
|
2833
|
-
/** 收缩是内部闭包、不外露:唯一的观察面是后续 `purge` / `purgeAll` / `orphanGroups` 看见的当前视图。 */
|
|
2834
|
-
const take = (id) => {
|
|
2835
|
-
current = withoutGroup(current, id);
|
|
2836
|
-
};
|
|
2837
3473
|
return {
|
|
2838
3474
|
purge: async (id) => {
|
|
2839
|
-
const claim =
|
|
3475
|
+
const claim = view.claim(id);
|
|
2840
3476
|
if (claim.verdict === "carried") return {
|
|
2841
3477
|
removed: 0,
|
|
2842
3478
|
freedBytes: 0
|
|
2843
3479
|
};
|
|
2844
3480
|
const stats = await purgeGroup(claim.verdict === "fresh" ? claim.group : [], id);
|
|
2845
|
-
take(id);
|
|
3481
|
+
view.take(id);
|
|
2846
3482
|
return stats;
|
|
2847
3483
|
},
|
|
2848
3484
|
purgeAll: async () => {
|
|
2849
3485
|
const stats = await purgeGroup(void 0);
|
|
2850
|
-
|
|
3486
|
+
view.takeAll();
|
|
2851
3487
|
return stats;
|
|
2852
|
-
}
|
|
2853
|
-
orphanGroups: (roots) => loadOrphanGroups(deps, current, roots)
|
|
3488
|
+
}
|
|
2854
3489
|
};
|
|
2855
3490
|
}
|
|
2856
3491
|
//#endregion
|
|
@@ -2864,8 +3499,9 @@ function createTrashScope(deps, rows) {
|
|
|
2864
3499
|
* - 恢复通告攒到批尾,一次 announceRestored(ids)。
|
|
2865
3500
|
*
|
|
2866
3501
|
* 「已被同批前一条带走」是幂等成功(delete/restore 回 null,purge 回 0),不是失败;
|
|
2867
|
-
* 判据在 trash/groups.ts
|
|
2868
|
-
*
|
|
3502
|
+
* 判据在 src/trash/groups.ts,收缩视图的持有机制在 src/trash/shrinking-view.ts;同批已带走集:
|
|
3503
|
+
* delete / restore 在 src/verbs/batch-carried.ts,purge 那份的实例由 src/verbs/trash-scope.ts
|
|
3504
|
+
* (清册作用域)持有。
|
|
2869
3505
|
*/
|
|
2870
3506
|
function failure(id, action, error) {
|
|
2871
3507
|
return {
|
|
@@ -2940,7 +3576,7 @@ async function applyRestore(deps, ids) {
|
|
|
2940
3576
|
* trash-empty(原文点名)都在 `scope.purge(id)` 里——这里整批只读一次清册、逐 id 只交一个 id,
|
|
2941
3577
|
* 两份数组(算好的组 + 收缩中的视图)不再从批量层递两遍。 */
|
|
2942
3578
|
async function applyPurge(deps, ids) {
|
|
2943
|
-
const scope = createTrashScope(deps, await deps.ledger.list());
|
|
3579
|
+
const scope = createTrashScope(deps, await deps.ledger.list(), (plan) => executeRemoval(deps, plan));
|
|
2944
3580
|
return forEachId("purge", ids, (entryId) => scope.purge(entryId));
|
|
2945
3581
|
}
|
|
2946
3582
|
/** 删除确认框那句「含 N 个子会话」:一次问完整批(`subagentMembersOf` 本来就是批量口)。
|
|
@@ -2952,6 +3588,17 @@ async function applyCount(deps, ids) {
|
|
|
2952
3588
|
return wanted.map((id) => success(id, "count", read.available ? read.value[id]?.length ?? 0 : 0));
|
|
2953
3589
|
}
|
|
2954
3590
|
/**
|
|
3591
|
+
* 解除归档(归档档的显式动作,ADR-0008 不翻案:它不是删除/恢复的副作用)。逐 id 调宿主
|
|
3592
|
+
* `unarchiveSession`(未归档是幂等 no-op);成功值固定 `1`——「这条 id 被处理成功」,不是
|
|
3593
|
+
* 实际状态变化数(宿主不给返回值,也不为此多读一次 `isArchived` 去猜)。
|
|
3594
|
+
*/
|
|
3595
|
+
async function applyUnarchive(deps, ids) {
|
|
3596
|
+
return forEachId("unarchive", ids, async (sessionId) => {
|
|
3597
|
+
await deps.host.unarchive(sessionId);
|
|
3598
|
+
return 1;
|
|
3599
|
+
});
|
|
3600
|
+
}
|
|
3601
|
+
/**
|
|
2955
3602
|
* 清一组无主子会话(父已被彻底删掉、孩子还留在 `sessions/` 里的那些)。id 是**根会话 id**——
|
|
2956
3603
|
* 界面先 `GET /orphans` 拿 `roots` 再原样带回来,所以这里的 `not-found` 说的是"这句话已经过期了"
|
|
2957
3604
|
* (父又被人放回回收站、组已被上一个请求带走,或另一处已经把目录清掉),不是"用户打错了一个 id"。
|
|
@@ -2963,7 +3610,7 @@ async function applyCount(deps, ids) {
|
|
|
2963
3610
|
* 点过的决定(那种组该跟着父恢复或彻底删除)。
|
|
2964
3611
|
*/
|
|
2965
3612
|
async function applyOrphanClean(deps, ids) {
|
|
2966
|
-
const groups = await
|
|
3613
|
+
const groups = await loadOrphanGroups(deps, await deps.ledger.list(), ids);
|
|
2967
3614
|
const byRoot = new Map(groups.map((group) => [bareSessionId(group.root.sessionId), group]));
|
|
2968
3615
|
return forEachId("orphan-clean", ids, async (id) => {
|
|
2969
3616
|
const group = byRoot.get(bareSessionId(id));
|
|
@@ -2978,6 +3625,7 @@ function applyActions(deps, action, ids) {
|
|
|
2978
3625
|
case "purge": return applyPurge(deps, ids);
|
|
2979
3626
|
case "count": return applyCount(deps, ids);
|
|
2980
3627
|
case "orphan-clean": return applyOrphanClean(deps, ids);
|
|
3628
|
+
case "unarchive": return applyUnarchive(deps, ids);
|
|
2981
3629
|
}
|
|
2982
3630
|
}
|
|
2983
3631
|
//#endregion
|
|
@@ -3149,6 +3797,10 @@ function displayNameOfLog(raw) {
|
|
|
3149
3797
|
*
|
|
3150
3798
|
* 附件随块一起收(`attachmentsInContent`):每块最多 20、每页最多 200;超出的**静默丢**,不另立计数——
|
|
3151
3799
|
* "少了几张图"与"这块被截断"不是同一件事,拿一个数兼报会让两个数都对不上。
|
|
3800
|
+
*
|
|
3801
|
+
* **读整本之前先看大小**(`MAX_SESSION_LOG_BYTES`,取值的家与理由住 `src/log/session-log.ts`):日志大小
|
|
3802
|
+
* 没有宿主上限,逐帧解压省的是"解压后的正文",省不掉 `readFile` 那一份整本字节。超限按读不出处理,
|
|
3803
|
+
* 抛 `io` 带实际字节与上限原文——不截断成半条正文(详情是用户据以决定删不删的读数)。
|
|
3152
3804
|
*/
|
|
3153
3805
|
/** 每块文字的上限(字符)。正文、工具参数、工具结果各自吃这一刀。 */
|
|
3154
3806
|
const PER_BLOCK_CHAR_CAP = 16e3;
|
|
@@ -3389,12 +4041,175 @@ async function childDisplayNameOf(deps, entry) {
|
|
|
3389
4041
|
const dir = trashDirOf(entry.id, deps.home);
|
|
3390
4042
|
const logName = pickSessionLog(await deps.fs.listFiles(dir));
|
|
3391
4043
|
if (logName === void 0) return void 0;
|
|
3392
|
-
const
|
|
4044
|
+
const logPath = `${dir}/${logName}`;
|
|
4045
|
+
if ((await deps.fs.statFile(logPath)).size > 268435456) return void 0;
|
|
4046
|
+
const { label, title } = displayNameOfLog(await deps.fs.readFile(logPath));
|
|
3393
4047
|
return label !== "" ? label : title !== "" ? title : void 0;
|
|
3394
4048
|
} catch {
|
|
3395
4049
|
return;
|
|
3396
4050
|
}
|
|
3397
4051
|
}
|
|
4052
|
+
/**
|
|
4053
|
+
* 折叠核心的工厂。**`before` 在构造时给**:它决定分页窗口的右边界(`PageBuilder.end`),
|
|
4054
|
+
* 只在收尾才说就晚了——所以 `finish` 不再收参数。
|
|
4055
|
+
*/
|
|
4056
|
+
function createDetailFold(limits = DEFAULT_LIMITS, before) {
|
|
4057
|
+
const detail = {
|
|
4058
|
+
cwd: "",
|
|
4059
|
+
createdAt: 0,
|
|
4060
|
+
lastActivity: 0,
|
|
4061
|
+
logTitle: "",
|
|
4062
|
+
models: [],
|
|
4063
|
+
turnCount: 0,
|
|
4064
|
+
userMessageCount: 0,
|
|
4065
|
+
assistantMessageCount: 0,
|
|
4066
|
+
toolCallCount: 0,
|
|
4067
|
+
injectedCount: 0,
|
|
4068
|
+
blocks: [],
|
|
4069
|
+
olderCursor: null
|
|
4070
|
+
};
|
|
4071
|
+
const models = /* @__PURE__ */ new Set();
|
|
4072
|
+
/** 这条会话**自己**的 descriptor label(独立子会话没有父日志可查时的兜底)。
|
|
4073
|
+
* 与宿主 `subagent` 投影同一语义:每遇一条 descriptor 就覆盖,空 label 重置——fork 种子里的
|
|
4074
|
+
* 祖先 descriptor 必须被子会话自己的那条覆盖,坏/空的后写不保留祖先的名字。 */
|
|
4075
|
+
let ownLabel = "";
|
|
4076
|
+
/** 这条会话的 header 带 `parentSession`:它是子会话(fork / subagent),自己的日志标题才是
|
|
4077
|
+
* 当前名字;主会话没有这一格,仍按清册快照优先。 */
|
|
4078
|
+
let ownParentSession = false;
|
|
4079
|
+
/** 整条会话的提问索引:与分页无关,只在首次读时过线(见 `SessionDetailWire.prompts`)。 */
|
|
4080
|
+
const prompts = [];
|
|
4081
|
+
const page = new PageBuilder(before ?? Number.POSITIVE_INFINITY, Math.max(1, limits.pageBlocks), limits.perBlockChars, Math.max(1, limits.pageChars ?? 5e5));
|
|
4082
|
+
return {
|
|
4083
|
+
add(r) {
|
|
4084
|
+
if (typeof r.time === "number" && r.time > detail.lastActivity) detail.lastActivity = r.time;
|
|
4085
|
+
const data = r.data ?? {};
|
|
4086
|
+
const time = r.time ?? 0;
|
|
4087
|
+
switch (r.type) {
|
|
4088
|
+
case "session":
|
|
4089
|
+
if (typeof r.cwd === "string") detail.cwd = r.cwd;
|
|
4090
|
+
if (typeof r.createdAt === "number") detail.createdAt = r.createdAt;
|
|
4091
|
+
if (typeof r.parentSession === "string" && r.parentSession !== "") ownParentSession = true;
|
|
4092
|
+
return;
|
|
4093
|
+
case "session/title":
|
|
4094
|
+
if (typeof data.title === "string") detail.logTitle = data.title;
|
|
4095
|
+
return;
|
|
4096
|
+
case "subagent/descriptor":
|
|
4097
|
+
ownLabel = descriptorLabelOf(data);
|
|
4098
|
+
return;
|
|
4099
|
+
case "turn/start":
|
|
4100
|
+
detail.turnCount += 1;
|
|
4101
|
+
return;
|
|
4102
|
+
case "user/message": {
|
|
4103
|
+
const source = data.source ?? {};
|
|
4104
|
+
const sourceKind = typeof source.kind === "string" ? source.kind : "";
|
|
4105
|
+
const text = textOf(data.content);
|
|
4106
|
+
const attachments = attachmentWires(data.content);
|
|
4107
|
+
if (sourceKind === "user") {
|
|
4108
|
+
const block = textBlock("user", time, text, attachments, limits.perBlockChars);
|
|
4109
|
+
if (block !== void 0) {
|
|
4110
|
+
detail.userMessageCount += 1;
|
|
4111
|
+
const id = page.add(block);
|
|
4112
|
+
if (before === void 0 && text !== "") prompts.push({
|
|
4113
|
+
id,
|
|
4114
|
+
at: time,
|
|
4115
|
+
preview: promptPreview(text)
|
|
4116
|
+
});
|
|
4117
|
+
}
|
|
4118
|
+
return;
|
|
4119
|
+
}
|
|
4120
|
+
const block = injectionBlock(time, sourceKind, text, attachments, limits.perBlockChars);
|
|
4121
|
+
if (block !== void 0) {
|
|
4122
|
+
detail.injectedCount += 1;
|
|
4123
|
+
page.add(block);
|
|
4124
|
+
}
|
|
4125
|
+
return;
|
|
4126
|
+
}
|
|
4127
|
+
case "assistant/message": {
|
|
4128
|
+
detail.assistantMessageCount += 1;
|
|
4129
|
+
const message = data.message ?? {};
|
|
4130
|
+
const source = message.source ?? {};
|
|
4131
|
+
if (typeof source.model === "string") models.add(source.model);
|
|
4132
|
+
const parts = Array.isArray(message.content) ? message.content : [];
|
|
4133
|
+
let pendingText = [];
|
|
4134
|
+
let pendingAttachments = [];
|
|
4135
|
+
const flush = () => {
|
|
4136
|
+
const block = textBlock("assistant", time, pendingText.join("\n"), pendingAttachments, limits.perBlockChars);
|
|
4137
|
+
if (block !== void 0) page.add(block);
|
|
4138
|
+
pendingText = [];
|
|
4139
|
+
pendingAttachments = [];
|
|
4140
|
+
};
|
|
4141
|
+
for (const part of parts) {
|
|
4142
|
+
if (part?.type === "text" && typeof part.text === "string") {
|
|
4143
|
+
pendingText.push(part.text);
|
|
4144
|
+
continue;
|
|
4145
|
+
}
|
|
4146
|
+
if (part?.type === "reasoning" && typeof part.text === "string") {
|
|
4147
|
+
flush();
|
|
4148
|
+
const block = textBlock("reasoning", time, part.text, [], limits.perBlockChars);
|
|
4149
|
+
if (block !== void 0) page.add(block);
|
|
4150
|
+
continue;
|
|
4151
|
+
}
|
|
4152
|
+
if (part?.type === "image" || part?.type === "file") {
|
|
4153
|
+
pendingAttachments.push(...attachmentWires([part]));
|
|
4154
|
+
continue;
|
|
4155
|
+
}
|
|
4156
|
+
}
|
|
4157
|
+
flush();
|
|
4158
|
+
return;
|
|
4159
|
+
}
|
|
4160
|
+
case "tool/call": {
|
|
4161
|
+
detail.toolCallCount += 1;
|
|
4162
|
+
const callId = typeof data.callId === "string" ? data.callId : "";
|
|
4163
|
+
const name = typeof data.name === "string" ? data.name : "";
|
|
4164
|
+
const args = clip(typeof data.arguments === "string" ? data.arguments : "", limits.perBlockChars);
|
|
4165
|
+
page.add({
|
|
4166
|
+
kind: "tool",
|
|
4167
|
+
id: "",
|
|
4168
|
+
time,
|
|
4169
|
+
callId,
|
|
4170
|
+
name,
|
|
4171
|
+
status: "unfinished",
|
|
4172
|
+
args: args.text,
|
|
4173
|
+
argsTruncated: args.truncated,
|
|
4174
|
+
result: "",
|
|
4175
|
+
resultTruncated: false,
|
|
4176
|
+
attachments: []
|
|
4177
|
+
});
|
|
4178
|
+
return;
|
|
4179
|
+
}
|
|
4180
|
+
case "tool/result": {
|
|
4181
|
+
const message = data.message ?? {};
|
|
4182
|
+
const callId = typeof message.toolCallId === "string" ? message.toolCallId : "";
|
|
4183
|
+
if (callId === "") return;
|
|
4184
|
+
page.result(callId, textOf(message.content), message.isError === true, attachmentWires(message.content));
|
|
4185
|
+
return;
|
|
4186
|
+
}
|
|
4187
|
+
case "system/message": {
|
|
4188
|
+
const message = data.message ?? {};
|
|
4189
|
+
const block = textBlock("system", time, textOf(message.content), attachmentWires(message.content), limits.perBlockChars);
|
|
4190
|
+
if (block !== void 0) page.add(block);
|
|
4191
|
+
return;
|
|
4192
|
+
}
|
|
4193
|
+
case "compaction/summary": {
|
|
4194
|
+
const block = textBlock("compaction", time, textOf(data.summary), [], limits.perBlockChars);
|
|
4195
|
+
if (block !== void 0) page.add(block);
|
|
4196
|
+
return;
|
|
4197
|
+
}
|
|
4198
|
+
default: return;
|
|
4199
|
+
}
|
|
4200
|
+
},
|
|
4201
|
+
finish() {
|
|
4202
|
+
const finished = page.finish();
|
|
4203
|
+
detail.blocks = finished.blocks;
|
|
4204
|
+
detail.olderCursor = finished.olderCursor;
|
|
4205
|
+
if (before === void 0) detail.prompts = prompts;
|
|
4206
|
+
detail.models = [...models];
|
|
4207
|
+
const ownDisplayName = ownLabel !== "" ? ownLabel : ownParentSession ? detail.logTitle : "";
|
|
4208
|
+
if (ownDisplayName !== "") detail.label = ownDisplayName;
|
|
4209
|
+
return detail;
|
|
4210
|
+
}
|
|
4211
|
+
};
|
|
4212
|
+
}
|
|
3398
4213
|
function readTrashDetail(deps, limits = DEFAULT_LIMITS) {
|
|
3399
4214
|
return async function readTrashDetail(entryId, before) {
|
|
3400
4215
|
const all = await deps.rows();
|
|
@@ -3405,176 +4220,42 @@ function readTrashDetail(deps, limits = DEFAULT_LIMITS) {
|
|
|
3405
4220
|
const names = await deps.fs.listFiles(dir);
|
|
3406
4221
|
const logName = pickSessionLog(names);
|
|
3407
4222
|
if (logName === void 0) throw verbError("io", `回收站目录里没有会话日志:${dir}(里面有:${names.join(", ") || "空目录"})`);
|
|
4223
|
+
const logPath = `${dir}/${logName}`;
|
|
4224
|
+
let logSize;
|
|
4225
|
+
try {
|
|
4226
|
+
logSize = (await deps.fs.statFile(logPath)).size;
|
|
4227
|
+
} catch (error) {
|
|
4228
|
+
throw verbError("io", `读取会话日志大小失败:${String(error)}`, error);
|
|
4229
|
+
}
|
|
4230
|
+
if (logSize > 268435456) throw verbError("io", `会话日志 ${logSize} 字节超过整本读取上限 ${MAX_SESSION_LOG_BYTES} 字节:${logPath}`);
|
|
3408
4231
|
let raw;
|
|
3409
4232
|
try {
|
|
3410
|
-
raw = await deps.fs.readFile(
|
|
4233
|
+
raw = await deps.fs.readFile(logPath);
|
|
3411
4234
|
} catch (error) {
|
|
3412
4235
|
throw verbError("io", `读会话日志失败:${String(error)}`, error);
|
|
3413
4236
|
}
|
|
3414
|
-
const
|
|
3415
|
-
entryId: record.id,
|
|
3416
|
-
cwd: "",
|
|
3417
|
-
createdAt: 0,
|
|
3418
|
-
lastActivity: 0,
|
|
3419
|
-
logTitle: "",
|
|
3420
|
-
models: [],
|
|
3421
|
-
turnCount: 0,
|
|
3422
|
-
userMessageCount: 0,
|
|
3423
|
-
assistantMessageCount: 0,
|
|
3424
|
-
toolCallCount: 0,
|
|
3425
|
-
injectedCount: 0,
|
|
3426
|
-
blocks: [],
|
|
3427
|
-
olderCursor: null
|
|
3428
|
-
};
|
|
3429
|
-
const models = /* @__PURE__ */ new Set();
|
|
4237
|
+
const fold = createDetailFold(limits, before);
|
|
3430
4238
|
/** 子会话的显示名(bare id → label):父日志的 `subagent/catalog` 事件逐孩子记着委派时的
|
|
3431
|
-
* `description`(与宿主工作中同名)。清册标题是删除那一刻的快照,起错名的存量条目靠它兜(ADR-0058)。
|
|
4239
|
+
* `description`(与宿主工作中同名)。清册标题是删除那一刻的快照,起错名的存量条目靠它兜(ADR-0058)。
|
|
4240
|
+
* 登记住这里、不住折叠核心:它只服务回收站子会话段。 */
|
|
3432
4241
|
const subagentLabels = /* @__PURE__ */ new Map();
|
|
3433
|
-
/** 这条会话**自己**的 descriptor label(独立子会话没有父日志可查时的兜底)。
|
|
3434
|
-
* 与宿主 `subagent` 投影同一语义:每遇一条 descriptor 就覆盖,空 label 重置——fork 种子里的
|
|
3435
|
-
* 祖先 descriptor 必须被子会话自己的那条覆盖,坏/空的后写不保留祖先的名字。 */
|
|
3436
|
-
let ownLabel = "";
|
|
3437
|
-
/** 这条会话的 header 带 `parentSession`:它是子会话(fork / subagent),自己的日志标题才是
|
|
3438
|
-
* 当前名字;主会话没有这一格,仍按清册快照优先。 */
|
|
3439
|
-
let ownParentSession = false;
|
|
3440
|
-
/** 整条会话的提问索引:与分页无关,只在首次读时过线(见 `TrashDetailWire.prompts`)。 */
|
|
3441
|
-
const prompts = [];
|
|
3442
|
-
const page = new PageBuilder(before ?? Number.POSITIVE_INFINITY, Math.max(1, limits.pageBlocks), limits.perBlockChars, Math.max(1, limits.pageChars ?? 5e5));
|
|
3443
4242
|
try {
|
|
3444
4243
|
walkSessionLog(raw, (r) => {
|
|
3445
|
-
if (
|
|
3446
|
-
|
|
3447
|
-
|
|
3448
|
-
|
|
3449
|
-
|
|
3450
|
-
if (typeof r.cwd === "string") detail.cwd = r.cwd;
|
|
3451
|
-
if (typeof r.createdAt === "number") detail.createdAt = r.createdAt;
|
|
3452
|
-
if (typeof r.parentSession === "string" && r.parentSession !== "") ownParentSession = true;
|
|
3453
|
-
return;
|
|
3454
|
-
case "session/title":
|
|
3455
|
-
if (typeof data.title === "string") detail.logTitle = data.title;
|
|
3456
|
-
return;
|
|
3457
|
-
case "subagent/catalog": {
|
|
3458
|
-
const childId = data.childId;
|
|
3459
|
-
const label = data.label;
|
|
3460
|
-
if (typeof childId === "string" && childId !== "" && typeof label === "string" && label !== "") subagentLabels.set(bareSessionId(childId), label);
|
|
3461
|
-
return;
|
|
3462
|
-
}
|
|
3463
|
-
case "subagent/descriptor":
|
|
3464
|
-
ownLabel = descriptorLabelOf(data);
|
|
3465
|
-
return;
|
|
3466
|
-
case "turn/start":
|
|
3467
|
-
detail.turnCount += 1;
|
|
3468
|
-
return;
|
|
3469
|
-
case "user/message": {
|
|
3470
|
-
const source = data.source ?? {};
|
|
3471
|
-
const sourceKind = typeof source.kind === "string" ? source.kind : "";
|
|
3472
|
-
const text = textOf(data.content);
|
|
3473
|
-
const attachments = attachmentWires(data.content);
|
|
3474
|
-
if (sourceKind === "user") {
|
|
3475
|
-
const block = textBlock("user", time, text, attachments, limits.perBlockChars);
|
|
3476
|
-
if (block !== void 0) {
|
|
3477
|
-
detail.userMessageCount += 1;
|
|
3478
|
-
const id = page.add(block);
|
|
3479
|
-
if (before === void 0 && text !== "") prompts.push({
|
|
3480
|
-
id,
|
|
3481
|
-
at: time,
|
|
3482
|
-
preview: promptPreview(text)
|
|
3483
|
-
});
|
|
3484
|
-
}
|
|
3485
|
-
return;
|
|
3486
|
-
}
|
|
3487
|
-
const block = injectionBlock(time, sourceKind, text, attachments, limits.perBlockChars);
|
|
3488
|
-
if (block !== void 0) {
|
|
3489
|
-
detail.injectedCount += 1;
|
|
3490
|
-
page.add(block);
|
|
3491
|
-
}
|
|
3492
|
-
return;
|
|
3493
|
-
}
|
|
3494
|
-
case "assistant/message": {
|
|
3495
|
-
detail.assistantMessageCount += 1;
|
|
3496
|
-
const message = data.message ?? {};
|
|
3497
|
-
const source = message.source ?? {};
|
|
3498
|
-
if (typeof source.model === "string") models.add(source.model);
|
|
3499
|
-
const parts = Array.isArray(message.content) ? message.content : [];
|
|
3500
|
-
let pendingText = [];
|
|
3501
|
-
let pendingAttachments = [];
|
|
3502
|
-
const flush = () => {
|
|
3503
|
-
const block = textBlock("assistant", time, pendingText.join("\n"), pendingAttachments, limits.perBlockChars);
|
|
3504
|
-
if (block !== void 0) page.add(block);
|
|
3505
|
-
pendingText = [];
|
|
3506
|
-
pendingAttachments = [];
|
|
3507
|
-
};
|
|
3508
|
-
for (const part of parts) {
|
|
3509
|
-
if (part?.type === "text" && typeof part.text === "string") {
|
|
3510
|
-
pendingText.push(part.text);
|
|
3511
|
-
continue;
|
|
3512
|
-
}
|
|
3513
|
-
if (part?.type === "reasoning" && typeof part.text === "string") {
|
|
3514
|
-
flush();
|
|
3515
|
-
const block = textBlock("reasoning", time, part.text, [], limits.perBlockChars);
|
|
3516
|
-
if (block !== void 0) page.add(block);
|
|
3517
|
-
continue;
|
|
3518
|
-
}
|
|
3519
|
-
if (part?.type === "image" || part?.type === "file") {
|
|
3520
|
-
pendingAttachments.push(...attachmentWires([part]));
|
|
3521
|
-
continue;
|
|
3522
|
-
}
|
|
3523
|
-
}
|
|
3524
|
-
flush();
|
|
3525
|
-
return;
|
|
3526
|
-
}
|
|
3527
|
-
case "tool/call": {
|
|
3528
|
-
detail.toolCallCount += 1;
|
|
3529
|
-
const callId = typeof data.callId === "string" ? data.callId : "";
|
|
3530
|
-
const name = typeof data.name === "string" ? data.name : "";
|
|
3531
|
-
const args = clip(typeof data.arguments === "string" ? data.arguments : "", limits.perBlockChars);
|
|
3532
|
-
page.add({
|
|
3533
|
-
kind: "tool",
|
|
3534
|
-
id: "",
|
|
3535
|
-
time,
|
|
3536
|
-
callId,
|
|
3537
|
-
name,
|
|
3538
|
-
status: "unfinished",
|
|
3539
|
-
args: args.text,
|
|
3540
|
-
argsTruncated: args.truncated,
|
|
3541
|
-
result: "",
|
|
3542
|
-
resultTruncated: false,
|
|
3543
|
-
attachments: []
|
|
3544
|
-
});
|
|
3545
|
-
return;
|
|
3546
|
-
}
|
|
3547
|
-
case "tool/result": {
|
|
3548
|
-
const message = data.message ?? {};
|
|
3549
|
-
const callId = typeof message.toolCallId === "string" ? message.toolCallId : "";
|
|
3550
|
-
if (callId === "") return;
|
|
3551
|
-
page.result(callId, textOf(message.content), message.isError === true, attachmentWires(message.content));
|
|
3552
|
-
return;
|
|
3553
|
-
}
|
|
3554
|
-
case "system/message": {
|
|
3555
|
-
const message = data.message ?? {};
|
|
3556
|
-
const block = textBlock("system", time, textOf(message.content), attachmentWires(message.content), limits.perBlockChars);
|
|
3557
|
-
if (block !== void 0) page.add(block);
|
|
3558
|
-
return;
|
|
3559
|
-
}
|
|
3560
|
-
case "compaction/summary": {
|
|
3561
|
-
const block = textBlock("compaction", time, textOf(data.summary), [], limits.perBlockChars);
|
|
3562
|
-
if (block !== void 0) page.add(block);
|
|
3563
|
-
return;
|
|
3564
|
-
}
|
|
3565
|
-
default: return;
|
|
4244
|
+
if (r.type === "subagent/catalog") {
|
|
4245
|
+
const data = r.data ?? {};
|
|
4246
|
+
const childId = data.childId;
|
|
4247
|
+
const label = data.label;
|
|
4248
|
+
if (typeof childId === "string" && childId !== "" && typeof label === "string" && label !== "") subagentLabels.set(bareSessionId(childId), label);
|
|
3566
4249
|
}
|
|
4250
|
+
fold.add(r);
|
|
3567
4251
|
});
|
|
3568
4252
|
} catch (error) {
|
|
3569
4253
|
throw verbError("io", error instanceof Error ? `读回收站日志失败:${error.message}` : `读回收站日志失败:${String(error)}`, error);
|
|
3570
4254
|
}
|
|
3571
|
-
const
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
detail.models = [...models];
|
|
3576
|
-
const ownDisplayName = ownLabel !== "" ? ownLabel : ownParentSession ? detail.logTitle : "";
|
|
3577
|
-
if (ownDisplayName !== "") detail.label = ownDisplayName;
|
|
4255
|
+
const detail = {
|
|
4256
|
+
entryId: record.id,
|
|
4257
|
+
...fold.finish()
|
|
4258
|
+
};
|
|
3578
4259
|
const kids = visibleGroups(all).find((group) => group.root.id === record.id)?.kids ?? [];
|
|
3579
4260
|
if (kids.length > 0) {
|
|
3580
4261
|
const limit = limits.subagents ?? 200;
|
|
@@ -3609,6 +4290,112 @@ function readTrashDetail(deps, limits = DEFAULT_LIMITS) {
|
|
|
3609
4290
|
};
|
|
3610
4291
|
}
|
|
3611
4292
|
//#endregion
|
|
4293
|
+
//#region src/trash/archive-detail.ts
|
|
4294
|
+
/** `readSession` 抛的宿主失败码(`SessionQueryError.code`):未知 id / 已无盘上记录。 */
|
|
4295
|
+
const SESSION_QUERY_SESSION_NOT_FOUND = "SESSION_QUERY_SESSION_NOT_FOUND";
|
|
4296
|
+
/** 「不在寻址边界内」的原文只此一份:三处 not-found 同句,cause 有就挂。 */
|
|
4297
|
+
const notInArchive = (sessionId, cause) => verbError("not-found", `归档里没有这一条:${sessionId}`, cause);
|
|
4298
|
+
function readArchiveDetail(deps, limits) {
|
|
4299
|
+
return async function readArchiveDetail(sessionId, before, rootSessionId) {
|
|
4300
|
+
const selfArchived = await assertArchiveReadable(deps, sessionId, rootSessionId);
|
|
4301
|
+
let session;
|
|
4302
|
+
let events;
|
|
4303
|
+
try {
|
|
4304
|
+
const read = await deps.host.readSession(sessionId);
|
|
4305
|
+
session = read.session;
|
|
4306
|
+
events = read.events;
|
|
4307
|
+
} catch (error) {
|
|
4308
|
+
if (error.code === SESSION_QUERY_SESSION_NOT_FOUND) throw notInArchive(sessionId, error);
|
|
4309
|
+
throw verbError("io", error instanceof Error ? `读归档日志失败:${error.message}` : `读归档日志失败:${String(error)}`, error);
|
|
4310
|
+
}
|
|
4311
|
+
const fold = createDetailFold(limits, before);
|
|
4312
|
+
const header = {
|
|
4313
|
+
type: "session",
|
|
4314
|
+
...typeof session.createdAt === "number" ? { createdAt: session.createdAt } : {},
|
|
4315
|
+
...typeof session.cwd === "string" ? { cwd: session.cwd } : {},
|
|
4316
|
+
...typeof session.parentSession === "string" ? { parentSession: session.parentSession } : {}
|
|
4317
|
+
};
|
|
4318
|
+
fold.add(header);
|
|
4319
|
+
for (const event of events) fold.add({
|
|
4320
|
+
type: event.type,
|
|
4321
|
+
time: event.time,
|
|
4322
|
+
data: event.data
|
|
4323
|
+
});
|
|
4324
|
+
const detail = {
|
|
4325
|
+
sessionId,
|
|
4326
|
+
archived: selfArchived,
|
|
4327
|
+
...fold.finish()
|
|
4328
|
+
};
|
|
4329
|
+
if (selfArchived) {
|
|
4330
|
+
let subagents;
|
|
4331
|
+
try {
|
|
4332
|
+
subagents = await readArchiveSubagents(deps, sessionId, limits);
|
|
4333
|
+
} catch {
|
|
4334
|
+
subagents = void 0;
|
|
4335
|
+
}
|
|
4336
|
+
if (subagents !== void 0) {
|
|
4337
|
+
detail.subagents = subagents.rows;
|
|
4338
|
+
if (subagents.total !== void 0) detail.subagentsTotal = subagents.total;
|
|
4339
|
+
if (subagents.sizeBytes !== void 0) detail.subagentsSizeBytes = subagents.sizeBytes;
|
|
4340
|
+
}
|
|
4341
|
+
}
|
|
4342
|
+
return detail;
|
|
4343
|
+
};
|
|
4344
|
+
}
|
|
4345
|
+
/** 归档详情读的寻址边界:目标自己已归档回 `true`(主体,子会话段照常装配);仅凭
|
|
4346
|
+
* `rootSessionId` 那条已归档根的闭包成员放行回 `false`(只读视图,不装配那一段)。
|
|
4347
|
+
* 其余一律 not-found。闭包读不出时失败关闭(`io`),不把「证明不了」当成「可以读」。 */
|
|
4348
|
+
async function assertArchiveReadable(deps, sessionId, rootSessionId) {
|
|
4349
|
+
if (await deps.host.isArchived(sessionId)) return true;
|
|
4350
|
+
if (rootSessionId === void 0 || !await deps.host.isArchived(rootSessionId)) throw notInArchive(sessionId);
|
|
4351
|
+
let members;
|
|
4352
|
+
try {
|
|
4353
|
+
members = await deps.host.subagentMembersOf([rootSessionId]);
|
|
4354
|
+
} catch (error) {
|
|
4355
|
+
throw verbError("io", error instanceof Error ? `读归档子会话闭包失败:${error.message}` : `读归档子会话闭包失败:${String(error)}`, error);
|
|
4356
|
+
}
|
|
4357
|
+
if (!members.available) throw verbError("io", `归档子会话闭包读不出,无法校验:${sessionId}`);
|
|
4358
|
+
const target = bareSessionId(sessionId);
|
|
4359
|
+
if (!(members.value[rootSessionId] ?? []).some((kid) => bareSessionId(kid.sessionId) === target)) throw notInArchive(sessionId);
|
|
4360
|
+
return false;
|
|
4361
|
+
}
|
|
4362
|
+
/** 归档详情的子会话只读投影:宿主闭包 + `session-rows.ts` 那一份行读数——按输出计划只装配
|
|
4363
|
+
* 显示的那几行,摘要条的合计覆盖全部孩子。 */
|
|
4364
|
+
async function readArchiveSubagents(deps, sessionId, limits) {
|
|
4365
|
+
const members = await deps.host.subagentMembersOf([sessionId]);
|
|
4366
|
+
if (!members.available) return void 0;
|
|
4367
|
+
const kids = members.value[sessionId] ?? [];
|
|
4368
|
+
if (kids.length === 0) return void 0;
|
|
4369
|
+
const limit = limits?.subagents ?? 200;
|
|
4370
|
+
const displayed = kids.slice(0, limit);
|
|
4371
|
+
const surfaces = await readRowSurfaces(deps, displayed.map((kid) => kid.sessionId), { sizeFailure: "absent" });
|
|
4372
|
+
const facts = await projectRowFacts(deps, surfaces, displayed.map((kid) => ({
|
|
4373
|
+
sessionId: kid.sessionId,
|
|
4374
|
+
wantsLabel: true
|
|
4375
|
+
})));
|
|
4376
|
+
const archived = await Promise.all(displayed.map((kid) => deps.host.isArchived(kid.sessionId)));
|
|
4377
|
+
const totals = sizeTotalsForIds(kids.map((kid) => kid.sessionId), surfaces.sizes);
|
|
4378
|
+
return {
|
|
4379
|
+
rows: facts.flatMap((fact, index) => {
|
|
4380
|
+
const kid = displayed[index];
|
|
4381
|
+
const isArchived = archived[index];
|
|
4382
|
+
if (kid === void 0 || isArchived === void 0) return [];
|
|
4383
|
+
return [{
|
|
4384
|
+
sessionId: kid.sessionId,
|
|
4385
|
+
archived: isArchived,
|
|
4386
|
+
projectDir: kid.projectDir,
|
|
4387
|
+
title: fact.title,
|
|
4388
|
+
...fact.label === void 0 ? {} : { label: fact.label },
|
|
4389
|
+
...fact.updatedAt === void 0 ? {} : { updatedAt: fact.updatedAt },
|
|
4390
|
+
...fact.updatedAtSource === void 0 ? {} : { updatedAtSource: fact.updatedAtSource },
|
|
4391
|
+
...fact.sizeBytes === void 0 ? {} : { sizeBytes: fact.sizeBytes }
|
|
4392
|
+
}];
|
|
4393
|
+
}),
|
|
4394
|
+
...kids.length > limit ? { total: kids.length } : {},
|
|
4395
|
+
...totals.missingSizeCount === kids.length ? {} : { sizeBytes: totals.totalBytes }
|
|
4396
|
+
};
|
|
4397
|
+
}
|
|
4398
|
+
//#endregion
|
|
3612
4399
|
//#region src/ports/attachments-port.ts
|
|
3613
4400
|
/** 服务在 `available()` 之后消失/形状变了:调用方可以退回直接 fs,而不是把这次读取判成 io。 */
|
|
3614
4401
|
var AttachmentsUnavailableError = class extends Error {
|
|
@@ -3912,6 +4699,40 @@ async function assembleTrashRows(deps, rows) {
|
|
|
3912
4699
|
}));
|
|
3913
4700
|
}
|
|
3914
4701
|
//#endregion
|
|
4702
|
+
//#region src/api/archive-rows.ts
|
|
4703
|
+
async function assembleArchiveRows(deps) {
|
|
4704
|
+
const archived = await deps.host.archivedSessionIds();
|
|
4705
|
+
const corpus = await deps.host.listSessions();
|
|
4706
|
+
if (!corpus.available) return { available: false };
|
|
4707
|
+
const archivedSet = new Set(archived);
|
|
4708
|
+
const identities = corpus.value.filter((row) => archivedSet.has(row.sessionId));
|
|
4709
|
+
const facts = await projectSessionRows(deps, identities.map((identity) => ({
|
|
4710
|
+
sessionId: identity.sessionId,
|
|
4711
|
+
...identity.createdAt === void 0 || identity.createdAt <= 0 ? {} : { createdAt: identity.createdAt },
|
|
4712
|
+
wantsLabel: identity.subagent
|
|
4713
|
+
})), { sizeFailure: "throw" });
|
|
4714
|
+
const { totalBytes, missingSizeCount } = sizeTotals(facts);
|
|
4715
|
+
return {
|
|
4716
|
+
available: true,
|
|
4717
|
+
rows: facts.flatMap((fact, index) => {
|
|
4718
|
+
const identity = identities[index];
|
|
4719
|
+
if (identity === void 0) return [];
|
|
4720
|
+
return [{
|
|
4721
|
+
sessionId: identity.sessionId,
|
|
4722
|
+
projectDir: identity.projectDir,
|
|
4723
|
+
title: fact.title,
|
|
4724
|
+
...fact.label === void 0 ? {} : { label: fact.label },
|
|
4725
|
+
...fact.updatedAt === void 0 ? {} : { updatedAt: fact.updatedAt },
|
|
4726
|
+
...fact.updatedAtSource === void 0 ? {} : { updatedAtSource: fact.updatedAtSource },
|
|
4727
|
+
...fact.sizeBytes === void 0 ? {} : { sizeBytes: fact.sizeBytes },
|
|
4728
|
+
subagent: identity.subagent
|
|
4729
|
+
}];
|
|
4730
|
+
}),
|
|
4731
|
+
totalBytes,
|
|
4732
|
+
missingSizeCount
|
|
4733
|
+
};
|
|
4734
|
+
}
|
|
4735
|
+
//#endregion
|
|
3915
4736
|
//#region src/api/route-table.ts
|
|
3916
4737
|
/**
|
|
3917
4738
|
* 路由表(ADR-0004;deps 切片见 ADR-0032):段名 → { 方法, 纯度, 读面, body, deps 切片, 处理 }。一条记录,两个消费者。
|
|
@@ -3923,8 +4744,9 @@ async function assembleTrashRows(deps, rows) {
|
|
|
3923
4744
|
* - 切片声明宽了 ⇒ 危险能力(删目录 / 时钟)漏进读段的 run;窄了 ⇒ 写段的处理编译不过。
|
|
3924
4745
|
*
|
|
3925
4746
|
* 这张表不放 shared/wire.ts:处理函数会 import 动词与 node:fs,而浏览器半要 import wire.ts。
|
|
3926
|
-
*
|
|
3927
|
-
*
|
|
4747
|
+
* 段名、方法、请求体形状与字段组描述住 wire.ts(`ROUTES` 每项 `{ path, method, body }`,本表的 method /
|
|
4748
|
+
* body 由 `defineRoute` 从段名表那一格派生、不写第二份字面量;字段组描述 `BODY_GROUPS` 由本表的
|
|
4749
|
+
* 通用解析手消费);这张表只回答“怎么处理”。
|
|
3928
4750
|
*/
|
|
3929
4751
|
/** 段名表那一格 → 分发器要不要预读 JSON。`satisfies` 让每个 `RouteBody` 值都必须在这里有
|
|
3930
4752
|
* 明确的一格:以后加一种 body,缺了映射就是编译错,不会被默认折成 JSON 预读。 */
|
|
@@ -3933,28 +4755,33 @@ const BODY_KIND = {
|
|
|
3933
4755
|
query: "none",
|
|
3934
4756
|
config: "json",
|
|
3935
4757
|
entry: "json",
|
|
3936
|
-
apply: "json"
|
|
4758
|
+
apply: "json",
|
|
4759
|
+
sessionId: "json"
|
|
3937
4760
|
};
|
|
3938
4761
|
/** 读的是 wire 那一格(`ROUTES.x.body`),本表不写第二份:无字段与查询串段不读;
|
|
3939
|
-
* 带 JSON 字段的段(config / entry / apply
|
|
4762
|
+
* 带 JSON 字段的段(config / entry / apply / sessionId)读一次。`defineRoute` 据此填行的 `body`。 */
|
|
3940
4763
|
function bodyOf(route) {
|
|
3941
4764
|
return BODY_KIND[route.body];
|
|
3942
4765
|
}
|
|
3943
|
-
|
|
3944
|
-
|
|
3945
|
-
|
|
3946
|
-
|
|
3947
|
-
|
|
4766
|
+
function defineRoute(name, decision) {
|
|
4767
|
+
const seg = ROUTES[name];
|
|
4768
|
+
return {
|
|
4769
|
+
name,
|
|
4770
|
+
spec: {
|
|
4771
|
+
...decision,
|
|
4772
|
+
response: decision.response ?? "json",
|
|
4773
|
+
method: seg.method,
|
|
4774
|
+
body: bodyOf(seg)
|
|
4775
|
+
}
|
|
4776
|
+
};
|
|
3948
4777
|
}
|
|
3949
|
-
/**
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw routeError("bad-request", 400, `请求体字段 ${PARAMS.before} 需是非负整数`);
|
|
3954
|
-
return value;
|
|
4778
|
+
/** 组装整张表:键从条目的段名派生(`ROUTES[name].path`)——行文里没有手写的键,
|
|
4779
|
+
* 缺键 / 多键 / 名不对号(这一格的 key 与 `defineRoute` 的段名不同源)都编译不过。 */
|
|
4780
|
+
function createRouteTable(rows) {
|
|
4781
|
+
return Object.fromEntries(Object.values(rows).map((entry) => [ROUTES[entry.name].path, entry.spec]));
|
|
3955
4782
|
}
|
|
3956
4783
|
/**
|
|
3957
|
-
* `/apply`
|
|
4784
|
+
* `/apply` 的六个动作与各自的**静态纯度**。一张表三个用途:动作名单由键派生,纯度从同一格读,
|
|
3958
4785
|
* 唯一识别器(`actionOf`)也只认这些键——新增动作必须同时给出纯度,漏了编译不过;
|
|
3959
4786
|
* 新加一个纯读动作也不会再静默落进 `chained`。
|
|
3960
4787
|
*/
|
|
@@ -3963,139 +4790,193 @@ const APPLY_ACTION_TABLE = {
|
|
|
3963
4790
|
restore: "chained",
|
|
3964
4791
|
purge: "chained",
|
|
3965
4792
|
count: "pure",
|
|
3966
|
-
"orphan-clean": "chained"
|
|
4793
|
+
"orphan-clean": "chained",
|
|
4794
|
+
unarchive: "chained"
|
|
3967
4795
|
};
|
|
3968
4796
|
const APPLY_ACTIONS = Object.keys(APPLY_ACTION_TABLE);
|
|
3969
4797
|
/**
|
|
3970
|
-
* `/apply`
|
|
4798
|
+
* `/apply` 的动作:**全仓唯一识别器**——纯度函数与字段闸的动作拒否都从这里过,
|
|
3971
4799
|
* 不各解析一遍动作。不抛:缺动作 / 不是字符串 / 不在名单,一律回 `undefined`;
|
|
3972
|
-
*
|
|
4800
|
+
* 抛不抛、抛哪句话归通用解析手({@link parseBody})。
|
|
3973
4801
|
*/
|
|
3974
|
-
function
|
|
3975
|
-
const value = body?.[PARAMS.action];
|
|
4802
|
+
function actionValueOf(value) {
|
|
3976
4803
|
if (typeof value !== "string" || !Object.hasOwn(APPLY_ACTION_TABLE, value)) return void 0;
|
|
3977
4804
|
return value;
|
|
3978
4805
|
}
|
|
3979
|
-
|
|
3980
|
-
|
|
3981
|
-
const action = actionOf(body);
|
|
3982
|
-
if (action === void 0) throw routeError("bad-request", 400, `批量动作不认识:需是 ${APPLY_ACTIONS.join(" / ")} 之一`);
|
|
3983
|
-
return action;
|
|
4806
|
+
function actionOf(body) {
|
|
4807
|
+
return actionValueOf(body?.[PARAMS.action]);
|
|
3984
4808
|
}
|
|
3985
|
-
/**
|
|
3986
|
-
|
|
3987
|
-
|
|
3988
|
-
|
|
3989
|
-
|
|
4809
|
+
/**
|
|
4810
|
+
* 请求字段组的**通用解析手**:wire 的描述(`BODY_GROUPS`,字段键 + 种类)→ typed 字段。
|
|
4811
|
+
* 必填串 / 可选串 / 游标 / 动作 / id 组五种读法收成 {@link readField} 的五条分支——描述里加一个
|
|
4812
|
+
* 字段不用再添一只手,`ParsedBody` 的类型与拒绝原文都从同一份描述派生。
|
|
4813
|
+
*
|
|
4814
|
+
* 按**描述的声明序**逐格读:`apply` 组先 `action` 后 `ids`,动作拒否必须先于 ids 栅栏
|
|
4815
|
+
* (`tests/route-table.test.ts` 的动作表用例靠这个顺序证明「已过识别器」,改描述或这里
|
|
4816
|
+
* 的读序前先回去核那句)。
|
|
4817
|
+
*/
|
|
4818
|
+
function parseBody(body, group) {
|
|
4819
|
+
const fields = {};
|
|
4820
|
+
for (const [field, kind] of Object.entries(group)) fields[field] = readField(body, field, kind);
|
|
4821
|
+
return fields;
|
|
4822
|
+
}
|
|
4823
|
+
/** 描述里的一个字段读成它的值:五种种类各一句 400 原文(请求本身不对,不是操作失败),
|
|
4824
|
+
* 原文只住这一处——`tests/api.test.ts` 与 `tests/route-table.test.ts` 逐字钉着它们。 */
|
|
4825
|
+
function readField(body, field, kind) {
|
|
4826
|
+
const value = body?.[field];
|
|
4827
|
+
switch (kind) {
|
|
4828
|
+
case "requiredString":
|
|
4829
|
+
if (typeof value !== "string" || value === "") throw routeError("bad-request", 400, `请求体需带非空字符串字段 ${field}`);
|
|
4830
|
+
return value;
|
|
4831
|
+
case "optionalString":
|
|
4832
|
+
if (value === void 0) return void 0;
|
|
4833
|
+
if (typeof value !== "string" || value === "") throw routeError("bad-request", 400, `请求体字段 ${field} 需是非空字符串`);
|
|
4834
|
+
return value;
|
|
4835
|
+
case "optionalCursor":
|
|
4836
|
+
if (value === void 0) return void 0;
|
|
4837
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw routeError("bad-request", 400, `请求体字段 ${field} 需是非负整数`);
|
|
4838
|
+
return value;
|
|
4839
|
+
case "action": {
|
|
4840
|
+
const action = actionValueOf(value);
|
|
4841
|
+
if (action === void 0) throw routeError("bad-request", 400, `批量动作不认识:需是 ${APPLY_ACTIONS.join(" / ")} 之一`);
|
|
4842
|
+
return action;
|
|
4843
|
+
}
|
|
4844
|
+
case "idArray":
|
|
4845
|
+
if (!Array.isArray(value) || value.length === 0 || value.some((id) => typeof id !== "string" || id === "")) throw routeError("bad-request", 400, `请求体需带 ${field}:非空字符串组成的非空数组`);
|
|
4846
|
+
return value;
|
|
4847
|
+
default: return kind;
|
|
4848
|
+
}
|
|
3990
4849
|
}
|
|
3991
4850
|
/**
|
|
3992
|
-
*
|
|
4851
|
+
* 段名表逐行:键是段名(`createRouteTable` 按条目的段名派生成 `ROUTES[name].path`,行文里不手写键),
|
|
4852
|
+
* 值经 `defineRoute` 构造。`Record<段名, AnyRouteSpec>` 是闸:`wire.ts` 加了段名而这里没加,编译不过;
|
|
3993
4853
|
* 每行的 `slice` 又把该行的 `run` 钉在自己那一格 deps 上(ADR-0032)。
|
|
3994
4854
|
*/
|
|
3995
|
-
const ROUTE_TABLE = {
|
|
3996
|
-
|
|
4855
|
+
const ROUTE_TABLE = createRouteTable({
|
|
4856
|
+
list: defineRoute("list", {
|
|
3997
4857
|
slice: "core",
|
|
3998
|
-
method: ROUTES.list.method,
|
|
3999
|
-
body: bodyOf(ROUTES.list),
|
|
4000
4858
|
purity: "chained",
|
|
4001
4859
|
read: "list",
|
|
4002
4860
|
response: "json",
|
|
4003
4861
|
run: async (deps, _body, read) => assembleTrashRows(deps, await read.rows())
|
|
4004
|
-
},
|
|
4005
|
-
|
|
4862
|
+
}),
|
|
4863
|
+
ping: defineRoute("ping", {
|
|
4006
4864
|
slice: "core",
|
|
4007
|
-
method: ROUTES.ping.method,
|
|
4008
|
-
body: bodyOf(ROUTES.ping),
|
|
4009
4865
|
purity: "pure",
|
|
4010
4866
|
read: "none",
|
|
4011
4867
|
response: "json",
|
|
4012
4868
|
run: async () => "pong"
|
|
4013
|
-
},
|
|
4014
|
-
|
|
4869
|
+
}),
|
|
4870
|
+
config: defineRoute("config", {
|
|
4015
4871
|
slice: "config",
|
|
4016
|
-
method: ROUTES.config.method,
|
|
4017
|
-
body: bodyOf(ROUTES.config),
|
|
4018
4872
|
purity: (body) => configPatchOf(body) === void 0 ? "pure" : "chained",
|
|
4019
4873
|
read: "none",
|
|
4020
4874
|
response: "json",
|
|
4021
4875
|
run: async (deps, body) => readOrSaveConfig(deps, body)
|
|
4022
|
-
},
|
|
4023
|
-
|
|
4876
|
+
}),
|
|
4877
|
+
attachment: defineRoute("attachment", {
|
|
4024
4878
|
slice: "attachment",
|
|
4025
|
-
method: ROUTES.attachment.method,
|
|
4026
|
-
body: bodyOf(ROUTES.attachment),
|
|
4027
4879
|
purity: "pure",
|
|
4028
4880
|
read: "none",
|
|
4029
4881
|
response: "binary",
|
|
4030
4882
|
fetchGate: "same-origin",
|
|
4031
4883
|
run: async (deps, query) => readAttachmentResponse(deps, query)
|
|
4032
|
-
},
|
|
4033
|
-
|
|
4884
|
+
}),
|
|
4885
|
+
attachmentOrphans: defineRoute("attachmentOrphans", {
|
|
4034
4886
|
slice: "core",
|
|
4035
|
-
method: ROUTES.attachmentOrphans.method,
|
|
4036
|
-
body: bodyOf(ROUTES.attachmentOrphans),
|
|
4037
4887
|
purity: "pure",
|
|
4038
4888
|
read: "none",
|
|
4039
4889
|
response: "json",
|
|
4040
4890
|
run: async (deps) => reportAttachmentOrphans(deps)
|
|
4041
|
-
},
|
|
4042
|
-
|
|
4891
|
+
}),
|
|
4892
|
+
attachmentClean: defineRoute("attachmentClean", {
|
|
4043
4893
|
slice: "removal",
|
|
4044
|
-
method: ROUTES.attachmentClean.method,
|
|
4045
|
-
body: bodyOf(ROUTES.attachmentClean),
|
|
4046
4894
|
purity: "chained",
|
|
4047
4895
|
read: "none",
|
|
4048
4896
|
response: "json",
|
|
4049
4897
|
run: async (deps) => cleanOrphanImageAttachments(deps)
|
|
4050
|
-
},
|
|
4051
|
-
|
|
4898
|
+
}),
|
|
4899
|
+
projectionOrphans: defineRoute("projectionOrphans", {
|
|
4900
|
+
slice: "core",
|
|
4901
|
+
purity: "pure",
|
|
4902
|
+
read: "raw",
|
|
4903
|
+
response: "json",
|
|
4904
|
+
run: async (deps, _body, read) => reportProjectionCacheOrphans(deps, await read.rows())
|
|
4905
|
+
}),
|
|
4906
|
+
projectionClean: defineRoute("projectionClean", {
|
|
4907
|
+
slice: "removal",
|
|
4908
|
+
purity: "chained",
|
|
4909
|
+
read: "raw",
|
|
4910
|
+
response: "json",
|
|
4911
|
+
run: async (deps, _body, read) => cleanProjectionCacheOrphans(deps, await read.rows())
|
|
4912
|
+
}),
|
|
4913
|
+
orphans: defineRoute("orphans", {
|
|
4052
4914
|
slice: "core",
|
|
4053
|
-
method: ROUTES.orphans.method,
|
|
4054
|
-
body: bodyOf(ROUTES.orphans),
|
|
4055
4915
|
purity: "pure",
|
|
4056
4916
|
read: "raw",
|
|
4057
4917
|
response: "json",
|
|
4058
4918
|
run: async (deps, _body, read) => reportOrphans(await loadOrphanGroups(deps, await read.rows()))
|
|
4059
|
-
},
|
|
4060
|
-
|
|
4919
|
+
}),
|
|
4920
|
+
apply: defineRoute("apply", {
|
|
4061
4921
|
slice: "full",
|
|
4062
|
-
method: ROUTES.apply.method,
|
|
4063
|
-
body: bodyOf(ROUTES.apply),
|
|
4064
4922
|
purity: (body) => {
|
|
4065
4923
|
const action = actionOf(body);
|
|
4066
4924
|
return action === void 0 ? "chained" : APPLY_ACTION_TABLE[action];
|
|
4067
4925
|
},
|
|
4068
4926
|
read: "none",
|
|
4069
4927
|
response: "json",
|
|
4070
|
-
run: async (deps, body) =>
|
|
4071
|
-
|
|
4072
|
-
|
|
4928
|
+
run: async (deps, body) => {
|
|
4929
|
+
const fields = parseBody(body, BODY_GROUPS.apply);
|
|
4930
|
+
return applyActions(deps, fields.action, fields.ids);
|
|
4931
|
+
}
|
|
4932
|
+
}),
|
|
4933
|
+
empty: defineRoute("empty", {
|
|
4073
4934
|
slice: "removal",
|
|
4074
|
-
method: ROUTES.empty.method,
|
|
4075
|
-
body: bodyOf(ROUTES.empty),
|
|
4076
4935
|
purity: "chained",
|
|
4077
4936
|
read: "list",
|
|
4078
4937
|
response: "json",
|
|
4079
4938
|
run: async (deps, _body, read) => {
|
|
4080
|
-
return await createTrashScope(deps, await read.rows()).purgeAll();
|
|
4939
|
+
return await createTrashScope(deps, await read.rows(), (plan) => executeRemoval(deps, plan)).purgeAll();
|
|
4081
4940
|
}
|
|
4082
|
-
},
|
|
4083
|
-
|
|
4941
|
+
}),
|
|
4942
|
+
detail: defineRoute("detail", {
|
|
4084
4943
|
slice: "core",
|
|
4085
|
-
method: ROUTES.detail.method,
|
|
4086
|
-
body: bodyOf(ROUTES.detail),
|
|
4087
4944
|
purity: "pure",
|
|
4088
4945
|
read: "raw",
|
|
4089
4946
|
response: "json",
|
|
4090
|
-
run: async (deps, body, read) =>
|
|
4091
|
-
|
|
4092
|
-
|
|
4093
|
-
|
|
4094
|
-
|
|
4095
|
-
|
|
4096
|
-
};
|
|
4097
|
-
|
|
4947
|
+
run: async (deps, body, read) => {
|
|
4948
|
+
const fields = parseBody(body, BODY_GROUPS.entry);
|
|
4949
|
+
return readTrashDetail({
|
|
4950
|
+
fs: deps.fs,
|
|
4951
|
+
rows: () => read.rows(),
|
|
4952
|
+
home: deps.home
|
|
4953
|
+
})(fields.entryId, fields.before);
|
|
4954
|
+
}
|
|
4955
|
+
}),
|
|
4956
|
+
archiveList: defineRoute("archiveList", {
|
|
4957
|
+
slice: "core",
|
|
4958
|
+
purity: "pure",
|
|
4959
|
+
read: "none",
|
|
4960
|
+
response: "json",
|
|
4961
|
+
run: async (deps) => assembleArchiveRows(deps)
|
|
4962
|
+
}),
|
|
4963
|
+
archiveDetail: defineRoute("archiveDetail", {
|
|
4964
|
+
slice: "core",
|
|
4965
|
+
purity: "pure",
|
|
4966
|
+
read: "none",
|
|
4967
|
+
response: "json",
|
|
4968
|
+
run: async (deps, body) => {
|
|
4969
|
+
const fields = parseBody(body, BODY_GROUPS.sessionId);
|
|
4970
|
+
return readArchiveDetail(deps)(fields.sessionId, fields.before, fields.rootSessionId);
|
|
4971
|
+
}
|
|
4972
|
+
})
|
|
4973
|
+
});
|
|
4974
|
+
/** 段名 → 那一行;不认识的段名回 `undefined`(调用方抛 404,并带出原路径)。
|
|
4975
|
+
* **必须问 `Object.hasOwn`**:段名来自线上路径,`constructor` / `toString` 这类原型属性名会从
|
|
4976
|
+
* `Record` 的索引读里"查到"一个函数,把未知路径判成已知路由(随后以 405 / 处理期炸开的形态出现)。
|
|
4977
|
+
* 这里只认表自身的键——表是 `Object.fromEntries` 建出来的,自有键恰好就是段名。 */
|
|
4098
4978
|
function routeOf(rest) {
|
|
4979
|
+
if (!Object.hasOwn(ROUTE_TABLE, rest)) return void 0;
|
|
4099
4980
|
return ROUTE_TABLE[rest];
|
|
4100
4981
|
}
|
|
4101
4982
|
//#endregion
|
|
@@ -4103,7 +4984,7 @@ function routeOf(rest) {
|
|
|
4103
4984
|
/**
|
|
4104
4985
|
* /dsh-session-delete-api 的分发核心:只负责路由记录的执行。
|
|
4105
4986
|
*
|
|
4106
|
-
* 传输适配器只有 `src/api/connection-route.ts`
|
|
4987
|
+
* 传输适配器只有 `src/api/connection-route.ts` 一个:全部段名注册到宿主 `connection.fetch.register`
|
|
4107
4988
|
* 的 exact Fetch 路由(`Request` / `Response`),Host/Origin/浏览器认证由宿主 `/api` bridge 完成
|
|
4108
4989
|
* (ADR-0033)。`Request` 的字节闸 / JSON 解析、`Response` 的头与失败信封都归适配器;
|
|
4109
4990
|
* 这里只收已经解析好的请求,做查表 → 按段注入窄面 → 跑处理 → 回结果。
|
|
@@ -4149,6 +5030,7 @@ function coreDepsOf(full) {
|
|
|
4149
5030
|
function removalOf(full, core) {
|
|
4150
5031
|
return {
|
|
4151
5032
|
...core,
|
|
5033
|
+
host: full.host,
|
|
4152
5034
|
fs: fsSlice(full.fs, [...FS_CORE_METHODS, ...FS_REMOVAL_METHODS])
|
|
4153
5035
|
};
|
|
4154
5036
|
}
|
|
@@ -4190,15 +5072,16 @@ function createDispatcher(deps) {
|
|
|
4190
5072
|
};
|
|
4191
5073
|
return async function dispatch(input) {
|
|
4192
5074
|
const spec = resolveRoute(input.method, input.rest);
|
|
4193
|
-
const kind = spec.read;
|
|
4194
|
-
let rowsPromise;
|
|
4195
|
-
const read = { rows() {
|
|
4196
|
-
if (kind === "none") return Promise.reject(/* @__PURE__ */ new Error("route read: none"));
|
|
4197
|
-
rowsPromise ??= kind === "list" ? deps.ledger.list() : deps.ledger.raw();
|
|
4198
|
-
return rowsPromise;
|
|
4199
|
-
} };
|
|
4200
5075
|
const rowDeps = depsFor(spec, slices);
|
|
4201
|
-
const task = () =>
|
|
5076
|
+
const task = () => {
|
|
5077
|
+
if (spec.response === "binary") return spec.run(rowDeps, input.search);
|
|
5078
|
+
if (spec.read === "none") return spec.run(rowDeps, input.body);
|
|
5079
|
+
let rowsPromise;
|
|
5080
|
+
return spec.run(rowDeps, input.body, { rows() {
|
|
5081
|
+
rowsPromise ??= spec.read === "list" ? deps.ledger.list() : deps.ledger.raw();
|
|
5082
|
+
return rowsPromise;
|
|
5083
|
+
} });
|
|
5084
|
+
};
|
|
4202
5085
|
const result = await (isPure(spec.purity, input.body) ? task() : throughChain(task));
|
|
4203
5086
|
if (spec.response === "binary") return {
|
|
4204
5087
|
kind: "binary",
|
|
@@ -4217,7 +5100,7 @@ function createDispatcher(deps) {
|
|
|
4217
5100
|
//#endregion
|
|
4218
5101
|
//#region src/api/connection-route.ts
|
|
4219
5102
|
/**
|
|
4220
|
-
* 现代宿主的 exact Fetch
|
|
5103
|
+
* 现代宿主的 exact Fetch 路由适配器:把全部段名注册到 `connection.fetch.register`,
|
|
4221
5104
|
* 由宿主 `/api` bridge 做 Host/Origin/浏览器认证(ADR-0033)。
|
|
4222
5105
|
*
|
|
4223
5106
|
* 为什么路径必须带 `/api`:宿主 `assertFetchRoute` 用 `endpointFromPath('/api', path)` 校验,
|
|
@@ -4245,6 +5128,13 @@ function parseJsonBody(text) {
|
|
|
4245
5128
|
throw error;
|
|
4246
5129
|
}
|
|
4247
5130
|
}
|
|
5131
|
+
/** `content-disposition` 的 `filename*`:RFC 5987 的 ext-value(`UTF-8''<pct-encoded>`)。
|
|
5132
|
+
* `encodeURIComponent` 已把非 ASCII、空格、引号、分号等转成 `%XX`,但它**保留 `'()*`**——这四枚
|
|
5133
|
+
* 都不是 attr-char(`'` 还是 ext-value 的分隔引号,`(` `)` 会被 part 参数解析吞掉),不补转就会在
|
|
5134
|
+
* 浏览器那里被解析成另一个文件名。取值是原始字节的 UTF-8 百分号编码,不解码、不猜编码。 */
|
|
5135
|
+
function encodeFilenameStar(filename) {
|
|
5136
|
+
return encodeURIComponent(filename).replace(/['()*]/gu, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
5137
|
+
}
|
|
4248
5138
|
/**
|
|
4249
5139
|
* 二进制响应的四道头(`/attachment` 专用)。判据不是口味:类型由处理函数给、长度与字节同源、
|
|
4250
5140
|
* 不许任何中间层留下已删除会话的附件、字节与声明类型不一致时浏览器不许改猜。
|
|
@@ -4256,7 +5146,7 @@ function binaryHeaders(body) {
|
|
|
4256
5146
|
"cache-control": "private, no-store",
|
|
4257
5147
|
"x-content-type-options": "nosniff"
|
|
4258
5148
|
};
|
|
4259
|
-
if (body.filename !== void 0) headers["content-disposition"] = `${body.disposition}; filename*=UTF-8''${
|
|
5149
|
+
if (body.filename !== void 0) headers["content-disposition"] = `${body.disposition}; filename*=UTF-8''${encodeFilenameStar(body.filename)}`;
|
|
4260
5150
|
else if (body.disposition === "attachment") headers["content-disposition"] = "attachment";
|
|
4261
5151
|
return headers;
|
|
4262
5152
|
}
|
|
@@ -4356,7 +5246,7 @@ function toResponse(result) {
|
|
|
4356
5246
|
});
|
|
4357
5247
|
}
|
|
4358
5248
|
/**
|
|
4359
|
-
*
|
|
5249
|
+
* 注册全部段名 exact Fetch 路由。返回一个组合 disposer;调用方把它挂在自己的 effect 上。
|
|
4360
5250
|
* `connection` 是插件的硬依赖(web UI / 桌面端都装 `client-connection`);`fetch.register`
|
|
4361
5251
|
* 缺席属于宿主形状漂移,直接抛——静默返回空 disposer 会让插件「在但没有入口」。
|
|
4362
5252
|
* `dispatch` 与分发器同源。
|
|
@@ -4447,15 +5337,25 @@ function resolveHome(env = process.env, homeDir = homedir()) {
|
|
|
4447
5337
|
* 落在「未分组」)、`wasArchived: false`(文件侧没有归档事实;旧条目恢复走迁移支)、`title: ''`(详情有日志标题兜底)
|
|
4448
5338
|
* ——这是重建的固有代价,不是可以"再读读看"的东西。
|
|
4449
5339
|
* ④ **认不出 / 读不出的目录:不动、不列**(名字不像条目、目录里没有日志、header 读不出、尺寸量不出,
|
|
4450
|
-
*
|
|
5340
|
+
* 各跳过各的)。header 走 {@link HEADER_READ_BYTES} 的**有界头读**:只为一行 header 不付整本日志的
|
|
5341
|
+
* 内存;窗口里切不出完整帧同样算认不出,不拿半截 header 冒充身份。它是"外人放进来的东西",不是
|
|
5342
|
+
* 用户动作失败:跳过即静默,绝不为它删目录或抛掉整次读数。
|
|
4451
5343
|
* ⑤ **幂等**:再跑一遍零写入;崩在任何一步,下一次读清单接着把它修完。
|
|
4452
5344
|
*
|
|
4453
5345
|
* 与三个写动词的**串行化不在这里**(那是传输层的事,见 `src/api/dispatch.ts` 的到达序链):
|
|
4454
5346
|
* 对账与删除/恢复/彻底删除都是"读清单 + 动文件 + 写清单"的多步,交错跑会互相踩——删除刚把目录搬进
|
|
4455
5347
|
* 回收站、行还没写上时,对账抢先把这行按目录"重建"出来,随后又被真实行覆盖成降级元数据。
|
|
4456
5348
|
*/
|
|
4457
|
-
/**
|
|
4458
|
-
*
|
|
5349
|
+
/** 对账只为读 header:**有界头读**的窗口(1 MiB)。
|
|
5350
|
+
* 日志的 header 是第一帧里的第一行(宿主建会话时先落它,实测远小于 1 KiB),1 MiB 留足余量;
|
|
5351
|
+
* 这个数不是"日志大小上限",而是"不为一行 header 把整本日志读进内存"的读取预算。窗口若切在
|
|
5352
|
+
* 某一帧中间,头读**按前缀读的容忍口径**丢掉最后那个不完整帧(`readSessionHeader` 的
|
|
5353
|
+
* `tolerateTruncatedTail`)——header 在第一个完整帧里,照样读得到;不在这个窗口里才是"认不出",
|
|
5354
|
+
* 按下面 ④ 的口径整条跳过,不猜半截 header。 */
|
|
5355
|
+
const HEADER_READ_BYTES = 1048576;
|
|
5356
|
+
/** 目录名是不是一条条目 id(形状契约在 `entry.ts`:`<删除时刻UTC>-<会话目录段>`;
|
|
5357
|
+
* 段是宿主 `encodeSegment` 的产物(编码前的存量条目也可能还是原始目录名),无论哪种都必须能
|
|
5358
|
+
* 安全地拼回磁盘路径——带分隔符的名字仍按"外人"跳过,不让一次对账读崩)。 */
|
|
4459
5359
|
function isEntryId(name) {
|
|
4460
5360
|
try {
|
|
4461
5361
|
return isSinglePathSegment(parseEntryId(name).sessionDirName);
|
|
@@ -4468,7 +5368,8 @@ function isEntryId(name) {
|
|
|
4468
5368
|
* 半截行比"不列"更坏——恢复会照它把目录搬去一个错的地方(同 `detail.ts` 那条"半截正文"的口径)。
|
|
4469
5369
|
*
|
|
4470
5370
|
* `sessionId` 取日志 header 的 `id`(恢复之后宿主按日志 header 建索引,那才是会话身份);
|
|
4471
|
-
* header
|
|
5371
|
+
* header 缺席这个字段才回落到目录段——反解回原始 id(编码前的存量条目段本身可能已是原始目录名,
|
|
5372
|
+
* 反解对不含 `~XXXX` 形态的串原样交回)。
|
|
4472
5373
|
*/
|
|
4473
5374
|
async function buildEntry(deps, id) {
|
|
4474
5375
|
const dir = trashDirOf(id, deps.home);
|
|
@@ -4481,13 +5382,13 @@ async function buildEntry(deps, id) {
|
|
|
4481
5382
|
if (logName === void 0) return void 0;
|
|
4482
5383
|
let raw;
|
|
4483
5384
|
try {
|
|
4484
|
-
raw = await deps.fs.
|
|
5385
|
+
raw = await deps.fs.readFileHead(`${dir}/${logName}`, HEADER_READ_BYTES);
|
|
4485
5386
|
} catch {
|
|
4486
5387
|
return;
|
|
4487
5388
|
}
|
|
4488
5389
|
let header;
|
|
4489
5390
|
try {
|
|
4490
|
-
header = readSessionHeader(raw);
|
|
5391
|
+
header = readSessionHeader(raw, { tolerateTruncatedTail: true });
|
|
4491
5392
|
} catch {
|
|
4492
5393
|
return;
|
|
4493
5394
|
}
|
|
@@ -4502,7 +5403,7 @@ async function buildEntry(deps, id) {
|
|
|
4502
5403
|
const cwd = typeof header.cwd === "string" ? header.cwd : void 0;
|
|
4503
5404
|
return {
|
|
4504
5405
|
id,
|
|
4505
|
-
sessionId: typeof header.id === "string" && header.id !== "" ? header.id : sessionDirName,
|
|
5406
|
+
sessionId: typeof header.id === "string" && header.id !== "" ? header.id : decodeSessionSegment(sessionDirName),
|
|
4506
5407
|
projectDir: projectDirOfCwd(cwd),
|
|
4507
5408
|
workspaceId: "",
|
|
4508
5409
|
wasArchived: false,
|
|
@@ -4665,7 +5566,7 @@ const name = "@xrn1997/dsh-session-delete";
|
|
|
4665
5566
|
* - `agents`:只给 handle 捕获用(`ctx.get('agents')`;缺席时 `ctx.inject(['agents'])` 等服务就绪再装)。
|
|
4666
5567
|
* 它同样可能晚于本插件激活,写进插件 inject 只会让整个插件 pending。
|
|
4667
5568
|
*
|
|
4668
|
-
* `connection`
|
|
5569
|
+
* `connection` 是浏览器半取数通道的唯一承载者:全部段名注册到 `connection.fetch.register` 的
|
|
4669
5570
|
* `/api/dsh-session-delete-api/*`,Host/Origin/浏览器认证由宿主 `/api` bridge 完成(ADR-0033)。
|
|
4670
5571
|
* 支持面是 web UI 与桌面端,二者的标准组合都装 `client-connection`;服务缺席时插件停在 pending
|
|
4671
5572
|
* ——可见的激活失败,而不是静默地没有入口。`webServer` 不再直接使用:exact route 仍由宿主的
|