pi-web-ui 0.87.2 → 0.89.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +66 -1
  2. package/bin/pi-web-ui.mjs +463 -0
  3. package/dist/server/agent-service.js +419 -45
  4. package/dist/server/attachments.js +39 -0
  5. package/dist/server/client-state.js +22 -0
  6. package/dist/server/conversation-read-tool.js +325 -0
  7. package/dist/server/dsh/dsh-agent-service.js +32 -3
  8. package/dist/server/files-service.js +103 -0
  9. package/dist/server/host-metrics.js +59 -0
  10. package/dist/server/index.js +381 -8
  11. package/dist/server/model-admin.js +285 -36
  12. package/dist/server/plugin-facilities.js +115 -2
  13. package/dist/server/plugin-llm.js +129 -0
  14. package/dist/server/plugin-permissions.js +176 -0
  15. package/dist/server/plugin-schedule.js +211 -0
  16. package/dist/server/plugins.js +1005 -68
  17. package/dist/server/scheduler-tasks.js +405 -0
  18. package/dist/server/settings-service.js +8 -1
  19. package/dist/server/terminals.js +14 -1
  20. package/dist/server/tool-manager.js +6 -1
  21. package/dist/server/update-check.js +249 -19
  22. package/extensions/webui.ts +9 -2
  23. package/package.json +4 -2
  24. package/plugin-sdk/README.md +127 -0
  25. package/plugin-sdk/index.d.ts +454 -0
  26. package/plugin-sdk/index.mjs +545 -0
  27. package/plugin-sdk/package.json +9 -0
  28. package/plugins/catalog.json +11 -2
  29. package/web/dist/assets/TerminalPanel-BOUmN3uu.js +6 -0
  30. package/web/dist/assets/TerminalPanel-DOrYoP_4.css +32 -0
  31. package/web/dist/assets/index-3XU67qMh.js +376 -0
  32. package/web/dist/assets/index-B-gdvWtW.css +10 -0
  33. package/web/dist/index.html +2 -3
  34. package/web/dist/assets/index-CYuoen3I.js +0 -374
  35. package/web/dist/assets/index-F86qWlJy.css +0 -41
@@ -0,0 +1,176 @@
1
+ /**
2
+ * 插件能力动态授权表(host.requestPermission 的底层)。
3
+ *
4
+ * 定位:manifest.permissions 管“有没有这个能力族”(静态、装时定),这张表管
5
+ * “运行时的具体范围”(动态、用户随时批):
6
+ * - net:在 manifest netAllowlist 之外,用户额外批准的主机(免改 manifest 重装);
7
+ * - llm:用户批准的模型作用域(空 = 不限模型),花 token 前插件可主动来问一次。
8
+ * 基础族未声明时 requestPermission 直接回 false(不弹框)——与 requestAccess
9
+ * 要求 fs:read 同口径,fail-closed。
10
+ *
11
+ * 两层存储:
12
+ * - 磁盘 `<dataDir>/plugin-permissions.json`(记住的授权,设置面板可审计/撤销);
13
+ * - 内存 session 授权(仅本次运行,进程结束即失)。
14
+ * 读坏/形状不对当空表,且不在读路径回写;只有真正变更的写才落盘(tmp+rename 原子写)。
15
+ */
16
+ import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
17
+ import { dirname, join } from "node:path";
18
+ /** 主机匹配(与 manifest netAllowlist 同口径):全等或点号后缀。纯函数,单测覆盖。 */
19
+ export function permissionHostMatches(hostname, entry) {
20
+ const h = String(hostname ?? "").toLowerCase();
21
+ const e = String(entry ?? "")
22
+ .toLowerCase()
23
+ .trim();
24
+ if (!h || !e)
25
+ return false;
26
+ return h === e || h.endsWith(`.${e}`);
27
+ }
28
+ function normalizeHosts(hosts) {
29
+ if (!Array.isArray(hosts))
30
+ return undefined;
31
+ const out = [
32
+ ...new Set(hosts.filter((x) => typeof x === "string" && x.trim() !== "").map((x) => x.trim().toLowerCase())),
33
+ ];
34
+ return out.length > 0 ? out.slice(0, 32) : undefined;
35
+ }
36
+ function normalizeModels(models) {
37
+ if (!Array.isArray(models))
38
+ return undefined;
39
+ const out = [
40
+ ...new Set(models.filter((x) => typeof x === "string" && x.includes("/")).map((x) => x.trim())),
41
+ ];
42
+ return out.length > 0 ? out.slice(0, 32) : undefined;
43
+ }
44
+ export class PluginPermissionStore {
45
+ dataDir;
46
+ sessionGrants = [];
47
+ constructor(dataDir) {
48
+ this.dataDir = dataDir;
49
+ }
50
+ file() {
51
+ return join(this.dataDir, "plugin-permissions.json");
52
+ }
53
+ read() {
54
+ try {
55
+ const parsed = JSON.parse(readFileSync(this.file(), "utf8"));
56
+ if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.grants))
57
+ return { v: 1, grants: [] };
58
+ return { v: 1, grants: parsed.grants };
59
+ }
60
+ catch {
61
+ return { v: 1, grants: [] };
62
+ }
63
+ }
64
+ write(grants) {
65
+ try {
66
+ mkdirSync(dirname(this.file()), { recursive: true });
67
+ const tmp = `${this.file()}.tmp-${process.pid}`;
68
+ writeFileSync(tmp, JSON.stringify({ v: 1, grants }));
69
+ renameSync(tmp, this.file());
70
+ }
71
+ catch (err) {
72
+ console.error(`[plugin-permissions] persist failed (${this.file()}):`, err);
73
+ }
74
+ }
75
+ static validId(id) {
76
+ return /^[A-Za-z0-9_-]+$/.test(id);
77
+ }
78
+ /** 是否有有效授权(磁盘 + 内存;host/model 命中才算)。 */
79
+ has(pluginId, family, scope) {
80
+ if (!PluginPermissionStore.validId(pluginId))
81
+ return false;
82
+ const all = [...this.read().grants, ...this.sessionGrants];
83
+ return all.some((g) => {
84
+ if (g.pluginId !== pluginId || g.family !== family)
85
+ return false;
86
+ if (family === "net") {
87
+ const host = String(scope?.host ?? "").toLowerCase();
88
+ if (!host || !g.hosts)
89
+ return false;
90
+ return g.hosts.some((entry) => permissionHostMatches(host, entry));
91
+ }
92
+ if (family === "llm" && scope?.model) {
93
+ if (!g.models || g.models.length === 0)
94
+ return true; // 不限模型
95
+ return g.models.includes(scope.model);
96
+ }
97
+ return true;
98
+ });
99
+ }
100
+ /** 写入一条授权(remember=true 落盘,false 只记内存)。同插件同族同范围覆盖旧条。 */
101
+ grant(pluginId, family, opts) {
102
+ if (!PluginPermissionStore.validId(pluginId))
103
+ throw new Error(`非法插件 id:${pluginId}`);
104
+ if (family !== "net" && family !== "llm")
105
+ throw new Error(`不支持的能力族:${String(family)}`);
106
+ const grant = {
107
+ pluginId,
108
+ family,
109
+ ...(family === "net" && normalizeHosts(opts?.hosts) ? { hosts: normalizeHosts(opts?.hosts) } : {}),
110
+ ...(family === "llm" && normalizeModels(opts?.models) ? { models: normalizeModels(opts?.models) } : {}),
111
+ ...(typeof opts?.reason === "string" && opts.reason.trim() ? { reason: opts.reason.trim().slice(0, 200) } : {}),
112
+ grantedAt: Date.now(),
113
+ };
114
+ if (opts?.remember === true) {
115
+ const grants = this.read().grants.filter((g) => !(g.pluginId === pluginId && g.family === family && sameScope(g, grant)));
116
+ grants.push(grant);
117
+ this.write(grants);
118
+ }
119
+ else {
120
+ this.sessionGrants = this.sessionGrants.filter((g) => !(g.pluginId === pluginId && g.family === family && sameScope(g, grant)));
121
+ this.sessionGrants.push(grant);
122
+ }
123
+ }
124
+ /** 撤销:都不给 = 清空整表;返回删掉的条数(磁盘 + 内存)。 */
125
+ revoke(pluginId, family, scope) {
126
+ let removed = 0;
127
+ const drop = (g) => {
128
+ if (pluginId && g.pluginId !== pluginId)
129
+ return false;
130
+ if (family && g.family !== family)
131
+ return false;
132
+ if (scope?.host && !(g.hosts ?? []).some((entry) => permissionHostMatches(scope.host, entry)))
133
+ return false;
134
+ if (scope?.model && g.models && g.models.length > 0 && !g.models.includes(scope.model))
135
+ return false;
136
+ return true;
137
+ };
138
+ const disk = this.read().grants;
139
+ const kept = disk.filter((g) => !drop(g));
140
+ if (kept.length !== disk.length) {
141
+ removed += disk.length - kept.length;
142
+ this.write(kept);
143
+ }
144
+ const before = this.sessionGrants.length;
145
+ this.sessionGrants = this.sessionGrants.filter((g) => !drop(g));
146
+ removed += before - this.sessionGrants.length;
147
+ return removed;
148
+ }
149
+ /** 模型是否在批准作用域内:无 llm 授权 → 不限(调用方先判声明);有授权时,
150
+ * 至少一条「不限模型」或命中模型才放行。空 model(走默认模型)不卡。 */
151
+ modelAllowed(pluginId, model) {
152
+ if (!PluginPermissionStore.validId(pluginId))
153
+ return false;
154
+ const scoped = [...this.read().grants, ...this.sessionGrants].filter((g) => g.pluginId === pluginId && g.family === "llm");
155
+ if (scoped.length === 0)
156
+ return true;
157
+ if (!model)
158
+ return true;
159
+ return scoped.some((g) => !g.models || g.models.length === 0 || g.models.includes(model));
160
+ }
161
+ /** 全量快照(设置面板审计用;session 授权带 session:true 标记)。 */
162
+ list() {
163
+ return [
164
+ ...this.read().grants.map((g) => ({ ...g })),
165
+ ...this.sessionGrants.map((g) => ({ ...g, session: true })),
166
+ ];
167
+ }
168
+ }
169
+ /** 同范围判定(撤销/覆盖时去重用;范围字段都为空 = 同族整单)。 */
170
+ function sameScope(a, b) {
171
+ const ah = [...(a.hosts ?? [])].sort().join(",");
172
+ const bh = [...(b.hosts ?? [])].sort().join(",");
173
+ const am = [...(a.models ?? [])].sort().join(",");
174
+ const bm = [...(b.models ?? [])].sort().join(",");
175
+ return ah === bh && am === bm;
176
+ }
@@ -0,0 +1,211 @@
1
+ /**
2
+ * 插件定时任务的 cron 解析与持久化(host.schedule 的底层,server/plugins.ts 调用)。
3
+ *
4
+ * 两部分:
5
+ * 1. 全 5 字段 cron(分 时 日 月 周):`"*"` / `"*\/n"` / `"a-b"` / `"a-b/n"` /
6
+ * `"a,b,c"` / 单数字;月/周支持英文名(jan/dec 不分大小写,sun..sat,7 视作 0)。
7
+ * 日-周按标准 cron OR 语义(都受限取并集,一侧 `*` 时另一侧说了算)。
8
+ * 时间一律按**服务器本地时区**算(文档写死,不做 TZ 配置)。
9
+ * 2. 持久记录 `<pluginDir>/schedules.json`:只存声明(spec/catchUp/label)+
10
+ * 上次触发 lastRun;fn 回调永远由插件代码在 activate 里重给(重启后重建)。
11
+ * 坏文件当空表(不回写,避免一次磁盘抖动清空全部定时)。
12
+ */
13
+ import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ const MONTH_NAMES = {
16
+ jan: 1,
17
+ feb: 2,
18
+ mar: 3,
19
+ apr: 4,
20
+ may: 5,
21
+ jun: 6,
22
+ jul: 7,
23
+ aug: 8,
24
+ sep: 9,
25
+ oct: 10,
26
+ nov: 11,
27
+ dec: 12,
28
+ };
29
+ const DOW_NAMES = {
30
+ sun: 0,
31
+ mon: 1,
32
+ tue: 2,
33
+ wed: 3,
34
+ thu: 4,
35
+ fri: 5,
36
+ sat: 6,
37
+ };
38
+ /** 单字段解析 → 升序去重数组;非法回 null。纯函数,单测覆盖。 */
39
+ export function parseCronField(raw, min, max, names) {
40
+ const src = String(raw ?? "")
41
+ .trim()
42
+ .toLowerCase();
43
+ if (!src)
44
+ return null;
45
+ const out = new Set();
46
+ const num = (tok) => {
47
+ const t = tok.trim();
48
+ if (!t)
49
+ return null;
50
+ if (names && t in names)
51
+ return names[t];
52
+ if (!/^\d+$/.test(t))
53
+ return null;
54
+ let n = Number(t);
55
+ if (n === 7 && min === 0 && max === 6)
56
+ n = 0; // 周日的 7 写法
57
+ if (!Number.isInteger(n) || n < min || n > max)
58
+ return null;
59
+ return n;
60
+ };
61
+ for (const part of src.split(",")) {
62
+ const p = part.trim();
63
+ if (!p)
64
+ return null;
65
+ // 步长:*/n 或 a-b/n(a 缺省 min,b 缺省 max)。
66
+ const step = p.split("/");
67
+ if (step.length === 2) {
68
+ const every = num(step[1]);
69
+ if (every === null || every <= 0)
70
+ return null;
71
+ let lo = min;
72
+ let hi = max;
73
+ if (step[0] !== "" && step[0] !== "*") {
74
+ const range = step[0].split("-");
75
+ if (range.length > 2)
76
+ return null;
77
+ const a = num(range[0]);
78
+ if (a === null)
79
+ return null;
80
+ lo = a;
81
+ if (range.length === 2) {
82
+ const b = num(range[1]);
83
+ if (b === null || b < a)
84
+ return null;
85
+ hi = b;
86
+ }
87
+ }
88
+ for (let v = lo; v <= hi; v += every)
89
+ out.add(v);
90
+ continue;
91
+ }
92
+ if (step.length > 2)
93
+ return null;
94
+ if (p === "*") {
95
+ for (let v = min; v <= max; v++)
96
+ out.add(v);
97
+ continue;
98
+ }
99
+ if (p.includes("-")) {
100
+ const range = p.split("-");
101
+ if (range.length !== 2)
102
+ return null;
103
+ const a = num(range[0]);
104
+ const b = num(range[1]);
105
+ if (a === null || b === null || b < a)
106
+ return null;
107
+ for (let v = a; v <= b; v++)
108
+ out.add(v);
109
+ continue;
110
+ }
111
+ const n = num(p);
112
+ if (n === null)
113
+ return null;
114
+ out.add(n);
115
+ }
116
+ if (out.size === 0)
117
+ return null;
118
+ return [...out].sort((a, b) => a - b);
119
+ }
120
+ /** 5 字段 cron 解析;非法回 null。纯函数,单测覆盖。 */
121
+ export function parseCronSpec(spec) {
122
+ const fields = String(spec ?? "")
123
+ .trim()
124
+ .split(/\s+/);
125
+ if (fields.length !== 5)
126
+ return null;
127
+ const minute = parseCronField(fields[0], 0, 59);
128
+ const hour = parseCronField(fields[1], 0, 23);
129
+ const dom = parseCronField(fields[2], 1, 31);
130
+ const month = parseCronField(fields[3], 1, 12, MONTH_NAMES);
131
+ const dow = parseCronField(fields[4], 0, 6, DOW_NAMES);
132
+ if (!minute || !hour || !dom || !month || !dow)
133
+ return null;
134
+ return { minute, hour, dom, month, dow };
135
+ }
136
+ function isFull(values, min, max) {
137
+ return values.length === max - min + 1;
138
+ }
139
+ /** 下一次触发毫秒时间戳(从 fromMs 的下一分钟开始扫,上限约一年)。纯函数,单测覆盖。 */
140
+ export function nextCronFire(parts, fromMs) {
141
+ const minuteSet = new Set(parts.minute);
142
+ const hourSet = new Set(parts.hour);
143
+ const monthSet = new Set(parts.month);
144
+ const domRestricted = !isFull(parts.dom, 1, 31);
145
+ const dowRestricted = !isFull(parts.dow, 0, 6);
146
+ const domSet = new Set(parts.dom);
147
+ const dowSet = new Set(parts.dow);
148
+ let t = Math.floor(Number(fromMs) / 60000) * 60000 + 60000;
149
+ const limit = t + 366 * 24 * 60 * 60000;
150
+ for (; t <= limit; t += 60000) {
151
+ const d = new Date(t);
152
+ if (!monthSet.has(d.getMonth() + 1))
153
+ continue;
154
+ const domHit = domSet.has(d.getDate());
155
+ const dowHit = dowSet.has(d.getDay());
156
+ // 标准 OR 语义:都受限取并集;一侧通配时另一侧说了算;都不受限天天跑。
157
+ const dayHit = domRestricted && dowRestricted ? domHit || dowHit : domRestricted ? domHit : dowRestricted ? dowHit : true;
158
+ if (!dayHit)
159
+ continue;
160
+ if (!hourSet.has(d.getHours()))
161
+ continue;
162
+ if (!minuteSet.has(d.getMinutes()))
163
+ continue;
164
+ return t;
165
+ }
166
+ return limit;
167
+ }
168
+ export function scheduleFile(pluginDir) {
169
+ return join(pluginDir, "schedules.json");
170
+ }
171
+ /** 读持久记录;坏文件/形状不对当空表(且不在读路径回写)。 */
172
+ export function loadScheduleRecords(pluginDir) {
173
+ try {
174
+ const parsed = JSON.parse(readFileSync(scheduleFile(pluginDir), "utf8"));
175
+ if (!parsed || typeof parsed !== "object" || parsed.schedules === null || typeof parsed.schedules !== "object") {
176
+ return {};
177
+ }
178
+ const out = {};
179
+ for (const [id, r] of Object.entries(parsed.schedules)) {
180
+ if (!r || typeof r !== "object")
181
+ continue;
182
+ const rec = r;
183
+ if (typeof rec.spec !== "string" || !rec.spec)
184
+ continue;
185
+ out[id] = {
186
+ spec: rec.spec,
187
+ catchUp: rec.catchUp === "once" ? "once" : "skip",
188
+ ...(typeof rec.label === "string" && rec.label ? { label: rec.label } : {}),
189
+ ...(typeof rec.lastRun === "number" && Number.isFinite(rec.lastRun) ? { lastRun: rec.lastRun } : {}),
190
+ createdAt: typeof rec.createdAt === "number" && Number.isFinite(rec.createdAt) ? rec.createdAt : Date.now(),
191
+ };
192
+ }
193
+ return out;
194
+ }
195
+ catch {
196
+ return {};
197
+ }
198
+ }
199
+ /** 写持久记录(tmp+rename 原子写;失败只记日志,内存态本次会话仍生效)。 */
200
+ export function saveScheduleRecords(pluginDir, records) {
201
+ try {
202
+ mkdirSync(pluginDir, { recursive: true });
203
+ const file = scheduleFile(pluginDir);
204
+ const tmp = `${file}.tmp-${process.pid}`;
205
+ writeFileSync(tmp, JSON.stringify({ v: 1, schedules: records }));
206
+ renameSync(tmp, file);
207
+ }
208
+ catch (err) {
209
+ console.error(`[plugin-schedule] persist failed (${pluginDir}):`, err);
210
+ }
211
+ }