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/session-lock.mjs
CHANGED
|
@@ -1,30 +1,67 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 会话锁 ——
|
|
2
|
+
* 会话锁 —— hub 自带一份实现;`pi-session-lock` 插件是**用户显式安装才有的互通增强**,不是依赖。
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* 三种状态(`lockSource`):
|
|
5
|
+
* plugin —— 装了插件且能消费(`CORE_API_VERSION` 匹配 + 7 个函数齐):
|
|
6
|
+
* hub 与桌面 pi / 其它装了插件的进程**共用同一份锁**。
|
|
7
|
+
* fallback —— **默认状态**:没装插件,用 `session-lock-fallback.mjs`。
|
|
8
|
+
* hub 自己(多会话、多端)的互斥照常;只是不与桌面 pi 共享锁。
|
|
9
|
+
* error —— 配置错误:`PI_HUB_SESSION_LOCK_CORE` 指到的不是文件。绝不静默回退(见下)。
|
|
8
10
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
11
|
+
* 两种正常模式落盘协议**完全相同**(`lock-protocol.mjs`),所以「装没装插件」只影响互通面,
|
|
12
|
+
* 不影响互斥面 —— 这也是本模块不再把 fallback 说成「降级/异常」的原因。
|
|
13
|
+
*
|
|
14
|
+
* 加载期不 throw:开箱即用是硬指标(全新机器上 `pi-hub doctor` / `serve` / `status` / `-h`
|
|
15
|
+
* 都必须能起来)。没装插件**不刷屏**(本模块被所有子命令 import),原因与「要不要装」的提示
|
|
16
|
+
* 由 `pi-hub doctor`、`serve` banner 与 `/v1/health.sessionLockInfo` 打出来。
|
|
17
|
+
*
|
|
18
|
+
* 唯一例外是**显式配置错误**:设了 `PI_HUB_SESSION_LOCK_CORE` 却指到不存在的文件/目录时,
|
|
19
|
+
* 用户点名的就是那一份,静默换用内置实现等于「你以为在共享锁,其实没有」。此时:
|
|
20
|
+
* - `explicitPointerError` 给出**一行**原因(`/v1/health.sessionLockInfo.explicitPointerError` 也报);
|
|
21
|
+
* - `serve` 在监听前打这一行并以非 0 退出;`doctor` 打这一行并以非 0 退出;
|
|
22
|
+
* - `claim`/`peek`/`release`/… 被调用时抛同一条错误(绝不静默回退)。
|
|
23
|
+
* 但**仍然不在 import 期 throw** —— 本模块被所有子命令共享,import-time throw 会把与锁无关的
|
|
24
|
+
* `pi-hub token` / `-h` / `status` 一起打死(`test/no-plugin.mjs` 钉住这条不变量)。
|
|
25
|
+
*
|
|
26
|
+
* 自动发现顺序(显式优先,其次各处**文档化**的安装位置;每条都带理由,形状由闸门钉死):
|
|
27
|
+
* 1. `PI_HUB_SESSION_LOCK_CORE`(显式指定;指坏了就是上面的 error 状态,不会落到 2-4)
|
|
28
|
+
* 2. 本包依赖解析(`npm i pi-session-lock` 落在本包 node_modules)
|
|
13
29
|
* 3. 兄弟全局目录 `<prefix>/lib/node_modules/pi-session-lock/core.mjs`(两个包各自全局装)
|
|
14
|
-
* 4.
|
|
15
|
-
*
|
|
30
|
+
* 4. `~/.pi/agent/npm/node_modules/pi-session-lock/core.mjs`(pi 自己的 npm 布局)
|
|
31
|
+
*
|
|
32
|
+
* 兼容口径:插件 0.6.0 起把 `CORE_API_VERSION` 冻结为对外契约(`core.mjs:35` /
|
|
33
|
+
* README「冻结面」:不匹配就自己降级,不要猜算法)。所以这里**先验版本再验函数**:
|
|
34
|
+
* 版本缺失或不等于 `SUPPORTED_CORE_API` 一律不用插件,不拿半残的实现去抢锁。
|
|
16
35
|
*/
|
|
17
36
|
import fs from "node:fs";
|
|
18
37
|
import path from "node:path";
|
|
19
38
|
import { createRequire } from "node:module";
|
|
20
39
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
21
40
|
import { HOME } from "./config.mjs";
|
|
41
|
+
import { REQUIRED_CORE_EXPORTS, SUPPORTED_CORE_API, lockCoreCandidates } from "./lock-protocol.mjs";
|
|
22
42
|
import * as fallbackLock from "./session-lock-fallback.mjs";
|
|
23
43
|
|
|
24
44
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
25
45
|
|
|
26
|
-
/**
|
|
27
|
-
const REQUIRED =
|
|
46
|
+
/** 插件必须给出的函数与可消费版本:常量表在 `lock-protocol.mjs`(与 fallback 同源)。 */
|
|
47
|
+
const REQUIRED = REQUIRED_CORE_EXPORTS;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 显式指针的**配置错误**(一行原因);没有设/指到了文件时为 null。
|
|
51
|
+
*
|
|
52
|
+
* 这是「用户说要用哪份插件」与「hub 到底用了哪份」之间唯一允许失败的地方:
|
|
53
|
+
* 指坏了就报错,不猜下一个候选(猜中了别的安装 = 用户被骗)。
|
|
54
|
+
*/
|
|
55
|
+
export const explicitPointerError = (() => {
|
|
56
|
+
const pointer = process.env.PI_HUB_SESSION_LOCK_CORE;
|
|
57
|
+
if (!pointer) return null;
|
|
58
|
+
try {
|
|
59
|
+
if (fs.statSync(pointer).isFile()) return null;
|
|
60
|
+
} catch {
|
|
61
|
+
/* 不存在:下面统一报错 */
|
|
62
|
+
}
|
|
63
|
+
return `PI_HUB_SESSION_LOCK_CORE 指到的不是一个文件:${pointer}(不会静默回退到内置锁;改对路径,或清掉这个环境变量)`;
|
|
64
|
+
})();
|
|
28
65
|
|
|
29
66
|
function resolveInstalled() {
|
|
30
67
|
const require = createRequire(import.meta.url);
|
|
@@ -39,15 +76,9 @@ function resolveInstalled() {
|
|
|
39
76
|
return null;
|
|
40
77
|
}
|
|
41
78
|
|
|
79
|
+
/** 自动发现候选(`lock-protocol.mjs` 里带每条的理由;**不扫作者本机的仓目录布局**)。 */
|
|
42
80
|
function candidates() {
|
|
43
|
-
return
|
|
44
|
-
process.env.PI_HUB_SESSION_LOCK_CORE,
|
|
45
|
-
resolveInstalled(),
|
|
46
|
-
path.join(HERE, "..", "node_modules", "pi-session-lock", "core.mjs"),
|
|
47
|
-
path.join(HERE, "..", "..", "pi-session-lock", "core.mjs"),
|
|
48
|
-
path.join(HOME, "pi-plugins", "pi-session-lock", "core.mjs"),
|
|
49
|
-
path.join(HOME, ".pi", "agent", "npm", "node_modules", "pi-session-lock", "core.mjs"),
|
|
50
|
-
].filter(Boolean);
|
|
81
|
+
return lockCoreCandidates({ here: HERE, home: HOME, resolved: resolveInstalled() }).map((c) => c.file);
|
|
51
82
|
}
|
|
52
83
|
|
|
53
84
|
function exists(p) {
|
|
@@ -58,32 +89,88 @@ function exists(p) {
|
|
|
58
89
|
}
|
|
59
90
|
}
|
|
60
91
|
|
|
61
|
-
|
|
92
|
+
/** 显式指针失效时**不做任何自动发现**:用户点名的那一份不在,别处的安装不算数。 */
|
|
93
|
+
const foundPath = explicitPointerError ? null : candidates().find(exists) ?? null;
|
|
94
|
+
|
|
95
|
+
/** 插件版本:与 core.mjs 同目录的 package.json(找不到就是 null,上报时按 unknown 处理)。 */
|
|
96
|
+
function readPluginVersion(coreFilePath) {
|
|
97
|
+
try {
|
|
98
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(path.dirname(coreFilePath), "package.json"), "utf8"));
|
|
99
|
+
return typeof pkg.version === "string" ? pkg.version : null;
|
|
100
|
+
} catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 没用插件时的**一行中性原因**(plugin 分支为 null);banner / doctor / /v1/health 都打它。 */
|
|
106
|
+
let unusedReason = null;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 记下「为什么没用插件」。
|
|
110
|
+
*
|
|
111
|
+
* `loud` 只给「装了但用不了」用:那说明用户以为生效了、其实没有,值得打一行。
|
|
112
|
+
* 「没装」是**默认状态**,不打(本模块被所有子命令 import,刷屏等于把正常状态说成故障)。
|
|
113
|
+
*/
|
|
114
|
+
function withoutPlugin(reason, { loud = true } = {}) {
|
|
115
|
+
unusedReason = reason;
|
|
116
|
+
if (loud) console.error(`会话锁:没有用上 pi-session-lock 插件 —— ${reason}`);
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
62
119
|
|
|
63
120
|
async function loadPlugin() {
|
|
64
|
-
if (!foundPath) return
|
|
121
|
+
if (!foundPath) return withoutPlugin("没有找到 pi-session-lock 插件(默认用内置锁)", { loud: false });
|
|
65
122
|
let mod;
|
|
66
123
|
try {
|
|
67
124
|
mod = await import(pathToFileURL(foundPath).href);
|
|
68
125
|
} catch (err) {
|
|
69
|
-
|
|
70
|
-
return null;
|
|
126
|
+
return withoutPlugin(`${foundPath} 加载失败:${err.message}`);
|
|
71
127
|
}
|
|
72
|
-
const
|
|
73
|
-
if (
|
|
74
|
-
|
|
75
|
-
|
|
128
|
+
const api = mod.CORE_API_VERSION;
|
|
129
|
+
if (typeof api !== "number") {
|
|
130
|
+
return withoutPlugin(`${foundPath} 缺少 CORE_API_VERSION(hub 支持 ${SUPPORTED_CORE_API})`);
|
|
131
|
+
}
|
|
132
|
+
if (api !== SUPPORTED_CORE_API) {
|
|
133
|
+
return withoutPlugin(`${foundPath} 的 CORE_API_VERSION=${api} 与 hub 支持的 ${SUPPORTED_CORE_API} 不兼容`);
|
|
76
134
|
}
|
|
135
|
+
const missing = REQUIRED.filter((name) => typeof mod[name] !== "function");
|
|
136
|
+
if (missing.length) return withoutPlugin(`${foundPath} 缺少 ${missing.join(", ")}`);
|
|
77
137
|
return mod;
|
|
78
138
|
}
|
|
79
139
|
|
|
140
|
+
/**
|
|
141
|
+
* 显式指针坏掉时的替身:每个锁操作都抛同一行错误。
|
|
142
|
+
* 用内置实现顶上就是「静默回退」——用户以为在和桌面 pi 共享锁,其实没有。
|
|
143
|
+
*/
|
|
144
|
+
function refusingImplementation() {
|
|
145
|
+
const refused = {};
|
|
146
|
+
for (const name of REQUIRED) {
|
|
147
|
+
refused[name] = () => {
|
|
148
|
+
throw new Error(`会话锁不可用:${explicitPointerError}`);
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
return refused;
|
|
152
|
+
}
|
|
153
|
+
|
|
80
154
|
const plugin = await loadPlugin();
|
|
81
|
-
const impl = plugin ?? fallbackLock;
|
|
155
|
+
const impl = explicitPointerError ? refusingImplementation() : plugin ?? fallbackLock;
|
|
82
156
|
|
|
83
|
-
/**
|
|
84
|
-
export const lockSource = plugin ? "plugin" : "fallback";
|
|
85
|
-
/** 插件 core.mjs
|
|
157
|
+
/** 实际使用的锁来源:"plugin" | "fallback" | "error"(serve banner / doctor / /v1/health 都打它)。 */
|
|
158
|
+
export const lockSource = explicitPointerError ? "error" : plugin ? "plugin" : "fallback";
|
|
159
|
+
/** 插件 core.mjs 的绝对路径;没用插件时为 null(内置实现的路径就是本仓 src/session-lock-fallback.mjs)。 */
|
|
86
160
|
export const corePath = plugin ? foundPath : null;
|
|
161
|
+
/** 插件 package.json 的 version;没用插件时 null(内置实现没有版本)。 */
|
|
162
|
+
export const pluginVersion = plugin ? readPluginVersion(foundPath) : null;
|
|
163
|
+
/** 插件冻结的 core API 版本;没用插件时 null(`/v1/health` 用 null 而不是报错)。 */
|
|
164
|
+
export const coreApiVersion = plugin ? plugin.CORE_API_VERSION : null;
|
|
165
|
+
/** 没用插件的原因(一行);plugin 分支为 null。显式指针失效时就是那条配置错误。 */
|
|
166
|
+
export const lockReason = plugin ? null : explicitPointerError ?? unusedReason;
|
|
167
|
+
/** 一行「要不要装插件」的可操作提示;plugin 与「显式指针配错」两种情况下为 null(后者看 explicitPointerError)。 */
|
|
168
|
+
export const lockHint =
|
|
169
|
+
plugin || explicitPointerError
|
|
170
|
+
? null
|
|
171
|
+
: "内置锁照常工作(hub 内多端互斥不变);要与桌面 pi 共用同一份锁:npm i -g pi-session-lock,或 PI_HUB_SESSION_LOCK_CORE=/abs/path/core.mjs";
|
|
172
|
+
/** hub 支持并可消费的 core API 版本(上报用;插件版本不等于它时不用插件)。 */
|
|
173
|
+
export const supportedCoreApi = SUPPORTED_CORE_API;
|
|
87
174
|
|
|
88
175
|
export const identity = impl.identity;
|
|
89
176
|
export const lockDirFor = impl.lockDirFor;
|
|
@@ -92,6 +179,8 @@ export const claim = impl.claim;
|
|
|
92
179
|
export const release = impl.release;
|
|
93
180
|
export const classify = impl.classify;
|
|
94
181
|
export const readOwner = impl.readOwner;
|
|
95
|
-
/**
|
|
182
|
+
/** 判活能力(插件若没导出就报 plugin,doctor 只用来提示平台差异)。 */
|
|
96
183
|
export const capabilities =
|
|
97
|
-
typeof impl.capabilities === "function"
|
|
184
|
+
typeof impl.capabilities === "function"
|
|
185
|
+
? impl.capabilities
|
|
186
|
+
: () => ({ platform: process.platform, note: explicitPointerError });
|
package/src/sessions-index.mjs
CHANGED
|
@@ -3,7 +3,13 @@ import path from "node:path";
|
|
|
3
3
|
import { SESSIONS_DIR } from "./config.mjs";
|
|
4
4
|
|
|
5
5
|
const HEAD_BYTES = 64 * 1024;
|
|
6
|
+
/** 判定 `lastStatus` 只读文件尾部这么多字节:一轮的收尾记录一定在最后,无需整文件扫描。 */
|
|
7
|
+
const TAIL_BYTES = 64 * 1024;
|
|
8
|
+
/** 尾窗口里没有完整 message 行时(最后一条记录本身 >64KB)重试一次的窗口。 */
|
|
9
|
+
const TAIL_RETRY_BYTES = 1024 * 1024;
|
|
6
10
|
const CACHE_TTL_MS = 3000;
|
|
11
|
+
/** 会话列表 `preview` 的截断长度:客户端把它当未命名会话的标题,160 字够一眼认出。 */
|
|
12
|
+
export const PREVIEW_MAX = 160;
|
|
7
13
|
|
|
8
14
|
/** @type {{at:number, entries:any[]}} */
|
|
9
15
|
let cache = { at: 0, entries: [] };
|
|
@@ -49,19 +55,92 @@ function parseHead(text) {
|
|
|
49
55
|
.filter((b) => b?.type === "text")
|
|
50
56
|
.map((b) => b.text)
|
|
51
57
|
.join("\n");
|
|
52
|
-
if (text) meta.preview = text.slice(0,
|
|
58
|
+
if (text) meta.preview = text.slice(0, PREVIEW_MAX);
|
|
53
59
|
if (meta.name && meta.id) break;
|
|
54
60
|
}
|
|
55
61
|
}
|
|
56
62
|
return meta;
|
|
57
63
|
}
|
|
58
64
|
|
|
65
|
+
function readTail(file, size, window = TAIL_BYTES) {
|
|
66
|
+
const start = Math.max(0, size - window);
|
|
67
|
+
const length = size - start;
|
|
68
|
+
if (length <= 0) return { text: "", truncated: false };
|
|
69
|
+
const fd = fs.openSync(file, "r");
|
|
70
|
+
try {
|
|
71
|
+
const buf = Buffer.alloc(length);
|
|
72
|
+
const n = fs.readSync(fd, buf, 0, length, start);
|
|
73
|
+
return { text: buf.subarray(0, n).toString("utf8"), truncated: start > 0 };
|
|
74
|
+
} finally {
|
|
75
|
+
fs.closeSync(fd);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** assistant 消息是否以工具调用收尾(本轮还没收口:工具结果或下一轮还没落盘)。 */
|
|
80
|
+
function hasToolCall(content) {
|
|
81
|
+
if (!Array.isArray(content)) return false;
|
|
82
|
+
return content.some((b) => b?.type === "toolCall");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 一条 `type=message` 记录对应的会话状态(`running` 只能由 live 状态给出,见 `mergedSessions`)。
|
|
87
|
+
* @param {any} message 会话文件里的 `message` 字段
|
|
88
|
+
* @returns {"done"|"aborted"|"error"}
|
|
89
|
+
*/
|
|
90
|
+
function statusOfMessage(message) {
|
|
91
|
+
const role = message?.role;
|
|
92
|
+
if (role === "assistant") {
|
|
93
|
+
const stop = message.stopReason;
|
|
94
|
+
if (stop === "error") return "error";
|
|
95
|
+
if (stop === "aborted") return "aborted";
|
|
96
|
+
// stopReason=toolUse 或带 toolCall 块:这一轮在等工具结果,没有收尾记录 ⇒ 进程被杀了。
|
|
97
|
+
if (stop === "toolUse" || hasToolCall(message.content)) return "error";
|
|
98
|
+
// end_turn / stop / max_tokens 等正常结束
|
|
99
|
+
return "done";
|
|
100
|
+
}
|
|
101
|
+
if (role === "toolResult") return "error"; // 工具跑完但助手没回话:中途退出
|
|
102
|
+
if (role === "user") return "error"; // 用户发完就断了,这一轮没开始/没收尾
|
|
103
|
+
return "done";
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 从文件尾部判定 `lastStatus`:取最后一条完整的 `type=message` 记录。
|
|
108
|
+
* 坏行/半行(并发写入被截断)跳过;空会话(没有 message)⇒ `done`。
|
|
109
|
+
* 截断窗口里一条完整 message 都没找到(最后一条记录本身超过窗口)⇒ `null`,调用方换大窗口重试。
|
|
110
|
+
* @param {{text:string, truncated:boolean}} tail `readTail` 的结果
|
|
111
|
+
* @returns {"done"|"aborted"|"error"|null}
|
|
112
|
+
*/
|
|
113
|
+
function parseTailStatus(tail) {
|
|
114
|
+
const lines = tail.text.split("\n");
|
|
115
|
+
// 尾部 64KB 从行中间切进来时,第一行必然不完整,丢掉(与 readHistory 丢弃半行同口径)。
|
|
116
|
+
if (tail.truncated) lines.shift();
|
|
117
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
118
|
+
const line = lines[i].trim();
|
|
119
|
+
if (!line) continue;
|
|
120
|
+
let rec;
|
|
121
|
+
try {
|
|
122
|
+
rec = JSON.parse(line);
|
|
123
|
+
} catch {
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (rec?.type !== "message" || !rec.message) continue;
|
|
127
|
+
return statusOfMessage(rec.message);
|
|
128
|
+
}
|
|
129
|
+
// 窗口被截断却一行 message 都没解析出来(最后一条记录 >窗口):不知道就说不知道,
|
|
130
|
+
// 别把 aborted/error 画成 done(R2 用 100KB 尾记录复现过)。
|
|
131
|
+
return tail.truncated ? null : "done";
|
|
132
|
+
}
|
|
133
|
+
|
|
59
134
|
function readFileMeta(file, stat) {
|
|
60
135
|
const cached = fileCache.get(file);
|
|
61
136
|
if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.meta;
|
|
62
|
-
let meta = { id: null, cwd: null, name: null, createdAt: null, preview: null, model: null };
|
|
137
|
+
let meta = { id: null, cwd: null, name: null, createdAt: null, preview: null, model: null, lastStatus: "done" };
|
|
63
138
|
try {
|
|
64
139
|
meta = parseHead(readHead(file));
|
|
140
|
+
// 先 64KB,未命中再 1MB;两次都没有完整 message 行才退回 done(空会话/超长单条记录)。
|
|
141
|
+
meta.lastStatus = parseTailStatus(readTail(file, stat.size, TAIL_BYTES))
|
|
142
|
+
?? parseTailStatus(readTail(file, stat.size, TAIL_RETRY_BYTES))
|
|
143
|
+
?? "done";
|
|
65
144
|
} catch {
|
|
66
145
|
// 忽略损坏/被并发重写的文件
|
|
67
146
|
}
|
|
@@ -69,9 +148,46 @@ function readFileMeta(file, stat) {
|
|
|
69
148
|
return meta;
|
|
70
149
|
}
|
|
71
150
|
|
|
151
|
+
/**
|
|
152
|
+
* 单个会话文件里首条用户消息的文本(截断 `PREVIEW_MAX`);文件不存在/坏行/还没有用户消息 → null。
|
|
153
|
+
* 续会话(resume)时 `LiveSession` 用它补 `firstUserText`:pi 不会重放首条用户消息。
|
|
154
|
+
* @param {string} file
|
|
155
|
+
* @returns {string|null}
|
|
156
|
+
*/
|
|
157
|
+
export function readFilePreview(file) {
|
|
158
|
+
try {
|
|
159
|
+
return parseHead(readHead(file)).preview ?? null;
|
|
160
|
+
} catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 会话列表行的唯一排序口径:`updatedAt` 降序,同 timestamp 用 `id` 升序兜底。
|
|
167
|
+
* 稳定且确定:两个 hub 请求之间同 timestamp 的行不会互换位置(客户端列表不会抖)。
|
|
168
|
+
* 原地排序并返回同一个数组(调用方持有 rows 的所有权)。
|
|
169
|
+
* @template {{id:string, updatedAt?:string|null}} T
|
|
170
|
+
* @param {T[]} rows
|
|
171
|
+
* @returns {T[]}
|
|
172
|
+
*/
|
|
173
|
+
export function sortSessionRows(rows) {
|
|
174
|
+
const at = (row) => {
|
|
175
|
+
const ms = Date.parse(row?.updatedAt ?? "");
|
|
176
|
+
return Number.isFinite(ms) ? ms : Number.NEGATIVE_INFINITY;
|
|
177
|
+
};
|
|
178
|
+
return rows.sort((a, b) => {
|
|
179
|
+
const diff = at(b) - at(a);
|
|
180
|
+
if (diff) return diff;
|
|
181
|
+
if (a.id === b.id) return 0;
|
|
182
|
+
return a.id < b.id ? -1 : 1;
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
72
186
|
/**
|
|
73
187
|
* 列出会话库里的一级会话文件(不追 subagent 嵌套目录)。
|
|
74
|
-
*
|
|
188
|
+
* 每行带 `lastStatus`(`running|done|aborted|error`):这里只能从文件尾部判出后三种,
|
|
189
|
+
* `running` 由 `mergedSessions` 拿 live 状态补;缓存键仍是 mtime+size(同一文件不改不动)。
|
|
190
|
+
* @param {{limit?:number, force?:boolean}} [opts]
|
|
75
191
|
*/
|
|
76
192
|
export function listSessions(opts = {}) {
|
|
77
193
|
const limit = opts.limit ?? 200;
|
|
@@ -112,6 +228,8 @@ export function listSessions(opts = {}) {
|
|
|
112
228
|
preview: meta.preview,
|
|
113
229
|
model: meta.model,
|
|
114
230
|
createdAt: meta.createdAt,
|
|
231
|
+
// 行尾三态图标(进行中/完成未读/异常退出)只有 live 行能判「进行中」,磁盘行看文件尾部。
|
|
232
|
+
lastStatus: meta.lastStatus ?? "done",
|
|
115
233
|
updatedAt: new Date(stat.mtimeMs).toISOString(),
|
|
116
234
|
updatedAtMs: stat.mtimeMs,
|
|
117
235
|
file,
|
|
@@ -120,7 +238,7 @@ export function listSessions(opts = {}) {
|
|
|
120
238
|
});
|
|
121
239
|
}
|
|
122
240
|
}
|
|
123
|
-
entries
|
|
241
|
+
sortSessionRows(entries);
|
|
124
242
|
cache = { at: now, entries };
|
|
125
243
|
return entries.slice(0, limit);
|
|
126
244
|
}
|
|
@@ -162,7 +280,12 @@ export function readHistory(file, opts = {}) {
|
|
|
162
280
|
for (const b of blocks) {
|
|
163
281
|
if (b?.type === "text" && b.text) textParts.push(b.text);
|
|
164
282
|
else if (b?.type === "thinking" && b.thinking) thinkingParts.push(b.thinking);
|
|
165
|
-
else if (b?.type === "toolCall")
|
|
283
|
+
else if (b?.type === "toolCall") {
|
|
284
|
+
// pi 落盘(以及 RPC get_messages)里的工具参数键是 `arguments`,
|
|
285
|
+
// 以前只读 `b.args` ⇒ 历史回放的 toolCalls[].args 恒为 null,网页端展开工具卡
|
|
286
|
+
// 只剩「输出」段看不到命令本体(R5 实测)。两条键都收,`args` 留着兼容旧夹具。
|
|
287
|
+
toolCalls.push({ id: b.id, name: b.name, args: b.arguments ?? b.args ?? null });
|
|
288
|
+
}
|
|
166
289
|
}
|
|
167
290
|
out.push({
|
|
168
291
|
entryId: rec.id,
|
|
@@ -173,6 +296,9 @@ export function readHistory(file, opts = {}) {
|
|
|
173
296
|
thinking: thinkingParts.join("\n"),
|
|
174
297
|
// toolResult 靠它并回对应工具卡片(多工具轮次里只看「上一条 tool」会堆错位置)。
|
|
175
298
|
toolCallId: m.toolCallId ?? null,
|
|
299
|
+
// toolResult 行才有的字段:客户端拿它显示「完成 · 耗时」与错误色,没有就回退到「完成」。
|
|
300
|
+
toolName: m.toolName ?? null,
|
|
301
|
+
isError: m.isError === true,
|
|
176
302
|
toolCalls,
|
|
177
303
|
ts: m.timestamp ? new Date(m.timestamp).toISOString() : rec.timestamp,
|
|
178
304
|
usage: m.usage ?? null,
|
|
@@ -183,4 +309,48 @@ export function readHistory(file, opts = {}) {
|
|
|
183
309
|
});
|
|
184
310
|
}
|
|
185
311
|
return limit > 0 ? out.slice(-limit) : out;
|
|
186
|
-
}
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* 历史分页切片(「更早一页」)。live 与文件两条来源共用同一份语义。
|
|
315
|
+
*
|
|
316
|
+
* - `before` 缺省:返回**最新** `limit` 条(`limit<=0` = 全部,向后兼容老客户端)。
|
|
317
|
+
* - `before=<entryId>`:返回该条之前(更旧)的一页,找不到该 entryId 抛 `code=stale_cursor`
|
|
318
|
+
* (客户端会话被压缩/分叉后游标会失效,必须能区分「没有更早的了」和「游标错了」)。
|
|
319
|
+
*
|
|
320
|
+
* 页边界一律**对齐到 user 消息**(一轮的起点):
|
|
321
|
+
* 客户端按页独立解析历史,若一页从 `toolResult` 中间开始,那半轮的工具输出会变成孤立卡片、
|
|
322
|
+
* 对应的 `toolCalls` 在上一页又只有输入没有输出(真机可见)。因此 `start` 只会往「更旧」方向
|
|
323
|
+
* 退到一个 user 消息;代价是一页可能略多于 `limit` 条(单个超长轮次会整轮返回),这是有意的。
|
|
324
|
+
*
|
|
325
|
+
* @param {Array<{role?:string, entryId?:string|null}>} messages 按时间升序的规整历史
|
|
326
|
+
* @param {{limit?:number, before?:string|null}} [opts]
|
|
327
|
+
* @returns {{messages:Array, hasMore:boolean, total:number, nextBefore:string|null}}
|
|
328
|
+
*/
|
|
329
|
+
export function sliceHistoryPage(messages, opts = {}) {
|
|
330
|
+
const all = Array.isArray(messages) ? messages : [];
|
|
331
|
+
const total = all.length;
|
|
332
|
+
const limit = Number(opts.limit ?? 0);
|
|
333
|
+
const before = opts.before == null || opts.before === "" ? null : String(opts.before);
|
|
334
|
+
let end = total;
|
|
335
|
+
if (before != null) {
|
|
336
|
+
const idx = all.findIndex((m) => m && m.entryId === before);
|
|
337
|
+
if (idx < 0) {
|
|
338
|
+
const err = new Error(`unknown history cursor ${before}`);
|
|
339
|
+
err.code = "stale_cursor";
|
|
340
|
+
throw err;
|
|
341
|
+
}
|
|
342
|
+
end = idx;
|
|
343
|
+
}
|
|
344
|
+
if (limit <= 0) return { messages: all.slice(0, end), hasMore: false, total, nextBefore: null };
|
|
345
|
+
let start = Math.max(0, end - limit);
|
|
346
|
+
while (start > 0 && all[start]?.role !== "user") start--;
|
|
347
|
+
const page = all.slice(start, end);
|
|
348
|
+
return {
|
|
349
|
+
messages: page,
|
|
350
|
+
hasMore: start > 0,
|
|
351
|
+
total,
|
|
352
|
+
// 客户端下一次 `before`:本页最旧一条的 entryId;为 null 说明这条没有 id(老会话),
|
|
353
|
+
// 客户端必须退回「全量重拉」,不能拿 null 当游标。
|
|
354
|
+
nextBefore: start > 0 ? (page[0]?.entryId ?? null) : null,
|
|
355
|
+
};
|
|
356
|
+
}
|
package/src/static.mjs
CHANGED
|
@@ -39,7 +39,13 @@ const EXACT_ROUTES = new Map([
|
|
|
39
39
|
["/", "index.html"],
|
|
40
40
|
["/index.html", "index.html"],
|
|
41
41
|
["/app.js", "app.js"],
|
|
42
|
+
["/markdown.js", "markdown.js"],
|
|
43
|
+
["/model.js", "model.js"],
|
|
44
|
+
// 网页端的纯逻辑(贴底判定 / 草稿键)单独成模块,app.js import 它,node 单测也 import 它
|
|
45
|
+
["/compose.js", "compose.js"],
|
|
42
46
|
["/style.css", "style.css"],
|
|
47
|
+
// 教程页(pi-hub tutorial 的网页版):静态、免鉴权、不含令牌,可以直接发给手机看。
|
|
48
|
+
["/tutorial.html", "tutorial.html"],
|
|
43
49
|
["/manifest.webmanifest", "manifest.webmanifest"],
|
|
44
50
|
["/sw.js", "sw.js"],
|
|
45
51
|
]);
|
package/systemd/pi-hub.service
CHANGED
|
@@ -9,6 +9,8 @@ WorkingDirectory=%h/pi-hub-suite/pi-hub
|
|
|
9
9
|
ExecStart=%h/.local/share/fnm/node-versions/v24.22.0/installation/bin/node %h/pi-hub-suite/pi-hub/bin/pi-hub.mjs serve
|
|
10
10
|
Restart=on-failure
|
|
11
11
|
RestartSec=3
|
|
12
|
+
# 停止上限:hub 收到 SIGTERM 会自己断连接并退(3 s 硬闸);卡住就是真有问题,别让 systemd 干等 90 s
|
|
13
|
+
TimeoutStopSec=15
|
|
12
14
|
# systemd 默认 PATH 里没有 ~/.pi/agent/bin(重启后 spawn pi ENOENT),显式补上
|
|
13
15
|
Environment=PATH=%h/.pi/agent/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
|
14
16
|
Environment=PI_HUB_PORT=6768
|