pi-web-ui 0.100.0 → 0.101.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 (77) hide show
  1. package/CHANGELOG.md +39 -1
  2. package/README.md +46 -44
  3. package/README.zh-CN.md +41 -39
  4. package/bin/pi-web-ui.mjs +4 -10
  5. package/dist/server/agent-formatters.js +191 -0
  6. package/dist/server/agent-service-daemon.js +1266 -0
  7. package/dist/server/agent-service.js +9883 -12935
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +41 -167
  10. package/dist/server/ask-user-question-tool.js +94 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/bash-tool.js +83 -0
  13. package/dist/server/browser-page-tool.js +207 -0
  14. package/dist/server/client-id-utils.js +51 -0
  15. package/dist/server/client-state.js +23 -2
  16. package/dist/server/compaction-markers.js +34 -1
  17. package/dist/server/context-budget-runner.js +43 -0
  18. package/dist/server/dangling-tools.js +18 -5
  19. package/dist/server/delegate-mode.js +1 -0
  20. package/dist/server/dispatch-domain-handlers.js +631 -0
  21. package/dist/server/dispatch-plugin-handlers.js +300 -0
  22. package/dist/server/dsh/dsh-agent-service.js +9 -1
  23. package/dist/server/goal-evidence.js +9 -2
  24. package/dist/server/goal-service.js +1 -1
  25. package/dist/server/hashline-engine.js +1 -1
  26. package/dist/server/index.js +191 -969
  27. package/dist/server/left-panel-running.js +115 -0
  28. package/dist/server/lsp-tool.js +40 -12
  29. package/dist/server/markers-list-tool.js +34 -0
  30. package/dist/server/market-service.js +277 -0
  31. package/dist/server/mcp-bridge.js +137 -30
  32. package/dist/server/mcp-hot-reload.js +84 -27
  33. package/dist/server/mcp-manager.js +215 -0
  34. package/dist/server/message-entry-resolver.js +32 -0
  35. package/dist/server/orphan-manager.js +44 -0
  36. package/dist/server/persona-chain.js +63 -0
  37. package/dist/server/plan-mode.js +2 -0
  38. package/dist/server/plan-update-tool.js +96 -0
  39. package/dist/server/plugin-api-catalog.js +20 -0
  40. package/dist/server/plugin-facilities.js +13 -3
  41. package/dist/server/plugin-ui-slots.js +39 -0
  42. package/dist/server/plugins.js +71 -38
  43. package/dist/server/preset-fields.js +7 -0
  44. package/dist/server/preset-share.js +1 -0
  45. package/dist/server/process-utils.js +30 -0
  46. package/dist/server/prompt-assembler.js +80 -0
  47. package/dist/server/scm-commitmsg.js +74 -0
  48. package/dist/server/serialize.js +97 -7
  49. package/dist/server/session-branch.js +367 -0
  50. package/dist/server/session-parser.js +235 -0
  51. package/dist/server/session-search.js +158 -0
  52. package/dist/server/settings-service.js +13 -1
  53. package/dist/server/skill-content-filler.js +33 -0
  54. package/dist/server/subagent-handoff.js +18 -0
  55. package/dist/server/subagent-helpers.js +88 -0
  56. package/dist/server/terminals.js +155 -58
  57. package/dist/server/tool-guards.js +527 -0
  58. package/dist/server/tool-host-factories.js +217 -0
  59. package/dist/server/tool-manager.js +30 -5
  60. package/dist/server/wait-subscription-scan.js +46 -1
  61. package/dist/server/workspace-snapshot.js +18 -0
  62. package/extensions/webui.ts +90 -24
  63. package/package.json +1 -1
  64. package/plugin-sdk/README.md +17 -0
  65. package/plugin-sdk/index.d.ts +17 -0
  66. package/plugin-sdk/index.mjs +5 -0
  67. package/plugins/catalog.json +20 -0
  68. package/themes/aetheris.css +3 -1
  69. package/themes/translucent.css +8 -1
  70. package/themes/transparent.css +9 -1
  71. package/web/dist/assets/{TerminalPanel-C3I1Mc-C.js → TerminalPanel-DD7I5_aC.js} +1 -1
  72. package/web/dist/assets/index-CpjA1YdT.css +1 -0
  73. package/web/dist/assets/index-nKn87VuM.js +678 -0
  74. package/web/dist/index.html +2 -2
  75. package/web/dist/sw.js +1 -1
  76. package/web/dist/assets/index-B-E2EM_0.css +0 -1
  77. package/web/dist/assets/index-BYumAaGi.js +0 -379
@@ -0,0 +1,115 @@
1
+ /** 单个插件同时可见的条目上限(超出的丢弃并给诊断)。 */
2
+ export const PANEL_ITEM_CAP = 50;
3
+ /** 心跳 TTL:缺省 60 秒(插件若不传 ttlMs)。 */
4
+ export const PANEL_TTL_DEFAULT_MS = 60_000;
5
+ /** TTL 夹取区间:过短会抖动,过长等于没有超时。 */
6
+ export const PANEL_TTL_MIN_MS = 5_000;
7
+ export const PANEL_TTL_MAX_MS = 3_600_000;
8
+ const ID_MAX = 96;
9
+ const TITLE_MAX = 200;
10
+ const HINT_MAX = 200;
11
+ const ICON_MAX = 8;
12
+ const ACTION_MAX = 96;
13
+ const STATUSES = new Set(["running", "done", "error"]);
14
+ /** 把插件传来的 `items` 清洗成可信的条目列表(纯函数)。不合法的条目丢弃,不抛错。 */
15
+ export function sanitizePanelItems(raw) {
16
+ const diags = [];
17
+ const items = [];
18
+ if (!Array.isArray(raw)) {
19
+ diags.push("setRunning: items must be an array — ignored");
20
+ return { items, diags };
21
+ }
22
+ const seen = new Set();
23
+ raw.forEach((rawItem, idx) => {
24
+ if (!rawItem || typeof rawItem !== "object") {
25
+ diags.push(`setRunning[#${idx}]: not an object — dropped`);
26
+ return;
27
+ }
28
+ const o = rawItem;
29
+ const id = typeof o.id === "string" ? o.id.trim().slice(0, ID_MAX) : "";
30
+ if (!id) {
31
+ diags.push(`setRunning[#${idx}]: missing id — dropped`);
32
+ return;
33
+ }
34
+ if (seen.has(id)) {
35
+ diags.push(`setRunning: duplicate id "${id}" — later one dropped`);
36
+ return;
37
+ }
38
+ if (items.length >= PANEL_ITEM_CAP) {
39
+ diags.push(`setRunning: capped at ${PANEL_ITEM_CAP} items — "${id}" and later dropped`);
40
+ return;
41
+ }
42
+ seen.add(id);
43
+ const title = typeof o.title === "string" && o.title.trim() ? o.title.trim().slice(0, TITLE_MAX) : id;
44
+ let status = "running";
45
+ if (o.status !== undefined) {
46
+ if (typeof o.status === "string" && STATUSES.has(o.status))
47
+ status = o.status;
48
+ else
49
+ diags.push(`setRunning["${id}"]: unknown status — treated as "running"`);
50
+ }
51
+ const item = { id, title, status };
52
+ if (typeof o.hint === "string" && o.hint.trim())
53
+ item.hint = o.hint.trim().slice(0, HINT_MAX);
54
+ if (typeof o.icon === "string" && o.icon.trim())
55
+ item.icon = o.icon.trim().slice(0, ICON_MAX);
56
+ if (typeof o.action === "string" && o.action.trim())
57
+ item.action = o.action.trim().slice(0, ACTION_MAX);
58
+ items.push(item);
59
+ });
60
+ return { items, diags };
61
+ }
62
+ /** TTL 夹取:非数字 / 缺省 → 默认值;其余夹进 [MIN, MAX]。 */
63
+ export function clampPanelTtl(raw) {
64
+ const n = typeof raw === "number" && Number.isFinite(raw) ? raw : PANEL_TTL_DEFAULT_MS;
65
+ return Math.min(PANEL_TTL_MAX_MS, Math.max(PANEL_TTL_MIN_MS, Math.round(n)));
66
+ }
67
+ export class LeftPanelRunningStore {
68
+ now;
69
+ slots = new Map();
70
+ constructor(now = Date.now) {
71
+ this.now = now;
72
+ }
73
+ /** 整体替换某插件的运行条目(同时是心跳)。 */
74
+ set(pluginId, pluginName, raw, opts) {
75
+ const { items, diags } = sanitizePanelItems(raw);
76
+ if (items.length === 0) {
77
+ const had = this.slots.delete(pluginId);
78
+ return { count: 0, changed: had, diags };
79
+ }
80
+ const ttlMs = clampPanelTtl(opts?.ttlMs);
81
+ const prev = this.slots.get(pluginId);
82
+ const changed = !prev || prev.pluginName !== pluginName || JSON.stringify(prev.items) !== JSON.stringify(items);
83
+ this.slots.set(pluginId, { pluginName, items, ttlMs, touchedAt: this.now() });
84
+ return { count: items.length, changed, diags };
85
+ }
86
+ /** 清空某插件的条目。返回是否真的删了东西(没有则不需要广播)。 */
87
+ clear(pluginId) {
88
+ return this.slots.delete(pluginId);
89
+ }
90
+ /** 清掉心跳过期的插件,返回被清掉的插件 id 列表(调用方据此广播)。 */
91
+ sweep() {
92
+ const t = this.now();
93
+ const expired = [];
94
+ for (const [pluginId, slot] of this.slots) {
95
+ if (t - slot.touchedAt > slot.ttlMs) {
96
+ this.slots.delete(pluginId);
97
+ expired.push(pluginId);
98
+ }
99
+ }
100
+ return expired;
101
+ }
102
+ /** 当前全部分组(按插件 id 排序,空组不出现)。返回副本,调用方随便改。 */
103
+ groups() {
104
+ return [...this.slots.entries()]
105
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
106
+ .map(([pluginId, slot]) => ({
107
+ pluginId,
108
+ pluginName: slot.pluginName,
109
+ items: slot.items.map((it) => ({ ...it })),
110
+ }));
111
+ }
112
+ get size() {
113
+ return this.slots.size;
114
+ }
115
+ }
@@ -226,17 +226,23 @@ export async function autoInstallLanguageServer(pkg) {
226
226
  const npmCmd = isWin ? "npm.cmd" : "npm";
227
227
  let stderr = "";
228
228
  await new Promise((resolve, reject) => {
229
- const proc = spawn(npmCmd, ["install", "--no-audit", "--no-fund", "--save-dev", ...pkgs], {
229
+ const spawnCmd = isWin ? process.env.ComSpec || "cmd.exe" : npmCmd;
230
+ const spawnArgs = isWin
231
+ ? ["/d", "/s", "/c", npmCmd, "install", "--no-audit", "--no-fund", "--save-dev", ...pkgs]
232
+ : ["install", "--no-audit", "--no-fund", "--save-dev", ...pkgs];
233
+ const proc = spawn(spawnCmd, spawnArgs, {
230
234
  cwd: userLspDir,
231
235
  stdio: ["ignore", "ignore", "pipe"],
232
- shell: isWin,
236
+ windowsHide: true,
233
237
  });
234
238
  const timer = setTimeout(() => {
235
239
  if (isWin) {
236
- // shell:true 时 proc.pid 只是 cmd.exe 的 PID——proc.kill() 只杀得到
237
- // cmd.exe,npm/node 整棵子进程树会残留。taskkill /T 连树强杀。
240
+ // win32 下 taskkill /T 连整棵子进程树强杀,避免 npm/node 残留。
238
241
  if (typeof proc.pid === "number") {
239
- const killer = spawn("taskkill", ["/PID", String(proc.pid), "/T", "/F"], { stdio: "ignore" });
242
+ const killer = spawn("taskkill", ["/PID", String(proc.pid), "/T", "/F"], {
243
+ stdio: "ignore",
244
+ windowsHide: true,
245
+ });
240
246
  killer.on("error", () => { });
241
247
  }
242
248
  }
@@ -316,13 +322,17 @@ export class LspClient {
316
322
  }
317
323
  async start() {
318
324
  this.touch();
319
- this.proc = spawn(this.binPath, this.binArgs, {
325
+ const isWin = process.platform === "win32";
326
+ const isBatch = isWin && /\.(cmd|bat)$/i.test(this.binPath);
327
+ const spawnCmd = isBatch ? process.env.ComSpec || "cmd.exe" : this.binPath;
328
+ const spawnArgs = isBatch ? ["/d", "/s", "/c", this.binPath, ...this.binArgs] : this.binArgs;
329
+ this.proc = spawn(spawnCmd, spawnArgs, {
320
330
  cwd: this.projectCwd,
321
331
  stdio: ["pipe", "pipe", "pipe"],
322
- shell: process.platform === "win32" && /\.(cmd|bat)$/i.test(this.binPath),
332
+ windowsHide: true,
323
333
  });
324
334
  this.proc.stdout?.on("data", (chunk) => this.handleData(chunk));
325
- this.proc.stderr?.on("data", (d) => {
335
+ this.proc.stderr?.on("data", (_d) => {
326
336
  // 可选记录 debug 日志,不干扰输出
327
337
  });
328
338
  // spawn 失败(ENOENT/EACCES 等)只触发 'error',进程从未启动时不会触发
@@ -347,7 +357,7 @@ export class LspClient {
347
357
  });
348
358
  try {
349
359
  // 发送 initialize 握手
350
- const initRes = await this.request("initialize", {
360
+ await this.request("initialize", {
351
361
  processId: process.pid,
352
362
  rootUri: pathToFileURL(this.projectCwd).toString(),
353
363
  workspaceFolders: [
@@ -372,7 +382,16 @@ export class LspClient {
372
382
  catch (err) {
373
383
  if (this.proc) {
374
384
  try {
375
- this.proc.kill();
385
+ if (process.platform === "win32" && typeof this.proc.pid === "number") {
386
+ const killer = spawn("taskkill", ["/PID", String(this.proc.pid), "/T", "/F"], {
387
+ stdio: "ignore",
388
+ windowsHide: true,
389
+ });
390
+ killer.on("error", () => { });
391
+ }
392
+ else {
393
+ this.proc.kill();
394
+ }
376
395
  }
377
396
  catch { }
378
397
  this.proc = null;
@@ -546,7 +565,16 @@ export class LspClient {
546
565
  catch { }
547
566
  if (this.proc) {
548
567
  try {
549
- this.proc.kill();
568
+ if (process.platform === "win32" && typeof this.proc.pid === "number") {
569
+ const killer = spawn("taskkill", ["/PID", String(this.proc.pid), "/T", "/F"], {
570
+ stdio: "ignore",
571
+ windowsHide: true,
572
+ });
573
+ killer.on("error", () => { });
574
+ }
575
+ else {
576
+ this.proc.kill();
577
+ }
550
578
  }
551
579
  catch { }
552
580
  this.proc = null;
@@ -1375,7 +1403,7 @@ export function makeLspTool(options) {
1375
1403
  while (pending.size > 0 && Date.now() < deadline) {
1376
1404
  await new Promise((r) => setTimeout(r, 120));
1377
1405
  const known = client.getAllDiagnostics();
1378
- for (const u of [...pending]) {
1406
+ for (const u of Array.from(pending)) {
1379
1407
  if (known.has(u))
1380
1408
  pending.delete(u);
1381
1409
  }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * markers-list-tool — 任务列表只读查询工具(todo_list)。
3
+ *
4
+ * 读操作仍走真工具;所有写操作由模型在回复正文中使用行内标记([[todo:new:...]] 等)。
5
+ * 从 agent-service.ts 抽出为独立模块。
6
+ */
7
+ import { Type } from "typebox";
8
+ import { MARKERS_LIST_TOOL_NAME } from "./tool-manager.js";
9
+ export function makeMarkersListTool(getActiveId, markerSvc) {
10
+ return {
11
+ name: MARKERS_LIST_TOOL_NAME,
12
+ promptSnippet: "list inline-marker tasks (read-only; writes use [[todo:...]])",
13
+ label: "List marker state",
14
+ description: "Read-only query of inline marker state. All WRITE operations must use inline markers ([[todo:new:...]] etc.) in the reply body — never this tool.",
15
+ parameters: Type.Object({
16
+ action: Type.Unsafe({ enum: ["list"] }),
17
+ tool: Type.Optional(Type.Literal("todo")),
18
+ includeDeleted: Type.Optional(Type.Boolean({
19
+ description: "Include deleted tasks (tombstones, todo only).",
20
+ })),
21
+ }),
22
+ execute: async (_id, params) => {
23
+ const p = params;
24
+ const convId = getActiveId();
25
+ const text = markerSvc.describe(convId, "todo", !!p.includeDeleted);
26
+ const state = markerSvc.getRawState(convId, "todo");
27
+ const visible = (state?.tasks ?? []).filter((t) => p.includeDeleted || t.status !== "deleted");
28
+ return {
29
+ content: [{ type: "text", text }],
30
+ details: { action: "list", todos: visible, nextId: state?.nextId },
31
+ };
32
+ },
33
+ };
34
+ }
@@ -0,0 +1,277 @@
1
+ /**
2
+ * 远程市场服务 —— MCP 服务器市场 API 与 GitHub 技能仓库目录抓取
3
+ *
4
+ * 职责:
5
+ * 1. 从 Smithery 等开放 API、GitHub 官方仓库拉取公开 MCP 服务器目录;
6
+ * 2. 从 GitHub 仓库(如 anthropics/skills 等)拉取公开 Agent Skills 清单及 SKILL.md 正文;
7
+ * 3. 本地磁盘缓存与超时防抖,网络失败时不影响主程序运行。
8
+ */
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ const DEFAULT_TIMEOUT_MS = 10_000;
12
+ const CACHE_TTL_MS = 60 * 60 * 1000; // 1 小时缓存
13
+ /** 获取 GitHub Token(优先使用配置的预设分享令牌或标准环境变量) */
14
+ function getGitHubToken() {
15
+ return (process.env.PI_WEB_PRESET_TOKEN?.trim() ||
16
+ process.env.GH_TOKEN?.trim() ||
17
+ process.env.GITHUB_TOKEN?.trim() ||
18
+ undefined);
19
+ }
20
+ function fetchHeaders(customHeaders) {
21
+ const headers = {
22
+ "User-Agent": "pi-web-ui-market/1.0",
23
+ Accept: "application/json",
24
+ ...customHeaders,
25
+ };
26
+ const token = getGitHubToken();
27
+ if (token && !headers.Authorization) {
28
+ headers.Authorization = `Bearer ${token}`;
29
+ }
30
+ return headers;
31
+ }
32
+ function readCache(cacheFile) {
33
+ if (!existsSync(cacheFile))
34
+ return null;
35
+ try {
36
+ const raw = JSON.parse(readFileSync(cacheFile, "utf8"));
37
+ if (Date.now() - raw.timestamp < CACHE_TTL_MS) {
38
+ return raw.data;
39
+ }
40
+ }
41
+ catch {
42
+ /* invalid cache */
43
+ }
44
+ return null;
45
+ }
46
+ function writeCache(cacheFile, data) {
47
+ try {
48
+ mkdirSync(dirname(cacheFile), { recursive: true });
49
+ const payload = {
50
+ timestamp: Date.now(),
51
+ data,
52
+ };
53
+ writeFileSync(cacheFile, JSON.stringify(payload), "utf8");
54
+ }
55
+ catch {
56
+ /* ignore write cache failure */
57
+ }
58
+ }
59
+ /** 从公开 API 或仓库拉取 MCP 服务器列表 */
60
+ export async function fetchRemoteMcpMarket(opts) {
61
+ const source = opts.source || "smithery";
62
+ const cacheKey = `mcp-market-${source.replace(/[^a-zA-Z0-9_-]/g, "_")}-${opts.query || "all"}.json`;
63
+ const cacheFile = join(opts.dataDir, "market-cache", cacheKey);
64
+ if (!opts.refresh) {
65
+ const cached = readCache(cacheFile);
66
+ if (cached) {
67
+ return { ok: true, servers: cached, source, total: cached.length };
68
+ }
69
+ }
70
+ try {
71
+ if (source === "smithery" || source.startsWith("https://api.smithery.ai")) {
72
+ const baseUrl = source === "smithery" ? "https://api.smithery.ai/servers" : source;
73
+ const url = new URL(baseUrl);
74
+ url.searchParams.set("pageSize", "50");
75
+ if (opts.query?.trim()) {
76
+ url.searchParams.set("q", opts.query.trim());
77
+ }
78
+ const res = await fetch(url.toString(), {
79
+ headers: fetchHeaders(),
80
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
81
+ });
82
+ if (!res.ok) {
83
+ throw new Error(`Smithery API 响应错误 HTTP ${res.status}: ${res.statusText}`);
84
+ }
85
+ const json = (await res.json());
86
+ const rawServers = Array.isArray(json.servers) ? json.servers : [];
87
+ const servers = rawServers.map((item) => {
88
+ const id = item.qualifiedName || item.id || "mcp-server";
89
+ const isRemote = !!item.remote;
90
+ return {
91
+ id,
92
+ name: item.displayName || item.qualifiedName || id,
93
+ displayName: item.displayName,
94
+ description: item.description || "Model Context Protocol Server",
95
+ homepage: item.homepage || `https://smithery.ai/server/${encodeURIComponent(id)}`,
96
+ package: item.qualifiedName ? `@smithery/${item.qualifiedName}` : id,
97
+ command: isRemote ? undefined : "npx",
98
+ args: isRemote ? undefined : ["-y", `@smithery/${item.qualifiedName}`],
99
+ transport: isRemote ? "http" : "stdio",
100
+ url: isRemote ? item.deploymentUrl : undefined,
101
+ source: "smithery",
102
+ downloads: typeof item.useCount === "number" ? item.useCount : undefined,
103
+ verified: !!item.verified,
104
+ iconUrl: item.iconUrl,
105
+ };
106
+ });
107
+ writeCache(cacheFile, servers);
108
+ return { ok: true, servers, source: "smithery", total: json.pagination?.total ?? servers.length };
109
+ }
110
+ if (source === "github" || source.includes("github.com/modelcontextprotocol/servers")) {
111
+ const apiUrl = "https://api.github.com/repos/modelcontextprotocol/servers/contents/src";
112
+ const res = await fetch(apiUrl, {
113
+ headers: fetchHeaders(),
114
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
115
+ });
116
+ if (!res.ok) {
117
+ throw new Error(`GitHub API 响应错误 HTTP ${res.status}`);
118
+ }
119
+ const list = (await res.json());
120
+ const dirs = list.filter((item) => item.type === "dir" && !item.name.startsWith("."));
121
+ const servers = dirs.map((d) => ({
122
+ id: d.name,
123
+ name: d.name,
124
+ description: `Official Model Context Protocol reference server for ${d.name}`,
125
+ homepage: d.html_url,
126
+ package: `@modelcontextprotocol/server-${d.name}`,
127
+ command: "npx",
128
+ args: ["-y", `@modelcontextprotocol/server-${d.name}`],
129
+ transport: "stdio",
130
+ source: "github",
131
+ verified: true,
132
+ }));
133
+ writeCache(cacheFile, servers);
134
+ return { ok: true, servers, source: "github", total: servers.length };
135
+ }
136
+ // 自定义 URL(支持返回 JSON 格式的 servers 列表)
137
+ const customRes = await fetch(source, {
138
+ headers: fetchHeaders(),
139
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
140
+ });
141
+ if (!customRes.ok) {
142
+ throw new Error(`自定义目录响应错误 HTTP ${customRes.status}`);
143
+ }
144
+ const customData = (await customRes.json());
145
+ const customServers = Array.isArray(customData)
146
+ ? customData
147
+ : Array.isArray(customData.servers)
148
+ ? customData.servers
149
+ : [];
150
+ writeCache(cacheFile, customServers);
151
+ return { ok: true, servers: customServers, source, total: customServers.length };
152
+ }
153
+ catch (err) {
154
+ const msg = err instanceof Error ? err.message : String(err);
155
+ // 网络出错时尝试回退至缓存
156
+ const cached = readCache(cacheFile);
157
+ if (cached) {
158
+ return { ok: true, servers: cached, source, total: cached.length, error: `网络请求失败,已展示本地缓存:${msg}` };
159
+ }
160
+ return { ok: false, servers: [], source, error: msg };
161
+ }
162
+ }
163
+ /** 从 GitHub 仓库拉取 Skills 清单 */
164
+ export async function fetchRemoteSkillMarket(opts) {
165
+ const repo = (opts.repo || "anthropics/skills").trim();
166
+ const cacheKey = `skill-market-${repo.replace(/[^a-zA-Z0-9_-]/g, "_")}.json`;
167
+ const cacheFile = join(opts.dataDir, "market-cache", cacheKey);
168
+ if (!opts.refresh) {
169
+ const cached = readCache(cacheFile);
170
+ if (cached) {
171
+ return { ok: true, skills: cached, repo };
172
+ }
173
+ }
174
+ try {
175
+ // 1. 优先尝试读取 repo 下的 skills 目录;若不存在则尝试根目录
176
+ let apiUrl = `https://api.github.com/repos/${repo}/contents/skills`;
177
+ let res = await fetch(apiUrl, {
178
+ headers: fetchHeaders(),
179
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
180
+ });
181
+ if (res.status === 404) {
182
+ apiUrl = `https://api.github.com/repos/${repo}/contents`;
183
+ res = await fetch(apiUrl, {
184
+ headers: fetchHeaders(),
185
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
186
+ });
187
+ }
188
+ if (!res.ok) {
189
+ throw new Error(`GitHub 仓库 ${repo} 读取失败 HTTP ${res.status}: ${res.statusText}`);
190
+ }
191
+ const items = (await res.json());
192
+ const skillDirs = items.filter((item) => item.type === "dir" && !item.name.startsWith("."));
193
+ // 2. 并发读取每个 skill 的 SKILL.md 提取描述(按 raw github 内容读取,避开 GitHub API rate limit)
194
+ const skills = await Promise.all(skillDirs.map(async (dir) => {
195
+ const id = dir.name;
196
+ const rawUrl = `https://raw.githubusercontent.com/${repo}/main/skills/${id}/SKILL.md`;
197
+ let description = `Agent skill ${id} from ${repo}`;
198
+ try {
199
+ const rawRes = await fetch(rawUrl, {
200
+ headers: { "User-Agent": "pi-web-ui" },
201
+ signal: AbortSignal.timeout(5000),
202
+ });
203
+ if (rawRes.ok) {
204
+ const text = await rawRes.text();
205
+ const descMatch = text.match(/description:\s*(?:>|\|)?\s*([^\r\n]+)/);
206
+ if (descMatch && descMatch[1].trim()) {
207
+ description = descMatch[1].trim();
208
+ }
209
+ }
210
+ }
211
+ catch {
212
+ /* fallback to default description */
213
+ }
214
+ return {
215
+ id,
216
+ name: id,
217
+ description,
218
+ repo,
219
+ url: dir.html_url,
220
+ };
221
+ }));
222
+ writeCache(cacheFile, skills);
223
+ return { ok: true, skills, repo };
224
+ }
225
+ catch (err) {
226
+ const msg = err instanceof Error ? err.message : String(err);
227
+ const cached = readCache(cacheFile);
228
+ if (cached) {
229
+ return { ok: true, skills: cached, repo, error: `网络请求失败,已展示本地缓存:${msg}` };
230
+ }
231
+ return { ok: false, skills: [], repo, error: msg };
232
+ }
233
+ }
234
+ /** 从 GitHub 仓库读取单个技能的完整 SKILL.md 内容 */
235
+ export async function fetchRemoteSkillContent(opts) {
236
+ const { repo, skillId } = opts;
237
+ const branches = ["main", "master"];
238
+ for (const branch of branches) {
239
+ const rawUrl = `https://raw.githubusercontent.com/${repo}/${branch}/skills/${skillId}/SKILL.md`;
240
+ try {
241
+ const res = await fetch(rawUrl, {
242
+ headers: { "User-Agent": "pi-web-ui" },
243
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
244
+ });
245
+ if (res.ok) {
246
+ const content = await res.text();
247
+ return { ok: true, skillId, content };
248
+ }
249
+ }
250
+ catch {
251
+ /* try next branch */
252
+ }
253
+ }
254
+ // 根目录下直接查找
255
+ for (const branch of branches) {
256
+ const rawUrl = `https://raw.githubusercontent.com/${repo}/${branch}/${skillId}/SKILL.md`;
257
+ try {
258
+ const res = await fetch(rawUrl, {
259
+ headers: { "User-Agent": "pi-web-ui" },
260
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
261
+ });
262
+ if (res.ok) {
263
+ const content = await res.text();
264
+ return { ok: true, skillId, content };
265
+ }
266
+ }
267
+ catch {
268
+ /* try next */
269
+ }
270
+ }
271
+ return {
272
+ ok: false,
273
+ skillId,
274
+ content: "",
275
+ error: `未在仓库 ${repo} 中找到技能 ${skillId} 的 SKILL.md 文件`,
276
+ };
277
+ }