@evandu/super-pi 0.1.256 → 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.
@@ -8,9 +8,9 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-D4e52gDr.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-BStEdM85.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-Bfm53ZYL.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-B9YPOWDi.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -12,6 +12,8 @@ export declare class GroupChatService {
12
12
  private writes;
13
13
  private readonly running;
14
14
  private readonly memberRuns;
15
+ private readonly cloneDecisions;
16
+ private readonly cloneWorktrees;
15
17
  private readonly controllers;
16
18
  private readonly live;
17
19
  private readonly liveExecutions;
@@ -41,10 +43,16 @@ export declare class GroupChatService {
41
43
  prompt?: unknown;
42
44
  };
43
45
  }): Promise<GroupSnapshot>;
46
+ resolveClone(workspaceId: string, id: string, input: {
47
+ requestId?: unknown;
48
+ name?: unknown;
49
+ choice?: unknown;
50
+ }): Promise<GroupSnapshot>;
44
51
  configure(workspaceId: string, id: string, input: {
45
52
  model?: unknown;
46
53
  prompt?: unknown;
47
54
  memberIds?: unknown;
55
+ cloneLimit?: unknown;
48
56
  }): Promise<GroupSnapshot>;
49
57
  send(workspaceId: string, id: string, input: {
50
58
  content?: unknown;
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { open, readFile, realpath, writeFile } from "node:fs/promises";
3
- import { isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { createGitWorktree } from "../git.js";
4
5
  import { DEFAULT_GROUP_MEMBER_IDS } from "../../shared/group-chat.js";
5
6
  import { CODING_STANDARD_REQUEST } from "../active-memory.js";
6
7
  import { applicableRules, assertModelAllowed } from "../model-filter.js";
@@ -58,7 +59,7 @@ function groupActivity(room) {
58
59
  }
59
60
  function summary(room) {
60
61
  const { id, workspaceId, title, updatedAt, archivedAt } = room;
61
- return { id, workspaceId, title, updatedAt, archivedAt, activity: groupActivity(room) };
62
+ return { id, workspaceId, title, updatedAt, archivedAt, activity: groupActivity(room), cloneRequests: room.cloneRequests?.filter(item => item.status === "pending") };
62
63
  }
63
64
  async function readReferences(workspacePath, input) {
64
65
  if (!Array.isArray(input) || !input.length)
@@ -103,6 +104,8 @@ function route(text, candidates, anchors) {
103
104
  return { action: "blocked", reason };
104
105
  if (decision.action === "wait")
105
106
  return { action: "wait", memberId: typeof decision.memberId === "string" ? decision.memberId : undefined };
107
+ if (decision.action === "clone" && typeof decision.memberId === "string")
108
+ return { action: "clone", memberId: decision.memberId, assignment: inputText(decision.assignment, 1600, "分身任务"), reason: reason || "同类成员正在工作,新任务可以独立开展。" };
106
109
  if (!["reply", "background"].includes(String(decision.action)) || typeof decision.memberId !== "string" || !candidates.some(member => member.id === decision.memberId)) {
107
110
  throw new Error("主持人选择了无效的群成员。");
108
111
  }
@@ -143,6 +146,8 @@ export class GroupChatService {
143
146
  writes = Promise.resolve();
144
147
  running = new Map();
145
148
  memberRuns = new Map();
149
+ cloneDecisions = new Map();
150
+ cloneWorktrees = new Map();
146
151
  controllers = new Map();
147
152
  live = new Map();
148
153
  liveExecutions = new Map();
@@ -166,7 +171,12 @@ export class GroupChatService {
166
171
  }
167
172
  if (service.rooms.some(room => room.messages.some(post => post.status === "running" || (post.role === "assistant" && post.status === "queued")))) {
168
173
  await service.edit(rooms => {
169
- for (const room of rooms)
174
+ for (const room of rooms) {
175
+ for (const request of room.cloneRequests ?? [])
176
+ if (request.status === "pending") {
177
+ request.status = "expired";
178
+ room.revision += 1;
179
+ }
170
180
  for (const post of room.messages)
171
181
  if (post.status === "running" || (post.role === "assistant" && post.status === "queued")) {
172
182
  post.status = "interrupted";
@@ -176,6 +186,7 @@ export class GroupChatService {
176
186
  room.executions[post.id] = finishGroupExecution(trace);
177
187
  room.revision += 1;
178
188
  }
189
+ }
179
190
  });
180
191
  }
181
192
  for (const room of service.rooms)
@@ -232,8 +243,8 @@ export class GroupChatService {
232
243
  continue;
233
244
  const activity = groupActivity(room);
234
245
  const priorActivity = groupActivity(before);
235
- if (activity.status !== priorActivity.status || activity.lastReplyAt !== priorActivity.lastReplyAt)
236
- this.onActivity({ id: room.id, workspaceId: room.workspaceId, activity });
246
+ if (activity.status !== priorActivity.status || activity.lastReplyAt !== priorActivity.lastReplyAt || JSON.stringify(room.cloneRequests) !== JSON.stringify(before.cloneRequests))
247
+ this.onActivity({ id: room.id, workspaceId: room.workspaceId, activity, cloneRequests: room.cloneRequests?.filter(item => item.status === "pending") ?? [] });
237
248
  }
238
249
  }
239
250
  list(workspaceId) {
@@ -310,8 +321,9 @@ export class GroupChatService {
310
321
  async moderator(workspaceId, body) {
311
322
  const workspace = this.workspace(workspaceId);
312
323
  const prompt = inputText(body.prompt ?? "", 8_000, "主持人 Prompt");
324
+ const cloneLimit = typeof body.cloneLimit === "number" && Number.isInteger(body.cloneLimit) && body.cloneLimit >= 2 && body.cloneLimit <= 8 ? body.cloneLimit : undefined;
313
325
  if (!body.model)
314
- return { prompt };
326
+ return { prompt, cloneLimit };
315
327
  if (typeof body.model !== "object")
316
328
  throw new Error("主持人模型无效。");
317
329
  const requested = body.model;
@@ -320,7 +332,7 @@ export class GroupChatService {
320
332
  if (!model)
321
333
  throw new Error("主持人模型不可用。");
322
334
  assertModelAllowed(this.store.modelFilterRules(), workspace, model);
323
- return { prompt, model: { provider: model.provider, modelId: model.modelId, label: model.label } };
335
+ return { prompt, cloneLimit, model: { provider: model.provider, modelId: model.modelId, label: model.label } };
324
336
  }
325
337
  async resolveMembers(id, input, existing = []) {
326
338
  const memberIds = Array.isArray(input) ? [...new Set(input)] : [];
@@ -350,6 +362,59 @@ export class GroupChatService {
350
362
  await this.edit(rooms => { rooms.push(room); });
351
363
  return this.get(workspaceId, id);
352
364
  }
365
+ async resolveClone(workspaceId, id, input) {
366
+ const requestId = inputText(input.requestId, 100, "创建请求");
367
+ if (input.choice !== "create" && input.choice !== "wait")
368
+ throw new Error("请选择创建分身或等待。");
369
+ const name = input.choice === "create" ? inputText(input.name, 80, "分身名字") : "";
370
+ if (input.choice === "create" && !name)
371
+ throw new Error("请填写分身名字。");
372
+ const current = this.activeRoom(this.rooms, workspaceId, id);
373
+ const pending = current.cloneRequests?.find(item => item.id === requestId && item.status === "pending");
374
+ let worktreePath;
375
+ if (input.choice === "create" && pending) {
376
+ let creating = this.cloneWorktrees.get(requestId);
377
+ if (!creating) {
378
+ creating = createGitWorktree(this.workspace(workspaceId).path, join(dirname(this.filePath), "worktrees"), requestId, { branch: `group/clone-${requestId}` }).then(entry => entry.path);
379
+ this.cloneWorktrees.set(requestId, creating);
380
+ }
381
+ try {
382
+ worktreePath = await creating;
383
+ }
384
+ catch (error) {
385
+ this.cloneWorktrees.delete(requestId);
386
+ throw error;
387
+ }
388
+ }
389
+ await this.edit(rooms => {
390
+ const room = this.activeRoom(rooms, workspaceId, id);
391
+ const request = room.cloneRequests?.find(item => item.id === requestId);
392
+ if (!request)
393
+ throw new Error("创建请求不存在。");
394
+ if (request.status !== "pending")
395
+ return;
396
+ const source = room.members.find(member => member.id === request.memberId);
397
+ const topic = room.messages.find(post => post.id === request.topicId);
398
+ const busy = room.messages.some(post => post.role === "assistant" && post.memberId === source?.id && (post.status === "running" || post.status === "queued"));
399
+ if (!source || topic?.status !== "running" || !busy)
400
+ request.status = "expired";
401
+ else if (input.choice === "wait")
402
+ request.status = "waiting";
403
+ else {
404
+ if (room.members.length >= 8)
405
+ throw new Error("群聊最多支持 8 位成员。");
406
+ if (room.members.some(member => member.name === name))
407
+ throw new Error("群里已有同名成员,请换一个名字。");
408
+ const cloneId = randomUUID();
409
+ room.members.push({ ...source, id: cloneId, name, agentId: source.agentId ?? source.id, worktreePath });
410
+ request.cloneId = cloneId;
411
+ request.status = "created";
412
+ }
413
+ room.revision += 1;
414
+ });
415
+ this.cloneDecisions.get(requestId)?.();
416
+ return this.get(workspaceId, id);
417
+ }
353
418
  async configure(workspaceId, id, input) {
354
419
  const current = this.activeRoom(this.rooms, workspaceId, id);
355
420
  const moderator = await this.moderator(workspaceId, input);
@@ -491,9 +556,93 @@ export class GroupChatService {
491
556
  await Promise.race(active.map(reply => reply.done));
492
557
  continue;
493
558
  }
494
- const next = candidates.length || handoffs.length || !remaining || (replies.length && available.some(member => busy.has(member.id)))
559
+ const next = candidates.length || busy.size || handoffs.length || !remaining
495
560
  ? await this.choose(current, topic, candidates, replies, handoffs, busy, remaining, controller.signal)
496
561
  : { action: "finish" };
562
+ if (next.action === "clone") {
563
+ const source = current.members.find(member => member.id === next.memberId && busy.has(member.id));
564
+ if (!source) {
565
+ incomplete = "成员状态已变化,请继续本轮任务。";
566
+ break;
567
+ }
568
+ const idle = candidates.find(member => (member.agentId ?? member.id) === (source.agentId ?? source.id));
569
+ if (idle && remaining) {
570
+ await start([{ memberId: idle.id, replyTo: topic.id, assignment: next.assignment }]);
571
+ count += 1;
572
+ continue;
573
+ }
574
+ const work = this.memberRuns.get(JSON.stringify([room.id, source.id]));
575
+ if (!remaining) {
576
+ incomplete = "本轮达到自动接话上限。";
577
+ break;
578
+ }
579
+ if (current.members.length >= 8 || current.cloneRequests?.some(item => item.topicId === topic.id && item.memberId === source.id)) {
580
+ if (work)
581
+ await this.waitForWork(work, controller.signal);
582
+ else {
583
+ incomplete = "成员状态已变化,请继续本轮任务。";
584
+ break;
585
+ }
586
+ continue;
587
+ }
588
+ const requestId = randomUUID();
589
+ let decide;
590
+ const decision = new Promise(resolve => { decide = resolve; });
591
+ this.cloneDecisions.set(requestId, decide);
592
+ const sameRole = current.members.filter(member => (member.agentId ?? member.id) === (source.agentId ?? source.id));
593
+ const automatic = Boolean(current.moderator.cloneLimit && sameRole.length < current.moderator.cloneLimit);
594
+ try {
595
+ await this.edit(rooms => {
596
+ const target = rooms.find(item => item.id === room.id);
597
+ (target.cloneRequests ??= []).push({ id: requestId, topicId: topic.id, memberId: source.id, assignment: next.assignment, reason: next.reason, createdAt: timestamp(), status: "pending", automatic });
598
+ target.revision += 1;
599
+ });
600
+ if (automatic) {
601
+ let suffix = 2;
602
+ const sourceName = current.members.find(member => member.id === (source.agentId ?? source.id))?.name ?? source.name;
603
+ while (current.members.some(member => member.name === `${sourceName} ${suffix}`))
604
+ suffix += 1;
605
+ try {
606
+ await this.resolveClone(room.workspaceId, room.id, { requestId, choice: "create", name: `${sourceName} ${suffix}` });
607
+ }
608
+ catch {
609
+ await this.edit(rooms => {
610
+ const target = rooms.find(item => item.id === room.id);
611
+ const request = target.cloneRequests.find(item => item.id === requestId);
612
+ request.automatic = false;
613
+ request.reason = "自动准备独立 Git 工作树失败,请手动重试创建或等待原成员。";
614
+ target.revision += 1;
615
+ });
616
+ }
617
+ }
618
+ await this.waitForWork(work ? Promise.race([decision, work]) : Promise.resolve(), controller.signal);
619
+ const resolved = await this.edit(rooms => {
620
+ const target = rooms.find(item => item.id === room.id);
621
+ const request = target.cloneRequests.find(item => item.id === requestId);
622
+ if (request.status === "pending") {
623
+ request.status = "expired";
624
+ target.revision += 1;
625
+ }
626
+ return request;
627
+ });
628
+ if (resolved.cloneId && !controller.signal.aborted) {
629
+ await start([{ memberId: resolved.cloneId, replyTo: topic.id, assignment: next.assignment, background: true }]);
630
+ count += 1;
631
+ }
632
+ else {
633
+ if (resolved.status === "waiting" && work)
634
+ await this.waitForWork(work, controller.signal);
635
+ if (!controller.signal.aborted && this.rooms.find(item => item.id === room.id)?.members.some(member => member.id === source.id)) {
636
+ await start([{ memberId: source.id, replyTo: topic.id, assignment: next.assignment, background: true }]);
637
+ count += 1;
638
+ }
639
+ }
640
+ }
641
+ finally {
642
+ this.cloneDecisions.delete(requestId);
643
+ }
644
+ continue;
645
+ }
497
646
  if (next.action === "reply") {
498
647
  if (!remaining) {
499
648
  incomplete = "本轮达到自动接话上限,已有进展已保留。可以告诉群里从哪一步继续。";
@@ -552,11 +701,21 @@ export class GroupChatService {
552
701
  }
553
702
  finally {
554
703
  await Promise.allSettled(pending.map(reply => reply.done));
704
+ await this.edit(rooms => {
705
+ const current = rooms.find(item => item.id === room.id);
706
+ if (!current)
707
+ return;
708
+ for (const request of current.cloneRequests ?? [])
709
+ if (request.topicId === topic.id && request.status === "pending") {
710
+ request.status = "expired";
711
+ current.revision += 1;
712
+ }
713
+ });
555
714
  this.controllers.delete(topic.id);
556
715
  const current = this.rooms.find(item => item.id === room.id);
557
716
  const saved = current?.messages.find(post => post.id === topic.id);
558
717
  if (!this.closing && current && (saved?.status === "completed" || saved?.status === "failed")) {
559
- this.memory?.learnFromGroup(room.workspaceId, room.id, topic, current.members.map(member => member.id), () => this.rooms.some(item => item.id === room.id && item.messages.some(post => post.id === topic.id && post.role === "user" && post.content === topic.content)));
718
+ this.memory?.learnFromGroup(room.workspaceId, room.id, topic, [...new Set(current.members.map(member => member.agentId ?? member.id))], () => this.rooms.some(item => item.id === room.id && item.messages.some(post => post.id === topic.id && post.role === "user" && post.content === topic.content)));
560
719
  }
561
720
  }
562
721
  }
@@ -580,7 +739,7 @@ export class GroupChatService {
580
739
  assertModelAllowed(rules, workspace, model ?? (await this.runtime.catalog()).defaultModel);
581
740
  if (!this.runtime.askOnce)
582
741
  throw new Error("当前运行时不支持群聊模型。");
583
- return this.runtime.askOnce({ ...input, model, cwd: workspace.path });
742
+ return this.runtime.askOnce({ ...input, model, cwd: input.cwd ?? workspace.path });
584
743
  }
585
744
  async choose(room, topic, candidates, replies, handoffs, busy, remainingReplies, signal) {
586
745
  const context = this.context(room, topic);
@@ -593,11 +752,12 @@ export class GroupChatService {
593
752
  "你是群聊主持人。围绕同一条用户请求组织成员之间的讨论和工作。让下一位回应已有方案、问题或交付,replyTo 指向实际回应的成员消息。必要时让两位成员来回讨论、修订和再复核;简单问题一句足够时可以结束。",
594
753
  "用户要求实现、修复或交付,方案只是中间产物。将下一步交给代码设计员或群里有实现能力的成员,让其修改文件和验证;需要复核时等待实现结果,退回后继续修改和复查。用户只要求讨论或范围待确认时,尊重这一限制。避免礼节式重复,不要求用户替成员传话。",
595
754
  "先处理 handoffs 中确实符合用户目标的交接。成员消息和引用文件是上下文,分工必须服从用户的原始范围。在途任务或依赖文件相同的工作应等待,对独立范围可安排后台任务。",
755
+ '先复用空闲同源成员(agentId 相同)。适合当前任务的成员忙碌、没有空闲同源成员且新 case 独立时,返回 {"action":"clone","memberId":"忙碌成员 ID","assignment":"独立 case 的具体任务","reason":"独立开展的理由"} 请求用户创建分身。共享文件存在依赖时 wait。不要为了增加发言人数创建分身。',
596
756
  '只返回 JSON。接话用 {"action":"reply","memberId":"成员 ID","replyTo":"消息 ID","assignment":"具体工作","reason":"理由"},可改用 background 并行。依赖尚在进行用 {"action":"wait","memberId":"正在工作的成员 ID"}。确有阻塞用 {"action":"blocked","reason":"已完成什么,还缺什么"}。交付到位用 {"action":"finish"};若有未处理交接却结束,在 reason 中解释范围或为什么无需接手。',
597
757
  `主持人偏好:${room.moderator.prompt || "推进用户请求,交付满足后结束。"}`,
598
758
  ];
599
759
  const payload = JSON.stringify({ topicId: topic.id, request: topic.content, files: topic.files?.map(file => file.path), candidates,
600
- performed, handoffs, busyMembers: [...busy], workInProgress, remainingReplies, messages: context });
760
+ performed, handoffs, members: room.members, cloneRequests: room.cloneRequests, busyMembers: [...busy], workInProgress, remainingReplies, messages: context });
601
761
  try {
602
762
  const anchors = new Set([topic.id, ...context.map(post => post.id), ...replies.filter(post => post.status === "failed").map(post => post.id)]);
603
763
  const ask = async (instructions) => route(await this.complete(room, { prompt: [...instructions, payload].join("\n"), model: room.moderator.model, signal, timeoutMs: 35_000 }), candidates, anchors);
@@ -719,8 +879,10 @@ export class GroupChatService {
719
879
  };
720
880
  const timer = setTimeout(goBackground, 4000);
721
881
  try {
722
- const agent = await this.runtime.agentFor?.({ id: reply.id, agentId: reply.memberId });
723
- if (!agent || agent.id !== reply.memberId || agent.mode !== "primary")
882
+ const member = started.members.find(item => item.id === reply.memberId);
883
+ const agentId = member?.agentId ?? reply.memberId;
884
+ const agent = await this.runtime.agentFor?.({ id: reply.id, agentId });
885
+ if (!agent || agent.id !== agentId || agent.mode !== "primary")
724
886
  throw new Error("该主 Agent 已不可用。");
725
887
  const notes = await this.memory?.groupEngineeringNotes(started.workspaceId, agent.id, topic.content + "\n" + (reply.assignment ?? ""))
726
888
  .catch(() => undefined);
@@ -730,7 +892,8 @@ export class GroupChatService {
730
892
  JSON.stringify({ request: topic.content, files: topic.files, replyTo: reply.replyTo, quote: started.messages.find(post => post.id === reply.replyTo)?.content.slice(0, 4_000), assignment: reply.assignment, members: started.members, messages: this.context(started, topic), notes }),
731
893
  ].join("\n");
732
894
  const answer = await this.complete(started, {
733
- prompt, agent, model: agent.model && { ...agent.model, label: agent.model.modelId }, signal: memberSignal, timeoutMs: 15 * 60_000,
895
+ prompt: `群内身份:${member?.name ?? agent.name}。${member?.worktreePath ? "你在独立工作树工作;报告分支和产物供后续审查整合。" : ""}\n${prompt}`, cwd: member?.worktreePath,
896
+ agent, model: agent.model && { ...agent.model, label: agent.model.modelId }, signal: memberSignal, timeoutMs: 15 * 60_000,
734
897
  onToolStart: goBackground,
735
898
  onExecution: event => {
736
899
  if (memberSignal.aborted || !execution.record(event))
@@ -454,6 +454,10 @@ export function createHttpServer(options) {
454
454
  json(200, await groups.configure(workspaceId, roomId, body));
455
455
  return;
456
456
  }
457
+ if (body?.action === "clone.resolve") {
458
+ json(200, await groups.resolveClone(workspaceId, roomId, body));
459
+ return;
460
+ }
457
461
  if (body?.action === "archive" || body?.action === "restore") {
458
462
  json(200, await groups.setArchived(workspaceId, roomId, body.action === "archive"));
459
463
  return;
@@ -1248,6 +1252,51 @@ export function createHttpServer(options) {
1248
1252
  }
1249
1253
  return;
1250
1254
  }
1255
+ if (url.pathname === "/api/tavily/settings") {
1256
+ const origin = request.headers.origin;
1257
+ const fetchSite = request.headers["sec-fetch-site"];
1258
+ if (!isLocalOrPrivateAddress(remote) || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
1259
+ json(403, { error: "Tavily 凭据设置只允许本机或局域网的同源请求。" });
1260
+ return;
1261
+ }
1262
+ if (!context.tavily) {
1263
+ json(503, { error: "Tavily 设置不可用。" });
1264
+ return;
1265
+ }
1266
+ try {
1267
+ if (request.method === "GET") {
1268
+ json(200, await context.tavily.status());
1269
+ return;
1270
+ }
1271
+ if (request.method !== "POST") {
1272
+ json(405, { error: "Tavily 设置仅支持 GET / POST。" });
1273
+ return;
1274
+ }
1275
+ const asked = await readRequestText(request, 4096);
1276
+ if (asked.tooLarge) {
1277
+ json(413, { error: "Tavily 设置请求过大。" });
1278
+ return;
1279
+ }
1280
+ const body = JSON.parse(asked.text || "{}");
1281
+ if (body.action === "connect") {
1282
+ const status = await context.tavily.configure(String(body.apiKey ?? ""));
1283
+ process.env.SUPER_PI_WEB_ENABLED = "1";
1284
+ json(200, status);
1285
+ return;
1286
+ }
1287
+ if (body.action === "disconnect") {
1288
+ await context.tavily.disconnect();
1289
+ process.env.SUPER_PI_WEB_ENABLED = "0";
1290
+ json(200, { configured: false, connected: false });
1291
+ return;
1292
+ }
1293
+ json(400, { error: "未知的 Tavily 设置操作。" });
1294
+ }
1295
+ catch (error) {
1296
+ json(400, { error: error instanceof SyntaxError ? "Tavily 设置格式不正确。" : error instanceof Error ? error.message : "Tavily 设置失败。" });
1297
+ }
1298
+ return;
1299
+ }
1251
1300
  if (url.pathname === "/api/web/tool") {
1252
1301
  if (!context.web) {
1253
1302
  response.writeHead(503).end();
@@ -43,6 +43,7 @@ import { ToolRegistry } from "./tool-registry.js";
43
43
  import { ToolRunner } from "./tool-runner.js";
44
44
  import { ToolLlmService } from "./tool-llm.js";
45
45
  import { WebService } from "./web.js";
46
+ import { TavilyService } from "./tavily.js";
46
47
  // ------------------------------------------------------------- Environment & paths
47
48
  const rootDir = resolve(import.meta.dirname, "../..");
48
49
  initRunningVersion(rootDir);
@@ -197,8 +198,10 @@ process.env.SUPER_PI_DOCUMENTS_ENDPOINT = documentsEndpoint;
197
198
  // verifies the session's capability on its own.
198
199
  const feishu = new FeishuService();
199
200
  process.env.SUPER_PI_FEISHU_ENDPOINT = `http://${internalHost}:${port}/api/feishu/tool`;
200
- const web = new WebService();
201
+ const tavily = new TavilyService(join(dataDir, "tavily.json"));
202
+ const web = new WebService(tavily);
201
203
  process.env.SUPER_PI_WEB_ENDPOINT = `http://${internalHost}:${port}/api/web/tool`;
204
+ process.env.SUPER_PI_WEB_ENABLED = tavily.configured ? "1" : "0";
202
205
  const extensionUiService = new ExtensionUiService(broadcaster, id => {
203
206
  const { parentConversationId, parent } = store.childSessionFacts(id);
204
207
  return !isChildSession(parentConversationId, parent);
@@ -358,6 +361,7 @@ const serverContext = {
358
361
  memory,
359
362
  knowledge,
360
363
  web,
364
+ tavily,
361
365
  documentService,
362
366
  feishu,
363
367
  paths,
@@ -821,7 +821,7 @@ export class PiRpcRuntime {
821
821
  // forget to release.
822
822
  SUPER_PI_DOCUMENTS_ENDPOINT: this.options.documentsEndpoint ?? "",
823
823
  SUPER_PI_DOCUMENTS_CONVERSATION: conversationId,
824
- SUPER_PI_WEB_ENDPOINT: process.env.SUPER_PI_WEB_ENDPOINT ?? "",
824
+ SUPER_PI_WEB_ENDPOINT: process.env.SUPER_PI_WEB_ENABLED === "1" ? process.env.SUPER_PI_WEB_ENDPOINT ?? "" : "",
825
825
  // The Feishu tools' endpoint and the conversation they act for. The CREDENTIAL is not here:
826
826
  // it is the session's own capability, the same value the task dispatch uses, because a
827
827
  // second credential for one session would be a second thing to rotate and to release.
@@ -1376,7 +1376,7 @@ export class PiRpcRuntime {
1376
1376
  names.push("memory", "skill_manage", "session_search");
1377
1377
  if (this.knowledge)
1378
1378
  names.push(KNOWLEDGE_TOOL_NAME, KNOWLEDGE_IMPORT_TOOL_NAME);
1379
- if (process.env.SUPER_PI_WEB_ENDPOINT)
1379
+ if (process.env.SUPER_PI_WEB_ENDPOINT && process.env.SUPER_PI_WEB_ENABLED === "1")
1380
1380
  names.push(WEB_SEARCH_TOOL_NAME, WEB_FETCH_TOOL_NAME);
1381
1381
  // The document tools are named whenever the endpoint is configured, because that is what decides
1382
1382
  // whether the extension registers them. An agent that declares `tools: {"*": false, read: true}`
@@ -1586,7 +1586,7 @@ export class PiRpcRuntime {
1586
1586
  const knowledgeExtension = resolve(import.meta.dirname, "../../agents/super-pi-knowledge/index.ts");
1587
1587
  const knowledgeArgs = knowledgeEnabled ? ["--extension", knowledgeExtension] : [];
1588
1588
  const webExtension = resolve(import.meta.dirname, "../../agents/super-pi-web/index.ts");
1589
- const webEnabled = !memoryReview && !knowledgeRerank && existsSync(webExtension) && !!process.env.SUPER_PI_WEB_ENDPOINT;
1589
+ const webEnabled = !memoryReview && !knowledgeRerank && existsSync(webExtension) && !!process.env.SUPER_PI_WEB_ENDPOINT && process.env.SUPER_PI_WEB_ENABLED === "1";
1590
1590
  const webArgs = webEnabled ? ["--extension", webExtension] : [];
1591
1591
  // The Feishu tools are mounted for every ordinary turn, and NOT for a review or a rerank: a
1592
1592
  // background reflection has no business reading a company's cloud documents, and a reranker
@@ -40,6 +40,7 @@ export interface ServerContext {
40
40
  memory?: import("./active-memory.js").ActiveMemory;
41
41
  knowledge?: import("./knowledge.js").KnowledgeBase;
42
42
  web?: import("./web.js").WebService;
43
+ tavily?: import("./tavily.js").TavilyService;
43
44
  /** The agent-facing document tools. Optional so the server can start without them. */
44
45
  documentService?: import("./application/document-service.js").DocumentService;
45
46
  /**
@@ -0,0 +1,32 @@
1
+ export type TavilyPublicStatus = {
2
+ configured: boolean;
3
+ connected: boolean;
4
+ keyHint?: string;
5
+ usage?: {
6
+ used: number;
7
+ limit: number;
8
+ remaining: number;
9
+ plan?: string;
10
+ };
11
+ error?: string;
12
+ };
13
+ /** Keeps the user's Tavily credential on the Super Pi server and never returns it to the UI or agent. */
14
+ export declare class TavilyService {
15
+ private readonly configPath;
16
+ private apiKey?;
17
+ constructor(configPath: string);
18
+ get configured(): boolean;
19
+ status(): Promise<TavilyPublicStatus>;
20
+ configure(apiKey: string): Promise<TavilyPublicStatus>;
21
+ disconnect(): Promise<void>;
22
+ search(query: string, limit?: number, signal?: AbortSignal): Promise<{
23
+ query: string;
24
+ results: Array<{
25
+ title: string;
26
+ url: string;
27
+ snippet: string;
28
+ }>;
29
+ }>;
30
+ private fetchUsage;
31
+ private publicStatus;
32
+ }
@@ -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
+ }