pi-web-ui 0.88.0 → 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.
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { existsSync, readFileSync } from "node:fs";
20
20
  import { stat } from "node:fs/promises";
21
- import { createServer } from "node:http";
21
+ import { createServer, request as proxyRequest } from "node:http";
22
22
  import { createConnection } from "node:net";
23
23
  import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
24
24
  import { homedir } from "node:os";
@@ -46,6 +46,7 @@ import { syncPluginCatalog } from "./plugin-catalog-sync.js";
46
46
  import { McpBridge } from "./mcp-bridge.js";
47
47
  import { createMcpHotReload } from "./mcp-hot-reload.js";
48
48
  import { createHostMetricsSampler } from "./host-metrics.js";
49
+ import { SchedulerStore } from "./scheduler-tasks.js";
49
50
  /** Strip npm-injected env (`npm start` exports `npm_config_*` / `npm_package_*` /
50
51
  * `npm_lifecycle_*` into every child). Anything this server spawns — shells,
51
52
  * `pi update` — would otherwise inherit `npm_config_allow_scripts`, which npm
@@ -503,6 +504,75 @@ app.all(["/plugins-api/:id/*", "/plugins-api/:id"], (req, res) => {
503
504
  const rest = String(req.params[0] ?? "");
504
505
  pluginMgr.handleHttp(String(req.params.id ?? ""), req.method, rest, req, res);
505
506
  });
507
+ function proxyForwardPath(hit, url) {
508
+ let fwd = String(url ?? "/").slice(hit.prefix.length);
509
+ if (!fwd.startsWith("/"))
510
+ fwd = `/${fwd}`;
511
+ return fwd || "/";
512
+ }
513
+ function proxyHttp(hit, req, res) {
514
+ const fwdPath = proxyForwardPath(hit, req.url ?? "/");
515
+ const headers = {};
516
+ for (const [k, v] of Object.entries(req.headers)) {
517
+ if (v === undefined)
518
+ continue;
519
+ if (k.toLowerCase() === "host")
520
+ continue;
521
+ if (k.toLowerCase() === "content-length" && req.method !== "GET" && req.method !== "HEAD")
522
+ continue;
523
+ headers[k] = v;
524
+ }
525
+ // 内页拼 SSE/资源绝对地址用(子路径反代下 import.meta 推导不到前缀,靠这个头)。
526
+ headers["x-pi-proxy-prefix"] = hit.prefix;
527
+ let body;
528
+ if (req.method !== "GET" && req.method !== "HEAD" && req.body !== undefined) {
529
+ const b = req.body;
530
+ if (Buffer.isBuffer(b))
531
+ body = b;
532
+ else if (typeof b === "string")
533
+ body = Buffer.from(b);
534
+ else if (b !== undefined) {
535
+ body = Buffer.from(JSON.stringify(b));
536
+ if (!headers["content-type"])
537
+ headers["content-type"] = "application/json";
538
+ }
539
+ if (body)
540
+ headers["content-length"] = String(body.length);
541
+ }
542
+ const up = proxyRequest({ host: hit.host, port: hit.port, method: req.method, path: fwdPath, headers, timeout: 30000 }, (upRes) => {
543
+ const out = {};
544
+ for (const [k, v] of Object.entries(upRes.headers)) {
545
+ if (v === undefined)
546
+ continue;
547
+ const lk = k.toLowerCase();
548
+ if (lk === "connection" || lk === "keep-alive" || lk === "transfer-encoding" || lk === "upgrade")
549
+ continue;
550
+ out[k] = v;
551
+ }
552
+ res.writeHead(upRes.statusCode ?? 502, out);
553
+ upRes.pipe(res);
554
+ });
555
+ up.on("timeout", () => up.destroy(new Error("proxy timeout")));
556
+ up.on("error", (err) => {
557
+ console.error(`[proxy:${hit.prefix}] → 127.0.0.1:${hit.port}${fwdPath} failed:`, err);
558
+ if (!res.headersSent)
559
+ res.status(502).end("proxy target unreachable");
560
+ else
561
+ res.end();
562
+ });
563
+ if (body)
564
+ up.end(body);
565
+ else
566
+ req.pipe(up);
567
+ }
568
+ app.use((req, res, next) => {
569
+ const hit = pluginMgr.findProxy(req.path);
570
+ if (!hit) {
571
+ next();
572
+ return;
573
+ }
574
+ proxyHttp(hit, req, res);
575
+ });
506
576
  app.get("/plugins/:id/client/*", (req, res) => {
507
577
  // express 4 的通配参数在运行时落在 params[0],但类型声明里没有 —— 显式取
508
578
  const rest = String(req.params[0] ?? "");
@@ -659,6 +729,67 @@ httpServer.on("upgrade", (req, socket, head) => {
659
729
  catch {
660
730
  /* fall through to the path check below */
661
731
  }
732
+ // 通用插件代理的 websocket 透传(live-reload 这类 socket 走这条;与 proxyHttp 同前缀表)。
733
+ const proxyHit = pluginMgr.findProxy(pathname);
734
+ if (proxyHit) {
735
+ if (!originAllowed(req)) {
736
+ socket.write("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
737
+ socket.destroy();
738
+ return;
739
+ }
740
+ if (AUTH_TOKEN && !tokenOk(req)) {
741
+ socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
742
+ socket.destroy();
743
+ return;
744
+ }
745
+ const target = createConnection(proxyHit.port, proxyHit.host);
746
+ const tearDown = () => {
747
+ try {
748
+ socket.destroy();
749
+ }
750
+ catch {
751
+ /* already gone */
752
+ }
753
+ try {
754
+ target.destroy();
755
+ }
756
+ catch {
757
+ /* already gone */
758
+ }
759
+ };
760
+ target.on("error", tearDown);
761
+ socket.on("error", tearDown);
762
+ target.setTimeout(10000, tearDown);
763
+ target.on("connect", () => {
764
+ target.setTimeout(0);
765
+ let fwdPath = String(req.url ?? "/").slice(proxyHit.prefix.length) || "/";
766
+ if (!fwdPath.startsWith("/"))
767
+ fwdPath = `/${fwdPath}`;
768
+ const lines = [`${req.method} ${fwdPath} HTTP/${req.httpVersion}`];
769
+ for (const [k, v] of Object.entries(req.headers)) {
770
+ if (k.toLowerCase() === "host") {
771
+ lines.push(`host: 127.0.0.1:${proxyHit.port}`);
772
+ continue;
773
+ }
774
+ if (Array.isArray(v))
775
+ for (const x of v)
776
+ lines.push(`${k}: ${x}`);
777
+ else if (v !== undefined)
778
+ lines.push(`${k}: ${v}`);
779
+ }
780
+ lines.push("", "");
781
+ try {
782
+ target.write(lines.join("\r\n"));
783
+ if (head?.length)
784
+ target.write(head);
785
+ socket.pipe(target).pipe(socket);
786
+ }
787
+ catch {
788
+ tearDown();
789
+ }
790
+ });
791
+ return;
792
+ }
662
793
  if (pathname !== "/ws") {
663
794
  socket.destroy();
664
795
  return;
@@ -821,6 +952,50 @@ pluginMgr.permissionRequester = (pluginId, req) => new Promise((resolve) => {
821
952
  }
822
953
  });
823
954
  pluginMgr.onPermGrantsChanged = () => pushPluginPermissions();
955
+ // 内置定时任务(issue #184):全局 <dataDir>/scheduler-tasks.json,TTL 与
956
+ // client-state 同级;执行走标准 pi 引擎的无头伪客户端(chatFromScheduler),
957
+ // DSH 引擎无该方法时 executor 回 not-supported(历史里记失败,不炸进程)。
958
+ const scheduler = new SchedulerStore(DATA_DIR, {
959
+ executor: async (task) => {
960
+ try {
961
+ const svc = service;
962
+ if (typeof svc.chatFromScheduler !== "function")
963
+ return { ok: false, error: "当前引擎不支持定时任务(仅标准 pi 引擎)" };
964
+ return await svc.chatFromScheduler({
965
+ id: task.id,
966
+ cwd: task.cwd,
967
+ prompt: task.prompt,
968
+ model: task.model,
969
+ thinkingLevel: task.thinkingLevel,
970
+ });
971
+ }
972
+ catch (err) {
973
+ return { ok: false, error: err.message };
974
+ }
975
+ },
976
+ onChange: () => pushSchedulerTasks(),
977
+ notify: (level, text, textEn) => pushNoticeToAll(level, text, textEn ?? text),
978
+ });
979
+ scheduler.start();
980
+ /** 把调度器任务列表推给所有在线客户端(设置面板展示 + 变更后刷新)。 */
981
+ function pushSchedulerTasks() {
982
+ try {
983
+ const payload = JSON.stringify({ type: "scheduler_tasks", tasks: scheduler.list() });
984
+ for (const client of wss.clients) {
985
+ if (client.readyState !== WebSocket.OPEN)
986
+ continue;
987
+ try {
988
+ client.send(payload);
989
+ }
990
+ catch {
991
+ /* 死连接:index.ts 自己会清理 */
992
+ }
993
+ }
994
+ }
995
+ catch {
996
+ /* 序列化失败不影响调度 */
997
+ }
998
+ }
824
999
  /** 广播通知条给全部在线客户端(全局事件,不属于某个 ClientSession —— 如 mcp.json 坏)。 */
825
1000
  function pushNoticeToAll(level, text, textEn) {
826
1001
  const payload = JSON.stringify({ type: "notice", level, text, textEn });
@@ -866,7 +1041,10 @@ pluginMgr.chatProvider = (pluginId, req) => service.chatFromPlugin?.(pluginId, r
866
1041
  // 插件扩展点:插件注册的 AI 工具(registerAgentTool)+ MCP 桥工具 → 会话创建时
867
1042
  // 带上 + 变化时动态注入/移除已有会话。
868
1043
  service.pluginToolsProvider = () => [...pluginMgr.getAgentTools(), ...mcpBridge.getTools()];
869
- pluginMgr.onAgentToolsChanged = () => service.applyPluginAgentTools();
1044
+ pluginMgr.onAgentToolsChanged = () => {
1045
+ service.applyPluginAgentTools();
1046
+ void pluginMgr.pushToAll().catch(() => { });
1047
+ };
870
1048
  // 插件扩展点:插件斜杠命令(registerCommand)→ 命令选择器目录 + prompt 拦截执行。
871
1049
  pluginMgr.onCommandsChanged = () => service.applyPluginCommandCatalog();
872
1050
  service.pluginCommandsProvider = () => pluginMgr.listCommands();
@@ -1252,6 +1430,12 @@ wss.on("connection", (ws) => {
1252
1430
  case "file_copy":
1253
1431
  void cs.copyEntry(msg.src, msg.destDir, msg.move);
1254
1432
  break;
1433
+ case "file_reveal":
1434
+ void cs.revealEntry(msg.path);
1435
+ break;
1436
+ case "file_open_default":
1437
+ void cs.openDefaultEntry(msg.path);
1438
+ break;
1255
1439
  case "list_models":
1256
1440
  void cs.listModels();
1257
1441
  break;
@@ -1367,6 +1551,12 @@ wss.on("connection", (ws) => {
1367
1551
  case "refresh_provider_models":
1368
1552
  void cs.refreshProviderModels(msg.providerId, msg.reqId);
1369
1553
  break;
1554
+ case "refresh_builtin_models":
1555
+ void cs.refreshBuiltinModels(msg.reqId);
1556
+ break;
1557
+ case "append_builtin_model":
1558
+ void cs.appendBuiltinModel(msg.providerId, msg.model, msg.reqId);
1559
+ break;
1370
1560
  case "clone_provider":
1371
1561
  void cs.cloneProvider(msg.provider, msg.reqId);
1372
1562
  break;
@@ -1451,6 +1641,7 @@ wss.on("connection", (ws) => {
1451
1641
  disabledSkills: msg.disabledSkills,
1452
1642
  disabledExtensions: msg.disabledExtensions,
1453
1643
  disabledAgentTools: msg.disabledAgentTools,
1644
+ disabledPluginTools: msg.disabledPluginTools,
1454
1645
  disabledPlugins: msg.disabledPlugins,
1455
1646
  terminalToolsEnabled: msg.terminalToolsEnabled,
1456
1647
  terminalBash: msg.terminalBash,
@@ -1695,6 +1886,63 @@ wss.on("connection", (ws) => {
1695
1886
  case "delete_preset":
1696
1887
  void cs.deletePreset(msg.name);
1697
1888
  break;
1889
+ case "schedule_list":
1890
+ try {
1891
+ send({ type: "scheduler_tasks", tasks: scheduler.list() });
1892
+ }
1893
+ catch (err) {
1894
+ send({
1895
+ type: "notice",
1896
+ level: "error",
1897
+ text: `读取定时任务失败:${err.message}`,
1898
+ textEn: `Failed to list scheduled tasks: ${err.message}`,
1899
+ });
1900
+ }
1901
+ break;
1902
+ case "schedule_save":
1903
+ try {
1904
+ scheduler.upsert(msg.task);
1905
+ }
1906
+ catch (err) {
1907
+ send({
1908
+ type: "notice",
1909
+ level: "error",
1910
+ text: `保存定时任务失败:${err.message}`,
1911
+ textEn: `Failed to save scheduled task: ${err.message}`,
1912
+ });
1913
+ }
1914
+ break;
1915
+ case "schedule_delete":
1916
+ if (!scheduler.remove(msg.id)) {
1917
+ send({
1918
+ type: "notice",
1919
+ level: "warning",
1920
+ text: `定时任务不存在:${msg.id}`,
1921
+ textEn: `No such scheduled task: ${msg.id}`,
1922
+ });
1923
+ }
1924
+ break;
1925
+ case "schedule_run":
1926
+ void scheduler.runNow(msg.id).then((r) => {
1927
+ if (!r.ok)
1928
+ send({
1929
+ type: "notice",
1930
+ level: "warning",
1931
+ text: `定时任务手动触发失败:${r.error ?? "未知错误"}`,
1932
+ textEn: `Manual scheduled-task run failed: ${r.error ?? "unknown error"}`,
1933
+ });
1934
+ });
1935
+ break;
1936
+ case "schedule_toggle":
1937
+ if (!scheduler.setEnabled(msg.id, msg.enabled === true)) {
1938
+ send({
1939
+ type: "notice",
1940
+ level: "warning",
1941
+ text: `定时任务不存在:${msg.id}`,
1942
+ textEn: `No such scheduled task: ${msg.id}`,
1943
+ });
1944
+ }
1945
+ break;
1698
1946
  default:
1699
1947
  break;
1700
1948
  }
@@ -1758,6 +2006,13 @@ wss.on("connection", (ws) => {
1758
2006
  // 注册表(plugin-fence.ts),`` ```lang `` 围栏才能立即命中插件;
1759
2007
  // 否则消息先落成普通代码块,清单后到也不会重渲。
1760
2008
  cs.flushSnapshot();
2009
+ // 内置定时任务列表随附推一次(后续变更经 pushSchedulerTasks 广播)。
2010
+ try {
2011
+ send({ type: "scheduler_tasks", tasks: scheduler.list() });
2012
+ }
2013
+ catch {
2014
+ /* 推送失败不挡快照 */
2015
+ }
1761
2016
  })
1762
2017
  .catch(() => {
1763
2018
  if (closed)
@@ -1903,6 +2158,7 @@ async function shutdown(signal = "SIGINT") {
1903
2158
  try {
1904
2159
  clearInterval(heartbeatTimer);
1905
2160
  stopControl();
2161
+ scheduler.stop();
1906
2162
  pluginMgr.dispose();
1907
2163
  pluginInstaller.dispose();
1908
2164
  mcpHotReload.dispose();