@evandu/super-pi 0.1.255 → 0.1.257

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.
@@ -0,0 +1,136 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { dirname } from "node:path";
5
+ const API_ROOT = "https://api.tavily.com";
6
+ const API_TIMEOUT_MS = 15_000;
7
+ const RESPONSE_LIMIT = 2 * 1024 * 1024;
8
+ function apiError(body, status, key) {
9
+ const data = body;
10
+ let message = typeof data?.detail === "string" ? data.detail : data?.detail?.error;
11
+ if (!message)
12
+ message = status === 401 ? "Tavily API key 无效或已撤销。" : `Tavily 请求失败(HTTP ${status})。`;
13
+ if (key)
14
+ message = message.replaceAll(key, "[已隐藏]");
15
+ return new Error(String(message).slice(0, 500));
16
+ }
17
+ function parseResponseText(text) {
18
+ if (text.length > RESPONSE_LIMIT)
19
+ throw new Error("Tavily 响应超过 2 MB 限制。");
20
+ try {
21
+ return JSON.parse(text);
22
+ }
23
+ catch {
24
+ throw new Error("Tavily 返回了无法读取的响应。");
25
+ }
26
+ }
27
+ /** Keeps the user's Tavily credential on the Super Pi server and never returns it to the UI or agent. */
28
+ export class TavilyService {
29
+ configPath;
30
+ apiKey;
31
+ constructor(configPath) {
32
+ this.configPath = configPath;
33
+ if (!existsSync(configPath))
34
+ return;
35
+ try {
36
+ const config = JSON.parse(readFileSync(configPath, "utf8"));
37
+ if (typeof config.apiKey === "string" && config.apiKey.trim())
38
+ this.apiKey = config.apiKey.trim();
39
+ }
40
+ catch { /* A corrupt settings file must not prevent Super Pi from starting. */ }
41
+ }
42
+ get configured() { return Boolean(this.apiKey); }
43
+ async status() {
44
+ if (!this.apiKey)
45
+ return { configured: false, connected: false };
46
+ try {
47
+ const usage = await this.fetchUsage(this.apiKey);
48
+ return this.publicStatus(this.apiKey, usage);
49
+ }
50
+ catch (error) {
51
+ return {
52
+ configured: true,
53
+ connected: false,
54
+ keyHint: `••••${this.apiKey.slice(-4)}`,
55
+ error: error instanceof Error ? error.message : "无法验证 Tavily 连接。",
56
+ };
57
+ }
58
+ }
59
+ async configure(apiKey) {
60
+ const normalized = apiKey.trim();
61
+ if (!normalized || normalized.length > 1024 || /[\r\n\0]/.test(normalized))
62
+ throw new Error("请填写有效的 Tavily API key。");
63
+ const usage = await this.fetchUsage(normalized);
64
+ await mkdir(dirname(this.configPath), { recursive: true, mode: 0o700 });
65
+ const temporary = `${this.configPath}.${randomUUID()}.tmp`;
66
+ try {
67
+ await writeFile(temporary, JSON.stringify({ apiKey: normalized }), { encoding: "utf8", mode: 0o600, flag: "wx" });
68
+ await rename(temporary, this.configPath);
69
+ }
70
+ catch (error) {
71
+ await rm(temporary, { force: true }).catch(() => { });
72
+ throw error;
73
+ }
74
+ this.apiKey = normalized;
75
+ return this.publicStatus(normalized, usage);
76
+ }
77
+ async disconnect() {
78
+ await rm(this.configPath, { force: true });
79
+ this.apiKey = undefined;
80
+ }
81
+ async search(query, limit = 5, signal) {
82
+ const key = this.apiKey;
83
+ if (!key)
84
+ throw new Error("尚未连接 Tavily。请在设置 → Tavily 中连接账号后再搜索。");
85
+ const clean = query.trim();
86
+ if (!clean)
87
+ throw new Error("搜索词不能为空。");
88
+ if (clean.length > 500)
89
+ throw new Error("搜索词不能超过 500 个字符。");
90
+ const response = await fetch(`${API_ROOT}/search`, {
91
+ method: "POST",
92
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json", accept: "application/json" },
93
+ body: JSON.stringify({ query: clean, search_depth: "basic", max_results: Math.min(10, Math.max(1, Math.floor(limit))), include_answer: false, include_raw_content: false }),
94
+ redirect: "error",
95
+ signal: signal ?? AbortSignal.timeout(API_TIMEOUT_MS),
96
+ });
97
+ const body = parseResponseText(await response.text());
98
+ if (!response.ok)
99
+ throw apiError(body, response.status, key);
100
+ const results = (body.results ?? []).flatMap(item => {
101
+ if (!item.title || !item.url)
102
+ return [];
103
+ try {
104
+ const target = new URL(item.url);
105
+ if (!/^https?:$/.test(target.protocol) || target.username || target.password)
106
+ return [];
107
+ return [{ title: item.title, url: target.href, snippet: String(item.content ?? "") }];
108
+ }
109
+ catch {
110
+ return [];
111
+ }
112
+ });
113
+ return { query: clean, results };
114
+ }
115
+ async fetchUsage(key) {
116
+ const response = await fetch(`${API_ROOT}/usage`, {
117
+ headers: { authorization: `Bearer ${key}`, accept: "application/json" },
118
+ redirect: "error",
119
+ signal: AbortSignal.timeout(API_TIMEOUT_MS),
120
+ });
121
+ const body = parseResponseText(await response.text());
122
+ if (!response.ok)
123
+ throw apiError(body, response.status, key);
124
+ return body;
125
+ }
126
+ publicStatus(key, data) {
127
+ const used = Number(data.key?.usage ?? data.account?.plan_usage ?? 0);
128
+ const limit = Number(data.key?.limit ?? data.account?.plan_limit ?? 0);
129
+ return {
130
+ configured: true,
131
+ connected: true,
132
+ keyHint: `••••${key.slice(-4)}`,
133
+ usage: { used, limit, remaining: Math.max(0, limit - used), ...(data.account?.current_plan ? { plan: data.account.current_plan } : {}) },
134
+ };
135
+ }
136
+ }
@@ -1,3 +1,4 @@
1
+ import type { TavilyService } from "./tavily.js";
1
2
  export declare const WEB_SEARCH_TOOL_NAME = "web_search";
2
3
  export declare const WEB_FETCH_TOOL_NAME = "web_fetch";
3
4
  export declare const MAX_WEB_REQUEST_BYTES: number;
@@ -13,9 +14,11 @@ export type WebFetchResult = {
13
14
  truncated: boolean;
14
15
  contentType: string;
15
16
  };
16
- /** Parse Bing's ordinary result page. Kept separate so captured fixtures can guard markup changes. */
17
- export declare function parseBingResults(html: string, limit?: number): WebSearchResult[];
17
+ /** Parse DuckDuckGo Lite result rows and unwrap their destination URLs. */
18
+ export declare function parseDuckDuckGoResults(html: string, limit?: number): WebSearchResult[];
18
19
  export declare class WebService {
20
+ private readonly tavily?;
21
+ constructor(tavily?: TavilyService | undefined);
19
22
  search(query: string, limit?: number, signal?: AbortSignal): Promise<{
20
23
  query: string;
21
24
  results: WebSearchResult[];
@@ -26,25 +26,35 @@ function plainText(html) {
26
26
  return decodeEntities(html.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, " ").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, " ").replace(/<[^>]+>/g, " "))
27
27
  .replace(/\s+/g, " ").trim();
28
28
  }
29
- /** Parse Bing's ordinary result page. Kept separate so captured fixtures can guard markup changes. */
30
- export function parseBingResults(html, limit = 5) {
29
+ /** Parse DuckDuckGo Lite result rows and unwrap their destination URLs. */
30
+ export function parseDuckDuckGoResults(html, limit = 5) {
31
31
  const results = [];
32
- const blocks = html.match(/<li\b[^>]*class=["'][^"']*\bb_algo\b[^"']*["'][^>]*>[\s\S]*?<\/li>/gi) ?? [];
32
+ const starts = [...html.matchAll(/<a\b(?=[^>]*\bclass=["'][^"']*\bresult-link\b[^"']*["'])[^>]*>/gi)].map(match => match.index);
33
+ const blocks = starts.map((start, index) => html.slice(start, starts[index + 1] ?? html.length));
33
34
  for (const block of blocks) {
34
- const anchor = /<h2\b[^>]*>[\s\S]*?<a\b[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/i.exec(block);
35
+ const anchor = /<a\b(?=[^>]*\bclass=["'][^"']*\bresult-link\b[^"']*["'])[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/i.exec(block);
35
36
  if (!anchor)
36
37
  continue;
37
38
  let url;
38
39
  try {
39
- url = new URL(decodeEntities(anchor[1]));
40
+ url = new URL(decodeEntities(anchor[1]), "https://duckduckgo.com");
41
+ if (url.hostname === "duckduckgo.com" && url.pathname === "/l/") {
42
+ const destination = url.searchParams.get("uddg");
43
+ if (!destination)
44
+ continue;
45
+ url = new URL(destination);
46
+ }
40
47
  }
41
48
  catch {
42
49
  continue;
43
50
  }
44
- if (!/^https?:$/.test(url.protocol))
51
+ if (!/^https?:$/.test(url.protocol) || url.username || url.password || /(^|\.)duckduckgo\.com$/i.test(url.hostname))
52
+ continue;
53
+ const cleanTitle = plainText(anchor[2]);
54
+ const caption = /<td\b[^>]*class=["'][^"']*\bresult-snippet\b[^"']*["'][^>]*>([\s\S]*?)<\/td>/i.exec(block)?.[1] ?? "";
55
+ if (!cleanTitle)
45
56
  continue;
46
- const caption = /<p\b[^>]*>([\s\S]*?)<\/p>/i.exec(block)?.[1] ?? "";
47
- results.push({ title: plainText(anchor[2]), url: url.href, snippet: plainText(caption) });
57
+ results.push({ title: cleanTitle, url: url.href, snippet: plainText(caption) });
48
58
  if (results.length >= Math.min(SEARCH_LIMIT, Math.max(1, limit)))
49
59
  break;
50
60
  }
@@ -152,21 +162,14 @@ function extractHtml(html) {
152
162
  return { title, text };
153
163
  }
154
164
  export class WebService {
165
+ tavily;
166
+ constructor(tavily) {
167
+ this.tavily = tavily;
168
+ }
155
169
  async search(query, limit = 5, signal) {
156
- const clean = query.trim();
157
- if (!clean)
158
- throw new Error("搜索词不能为空");
159
- if (clean.length > 500)
160
- throw new Error("搜索词不能超过 500 个字符");
161
- const url = new URL("https://www.bing.com/search");
162
- url.searchParams.set("q", clean);
163
- url.searchParams.set("count", String(Math.min(SEARCH_LIMIT, Math.max(1, Math.floor(limit)))));
164
- url.searchParams.set("setlang", "zh-Hans");
165
- const response = await download(url.href, signal);
166
- const results = parseBingResults(response.body.toString("utf8"), limit);
167
- if (!results.length)
168
- throw new Error("搜索引擎没有返回可解析的结果,可能暂时限流或页面格式已变化");
169
- return { query: clean, results };
170
+ if (!this.tavily)
171
+ throw new Error("网页搜索服务未配置。");
172
+ return this.tavily.search(query, limit, signal);
170
173
  }
171
174
  async fetch(url, signal) {
172
175
  const response = await download(url, signal);
@@ -0,0 +1,4 @@
1
+ /** Title generation is a short background operation; both ends use the same deadline plus a transport margin. */
2
+ export declare const CONVERSATION_TITLE_TIMEOUT_MS = 90000;
3
+ export declare const CONVERSATION_TITLE_CLIENT_TIMEOUT_MS: number;
4
+ export declare const CONVERSATION_TITLE_CONTEXT_MAX_CHARS = 12000;
@@ -0,0 +1,4 @@
1
+ /** Title generation is a short background operation; both ends use the same deadline plus a transport margin. */
2
+ export const CONVERSATION_TITLE_TIMEOUT_MS = 90_000;
3
+ export const CONVERSATION_TITLE_CLIENT_TIMEOUT_MS = CONVERSATION_TITLE_TIMEOUT_MS + 5_000;
4
+ export const CONVERSATION_TITLE_CONTEXT_MAX_CHARS = 12_000;
@@ -7,12 +7,26 @@ export type GroupModel = {
7
7
  export type GroupModerator = {
8
8
  model?: GroupModel;
9
9
  prompt: string;
10
+ cloneLimit?: number;
10
11
  };
11
12
  export declare const DEFAULT_GROUP_MEMBER_IDS: readonly ["solution-designer", "code-designer", "code-auditor", "document-organizer"];
12
13
  export type GroupMember = {
13
14
  id: string;
14
15
  name: string;
15
16
  description: string;
17
+ agentId?: string;
18
+ worktreePath?: string;
19
+ };
20
+ export type GroupCloneRequest = {
21
+ id: string;
22
+ topicId: string;
23
+ memberId: string;
24
+ assignment: string;
25
+ reason: string;
26
+ createdAt: string;
27
+ status: "pending" | "created" | "waiting" | "expired";
28
+ cloneId?: string;
29
+ automatic?: boolean;
16
30
  };
17
31
  export type GroupStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | "interrupted";
18
32
  export type GroupExecutionActivity = {
@@ -91,6 +105,7 @@ export type GroupActivityUpdate = {
91
105
  id: string;
92
106
  workspaceId: string;
93
107
  activity: GroupActivity;
108
+ cloneRequests?: GroupCloneRequest[];
94
109
  };
95
110
  type GroupIdentity = {
96
111
  id: string;
@@ -101,12 +116,14 @@ type GroupIdentity = {
101
116
  };
102
117
  export type GroupSummary = GroupIdentity & {
103
118
  activity: GroupActivity;
119
+ cloneRequests?: GroupCloneRequest[];
104
120
  };
105
121
  export type GroupRoom = GroupIdentity & {
106
122
  members: GroupMember[];
107
123
  moderator: GroupModerator;
108
124
  revision: number;
109
125
  messages: GroupMessage[];
126
+ cloneRequests?: GroupCloneRequest[];
110
127
  };
111
128
  export type GroupSnapshot = Omit<GroupRoom, "revision"> & {
112
129
  revision: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evandu/super-pi",
3
- "version": "0.1.255",
3
+ "version": "0.1.257",
4
4
  "description": "Web control plane and companion for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",