pi-hub-server 0.4.2 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +172 -0
- package/README.md +124 -43
- package/bin/pi-hub.mjs +332 -33
- package/docs/AUTH.md +5 -5
- package/docs/PLUGIN-DEPS.md +177 -0
- package/package.json +2 -4
- package/src/cli-control.mjs +309 -0
- package/src/help-text.mjs +215 -0
- package/src/lock-protocol.mjs +106 -0
- package/src/pi-session.mjs +91 -11
- package/src/server.mjs +217 -18
- package/src/session-lock-fallback.mjs +23 -19
- package/src/session-lock.mjs +124 -35
- package/src/sessions-index.mjs +176 -6
- package/src/static.mjs +6 -0
- package/systemd/pi-hub.service +2 -0
- package/web/app.js +753 -328
- package/web/compose.js +39 -0
- package/web/index.html +51 -20
- package/web/markdown.js +182 -0
- package/web/model.js +342 -0
- package/web/style.css +454 -58
- package/web/sw.js +1 -1
- package/web/tutorial.html +585 -0
package/src/server.mjs
CHANGED
|
@@ -3,11 +3,21 @@ import fs from "node:fs";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
5
5
|
import { AUTH_DISABLED, CONFIG_DIR, HEARTBEAT_MS, HOME, HOST, IDLE_MS, PI_BIN, PORT, SESSIONS_DIR, UPLOAD_DIR, ensureToken, readToken } from "./config.mjs";
|
|
6
|
-
import { findSession, listSessions, readHistory } from "./sessions-index.mjs";
|
|
6
|
+
import { PREVIEW_MAX, findSession, listSessions, readHistory, sliceHistoryPage, sortSessionRows } from "./sessions-index.mjs";
|
|
7
7
|
import { HttpError, Registry } from "./registry.mjs";
|
|
8
8
|
import { listModels, rpcOnce } from "./rpc-once.mjs";
|
|
9
9
|
import { extensionPaths, extensionsMode, piArgs } from "./pi-args.mjs";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
peek as peekSessionLock,
|
|
12
|
+
corePath as sessionLockCorePath,
|
|
13
|
+
coreApiVersion as sessionLockCoreApiVersion,
|
|
14
|
+
lockSource as sessionLockSource,
|
|
15
|
+
lockReason as sessionLockReason,
|
|
16
|
+
lockHint as sessionLockHint,
|
|
17
|
+
explicitPointerError as sessionLockExplicitPointerError,
|
|
18
|
+
pluginVersion as sessionLockPluginVersion,
|
|
19
|
+
supportedCoreApi as sessionLockSupportedCoreApi,
|
|
20
|
+
} from "./session-lock.mjs";
|
|
11
21
|
import { PairingStore, publicDevice, requireSignature } from "./pairing.mjs";
|
|
12
22
|
import { mimeForFile, serveStatic } from "./static.mjs";
|
|
13
23
|
import { WebAuth, clearSessionCookie, handleWebSessionRevoke, handleWebSessionsList, isSecureRequest, sessionCookie } from "./web-auth.mjs";
|
|
@@ -19,6 +29,8 @@ import { HUB_VERSION, UpdateChecker } from "./update-check.mjs";
|
|
|
19
29
|
import { piVersionSnapshot, startPiVersionRefresh } from "./pi-version.mjs";
|
|
20
30
|
|
|
21
31
|
const MAX_BODY = 16 * 1024 * 1024; // prompt 里带 base64 图片
|
|
32
|
+
// /v1/workspace?list=1 一级列举上限:目录可能有几万条(node_modules),联想只需要前几百。
|
|
33
|
+
const WORKSPACE_LIST_MAX = 500;
|
|
22
34
|
const MAX_UPLOAD = 32 * 1024 * 1024;
|
|
23
35
|
|
|
24
36
|
function log(...args) {
|
|
@@ -190,7 +202,10 @@ function normalizeMessages(messages, limit = 0) {
|
|
|
190
202
|
for (const b of blocks) {
|
|
191
203
|
if (b?.type === "text" && b.text) parts.push(b.text);
|
|
192
204
|
else if (b?.type === "thinking" && b.thinking) thinkingParts.push(b.thinking);
|
|
193
|
-
else if (b?.type === "toolCall")
|
|
205
|
+
else if (b?.type === "toolCall") {
|
|
206
|
+
// 与 sessions-index.readHistory 同口径:pi 的 toolCall 块字段是 `arguments`(RPC get_messages 亦然)。
|
|
207
|
+
toolCalls.push({ id: b.id, name: b.name, args: b.arguments ?? b.args ?? null });
|
|
208
|
+
}
|
|
194
209
|
}
|
|
195
210
|
const ts = typeof m.timestamp === "number" ? new Date(m.timestamp).toISOString() : (m.timestamp ?? null);
|
|
196
211
|
out.push({
|
|
@@ -200,6 +215,9 @@ function normalizeMessages(messages, limit = 0) {
|
|
|
200
215
|
// 与会话文件路径(sessions-index.readHistory)同口径:思考正文回放给客户端「过程」折叠块。
|
|
201
216
|
thinking: thinkingParts.join("\n"),
|
|
202
217
|
toolCallId: m.toolCallId ?? null,
|
|
218
|
+
// 与 sessions-index.readHistory 同口径:toolResult 行的工具名与失败标记。
|
|
219
|
+
toolName: m.toolName ?? null,
|
|
220
|
+
isError: m.isError === true,
|
|
203
221
|
toolCalls,
|
|
204
222
|
ts,
|
|
205
223
|
usage: m.usage ?? null,
|
|
@@ -260,6 +278,29 @@ function modelAlias(model) {
|
|
|
260
278
|
/** pi 的会话 id 是 UUID(大小写不论);用来把「文件名被误当 id」的 artifact 行筛掉。 */
|
|
261
279
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
262
280
|
|
|
281
|
+
// ---------------------------------------------------------------------------
|
|
282
|
+
// 会话锁来源 / 版本面
|
|
283
|
+
// ---------------------------------------------------------------------------
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* `/v1/health.sessionLockInfo` 与 createHubServer().sessionLock 的同一份口径。
|
|
287
|
+
*
|
|
288
|
+
* `source:"fallback"` 是**默认状态**(内置锁),不是故障:`hint` 给出「要不要装插件」的那一行,
|
|
289
|
+
* `explicitPointerError` 只在用户把 `PI_HUB_SESSION_LOCK_CORE` 指坏时非 null(那时 serve 不会起来)。
|
|
290
|
+
*/
|
|
291
|
+
function sessionLockInfo() {
|
|
292
|
+
return {
|
|
293
|
+
source: sessionLockSource,
|
|
294
|
+
corePath: sessionLockCorePath,
|
|
295
|
+
pluginVersion: sessionLockPluginVersion,
|
|
296
|
+
coreApiVersion: sessionLockCoreApiVersion,
|
|
297
|
+
supportedCoreApi: sessionLockSupportedCoreApi,
|
|
298
|
+
reason: sessionLockReason,
|
|
299
|
+
hint: sessionLockHint,
|
|
300
|
+
explicitPointerError: sessionLockExplicitPointerError,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
263
304
|
/**
|
|
264
305
|
* `GET /v1/extensions` 的正文:当前进程拉 pi 时真正会加载的扩展。
|
|
265
306
|
* 默认 mode: "all"(不传 --no-extensions,pi 自己发现扩展);PI_HUB_EXTENSIONS=off ⇒ mode: "none";
|
|
@@ -607,6 +648,45 @@ function fileSessionSnapshot(entry) {
|
|
|
607
648
|
};
|
|
608
649
|
}
|
|
609
650
|
|
|
651
|
+
/**
|
|
652
|
+
* 生成耗时合计:只认 assistant 消息自带的 `durationMs`(pi 落盘的生成耗时)。
|
|
653
|
+
* live 与文件两条 stats 路径共用,口径一致:思考/工具/排队时间不进分母。
|
|
654
|
+
*/
|
|
655
|
+
function generationMsTotal(messages) {
|
|
656
|
+
let ms = 0;
|
|
657
|
+
for (const m of messages ?? []) {
|
|
658
|
+
if (m.role === "assistant" && m.usage && Number.isFinite(m.durationMs)) ms += m.durationMs;
|
|
659
|
+
}
|
|
660
|
+
return ms;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* 回合级速率(W1-d):`tokensPerSecond` = 输出 token / 生成耗时秒数(无耗时 → null);
|
|
665
|
+
* `cacheHitRate` = cacheRead / (input + cacheRead),0..1(分母 0 → null)。
|
|
666
|
+
* cacheWrite 单列、不进命中率分母(与 DSH 的 Cache hit 口径一致)。
|
|
667
|
+
* 字段只增不改:老客户端忽略两个新字段即可。
|
|
668
|
+
*/
|
|
669
|
+
export function tokenRates({ outputTokens = 0, generationMs = 0, inputTokens = 0, cacheReadTokens = 0 } = {}) {
|
|
670
|
+
const seconds = generationMs / 1000;
|
|
671
|
+
const tokensPerSecond = seconds > 0 && outputTokens > 0 ? Math.round((outputTokens / seconds) * 10) / 10 : null;
|
|
672
|
+
const denom = inputTokens + cacheReadTokens;
|
|
673
|
+
const cacheHitRate = denom > 0 ? Math.round((cacheReadTokens / denom) * 10000) / 10000 : null;
|
|
674
|
+
return { tokensPerSecond, cacheHitRate };
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/**
|
|
678
|
+
* 会话消息 + 已聚合的 tokens → 两个速率字段。file 路径传自己聚合的 tokens,
|
|
679
|
+
* live 路径传 pi `get_session_stats` 的 tokens(分母同源,不混两套账)。
|
|
680
|
+
*/
|
|
681
|
+
function sessionRates(messages, tokens) {
|
|
682
|
+
return tokenRates({
|
|
683
|
+
outputTokens: tokens?.output ?? 0,
|
|
684
|
+
generationMs: generationMsTotal(messages),
|
|
685
|
+
inputTokens: tokens?.input ?? 0,
|
|
686
|
+
cacheReadTokens: tokens?.cacheRead ?? 0,
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
|
|
610
690
|
/** 从会话文件的消息聚合出 `get_session_stats` 的同一字段集;`contextUsage` 需要模型上下文窗口,非 live 时给 null。 */
|
|
611
691
|
function fileSessionStats(entry) {
|
|
612
692
|
const messages = readHistory(entry.file);
|
|
@@ -639,6 +719,7 @@ function fileSessionStats(entry) {
|
|
|
639
719
|
tokens,
|
|
640
720
|
cost,
|
|
641
721
|
contextUsage: null,
|
|
722
|
+
...sessionRates(messages, tokens),
|
|
642
723
|
};
|
|
643
724
|
}
|
|
644
725
|
|
|
@@ -651,10 +732,43 @@ function readStreamingBehavior(body) {
|
|
|
651
732
|
return body.streamingBehavior;
|
|
652
733
|
}
|
|
653
734
|
|
|
735
|
+
/**
|
|
736
|
+
* live 会话的标题来源:`firstUserText`(prompt/follow-up 记录或 resume 时从文件补)截到 160。
|
|
737
|
+
* 拿不到就 null —— 客户端回退到「新会话」。
|
|
738
|
+
*/
|
|
739
|
+
function livePreview(session) {
|
|
740
|
+
const text = typeof session?.firstUserText === "string" ? session.firstUserText.trim() : "";
|
|
741
|
+
return text ? text.slice(0, PREVIEW_MAX) : null;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* live 状态里算「还在跑」的那几个:客户端行尾要转圈。
|
|
746
|
+
* `starting` 是刚 spawn 还没收到第一条事件(同样不该显示成「完成」),`idle`/`closed` 落到文件行。
|
|
747
|
+
*/
|
|
748
|
+
const LIVE_RUNNING_STATES = new Set(["starting", "running", "thinking", "compacting"]);
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* 会话行的 `lastStatus`:live 会话能判「进行中」,其余(含 idle)回落到文件尾部的判定,
|
|
752
|
+
* 没有文件的行(刚建、未落盘)当 `done`。
|
|
753
|
+
* @param {{status?:string}|null|undefined} session registry 快照
|
|
754
|
+
* @param {"done"|"aborted"|"error"|undefined} diskLastStatus 同 id 的磁盘行判定
|
|
755
|
+
* @returns {"running"|"done"|"aborted"|"error"}
|
|
756
|
+
*/
|
|
757
|
+
function rowLastStatus(session, diskLastStatus) {
|
|
758
|
+
// 只在状态字段上判会漏掉「prompt 已到、pi 的 status 事件还没到」的瞬时空窗:
|
|
759
|
+
// 那时磁盘尾行是刚写入的 user 消息,会被判成 error 红点。isStreaming/isCompacting 一并对齐。
|
|
760
|
+
if (session && (LIVE_RUNNING_STATES.has(session.status) || session.isStreaming || session.isCompacting)) {
|
|
761
|
+
return "running";
|
|
762
|
+
}
|
|
763
|
+
return diskLastStatus ?? "done";
|
|
764
|
+
}
|
|
765
|
+
|
|
654
766
|
/**
|
|
655
767
|
* 会话库 + 存活状态合并。
|
|
656
768
|
* `limit` 省略时保持旧行为(磁盘侧 200 条 + 未落盘的 live 行,不做合并截断);
|
|
657
769
|
* `before` 是 `updatedAt` ISO 游标,只保留严格早于它的条目。
|
|
770
|
+
* 结果全局按 `updatedAt` 降序(同 timestamp 用 id 兜底,见 `sortSessionRows`):
|
|
771
|
+
* 主机侧新建/刚活动的会话必须能把位置顶到前面,不能靠「live 行前插」这种偶然顺序。
|
|
658
772
|
*/
|
|
659
773
|
function mergedSessions(registry, { limit, before } = {}) {
|
|
660
774
|
const cap = limit === undefined ? 200 : Math.min(limit, MAX_SESSIONS_LIMIT);
|
|
@@ -667,20 +781,25 @@ function mergedSessions(registry, { limit, before } = {}) {
|
|
|
667
781
|
return {
|
|
668
782
|
id: entry.id,
|
|
669
783
|
name: session?.name ?? entry.name,
|
|
670
|
-
|
|
784
|
+
// 文件里已解析出首条用户消息就用它;还没写盘(刚建会话/首轮未 flush)用 live 记录的兜底。
|
|
785
|
+
preview: entry.preview ?? livePreview(session),
|
|
671
786
|
cwd: entry.cwd,
|
|
672
787
|
model: modelAlias(session?.model ?? entry.model),
|
|
673
788
|
updatedAt: entry.updatedAt,
|
|
674
789
|
createdAt: entry.createdAt,
|
|
675
790
|
live: Boolean(session),
|
|
676
791
|
status: session?.status ?? null,
|
|
792
|
+
lastStatus: rowLastStatus(session, entry.lastStatus),
|
|
677
793
|
};
|
|
678
794
|
});
|
|
679
795
|
for (const [id, session] of live) {
|
|
680
796
|
if (rows.some((r) => r.id === id)) continue;
|
|
681
797
|
// registry.list() 返回的已经是快照,不要再调 .snapshot()
|
|
682
|
-
|
|
798
|
+
// 未落盘的行没有文件 mtime:`lastActivity` 是实时值(每个请求重新取快照),preview 取首条用户消息。
|
|
799
|
+
rows.push({ id, name: session.name, preview: livePreview(session), cwd: session.cwd, model: modelAlias(session.model), updatedAt: session.lastActivity, createdAt: session.startedAt, live: true, status: session.status, lastStatus: rowLastStatus(session, null) });
|
|
683
800
|
}
|
|
801
|
+
// 全局降序:排序必须在去重之前,同一 id 多行时才保留「先到(更新)」那行作为排序位。
|
|
802
|
+
sortSessionRows(rows);
|
|
684
803
|
// 游标对所有行生效(包括未落盘的 live 行),保证「严格小于 updatedAt」
|
|
685
804
|
const kept = cutoff === null ? rows : rows.filter((r) => Date.parse(r.updatedAt) < cutoff);
|
|
686
805
|
// 去重:同一个会话文件可能在多个项目目录里各有一份(扫出来 id 相同);
|
|
@@ -1083,8 +1202,10 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
1083
1202
|
idleMs: IDLE_MS,
|
|
1084
1203
|
// 升级后第一眼看见契约漂移:不认识的事件数(进程级累计)。
|
|
1085
1204
|
unknownEvents: registry.unknownEvents(),
|
|
1086
|
-
//
|
|
1205
|
+
// 锁的来源:plugin = 与桌面 pi 共用一份锁(装了插件),fallback = hub 内置锁(默认状态)。
|
|
1087
1206
|
sessionLock: sessionLockSource,
|
|
1207
|
+
// 版本面:没用插件时版本字段为 null(不报错),reason 是一行中性原因,hint 是「要不要装」的提示。
|
|
1208
|
+
sessionLockInfo: sessionLockInfo(),
|
|
1088
1209
|
// pi 实测版本(后台探测);未探到时为 null。
|
|
1089
1210
|
piVersion: piVersion.version,
|
|
1090
1211
|
piVersionCheckedAt: piVersion.checkedAt,
|
|
@@ -1154,17 +1275,50 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
1154
1275
|
return json(res, 200, { session: live ? live.snapshot() : null, index: entry ? { ...entry, file: undefined } : null, live: Boolean(live) });
|
|
1155
1276
|
}
|
|
1156
1277
|
|
|
1157
|
-
// GET /v1/sessions/:id/history
|
|
1278
|
+
// GET /v1/sessions/:id/history?limit=N&before=<entryId>
|
|
1279
|
+
// limit 缺省/0 = 全部(老客户端);before 走「更早一页」,见 sessions-index.sliceHistoryPage。
|
|
1158
1280
|
if (method === "GET" && leaf === "history") {
|
|
1159
1281
|
const limit = Number(url.searchParams.get("limit") ?? 0);
|
|
1282
|
+
const before = url.searchParams.get("before");
|
|
1160
1283
|
const live = registry.get(sessionId);
|
|
1284
|
+
let source = "live";
|
|
1285
|
+
let fromFile = false;
|
|
1286
|
+
let all;
|
|
1161
1287
|
if (live) {
|
|
1162
|
-
|
|
1163
|
-
|
|
1288
|
+
// 优先读会话文件:pi 的 `get_messages` 消息**不带 id**,`normalizeMessages` 只能给
|
|
1289
|
+
// entryId=null ⇒ 客户端「编辑并发送」被 entryId 门控而消失,`nextBefore` 也为 null
|
|
1290
|
+
// 导致分页退化全量重拉(R11 真机 F2/F4)。文件里的 `rec.id` 才是 fork 认的 entryId。
|
|
1291
|
+
all = live.sessionFile ? readHistory(live.sessionFile) : [];
|
|
1292
|
+
if (all.length) {
|
|
1293
|
+
fromFile = true;
|
|
1294
|
+
} else {
|
|
1295
|
+
// 降级:文件还没落盘(刚 spawn、首轮未写、或读不到)时才退回 RPC。此时 entryId
|
|
1296
|
+
// 仍可能是 null,客户端会退回全量重拉 —— 可接受降级,不当错误。
|
|
1297
|
+
const data = await live.command("get_messages");
|
|
1298
|
+
all = normalizeMessages(data?.messages ?? []);
|
|
1299
|
+
}
|
|
1300
|
+
} else {
|
|
1301
|
+
const entry = findSession(sessionId);
|
|
1302
|
+
if (!entry) throw new HttpError(404, `unknown session ${sessionId}`, "unknown_session");
|
|
1303
|
+
source = "file";
|
|
1304
|
+
all = readHistory(entry.file);
|
|
1164
1305
|
}
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1306
|
+
let page;
|
|
1307
|
+
try {
|
|
1308
|
+
page = sliceHistoryPage(all, { limit, before });
|
|
1309
|
+
} catch (err) {
|
|
1310
|
+
if (err?.code === "stale_cursor") throw new HttpError(409, err.message, "stale_history_cursor");
|
|
1311
|
+
throw err;
|
|
1312
|
+
}
|
|
1313
|
+
return json(res, 200, {
|
|
1314
|
+
source,
|
|
1315
|
+
// 只在「live 会话但历史取自文件」时出现:source 仍表示会话是 live 还是纯文件会话。
|
|
1316
|
+
...(fromFile ? { fromFile: true } : {}),
|
|
1317
|
+
messages: page.messages,
|
|
1318
|
+
hasMore: page.hasMore,
|
|
1319
|
+
total: page.total,
|
|
1320
|
+
nextBefore: page.nextBefore,
|
|
1321
|
+
});
|
|
1168
1322
|
}
|
|
1169
1323
|
|
|
1170
1324
|
// GET /v1/sessions/:id/stats (live 走 RPC;非 live 由会话文件消息聚合,绝不 spawn)
|
|
@@ -1176,6 +1330,10 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
1176
1330
|
return json(res, 200, { stats: fileSessionStats(entry) });
|
|
1177
1331
|
}
|
|
1178
1332
|
const data = await live.command("get_session_stats");
|
|
1333
|
+
// 速率字段:tokens 直接用 pi 的聚合,生成耗时长从会话文件里的 assistant `durationMs` 求和
|
|
1334
|
+
// (pi 的 SessionStats 不带耗时)。文件读不到就只靠 tokens 算缓存命中率,tok/s 诚实地 null。
|
|
1335
|
+
const file = live.sessionFile;
|
|
1336
|
+
const rates = sessionRates(file ? readHistory(file) : [], data?.tokens ?? null);
|
|
1179
1337
|
return json(res, 200, {
|
|
1180
1338
|
stats: {
|
|
1181
1339
|
userMessages: data?.userMessages ?? 0,
|
|
@@ -1186,6 +1344,7 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
1186
1344
|
tokens: data?.tokens ?? null,
|
|
1187
1345
|
cost: data?.cost ?? 0,
|
|
1188
1346
|
contextUsage: data?.contextUsage ?? null,
|
|
1347
|
+
...rates,
|
|
1189
1348
|
},
|
|
1190
1349
|
});
|
|
1191
1350
|
}
|
|
@@ -1277,9 +1436,13 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
1277
1436
|
if (streamingBehavior) payload.streamingBehavior = streamingBehavior;
|
|
1278
1437
|
// 扩展命令里可能 await 一个对话框;pi 会等命令处理完才回 prompt 响应,
|
|
1279
1438
|
// 所以这里不能用默认 30s(否则客户端还没看到 ui_request 就收到 409 prompt_rejected)。
|
|
1439
|
+
// session_locked 要原样透出:hub 回合结束会主动让锁,写前重抢;桌面这时已经占着就不能闷成 prompt_rejected。
|
|
1280
1440
|
const data = await session.command("prompt", payload, { timeoutMs: 5 * 60 * 1000 }).catch((err) => {
|
|
1441
|
+
if (err.code === "session_locked") throw new HttpError(409, err.message, "session_locked");
|
|
1281
1442
|
throw new HttpError(409, err.message, "prompt_rejected");
|
|
1282
1443
|
});
|
|
1444
|
+
// 列表标题:未命名会话显示首条用户消息(只在还没有首条时写入)。
|
|
1445
|
+
session.noteUserText(text);
|
|
1283
1446
|
return json(res, 200, { disposition: data?.disposition ?? null });
|
|
1284
1447
|
}
|
|
1285
1448
|
|
|
@@ -1294,8 +1457,11 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
1294
1457
|
const payload = { message: text || "请看这些图片。" };
|
|
1295
1458
|
if (images.length) payload.images = images;
|
|
1296
1459
|
const data = await session.command("follow_up", payload, { timeoutMs: 5 * 60 * 1000 }).catch((err) => {
|
|
1460
|
+
if (err.code === "session_locked") throw new HttpError(409, err.message, "session_locked");
|
|
1297
1461
|
throw new HttpError(409, err.message, "follow_up_rejected");
|
|
1298
1462
|
});
|
|
1463
|
+
// 只有 follow-up 的首条消息也算「会话第一句话」(用户可能直接排队等 agent 说完)。
|
|
1464
|
+
session.noteUserText(text);
|
|
1299
1465
|
return json(res, 200, { disposition: data?.disposition ?? null });
|
|
1300
1466
|
}
|
|
1301
1467
|
|
|
@@ -1561,16 +1727,43 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
1561
1727
|
}
|
|
1562
1728
|
|
|
1563
1729
|
// GET /v1/workspace?path=/home/x/foo (工作区路径校验)
|
|
1730
|
+
// &list=1 时额外返回一级目录列举(移动端路径联想用,见 PLAN mobile-r6 §5):
|
|
1731
|
+
// { path, exists, isDir, home, entries:[{name,isDir}] },只列一级、上限 500、不递归。
|
|
1564
1732
|
if (method === "GET" && url.pathname === "/v1/workspace") {
|
|
1565
1733
|
const raw = url.searchParams.get("path");
|
|
1566
1734
|
if (!raw) throw new HttpError(400, "path is required");
|
|
1567
1735
|
const abs = path.resolve(raw);
|
|
1736
|
+
const wantList = url.searchParams.get("list") === "1";
|
|
1737
|
+
let stat;
|
|
1568
1738
|
try {
|
|
1569
|
-
|
|
1570
|
-
return json(res, 200, { path: abs, exists: true, isDir: stat.isDirectory() });
|
|
1739
|
+
stat = fs.statSync(abs);
|
|
1571
1740
|
} catch {
|
|
1572
|
-
return json(res, 200, { path: abs, exists: false, isDir: false });
|
|
1741
|
+
if (!wantList) return json(res, 200, { path: abs, exists: false, isDir: false });
|
|
1742
|
+
// list=1 缺路径要能被客户端与本机其它 404 区分开:复用 file_not_found 错误码。
|
|
1743
|
+
throw new HttpError(404, `path not found: ${abs}`, "file_not_found");
|
|
1573
1744
|
}
|
|
1745
|
+
const isDir = stat.isDirectory();
|
|
1746
|
+
if (!wantList) return json(res, 200, { path: abs, exists: true, isDir });
|
|
1747
|
+
if (!isDir) return json(res, 200, { path: abs, exists: true, isDir: false, home: HOME, entries: [] });
|
|
1748
|
+
let dirents;
|
|
1749
|
+
try {
|
|
1750
|
+
dirents = fs.readdirSync(abs, { withFileTypes: true });
|
|
1751
|
+
} catch (err) {
|
|
1752
|
+
// 权限/竞态:403 让客户端退化成「本地前缀过滤」,不要用 500 把联想区打成报错。
|
|
1753
|
+
throw new HttpError(403, `cannot list ${abs}: ${err.code ?? err.message}`, "path_not_allowed");
|
|
1754
|
+
}
|
|
1755
|
+
const entries = [];
|
|
1756
|
+
for (const d of dirents) {
|
|
1757
|
+
const entry = { name: d.name, isDir: d.isDirectory() };
|
|
1758
|
+
if (!entry.isDir && d.isSymbolicLink()) {
|
|
1759
|
+
// 符号链接按目标判定,方便 ~/ 下的链接目录也能点进去
|
|
1760
|
+
try { entry.isDir = fs.statSync(path.join(abs, d.name)).isDirectory(); } catch { /* 断链当文件 */ }
|
|
1761
|
+
}
|
|
1762
|
+
entries.push(entry);
|
|
1763
|
+
if (entries.length >= WORKSPACE_LIST_MAX) break;
|
|
1764
|
+
}
|
|
1765
|
+
entries.sort((a, b) => (a.isDir === b.isDir ? a.name.localeCompare(b.name) : a.isDir ? -1 : 1));
|
|
1766
|
+
return json(res, 200, { path: abs, exists: true, isDir: true, home: HOME, entries });
|
|
1574
1767
|
}
|
|
1575
1768
|
|
|
1576
1769
|
// POST /v1/doctor (诊断:能否起 pi、模型表是否可读)
|
|
@@ -1619,8 +1812,8 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
1619
1812
|
registry,
|
|
1620
1813
|
pairing,
|
|
1621
1814
|
token,
|
|
1622
|
-
/**
|
|
1623
|
-
sessionLock:
|
|
1815
|
+
/** 实际使用的锁来源、插件路径与版本面(banner / 测试读它,避免每处各自重新解析)。 */
|
|
1816
|
+
sessionLock: sessionLockInfo(),
|
|
1624
1817
|
/**
|
|
1625
1818
|
* 起监听。**失败必须 reject**(旧实现只挂 listening 回调、没有 error 监听):
|
|
1626
1819
|
* EADDRINUSE 会变成 `server` 上的未处理 'error' 事件,Node 直接打整屏栈崩掉 ——
|
|
@@ -1644,7 +1837,13 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
1644
1837
|
close() {
|
|
1645
1838
|
clearInterval(reaper);
|
|
1646
1839
|
registry.closeAll();
|
|
1647
|
-
return new Promise((resolve) =>
|
|
1840
|
+
return new Promise((resolve) => {
|
|
1841
|
+
server.close(() => resolve());
|
|
1842
|
+
// server.close() 只停 accept,**不**断已有连接:SSE 是长连接,浏览器/手机不主动断,
|
|
1843
|
+
// 回调就永远不来(实测 systemctl restart 卡 30 s、Consumed 才报出来)。
|
|
1844
|
+
// engines 是 node >=22.19,closeAllConnections 一定有(18.2 起)。
|
|
1845
|
+
server.closeAllConnections();
|
|
1846
|
+
});
|
|
1648
1847
|
},
|
|
1649
1848
|
};
|
|
1650
1849
|
}
|
|
@@ -12,20 +12,30 @@
|
|
|
12
12
|
* 3. 只有能证明 owner 已死(pid 没了 / pid 被复用 / 关机重启)才回收,其余一律 fail-open
|
|
13
13
|
* 降级不放宽互斥:抢到手的锁靠 mkdir 原子性保证,不依赖任何进程内状态。
|
|
14
14
|
* 删掉的是插件的额外策略(yield 请求、paseo 轮次、follow 转发),那些不影响互斥。
|
|
15
|
+
*
|
|
16
|
+
* 落盘协议(目录命名 / owner.json 字段 / 判定取值)**不在本文件里定义**:
|
|
17
|
+
* 常量与路径计算统一来自 `lock-protocol.mjs`,与插件的差异由
|
|
18
|
+
* `test/lock-conformance.mjs` 用同一批夹具逐条比对(漂了就红)。
|
|
15
19
|
*/
|
|
16
20
|
import fs from "node:fs";
|
|
17
21
|
import os from "node:os";
|
|
18
22
|
import path from "node:path";
|
|
19
23
|
import crypto from "node:crypto";
|
|
24
|
+
import {
|
|
25
|
+
IDENTITY_KEY,
|
|
26
|
+
canonicalSessionPath,
|
|
27
|
+
lockDirFor as protocolLockDirFor,
|
|
28
|
+
ownerPath,
|
|
29
|
+
resolveAgentDir,
|
|
30
|
+
} from "./lock-protocol.mjs";
|
|
20
31
|
|
|
21
32
|
const HOST = os.hostname();
|
|
22
33
|
|
|
23
34
|
/** 与插件同一个 globalThis 键:真插件与 fallback 同进程加载时不会互相判成「别人」。 */
|
|
24
|
-
const IDENTITY =
|
|
35
|
+
const IDENTITY = IDENTITY_KEY;
|
|
25
36
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
37
|
+
/** 锁根目录的解析口径与协议同源(生产代码在本文件内不再自带一份)。 */
|
|
38
|
+
export { resolveAgentDir };
|
|
29
39
|
|
|
30
40
|
/** 逃生阀:`PI_SESSION_LOCK=off`(插件口径)/ `PI_HUB_NO_SESSION_LOCK=1` 都关锁。 */
|
|
31
41
|
export function enabled() {
|
|
@@ -98,22 +108,12 @@ export function identity() {
|
|
|
98
108
|
return g[IDENTITY];
|
|
99
109
|
}
|
|
100
110
|
|
|
101
|
-
/**
|
|
102
|
-
export
|
|
103
|
-
const canonical = (() => {
|
|
104
|
-
try {
|
|
105
|
-
return fs.realpathSync(sessionFile);
|
|
106
|
-
} catch {
|
|
107
|
-
return path.resolve(sessionFile);
|
|
108
|
-
}
|
|
109
|
-
})();
|
|
110
|
-
const hash = crypto.createHash("sha256").update(canonical).digest("hex");
|
|
111
|
-
return path.join(resolveAgentDir(opts.agentDir), "session-locks", `${hash}.lock`);
|
|
112
|
-
}
|
|
111
|
+
/** 与插件逐字一致的锁目录(协议实现只有 `lock-protocol.mjs` 一份)。 */
|
|
112
|
+
export const lockDirFor = protocolLockDirFor;
|
|
113
113
|
|
|
114
114
|
export function readOwner(dir) {
|
|
115
115
|
try {
|
|
116
|
-
return JSON.parse(fs.readFileSync(
|
|
116
|
+
return JSON.parse(fs.readFileSync(ownerPath(dir), "utf8"));
|
|
117
117
|
} catch {
|
|
118
118
|
return null;
|
|
119
119
|
}
|
|
@@ -161,14 +161,18 @@ export function claim(sessionFile, opts = {}) {
|
|
|
161
161
|
pid: writer,
|
|
162
162
|
startTicks: readStartTicks(writer),
|
|
163
163
|
source: opts.source ?? "pi-hub-fallback",
|
|
164
|
-
|
|
164
|
+
// 与插件同口径:`idleYield` 是给桌面扩展看的「空闲就会让锁」标记(漏了它,桌面只能看到
|
|
165
|
+
// 「被占着」而不知道对面会松手,冲突提示就退化成硬拦)。
|
|
166
|
+
...(opts.idleYield ? { idleYield: true } : {}),
|
|
167
|
+
// 与插件同口径:记规范绝对路径(相对路径在这里就消掉,读方不必知道调用者的 cwd)。
|
|
168
|
+
sessionFile: canonicalSessionPath(sessionFile),
|
|
165
169
|
acquiredAt: new Date().toISOString(),
|
|
166
170
|
};
|
|
167
171
|
// hub 代管时 pid 是 pi 子进程:hub 被 SIGKILL 后子进程也走了,锁随之判死;
|
|
168
172
|
// ownerPid 只为排查「谁认领的」。
|
|
169
173
|
if (me.pid !== writer) owner.ownerPid = me.pid;
|
|
170
174
|
try {
|
|
171
|
-
fs.writeFileSync(
|
|
175
|
+
fs.writeFileSync(ownerPath(dir), `${JSON.stringify(owner, null, 2)}\n`, { mode: 0o600 });
|
|
172
176
|
} catch (error) {
|
|
173
177
|
// 目录建了但 owner.json 写不进去:清掉,别留一把谁也认不出的锁。
|
|
174
178
|
try {
|