pi-hub-server 0.0.0-stage → 0.3.2
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 +403 -2
- package/bin/pi-hub.mjs +353 -0
- package/docs/AUTH.md +141 -0
- package/package.json +45 -4
- package/src/config.mjs +54 -0
- package/src/otp.mjs +162 -0
- package/src/pairing.mjs +403 -0
- package/src/pi-args.mjs +51 -0
- package/src/pi-session.mjs +635 -0
- package/src/proxy-auth.mjs +181 -0
- package/src/registry.mjs +145 -0
- package/src/rpc-once.mjs +83 -0
- package/src/server.mjs +1532 -0
- package/src/session-lock.mjs +42 -0
- package/src/sessions-index.mjs +179 -0
- package/src/static.mjs +148 -0
- package/src/totp.mjs +151 -0
- package/src/update-check.mjs +218 -0
- package/src/web-auth.mjs +450 -0
- package/systemd/pi-hub.service +22 -0
- package/web/app.js +1339 -0
- package/web/icons/icon.svg +7 -0
- package/web/index.html +121 -0
- package/web/manifest.webmanifest +20 -0
- package/web/style.css +782 -0
- package/web/sw.js +45 -0
package/src/server.mjs
ADDED
|
@@ -0,0 +1,1532 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
5
|
+
import { AUTH_DISABLED, CONFIG_DIR, HEARTBEAT_MS, HOME, HOST, IDLE_MS, PORT, SESSIONS_DIR, UPLOAD_DIR, ensureToken, readToken } from "./config.mjs";
|
|
6
|
+
import { findSession, listSessions, readHistory } from "./sessions-index.mjs";
|
|
7
|
+
import { HttpError, Registry } from "./registry.mjs";
|
|
8
|
+
import { listModels, rpcOnce } from "./rpc-once.mjs";
|
|
9
|
+
import { extensionPaths, piArgs } from "./pi-args.mjs";
|
|
10
|
+
import { peek as peekSessionLock } from "./session-lock.mjs";
|
|
11
|
+
import { PairingStore, publicDevice } from "./pairing.mjs";
|
|
12
|
+
import { mimeForFile, serveStatic } from "./static.mjs";
|
|
13
|
+
import { WebAuth, clearSessionCookie, handleWebSessionRevoke, handleWebSessionsList, isSecureRequest, sessionCookie } from "./web-auth.mjs";
|
|
14
|
+
import { createOtpStore } from "./otp.mjs";
|
|
15
|
+
import { base32Decode, verifyTotp } from "./totp.mjs";
|
|
16
|
+
import { parseTrustProxyEnv, resolveProxyIdentity } from "./proxy-auth.mjs";
|
|
17
|
+
import { HUB_VERSION, UpdateChecker } from "./update-check.mjs";
|
|
18
|
+
|
|
19
|
+
const MAX_BODY = 16 * 1024 * 1024; // prompt 里带 base64 图片
|
|
20
|
+
const MAX_UPLOAD = 32 * 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
function log(...args) {
|
|
23
|
+
console.log(new Date().toISOString(), ...args);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// API 响应一律 no-store;content-security-policy 只对 HTML/JS document 有意义,
|
|
27
|
+
// 由 src/static.mjs 的 serveStatic 下发(这里不重复加)。
|
|
28
|
+
function json(res, status, value, extraHeaders = {}) {
|
|
29
|
+
const body = JSON.stringify(value);
|
|
30
|
+
res.writeHead(status, {
|
|
31
|
+
"content-type": "application/json; charset=utf-8",
|
|
32
|
+
"content-length": Buffer.byteLength(body),
|
|
33
|
+
"cache-control": "no-store",
|
|
34
|
+
...extraHeaders,
|
|
35
|
+
});
|
|
36
|
+
res.end(body);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function bearerToken(req) {
|
|
40
|
+
const match = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? "");
|
|
41
|
+
return match ? match[1].trim() : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 登录失败延迟:只在路由层加,AUTH-1 的纯函数保持不阻塞(单测不被拖慢)。 */
|
|
45
|
+
const LOGIN_FAILURE_DELAY_MS = 250;
|
|
46
|
+
/** 一次性码兑换可选的会话 TTL(`sessionTtlMs`)允许范围。 */
|
|
47
|
+
const SESSION_TTL_MIN_MS = 60 * 1000;
|
|
48
|
+
const SESSION_TTL_MAX_MS = 90 * 24 * 60 * 60 * 1000;
|
|
49
|
+
const OTP_RATE_LIMIT = 10;
|
|
50
|
+
const OTP_RATE_WINDOW_MS = 60 * 1000;
|
|
51
|
+
const TOTP_COUNTER_TTL_MS = 60 * 1000;
|
|
52
|
+
|
|
53
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
54
|
+
|
|
55
|
+
/** 固定窗口限速:每 ip 每 windowMs 最多 limit 次;返回 true 表示本次被拒(不计数)。 */
|
|
56
|
+
function slidingWindowLimiter({ limit = OTP_RATE_LIMIT, windowMs = OTP_RATE_WINDOW_MS } = {}) {
|
|
57
|
+
const hits = new Map();
|
|
58
|
+
return (ip) => {
|
|
59
|
+
const key = ip || "unknown";
|
|
60
|
+
const now = Date.now();
|
|
61
|
+
const recent = (hits.get(key) ?? []).filter((t) => now - t < windowMs);
|
|
62
|
+
if (recent.length >= limit) {
|
|
63
|
+
hits.set(key, recent);
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
recent.push(now);
|
|
67
|
+
hits.set(key, recent);
|
|
68
|
+
return false;
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** OTP 兑换可选的会话 TTL;缺省返回 null(用 WebAuth 默认 30 天)。 */
|
|
73
|
+
function readSessionTtl(raw) {
|
|
74
|
+
if (raw === undefined || raw === null) return null;
|
|
75
|
+
const value = Number(raw);
|
|
76
|
+
if (!Number.isSafeInteger(value) || value < SESSION_TTL_MIN_MS || value > SESSION_TTL_MAX_MS) {
|
|
77
|
+
throw new HttpError(
|
|
78
|
+
400,
|
|
79
|
+
`sessionTtlMs must be an integer in ${SESSION_TTL_MIN_MS}..${SESSION_TTL_MAX_MS}`,
|
|
80
|
+
"invalid_session_ttl",
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** base32 secret → Buffer;坏值只停用 TOTP(绝不因此把用户挡在门外)。 */
|
|
87
|
+
function loadTotpSecret(raw) {
|
|
88
|
+
const text = String(raw ?? "").trim();
|
|
89
|
+
if (!text) return null;
|
|
90
|
+
try {
|
|
91
|
+
const secret = base32Decode(text);
|
|
92
|
+
if (secret.length) return secret;
|
|
93
|
+
log("PI_HUB_TOTP_SECRET 为空密钥,TOTP 已停用");
|
|
94
|
+
} catch (err) {
|
|
95
|
+
log("PI_HUB_TOTP_SECRET 不是合法 base32,TOTP 已停用:", err.message);
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 主令牌:恒时比较(长度也参与判定,行为与旧实现一致)。 */
|
|
101
|
+
function matchesPrimaryToken(given, token) {
|
|
102
|
+
if (typeof given !== "string" || !given) return false;
|
|
103
|
+
const a = Buffer.from(given);
|
|
104
|
+
const b = Buffer.from(token ?? "");
|
|
105
|
+
if (a.length !== b.length) return false;
|
|
106
|
+
return timingSafeEqual(a, b);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 鉴权优先级:主令牌(Bearer)> 设备令牌 + 完整签名 > Web 会话 cookie。
|
|
111
|
+
* - 带了 Bearer 就只按 Bearer/设备签名判(失败不回落 cookie,否则令牌错误会被静默降级)。
|
|
112
|
+
* - cookie 只承载「浏览器登录态」,因此非 GET/HEAD 必须再带 `x-pi-csrf`(与 cookie 绑定)。
|
|
113
|
+
* 设备签名覆盖 SHA256(body),所以调用前 req.rawBody 必须已就绪。
|
|
114
|
+
*/
|
|
115
|
+
function authenticate(req, token, rawBody, pairing, webAuth) {
|
|
116
|
+
if (AUTH_DISABLED) return { ok: true, primary: true, device: null, via: "disabled" };
|
|
117
|
+
const given = bearerToken(req);
|
|
118
|
+
if (given) {
|
|
119
|
+
if (matchesPrimaryToken(given, token)) return { ok: true, primary: true, device: null, via: "bearer" };
|
|
120
|
+
const verdict = pairing.verifyDeviceSignature({
|
|
121
|
+
method: req.method ?? "GET",
|
|
122
|
+
path: req.url ?? "/",
|
|
123
|
+
headers: req.headers,
|
|
124
|
+
rawBody,
|
|
125
|
+
token: given,
|
|
126
|
+
});
|
|
127
|
+
if (!verdict.ok) return { ok: false, code: verdict.code, message: verdict.message };
|
|
128
|
+
return { ok: true, primary: false, device: verdict.device, via: "device" };
|
|
129
|
+
}
|
|
130
|
+
const cookie = webAuth.cookieValue(req);
|
|
131
|
+
const web = webAuth.session(cookie);
|
|
132
|
+
if (!web.ok) return { ok: false, code: "unauthorized", message: "unauthorized" };
|
|
133
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
134
|
+
if (method !== "GET" && method !== "HEAD" && !webAuth.verifyCsrf(cookie, req.headers["x-pi-csrf"])) {
|
|
135
|
+
return { ok: false, status: 403, code: "csrf", message: "x-pi-csrf header required" };
|
|
136
|
+
}
|
|
137
|
+
return { ok: true, primary: false, device: null, via: "cookie" };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function clientIp(req) {
|
|
141
|
+
return String(req.socket?.remoteAddress ?? "unknown").replace(/^::ffff:/, "");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 配对管理路由只允许本机(CLI)访问,非 loopback 一律 403 local_only。 */
|
|
145
|
+
function isLoopback(req) {
|
|
146
|
+
const addr = clientIp(req);
|
|
147
|
+
return addr === "127.0.0.1" || addr === "::1" || addr === "localhost";
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 请求入口一次性读完整 body:设备签名要算 SHA256(body),鉴权前拿不到原文就没法验签。 */
|
|
151
|
+
async function bufferBody(req, max) {
|
|
152
|
+
const chunks = [];
|
|
153
|
+
let total = 0;
|
|
154
|
+
for await (const chunk of req) {
|
|
155
|
+
total += chunk.length;
|
|
156
|
+
if (total > max) throw new HttpError(413, "body too large");
|
|
157
|
+
chunks.push(chunk);
|
|
158
|
+
}
|
|
159
|
+
return Buffer.concat(chunks);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function readRawBody(req, max = MAX_UPLOAD) {
|
|
163
|
+
const body = req.rawBody ?? Buffer.alloc(0);
|
|
164
|
+
if (body.length > max) throw new HttpError(413, "body too large");
|
|
165
|
+
return body;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function readJsonBody(req) {
|
|
169
|
+
const raw = readRawBody(req, MAX_BODY);
|
|
170
|
+
if (!raw.length) return {};
|
|
171
|
+
try {
|
|
172
|
+
return JSON.parse(raw.toString("utf8"));
|
|
173
|
+
} catch {
|
|
174
|
+
throw new HttpError(400, "invalid JSON body");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
/** 把 RPC get_messages 的 content 数组规整成与会话文件相同的历史形状。 */
|
|
180
|
+
function normalizeMessages(messages, limit = 0) {
|
|
181
|
+
const out = [];
|
|
182
|
+
for (const m of messages ?? []) {
|
|
183
|
+
if (!m || !m.role) continue;
|
|
184
|
+
const blocks = Array.isArray(m.content) ? m.content : [{ type: "text", text: m.content ?? "" }];
|
|
185
|
+
const parts = [];
|
|
186
|
+
const toolCalls = [];
|
|
187
|
+
for (const b of blocks) {
|
|
188
|
+
if (b?.type === "text" && b.text) parts.push(b.text);
|
|
189
|
+
else if (b?.type === "toolCall") toolCalls.push({ id: b.id, name: b.name, args: b.args });
|
|
190
|
+
}
|
|
191
|
+
const ts = typeof m.timestamp === "number" ? new Date(m.timestamp).toISOString() : (m.timestamp ?? null);
|
|
192
|
+
out.push({
|
|
193
|
+
entryId: m.id ?? null,
|
|
194
|
+
role: m.role,
|
|
195
|
+
text: parts.join("\n"),
|
|
196
|
+
toolCalls,
|
|
197
|
+
ts,
|
|
198
|
+
usage: m.usage ?? null,
|
|
199
|
+
model: m.model ?? null,
|
|
200
|
+
provider: m.provider ?? null,
|
|
201
|
+
durationMs: m.durationMs ?? null,
|
|
202
|
+
stopReason: m.stopReason ?? null,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
return limit > 0 ? out.slice(-limit) : out;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
let commandsCache = { at: 0, value: null };
|
|
209
|
+
/** 可发现的斜杠命令(扩展 / prompt 模板 / skill),缓存 5 分钟。 */
|
|
210
|
+
async function listCommands() {
|
|
211
|
+
if (Date.now() - commandsCache.at < 5 * 60 * 1000 && commandsCache.value) return commandsCache.value;
|
|
212
|
+
const data = await rpcOnce("get_commands", {}, { timeoutMs: 30000 });
|
|
213
|
+
const commands = (data?.commands ?? []).map((c) => ({
|
|
214
|
+
name: c.name,
|
|
215
|
+
description: c.description ?? null,
|
|
216
|
+
source: c.source ?? null,
|
|
217
|
+
sourceInfo: c.sourceInfo ?? null,
|
|
218
|
+
}));
|
|
219
|
+
commandsCache = { at: Date.now(), value: commands };
|
|
220
|
+
return commands;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let thinkingCache = { at: 0, value: null };
|
|
224
|
+
/** 默认(未开会话)时 pi 支持的推理强度,缓存 5 分钟。 */
|
|
225
|
+
async function defaultThinking() {
|
|
226
|
+
if (Date.now() - thinkingCache.at < 5 * 60 * 1000 && thinkingCache.value) return thinkingCache.value;
|
|
227
|
+
const [state, levels] = await Promise.all([
|
|
228
|
+
rpcOnce("get_state", {}, { timeoutMs: 30000 }).catch(() => null),
|
|
229
|
+
rpcOnce("get_available_thinking_levels", {}, { timeoutMs: 30000 }).catch(() => null),
|
|
230
|
+
]);
|
|
231
|
+
const value = {
|
|
232
|
+
level: state?.thinkingLevel ?? "medium",
|
|
233
|
+
levels: levels?.levels ?? ["off", "low", "medium", "high"],
|
|
234
|
+
model: state?.model?.id ?? null,
|
|
235
|
+
};
|
|
236
|
+
thinkingCache = { at: Date.now(), value };
|
|
237
|
+
return value;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const MAX_SESSIONS_LIMIT = 1000;
|
|
241
|
+
/**
|
|
242
|
+
* 会话快照里的 `model` 是完整对象(id/name/provider/baseUrl…),
|
|
243
|
+
* 但列表接口对外约定是字符串别名(客户端直接拿它做筛选/展示)。
|
|
244
|
+
* 不转换时客户端 `JSONObject.optString("model")` 会拿到整段 JSON,
|
|
245
|
+
* 底栏模型 chip 就变成「…/127.0.0.1」(实测)。
|
|
246
|
+
*/
|
|
247
|
+
function modelAlias(model) {
|
|
248
|
+
if (!model) return null;
|
|
249
|
+
if (typeof model === "string") return model;
|
|
250
|
+
if (model.provider && model.id) return `${model.provider}/${model.id}`;
|
|
251
|
+
return model.id ?? null;
|
|
252
|
+
}
|
|
253
|
+
/** pi 的会话 id 是 UUID(大小写不论);用来把「文件名被误当 id」的 artifact 行筛掉。 */
|
|
254
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* `GET /v1/extensions` 的正文:当前进程拉 pi 时真正会加载的扩展。
|
|
258
|
+
* hub 用 `--no-extensions -e <path>` 起 pi,生效列表就是 extensionPaths() 的结果;
|
|
259
|
+
* 每个路径做一次存在性探测(缺失=加载必然失败)。extras 是除扩展之外的启动参数。
|
|
260
|
+
*/
|
|
261
|
+
function describeExtensions() {
|
|
262
|
+
const extensions = extensionPaths().map((p) => {
|
|
263
|
+
try {
|
|
264
|
+
if (!fs.statSync(p).isFile()) return { path: p, ok: false, error: "not a file" };
|
|
265
|
+
return { path: p, ok: true };
|
|
266
|
+
} catch (err) {
|
|
267
|
+
return { path: p, ok: false, error: err.code === "ENOENT" ? "not found" : err.message };
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
const args = piArgs({});
|
|
271
|
+
const extras = [];
|
|
272
|
+
for (let i = 0; i < args.length; i++) {
|
|
273
|
+
if (args[i] === "-e") {
|
|
274
|
+
i++;
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
extras.push(args[i]);
|
|
278
|
+
}
|
|
279
|
+
return {
|
|
280
|
+
extensions,
|
|
281
|
+
extras,
|
|
282
|
+
source: process.env.PI_HUB_EXTENSIONS === undefined ? "default" : "env",
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// ---------------------------------------------------------------------------
|
|
287
|
+
// GET /v1/plugins —— 主机侧 pi 资源的只读清单(契约见 PLAN §3)
|
|
288
|
+
// ---------------------------------------------------------------------------
|
|
289
|
+
|
|
290
|
+
/** 主机侧 pi 资源根:`PI_HUB_AGENT_DIR` 优先(测试隔离用),否则 `~/.pi/agent`。 */
|
|
291
|
+
const AGENT_DIR = process.env.PI_HUB_AGENT_DIR ?? path.join(HOME, ".pi", "agent");
|
|
292
|
+
/** 每段最多返回多少条;超出时 host.truncated 标出段名。 */
|
|
293
|
+
const PLUGIN_SEGMENT_MAX = 200;
|
|
294
|
+
const EXTENSION_FILE_RE = /\.(?:ts|js|mjs|cjs)$/;
|
|
295
|
+
|
|
296
|
+
function safeStat(p, { lstat = false } = {}) {
|
|
297
|
+
try {
|
|
298
|
+
return lstat ? fs.lstatSync(p) : fs.statSync(p);
|
|
299
|
+
} catch {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function safeRealpath(p) {
|
|
305
|
+
try {
|
|
306
|
+
return fs.realpathSync(p);
|
|
307
|
+
} catch {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function readJsonFile(file) {
|
|
313
|
+
try {
|
|
314
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
315
|
+
} catch {
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function pathInside(root, real) {
|
|
321
|
+
return real === root || real.startsWith(root + path.sep);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** pi 的扩展发现规则(docs/extensions.md):`*.ts/js` 文件、含 `index.*` 的目录、`pi.extensions` 非空的包。 */
|
|
325
|
+
function isExtensionEntry(abs) {
|
|
326
|
+
const stat = safeStat(abs);
|
|
327
|
+
if (!stat) return false;
|
|
328
|
+
if (stat.isFile()) return EXTENSION_FILE_RE.test(abs);
|
|
329
|
+
if (!stat.isDirectory()) return false;
|
|
330
|
+
if (["index.ts", "index.js", "index.mjs"].some((name) => safeStat(path.join(abs, name))?.isFile())) return true;
|
|
331
|
+
const pkg = readJsonFile(path.join(abs, "package.json"));
|
|
332
|
+
return Array.isArray(pkg?.pi?.extensions) && pkg.pi.extensions.length > 0;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* `agentDir/extensions/` 的一级条目。按 A4-P1-3 的两档判定:
|
|
337
|
+
* 用户在这里声明的 symlink 允许 realpath 出界(`outsideAgentDir:true` + `realPath`),
|
|
338
|
+
* 但只解析一跳、不递归、不跟随链中链;出界条目不会被当作路径泄露删掉,否则本机 7 条扩展全消失。
|
|
339
|
+
*/
|
|
340
|
+
function collectHostExtensions(root, errors) {
|
|
341
|
+
const dir = path.join(AGENT_DIR, "extensions");
|
|
342
|
+
const out = [];
|
|
343
|
+
let dirents = [];
|
|
344
|
+
try {
|
|
345
|
+
dirents = fs.readdirSync(dir, { withFileTypes: true });
|
|
346
|
+
} catch {
|
|
347
|
+
return out;
|
|
348
|
+
}
|
|
349
|
+
for (const dirent of dirents) {
|
|
350
|
+
if (dirent.name.startsWith(".")) continue;
|
|
351
|
+
const abs = path.join(dir, dirent.name);
|
|
352
|
+
if (!isExtensionEntry(abs)) continue; // 备份文件 / 无 entry 的目录不是扩展
|
|
353
|
+
const link = safeStat(abs, { lstat: true })?.isSymbolicLink() ?? false;
|
|
354
|
+
const stat = safeStat(abs);
|
|
355
|
+
let realPath = null;
|
|
356
|
+
if (link) {
|
|
357
|
+
try {
|
|
358
|
+
const target = path.resolve(dir, fs.readlinkSync(abs));
|
|
359
|
+
// 链中链:只记录第一跳,不再展开(避免跟随攻击者链条)
|
|
360
|
+
realPath = target;
|
|
361
|
+
} catch {
|
|
362
|
+
realPath = null;
|
|
363
|
+
}
|
|
364
|
+
} else {
|
|
365
|
+
realPath = safeRealpath(abs);
|
|
366
|
+
}
|
|
367
|
+
if (realPath === null && stat) errors.push({ path: abs, error: "unresolvable path" });
|
|
368
|
+
out.push({
|
|
369
|
+
path: abs,
|
|
370
|
+
name: dirent.name.replace(EXTENSION_FILE_RE, ""),
|
|
371
|
+
kind: "local",
|
|
372
|
+
exists: Boolean(stat),
|
|
373
|
+
ok: Boolean(stat),
|
|
374
|
+
mtime: stat ? stat.mtime.toISOString() : null,
|
|
375
|
+
realPath,
|
|
376
|
+
outsideAgentDir: realPath !== null && !pathInside(root, realPath),
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
return out;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** settings.json 的 `packages[]`:npm 包解析到 `agentDir/npm/node_modules`,本地路径相对 agentDir。 */
|
|
383
|
+
function resolvePackageDir(source) {
|
|
384
|
+
if (source.startsWith("npm:")) {
|
|
385
|
+
const spec = source.slice(4);
|
|
386
|
+
const at = spec.lastIndexOf("@");
|
|
387
|
+
const name = at > 0 ? spec.slice(0, at) : spec;
|
|
388
|
+
return path.join(AGENT_DIR, "npm", "node_modules", ...name.split("/"));
|
|
389
|
+
}
|
|
390
|
+
if (/^(?:git|github|https?):/.test(source)) return null; // 远程源没有本地落地路径
|
|
391
|
+
return path.resolve(AGENT_DIR, source);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* settingsPackages:声明项全保留(B1b)。`npm:`/远程源维持原逻辑,仅当 realpath 落在
|
|
396
|
+
* agentDir 内才算存在;相对路径按 settings.json 所在目录解析,出界也保留并标
|
|
397
|
+
* `path`/`realPath`/`outsideAgentDir`(与 extensions 同口径:只 realpath 一次、不递归)。
|
|
398
|
+
*/
|
|
399
|
+
function collectSettingsPackages(root, errors) {
|
|
400
|
+
const file = path.join(AGENT_DIR, "settings.json");
|
|
401
|
+
const settings = readJsonFile(file);
|
|
402
|
+
const out = [];
|
|
403
|
+
if (!settings) {
|
|
404
|
+
if (safeStat(file)) errors.push({ path: file, error: "settings.json is not valid JSON" });
|
|
405
|
+
return out;
|
|
406
|
+
}
|
|
407
|
+
const settingsDir = path.dirname(file);
|
|
408
|
+
const list = Array.isArray(settings.packages) ? settings.packages : [];
|
|
409
|
+
for (const raw of list) {
|
|
410
|
+
const source = typeof raw === "string" ? raw : raw?.source;
|
|
411
|
+
const scope = typeof raw === "object" && typeof raw?.scope === "string" ? raw.scope : "user";
|
|
412
|
+
if (typeof source !== "string" || !source) {
|
|
413
|
+
errors.push({ path: file, error: `invalid packages entry: ${JSON.stringify(raw)}` });
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
const isNpm = source.startsWith("npm:");
|
|
417
|
+
const isRemote = /^(?:git|github|https?):/.test(source);
|
|
418
|
+
if (isNpm || isRemote) {
|
|
419
|
+
const dir = resolvePackageDir(source);
|
|
420
|
+
const real = dir ? safeRealpath(dir) : null;
|
|
421
|
+
if (real && !pathInside(root, real)) continue; // npm 包仍严格限定在 agentDir 内
|
|
422
|
+
out.push({ source, scope, exists: Boolean(real) });
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
const abs = path.resolve(settingsDir, source);
|
|
426
|
+
const real = safeRealpath(abs);
|
|
427
|
+
const outsideAgentDir = real !== null && !pathInside(root, real);
|
|
428
|
+
out.push({
|
|
429
|
+
source,
|
|
430
|
+
scope,
|
|
431
|
+
exists: real !== null,
|
|
432
|
+
path: abs,
|
|
433
|
+
...(real ? { realPath: real } : {}),
|
|
434
|
+
outsideAgentDir,
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
return out;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** npmPackages:只列 pi 包(`pi` 字段或 `keywords` 含 `pi-package`),出界的 symlink 包剔除。 */
|
|
441
|
+
function collectNpmPackages(root) {
|
|
442
|
+
const base = path.join(AGENT_DIR, "npm", "node_modules");
|
|
443
|
+
const out = [];
|
|
444
|
+
let dirents = [];
|
|
445
|
+
try {
|
|
446
|
+
dirents = fs.readdirSync(base, { withFileTypes: true });
|
|
447
|
+
} catch {
|
|
448
|
+
return out;
|
|
449
|
+
}
|
|
450
|
+
const packageDirs = [];
|
|
451
|
+
for (const dirent of dirents) {
|
|
452
|
+
if (dirent.name.startsWith(".")) continue;
|
|
453
|
+
const abs = path.join(base, dirent.name);
|
|
454
|
+
if (dirent.name.startsWith("@")) {
|
|
455
|
+
let scoped = [];
|
|
456
|
+
try {
|
|
457
|
+
scoped = fs.readdirSync(abs, { withFileTypes: true });
|
|
458
|
+
} catch {
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
for (const s of scoped) packageDirs.push(path.join(abs, s.name));
|
|
462
|
+
} else {
|
|
463
|
+
packageDirs.push(abs);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
for (const dir of packageDirs) {
|
|
467
|
+
const real = safeRealpath(dir);
|
|
468
|
+
if (!real || !pathInside(root, real)) continue;
|
|
469
|
+
const pkg = readJsonFile(path.join(dir, "package.json"));
|
|
470
|
+
if (!pkg) continue;
|
|
471
|
+
const hasPiManifest = Boolean(pkg.pi) || (Array.isArray(pkg.keywords) && pkg.keywords.includes("pi-package"));
|
|
472
|
+
if (!hasPiManifest) continue;
|
|
473
|
+
out.push({ name: pkg.name ?? path.basename(dir), version: pkg.version ?? null, hasPiManifest });
|
|
474
|
+
}
|
|
475
|
+
return out;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** localPackages:`agentDir/local-packages/*`(`pi install -l`),同样限定在 agentDir 内。 */
|
|
479
|
+
function collectLocalPackages(root) {
|
|
480
|
+
const base = path.join(AGENT_DIR, "local-packages");
|
|
481
|
+
const out = [];
|
|
482
|
+
let dirents = [];
|
|
483
|
+
try {
|
|
484
|
+
dirents = fs.readdirSync(base, { withFileTypes: true });
|
|
485
|
+
} catch {
|
|
486
|
+
return out;
|
|
487
|
+
}
|
|
488
|
+
for (const dirent of dirents) {
|
|
489
|
+
if (dirent.name.startsWith(".")) continue;
|
|
490
|
+
const abs = path.join(base, dirent.name);
|
|
491
|
+
const real = safeRealpath(abs);
|
|
492
|
+
if (!real || !pathInside(root, real)) continue;
|
|
493
|
+
const pkg = readJsonFile(path.join(abs, "package.json"));
|
|
494
|
+
out.push({ path: abs, name: pkg?.name ?? dirent.name });
|
|
495
|
+
}
|
|
496
|
+
return out;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function countFiles(dir, predicate) {
|
|
500
|
+
let total = 0;
|
|
501
|
+
const walk = (current, depth) => {
|
|
502
|
+
if (depth > 8) return;
|
|
503
|
+
let entries = [];
|
|
504
|
+
try {
|
|
505
|
+
entries = fs.readdirSync(current, { withFileTypes: true });
|
|
506
|
+
} catch {
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
for (const entry of entries) {
|
|
510
|
+
if (entry.name.startsWith(".")) continue;
|
|
511
|
+
const abs = path.join(current, entry.name);
|
|
512
|
+
if (entry.isDirectory()) walk(abs, depth + 1);
|
|
513
|
+
else if (entry.isFile() && predicate(abs, entry.name)) total++;
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
walk(dir, 0);
|
|
517
|
+
return total;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function countEntries(dir) {
|
|
521
|
+
try {
|
|
522
|
+
return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && e.isFile()).length;
|
|
523
|
+
} catch {
|
|
524
|
+
return 0;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** `GET /v1/plugins` 正文:主机已安装资源(只读)+ hub 已加载扩展 + 客户端接入点。 */
|
|
529
|
+
function describePlugins() {
|
|
530
|
+
const root = safeRealpath(AGENT_DIR) ?? path.resolve(AGENT_DIR);
|
|
531
|
+
const errors = [];
|
|
532
|
+
const trim = (list) => {
|
|
533
|
+
if (list.length <= PLUGIN_SEGMENT_MAX) return { list, truncated: false };
|
|
534
|
+
return { list: list.slice(0, PLUGIN_SEGMENT_MAX), truncated: true };
|
|
535
|
+
};
|
|
536
|
+
const settings = trim(collectSettingsPackages(root, errors));
|
|
537
|
+
const extensions = trim(collectHostExtensions(root, errors));
|
|
538
|
+
const npm = trim(collectNpmPackages(root));
|
|
539
|
+
const local = trim(collectLocalPackages(root));
|
|
540
|
+
const truncated = {};
|
|
541
|
+
for (const [name, segment] of [
|
|
542
|
+
["settingsPackages", settings],
|
|
543
|
+
["extensions", extensions],
|
|
544
|
+
["npmPackages", npm],
|
|
545
|
+
["localPackages", local],
|
|
546
|
+
]) {
|
|
547
|
+
if (segment.truncated) truncated[name] = true;
|
|
548
|
+
}
|
|
549
|
+
const mcp = readJsonFile(path.join(AGENT_DIR, "mcp.json"));
|
|
550
|
+
const describe = describeExtensions();
|
|
551
|
+
return {
|
|
552
|
+
host: {
|
|
553
|
+
agentDir: AGENT_DIR,
|
|
554
|
+
settingsPackages: settings.list,
|
|
555
|
+
extensions: extensions.list,
|
|
556
|
+
npmPackages: npm.list,
|
|
557
|
+
localPackages: local.list,
|
|
558
|
+
counts: {
|
|
559
|
+
skills: countFiles(path.join(AGENT_DIR, "skills"), (_abs, name) => name === "SKILL.md"),
|
|
560
|
+
prompts: countEntries(path.join(AGENT_DIR, "prompts")),
|
|
561
|
+
themes: countEntries(path.join(AGENT_DIR, "themes")),
|
|
562
|
+
mcpServers: Object.keys(mcp?.mcpServers ?? {}).length,
|
|
563
|
+
},
|
|
564
|
+
errors,
|
|
565
|
+
...(Object.keys(truncated).length ? { truncated } : {}),
|
|
566
|
+
},
|
|
567
|
+
hub: { loaded: describe.extensions, extras: describe.extras, source: describe.source },
|
|
568
|
+
clientIntegrationPoints: [
|
|
569
|
+
{ id: "slash-commands", name: "斜杠命令", source: "/v1/commands", writable: false },
|
|
570
|
+
{ id: "ui-request", name: "扩展 UI 对话框", source: "/v1/sessions/:id/ui/:uiId", writable: false },
|
|
571
|
+
{ id: "extensions", name: "hub 扩展加载", source: "PI_HUB_EXTENSIONS", writable: false },
|
|
572
|
+
],
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** 非 live 会话的状态快照:形状与 live `snapshot()` 一致的最小集,全部来自会话文件/索引。 */
|
|
577
|
+
function fileSessionSnapshot(entry) {
|
|
578
|
+
return {
|
|
579
|
+
id: entry.id,
|
|
580
|
+
cwd: entry.cwd,
|
|
581
|
+
name: entry.name,
|
|
582
|
+
model: entry.model,
|
|
583
|
+
status: "idle",
|
|
584
|
+
ready: false,
|
|
585
|
+
isStreaming: false,
|
|
586
|
+
isCompacting: false,
|
|
587
|
+
sessionFile: entry.file,
|
|
588
|
+
pid: null,
|
|
589
|
+
startedAt: entry.createdAt,
|
|
590
|
+
lastActivity: entry.updatedAt,
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** 从会话文件的消息聚合出 `get_session_stats` 的同一字段集;`contextUsage` 需要模型上下文窗口,非 live 时给 null。 */
|
|
595
|
+
function fileSessionStats(entry) {
|
|
596
|
+
const messages = readHistory(entry.file);
|
|
597
|
+
const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
|
|
598
|
+
let cost = 0;
|
|
599
|
+
let userMessages = 0;
|
|
600
|
+
let assistantMessages = 0;
|
|
601
|
+
let toolCalls = 0;
|
|
602
|
+
let toolResults = 0;
|
|
603
|
+
for (const m of messages) {
|
|
604
|
+
if (m.role === "user") userMessages++;
|
|
605
|
+
else if (m.role === "assistant") assistantMessages++;
|
|
606
|
+
else if (m.role === "toolResult") toolResults++;
|
|
607
|
+
toolCalls += m.toolCalls?.length ?? 0;
|
|
608
|
+
if (m.role !== "assistant" || !m.usage) continue;
|
|
609
|
+
const u = m.usage;
|
|
610
|
+
tokens.input += u.input ?? 0;
|
|
611
|
+
tokens.output += u.output ?? 0;
|
|
612
|
+
tokens.cacheRead += u.cacheRead ?? 0;
|
|
613
|
+
tokens.cacheWrite += u.cacheWrite ?? 0;
|
|
614
|
+
tokens.total += u.totalTokens ?? (u.input ?? 0) + (u.output ?? 0);
|
|
615
|
+
cost += u.cost?.total ?? 0;
|
|
616
|
+
}
|
|
617
|
+
return {
|
|
618
|
+
userMessages,
|
|
619
|
+
assistantMessages,
|
|
620
|
+
toolCalls,
|
|
621
|
+
toolResults,
|
|
622
|
+
totalMessages: messages.length,
|
|
623
|
+
tokens,
|
|
624
|
+
cost,
|
|
625
|
+
contextUsage: null,
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** `prompt`/`follow-up` 共用的 streamingBehavior 白名单:pi 只认这两个值。 */
|
|
630
|
+
function readStreamingBehavior(body) {
|
|
631
|
+
if (body.streamingBehavior === undefined) return undefined;
|
|
632
|
+
if (body.streamingBehavior !== "steer" && body.streamingBehavior !== "followUp") {
|
|
633
|
+
throw new HttpError(400, 'streamingBehavior must be "steer" or "followUp"', "invalid_streaming_behavior");
|
|
634
|
+
}
|
|
635
|
+
return body.streamingBehavior;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* 会话库 + 存活状态合并。
|
|
640
|
+
* `limit` 省略时保持旧行为(磁盘侧 200 条 + 未落盘的 live 行,不做合并截断);
|
|
641
|
+
* `before` 是 `updatedAt` ISO 游标,只保留严格早于它的条目。
|
|
642
|
+
*/
|
|
643
|
+
function mergedSessions(registry, { limit, before } = {}) {
|
|
644
|
+
const cap = limit === undefined ? 200 : Math.min(limit, MAX_SESSIONS_LIMIT);
|
|
645
|
+
const cutoff = before ? Date.parse(before) : null;
|
|
646
|
+
if (before && !Number.isFinite(cutoff)) throw new HttpError(400, "before must be an ISO timestamp", "invalid_before");
|
|
647
|
+
const live = new Map(registry.list().map((s) => [s.id, s]));
|
|
648
|
+
const diskRows = listSessions({ limit: cutoff === null ? cap : MAX_SESSIONS_LIMIT });
|
|
649
|
+
const rows = diskRows.map((entry) => {
|
|
650
|
+
const session = live.get(entry.id);
|
|
651
|
+
return {
|
|
652
|
+
id: entry.id,
|
|
653
|
+
name: session?.name ?? entry.name,
|
|
654
|
+
preview: entry.preview,
|
|
655
|
+
cwd: entry.cwd,
|
|
656
|
+
model: modelAlias(session?.model ?? entry.model),
|
|
657
|
+
updatedAt: entry.updatedAt,
|
|
658
|
+
createdAt: entry.createdAt,
|
|
659
|
+
live: Boolean(session),
|
|
660
|
+
status: session?.status ?? null,
|
|
661
|
+
};
|
|
662
|
+
});
|
|
663
|
+
for (const [id, session] of live) {
|
|
664
|
+
if (rows.some((r) => r.id === id)) continue;
|
|
665
|
+
// registry.list() 返回的已经是快照,不要再调 .snapshot()
|
|
666
|
+
rows.unshift({ id, name: session.name, preview: null, cwd: session.cwd, model: modelAlias(session.model), updatedAt: session.lastActivity, createdAt: session.startedAt, live: true, status: session.status });
|
|
667
|
+
}
|
|
668
|
+
// 游标对所有行生效(包括未落盘的 live 行),保证「严格小于 updatedAt」
|
|
669
|
+
const kept = cutoff === null ? rows : rows.filter((r) => Date.parse(r.updatedAt) < cutoff);
|
|
670
|
+
// 去重:同一个会话文件可能在多个项目目录里各有一份(扫出来 id 相同);
|
|
671
|
+
// 子代理 artifact(*_worker_transcript.jsonl)会被文件名解析成 id "transcript" 这种非会话行。
|
|
672
|
+
// 不去重的话客户端 LazyColumn 直接崩(Key was already used),且 findSession 会拿到错的会话。
|
|
673
|
+
const seen = new Map();
|
|
674
|
+
const unique = [];
|
|
675
|
+
for (const r of kept) {
|
|
676
|
+
if (!UUID_RE.test(r.id) && !r.cwd && !r.createdAt && !r.name && !r.preview) continue;
|
|
677
|
+
const prev = seen.get(r.id);
|
|
678
|
+
if (!prev) {
|
|
679
|
+
seen.set(r.id, r);
|
|
680
|
+
unique.push(r);
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
// 同一 id 多行:字段级合并(空值被非空覆盖),排序位保留先到(更新)那行。
|
|
684
|
+
// 真例:同一会话文件在两个项目目录各一份,其中一份是空文件——只丢掉它会让会话变成幽灵行。
|
|
685
|
+
for (const k of ["name", "preview", "cwd", "model", "createdAt"]) if (!prev[k] && r[k]) prev[k] = r[k];
|
|
686
|
+
}
|
|
687
|
+
// 无论是否带 before,都按 cap 截断:否则 `?before=...` 会绕过默认 200(实测曾回 1001 行)
|
|
688
|
+
return unique.slice(0, cap);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
async function resolveTarget(registry, sessionId) {
|
|
692
|
+
const live = registry.get(sessionId);
|
|
693
|
+
if (live) return { live, entry: findSession(sessionId) };
|
|
694
|
+
const entry = findSession(sessionId);
|
|
695
|
+
if (!entry) throw new HttpError(404, `unknown session ${sessionId}`, "unknown_session");
|
|
696
|
+
return { live: null, entry };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
async function requireLive(registry, sessionId) {
|
|
700
|
+
const live = registry.get(sessionId);
|
|
701
|
+
if (live) return live;
|
|
702
|
+
const { entry } = await resolveTarget(registry, sessionId);
|
|
703
|
+
return registry.open({ id: entry.id, cwd: entry.cwd, name: entry.name, model: null, sessionFile: entry.file });
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function sse(req, res, session, since) {
|
|
707
|
+
res.writeHead(200, {
|
|
708
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
709
|
+
"cache-control": "no-cache, no-transform",
|
|
710
|
+
connection: "keep-alive",
|
|
711
|
+
"x-accel-buffering": "no",
|
|
712
|
+
});
|
|
713
|
+
const write = (ev) => res.write(`id: ${ev.seq}\ndata: ${JSON.stringify(ev)}\n\n`);
|
|
714
|
+
const unsubscribe = session.subscribe(write, since);
|
|
715
|
+
// 回放结束的边界:客户端首次订阅时用它区分「历史回放」与「新事件」。
|
|
716
|
+
res.write(": live\n\n");
|
|
717
|
+
// 重连补状态:仍在校的工具(无 `id:` 行、不占 seq,避免污染 since 回放)
|
|
718
|
+
for (const ev of session.activeToolEvents?.() ?? []) res.write(`data: ${JSON.stringify(ev)}\n\n`);
|
|
719
|
+
const heartbeat = setInterval(() => {
|
|
720
|
+
// 注释帧给老客户端保活;data 帧给 EventSource 类客户端做静默判死(注释对它是不可见的)
|
|
721
|
+
res.write(": ping\n\n");
|
|
722
|
+
res.write(`data: ${JSON.stringify({ type: "heartbeat", ts: Date.now() })}\n\n`);
|
|
723
|
+
}, HEARTBEAT_MS);
|
|
724
|
+
const cleanup = () => {
|
|
725
|
+
clearInterval(heartbeat);
|
|
726
|
+
unsubscribe();
|
|
727
|
+
};
|
|
728
|
+
req.on("close", cleanup);
|
|
729
|
+
res.on("close", cleanup);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
export function createHubServer({ fetchJson } = {}) {
|
|
733
|
+
const registry = new Registry({ log });
|
|
734
|
+
const token = AUTH_DISABLED ? null : (readToken() ?? ensureToken());
|
|
735
|
+
const pairing = new PairingStore({ configDir: CONFIG_DIR, log });
|
|
736
|
+
// Web 会话只在内存:hub 重启 = 所有浏览器重新登录(不落盘就没有 session 文件泄漏面)
|
|
737
|
+
const webAuth = new WebAuth({ token, log });
|
|
738
|
+
// 一次性登录码(M4):只在内存,单次消费、2 min TTL(otp.mjs 的 OTP_TTL_MS)
|
|
739
|
+
const otpStore = createOtpStore();
|
|
740
|
+
const otpCreateLimited = slidingWindowLimiter();
|
|
741
|
+
const otpRedeemLimited = slidingWindowLimiter();
|
|
742
|
+
// 反代可信身份(M6)与 TOTP(M5)在进程启动时各读一次 env:
|
|
743
|
+
// PI_HUB_TRUST_PROXY / PI_HUB_PROXY_SECRET / PI_HUB_PROXY_CIDRS / PI_HUB_PROXY_USER_HEADER、PI_HUB_TOTP_SECRET
|
|
744
|
+
const proxyTrust = parseTrustProxyEnv(process.env);
|
|
745
|
+
const totpSecret = loadTotpSecret(process.env.PI_HUB_TOTP_SECRET);
|
|
746
|
+
/** TOTP 已用步号(防同窗口重放):步号 → 命中时间,60 s 清理。 */
|
|
747
|
+
const totpCounters = new Map();
|
|
748
|
+
const checkTotp = (code) => {
|
|
749
|
+
if (!totpSecret) return true;
|
|
750
|
+
const now = Date.now();
|
|
751
|
+
for (const [counter, at] of totpCounters) if (now - at > TOTP_COUNTER_TTL_MS) totpCounters.delete(counter);
|
|
752
|
+
return verifyTotp(totpSecret, code, {
|
|
753
|
+
usedCounters: {
|
|
754
|
+
has: (counter) => totpCounters.has(counter),
|
|
755
|
+
add: (counter) => totpCounters.set(counter, now),
|
|
756
|
+
},
|
|
757
|
+
});
|
|
758
|
+
};
|
|
759
|
+
/**
|
|
760
|
+
* 建网页会话 + 下发 cookie。`ttlMs` 只用于一次性码兑换(`sessionTtlMs`):
|
|
761
|
+
* web-auth.mjs 的 createSession 没有 per-call TTL,这里建完再改台账条目的 expiresAt,
|
|
762
|
+
* 保证 cookie Max-Age 与台账一致(模块本身不改,归 AUTH-1)。
|
|
763
|
+
*/
|
|
764
|
+
function issueWebSession(req, res, { ip = null, ttlMs = null, reason = "web" } = {}) {
|
|
765
|
+
const issued = webAuth.createSession({ ip, ua: req.headers["user-agent"] ?? null });
|
|
766
|
+
let expiresAt = issued.expiresAt;
|
|
767
|
+
if (ttlMs !== null) {
|
|
768
|
+
expiresAt = Date.now() + ttlMs;
|
|
769
|
+
const entry = webAuth.sessions.get(createHash("sha256").update(issued.session).digest("hex"));
|
|
770
|
+
if (entry) entry.expiresAt = expiresAt;
|
|
771
|
+
}
|
|
772
|
+
log("web session issued", reason, ip ?? "unknown", ttlMs === null ? "default-ttl" : `${ttlMs}ms`);
|
|
773
|
+
return json(
|
|
774
|
+
res,
|
|
775
|
+
200,
|
|
776
|
+
{ ok: true, expiresAt: new Date(expiresAt).toISOString() },
|
|
777
|
+
{
|
|
778
|
+
"set-cookie": sessionCookie(issued.session, {
|
|
779
|
+
secure: isSecureRequest(req),
|
|
780
|
+
maxAgeSeconds: ttlMs === null ? webAuth.ttlSeconds : Math.floor(ttlMs / 1000),
|
|
781
|
+
}),
|
|
782
|
+
},
|
|
783
|
+
);
|
|
784
|
+
}
|
|
785
|
+
const updates = new UpdateChecker(fetchJson ? { fetchJson } : {});
|
|
786
|
+
const reaper = setInterval(() => registry.reap(IDLE_MS), 60000);
|
|
787
|
+
reaper.unref();
|
|
788
|
+
|
|
789
|
+
const server = http.createServer(async (req, res) => {
|
|
790
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
791
|
+
const parts = url.pathname.split("/").filter(Boolean);
|
|
792
|
+
const method = req.method ?? "GET";
|
|
793
|
+
try {
|
|
794
|
+
// 静态资源必须先于鉴权:登录页本身不能要求 cookie(否则浏览器永远进不来)。
|
|
795
|
+
// 路由白名单在 src/static.mjs,未命中返回 false 继续走 /v1。
|
|
796
|
+
if (serveStatic(req, res, url)) return;
|
|
797
|
+
|
|
798
|
+
// 入口一次性 buffer:设备签名覆盖 SHA256(body)。上限按路由定:上传 32 MB,其余 JSON 16 MB。
|
|
799
|
+
req.rawBody =
|
|
800
|
+
method === "GET" || method === "HEAD"
|
|
801
|
+
? Buffer.alloc(0)
|
|
802
|
+
: await bufferBody(req, url.pathname === "/v1/upload" ? MAX_UPLOAD : MAX_BODY);
|
|
803
|
+
|
|
804
|
+
// 反向代理可信身份(M6):命中就等价主令牌,未启用或头不匹配时完全不影响后面的鉴权链。
|
|
805
|
+
const proxyIdentity = resolveProxyIdentity(req.headers, clientIp(req), proxyTrust);
|
|
806
|
+
if (proxyIdentity.ok) req.auth = { kind: "proxy", user: proxyIdentity.user };
|
|
807
|
+
|
|
808
|
+
// ---------- 同源 Web 会话(cookie 注入鉴权,PLAN C5) ----------
|
|
809
|
+
// POST /v1/web/login {token, totp?}:主令牌换 session cookie(每 IP 10 次/分;失败延迟 250 ms)
|
|
810
|
+
if (method === "POST" && url.pathname === "/v1/web/login") {
|
|
811
|
+
const ip = clientIp(req);
|
|
812
|
+
if (webAuth.rateLimited(ip)) {
|
|
813
|
+
throw new HttpError(429, "too many login attempts", "rate_limited");
|
|
814
|
+
}
|
|
815
|
+
const body = readJsonBody(req);
|
|
816
|
+
const presented = typeof body.token === "string" ? body.token : "";
|
|
817
|
+
const tokenOk = AUTH_DISABLED || matchesPrimaryToken(presented, token);
|
|
818
|
+
const totpOk = tokenOk ? checkTotp(body.totp) : true;
|
|
819
|
+
if (!tokenOk || !totpOk) {
|
|
820
|
+
webAuth.limiter.fail(ip);
|
|
821
|
+
log(tokenOk ? "web login rejected (totp)" : "web login rejected", ip);
|
|
822
|
+
await sleep(LOGIN_FAILURE_DELAY_MS);
|
|
823
|
+
if (!tokenOk) throw new HttpError(401, "invalid token", "invalid_token");
|
|
824
|
+
throw new HttpError(401, "invalid TOTP code", "bad_totp");
|
|
825
|
+
}
|
|
826
|
+
const verdict = webAuth.login({ token: presented, ip, ua: req.headers["user-agent"] ?? null });
|
|
827
|
+
if (verdict.disabled) return json(res, 200, { ok: true, authDisabled: true, expiresAt: null });
|
|
828
|
+
webAuth.limiter.succeed(ip);
|
|
829
|
+
log("web login", ip);
|
|
830
|
+
return json(
|
|
831
|
+
res,
|
|
832
|
+
200,
|
|
833
|
+
{ ok: true, expiresAt: new Date(verdict.expiresAt).toISOString() },
|
|
834
|
+
{ "set-cookie": sessionCookie(verdict.session, { secure: isSecureRequest(req), maxAgeSeconds: webAuth.ttlSeconds }) },
|
|
835
|
+
);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// GET /v1/web/session:SPA 启动时问「我现在算不算登录」;无 cookie 时 Bearer 也算登录
|
|
839
|
+
if (method === "GET" && url.pathname === "/v1/web/session") {
|
|
840
|
+
const web = webAuth.session(webAuth.cookieValue(req));
|
|
841
|
+
if (web.ok) return json(res, 200, { ok: true, expiresAt: new Date(web.expiresAt).toISOString() });
|
|
842
|
+
if (webAuth.authDisabled) return json(res, 200, { ok: true, expiresAt: null, authDisabled: true });
|
|
843
|
+
if (token && matchesPrimaryToken(bearerToken(req), token)) return json(res, 200, { ok: true, expiresAt: null });
|
|
844
|
+
return json(res, 200, { ok: false, expiresAt: null });
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
// POST /v1/web/logout:删会话 + 让 cookie 立即过期(cookie 鉴权下仍需 CSRF)
|
|
848
|
+
if (method === "POST" && url.pathname === "/v1/web/logout") {
|
|
849
|
+
const cookie = webAuth.cookieValue(req);
|
|
850
|
+
const web = webAuth.session(cookie);
|
|
851
|
+
if (web.ok && !webAuth.verifyCsrf(cookie, req.headers["x-pi-csrf"])) {
|
|
852
|
+
throw new HttpError(403, "x-pi-csrf header required", "csrf");
|
|
853
|
+
}
|
|
854
|
+
webAuth.logout(cookie);
|
|
855
|
+
return json(res, 200, { ok: true }, { "set-cookie": clearSessionCookie({ secure: isSecureRequest(req) }) });
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// GET /v1/web/csrf:下发与 cookie 绑定的 CSRF token(double-submit)
|
|
859
|
+
if (method === "GET" && url.pathname === "/v1/web/csrf") {
|
|
860
|
+
const web = webAuth.session(webAuth.cookieValue(req));
|
|
861
|
+
if (!web.ok) {
|
|
862
|
+
if (webAuth.authDisabled) return json(res, 200, { csrf: null, authDisabled: true });
|
|
863
|
+
throw new HttpError(401, "unauthorized", "unauthorized");
|
|
864
|
+
}
|
|
865
|
+
return json(res, 200, { csrf: web.csrf, expiresAt: new Date(web.expiresAt).toISOString() });
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// POST /v1/web/otp/redeem {code, totp?, sessionTtlMs?}:无鉴权但限速(每 IP 10 次/分)
|
|
869
|
+
if (method === "POST" && url.pathname === "/v1/web/otp/redeem") {
|
|
870
|
+
const ip = clientIp(req);
|
|
871
|
+
if (otpRedeemLimited(ip)) throw new HttpError(429, "too many otp redeem attempts", "rate_limited");
|
|
872
|
+
const body = readJsonBody(req);
|
|
873
|
+
// TOTP 先于兑换:错码不能把一次性码消耗掉
|
|
874
|
+
if (!checkTotp(body.totp)) {
|
|
875
|
+
log("web otp redeem rejected (totp)", ip);
|
|
876
|
+
throw new HttpError(401, "invalid TOTP code", "bad_totp");
|
|
877
|
+
}
|
|
878
|
+
const ttlMs = readSessionTtl(body.sessionTtlMs);
|
|
879
|
+
const verdict = otpStore.redeem(typeof body.code === "string" ? body.code : "");
|
|
880
|
+
if (!verdict.ok) {
|
|
881
|
+
const [status, message, code] = {
|
|
882
|
+
unknown: [400, "invalid or unknown code", "invalid_code"],
|
|
883
|
+
meta_mismatch: [400, "invalid or unknown code", "invalid_code"],
|
|
884
|
+
expired: [410, "code expired", "code_expired"],
|
|
885
|
+
used: [410, "code already used", "code_used"],
|
|
886
|
+
too_many: [429, "too many failed attempts", "too_many_attempts"],
|
|
887
|
+
}[verdict.reason] ?? [400, "invalid or unknown code", "invalid_code"];
|
|
888
|
+
log("web otp redeem failed", ip, verdict.reason);
|
|
889
|
+
throw new HttpError(status, message, code);
|
|
890
|
+
}
|
|
891
|
+
return issueWebSession(req, res, { ip, ttlMs, reason: "otp" });
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// GET /v1/web/sessions:网页会话列表(cookie 会话,或主令牌 / 可信代理身份)
|
|
895
|
+
if (method === "GET" && url.pathname === "/v1/web/sessions") {
|
|
896
|
+
const out = handleWebSessionsList(req, {
|
|
897
|
+
webAuth,
|
|
898
|
+
ip: clientIp(req),
|
|
899
|
+
secure: isSecureRequest(req),
|
|
900
|
+
primary: proxyIdentity.ok || (!AUTH_DISABLED && matchesPrimaryToken(bearerToken(req), token)),
|
|
901
|
+
});
|
|
902
|
+
return json(res, out.status, out.body, out.headers);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// DELETE /v1/web/sessions/:id:吊销一条(cookie 会话需 x-pi-csrf;未知 id → 404)
|
|
906
|
+
if (method === "DELETE" && parts[0] === "v1" && parts[1] === "web" && parts[2] === "sessions" && parts[3]) {
|
|
907
|
+
const out = handleWebSessionRevoke(req, {
|
|
908
|
+
webAuth,
|
|
909
|
+
ip: clientIp(req),
|
|
910
|
+
secure: isSecureRequest(req),
|
|
911
|
+
params: { id: decodeURIComponent(parts[3]) },
|
|
912
|
+
primary: proxyIdentity.ok || (!AUTH_DISABLED && matchesPrimaryToken(bearerToken(req), token)),
|
|
913
|
+
});
|
|
914
|
+
return json(res, out.status, out.body, out.headers);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// POST /v1/pair/request (无鉴权;TTL 5 min;每 IP 10 次/分)
|
|
918
|
+
if (method === "POST" && url.pathname === "/v1/pair/request") {
|
|
919
|
+
if (pairing.rateLimited(clientIp(req))) {
|
|
920
|
+
throw new HttpError(429, "too many pairing requests", "rate_limited");
|
|
921
|
+
}
|
|
922
|
+
const body = readJsonBody(req);
|
|
923
|
+
return json(res, 201, pairing.createRequest({ name: body.name, platform: body.platform, publicKey: body.publicKey }));
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
// GET /v1/pair/status?pairId= (无鉴权;token 只交付一次)
|
|
927
|
+
if (method === "GET" && url.pathname === "/v1/pair/status") {
|
|
928
|
+
const pairId = url.searchParams.get("pairId");
|
|
929
|
+
if (!pairId) throw new HttpError(400, "pairId is required", "invalid_pair_id");
|
|
930
|
+
return json(res, 200, pairing.status(pairId));
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
const auth = proxyIdentity.ok
|
|
934
|
+
? { ok: true, primary: true, device: null, via: "proxy", user: proxyIdentity.user }
|
|
935
|
+
: authenticate(req, token, req.rawBody, pairing, webAuth);
|
|
936
|
+
if (!auth.ok) throw new HttpError(auth.status ?? 401, auth.message, auth.code);
|
|
937
|
+
|
|
938
|
+
// 本地管理路由(仅 loopback + 主令牌,给 CLI 用;pending 只在 hub 内存)
|
|
939
|
+
if (url.pathname === "/v1/pair/pending" || url.pathname === "/v1/pair/approve" || url.pathname === "/v1/pair/deny") {
|
|
940
|
+
if (!isLoopback(req)) throw new HttpError(403, "pairing admin routes are loopback-only", "local_only");
|
|
941
|
+
if (!auth.primary) throw new HttpError(403, "primary token required", "primary_token_required");
|
|
942
|
+
if (method === "GET" && url.pathname === "/v1/pair/pending") {
|
|
943
|
+
return json(res, 200, { pending: pairing.listPending() });
|
|
944
|
+
}
|
|
945
|
+
if (method === "POST" && url.pathname === "/v1/pair/approve") {
|
|
946
|
+
const body = readJsonBody(req);
|
|
947
|
+
const code = typeof body.code === "string" ? body.code.trim() : "";
|
|
948
|
+
if (!code) throw new HttpError(400, "code is required", "invalid_code");
|
|
949
|
+
const { device, token: deviceToken } = pairing.approveCode(code);
|
|
950
|
+
log("pair approve", device.id, device.name);
|
|
951
|
+
return json(res, 200, { ...publicDevice(device), deviceId: device.id, token: deviceToken });
|
|
952
|
+
}
|
|
953
|
+
if (method === "POST" && url.pathname === "/v1/pair/deny") {
|
|
954
|
+
const body = readJsonBody(req);
|
|
955
|
+
const code = typeof body.code === "string" ? body.code.trim() : "";
|
|
956
|
+
if (!code) throw new HttpError(400, "code is required", "invalid_code");
|
|
957
|
+
pairing.denyCode(code);
|
|
958
|
+
log("pair deny", code);
|
|
959
|
+
return json(res, 200, { ok: true });
|
|
960
|
+
}
|
|
961
|
+
throw new HttpError(404, `no route: ${method} ${url.pathname}`, "no_route");
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
// POST /v1/web/otp:生成一次性登录码(仅 loopback + 主令牌,同 /v1/pair/pending 口径;每 IP 10 次/分)
|
|
965
|
+
if (method === "POST" && url.pathname === "/v1/web/otp") {
|
|
966
|
+
if (!isLoopback(req)) throw new HttpError(403, "otp generation is loopback-only", "local_only");
|
|
967
|
+
if (!auth.primary) throw new HttpError(403, "primary token required", "primary_token_required");
|
|
968
|
+
if (otpCreateLimited(clientIp(req))) throw new HttpError(429, "too many otp requests", "rate_limited");
|
|
969
|
+
const created = otpStore.create();
|
|
970
|
+
log("web otp created", clientIp(req));
|
|
971
|
+
return json(res, 201, { code: created.code, expiresAt: new Date(created.expiresAt).toISOString() });
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// GET /v1/devices (仅主令牌)
|
|
975
|
+
if (method === "GET" && url.pathname === "/v1/devices") {
|
|
976
|
+
if (!auth.primary) throw new HttpError(403, "primary token required", "primary_token_required");
|
|
977
|
+
return json(res, 200, { devices: pairing.listDevices() });
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// DELETE /v1/devices/:id (仅主令牌;已吊销再调是幂等的)
|
|
981
|
+
if (method === "DELETE" && parts[0] === "v1" && parts[1] === "devices" && parts[2]) {
|
|
982
|
+
if (!auth.primary) throw new HttpError(403, "primary token required", "primary_token_required");
|
|
983
|
+
const device = pairing.revokeDevice(decodeURIComponent(parts[2]));
|
|
984
|
+
log("device revoke", device.id, device.name);
|
|
985
|
+
return json(res, 200, { ok: true, device });
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// 设备请求成功:刷新 lastSeenAt(节流 ≥60 s;吊销检查已在验签里每次都做)
|
|
989
|
+
if (auth.device) pairing.touchDevice(auth.device.id);
|
|
990
|
+
|
|
991
|
+
// GET /v1/health
|
|
992
|
+
if (method === "GET" && url.pathname === "/v1/health") {
|
|
993
|
+
return json(res, 200, { ok: true, version: HUB_VERSION, liveSessions: registry.list().length, idleMs: IDLE_MS });
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
// GET /v1/update[?android=<当前客户端版本>] 最新版本(缓存 1 h;上游失败也回 200 + error)
|
|
997
|
+
if (method === "GET" && url.pathname === "/v1/update") {
|
|
998
|
+
const androidCurrent = url.searchParams.get("android") || null;
|
|
999
|
+
return json(res, 200, await updates.get({ androidCurrent }));
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
// GET /v1/models
|
|
1003
|
+
if (method === "GET" && url.pathname === "/v1/models") {
|
|
1004
|
+
const models = await listModels().catch((err) => {
|
|
1005
|
+
throw new HttpError(503, `cannot list models: ${err.message}`);
|
|
1006
|
+
});
|
|
1007
|
+
return json(res, 200, { models });
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
// GET /v1/extensions (当前实例实际加载的扩展 + 除扩展外的启动参数)
|
|
1011
|
+
if (method === "GET" && url.pathname === "/v1/extensions") {
|
|
1012
|
+
return json(res, 200, describeExtensions());
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// GET /v1/plugins (主机已安装的 pi 资源只读清单 + hub 已加载扩展 + 客户端接入点)
|
|
1016
|
+
if (method === "GET" && url.pathname === "/v1/plugins") {
|
|
1017
|
+
return json(res, 200, describePlugins());
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
// GET /v1/sessions?limit=&before=
|
|
1021
|
+
if (method === "GET" && url.pathname === "/v1/sessions") {
|
|
1022
|
+
const limitParam = url.searchParams.get("limit");
|
|
1023
|
+
const limit = limitParam === null ? undefined : Number(limitParam);
|
|
1024
|
+
if (limit !== undefined && (!Number.isInteger(limit) || limit <= 0)) {
|
|
1025
|
+
throw new HttpError(400, "limit must be a positive integer", "invalid_limit");
|
|
1026
|
+
}
|
|
1027
|
+
return json(res, 200, { sessions: mergedSessions(registry, { limit, before: url.searchParams.get("before") }) });
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// POST /v1/sessions
|
|
1031
|
+
if (method === "POST" && url.pathname === "/v1/sessions") {
|
|
1032
|
+
const body = await readJsonBody(req);
|
|
1033
|
+
const cwd = typeof body.cwd === "string" && body.cwd ? path.resolve(body.cwd) : null;
|
|
1034
|
+
if (!cwd) throw new HttpError(400, "cwd is required");
|
|
1035
|
+
if (!fs.existsSync(cwd)) throw new HttpError(400, `cwd does not exist: ${cwd}`);
|
|
1036
|
+
const resumeId = typeof body.id === "string" && body.id ? body.id : null;
|
|
1037
|
+
const entry = resumeId ? findSession(resumeId) : null;
|
|
1038
|
+
const id = resumeId ?? randomUUID();
|
|
1039
|
+
const session = await registry.open({
|
|
1040
|
+
id,
|
|
1041
|
+
cwd: entry?.cwd ?? cwd,
|
|
1042
|
+
name: typeof body.name === "string" ? body.name : (entry?.name ?? null),
|
|
1043
|
+
model: typeof body.model === "string" ? body.model : null,
|
|
1044
|
+
sessionFile: entry?.file ?? null,
|
|
1045
|
+
});
|
|
1046
|
+
return json(res, 201, { session: session.snapshot() });
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
if (parts[0] === "v1" && parts[1] === "sessions" && parts[2]) {
|
|
1050
|
+
const sessionId = parts[2];
|
|
1051
|
+
const leaf = parts[3];
|
|
1052
|
+
|
|
1053
|
+
// GET /v1/sessions/:id
|
|
1054
|
+
if (method === "GET" && !leaf) {
|
|
1055
|
+
const { live, entry } = await resolveTarget(registry, sessionId);
|
|
1056
|
+
return json(res, 200, { session: live ? live.snapshot() : null, index: entry ? { ...entry, file: undefined } : null, live: Boolean(live) });
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
// GET /v1/sessions/:id/history
|
|
1060
|
+
if (method === "GET" && leaf === "history") {
|
|
1061
|
+
const limit = Number(url.searchParams.get("limit") ?? 0);
|
|
1062
|
+
const live = registry.get(sessionId);
|
|
1063
|
+
if (live) {
|
|
1064
|
+
const data = await live.command("get_messages");
|
|
1065
|
+
return json(res, 200, { source: "live", messages: normalizeMessages(data?.messages ?? [], limit) });
|
|
1066
|
+
}
|
|
1067
|
+
const entry = findSession(sessionId);
|
|
1068
|
+
if (!entry) throw new HttpError(404, `unknown session ${sessionId}`, "unknown_session");
|
|
1069
|
+
return json(res, 200, { source: "file", messages: readHistory(entry.file, { limit }) });
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
// GET /v1/sessions/:id/stats (live 走 RPC;非 live 由会话文件消息聚合,绝不 spawn)
|
|
1073
|
+
if (method === "GET" && leaf === "stats") {
|
|
1074
|
+
const live = registry.get(sessionId);
|
|
1075
|
+
if (!live) {
|
|
1076
|
+
const entry = findSession(sessionId);
|
|
1077
|
+
if (!entry) throw new HttpError(404, `unknown session ${sessionId}`, "unknown_session");
|
|
1078
|
+
return json(res, 200, { stats: fileSessionStats(entry) });
|
|
1079
|
+
}
|
|
1080
|
+
const data = await live.command("get_session_stats");
|
|
1081
|
+
return json(res, 200, {
|
|
1082
|
+
stats: {
|
|
1083
|
+
userMessages: data?.userMessages ?? 0,
|
|
1084
|
+
assistantMessages: data?.assistantMessages ?? 0,
|
|
1085
|
+
toolCalls: data?.toolCalls ?? 0,
|
|
1086
|
+
toolResults: data?.toolResults ?? 0,
|
|
1087
|
+
totalMessages: data?.totalMessages ?? 0,
|
|
1088
|
+
tokens: data?.tokens ?? null,
|
|
1089
|
+
cost: data?.cost ?? 0,
|
|
1090
|
+
contextUsage: data?.contextUsage ?? null,
|
|
1091
|
+
},
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
// GET /v1/sessions/:id/entries?since=&limit=
|
|
1096
|
+
if (method === "GET" && leaf === "entries") {
|
|
1097
|
+
const since = url.searchParams.get("since") || null;
|
|
1098
|
+
const limit = Number(url.searchParams.get("limit") ?? 0);
|
|
1099
|
+
const live = registry.get(sessionId);
|
|
1100
|
+
if (!live) {
|
|
1101
|
+
// 非 live 不 spawn:会话文件里的 entries 没有 RPC 树节点,诚实返回空集而不是 500。
|
|
1102
|
+
const entry = findSession(sessionId);
|
|
1103
|
+
if (!entry) throw new HttpError(404, `unknown session ${sessionId}`, "unknown_session");
|
|
1104
|
+
return json(res, 200, { entries: [], leafId: null, nextSince: since });
|
|
1105
|
+
}
|
|
1106
|
+
// pi 在 since 不匹配任何 entry id 时回 success:false(command() 只在这个分支带 .command)
|
|
1107
|
+
const data = since
|
|
1108
|
+
? await live.command("get_entries", { since }).catch((err) => {
|
|
1109
|
+
if (err.command === "get_entries") throw new HttpError(409, err.message, "stale_cursor");
|
|
1110
|
+
throw new HttpError(500, err.message);
|
|
1111
|
+
})
|
|
1112
|
+
: await live.command("get_entries");
|
|
1113
|
+
const entries = Array.isArray(data?.entries) ? data.entries : [];
|
|
1114
|
+
const leafId = data?.leafId ?? null;
|
|
1115
|
+
return json(res, 200, {
|
|
1116
|
+
entries: Number.isFinite(limit) && limit > 0 ? entries.slice(-limit) : entries,
|
|
1117
|
+
leafId,
|
|
1118
|
+
nextSince: leafId ?? since,
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
// POST /v1/sessions/:id/queue/clear
|
|
1123
|
+
if (method === "POST" && leaf === "queue" && parts[4] === "clear") {
|
|
1124
|
+
const session = await requireLive(registry, sessionId);
|
|
1125
|
+
const data = await session.command("clear_queue");
|
|
1126
|
+
return json(res, 200, { steering: data?.steering ?? [], followUp: data?.followUp ?? [] });
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
// POST /v1/sessions/:id/retry/abort
|
|
1130
|
+
if (method === "POST" && leaf === "retry" && parts[4] === "abort") {
|
|
1131
|
+
const session = await requireLive(registry, sessionId);
|
|
1132
|
+
await session.command("abort_retry");
|
|
1133
|
+
return json(res, 200, { ok: true });
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
// POST /v1/sessions/:id/export (忽略客户端 outputPath,只写 UPLOAD_DIR/exports)
|
|
1137
|
+
if (method === "POST" && leaf === "export") {
|
|
1138
|
+
const session = await requireLive(registry, sessionId);
|
|
1139
|
+
const dir = path.resolve(UPLOAD_DIR, "exports");
|
|
1140
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1141
|
+
fs.chmodSync(dir, 0o700);
|
|
1142
|
+
const file = path.join(dir, `${path.basename(sessionId)}-${Date.now()}.html`);
|
|
1143
|
+
const data = await session.command("export_html", { outputPath: file }).catch((err) => {
|
|
1144
|
+
// pi 对空会话回 success:false "Nothing to export yet"(无 data),别当 500
|
|
1145
|
+
if (err.command === "export_html" && /nothing to export/i.test(err.message)) {
|
|
1146
|
+
throw new HttpError(409, err.message, "nothing_to_export");
|
|
1147
|
+
}
|
|
1148
|
+
throw err;
|
|
1149
|
+
});
|
|
1150
|
+
const exported = path.resolve(data?.path ?? file);
|
|
1151
|
+
if (path.dirname(exported) !== dir) throw new HttpError(500, `export wrote outside exports dir: ${exported}`);
|
|
1152
|
+
// pi 按默认 umask 落盘(0644),统一收紧到 0600
|
|
1153
|
+
fs.chmodSync(exported, 0o600);
|
|
1154
|
+
const stat = fs.statSync(exported);
|
|
1155
|
+
log("export", exported, stat.size);
|
|
1156
|
+
return json(res, 200, { path: exported, size: stat.size });
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
// GET /v1/sessions/:id/events (SSE)
|
|
1160
|
+
if (method === "GET" && leaf === "events") {
|
|
1161
|
+
const sinceParam = Number(url.searchParams.get("since") ?? req.headers["last-event-id"] ?? 0);
|
|
1162
|
+
const since = Number.isFinite(sinceParam) ? sinceParam : 0;
|
|
1163
|
+
const session = await requireLive(registry, sessionId);
|
|
1164
|
+
return sse(req, res, session, since);
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
// POST /v1/sessions/:id/prompt
|
|
1168
|
+
if (method === "POST" && leaf === "prompt") {
|
|
1169
|
+
const body = await readJsonBody(req);
|
|
1170
|
+
const images = Array.isArray(body.images) ? body.images.filter((i) => i?.data && i?.mimeType).slice(0, 4) : [];
|
|
1171
|
+
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
1172
|
+
if (!text && !images.length) throw new HttpError(400, "text or images is required");
|
|
1173
|
+
const streamingBehavior = readStreamingBehavior(body);
|
|
1174
|
+
const session = await requireLive(registry, sessionId);
|
|
1175
|
+
const payload = { message: text || "请看这些图片。" };
|
|
1176
|
+
if (images.length) payload.images = images;
|
|
1177
|
+
if (streamingBehavior) payload.streamingBehavior = streamingBehavior;
|
|
1178
|
+
// 扩展命令里可能 await 一个对话框;pi 会等命令处理完才回 prompt 响应,
|
|
1179
|
+
// 所以这里不能用默认 30s(否则客户端还没看到 ui_request 就收到 409 prompt_rejected)。
|
|
1180
|
+
const data = await session.command("prompt", payload, { timeoutMs: 5 * 60 * 1000 }).catch((err) => {
|
|
1181
|
+
throw new HttpError(409, err.message, "prompt_rejected");
|
|
1182
|
+
});
|
|
1183
|
+
return json(res, 200, { disposition: data?.disposition ?? null });
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
// POST /v1/sessions/:id/follow-up {text, images?} → 转发 pi `follow_up`(agent 说完再说)
|
|
1187
|
+
if (method === "POST" && leaf === "follow-up") {
|
|
1188
|
+
const body = await readJsonBody(req);
|
|
1189
|
+
readStreamingBehavior(body); // follow_up 本身没有排队语义,但客户端传了非法值一样 400
|
|
1190
|
+
const images = Array.isArray(body.images) ? body.images.filter((i) => i?.data && i?.mimeType).slice(0, 4) : [];
|
|
1191
|
+
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
1192
|
+
if (!text && !images.length) throw new HttpError(400, "text or images is required");
|
|
1193
|
+
const session = await requireLive(registry, sessionId);
|
|
1194
|
+
const payload = { message: text || "请看这些图片。" };
|
|
1195
|
+
if (images.length) payload.images = images;
|
|
1196
|
+
const data = await session.command("follow_up", payload, { timeoutMs: 5 * 60 * 1000 }).catch((err) => {
|
|
1197
|
+
throw new HttpError(409, err.message, "follow_up_rejected");
|
|
1198
|
+
});
|
|
1199
|
+
return json(res, 200, { disposition: data?.disposition ?? null });
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
// POST /v1/sessions/:id/steer
|
|
1203
|
+
if (method === "POST" && leaf === "steer") {
|
|
1204
|
+
const body = await readJsonBody(req);
|
|
1205
|
+
if (typeof body.text !== "string" || !body.text.trim()) throw new HttpError(400, "text is required");
|
|
1206
|
+
const session = await requireLive(registry, sessionId);
|
|
1207
|
+
await session.command("steer", { message: body.text });
|
|
1208
|
+
return json(res, 200, { ok: true });
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
// POST /v1/sessions/:id/abort
|
|
1212
|
+
if (method === "POST" && leaf === "abort") {
|
|
1213
|
+
const session = await requireLive(registry, sessionId);
|
|
1214
|
+
await session.command("abort", {});
|
|
1215
|
+
return json(res, 200, { ok: true });
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// POST /v1/sessions/:id/model {provider, modelId}
|
|
1219
|
+
if (method === "POST" && leaf === "model") {
|
|
1220
|
+
const body = await readJsonBody(req);
|
|
1221
|
+
if (typeof body.provider !== "string" || typeof body.modelId !== "string") {
|
|
1222
|
+
throw new HttpError(400, "provider and modelId are required");
|
|
1223
|
+
}
|
|
1224
|
+
const session = await requireLive(registry, sessionId);
|
|
1225
|
+
const data = await session.command("set_model", { provider: body.provider, modelId: body.modelId });
|
|
1226
|
+
return json(res, 200, { model: data?.id ?? body.modelId });
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
// POST /v1/sessions/:id/thinking {level}
|
|
1230
|
+
if (method === "POST" && leaf === "thinking") {
|
|
1231
|
+
const body = await readJsonBody(req);
|
|
1232
|
+
if (typeof body.level !== "string") throw new HttpError(400, "level is required");
|
|
1233
|
+
const session = await requireLive(registry, sessionId);
|
|
1234
|
+
await session.command("set_thinking_level", { level: body.level });
|
|
1235
|
+
return json(res, 200, { ok: true });
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
// POST /v1/sessions/:id/name {name}
|
|
1239
|
+
if (method === "POST" && leaf === "name") {
|
|
1240
|
+
const body = await readJsonBody(req);
|
|
1241
|
+
if (typeof body.name !== "string") throw new HttpError(400, "name is required");
|
|
1242
|
+
const session = await requireLive(registry, sessionId);
|
|
1243
|
+
await session.command("set_session_name", { name: body.name });
|
|
1244
|
+
return json(res, 200, { name: body.name });
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
// GET /v1/sessions/:id/state (非 live 读会话文件/索引,绝不 spawn)
|
|
1248
|
+
if (method === "GET" && leaf === "state") {
|
|
1249
|
+
const live = registry.get(sessionId);
|
|
1250
|
+
if (live) return json(res, 200, { state: live.snapshot(), live: true });
|
|
1251
|
+
const entry = findSession(sessionId);
|
|
1252
|
+
if (!entry) throw new HttpError(404, `unknown session ${sessionId}`, "unknown_session");
|
|
1253
|
+
return json(res, 200, { state: fileSessionSnapshot(entry), live: false });
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
// GET /v1/sessions/:id/thinking (当前档位 + 该模型支持的档位)
|
|
1257
|
+
if (method === "GET" && leaf === "thinking") {
|
|
1258
|
+
const session = await requireLive(registry, sessionId);
|
|
1259
|
+
const [state, levels] = await Promise.all([
|
|
1260
|
+
session.command("get_state"),
|
|
1261
|
+
session.command("get_available_thinking_levels").catch(() => null),
|
|
1262
|
+
]);
|
|
1263
|
+
return json(res, 200, {
|
|
1264
|
+
level: state?.thinkingLevel ?? "medium",
|
|
1265
|
+
levels: levels?.levels ?? ["off", "low", "medium", "high"],
|
|
1266
|
+
model: state?.model?.id ?? null,
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
// POST /v1/sessions/:id/fork {entryId?, clone?} -> 新会话
|
|
1271
|
+
// fork:从某个 user 消息处分叉(新会话不含该消息,返回其文本供编辑)
|
|
1272
|
+
// clone:复制当前分支到末尾(“从这里继续”用这个)
|
|
1273
|
+
if (method === "POST" && leaf === "fork") {
|
|
1274
|
+
const body = await readJsonBody(req);
|
|
1275
|
+
const session = await requireLive(registry, sessionId);
|
|
1276
|
+
const snap = session.snapshot();
|
|
1277
|
+
const clone = body.clone === true;
|
|
1278
|
+
const history = snap.sessionFile ? readHistory(snap.sessionFile) : [];
|
|
1279
|
+
const firstUserText = history.find((m) => m.role === "user")?.text ?? null;
|
|
1280
|
+
let entryId = null;
|
|
1281
|
+
let data;
|
|
1282
|
+
if (clone) {
|
|
1283
|
+
data = await session.command("clone", {});
|
|
1284
|
+
} else {
|
|
1285
|
+
entryId = typeof body.entryId === "string" && body.entryId ? body.entryId : null;
|
|
1286
|
+
// live 会话的 get_messages 不带 entryId,用 pi 的 get_fork_messages 按序号解析
|
|
1287
|
+
if (!entryId && Number.isInteger(body.userIndex)) {
|
|
1288
|
+
const forkable = await session.command("get_fork_messages").catch(() => null);
|
|
1289
|
+
entryId = forkable?.messages?.[body.userIndex]?.entryId ?? null;
|
|
1290
|
+
}
|
|
1291
|
+
if (!entryId) {
|
|
1292
|
+
entryId = [...history].reverse().find((m) => m.role === "user")?.entryId ?? null;
|
|
1293
|
+
}
|
|
1294
|
+
if (!entryId) throw new HttpError(400, "no user message to fork from");
|
|
1295
|
+
data = await session.command("fork", { entryId });
|
|
1296
|
+
}
|
|
1297
|
+
if (data?.cancelled) return json(res, 200, { cancelled: true });
|
|
1298
|
+
const state = await session.command("get_state");
|
|
1299
|
+
const newId = state?.sessionId;
|
|
1300
|
+
if (!newId) throw new HttpError(500, "fork did not return a new session id");
|
|
1301
|
+
const oldId = session.rekey({
|
|
1302
|
+
id: newId,
|
|
1303
|
+
sessionFile: state?.sessionFile ?? null,
|
|
1304
|
+
name: state?.sessionName ?? snap.name,
|
|
1305
|
+
cwd: state?.cwd ?? snap.cwd,
|
|
1306
|
+
model: state?.model ?? null,
|
|
1307
|
+
});
|
|
1308
|
+
registry.rekey(oldId, newId, session);
|
|
1309
|
+
{
|
|
1310
|
+
const base = (snap.name || firstUserText || "会话").trim().slice(0, 44);
|
|
1311
|
+
const name = base.endsWith("· 分支") ? base : `${base} · 分支`;
|
|
1312
|
+
await session.command("set_session_name", { name }).then(() => {
|
|
1313
|
+
session.name = name;
|
|
1314
|
+
session.state.sessionName = name;
|
|
1315
|
+
}).catch(() => {});
|
|
1316
|
+
}
|
|
1317
|
+
// 已连着的 SSE 客户端不用重连:直接告诉它 id 变了
|
|
1318
|
+
session.emit({ type: "forked", from: oldId, session: session.snapshot() });
|
|
1319
|
+
log("fork", oldId, "->", newId);
|
|
1320
|
+
return json(res, 201, {
|
|
1321
|
+
cancelled: false,
|
|
1322
|
+
text: data?.text ?? null,
|
|
1323
|
+
session: session.snapshot(),
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
// DELETE /v1/sessions/:id[?delete=1]
|
|
1328
|
+
if (method === "DELETE" && !leaf) {
|
|
1329
|
+
const live = registry.get(sessionId);
|
|
1330
|
+
if (live) live.stop("deleted");
|
|
1331
|
+
if (url.searchParams.get("delete") === "1") {
|
|
1332
|
+
const entry = findSession(sessionId);
|
|
1333
|
+
if (entry) {
|
|
1334
|
+
// 只读判活:其它活进程(桌面 TUI / 别的 hub)正写这个会话时,删文件 = 不可恢复的数据丢失
|
|
1335
|
+
const probe = peekSessionLock(entry.file);
|
|
1336
|
+
if (probe.state === "live") {
|
|
1337
|
+
throw new HttpError(
|
|
1338
|
+
409,
|
|
1339
|
+
`session ${sessionId} is open in another live process (${probe.reason})`,
|
|
1340
|
+
"session_locked",
|
|
1341
|
+
);
|
|
1342
|
+
}
|
|
1343
|
+
fs.rmSync(entry.file, { force: true });
|
|
1344
|
+
}
|
|
1345
|
+
return json(res, 200, { deleted: true, file: Boolean(entry) });
|
|
1346
|
+
}
|
|
1347
|
+
return json(res, 200, { stopped: Boolean(live) });
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
// POST /v1/sessions/:id/compact
|
|
1351
|
+
if (method === "POST" && leaf === "compact") {
|
|
1352
|
+
const session = await requireLive(registry, sessionId);
|
|
1353
|
+
await session.command("compact", {});
|
|
1354
|
+
return json(res, 200, { ok: true });
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
// POST /v1/sessions/:id/lease 只续活动时间,绝不 spawn(手机前台服务保活用)
|
|
1358
|
+
if (method === "POST" && leaf === "lease") {
|
|
1359
|
+
const session = registry.get(sessionId);
|
|
1360
|
+
if (!session) return json(res, 200, { ok: true, live: false, status: null });
|
|
1361
|
+
session.touch();
|
|
1362
|
+
return json(res, 200, { ok: true, live: true, status: session.state?.status ?? null });
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
// 设置类开关:{enabled} / {mode}
|
|
1366
|
+
if (method === "POST" && (leaf === "auto-compaction" || leaf === "auto-retry")) {
|
|
1367
|
+
const body = await readJsonBody(req);
|
|
1368
|
+
if (typeof body.enabled !== "boolean") throw new HttpError(400, "enabled must be a boolean");
|
|
1369
|
+
const session = await requireLive(registry, sessionId);
|
|
1370
|
+
const cmd = leaf === "auto-compaction" ? "set_auto_compaction" : "set_auto_retry";
|
|
1371
|
+
await session.command(cmd, { enabled: body.enabled });
|
|
1372
|
+
return json(res, 200, { ok: true, enabled: body.enabled });
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
if (method === "POST" && (leaf === "steering-mode" || leaf === "follow-up-mode")) {
|
|
1376
|
+
const body = await readJsonBody(req);
|
|
1377
|
+
if (body.mode !== "all" && body.mode !== "one-at-a-time") {
|
|
1378
|
+
throw new HttpError(400, 'mode must be "all" or "one-at-a-time"', "invalid_mode");
|
|
1379
|
+
}
|
|
1380
|
+
const session = await requireLive(registry, sessionId);
|
|
1381
|
+
const cmd = leaf === "steering-mode" ? "set_steering_mode" : "set_follow_up_mode";
|
|
1382
|
+
await session.command(cmd, { mode: body.mode });
|
|
1383
|
+
return json(res, 200, { ok: true, mode: body.mode });
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
// POST /v1/sessions/:id/ui/:uiId 回答扩展 UI 对话框
|
|
1387
|
+
// body: {value} | {confirmed} | {cancelled:true}
|
|
1388
|
+
if (method === "POST" && leaf === "ui" && parts[4]) {
|
|
1389
|
+
const body = await readJsonBody(req);
|
|
1390
|
+
const session = registry.get(sessionId);
|
|
1391
|
+
if (!session) throw new HttpError(404, `session ${sessionId} is not live`, "not_live");
|
|
1392
|
+
const hasAnswer =
|
|
1393
|
+
body.cancelled === true || typeof body.value === "string" || typeof body.confirmed === "boolean";
|
|
1394
|
+
if (!hasAnswer) throw new HttpError(400, "value, confirmed or cancelled is required");
|
|
1395
|
+
try {
|
|
1396
|
+
session.answerUi(parts[4], body);
|
|
1397
|
+
} catch (err) {
|
|
1398
|
+
throw new HttpError(err.statusCode ?? 409, err.message, err.code ?? "unknown_ui_request");
|
|
1399
|
+
}
|
|
1400
|
+
return json(res, 200, { ok: true });
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
// GET /v1/commands (扩展命令 / prompt 模板 / skill;缓存 5 min)
|
|
1405
|
+
if (method === "GET" && url.pathname === "/v1/commands") {
|
|
1406
|
+
const commands = await listCommands().catch((err) => {
|
|
1407
|
+
throw new HttpError(503, `cannot list commands: ${err.message}`);
|
|
1408
|
+
});
|
|
1409
|
+
return json(res, 200, { commands });
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
// POST /v1/upload?name=foo.pdf (原始二进制;落盘到 UPLOAD_DIR,返回可被 agent 读取的绝对路径)
|
|
1413
|
+
if (method === "POST" && url.pathname === "/v1/upload") {
|
|
1414
|
+
const rawName = url.searchParams.get("name") || "attachment";
|
|
1415
|
+
const safe = path.basename(rawName).replace(/[^\w.\- ()\u4e00-\u9fa5]/g, "_").slice(-120) || "attachment";
|
|
1416
|
+
const buf = await readRawBody(req);
|
|
1417
|
+
if (!buf.length) throw new HttpError(400, "empty body");
|
|
1418
|
+
fs.mkdirSync(UPLOAD_DIR, { recursive: true, mode: 0o700 });
|
|
1419
|
+
const file = path.join(UPLOAD_DIR, `${Date.now().toString(36)}-${randomBytes(3).toString("hex")}-${safe}`);
|
|
1420
|
+
fs.writeFileSync(file, buf, { mode: 0o600 });
|
|
1421
|
+
log("upload", file, buf.length);
|
|
1422
|
+
return json(res, 201, { path: file, name: safe, size: buf.length });
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
// GET /v1/thinking (未开会话时的默认推理强度 + 可选档位)
|
|
1426
|
+
if (method === "GET" && url.pathname === "/v1/thinking") {
|
|
1427
|
+
return json(res, 200, await defaultThinking());
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
// GET /v1/files?path=/abs/file (下载 UPLOAD_DIR 子树内的文件;export 分享用)
|
|
1431
|
+
if (method === "GET" && url.pathname === "/v1/files") {
|
|
1432
|
+
const raw = url.searchParams.get("path");
|
|
1433
|
+
if (!raw) throw new HttpError(400, "path is required");
|
|
1434
|
+
let root;
|
|
1435
|
+
try {
|
|
1436
|
+
root = fs.realpathSync(UPLOAD_DIR);
|
|
1437
|
+
} catch {
|
|
1438
|
+
throw new HttpError(404, `upload dir does not exist: ${UPLOAD_DIR}`, "file_not_found");
|
|
1439
|
+
}
|
|
1440
|
+
let real;
|
|
1441
|
+
try {
|
|
1442
|
+
real = fs.realpathSync(path.resolve(raw));
|
|
1443
|
+
} catch {
|
|
1444
|
+
throw new HttpError(404, `file not found: ${raw}`, "file_not_found");
|
|
1445
|
+
}
|
|
1446
|
+
if (real !== root && !real.startsWith(root + path.sep)) {
|
|
1447
|
+
throw new HttpError(403, "path outside upload dir", "path_not_allowed");
|
|
1448
|
+
}
|
|
1449
|
+
const stat = fs.statSync(real);
|
|
1450
|
+
if (!stat.isFile()) throw new HttpError(404, "not a file", "file_not_found");
|
|
1451
|
+
res.writeHead(200, {
|
|
1452
|
+
"content-type": mimeForFile(real),
|
|
1453
|
+
"content-length": stat.size,
|
|
1454
|
+
"content-disposition": `attachment; filename="${encodeURIComponent(path.basename(real))}"`,
|
|
1455
|
+
"cache-control": "no-store",
|
|
1456
|
+
});
|
|
1457
|
+
const stream = fs.createReadStream(real);
|
|
1458
|
+
stream.on("error", () => res.destroy());
|
|
1459
|
+
stream.pipe(res);
|
|
1460
|
+
return;
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
// GET /v1/workspace?path=/home/x/foo (工作区路径校验)
|
|
1464
|
+
if (method === "GET" && url.pathname === "/v1/workspace") {
|
|
1465
|
+
const raw = url.searchParams.get("path");
|
|
1466
|
+
if (!raw) throw new HttpError(400, "path is required");
|
|
1467
|
+
const abs = path.resolve(raw);
|
|
1468
|
+
try {
|
|
1469
|
+
const stat = fs.statSync(abs);
|
|
1470
|
+
return json(res, 200, { path: abs, exists: true, isDir: stat.isDirectory() });
|
|
1471
|
+
} catch {
|
|
1472
|
+
return json(res, 200, { path: abs, exists: false, isDir: false });
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
// POST /v1/doctor (诊断:能否起 pi、模型表是否可读)
|
|
1477
|
+
if (method === "POST" && url.pathname === "/v1/doctor") {
|
|
1478
|
+
const result = { pi: null, models: null, sessionsDir: null };
|
|
1479
|
+
try {
|
|
1480
|
+
const stat = fs.statSync(SESSIONS_DIR);
|
|
1481
|
+
result.sessionsDir = { ok: stat.isDirectory(), path: SESSIONS_DIR, sessions: listSessions({ limit: 5000, force: true }).length };
|
|
1482
|
+
} catch (err) {
|
|
1483
|
+
result.sessionsDir = { ok: false, path: SESSIONS_DIR, error: err.message };
|
|
1484
|
+
}
|
|
1485
|
+
try {
|
|
1486
|
+
const state = await rpcOnce("get_state", {}, { timeoutMs: 25000 });
|
|
1487
|
+
result.pi = { ok: true, sessionFile: state?.sessionFile ?? null, model: state?.model?.id ?? null };
|
|
1488
|
+
} catch (err) {
|
|
1489
|
+
result.pi = { ok: false, error: err.message };
|
|
1490
|
+
}
|
|
1491
|
+
try {
|
|
1492
|
+
const models = await listModels();
|
|
1493
|
+
result.models = { ok: true, count: models.length };
|
|
1494
|
+
} catch (err) {
|
|
1495
|
+
result.models = { ok: false, error: err.message };
|
|
1496
|
+
}
|
|
1497
|
+
return json(res, 200, result);
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
throw new HttpError(404, `no route: ${method} ${url.pathname}`, "no_route");
|
|
1501
|
+
} catch (err) {
|
|
1502
|
+
const status = err.status ?? err.statusCode ?? 500;
|
|
1503
|
+
if (status >= 500) log("error", req.method, url.pathname, err.stack ?? err.message);
|
|
1504
|
+
if (!res.headersSent) json(res, status, { error: { message: err.message, code: err.code ?? null } });
|
|
1505
|
+
else res.end();
|
|
1506
|
+
}
|
|
1507
|
+
});
|
|
1508
|
+
|
|
1509
|
+
server.on("clientError", (_err, socket) => {
|
|
1510
|
+
try {
|
|
1511
|
+
socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
|
|
1512
|
+
} catch {
|
|
1513
|
+
// ignore
|
|
1514
|
+
}
|
|
1515
|
+
});
|
|
1516
|
+
|
|
1517
|
+
return {
|
|
1518
|
+
server,
|
|
1519
|
+
registry,
|
|
1520
|
+
token,
|
|
1521
|
+
listen({ port = PORT, host = HOST } = {}) {
|
|
1522
|
+
return new Promise((resolve) => {
|
|
1523
|
+
server.listen(port, host, () => resolve(server.address()));
|
|
1524
|
+
});
|
|
1525
|
+
},
|
|
1526
|
+
close() {
|
|
1527
|
+
clearInterval(reaper);
|
|
1528
|
+
registry.closeAll();
|
|
1529
|
+
return new Promise((resolve) => server.close(() => resolve()));
|
|
1530
|
+
},
|
|
1531
|
+
};
|
|
1532
|
+
}
|