pygmalion 0.1.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 +68 -0
- package/cordis.patch.yml +6 -0
- package/docs/ARCHITECTURE.md +107 -0
- package/docs/DEPLOY.md +129 -0
- package/docs/PRESET.md +59 -0
- package/package.json +32 -0
- package/preset/pygmalion-director/agent.cordis.yml +138 -0
- package/preset/pygmalion-director/preset.yml +3 -0
- package/preset/pygmalion-director/pygmalion-tools.js +20 -0
- package/src/active-session.js +64 -0
- package/src/agent-life.js +487 -0
- package/src/bot-factory.js +282 -0
- package/src/bots.js +273 -0
- package/src/config.js +67 -0
- package/src/dsh-bookkeeping.js +73 -0
- package/src/gateway.js +248 -0
- package/src/heartbeat.js +318 -0
- package/src/http-api.js +444 -0
- package/src/inbound.js +759 -0
- package/src/index.js +195 -0
- package/src/log.js +56 -0
- package/src/memory-write.js +133 -0
- package/src/outbound.js +392 -0
- package/src/persona.js +380 -0
- package/src/qqapi.js +420 -0
- package/src/refindex.js +83 -0
- package/src/session-log.js +140 -0
- package/src/setup-agent.js +96 -0
- package/src/slash-commands.js +142 -0
- package/src/store.js +155 -0
- package/src/threads.js +118 -0
- package/src/tools.js +500 -0
- package/src/types.js +19 -0
- package/src/wakeup.js +205 -0
- package/src/web-public/app.js +381 -0
- package/src/web-public/index.html +130 -0
- package/src/web-public/style.css +44 -0
- package/src/web-server.js +484 -0
- package/templates/sample-life.mjs +52 -0
package/src/http-api.js
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional HTTP push API mounted on the DSH web server's `webServer` service.
|
|
3
|
+
*
|
|
4
|
+
* Two authenticated endpoints under one configurable prefix (default
|
|
5
|
+
* `/external/qq`):
|
|
6
|
+
*
|
|
7
|
+
* POST <prefix>/send Push text to a QQ target through the same
|
|
8
|
+
* `QQApi.sendText` path agent replies use. With
|
|
9
|
+
* `record: true`, additionally injects a
|
|
10
|
+
* model-visible record into the target's current
|
|
11
|
+
* agent session (`agent.inject`, no wakeup) so the
|
|
12
|
+
* model knows about the push without answering it.
|
|
13
|
+
* GET <prefix>/channels List every target the adapter has routed before
|
|
14
|
+
* (deduped by target, newest activity first).
|
|
15
|
+
*
|
|
16
|
+
* The mount is a plain prefix registration on the host webServer — it never
|
|
17
|
+
* touches the `/api` RPC channel. Bearer authentication is mandatory: the dsh
|
|
18
|
+
* web server binds loopback by default and its request fence is not an auth
|
|
19
|
+
* layer, so without a token any local process could drive the bot.
|
|
20
|
+
*/
|
|
21
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
22
|
+
import { chunkText } from './outbound.js';
|
|
23
|
+
import { effectiveSessionId } from './inbound.js';
|
|
24
|
+
import { targetKey } from './threads.js';
|
|
25
|
+
import { wakeupSession, archiveWakeup } from './wakeup.js';
|
|
26
|
+
/** Request-body cap: pushes are text-only; 1 MiB is far beyond any sane chunk set. */
|
|
27
|
+
const BODY_LIMIT_BYTES = 1024 * 1024;
|
|
28
|
+
/** Mount point: absolute path of URL-safe segments, no trailing slash. */
|
|
29
|
+
const PATH_PATTERN = /^\/[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*$/;
|
|
30
|
+
/** Channel shorthand: `c2c:<openid>` / `group:<openid>` / `channel:<id>`. */
|
|
31
|
+
const SHORTHAND_PATTERN = /^(c2c|group|channel):([A-Za-z0-9_-]+)$/;
|
|
32
|
+
/** Full session-id form also accepted as shorthand: `qq:v2:<scope>:<id>[#n<k>]`. */
|
|
33
|
+
const SESSION_ID_PATTERN = /^qq:v2:(c2c|group|channel):([^:#]+?)(?:#n\d+)?$/;
|
|
34
|
+
/**
|
|
35
|
+
* Validate the per-bot HTTP push API config (修 D15:path/endpoint 配置化到 BotConfig)。
|
|
36
|
+
* @param opts - { path: 挂载前缀, token: Bearer token }
|
|
37
|
+
* @throws when the token is missing/short or the path is malformed — an
|
|
38
|
+
* explicitly requested API must fail the plugin load loudly, never silently
|
|
39
|
+
* skip mounting.
|
|
40
|
+
*/
|
|
41
|
+
export function resolveHttpApiMount({ path, token }) {
|
|
42
|
+
if (typeof token !== 'string' || token.length < 8) {
|
|
43
|
+
throw new Error('pygmalion: httpApiToken 缺失或过短(至少 8 个字符)');
|
|
44
|
+
}
|
|
45
|
+
const p = path ?? '/external/qq/bot-1';
|
|
46
|
+
if (!PATH_PATTERN.test(p)) {
|
|
47
|
+
throw new Error(`pygmalion: httpApiPath ${JSON.stringify(p)} 必须是绝对路径(段内仅字母数字与 . _ ~ -),且不以 / 结尾`);
|
|
48
|
+
}
|
|
49
|
+
return { path: p, token };
|
|
50
|
+
}
|
|
51
|
+
/** Constant-time Bearer check; length mismatch already leaks only the length. */
|
|
52
|
+
function authorized(req, token) {
|
|
53
|
+
const header = req.headers.authorization;
|
|
54
|
+
if (typeof header !== 'string')
|
|
55
|
+
return false;
|
|
56
|
+
const match = /^Bearer (.+)$/.exec(header);
|
|
57
|
+
if (match === null)
|
|
58
|
+
return false;
|
|
59
|
+
const provided = Buffer.from(match[1], 'utf8');
|
|
60
|
+
const expected = Buffer.from(token, 'utf8');
|
|
61
|
+
if (provided.length !== expected.length)
|
|
62
|
+
return false;
|
|
63
|
+
return timingSafeEqual(provided, expected);
|
|
64
|
+
}
|
|
65
|
+
/** Body read failure categories mapped onto distinct HTTP statuses. */
|
|
66
|
+
class BodyError extends Error {
|
|
67
|
+
status;
|
|
68
|
+
constructor(status, message) {
|
|
69
|
+
super(message);
|
|
70
|
+
this.status = status;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** Read and parse one JSON request body, enforcing the size cap. */
|
|
74
|
+
async function readJsonBody(req) {
|
|
75
|
+
const chunks = [];
|
|
76
|
+
let size = 0;
|
|
77
|
+
for await (const chunk of req) {
|
|
78
|
+
const part = chunk;
|
|
79
|
+
size += part.length;
|
|
80
|
+
if (size > BODY_LIMIT_BYTES)
|
|
81
|
+
throw new BodyError(413, `请求体超过 ${BODY_LIMIT_BYTES} 字节上限`);
|
|
82
|
+
chunks.push(part);
|
|
83
|
+
}
|
|
84
|
+
const raw = Buffer.concat(chunks).toString('utf8');
|
|
85
|
+
let parsed;
|
|
86
|
+
try {
|
|
87
|
+
parsed = JSON.parse(raw);
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
throw new BodyError(400, '请求体不是合法 JSON');
|
|
91
|
+
}
|
|
92
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
93
|
+
throw new BodyError(400, '请求体必须是 JSON 对象');
|
|
94
|
+
}
|
|
95
|
+
return parsed;
|
|
96
|
+
}
|
|
97
|
+
/** Parse `channel` shorthand (`c2c:U` / `qq:v2:c2c:U#n1`) into a target. */
|
|
98
|
+
function parseShorthand(value) {
|
|
99
|
+
const short = SHORTHAND_PATTERN.exec(value);
|
|
100
|
+
if (short !== null) {
|
|
101
|
+
if (short[1] === 'c2c')
|
|
102
|
+
return { kind: 'c2c', userId: short[2] };
|
|
103
|
+
if (short[1] === 'group')
|
|
104
|
+
return { kind: 'group', groupId: short[2] };
|
|
105
|
+
return { kind: 'channel', channelId: short[2] };
|
|
106
|
+
}
|
|
107
|
+
const full = SESSION_ID_PATTERN.exec(value);
|
|
108
|
+
if (full !== null) {
|
|
109
|
+
if (full[1] === 'c2c')
|
|
110
|
+
return { kind: 'c2c', userId: full[2] };
|
|
111
|
+
if (full[1] === 'group')
|
|
112
|
+
return { kind: 'group', groupId: full[2] };
|
|
113
|
+
return { kind: 'channel', channelId: full[2] };
|
|
114
|
+
}
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
/** Parse the request target: `channel` shorthand or a `target` object. */
|
|
118
|
+
function parseTarget(body) {
|
|
119
|
+
const channel = body.channel;
|
|
120
|
+
if (typeof channel === 'string') {
|
|
121
|
+
const target = parseShorthand(channel);
|
|
122
|
+
if (target === undefined) {
|
|
123
|
+
return { ok: false, error: `channel ${JSON.stringify(channel)} 无法解析(期望 c2c:<openid> / group:<openid> / channel:<id> 或完整会话 id)` };
|
|
124
|
+
}
|
|
125
|
+
return { ok: true, target };
|
|
126
|
+
}
|
|
127
|
+
const raw = body.target;
|
|
128
|
+
if (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) {
|
|
129
|
+
const t = raw;
|
|
130
|
+
if (t.kind === 'c2c' && typeof t.userId === 'string' && t.userId.length > 0)
|
|
131
|
+
return { ok: true, target: { kind: 'c2c', userId: t.userId } };
|
|
132
|
+
if (t.kind === 'group' && typeof t.groupId === 'string' && t.groupId.length > 0)
|
|
133
|
+
return { ok: true, target: { kind: 'group', groupId: t.groupId } };
|
|
134
|
+
if (t.kind === 'channel' && typeof t.channelId === 'string' && t.channelId.length > 0)
|
|
135
|
+
return { ok: true, target: { kind: 'channel', channelId: t.channelId } };
|
|
136
|
+
}
|
|
137
|
+
return { ok: false, error: '缺少有效目标:提供 channel 简写(如 "c2c:<openid>")或 target 对象({kind:"c2c",userId:...})' };
|
|
138
|
+
}
|
|
139
|
+
/** Send one JSON response. */
|
|
140
|
+
function sendJson(res, status, body) {
|
|
141
|
+
const payload = JSON.stringify(body);
|
|
142
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
|
|
143
|
+
res.end(payload);
|
|
144
|
+
}
|
|
145
|
+
/** Stable per-target id used in the channels listing. */
|
|
146
|
+
function targetId(target) {
|
|
147
|
+
return target.kind === 'c2c' ? target.userId : target.kind === 'group' ? target.groupId : target.channelId;
|
|
148
|
+
}
|
|
149
|
+
/** Model-facing text injected by `record: true`. */
|
|
150
|
+
function recordText(text) {
|
|
151
|
+
return '[HTTP 推送记录] 以下内容已通过 HTTP 推送接口直接送达本会话对应的 QQ 通道'
|
|
152
|
+
+ '(未经过你生成回复;用户询问时请基于此内容回答):\n' + text;
|
|
153
|
+
}
|
|
154
|
+
/** Build the deduped, newest-first channel listing from the route store. */
|
|
155
|
+
function listChannels(deps) {
|
|
156
|
+
const byTarget = new Map();
|
|
157
|
+
for (const { record } of deps.routes.entries()) {
|
|
158
|
+
const key = targetKey(record.target);
|
|
159
|
+
const row = {
|
|
160
|
+
kind: record.target.kind,
|
|
161
|
+
id: targetId(record.target),
|
|
162
|
+
target: record.target,
|
|
163
|
+
currentSessionId: effectiveSessionId(record.target, deps.threads.current(key), deps.botId),
|
|
164
|
+
lastActiveAt: record.lastMsgAt,
|
|
165
|
+
};
|
|
166
|
+
const existing = byTarget.get(key);
|
|
167
|
+
if (existing === undefined || (row.lastActiveAt ?? 0) >= (existing.lastActiveAt ?? 0)) {
|
|
168
|
+
byTarget.set(key, row);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return [...byTarget.values()].sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0));
|
|
172
|
+
}
|
|
173
|
+
/** `POST <prefix>/send` handler body after auth and JSON parsing. */
|
|
174
|
+
async function handleSend(deps, res, body) {
|
|
175
|
+
const parsed = parseTarget(body);
|
|
176
|
+
if (!parsed.ok) {
|
|
177
|
+
sendJson(res, 400, { ok: false, error: parsed.error });
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const target = parsed.target;
|
|
181
|
+
const text = body.text;
|
|
182
|
+
if (typeof text !== 'string' || text.trim().length === 0) {
|
|
183
|
+
sendJson(res, 400, { ok: false, error: 'text 必须是非空字符串' });
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const msgId = body.msgId;
|
|
187
|
+
if (msgId !== undefined && typeof msgId !== 'string') {
|
|
188
|
+
sendJson(res, 400, { ok: false, error: 'msgId(可选)必须是字符串:提供时各分段以该消息为被动锚点' });
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (body.record !== undefined && typeof body.record !== 'boolean') {
|
|
192
|
+
sendJson(res, 400, { ok: false, error: 'record(可选)必须是布尔值:true 时同时向当前会话注入一条不唤醒模型的记录' });
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const limit = deps.config.textChunkLimit ?? 4_000;
|
|
196
|
+
const chunks = chunkText(text, limit);
|
|
197
|
+
const messageIds = [];
|
|
198
|
+
deps.log.info('httpApi send: kind=%s id=%s chars=%d chunks=%d passive=%s', target.kind, targetId(target), text.length, chunks.length, msgId !== undefined ? 'yes' : 'no');
|
|
199
|
+
for (const chunk of chunks) {
|
|
200
|
+
try {
|
|
201
|
+
messageIds.push(await deps.api.sendText(target, chunk, msgId));
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
deps.log.error('httpApi send failed on chunk %d/%d: %o', messageIds.length + 1, chunks.length, error);
|
|
205
|
+
sendJson(res, 502, {
|
|
206
|
+
ok: false,
|
|
207
|
+
error: `QQ 发送失败(第 ${messageIds.length + 1}/${chunks.length} 段):${String(error instanceof Error ? error.message : error)}`,
|
|
208
|
+
messageIds,
|
|
209
|
+
chunksSent: messageIds.length,
|
|
210
|
+
});
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
let recorded = false;
|
|
215
|
+
let recordError;
|
|
216
|
+
if (body.record === true) {
|
|
217
|
+
try {
|
|
218
|
+
const sessionId = effectiveSessionId(target, deps.threads.current(targetKey(target)), deps.botId);
|
|
219
|
+
const agent = await deps.ensureAgent(sessionId);
|
|
220
|
+
agent.inject({
|
|
221
|
+
id: `qqpush:${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`,
|
|
222
|
+
role: 'user',
|
|
223
|
+
content: [{ type: 'text', text: recordText(text) }],
|
|
224
|
+
source: { kind: 'user', id: 'dsh-http-api', name: 'HTTP 推送 API' },
|
|
225
|
+
});
|
|
226
|
+
recorded = true;
|
|
227
|
+
deps.log.info('httpApi record: injected into %s', sessionId);
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
recordError = String(error instanceof Error ? error.message : error);
|
|
231
|
+
deps.log.warn('httpApi record failed for %s: %o', targetId(target), error);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
sendJson(res, 200, { ok: true, messageIds, chunks: chunks.length, recorded, ...(recordError !== undefined ? { recordError } : {}) });
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* `POST <prefix>/wakeup` — Pygmalion proactive interaction.
|
|
238
|
+
*
|
|
239
|
+
* Unlike `/send` (which pushes text directly), `/wakeup` does NOT send a preset
|
|
240
|
+
* message. It wakes the per-user dsh session with a situational [唤醒事件]
|
|
241
|
+
* context (reason + hint) and lets the director decide — based on the actual
|
|
242
|
+
* current state (recent memory, whether the user is mid-chat) — whether to say
|
|
243
|
+
* something, and what. The agent's reply flows out through the normal outbound
|
|
244
|
+
* pipeline; a silent decision sends nothing.
|
|
245
|
+
*/
|
|
246
|
+
async function handleWakeup(deps, res, body) {
|
|
247
|
+
const parsed = parseTarget(body);
|
|
248
|
+
if (!parsed.ok) {
|
|
249
|
+
sendJson(res, 400, { ok: false, error: parsed.error });
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const target = parsed.target;
|
|
253
|
+
const reason = body.reason;
|
|
254
|
+
if (reason !== undefined && typeof reason !== 'string') {
|
|
255
|
+
sendJson(res, 400, { ok: false, error: 'reason(可选)必须是字符串:唤醒原因' });
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
const memoryHint = body.memoryHint;
|
|
259
|
+
if (memoryHint !== undefined && typeof memoryHint !== 'string') {
|
|
260
|
+
sendJson(res, 400, { ok: false, error: 'memoryHint(可选)必须是字符串:给 dsh 的记忆提示' });
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
const force = body.force;
|
|
264
|
+
if (force !== undefined && typeof force !== 'boolean') {
|
|
265
|
+
sendJson(res, 400, { ok: false, error: 'force(可选)必须是布尔值:true 跳过撞车检测' });
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const kind = body.kind;
|
|
269
|
+
if (kind !== undefined && typeof kind !== 'string') {
|
|
270
|
+
sendJson(res, 400, { ok: false, error: 'kind(可选)必须是字符串:唤醒情境类型(如 script-hook)' });
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
const mood = body.mood;
|
|
274
|
+
if (mood !== undefined && typeof mood !== 'string') {
|
|
275
|
+
sendJson(res, 400, { ok: false, error: 'mood(可选)必须是字符串:脚本事件的心情' });
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const topic = body.topic;
|
|
279
|
+
if (topic !== undefined && typeof topic !== 'string') {
|
|
280
|
+
sendJson(res, 400, { ok: false, error: 'topic(可选)必须是字符串:脚本事件的主题' });
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
// 脚本唤醒节流:同角色 scriptWakeMinIntervalMs 内至多一次(防脚本循环轰炸)。
|
|
284
|
+
if (kind === 'script-hook' && deps.persona && deps.roleId && force !== true) {
|
|
285
|
+
try {
|
|
286
|
+
const min = deps.scriptWakeMinIntervalMs ?? 10 * 60 * 1000;
|
|
287
|
+
const role = await deps.persona.loadRole(deps.roleId);
|
|
288
|
+
if (role && Date.now() - (role.state?.lastScriptWakeAt ?? 0) < min) {
|
|
289
|
+
sendJson(res, 200, { ok: false, skipped: 'throttled', scriptWake: true });
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
} catch { /* 节流读取失败不阻塞 */ }
|
|
293
|
+
}
|
|
294
|
+
try {
|
|
295
|
+
const result = await wakeupSession({
|
|
296
|
+
threads: deps.threads,
|
|
297
|
+
routes: deps.routes,
|
|
298
|
+
ensureAgent: deps.ensureAgent,
|
|
299
|
+
persona: deps.persona,
|
|
300
|
+
botId: deps.botId,
|
|
301
|
+
roleId: deps.roleId,
|
|
302
|
+
activityAt: deps.activityAt,
|
|
303
|
+
withinChatWindowMs: deps.withinChatWindowMs,
|
|
304
|
+
log: deps.log,
|
|
305
|
+
}, { target, reason, memoryHint, force, kind, mood, topic });
|
|
306
|
+
if (result.ok === false) {
|
|
307
|
+
sendJson(res, 200, result); // collision/skip is a normal outcome, not an error
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (kind === 'script-hook' && deps.persona && deps.roleId) {
|
|
311
|
+
try {
|
|
312
|
+
const role = await deps.persona.loadRole(deps.roleId);
|
|
313
|
+
if (role) {
|
|
314
|
+
const state = { ...(role.state || {}) };
|
|
315
|
+
state.lastScriptWakeAt = Date.now();
|
|
316
|
+
await deps.persona.saveRoleField(deps.roleId, 'state', state);
|
|
317
|
+
}
|
|
318
|
+
} catch { /* 节流写入失败不阻塞 */ }
|
|
319
|
+
}
|
|
320
|
+
sendJson(res, 200, { ok: true, woken: true, sessionId: result.sessionId });
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
deps.log.error('pygmalion wakeup failed: %o', error);
|
|
324
|
+
sendJson(res, 502, { ok: false, error: `唤醒失败:${String(error instanceof Error ? error.message : error)}` });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* `POST <prefix>/archive` — Pygmalion 归档任务。
|
|
330
|
+
* 用户长时间(如 45 分钟)未发言时调用:唤醒 dsh 把当日原始记录按话题切片归档为
|
|
331
|
+
* 三层记忆(日期/话题/原文)并建立索引。归档是后台维护,不向用户发送任何消息。
|
|
332
|
+
*/
|
|
333
|
+
async function handleArchive(deps, res, body) {
|
|
334
|
+
const parsed = parseTarget(body);
|
|
335
|
+
if (!parsed.ok) { sendJson(res, 400, { ok: false, error: parsed.error }); return; }
|
|
336
|
+
const target = parsed.target;
|
|
337
|
+
const date = body.date;
|
|
338
|
+
if (date !== undefined && typeof date !== 'string') {
|
|
339
|
+
sendJson(res, 400, { ok: false, error: 'date(可选)必须是 YYYY-MM-DD' }); return;
|
|
340
|
+
}
|
|
341
|
+
try {
|
|
342
|
+
const result = await archiveWakeup({
|
|
343
|
+
threads: deps.threads,
|
|
344
|
+
ensureAgent: deps.ensureAgent,
|
|
345
|
+
persona: deps.persona,
|
|
346
|
+
botId: deps.botId,
|
|
347
|
+
roleId: deps.roleId,
|
|
348
|
+
log: deps.log,
|
|
349
|
+
}, { target, date });
|
|
350
|
+
if (result.ok === false) { sendJson(res, 200, result); return; }
|
|
351
|
+
sendJson(res, 200, { ok: true, archived: true, sessionId: result.sessionId });
|
|
352
|
+
}
|
|
353
|
+
catch (error) {
|
|
354
|
+
deps.log.error('pygmalion archive failed: %o', error);
|
|
355
|
+
sendJson(res, 502, { ok: false, error: `归档失败:${String(error instanceof Error ? error.message : error)}` });
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Build the prefix-route handler for the webServer registration.
|
|
361
|
+
* @param deps - mount facts plus the pipelines the endpoints drive.
|
|
362
|
+
* @returns async handler owning the full response lifecycle under the prefix.
|
|
363
|
+
*/
|
|
364
|
+
export function createHttpApiHandler(deps) {
|
|
365
|
+
return async (req, res) => {
|
|
366
|
+
if (!authorized(req, deps.token)) {
|
|
367
|
+
sendJson(res, 401, { ok: false, error: '未认证:缺少或错误的 Authorization: Bearer <token>' });
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
let pathname;
|
|
371
|
+
try {
|
|
372
|
+
pathname = new URL(req.url ?? '/', 'http://x').pathname;
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
sendJson(res, 400, { ok: false, error: '无法解析的请求路径' });
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const suffix = pathname === deps.mountPath ? '' : pathname.slice(deps.mountPath.length);
|
|
379
|
+
try {
|
|
380
|
+
if (suffix === '' || suffix === '/') {
|
|
381
|
+
sendJson(res, 200, {
|
|
382
|
+
ok: true,
|
|
383
|
+
endpoints: {
|
|
384
|
+
send: `POST ${deps.mountPath}/send`,
|
|
385
|
+
wakeup: `POST ${deps.mountPath}/wakeup`,
|
|
386
|
+
archive: `POST ${deps.mountPath}/archive`,
|
|
387
|
+
channels: `GET ${deps.mountPath}/channels`,
|
|
388
|
+
},
|
|
389
|
+
});
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (suffix === '/send') {
|
|
393
|
+
if (req.method !== 'POST') {
|
|
394
|
+
sendJson(res, 405, { ok: false, error: 'send 只接受 POST' });
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
const body = await readJsonBody(req);
|
|
398
|
+
await handleSend(deps, res, body);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
if (suffix === '/wakeup') {
|
|
402
|
+
if (req.method !== 'POST') {
|
|
403
|
+
sendJson(res, 405, { ok: false, error: 'wakeup 只接受 POST' });
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
const body = await readJsonBody(req);
|
|
407
|
+
await handleWakeup(deps, res, body);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
if (suffix === '/archive') {
|
|
411
|
+
if (req.method !== 'POST') {
|
|
412
|
+
sendJson(res, 405, { ok: false, error: 'archive 只接受 POST' });
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const body = await readJsonBody(req);
|
|
416
|
+
await handleArchive(deps, res, body);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
if (suffix === '/channels') {
|
|
420
|
+
if (req.method !== 'GET') {
|
|
421
|
+
sendJson(res, 405, { ok: false, error: 'channels 只接受 GET' });
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
sendJson(res, 200, { ok: true, channels: listChannels(deps) });
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
sendJson(res, 404, { ok: false, error: `未知端点 ${JSON.stringify(suffix)}` });
|
|
428
|
+
}
|
|
429
|
+
catch (error) {
|
|
430
|
+
if (error instanceof BodyError) {
|
|
431
|
+
sendJson(res, error.status, { ok: false, error: error.message });
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
deps.log.error('httpApi handler failure: %o', error);
|
|
435
|
+
if (!res.headersSent) {
|
|
436
|
+
sendJson(res, 500, { ok: false, error: `处理失败:${String(error instanceof Error ? error.message : error)}` });
|
|
437
|
+
}
|
|
438
|
+
else {
|
|
439
|
+
res.destroy();
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
//# sourceMappingURL=http-api.js.map
|