dsh-session-webhook 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +412 -2
- package/cordis.patch.yml +8 -0
- package/docs/ACCEPTANCE.md +158 -0
- package/docs/DESIGN.md +136 -0
- package/docs/TOOL-CONTRACT.md +315 -0
- package/icon.svg +13 -0
- package/lib/bases.js +527 -0
- package/lib/client.js +1755 -0
- package/lib/control.js +321 -0
- package/lib/deliver.js +272 -0
- package/lib/errors.js +62 -0
- package/lib/http.js +258 -0
- package/lib/index.js +220 -0
- package/lib/store.js +381 -0
- package/lib/tools.js +433 -0
- package/lib/types.js +1 -0
- package/lib/urlfile.js +290 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +72 -4
- package/scripts/cold-resume-health.mjs +268 -0
- package/scripts/verify-client.mjs +1199 -0
- package/scripts/verify-health-contract.mjs +173 -0
- package/scripts/verify-host.mjs +1322 -0
package/lib/urlfile.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* urlFile:把端点的完整 URL 落到本机文件,给外部脚本读。
|
|
3
|
+
*
|
|
4
|
+
* 布局(docs/DESIGN.md §4):
|
|
5
|
+
*
|
|
6
|
+
* $DSH_HOME/session-inject/urls/<hookId>.url ← default 入口(`cat` 惯用法)
|
|
7
|
+
* $DSH_HOME/session-inject/urls/<hookId>.<name>.url ← 其余入口
|
|
8
|
+
*
|
|
9
|
+
* 目录 0700、文件 0600、内容是一行完整 URL(末尾带换行,`cat`/`$(cat …)` 都方便)。
|
|
10
|
+
* 这些文件是**消费方接口**,不是秘密的唯一副本:令牌本身在 hooks.json 里,
|
|
11
|
+
* 文件只是「怎么到达」的展开,因此重写可以随时全量覆盖。
|
|
12
|
+
*
|
|
13
|
+
* 三条自愈规则:
|
|
14
|
+
* 1. 插件 apply 时按当前入口集合全量重写(配置改了,重启即对齐);
|
|
15
|
+
* 2. 单个端点重写时删掉它已不存在的入口文件(入口被删/改名);
|
|
16
|
+
* 3. revoke 删除该端点的全部文件(UI 撤销与工具撤销走同一处)。
|
|
17
|
+
*/
|
|
18
|
+
import { chmod, mkdir, readFile, readdir, rename, unlink, writeFile } from 'node:fs/promises';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { randomUUID } from 'node:crypto';
|
|
21
|
+
import { DIRECT_BASE_NAME, normalizeBaseName } from './bases.js';
|
|
22
|
+
/** urlFile 目录名(位于插件数据目录之下)。 */
|
|
23
|
+
export const URLS_DIRNAME = 'urls';
|
|
24
|
+
/** urlFile 后缀。 */
|
|
25
|
+
export const URL_FILE_SUFFIX = '.url';
|
|
26
|
+
/** 目录与文件权限(目录 0700、文件 0600)。 */
|
|
27
|
+
const DIRECTORY_MODE = 0o700;
|
|
28
|
+
const FILE_MODE = 0o600;
|
|
29
|
+
/** 端点 id 允许的字符:store 生成 `wh_<uuid>`,这里同时防路径穿越。 */
|
|
30
|
+
const HOOK_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
31
|
+
/** 从插件数据目录推出 urlFile 目录。 */
|
|
32
|
+
export function urlsDirectoryFor(baseDirectory) {
|
|
33
|
+
return join(baseDirectory, URLS_DIRNAME);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 一个目录下的 urlFile 管理器。
|
|
37
|
+
*
|
|
38
|
+
* 实例本身无状态(只记目录与 defaultBase),读取/重写都直接走文件系统,
|
|
39
|
+
* 因此 `config/set` 之后换一个 defaultBase 只需要换实例。
|
|
40
|
+
*/
|
|
41
|
+
export class UrlFiles {
|
|
42
|
+
#directory;
|
|
43
|
+
#defaultBase;
|
|
44
|
+
#logger;
|
|
45
|
+
constructor(options) {
|
|
46
|
+
if (typeof options.directory !== 'string' || options.directory === '') {
|
|
47
|
+
throw new TypeError('UrlFiles 需要目录路径');
|
|
48
|
+
}
|
|
49
|
+
this.#directory = options.directory;
|
|
50
|
+
this.#defaultBase = normalizeBaseName(options.defaultBase);
|
|
51
|
+
this.#logger = options.logger ?? null;
|
|
52
|
+
}
|
|
53
|
+
/** urlFile 目录的绝对路径。 */
|
|
54
|
+
get directory() {
|
|
55
|
+
return this.#directory;
|
|
56
|
+
}
|
|
57
|
+
/** default 入口名。 */
|
|
58
|
+
get defaultBase() {
|
|
59
|
+
return this.#defaultBase;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 计算一个端点在某入口下的文件路径(纯函数,不碰磁盘)。
|
|
63
|
+
* @param hookId 端点 id。
|
|
64
|
+
* @param baseName 入口名。
|
|
65
|
+
* @returns 绝对路径。
|
|
66
|
+
*/
|
|
67
|
+
pathFor(hookId, baseName) {
|
|
68
|
+
return join(this.#directory, this.#fileName(hookId, baseName));
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* 写入一个端点在全部入口下的 URL 文件,并删掉该端点已失效的入口文件。
|
|
72
|
+
* 单个入口写失败只告警不抛错(文件是消费方便利层,不该让建端点失败)。
|
|
73
|
+
* @param hookId 端点 id。
|
|
74
|
+
* @param urls 入口名 → 完整 URL。
|
|
75
|
+
* @returns 写成功的 入口名 → 路径。
|
|
76
|
+
*/
|
|
77
|
+
async write(hookId, urls) {
|
|
78
|
+
this.#assertHookId(hookId);
|
|
79
|
+
await this.#ensureDirectory();
|
|
80
|
+
const written = {};
|
|
81
|
+
for (const [baseName, url] of Object.entries(urls)) {
|
|
82
|
+
const name = normalizeBaseName(baseName);
|
|
83
|
+
const path = this.pathFor(hookId, name);
|
|
84
|
+
try {
|
|
85
|
+
await this.#writeFile(path, url);
|
|
86
|
+
written[name] = path;
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
this.#warn(`无法写入 urlFile ${path}:${describeError(error)}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
await this.#removeStale(hookId, new Set(Object.values(written)));
|
|
93
|
+
return written;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* 删除一个端点的全部 urlFile(revoke 路径)。
|
|
97
|
+
* @param hookId 端点 id。
|
|
98
|
+
* @returns 实际删除的路径。
|
|
99
|
+
*/
|
|
100
|
+
async remove(hookId) {
|
|
101
|
+
this.#assertHookId(hookId);
|
|
102
|
+
let names;
|
|
103
|
+
try {
|
|
104
|
+
names = await readdir(this.#directory);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
if (error.code === 'ENOENT')
|
|
108
|
+
return [];
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
const removed = [];
|
|
112
|
+
for (const name of names) {
|
|
113
|
+
const parsed = this.#parseFileName(name);
|
|
114
|
+
if (parsed === undefined || parsed.hookId !== hookId)
|
|
115
|
+
continue;
|
|
116
|
+
const path = join(this.#directory, name);
|
|
117
|
+
try {
|
|
118
|
+
await unlink(path);
|
|
119
|
+
removed.push(path);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
this.#warn(`无法删除 urlFile ${path}:${describeError(error)}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return removed;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* 只返回**真实存在**的入口文件路径(列表用;不制造「应该有」的假路径)。
|
|
129
|
+
* @param hookId 端点 id。
|
|
130
|
+
* @param baseNames 期望的入口名集合。
|
|
131
|
+
* @returns 存在的 入口名 → 路径。
|
|
132
|
+
*/
|
|
133
|
+
async existing(hookId, baseNames) {
|
|
134
|
+
this.#assertHookId(hookId);
|
|
135
|
+
const found = {};
|
|
136
|
+
for (const baseName of baseNames) {
|
|
137
|
+
const name = normalizeBaseName(baseName);
|
|
138
|
+
const path = this.pathFor(hookId, name);
|
|
139
|
+
try {
|
|
140
|
+
await readFile(path);
|
|
141
|
+
found[name] = path;
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// 不存在(或不可读):列表里就不出现,避免给出死路径。
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return found;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* 按当前入口集合全量重写所有端点的 urlFile(apply 时调用,自愈)。
|
|
151
|
+
*
|
|
152
|
+
* 除逐个重写外还会扫一遍目录:删掉已不存在端点的文件、以及端点已不再
|
|
153
|
+
* 配置的入口文件——这样「配置删了一个入口再重启」不会留下指向旧域名
|
|
154
|
+
* 的文件给外部脚本继续读。
|
|
155
|
+
*
|
|
156
|
+
* @param endpoints 当前全部端点。
|
|
157
|
+
* @param compose 由令牌算出「入口名 → 完整 URL」;direct origin 取不到时应抛错。
|
|
158
|
+
* @returns 端点 id → (入口名 → 路径)。
|
|
159
|
+
*/
|
|
160
|
+
async rewriteAll(endpoints, compose) {
|
|
161
|
+
await this.#ensureDirectory();
|
|
162
|
+
const expected = new Map();
|
|
163
|
+
const result = {};
|
|
164
|
+
for (const endpoint of endpoints) {
|
|
165
|
+
this.#assertHookId(endpoint.id);
|
|
166
|
+
const urls = compose(endpoint.token);
|
|
167
|
+
const written = {};
|
|
168
|
+
for (const [baseName, url] of Object.entries(urls)) {
|
|
169
|
+
const name = normalizeBaseName(baseName);
|
|
170
|
+
const path = this.pathFor(endpoint.id, name);
|
|
171
|
+
await this.#writeFile(path, url);
|
|
172
|
+
written[name] = path;
|
|
173
|
+
}
|
|
174
|
+
expected.set(endpoint.id, new Set(Object.values(written)));
|
|
175
|
+
result[endpoint.id] = written;
|
|
176
|
+
}
|
|
177
|
+
await this.#sweep(expected);
|
|
178
|
+
return result;
|
|
179
|
+
}
|
|
180
|
+
/** 文件名:default 入口用短名,其余入口带后缀。 */
|
|
181
|
+
#fileName(hookId, baseName) {
|
|
182
|
+
if (baseName === this.#defaultBase)
|
|
183
|
+
return `${hookId}${URL_FILE_SUFFIX}`;
|
|
184
|
+
return `${hookId}.${baseName}${URL_FILE_SUFFIX}`;
|
|
185
|
+
}
|
|
186
|
+
/** 解析目录里的一个文件名;不是本模块生成的文件返回 undefined(不碰)。 */
|
|
187
|
+
#parseFileName(name) {
|
|
188
|
+
if (!name.endsWith(URL_FILE_SUFFIX))
|
|
189
|
+
return undefined;
|
|
190
|
+
const stem = name.slice(0, -URL_FILE_SUFFIX.length);
|
|
191
|
+
const parts = stem.split('.');
|
|
192
|
+
if (parts.length === 1) {
|
|
193
|
+
const [hookId] = parts;
|
|
194
|
+
return HOOK_ID_PATTERN.test(hookId) ? { hookId, baseName: DIRECT_BASE_NAME } : undefined;
|
|
195
|
+
}
|
|
196
|
+
if (parts.length !== 2)
|
|
197
|
+
return undefined;
|
|
198
|
+
const [hookId, baseName] = parts;
|
|
199
|
+
if (!HOOK_ID_PATTERN.test(hookId) || !/^[a-z][a-z0-9-]*$/.test(baseName))
|
|
200
|
+
return undefined;
|
|
201
|
+
return { hookId, baseName };
|
|
202
|
+
}
|
|
203
|
+
/** 删掉某个端点不在 expected 里的旧文件。 */
|
|
204
|
+
async #removeStale(hookId, keep) {
|
|
205
|
+
let names;
|
|
206
|
+
try {
|
|
207
|
+
names = await readdir(this.#directory);
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
if (error.code === 'ENOENT')
|
|
211
|
+
return;
|
|
212
|
+
throw error;
|
|
213
|
+
}
|
|
214
|
+
for (const name of names) {
|
|
215
|
+
const parsed = this.#parseFileName(name);
|
|
216
|
+
if (parsed === undefined || parsed.hookId !== hookId)
|
|
217
|
+
continue;
|
|
218
|
+
const path = join(this.#directory, name);
|
|
219
|
+
if (keep.has(path))
|
|
220
|
+
continue;
|
|
221
|
+
try {
|
|
222
|
+
await unlink(path);
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
this.#warn(`无法清理 urlFile ${path}:${describeError(error)}`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/** 全目录清理:删掉未知端点与已删入口的文件。 */
|
|
230
|
+
async #sweep(expected) {
|
|
231
|
+
let names;
|
|
232
|
+
try {
|
|
233
|
+
names = await readdir(this.#directory);
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
if (error.code === 'ENOENT')
|
|
237
|
+
return;
|
|
238
|
+
throw error;
|
|
239
|
+
}
|
|
240
|
+
for (const name of names) {
|
|
241
|
+
const parsed = this.#parseFileName(name);
|
|
242
|
+
if (parsed === undefined)
|
|
243
|
+
continue;
|
|
244
|
+
const path = join(this.#directory, name);
|
|
245
|
+
const keep = expected.get(parsed.hookId);
|
|
246
|
+
if (keep !== undefined && keep.has(path))
|
|
247
|
+
continue;
|
|
248
|
+
try {
|
|
249
|
+
await unlink(path);
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
this.#warn(`无法清理 urlFile ${path}:${describeError(error)}`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/** 建目录并确保 0700(mkdir 的 mode 只对新建生效,这里显式再 chmod)。 */
|
|
257
|
+
async #ensureDirectory() {
|
|
258
|
+
await mkdir(this.#directory, { recursive: true, mode: DIRECTORY_MODE });
|
|
259
|
+
await chmod(this.#directory, DIRECTORY_MODE);
|
|
260
|
+
}
|
|
261
|
+
/** 原子写一个 urlFile:临时文件 0600 → rename 覆盖。 */
|
|
262
|
+
async #writeFile(path, url) {
|
|
263
|
+
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
264
|
+
await writeFile(temporary, `${url}\n`, { mode: FILE_MODE });
|
|
265
|
+
try {
|
|
266
|
+
await chmod(temporary, FILE_MODE);
|
|
267
|
+
await rename(temporary, path);
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
// 半成品临时文件不能留在目录里(消费方可能按 *.url 扫)。
|
|
271
|
+
await unlink(temporary).catch(() => { });
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/** 校验端点 id 形态,阻止把任意字符串当文件名用。 */
|
|
276
|
+
#assertHookId(hookId) {
|
|
277
|
+
if (!HOOK_ID_PATTERN.test(hookId)) {
|
|
278
|
+
throw new Error(`session-inject: 非法的端点 id ${JSON.stringify(hookId)}`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
#warn(message) {
|
|
282
|
+
this.#logger?.warn?.(`[session-inject] ${message}`);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/** 把任意异常压成一行可读文本(日志用)。 */
|
|
286
|
+
function describeError(error) {
|
|
287
|
+
if (error instanceof Error)
|
|
288
|
+
return error.message;
|
|
289
|
+
return String(error);
|
|
290
|
+
}
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,74 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-session-webhook",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Per-session webhook endpoints for DeepSeek Harness: named, revocable URLs that deliver one message into exactly one session.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"deepseek-harness",
|
|
8
|
+
"dsh",
|
|
9
|
+
"dsh-plugin",
|
|
10
|
+
"webhook",
|
|
11
|
+
"session"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": "./lib/index.js",
|
|
16
|
+
"./client": "./lib/client.js",
|
|
17
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
18
|
+
"./package.json": "./package.json",
|
|
19
|
+
"./locale/*.json": "./locale/*.json",
|
|
20
|
+
"./icon": "./icon.svg"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"lib/",
|
|
24
|
+
"cordis.patch.yml",
|
|
25
|
+
"locale/*.json",
|
|
26
|
+
"icon.svg",
|
|
27
|
+
"README.md",
|
|
28
|
+
"scripts/",
|
|
29
|
+
"docs/",
|
|
30
|
+
"LICENSE"
|
|
31
|
+
],
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "node build.mjs",
|
|
34
|
+
"prepare": "node build.mjs",
|
|
35
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
36
|
+
"test": "node scripts/verify-host.mjs && node scripts/verify-client.mjs && node scripts/verify-health-contract.mjs",
|
|
37
|
+
"check": "npm run build && npm run typecheck && npm test"
|
|
38
|
+
},
|
|
39
|
+
"dsh": {
|
|
40
|
+
"bundle": {
|
|
41
|
+
"patch": "./cordis.patch.yml"
|
|
42
|
+
},
|
|
43
|
+
"client": {
|
|
44
|
+
"platform": "web",
|
|
45
|
+
"immediately": true,
|
|
46
|
+
"inject": [
|
|
47
|
+
"@deepseek-ai/dsh-client-connection",
|
|
48
|
+
"@deepseek-ai/dsh-client-locale",
|
|
49
|
+
"@deepseek-ai/dsh-client-ui-settings",
|
|
50
|
+
"@deepseek-ai/dsh-client-ui-workspace",
|
|
51
|
+
"@deepseek-ai/dsh-client-ui-conversation"
|
|
52
|
+
]
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
"engines": {
|
|
56
|
+
"node": ">=22"
|
|
57
|
+
},
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"@deepseek-ai/cordis": "*",
|
|
60
|
+
"@deepseek-ai/dsh-llm": "*",
|
|
61
|
+
"@deepseek-ai/dsh-tools": "*",
|
|
62
|
+
"@deepseek-ai/schemastery": "*"
|
|
63
|
+
},
|
|
64
|
+
"devDependencies": {
|
|
65
|
+
"@deepseek-ai/cordis": "*",
|
|
66
|
+
"@deepseek-ai/dsh-llm": "*",
|
|
67
|
+
"@deepseek-ai/dsh-tools": "*",
|
|
68
|
+
"@deepseek-ai/schemastery": "*",
|
|
69
|
+
"@types/node": "^24.19.2",
|
|
70
|
+
"@types/react": "^18.3.31",
|
|
71
|
+
"esbuild": "0.28.2",
|
|
72
|
+
"typescript": "5.9.3"
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 冷恢复健康检查:从会话日志直接判断「这个会话有没有被降级」。
|
|
4
|
+
*
|
|
5
|
+
* 为什么需要:外部投递(webhook / send_to_session)命中已存会话时会冷恢复它。
|
|
6
|
+
* 若冷恢复漏了 preset 重挂,目标会话会以**残缺组合**继续跑(工具集塌缩、丢自动压缩),
|
|
7
|
+
* 且这个降级是**终身**的——命中已 live 会话时只 steer 不 resume,残缺组合会一直跟着该 agent。
|
|
8
|
+
*
|
|
9
|
+
* 本脚本只读会话日志,**不依赖插件内部 API、不连服务**,所以任何项目都能直接拿去用。
|
|
10
|
+
*
|
|
11
|
+
* node scripts/cold-resume-health.mjs <session-id | 日志路径> [...]
|
|
12
|
+
* node scripts/cold-resume-health.mjs --all # 扫全部会话,只报可疑的
|
|
13
|
+
*
|
|
14
|
+
* ## 输出契约(外部消费方直接依赖,改动需 bump 版本)
|
|
15
|
+
*
|
|
16
|
+
* 退出码(两种模式语义一致):
|
|
17
|
+
* 0 = 全部健康(**含「曾降级但已恢复」**——它现在是健康的,不该让 CI 红)
|
|
18
|
+
* 1 = 存在**当前仍处于降级态**的会话
|
|
19
|
+
* 2 = 用法错误 / 找不到日志
|
|
20
|
+
*
|
|
21
|
+
* 输出格式:人类可读文本,**不做机器解析契约**。唯一稳定的机器接口是退出码。
|
|
22
|
+
* 若需要结构化输出请用 `--json`(尚未提供;有需求再加,会作为新契约引入)。
|
|
23
|
+
*
|
|
24
|
+
* 契约版本:v1(2026-10-29 起)。判据或退出码语义若有变化,
|
|
25
|
+
* 会在文件头标注 v2 并在 CHANGELOG 记一条。
|
|
26
|
+
*
|
|
27
|
+
* 判据(见 docs/TOOL-CONTRACT.md §5.1):
|
|
28
|
+
* 1. 每次 reason=resume 的工具数不应比上一次 request/header 少;
|
|
29
|
+
* 2. bash 必须一直在——它是 preset 专属工具,丢了就是 preset 没挂上;
|
|
30
|
+
* 3. compaction 能力不体现在工具列表里(它是 agent/request-error 上的监听器),
|
|
31
|
+
* 所以工具健康 ≠ 压缩健康;本脚本把 compaction/* 事件数一并报出来供人工判断。
|
|
32
|
+
*/
|
|
33
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
34
|
+
import { join } from 'node:path';
|
|
35
|
+
import { zstdDecompressSync } from 'node:zlib';
|
|
36
|
+
|
|
37
|
+
const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
|
|
38
|
+
const SESSIONS_ROOT = join(process.env.DSH_HOME ?? join(process.env.HOME ?? '/root', '.dsh'), 'sessions');
|
|
39
|
+
|
|
40
|
+
/** 会话日志是**多帧** zstd:必须按 magic 切帧,只解第一帧会漏掉大部分事件。 */
|
|
41
|
+
function readEvents(file) {
|
|
42
|
+
let buf;
|
|
43
|
+
try {
|
|
44
|
+
buf = readFileSync(file);
|
|
45
|
+
} catch {
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
const starts = [];
|
|
49
|
+
let i = 0;
|
|
50
|
+
while ((i = buf.indexOf(MAGIC, i)) !== -1) {
|
|
51
|
+
starts.push(i);
|
|
52
|
+
i += 4;
|
|
53
|
+
}
|
|
54
|
+
let text = '';
|
|
55
|
+
for (let k = 0; k < starts.length; k += 1) {
|
|
56
|
+
const end = k + 1 < starts.length ? starts[k + 1] : buf.length;
|
|
57
|
+
try {
|
|
58
|
+
text += zstdDecompressSync(buf.subarray(starts[k], end)).toString('utf8');
|
|
59
|
+
} catch {
|
|
60
|
+
// 单帧损坏不该让整次检查失败
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const events = [];
|
|
64
|
+
for (const line of text.split('\n')) {
|
|
65
|
+
if (!line.trim()) continue;
|
|
66
|
+
try {
|
|
67
|
+
events.push(JSON.parse(line));
|
|
68
|
+
} catch {
|
|
69
|
+
// 截断的尾行
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return events;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 从 request/header 事件抽出工具集快照。 */
|
|
76
|
+
function toolSnapshots(events) {
|
|
77
|
+
const out = [];
|
|
78
|
+
for (const ev of events) {
|
|
79
|
+
if (ev.type !== 'request/header') continue;
|
|
80
|
+
const tools = ev.data?.header?.tools ?? [];
|
|
81
|
+
const names = new Set(tools.map((tool) => tool.name));
|
|
82
|
+
out.push({
|
|
83
|
+
seq: ev.seq,
|
|
84
|
+
reason: ev.data?.reason ?? '(unknown)',
|
|
85
|
+
at: ev.at ?? ev.time,
|
|
86
|
+
count: names.size,
|
|
87
|
+
names,
|
|
88
|
+
bash: names.has('bash'),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 统计该会话消息的来源 kind(`webhook` = 本插件投递;其余 kind 来自宿主或其它插件)。 */
|
|
95
|
+
function sourceKinds(events) {
|
|
96
|
+
const kinds = new Map();
|
|
97
|
+
for (const ev of events) {
|
|
98
|
+
if (ev.type !== 'user/message') continue;
|
|
99
|
+
const kind = ev.data?.source?.kind ?? '(none)';
|
|
100
|
+
kinds.set(kind, (kinds.get(kind) ?? 0) + 1);
|
|
101
|
+
}
|
|
102
|
+
return kinds;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function formatTime(at) {
|
|
106
|
+
if (typeof at !== 'number') return '?';
|
|
107
|
+
return new Date(at).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 分析一个会话。
|
|
112
|
+
* @returns {{id: string, file: string, healthy: boolean, snapshots: Array, problems: string[], compactions: number}}
|
|
113
|
+
*/
|
|
114
|
+
function analyze(file, id) {
|
|
115
|
+
const events = readEvents(file);
|
|
116
|
+
const snapshots = toolSnapshots(events);
|
|
117
|
+
const compactions = events.filter((ev) => String(ev.type).startsWith('compaction/')).length;
|
|
118
|
+
const problems = [];
|
|
119
|
+
|
|
120
|
+
if (snapshots.length === 0) {
|
|
121
|
+
return { id, file, healthy: true, snapshots, problems: ['(无 request/header 事件,跳过)'], compactions };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// 判据 1:resume 之后工具数不应下降
|
|
125
|
+
for (let k = 1; k < snapshots.length; k += 1) {
|
|
126
|
+
const prev = snapshots[k - 1];
|
|
127
|
+
const cur = snapshots[k];
|
|
128
|
+
if (cur.reason !== 'resume') continue;
|
|
129
|
+
if (cur.count < prev.count) {
|
|
130
|
+
const lost = [...prev.names].filter((name) => !cur.names.has(name));
|
|
131
|
+
problems.push(
|
|
132
|
+
`seq=${cur.seq} resume 工具数下降 ${prev.count} → ${cur.count}(丢 ${lost.length} 个:`
|
|
133
|
+
+ `${lost.slice(0, 6).join(', ')}${lost.length > 6 ? ' …' : ''})@ ${formatTime(cur.at)}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// 判据 2:**丢失** bash(而不是「从来没有 bash」)。
|
|
138
|
+
// 注意这个区别很重要:IM 桥接类会话本来就不挂 preset、天生没有 bash,
|
|
139
|
+
// 用「没有 bash 就是坏」会把它判成降级 —— 那是误报。
|
|
140
|
+
// 真正的降级指纹是「之前有、后来没了」。
|
|
141
|
+
const hadBash = snapshots.some((snap) => snap.bash);
|
|
142
|
+
if (hadBash) {
|
|
143
|
+
const bashLost = snapshots.find((snap) => !snap.bash);
|
|
144
|
+
if (bashLost !== undefined) {
|
|
145
|
+
problems.push(`seq=${bashLost.seq} ${bashLost.reason} 时 bash 消失(= 原本挂着 preset,恢复时没重挂)@ ${formatTime(bashLost.at)}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 判据 2b:连初始快照都没有 bash,但工具数量级像 preset 会话(≥60)—— 可疑但无法断言
|
|
150
|
+
if (!hadBash && snapshots[0].count >= 60) {
|
|
151
|
+
problems.push(`初始快照(${snapshots[0].count} 个工具)就没有 bash:${''
|
|
152
|
+
}既可能是非 preset 会话,也可能从一开始就没挂上,需人工确认`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// 判据 3:曾经降级过、现在是否已恢复
|
|
156
|
+
const last = snapshots[snapshots.length - 1];
|
|
157
|
+
const recovered = problems.length > 0 && last.bash && last.count >= snapshots[0].count
|
|
158
|
+
&& hadBash === true;
|
|
159
|
+
|
|
160
|
+
return { id, file, healthy: problems.length === 0, recovered, snapshots, problems, compactions };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function sessionLogPath(idOrPath) {
|
|
164
|
+
if (idOrPath.includes('/')) return idOrPath;
|
|
165
|
+
for (const workspace of readdirSync(SESSIONS_ROOT)) {
|
|
166
|
+
const dir = join(SESSIONS_ROOT, workspace, idOrPath);
|
|
167
|
+
const file = join(dir, 'session.v4.jsonl.zstd');
|
|
168
|
+
try {
|
|
169
|
+
if (statSync(file).isFile()) return file;
|
|
170
|
+
} catch {
|
|
171
|
+
// 不是这个 workspace
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function allSessionLogs() {
|
|
178
|
+
const out = [];
|
|
179
|
+
for (const workspace of readdirSync(SESSIONS_ROOT)) {
|
|
180
|
+
let sessions;
|
|
181
|
+
try {
|
|
182
|
+
sessions = readdirSync(join(SESSIONS_ROOT, workspace));
|
|
183
|
+
} catch {
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
for (const id of sessions) {
|
|
187
|
+
const file = join(SESSIONS_ROOT, workspace, id, 'session.v4.jsonl.zstd');
|
|
188
|
+
try {
|
|
189
|
+
if (statSync(file).isFile()) out.push({ id, file });
|
|
190
|
+
} catch {
|
|
191
|
+
// 没有日志
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function report(result, verbose) {
|
|
199
|
+
const badge = result.healthy ? '✅' : '⚠️ ';
|
|
200
|
+
console.log(`\n───── ${badge} ${result.id}`);
|
|
201
|
+
console.log(` 日志: ${result.file}`);
|
|
202
|
+
|
|
203
|
+
if (verbose && result.snapshots.length > 0) {
|
|
204
|
+
console.log(' 工具集轨迹:');
|
|
205
|
+
let prev = null;
|
|
206
|
+
for (const snap of result.snapshots) {
|
|
207
|
+
// 只打印「工具数变化」或 resume 点的行,避免几十条重复
|
|
208
|
+
if (prev === snap.count && snap.reason !== 'resume') continue;
|
|
209
|
+
const mark = snap.bash ? '✅' : '❌';
|
|
210
|
+
console.log(` seq=${String(snap.seq).padStart(5)} ${String(snap.reason).padEnd(8)} `
|
|
211
|
+
+ `tools=${String(snap.count).padStart(3)} bash=${mark} ${formatTime(snap.at)}`);
|
|
212
|
+
prev = snap.count;
|
|
213
|
+
}
|
|
214
|
+
console.log(` compaction/* 事件: ${result.compactions} 条(0 只说明没触发过压缩,不等于坏)`);
|
|
215
|
+
const kinds = [...sourceKinds(readEvents(result.file)).entries()]
|
|
216
|
+
.map(([kind, n]) => `${kind}×${n}`).join(', ');
|
|
217
|
+
console.log(` 消息来源: ${kinds}`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (result.healthy) {
|
|
221
|
+
if (verbose) console.log(' ✅ 健康:无工具数下降,bash 全程在场');
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
for (const problem of result.problems) console.log(` · ${problem}`);
|
|
225
|
+
if (result.recovered) {
|
|
226
|
+
console.log(' ✅ 但最后一次快照已恢复(bash 在场、工具数不低于初始)—— 无需新开会话');
|
|
227
|
+
} else {
|
|
228
|
+
console.log(' ❌ 仍处于降级态:下一次带 setup 的 resume(Web 控制器或已修复的投递插件)可修回');
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const args = process.argv.slice(2);
|
|
233
|
+
if (args.length === 0) {
|
|
234
|
+
console.error('用法: node scripts/cold-resume-health.mjs <session-id|日志路径> [...] | --all');
|
|
235
|
+
process.exit(2);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
let exitCode = 0;
|
|
239
|
+
if (args[0] === '--all') {
|
|
240
|
+
const suspects = [];
|
|
241
|
+
for (const { id, file } of allSessionLogs()) {
|
|
242
|
+
const result = analyze(file, id);
|
|
243
|
+
if (!result.healthy) suspects.push(result);
|
|
244
|
+
}
|
|
245
|
+
const stillBad = suspects.filter((result) => result.recovered !== true);
|
|
246
|
+
const recovered = suspects.length - stillBad.length;
|
|
247
|
+
console.log(`扫描完成:${suspects.length} 个会话曾出现工具数下降或 bash 丢失`
|
|
248
|
+
+ `(已恢复 ${recovered} 个,仍降级 ${stillBad.length} 个)`);
|
|
249
|
+
for (const result of suspects) report(result, false);
|
|
250
|
+
// 注意:只有「仍降级」才让 CI 红。曾降级但已恢复的会话现在是健康的,
|
|
251
|
+
// 把它算失败会让 CI 永久红下去(历史降级不会消失)。
|
|
252
|
+
if (stillBad.length > 0) exitCode = 1;
|
|
253
|
+
} else {
|
|
254
|
+
for (const target of args) {
|
|
255
|
+
const file = sessionLogPath(target);
|
|
256
|
+
if (file === undefined) {
|
|
257
|
+
console.error(`找不到会话日志: ${target}`);
|
|
258
|
+
exitCode = 2;
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
const result = analyze(file, target);
|
|
262
|
+
report(result, true);
|
|
263
|
+
if (!result.healthy) {
|
|
264
|
+
exitCode = result.recovered === true ? 0 : 1;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
process.exit(exitCode);
|