@evandu/super-pi 0.1.254 → 0.1.256

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 (45) hide show
  1. package/agents/super-pi-task/core.ts +1 -1
  2. package/agents/super-pi-task/index.ts +24 -0
  3. package/agents/super-pi-web/index.ts +1 -1
  4. package/dist/client/.super-pi-client-sources.json +11 -11
  5. package/dist/client/assets/{CodeMirrorEditor-DdxPcLjw.js → CodeMirrorEditor-DLrgnK0F.js} +2 -2
  6. package/dist/client/assets/GitDiffEditor-DkVFBAIL.js +29 -0
  7. package/dist/client/assets/{dist-D1NpQAva.js → dist-AW5lyI3I.js} +1 -1
  8. package/dist/client/assets/{dist-DkPVc7Rf.js → dist-BGxkyh6e.js} +1 -1
  9. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  10. package/dist/client/assets/{dist-AczI3ocs.js → dist-BRVQKlcp.js} +1 -1
  11. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  12. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  13. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  14. package/dist/client/assets/{dist-DRk4qy9i.js → dist-Cx00EZKR.js} +2 -2
  15. package/dist/client/assets/{dist-D09S6VMH.js → dist-D71y2EI1.js} +1 -1
  16. package/dist/client/assets/{dist-CISO_jYt.js → dist-Dc1MBGAG.js} +1 -1
  17. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  18. package/dist/client/assets/{dist-BbuAnJ4T.js → dist-DeD9copn.js} +1 -1
  19. package/dist/client/assets/{dist-BUl4ovQu.js → dist-DuvGReu-.js} +2 -2
  20. package/dist/client/assets/{dist-C8yZkfJN.js → dist-Dvb0SqcK.js} +2 -2
  21. package/dist/client/assets/{dist-BsG-6pTu.js → dist-J6XWqRpB.js} +1 -1
  22. package/dist/client/assets/{dist-BSugRTzs.js → dist-QzbOCAU6.js} +1 -1
  23. package/dist/client/assets/{dist-uuaqc1SU.js → dist-moiMRpw_.js} +1 -1
  24. package/dist/client/assets/index-Bfm53ZYL.css +1 -0
  25. package/dist/client/assets/{index-WcUajwk6.js → index-D4e52gDr.js} +18 -18
  26. package/dist/client/index.html +2 -2
  27. package/dist/server/agents.d.ts +1 -1
  28. package/dist/server/agents.js +1 -1
  29. package/dist/server/http-server.js +91 -1
  30. package/dist/server/runtime.js +39 -9
  31. package/dist/server/tool-registry.d.ts +12 -0
  32. package/dist/server/tool-registry.js +24 -1
  33. package/dist/server/web.d.ts +2 -2
  34. package/dist/server/web.js +21 -12
  35. package/dist/shared/conversation-title.d.ts +4 -0
  36. package/dist/shared/conversation-title.js +4 -0
  37. package/package.json +1 -1
  38. package/skills/super-pi-tool-development/SKILL.md +12 -0
  39. package/dist/client/assets/GitDiffEditor-CNCMPKVv.js +0 -27
  40. package/dist/client/assets/dist-0FXz0KLB.js +0 -9
  41. package/dist/client/assets/dist-D5-SYidb.js +0 -1
  42. package/dist/client/assets/dist-QyJg7PsR.js +0 -11
  43. package/dist/client/assets/dist-gBVaCjue.js +0 -1
  44. package/dist/client/assets/dist-vK4fMIi8.js +0 -1
  45. package/dist/client/assets/index-BvAvBj_1.css +0 -1
@@ -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-WcUajwk6.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-D4e52gDr.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-BvAvBj_1.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-Bfm53ZYL.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -38,7 +38,7 @@ type Frontmatter = Record<string, unknown>;
38
38
  */
39
39
  export declare const PI_TOOL_NAMES: readonly ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls", "codemode", "tool_search", "list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"];
40
40
  /** Tools shipped by this package. Authors must be able to explicitly deny host extras. */
41
- export declare const SUPER_PI_TOOL_NAMES: readonly ["task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "memory", "skill_manage", "session_search", "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder", "knowledge_search", "knowledge_import", "document_read", "document_write", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write"];
41
+ export declare const SUPER_PI_TOOL_NAMES: readonly ["task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "tool_shortcut", "tool_remove", "memory", "skill_manage", "session_search", "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder", "knowledge_search", "knowledge_import", "document_read", "document_write", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write"];
42
42
  /**
43
43
  * Whether a name can be a real Pi tool. A name is real if it is one of `PI_TOOL_NAMES`, an MCP
44
44
  * server tool, or a PATTERN.
@@ -39,7 +39,7 @@ export const PI_TOOL_NAMES = [
39
39
  ];
40
40
  /** Tools shipped by this package. Authors must be able to explicitly deny host extras. */
41
41
  export const SUPER_PI_TOOL_NAMES = [
42
- "task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register",
42
+ "task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "tool_shortcut", "tool_remove",
43
43
  "memory", "skill_manage", "session_search",
44
44
  "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder",
45
45
  "knowledge_search", "knowledge_import",
@@ -406,7 +406,7 @@ export function createHttpServer(options) {
406
406
  // the endpoint that can spend it is exactly the one an agent's own turn can reach, and the
407
407
  // management half (`/api/feishu/config`) stays behind the ordinary token AND the local-address
408
408
  // predicate.
409
- if (requestPath !== "/api/conversations" && requestPath !== "/api/conversation/usage" && requestPath !== "/api/memory/tool" && requestPath !== "/api/knowledge/tool" && requestPath !== "/api/documents/tool" && requestPath !== "/api/web/tool" && requestPath !== "/api/feishu/tool" && requestPath !== "/api/todos" && requestPath !== "/api/scheduled-tasks" && requestPath !== "/api/projects/tool" && requestPath !== "/api/question" && (requestPath !== "/api/tools" || request.method !== "POST") && !requestPath.startsWith("/tools/") && !isAuthorized(request, accessToken)) {
409
+ if (requestPath !== "/api/conversations" && requestPath !== "/api/conversation/usage" && requestPath !== "/api/memory/tool" && requestPath !== "/api/knowledge/tool" && requestPath !== "/api/documents/tool" && requestPath !== "/api/web/tool" && requestPath !== "/api/feishu/tool" && requestPath !== "/api/todos" && requestPath !== "/api/scheduled-tasks" && requestPath !== "/api/projects/tool" && requestPath !== "/api/question" && requestPath !== "/api/tools/agent" && (requestPath !== "/api/tools" || request.method !== "POST") && !requestPath.startsWith("/tools/") && !isAuthorized(request, accessToken)) {
410
410
  response.writeHead(401, { "www-authenticate": "Bearer" }).end("Authentication required");
411
411
  return;
412
412
  }
@@ -573,6 +573,96 @@ export function createHttpServer(options) {
573
573
  return;
574
574
  }
575
575
  }
576
+ if (url.pathname === "/api/tools/shortcut") {
577
+ try {
578
+ if (request.method !== "POST") {
579
+ json(405, { error: "这个接口只接受 POST 请求。" });
580
+ return;
581
+ }
582
+ const input = await readRequestText(request, 8_000);
583
+ if (input.tooLarge) {
584
+ json(413, { error: "快捷键请求内容过大。" });
585
+ return;
586
+ }
587
+ const body = JSON.parse(input.text);
588
+ if (!body.slug) {
589
+ json(400, { error: "缺少工具 slug。" });
590
+ return;
591
+ }
592
+ const result = await toolRegistry.setShortcut(body.slug, body.shortcut ?? undefined);
593
+ if (result.conflict) {
594
+ json(409, { error: `快捷键已被「${result.conflict}」占用。` });
595
+ return;
596
+ }
597
+ broadcaster.broadcast({ type: "tools.updated", tools: await toolRegistry.list() });
598
+ json(200, { ok: true });
599
+ return;
600
+ }
601
+ catch (error) {
602
+ json(400, { error: describeThrown(error) || "快捷键设置失败。" });
603
+ return;
604
+ }
605
+ }
606
+ if (url.pathname === "/api/tools/agent") {
607
+ try {
608
+ if (request.method !== "POST") {
609
+ json(405, { error: "这个接口只接受 POST 请求。" });
610
+ return;
611
+ }
612
+ const input = await readRequestText(request, 8_000);
613
+ if (input.tooLarge) {
614
+ json(413, { error: "工具操作请求内容过大。" });
615
+ return;
616
+ }
617
+ const body = JSON.parse(input.text);
618
+ if (!body.conversationId || !runService.verifyPrimaryCapability(body.conversationId, body.capability ?? request.headers["x-super-pi-capability"]).ok) {
619
+ json(403, { error: "只有当前主会话可以管理全局工具。" });
620
+ return;
621
+ }
622
+ if (!body.slug) {
623
+ json(400, { error: "缺少工具 slug。" });
624
+ return;
625
+ }
626
+ if (body.action === "get-shortcut") {
627
+ const tool = (await toolRegistry.list()).find(item => item.slug === body.slug);
628
+ if (!tool) {
629
+ json(404, { error: "找不到这个工具,可能已经下架。" });
630
+ return;
631
+ }
632
+ json(200, { shortcut: tool.shortcut ?? null });
633
+ return;
634
+ }
635
+ if (body.action === "set-shortcut") {
636
+ const result = await toolRegistry.setShortcut(body.slug, body.shortcut ?? undefined);
637
+ if (result.conflict) {
638
+ json(409, { error: `快捷键已被「${result.conflict}」占用。` });
639
+ return;
640
+ }
641
+ broadcaster.broadcast({ type: "tools.updated", tools: await toolRegistry.list() });
642
+ json(200, { shortcut: result.tool?.shortcut ?? null });
643
+ return;
644
+ }
645
+ if (body.action === "remove") {
646
+ const tool = (await toolRegistry.list()).find(item => item.slug === body.slug);
647
+ if (!tool) {
648
+ json(404, { error: "找不到这个工具,可能已经下架。" });
649
+ return;
650
+ }
651
+ const removed = await toolRegistry.remove(tool.id);
652
+ if (removed)
653
+ await rm(toolRunner.envDir(tool.id), { recursive: true, force: true });
654
+ broadcaster.broadcast({ type: "tools.updated", tools: await toolRegistry.list() });
655
+ json(200, { removed });
656
+ return;
657
+ }
658
+ json(400, { error: "不支持的工具操作。" });
659
+ return;
660
+ }
661
+ catch (error) {
662
+ json(400, { error: describeThrown(error) || "工具操作失败。" });
663
+ return;
664
+ }
665
+ }
576
666
  if (url.pathname.startsWith("/tools/")) {
577
667
  let id;
578
668
  let resource;
@@ -23,6 +23,7 @@ import { PiSessionPool, repositoryRootFrom } from "./pi-session-pool.js";
23
23
  import { nativeToolArgs, nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, nativeToolExtensionPath, readNativeToolSettings } from "./native-tool-settings.js";
24
24
  import { describeDeliveredUserMessage, describePiQueue, handleSessionEvent, TurnQueue } from "./pi-session-events.js";
25
25
  import { LengthExceededError } from "./turn-failure.js";
26
+ import { CONVERSATION_TITLE_CONTEXT_MAX_CHARS, CONVERSATION_TITLE_TIMEOUT_MS } from "../shared/conversation-title.js";
26
27
  // The queue/steer recognisers live in pi-session-events.ts, where the SESSION path's bridge can use
27
28
  // them; the one-shot drain loop below reads the same records through the same two functions, so both
28
29
  // paths recognise a delivery identically. Re-exported because they were part of this module's surface.
@@ -1614,7 +1615,7 @@ export class PiRpcRuntime {
1614
1615
  // allowlist and naming a tool Pi has not registered would change the spawn line for every other
1615
1616
  // mode. The prompt asks for a bare JSON array and nothing else; if the model spends a turn on a
1616
1617
  // tool call anyway the reranker times out and falls back to the lexical order.
1617
- const agentArgs = memoryReview ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates", "--tools", "memory,skill_manage,session_search"] : knowledgeRerank ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates"] : await agentSpawnArgs(this.agents.promptDir, agent, { extraAllowedTools: [...(extensionArgs.length ? [TASK_TOOL_NAME, TODO_TOOL_NAME, PROJECT_TOOL_NAME, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, SCHEDULED_TASK_TOOL_NAME, "question", "tool_register", ...(this.options.orchestratorEndpoint ? [WORKTREE_TOOL_NAME, SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME, SESSION_REMINDER_TOOL_NAME] : [])] : []), ...(memoryEnabled ? ["memory", "skill_manage", "session_search"] : []), ...(knowledgeEnabled ? [KNOWLEDGE_TOOL_NAME, KNOWLEDGE_IMPORT_TOOL_NAME] : []), ...(documentsEnabled ? [DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME] : []), ...(webEnabled ? [WEB_SEARCH_TOOL_NAME, WEB_FETCH_TOOL_NAME] : []), ...(feishuEnabled ? [FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME] : [])] });
1618
+ const agentArgs = memoryReview ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates", "--tools", "memory,skill_manage,session_search"] : knowledgeRerank ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates"] : await agentSpawnArgs(this.agents.promptDir, agent, { extraAllowedTools: [...(extensionArgs.length ? [TASK_TOOL_NAME, TODO_TOOL_NAME, PROJECT_TOOL_NAME, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, SCHEDULED_TASK_TOOL_NAME, "question", "tool_register", "tool_shortcut", "tool_remove", ...(this.options.orchestratorEndpoint ? [WORKTREE_TOOL_NAME, SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME, SESSION_REMINDER_TOOL_NAME] : [])] : []), ...(memoryEnabled ? ["memory", "skill_manage", "session_search"] : []), ...(knowledgeEnabled ? [KNOWLEDGE_TOOL_NAME, KNOWLEDGE_IMPORT_TOOL_NAME] : []), ...(documentsEnabled ? [DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME] : []), ...(webEnabled ? [WEB_SEARCH_TOOL_NAME, WEB_FETCH_TOOL_NAME] : []), ...(feishuEnabled ? [FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME] : [])] });
1618
1619
  // Refused here, with the reason, rather than handed to the spawn: an ENOENT from `spawn` reads as
1619
1620
  // "the app is broken" and hides the one fact that matters, which is where it looked for Pi.
1620
1621
  if (!this.pi.found)
@@ -2540,33 +2541,62 @@ export class PiRpcRuntime {
2540
2541
  async summarizeConversation(conversation, cwd, signal) {
2541
2542
  if (!this.pi.found)
2542
2543
  throw new Error(this.pi.reason);
2543
- const TIMEOUT_MS = 30_000;
2544
+ const TIMEOUT_MS = CONVERSATION_TITLE_TIMEOUT_MS;
2544
2545
  // Session names live in a narrow sidebar row. Keep the model's budget well below the storage
2545
2546
  // limit so the result remains a concise label instead of becoming a sentence.
2546
2547
  const MAX_TITLE_CHARS = 18;
2547
2548
  // A throwaway session id, not the conversation's: this child reads nothing else and its history must
2548
2549
  // not be filed under the conversation whose title it is producing.
2549
- const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--session-dir", this.sessionDir, "--session-id", `autotitle-${randomUUID()}`], {
2550
+ // The selected model is carried over, but the current conversation transcript and its live cache are
2551
+ // deliberately not: title generation is an isolated, bounded one-shot request.
2552
+ const selectedModel = conversation.model;
2553
+ const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-session", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates"], {
2550
2554
  cwd: resolve(cwd),
2551
- env: { ...process.env, ...await readProviderProxyEnv(defaultAgentDir()) },
2555
+ env: { ...process.env, ...await readProviderProxyEnv(defaultAgentDir(), selectedModel?.provider) },
2552
2556
  stdio: ["pipe", "pipe", "pipe"],
2553
2557
  shell: process.platform === "win32",
2554
2558
  });
2555
2559
  const channel = new RpcChannel(child);
2556
2560
  const deadline = Date.now() + TIMEOUT_MS;
2557
2561
  try {
2558
- const transcript = conversation.messages
2562
+ const messages = conversation.messages
2559
2563
  .filter(message => (message.role === "user" || message.role === "assistant" || message.source === "session-reminder") && message.content.trim())
2560
- .map(message => `${message.source === "session-reminder" ? "定时提醒" : message.role === "user" ? "User" : "Assistant"}: ${message.content.trim()}`)
2561
- .join("\n");
2564
+ .map(message => ({
2565
+ label: message.source === "session-reminder" ? "定时提醒" : message.role === "user" ? "User" : "Assistant",
2566
+ content: message.content.trim(),
2567
+ }));
2568
+ const firstUser = messages.find(message => message.label === "User");
2569
+ const recent = messages.slice(-10);
2570
+ const selected = firstUser && !recent.includes(firstUser) ? [firstUser, ...recent] : recent;
2571
+ const excerpts = selected.map(message => {
2572
+ const content = message.content.length > 1_500
2573
+ ? `${message.content.slice(0, 1_100)}\n[…中间内容省略…]\n${message.content.slice(-300)}`
2574
+ : message.content;
2575
+ return `${message.label}: ${content}`;
2576
+ });
2577
+ let transcript = excerpts.join("\n\n");
2578
+ if (transcript.length > CONVERSATION_TITLE_CONTEXT_MAX_CHARS) {
2579
+ const headSize = 2_500;
2580
+ transcript = `${transcript.slice(0, headSize)}\n\n[…较早对话省略…]\n\n${transcript.slice(-(CONVERSATION_TITLE_CONTEXT_MAX_CHARS - headSize - 32))}`;
2581
+ }
2562
2582
  if (!transcript)
2563
2583
  throw new Error("这个会话还没有内容,无法据此生成标题");
2584
+ if (selectedModel?.provider && selectedModel.modelId) {
2585
+ const modelResponse = await channel.request({ id: "autotitle_model", type: "set_model", provider: selectedModel.provider, modelId: selectedModel.modelId }, Math.min(TIMEOUT_MS, 8_000));
2586
+ if (modelResponse.success !== true)
2587
+ throw new Error(modelResponse.error || `Pi 无法使用当前会话模型 ${selectedModel.provider}/${selectedModel.modelId}`);
2588
+ }
2589
+ // Reasoning adds latency without improving a short session label. Keep this one-shot call fast
2590
+ // even when the user's normal default thinking level is high.
2591
+ const thinkingResponse = await channel.request({ id: "autotitle_thinking", type: "set_thinking_level", level: "off" }, Math.min(TIMEOUT_MS, 8_000));
2592
+ if (thinkingResponse.success !== true)
2593
+ throw new Error(thinkingResponse.error || "Pi 未能关闭标题生成的思考等级");
2564
2594
  channel.write({
2565
2595
  id: "autotitle_prompt",
2566
2596
  type: "prompt",
2567
2597
  message: [
2568
- "为下面这段对话起一个简短的标题,用作会话列表里的一行字。",
2569
- "只输出标题本身:不要引号,不要句末标点,不要「标题:」之类的前缀,不要解释,不要换行。",
2598
+ "为下面这段对话起一个简短标题,用作会话列表里的一行字。直接命名,不需要展开分析或推理。",
2599
+ "只输出标题本身:不要引号、句末标点、「标题:」前缀、解释或换行。",
2570
2600
  `只生成一个简短的会话标签,长度严格不超过 ${MAX_TITLE_CHARS} 个字符(中文按一个字计数)。优先控制在 8-12 个字符;不要写成完整句子,不要使用副标题、解释、列表或多个候选标题。用与对话内容相同的语言。`,
2571
2601
  "",
2572
2602
  transcript,
@@ -33,6 +33,13 @@ export type ToolFingerprint = {
33
33
  export type ToolPermissions = {
34
34
  llm?: boolean;
35
35
  };
36
+ export type ToolShortcut = {
37
+ key: string;
38
+ ctrl?: boolean;
39
+ alt?: boolean;
40
+ shift?: boolean;
41
+ meta?: boolean;
42
+ };
36
43
  export type MountedTool = {
37
44
  id: string;
38
45
  slug: string;
@@ -43,6 +50,7 @@ export type MountedTool = {
43
50
  width: number;
44
51
  height: number;
45
52
  };
53
+ shortcut?: ToolShortcut;
46
54
  entrypoint: string;
47
55
  script?: ToolScript;
48
56
  environment?: ToolEnvironment;
@@ -76,6 +84,10 @@ export declare class ToolRegistry {
76
84
  private load;
77
85
  private save;
78
86
  list(): Promise<MountedTool[]>;
87
+ setShortcut(slug: string, shortcut?: ToolShortcut): Promise<{
88
+ tool?: MountedTool;
89
+ conflict?: string;
90
+ }>;
79
91
  register(input: {
80
92
  slug: string;
81
93
  name: string;
@@ -35,6 +35,28 @@ export class ToolRegistry {
35
35
  } }
36
36
  async save() { await mkdir(dirname(this.file), { recursive: true }); const tmp = `${this.file}.${process.pid}.tmp`; await writeFile(tmp, JSON.stringify(this.items, null, 2), "utf8"); await rename(tmp, this.file); }
37
37
  async list() { await this.load(); return this.items.map(copy); }
38
+ async setShortcut(slug, shortcut) {
39
+ await this.load();
40
+ const tool = this.items.find(item => item.slug === slug);
41
+ if (!tool)
42
+ throw new Error("找不到这个工具,可能已经下架。");
43
+ if (shortcut && (typeof shortcut.key !== "string" || !shortcut.key.trim() || shortcut.key.length > 32 || [shortcut.ctrl, shortcut.alt, shortcut.shift, shortcut.meta].some(value => value !== undefined && typeof value !== "boolean")))
44
+ throw new Error("快捷键格式无效。");
45
+ if (shortcut) {
46
+ const normalized = { ...shortcut, key: shortcut.key.toLowerCase() };
47
+ if (normalized.key === "escape" || (!normalized.ctrl && !normalized.alt && !normalized.shift && !normalized.meta && ["enter", "space", "tab"].includes(normalized.key)))
48
+ throw new Error("这个按键被弹窗或焦点控件保留,不能绑定为工具快捷键。");
49
+ const conflict = this.items.find(item => item.id !== tool.id && item.shortcut && item.shortcut.key.toLowerCase() === normalized.key && !!item.shortcut.ctrl === !!normalized.ctrl && !!item.shortcut.alt === !!normalized.alt && !!item.shortcut.shift === !!normalized.shift && !!item.shortcut.meta === !!normalized.meta);
50
+ if (conflict)
51
+ return { conflict: conflict.name };
52
+ tool.shortcut = normalized;
53
+ }
54
+ else
55
+ delete tool.shortcut;
56
+ tool.updatedAt = new Date().toISOString();
57
+ await this.save();
58
+ return { tool: copy(tool) };
59
+ }
38
60
  async register(input) {
39
61
  await this.load();
40
62
  const slug = input.slug.trim().toLowerCase();
@@ -222,5 +244,6 @@ function isParam(value) { const x = value; return !!x && typeof x === "object" &
222
244
  function isTool(value) { const x = value; if (!x || typeof x !== "object" || typeof x.id !== "string" || typeof x.slug !== "string" || typeof x.name !== "string" || typeof x.entrypoint !== "string" || (x.source !== "user" && x.source !== "builtin"))
223
245
  return false; if (x.dialogSize !== undefined && (!x.dialogSize || !Number.isFinite(x.dialogSize.width) || !Number.isFinite(x.dialogSize.height)))
224
246
  return false; if (x.environment !== undefined && (typeof x.environment !== "object" || x.environment === null))
247
+ return false; if (x.shortcut !== undefined && (!x.shortcut || typeof x.shortcut.key !== "string" || [x.shortcut.ctrl, x.shortcut.alt, x.shortcut.shift, x.shortcut.meta].some(item => item !== undefined && typeof item !== "boolean")))
225
248
  return false; return x.permissions === undefined || (typeof x.permissions === "object" && x.permissions !== null); }
226
- function copy(value) { return { ...value, script: value.script ? { ...value.script, parameters: value.script.parameters ? { ...value.script.parameters } : undefined } : undefined, environment: value.environment ? { ...value.environment, requires: value.environment.requires ? [...value.environment.requires] : undefined } : undefined, permissions: value.permissions ? { ...value.permissions } : undefined }; }
249
+ function copy(value) { return { ...value, shortcut: value.shortcut ? { ...value.shortcut } : undefined, script: value.script ? { ...value.script, parameters: value.script.parameters ? { ...value.script.parameters } : undefined } : undefined, environment: value.environment ? { ...value.environment, requires: value.environment.requires ? [...value.environment.requires] : undefined } : undefined, permissions: value.permissions ? { ...value.permissions } : undefined }; }
@@ -13,8 +13,8 @@ export type WebFetchResult = {
13
13
  truncated: boolean;
14
14
  contentType: string;
15
15
  };
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[];
16
+ /** Parse DuckDuckGo Lite result rows and unwrap their destination URLs. */
17
+ export declare function parseDuckDuckGoResults(html: string, limit?: number): WebSearchResult[];
18
18
  export declare class WebService {
19
19
  search(query: string, limit?: number, signal?: AbortSignal): Promise<{
20
20
  query: string;
@@ -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
  }
@@ -158,12 +168,11 @@ export class WebService {
158
168
  throw new Error("搜索词不能为空");
159
169
  if (clean.length > 500)
160
170
  throw new Error("搜索词不能超过 500 个字符");
161
- const url = new URL("https://www.bing.com/search");
171
+ const url = new URL("https://lite.duckduckgo.com/lite/");
162
172
  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");
173
+ url.searchParams.set("kl", "us-en");
165
174
  const response = await download(url.href, signal);
166
- const results = parseBingResults(response.body.toString("utf8"), limit);
175
+ const results = parseDuckDuckGoResults(response.body.toString("utf8"), limit);
167
176
  if (!results.length)
168
177
  throw new Error("搜索引擎没有返回可解析的结果,可能暂时限流或页面格式已变化");
169
178
  return { query: clean, results };
@@ -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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evandu/super-pi",
3
- "version": "0.1.254",
3
+ "version": "0.1.256",
4
4
  "description": "Web control plane and companion for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,6 +22,18 @@ If the tool needs more reading space, include `dialogSize: { width, height }` in
22
22
 
23
23
  Keep the iframe content usable when the popup is narrow: use flexible layouts, allow long tables or code to scroll inside the panel, and do not assume the requested size will fit every viewport.
24
24
 
25
+ ## Updating an existing tool
26
+
27
+ When replacing or rebuilding an existing tool, preserve its shortcut explicitly:
28
+
29
+ 1. Call `tool_shortcut` with `action: "get"` and the existing `slug` before removing the tool.
30
+ 2. Remove it with `tool_remove`. Removal clears its shortcut immediately, making the key available to other tools.
31
+ 3. Register the replacement with `tool_register`.
32
+ 4. If a shortcut was returned in step 1, call `tool_shortcut` with `action: "set"` and that shortcut.
33
+ 5. If setting it reports a conflict, keep the replacement registered and tell the user which tool owns the key. Do not silently change or clear the other tool's shortcut.
34
+
35
+ Never assume a shortcut survives removal or re-registration. New tools do not claim a shortcut unless the user asks for one.
36
+
25
37
  ## Finish
26
38
 
27
39
  Register only after the HTML and any script files are complete. Return the tool name, registration result, and the main interaction or calculation verified. If registration is unavailable in the current environment, report that constraint and provide the retained copy-prompt fallback only then.