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/control.js
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { asFailure, fail } from './errors.js';
|
|
2
|
+
import { isArchived } from './deliver.js';
|
|
3
|
+
import { hookView, normalizeMode, normalizeName, normalizeTags } from './store.js';
|
|
4
|
+
import { normalizeDefaultBase, normalizeLimits, normalizePublicBaseUrls, } from './bases.js';
|
|
5
|
+
const ROUTE_PATH = '/api/session-inject-rpc';
|
|
6
|
+
const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
7
|
+
/** `config/reset` 允许回退到 YAML 的三个覆盖键。 */
|
|
8
|
+
const RESETTABLE_KEYS = ['publicBaseUrls', 'defaultBase', 'limits'];
|
|
9
|
+
/**
|
|
10
|
+
* 校验 `config/reset` 的 keys 入参。
|
|
11
|
+
* @param value 任意 JSON 值;缺省表示重置全部覆盖。
|
|
12
|
+
* @returns 去重后的键列表。
|
|
13
|
+
*/
|
|
14
|
+
function resetKeysOf(value) {
|
|
15
|
+
if (value === undefined)
|
|
16
|
+
return [...RESETTABLE_KEYS];
|
|
17
|
+
if (!Array.isArray(value)) {
|
|
18
|
+
throw fail(400, 'bad-request', 'keys 必须是字符串数组');
|
|
19
|
+
}
|
|
20
|
+
const keys = [];
|
|
21
|
+
for (const entry of value) {
|
|
22
|
+
if (typeof entry !== 'string' || !RESETTABLE_KEYS.includes(entry)) {
|
|
23
|
+
throw fail(400, 'bad-request', `未知的配置键 ${JSON.stringify(entry)}(可用:${RESETTABLE_KEYS.join('、')})`);
|
|
24
|
+
}
|
|
25
|
+
const key = entry;
|
|
26
|
+
if (!keys.includes(key))
|
|
27
|
+
keys.push(key);
|
|
28
|
+
}
|
|
29
|
+
return keys;
|
|
30
|
+
}
|
|
31
|
+
/** 判断一个 JSON 值是不是普通对象(数组与 null 都不算)。 */
|
|
32
|
+
function isRecord(value) {
|
|
33
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 要求 payload 是对象。
|
|
37
|
+
* @param payload wire 上的 payload。
|
|
38
|
+
*/
|
|
39
|
+
function payloadOf(payload) {
|
|
40
|
+
if (!isRecord(payload)) {
|
|
41
|
+
throw fail(400, 'bad-request', 'payload 必须是 JSON 对象');
|
|
42
|
+
}
|
|
43
|
+
return payload;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* 要求一个「有可能存在」的会话 id。
|
|
47
|
+
* @param value 任意 JSON 值。
|
|
48
|
+
*/
|
|
49
|
+
function sessionIdOf(value) {
|
|
50
|
+
if (typeof value !== 'string' || !SESSION_ID_PATTERN.test(value)) {
|
|
51
|
+
throw fail(400, 'bad-request', 'sessionId 必须是 1–128 位的会话 id');
|
|
52
|
+
}
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* 在共享的 `/api` 通道上注册管理路由。
|
|
57
|
+
* @param options 上下文与各服务。
|
|
58
|
+
* @returns 交给调用方 effect 持有的 disposer。
|
|
59
|
+
*/
|
|
60
|
+
export function registerControl({ ctx, agents, connection, store, getConfig, getUrlFiles, settings, onConfigChanged, logger, }) {
|
|
61
|
+
/**
|
|
62
|
+
* 绑定 URL 之前确认会话确实存在。
|
|
63
|
+
* @param sessionId 会话 id。
|
|
64
|
+
*/
|
|
65
|
+
async function assertSessionExists(sessionId) {
|
|
66
|
+
if (agents.get(sessionId) !== undefined)
|
|
67
|
+
return;
|
|
68
|
+
const persistence = ctx.get('sessionPersistence');
|
|
69
|
+
if (persistence === undefined) {
|
|
70
|
+
throw fail(501, 'stored-unsupported', '本 profile 没有组合 sessionPersistence,只有活着的会话可以拥有端点');
|
|
71
|
+
}
|
|
72
|
+
const snapshot = await persistence.stat(sessionId);
|
|
73
|
+
if (snapshot === undefined)
|
|
74
|
+
throw fail(404, 'unknown-session', `会话 ${sessionId} 不存在`);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* `config/set`:全量覆盖语义(不是 merge-patch)。
|
|
78
|
+
*
|
|
79
|
+
* 入参三键都可缺省(缺省=沿用当前生效值),但一旦给了 `publicBaseUrls` 就是
|
|
80
|
+
* **整表替换**(`{}` / `null` 表示清空显式入口,只剩隐式 direct);给了 `limits`
|
|
81
|
+
* 就要求三个字段齐全。这样界面删行才删得掉。
|
|
82
|
+
*
|
|
83
|
+
* 保存后立即生效(替换 `RuntimeConfig` 快照 + 重建投递 handler + 重写 urlFile)。
|
|
84
|
+
* `directOrigin` 取不到时保存**仍然成功**(settings.json 只是覆盖层):urlFile 重写
|
|
85
|
+
* 由 index 侧记 warn,返回体里的 `directError` 会让界面显示原因。
|
|
86
|
+
* @param body 设置页提交的配置。
|
|
87
|
+
*/
|
|
88
|
+
async function saveConfig(body) {
|
|
89
|
+
const config = getConfig();
|
|
90
|
+
const publicBaseUrls = body.publicBaseUrls === undefined
|
|
91
|
+
? config.explicitBases
|
|
92
|
+
: normalizePublicBaseUrls(body.publicBaseUrls);
|
|
93
|
+
// defaultBase 缺省时沿用当前值;但它在新的入口表里必须仍然存在(删掉当前默认
|
|
94
|
+
// 入口时必须同时指定新的 defaultBase),否则明确报 unknown-base。
|
|
95
|
+
const defaultBase = normalizeDefaultBase(body.defaultBase === undefined ? config.effectiveDefaultBase : body.defaultBase, publicBaseUrls);
|
|
96
|
+
const limits = body.limits === undefined
|
|
97
|
+
? normalizeLimits(config.limits)
|
|
98
|
+
: normalizeLimits(body.limits);
|
|
99
|
+
// 三个键全量写:界面保存即「整表接管」这三个键(reset 才逐键回退)。
|
|
100
|
+
const document = { publicBaseUrls, defaultBase, limits };
|
|
101
|
+
// 顺序很重要:先落盘(设置页的持久化事实),再替换生效值,最后重建
|
|
102
|
+
// 投递 handler + 重写 urlFile。中途失败时配置仍然已保存,下次重载自愈。
|
|
103
|
+
await settings.save(document);
|
|
104
|
+
config.replaceSettings(document);
|
|
105
|
+
try {
|
|
106
|
+
await onConfigChanged();
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
110
|
+
throw fail(500, 'urlfile-failed', `配置已保存并已生效,但 URL 文件(urlFile)写入失败:${reason}(下次插件重载会自动对齐)`);
|
|
111
|
+
}
|
|
112
|
+
// 返回体与 `config/get` 同形(多一个 saved),界面可直接复渲染。
|
|
113
|
+
return { saved: true, ...getConfig().describe() };
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* `config/reset`:把指定键的界面覆盖删除,回落到 YAML 层。
|
|
117
|
+
*
|
|
118
|
+
* 存在的理由:设置文件是「整表接管」的覆盖层,界面保存一次之后 YAML 就永久失效。
|
|
119
|
+
* 没有回退口,用户想回到 YAML 只能手改 `settings.json`——这正好违背「不用改配置文件」。
|
|
120
|
+
*
|
|
121
|
+
* 语义:`keys` 缺省 = 清空全部覆盖(删掉 settings.json);否则逐键删除、其余键保留。
|
|
122
|
+
* 删除覆盖可能让 `defaultBase` 指向一个只存在于被删层里的入口,因此**先校验再落盘**:
|
|
123
|
+
* 校验失败时 settings.json 与生效值都保持原样。
|
|
124
|
+
* @param body 设置页提交的 `{ keys? }`。
|
|
125
|
+
*/
|
|
126
|
+
async function resetConfig(body) {
|
|
127
|
+
const keys = resetKeysOf(body.keys);
|
|
128
|
+
const config = getConfig();
|
|
129
|
+
const next = config.settingsLayer;
|
|
130
|
+
for (const key of keys)
|
|
131
|
+
delete next[key];
|
|
132
|
+
config.validateSettings(next);
|
|
133
|
+
if (Object.keys(next).length === 0) {
|
|
134
|
+
await settings.clear();
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
await settings.save(next);
|
|
138
|
+
}
|
|
139
|
+
config.replaceSettings(next);
|
|
140
|
+
try {
|
|
141
|
+
await onConfigChanged();
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
145
|
+
throw fail(500, 'urlfile-failed', `配置覆盖已回退并生效,但 URL 文件(urlFile)写入失败:${reason}(下次重载会自动对齐)`);
|
|
146
|
+
}
|
|
147
|
+
return { saved: true, ...getConfig().describe() };
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* 派发一个管理方法。
|
|
151
|
+
* @param endpoint 方法名(`hooks/list` 等)。
|
|
152
|
+
* @param payload 方法入参。
|
|
153
|
+
*/
|
|
154
|
+
async function invoke(endpoint, payload) {
|
|
155
|
+
const body = payloadOf(payload);
|
|
156
|
+
switch (endpoint) {
|
|
157
|
+
case 'hooks/list': {
|
|
158
|
+
const sessionId = body.sessionId === undefined ? undefined : sessionIdOf(body.sessionId);
|
|
159
|
+
const config = getConfig();
|
|
160
|
+
const urlFiles = getUrlFiles();
|
|
161
|
+
const baseNames = config.bases.names();
|
|
162
|
+
const hooks = [];
|
|
163
|
+
for (const hook of store.list(sessionId)) {
|
|
164
|
+
hooks.push({
|
|
165
|
+
...hookView(hook),
|
|
166
|
+
archived: isArchived(ctx, hook.sessionId),
|
|
167
|
+
urlFiles: await urlFiles.existing(hook.id, baseNames),
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
return { hooks };
|
|
171
|
+
}
|
|
172
|
+
case 'hooks/create': {
|
|
173
|
+
const sessionId = sessionIdOf(body.sessionId);
|
|
174
|
+
await assertSessionExists(sessionId);
|
|
175
|
+
const config = getConfig();
|
|
176
|
+
// 先确认入口集合可解析(direct origin 现取),避免「建了端点却返回不了 URL」。
|
|
177
|
+
config.bases.bases();
|
|
178
|
+
const hook = await store.create({
|
|
179
|
+
sessionId,
|
|
180
|
+
name: normalizeName(body.name),
|
|
181
|
+
tags: normalizeTags(body.tags),
|
|
182
|
+
defaultMode: normalizeMode(body.defaultMode),
|
|
183
|
+
// 界面创建 → 'ui';工具创建走 tools.ts 显式传 'agent'。
|
|
184
|
+
createdBy: 'ui',
|
|
185
|
+
});
|
|
186
|
+
const urlFiles = await getUrlFiles().write(hook.id, config.bases.urlsFor(config.basePath, hook.token));
|
|
187
|
+
return {
|
|
188
|
+
hook: hookView(hook),
|
|
189
|
+
// `url` 是默认入口的完整 URL(管理面与浏览器同源,允许揭示)。
|
|
190
|
+
url: config.bases.urlFor(config.basePath, hook.token),
|
|
191
|
+
defaultBase: config.bases.defaultBase,
|
|
192
|
+
urlFiles,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
case 'hooks/update': {
|
|
196
|
+
if (typeof body.hookId !== 'string')
|
|
197
|
+
throw fail(400, 'bad-request', 'hookId 是必填项');
|
|
198
|
+
const patch = {
|
|
199
|
+
...(body.name === undefined ? {} : { name: body.name }),
|
|
200
|
+
...(body.tags === undefined ? {} : { tags: body.tags }),
|
|
201
|
+
...(body.defaultMode === undefined ? {} : { defaultMode: body.defaultMode }),
|
|
202
|
+
...(body.enabled === undefined ? {} : { enabled: body.enabled }),
|
|
203
|
+
};
|
|
204
|
+
const hook = await store.update(body.hookId, patch);
|
|
205
|
+
return { hook: hookView(hook) };
|
|
206
|
+
}
|
|
207
|
+
case 'hooks/reveal': {
|
|
208
|
+
if (typeof body.hookId !== 'string')
|
|
209
|
+
throw fail(400, 'bad-request', 'hookId 是必填项');
|
|
210
|
+
const hook = store.get(body.hookId);
|
|
211
|
+
if (hook === undefined)
|
|
212
|
+
throw fail(404, 'unknown-endpoint', '没有这个 id 的端点');
|
|
213
|
+
const config = getConfig();
|
|
214
|
+
// 多入口下揭示默认入口;其余入口的完整 URL 只在各自的 urlFile 里。
|
|
215
|
+
return { url: config.bases.urlFor(config.basePath, hook.token) };
|
|
216
|
+
}
|
|
217
|
+
case 'hooks/revoke': {
|
|
218
|
+
if (typeof body.hookId !== 'string')
|
|
219
|
+
throw fail(400, 'bad-request', 'hookId 是必填项');
|
|
220
|
+
const hook = await store.revoke(body.hookId);
|
|
221
|
+
// UI 撤销不受 createdBy 限制;工具撤销的权限判定在 tools.ts。
|
|
222
|
+
await getUrlFiles().remove(hook.id);
|
|
223
|
+
return { revoked: true };
|
|
224
|
+
}
|
|
225
|
+
case 'config/get': {
|
|
226
|
+
return getConfig().describe();
|
|
227
|
+
}
|
|
228
|
+
case 'config/set': {
|
|
229
|
+
return saveConfig(body);
|
|
230
|
+
}
|
|
231
|
+
case 'config/reset': {
|
|
232
|
+
return resetConfig(body);
|
|
233
|
+
}
|
|
234
|
+
default:
|
|
235
|
+
throw fail(404, 'unknown-method', `未知的管理方法 ${endpoint}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* 管理入口:把领域失败折成 `{ok:false}` 包络。
|
|
240
|
+
* @param endpoint 方法名。
|
|
241
|
+
* @param payload 方法入参。
|
|
242
|
+
*/
|
|
243
|
+
const handler = async (endpoint, payload) => {
|
|
244
|
+
try {
|
|
245
|
+
return { ok: true, value: await invoke(endpoint, payload) };
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
const failure = asFailure(error);
|
|
249
|
+
if (failure.code === 'delivery-failed') {
|
|
250
|
+
logger?.warn?.(`[session-inject] 管理调用 ${endpoint} 失败:${failure.message}`);
|
|
251
|
+
}
|
|
252
|
+
return { ok: false, error: failure };
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
// 共享 `/api` 通道上的一条精确 Fetch 路由。
|
|
256
|
+
//
|
|
257
|
+
// 不用 `rpc.handle()`:那个 helper 经 Connection 服务自己的 context 注册 web 路由,
|
|
258
|
+
// 而那个 fiber 并不 inject `webServer`,对任何插件都会抛
|
|
259
|
+
// `cannot get property "webServer" without inject`。
|
|
260
|
+
// 也不用 `rpc.intercept('/api')`:那个座位是排他的,API gateway 已经占着。
|
|
261
|
+
return connection.fetch.register({
|
|
262
|
+
path: ROUTE_PATH,
|
|
263
|
+
methods: ['POST'],
|
|
264
|
+
requestBody: 'buffered',
|
|
265
|
+
fetch: createManagementFetch(handler, logger),
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* 组一个服务端响应包络。
|
|
270
|
+
* @param rpcId 关联 id。
|
|
271
|
+
* @param result 处理结果。
|
|
272
|
+
*/
|
|
273
|
+
function envelope(rpcId, result) {
|
|
274
|
+
return { type: 'server-response', rpcId, result };
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* 把 RPC handler 适配到 Fetch 路由契约:解客户端包络、派发、回带关联 id。
|
|
278
|
+
* @param handler 管理方法分发器。
|
|
279
|
+
* @param logger 可选 logger。
|
|
280
|
+
*/
|
|
281
|
+
export function createManagementFetch(handler, logger) {
|
|
282
|
+
return async function managementFetch(request) {
|
|
283
|
+
if (request.method !== 'POST') {
|
|
284
|
+
return new Response('method not allowed', { status: 405, headers: { allow: 'POST' } });
|
|
285
|
+
}
|
|
286
|
+
let message;
|
|
287
|
+
try {
|
|
288
|
+
message = await request.json();
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
return Response.json(envelope('invalid-request', {
|
|
292
|
+
ok: false,
|
|
293
|
+
error: { code: 'bad-request', message: 'body 不是 JSON', details: {} },
|
|
294
|
+
}));
|
|
295
|
+
}
|
|
296
|
+
const rpcId = isRecord(message) && typeof message.rpcId === 'string' ? message.rpcId : 'invalid-request';
|
|
297
|
+
if (!isRecord(message) || message.type !== 'client-request') {
|
|
298
|
+
return Response.json(envelope(rpcId, {
|
|
299
|
+
ok: false,
|
|
300
|
+
error: { code: 'bad-request', message: '期望 client-request 包络', details: {} },
|
|
301
|
+
}));
|
|
302
|
+
}
|
|
303
|
+
const call = message.payload;
|
|
304
|
+
if (!isRecord(call) || typeof call.method !== 'string') {
|
|
305
|
+
return Response.json(envelope(rpcId, {
|
|
306
|
+
ok: false,
|
|
307
|
+
error: { code: 'bad-request', message: 'payload 必须带字符串 method', details: {} },
|
|
308
|
+
}));
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
return Response.json(envelope(rpcId, await handler(call.method, call.payload)));
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
logger?.warn?.(`[session-inject] 管理包络失败:${error instanceof Error ? error.message : String(error)}`);
|
|
315
|
+
return Response.json(envelope(rpcId, {
|
|
316
|
+
ok: false,
|
|
317
|
+
error: { code: 'delivery-failed', message: error instanceof Error ? error.message : String(error), details: {} },
|
|
318
|
+
}), { status: 500 });
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
}
|
package/lib/deliver.js
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 目标解析与收件箱投递。
|
|
3
|
+
*
|
|
4
|
+
* 注册表里只存一个会话 id,所以每次投递都要现场判断目标处在六种状态里的哪一种:
|
|
5
|
+
* 活着、已存(磁盘上有)、已归档、被别的 writer 占用、当前组合里恢复不了、已删除。
|
|
6
|
+
* 前两种可以投;其余一律明确失败——一个回 2xx 却永远不执行的 webhook,比一个当场
|
|
7
|
+
* 拒绝的 webhook 更糟。
|
|
8
|
+
*/
|
|
9
|
+
import { boundContextSummary, createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
10
|
+
import { fail } from './errors.js';
|
|
11
|
+
/**
|
|
12
|
+
* 目标会话当前是否被某个活 Agent 占用。
|
|
13
|
+
* @param agents agents 服务。
|
|
14
|
+
* @param sessionId 会话 id。
|
|
15
|
+
*/
|
|
16
|
+
export function isLive(agents, sessionId) {
|
|
17
|
+
return agents.get(sessionId) !== undefined;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* 工作区注册表是否把该会话标为已归档。
|
|
21
|
+
* @param ctx 插件上下文。
|
|
22
|
+
* @param sessionId 会话 id。
|
|
23
|
+
*/
|
|
24
|
+
export function isArchived(ctx, sessionId) {
|
|
25
|
+
const registry = ctx.get('workspaceRegistry');
|
|
26
|
+
const ids = registry?.archivedSessionIds;
|
|
27
|
+
return Array.isArray(ids) && ids.includes(sessionId);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* 把冷恢复的拒绝映射到 wire 词汇。
|
|
31
|
+
* @param sessionId 会话 id。
|
|
32
|
+
* @param error 捕获到的任意值。
|
|
33
|
+
*/
|
|
34
|
+
function resumeFailure(sessionId, error) {
|
|
35
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
36
|
+
const name = error instanceof Error ? error.name : '';
|
|
37
|
+
if (name === 'SessionAlreadyOwnedError' || /already owned|ownership/i.test(message)) {
|
|
38
|
+
return fail(409, 'session-busy', `会话 ${sessionId} 被另一个写入方占用`, { cause: message });
|
|
39
|
+
}
|
|
40
|
+
if (/preset/i.test(message) || /does not compose/i.test(message)) {
|
|
41
|
+
return fail(409, 'preset-unavailable', `会话 ${sessionId} 无法在当前组合里恢复:${message}`);
|
|
42
|
+
}
|
|
43
|
+
return fail(409, 'resume-failed', `会话 ${sessionId} 恢复失败:${message}`);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* 投递前的廉价检查:决定「这条投递能不能受理」。
|
|
47
|
+
* 跑在 202 之前,脚本能当场知道链接目标死了;只有慢的冷恢复留在请求路径之外。
|
|
48
|
+
* @param ctx 插件上下文。
|
|
49
|
+
* @param agents agents 服务。
|
|
50
|
+
* @param hook 端点记录。
|
|
51
|
+
* @param mode 本次投递方式。
|
|
52
|
+
* @returns 目标是活着的还是需要冷恢复。
|
|
53
|
+
*/
|
|
54
|
+
export async function preflight(ctx, agents, hook, mode) {
|
|
55
|
+
if (isLive(agents, hook.sessionId))
|
|
56
|
+
return { live: true };
|
|
57
|
+
if (mode === 'passive') {
|
|
58
|
+
throw fail(400, 'passive-requires-live', 'passive 只能进入活会话的上下文;已存会话被冷恢复后也不会被唤醒');
|
|
59
|
+
}
|
|
60
|
+
const persistence = ctx.get('sessionPersistence');
|
|
61
|
+
if (persistence === undefined) {
|
|
62
|
+
throw fail(501, 'stored-unsupported', `会话 ${hook.sessionId} 不活着,且本 profile 没有组合 sessionPersistence`);
|
|
63
|
+
}
|
|
64
|
+
if (isArchived(ctx, hook.sessionId)) {
|
|
65
|
+
throw fail(409, 'session-archived', `会话 ${hook.sessionId} 已归档:它会受理这条投递但永远不会执行`);
|
|
66
|
+
}
|
|
67
|
+
const snapshot = await persistence.stat(hook.sessionId);
|
|
68
|
+
if (snapshot === undefined) {
|
|
69
|
+
throw fail(404, 'unknown-session', `会话 ${hook.sessionId} 已不存在`);
|
|
70
|
+
}
|
|
71
|
+
return { live: false };
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* 冷恢复时按会话记录重新挂上它原来的组合(preset)。
|
|
75
|
+
*
|
|
76
|
+
* 为什么必须做:preset 不是「会话的属性」,而是**挂在 agentCtx 上的一整套插件**。
|
|
77
|
+
* 冷恢复只把会话日志读回来,不会自动重挂那套组合——漏掉的后果是目标会话用一份残缺的
|
|
78
|
+
* 组合继续跑:工具集从 78 掉到 50(`bash`、`read`、`write` 等全没了),
|
|
79
|
+
* 连 `compaction-basic` 都不在(宿主在 `dsh-web-app` 的 cordis.patch 里**故意**禁用了
|
|
80
|
+
* host 层的压缩,把家放在 preset 里),于是该会话永久失去自动压缩能力——上下文涨过
|
|
81
|
+
* 窗口后每轮被 provider 400 拒绝,且它自己修不好(没有工具去压缩)。
|
|
82
|
+
*
|
|
83
|
+
* 权威来源必须是 Session 投影,不能是 header:header 是**创建时**的事实,会话可以在
|
|
84
|
+
* blank 期换 preset,改动记在 `agent-preset/selected` 事件里、由投影推进。
|
|
85
|
+
* 用 `stateOf() ?? header` 会在改过 preset 的会话上**静默挂错**组合——比直接失败更糟。
|
|
86
|
+
* 上游契约见 `@deepseek-ai/dsh-agent-preset-registry/lib/types/session.d.ts`:
|
|
87
|
+
* 「Reconstruction reads the `agentPreset` Session projection, never the header alone.」
|
|
88
|
+
*
|
|
89
|
+
* 服务用 `ctx.get()` 而不是加进插件 `inject`:把 `agentPresets` 写进 inject 会让
|
|
90
|
+
* **没有 preset 的 profile 整个插件都加载不了**,包括「只给活会话投递」这种根本不需要
|
|
91
|
+
* preset 的场景。按 harness 的规矩(配置问题要么加载时炸、否则在最早可解析点炸),
|
|
92
|
+
* 冷恢复就是最早可解析点,所以在这里显式抛错。
|
|
93
|
+
*
|
|
94
|
+
* @param ctx 插件上下文(读取宿主服务)。
|
|
95
|
+
* @param agentCtx 刚铸造出来的 agent 上下文(组合挂在这里)。
|
|
96
|
+
* @param agent 正在恢复的 agent(用于读会话投影)。
|
|
97
|
+
*/
|
|
98
|
+
async function mountResumedPreset(ctx, agentCtx, agent) {
|
|
99
|
+
const presets = ctx.get('agentPresets');
|
|
100
|
+
if (presets === undefined) {
|
|
101
|
+
throw fail(409, 'preset-unavailable', '冷恢复需要一个 agentPresets 注册表来重建会话的 preset,但当前 profile 没有组合它');
|
|
102
|
+
}
|
|
103
|
+
const projections = ctx.get('sessionProjections');
|
|
104
|
+
if (projections === undefined) {
|
|
105
|
+
throw fail(409, 'preset-unavailable', '冷恢复需要 sessionProjections 读取会话记录的 preset,但当前 profile 没有组合它');
|
|
106
|
+
}
|
|
107
|
+
// 投影缺省(会话创建时没记 preset)时传 undefined,交给注册表用 profile 默认值。
|
|
108
|
+
await presets.mount(agentCtx, projections.stateOf(agent.session, 'agentPreset') ?? undefined);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* 给冷恢复的 Agent 补上它这个会话上次用的模型路由。
|
|
112
|
+
*
|
|
113
|
+
* driver 从 AgentOptions 解析 provider/model,并从同一份 options 渲染 `{{model}}`,
|
|
114
|
+
* 所以不带路由的 resume 会在第一轮就挂在 'prompt variable "{{model}}" has no value'。
|
|
115
|
+
* 下面这两个 Agent 作用域监听器与 Web 会话控制器装的是同一套(installModelSelection),
|
|
116
|
+
* 差别只有一点:它们只在「下游还没有人选定」时兜底。
|
|
117
|
+
*
|
|
118
|
+
* 传给 resume 的种子就是循环后面每次请求的路由,因此「请求里的值还等于种子」等价于
|
|
119
|
+
* 「还没有后来的权威改过它」。等 Web 会话控制器挂上自己的选择(例如用户打开这个会话
|
|
120
|
+
* 切了模型),请求就不再等于种子,这两个监听器自动让位,不会把旧路由钉死。
|
|
121
|
+
*
|
|
122
|
+
* 内联而不是从 `@deepseek-ai/dsh-agent` import:插件解析的是自己那份 `@deepseek-ai/*`
|
|
123
|
+
* 依赖副本,不依赖 dsh-agent。
|
|
124
|
+
*/
|
|
125
|
+
function installSessionRoute(ctx, agent, seed) {
|
|
126
|
+
const header = agent.session.requestHeader();
|
|
127
|
+
const config = header?.config;
|
|
128
|
+
const route = config === undefined
|
|
129
|
+
? ctx.get('agentDefaultModel')?.currentSelection()
|
|
130
|
+
: {
|
|
131
|
+
provider: config.provider,
|
|
132
|
+
model: config.model,
|
|
133
|
+
...(config.reasoningEffort === undefined || header?.adapterDefaults?.reasoningEffort === true
|
|
134
|
+
? {} : { reasoningEffort: config.reasoningEffort }),
|
|
135
|
+
};
|
|
136
|
+
if (route === undefined)
|
|
137
|
+
return;
|
|
138
|
+
/** 值缺失、或仍等于 resume 传下去的种子。 */
|
|
139
|
+
const untouched = (value, seeded) => value === undefined || value === seeded;
|
|
140
|
+
const bus = agent.ctx;
|
|
141
|
+
bus.on('system-prompt/assemble', async (_assembly, _context, next) => {
|
|
142
|
+
const assembled = await next();
|
|
143
|
+
const variables = assembled.variables ?? {};
|
|
144
|
+
if (!untouched(variables.provider, seed.provider) || !untouched(variables.model, seed.model))
|
|
145
|
+
return assembled;
|
|
146
|
+
return {
|
|
147
|
+
...assembled,
|
|
148
|
+
variables: {
|
|
149
|
+
...variables,
|
|
150
|
+
provider: variables.provider ?? route.provider,
|
|
151
|
+
model: variables.model ?? route.model,
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
});
|
|
155
|
+
bus.on('agent/request', async (_payload, next) => {
|
|
156
|
+
const resolved = await next();
|
|
157
|
+
if (!untouched(resolved.provider, seed.provider) || !untouched(resolved.model, seed.model))
|
|
158
|
+
return resolved;
|
|
159
|
+
// 只丢掉继承来的 reasoningEffort,由下面按 route 重新决定;其余字段原样透传。
|
|
160
|
+
const { reasoningEffort: _inherited, ...rest } = resolved;
|
|
161
|
+
const rebound = {
|
|
162
|
+
...rest,
|
|
163
|
+
provider: route.provider,
|
|
164
|
+
model: route.model,
|
|
165
|
+
...(route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort }),
|
|
166
|
+
};
|
|
167
|
+
return rebound;
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* 把端点绑定的会话解析成本进程里的活 Agent;会话已存则冷恢复。
|
|
172
|
+
* @param ctx 插件上下文。
|
|
173
|
+
* @param agents agents 服务。
|
|
174
|
+
* @param hook 端点记录。
|
|
175
|
+
* @returns Agent 句柄与「是不是冷恢复出来的」。
|
|
176
|
+
*/
|
|
177
|
+
export async function resolveTarget(ctx, agents, hook) {
|
|
178
|
+
const live = agents.get(hook.sessionId);
|
|
179
|
+
if (live !== undefined)
|
|
180
|
+
return { agent: live, resumed: false };
|
|
181
|
+
const persistence = ctx.get('sessionPersistence');
|
|
182
|
+
if (persistence === undefined) {
|
|
183
|
+
throw fail(501, 'stored-unsupported', `会话 ${hook.sessionId} 不活着,且本 profile 没有组合 sessionPersistence`);
|
|
184
|
+
}
|
|
185
|
+
if (isArchived(ctx, hook.sessionId)) {
|
|
186
|
+
throw fail(409, 'session-archived', `会话 ${hook.sessionId} 已归档:它会受理这条投递但永远不会执行`);
|
|
187
|
+
}
|
|
188
|
+
const snapshot = await persistence.stat(hook.sessionId);
|
|
189
|
+
if (snapshot === undefined) {
|
|
190
|
+
throw fail(404, 'unknown-session', `会话 ${hook.sessionId} 已不存在`);
|
|
191
|
+
}
|
|
192
|
+
// 冷恢复必须带模型路由;profile 默认值就是 Web 会话控制器在装自己的选择之前用的那个种子。
|
|
193
|
+
const fallback = ctx.get('agentDefaultModel')?.currentSelection();
|
|
194
|
+
const seed = {
|
|
195
|
+
provider: fallback?.provider,
|
|
196
|
+
model: fallback?.model,
|
|
197
|
+
};
|
|
198
|
+
const handle = await (async () => {
|
|
199
|
+
try {
|
|
200
|
+
return await agents.resume({
|
|
201
|
+
resumeSessionId: hook.sessionId,
|
|
202
|
+
...(fallback === undefined ? {} : {
|
|
203
|
+
agentOptions: {
|
|
204
|
+
provider: fallback.provider,
|
|
205
|
+
model: fallback.model,
|
|
206
|
+
...(fallback.reasoningEffort === undefined ? {} : { reasoningEffort: fallback.reasoningEffort }),
|
|
207
|
+
},
|
|
208
|
+
}),
|
|
209
|
+
// 组合必须在发布 agent 之前挂好,否则目标会话会以残缺组合继续跑(见函数注释)。
|
|
210
|
+
setup: async (agentCtx, agent) => { await mountResumedPreset(ctx, agentCtx, agent); },
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
throw resumeFailure(hook.sessionId, error);
|
|
215
|
+
}
|
|
216
|
+
})();
|
|
217
|
+
installSessionRoute(ctx, handle.agent, seed);
|
|
218
|
+
return { agent: handle.agent, resumed: true };
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* 构造目标会话看到的那条用户消息。
|
|
222
|
+
*
|
|
223
|
+
* 来源是 `webhook` 记录而不是 `user`:Chat 面把任何非 user 来源渲染成注入的上下文行,
|
|
224
|
+
* 一条唤醒回合的消息会显示成「收到外部事件」的触发卡并带 webhook 图标。若写成 `user`,
|
|
225
|
+
* 它会渲染成普通人发的气泡——那正是这个端点绝不能做的冒充。
|
|
226
|
+
*
|
|
227
|
+
* 声明成 `webhook` 来源还要带上 rule-runtime 的 id 与 `form: 'notice'` 的一行摘要。
|
|
228
|
+
* 这些 id 是不透明的品牌字符串、没有运行时注册表,所以本生产者自己铸:端点 id 顶替
|
|
229
|
+
* rule/source,投递 id 用注册表里记下的那个。摘要用宿主自己的 helper 截断,因为它会
|
|
230
|
+
* 落进会话日志并在不展开时直接展示。
|
|
231
|
+
*
|
|
232
|
+
* 正文第一行保留 `[webhook: <名字>]`:卡片头已经说明这是外部事件,这个标签仍然告诉
|
|
233
|
+
* 模型(以及后来的读者)是哪一个端点投进来的。
|
|
234
|
+
*
|
|
235
|
+
* @param hook 端点记录(只用到 id 与 name,测试里可以只给这两个字段)。
|
|
236
|
+
* @param text 投递正文。
|
|
237
|
+
* @param source 调用方自报的来源(可选,最多 100 字符)。
|
|
238
|
+
* @param deliveryId 投递 id;省略时用端点 id 顶替。
|
|
239
|
+
*/
|
|
240
|
+
export function buildMessage(hook, text, source, deliveryId) {
|
|
241
|
+
const label = source === undefined || source === '' || source === hook.name
|
|
242
|
+
? `[webhook: ${hook.name}]`
|
|
243
|
+
: `[webhook: ${hook.name}] (source: ${source})`;
|
|
244
|
+
const firstLine = text.split('\n', 1)[0]?.trim() ?? '';
|
|
245
|
+
const summary = boundContextSummary(firstLine === '' ? `webhook ${hook.name}` : `${hook.name}: ${firstLine}`);
|
|
246
|
+
return createUserMessage({
|
|
247
|
+
content: [{ type: 'text', text: `${label}\n${text}` }],
|
|
248
|
+
source: {
|
|
249
|
+
kind: 'webhook',
|
|
250
|
+
provider: 'session-inject',
|
|
251
|
+
source: hook.id,
|
|
252
|
+
deliveryId: deliveryId ?? hook.id,
|
|
253
|
+
ruleId: hook.id,
|
|
254
|
+
form: 'notice',
|
|
255
|
+
summary,
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* 按投递方式把一条消息交给 Agent 收件箱。
|
|
261
|
+
* @param agent 目标 Agent。
|
|
262
|
+
* @param mode 投递方式。
|
|
263
|
+
* @param message 构造好的消息。
|
|
264
|
+
*/
|
|
265
|
+
export function deliver(agent, mode, message) {
|
|
266
|
+
if (mode === 'queue')
|
|
267
|
+
agent.followup(message);
|
|
268
|
+
else if (mode === 'passive')
|
|
269
|
+
agent.inject(message);
|
|
270
|
+
else
|
|
271
|
+
agent.steer(message);
|
|
272
|
+
}
|
package/lib/errors.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP 面与管理 RPC 面共享的稳定失败词汇。
|
|
3
|
+
*
|
|
4
|
+
* 线上脚本靠 `error.code` 判断该重试还是该改配置,所以 code 是契约的一部分:
|
|
5
|
+
* 只能新增,不能改名。
|
|
6
|
+
*/
|
|
7
|
+
/** 带稳定 code 的领域失败:HTTP 状态码与 wire 上的错误包络都由它决定。 */
|
|
8
|
+
export class InjectError extends Error {
|
|
9
|
+
/** 稳定的机器可读 code(同时是 wire 上的 `error.code`)。 */
|
|
10
|
+
code;
|
|
11
|
+
/** 该失败对应的 HTTP 状态码。 */
|
|
12
|
+
status;
|
|
13
|
+
/** 附加细节,原样进 wire 的 `error.details`。 */
|
|
14
|
+
details;
|
|
15
|
+
/**
|
|
16
|
+
* @param code 稳定的机器可读 code。
|
|
17
|
+
* @param message 人能读的原因。
|
|
18
|
+
* @param options HTTP 状态码(默认 400)与附加细节。
|
|
19
|
+
*/
|
|
20
|
+
constructor(code, message, options = {}) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.name = 'InjectError';
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.status = options.status ?? 400;
|
|
25
|
+
this.details = options.details ?? {};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* 构造一个领域失败。
|
|
30
|
+
* @param status 投递面返回的 HTTP 状态码。
|
|
31
|
+
* @param code 稳定的机器可读 code。
|
|
32
|
+
* @param message 人能读的原因。
|
|
33
|
+
* @param details 附加的 wire 细节。
|
|
34
|
+
*/
|
|
35
|
+
export function fail(status, code, message, details) {
|
|
36
|
+
return new InjectError(code, message, { status, details });
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* 把任意抛出值窄化成 wire 失败形状。
|
|
40
|
+
* @param error 捕获到的任意值。
|
|
41
|
+
* @returns 稳定的三方字段包络。
|
|
42
|
+
*/
|
|
43
|
+
export function asFailure(error) {
|
|
44
|
+
if (error instanceof InjectError) {
|
|
45
|
+
return { code: error.code, message: error.message, details: error.details };
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
code: 'delivery-failed',
|
|
49
|
+
message: error instanceof Error ? error.message : String(error),
|
|
50
|
+
details: {},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* 取一个失败该用的 HTTP 状态码。
|
|
55
|
+
* 原型里是「任何带数字 status 的错误都沿用它的 status」,这里保留同一口径,
|
|
56
|
+
* 因为 node:http 之外还有别的层会抛带 status 的错误。
|
|
57
|
+
* @param error 捕获到的任意值。
|
|
58
|
+
*/
|
|
59
|
+
export function statusOf(error) {
|
|
60
|
+
const status = typeof error === 'object' && error !== null ? Reflect.get(error, 'status') : undefined;
|
|
61
|
+
return typeof status === 'number' ? status : 500;
|
|
62
|
+
}
|