Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions apps/desktop/src/renderer/features/settings/search-settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,15 @@ import { requirePeer, writeCredential } from "./operations.ts";
import css from "./search-settings.module.css";

type SearchProvider = SearchConfig["provider"];
const PROVIDERS = ["keyless", "duckduckgo", "bing", "brave", "tavily", "searxng"] as const;
const PROVIDERS = [
"keyless",
"duckduckgo",
"bing",
"brave",
"tavily",
"keenable",
"searxng",
] as const;
const keyFree = (provider: SearchProvider): provider is "keyless" | "duckduckgo" | "bing" =>
provider === "keyless" || provider === "duckduckgo" || provider === "bing";

Expand Down Expand Up @@ -152,7 +160,7 @@ export function SearchSettings() {
))}
</fieldset>
</SettingsRow>
{(provider === "brave" || provider === "tavily") && (
{(provider === "brave" || provider === "tavily" || provider === "keenable") && (
<form
className={layoutStyles.row}
onSubmit={(event) => {
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/en/09-models-and-keys.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ If your network needs a proxy, set it in Settings › General › Network proxy

- **No API key (automatic)**: tries DuckDuckGo first, then Bing if it can't connect. Keyless services also ask in chat on the first search.
- **DuckDuckGo**, **Bing**: no account needed; may be rate-limited.
- **Brave Search API**, **Tavily**: enter an API key.
- **Brave Search API**, **Tavily**, **Keenable**: enter an API key. These are optional; nothing changes unless you pick one.
- **Self-hosted SearXNG**: enter your service address; only that address is allowed.

## A different model per Bot
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/zh/09-models-and-keys.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ Anthropic 不允许 Claude 订阅登录第三方应用,所以 Claude 在这里

- **免 Key(自动)**:先试 DuckDuckGo,不通时换 Bing。第一次搜索时还会在聊天里请你确认。
- **DuckDuckGo**、**Bing**:不用注册,可能被限流。
- **Brave Search API**、**Tavily**:填 API Key。
- **Brave Search API**、**Tavily**、**Keenable**:填 API Key。都是可选项,不选就不会有任何变化。
- **自建 SearXNG**:填你的服务地址,只放行这一个地址。

## 每个 Bot 用不同的模型
Expand Down
6 changes: 3 additions & 3 deletions docs/privacy/en/outbound-connections.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ This page lists every network connection Pi Bot can make: the desktop app, the A
| [Role library](#role-library) | `roles.pibot.space` | Only when you use it |
| [Model providers](#model-providers) | The provider you configure | Only after you set up a model |
| [ChatGPT plan](#chatgpt-plan) | `auth.openai.com`, `api.openai.com` or `chatgpt.com` | When signing in, refreshing sign-in or using a signed-in model |
| [Web search](#web-search) | DuckDuckGo, Bing, Brave, Tavily or your SearXNG | Yes, asks on first use |
| [Web search](#web-search) | DuckDuckGo, Bing, Brave, Tavily, Keenable or your SearXNG | Yes, asks on first use |
| [Websites Bots visit](#websites-bots-visit) | The sites themselves | Yes |
| [Commands Bots run](#commands-bots-run) | Package registries, your allowed sites, your SSH hosts | Yes, limited |
| [MCP servers and connected apps](#mcp-servers-and-connected-apps) | The services you connect | No |
Expand Down Expand Up @@ -84,9 +84,9 @@ The relay (`relay.pibot.space`) and `auth.pibot.space` are described under [Phon
- **Receiver:** the search service chosen in Settings › Models & API keys › Web search:
- **No API key (automatic)**, the default: DuckDuckGo (`html.duckduckgo.com`), falling back to Bing (`cn.bing.com` or `www.bing.com`) when DuckDuckGo can't be reached.
- **DuckDuckGo** or **Bing** on their own.
- **Brave Search API** (`api.search.brave.com`) or **Tavily** (`api.tavily.com`), with your API key.
- **Brave Search API** (`api.search.brave.com`), **Tavily** (`api.tavily.com`) or **Keenable** (`api.keenable.ai`), with your API key.
- **Self-hosted SearXNG**: only the address you enter.
- **What is sent:** the search terms the Bot writes, plus your key for Brave or Tavily.
- **What is sent:** the search terms the Bot writes, plus your key for Brave, Tavily or Keenable. Pi Bot also sends the app name `Pi Bot` in the `X-Keenable-Title` header on Keenable requests, and nothing about you or your device. Keenable logs search requests (the query and the results, with the request's IP address and user agent) under its default data policy; adding a key does not turn that off. Only an Enterprise zero-data-retention agreement with Keenable changes it. See [Keenable's data and privacy page](https://docs.keenable.ai/data-privacy).
- **When:** when a Bot searches the web. The keyless services ask in the chat the first time.
- **To stop it:** set **Visit websites** to **Never** in Settings › Permissions (for all Bots or for one Bot). This also blocks web search.

Expand Down
6 changes: 3 additions & 3 deletions docs/privacy/zh/outbound-connections.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
| [角色库](#角色库) | `roles.pibot.space` | 你用到时才连 |
| [模型厂商](#模型厂商) | 你配置的厂商 | 配好模型后才连 |
| [ChatGPT 计划](#chatgpt-计划) | `auth.openai.com`、`api.openai.com` 或 `chatgpt.com` | 登录、刷新登录或使用已登录的模型时 |
| [联网搜索](#联网搜索) | DuckDuckGo、Bing、Brave、Tavily 或你的 SearXNG | 是,第一次使用时会问你 |
| [联网搜索](#联网搜索) | DuckDuckGo、Bing、Brave、Tavily、Keenable 或你的 SearXNG | 是,第一次使用时会问你 |
| [Bot 访问的网站](#bot-访问的网站) | 网站本身 | 是 |
| [Bot 跑的命令](#bot-跑的命令) | 软件包仓库、你允许的网站、你的 SSH 主机 | 是,有限制 |
| [MCP 服务器和连接的应用](#mcp-服务器和连接的应用) | 你连接的服务 | 否 |
Expand Down Expand Up @@ -84,9 +84,9 @@ Pi Bot 自己的服务器只走 HTTPS 或 WSS。STUN 是一次很小的 UDP 查
- **接收方:** 设置 › 模型与密钥 ›「联网搜索」里选的服务:
- **免 Key(自动)**(默认):先用 DuckDuckGo(`html.duckduckgo.com`),连不上时换 Bing(`cn.bing.com` 或 `www.bing.com`)。
- 单独选 **DuckDuckGo** 或 **Bing**。
- **Brave Search API**(`api.search.brave.com`)或 **Tavily**(`api.tavily.com`),需要填你的 API Key。
- **Brave Search API**(`api.search.brave.com`)、**Tavily**(`api.tavily.com`)或 **Keenable**(`api.keenable.ai`),需要填你的 API Key。
- **自建 SearXNG**:只连你填的地址。
- **发什么:** Bot 写的查询词;用 Brave 或 Tavily 时还有你的 Key。
- **发什么:** Bot 写的查询词;用 Brave、Tavily 或 Keenable 时还有你的 Key。用 Keenable 时,请求头 `X-Keenable-Title` 里只带应用名 `Pi Bot`,不带任何关于你或你设备的信息。Keenable 在默认数据政策下会记录搜索请求(查询词、结果,以及请求的 IP 地址和 user agent),填 Key 不会关闭记录;只有与 Keenable 签订企业版零数据留存协议才会不同。详见 [Keenable 的数据与隐私说明](https://docs.keenable.ai/data-privacy)。
- **什么时候:** Bot 联网搜索时。免 Key 服务第一次使用会在聊天里问你。
- **怎么关:** 在 设置 › 权限 里把「访问网站」设为「不允许」(可以对全部 Bot,也可以只对某个 Bot),搜索也会一起被拦下。

Expand Down
1 change: 1 addition & 0 deletions packages/brain/src/core/audit-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export function auditProviderName(id: string): string | undefined {
"github-copilot": "GitHub Copilot",
brave: "Brave",
tavily: "Tavily",
keenable: "Keenable",
searxng: "SearXNG",
duckduckgo: "DuckDuckGo",
bing: "Microsoft Bing",
Expand Down
1 change: 1 addition & 0 deletions packages/brain/src/core/personas/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export function capabilityPrompt(language: "zh" | "en", facts: CapabilityFacts):
bing: "Bing",
brave: "Brave Search",
tavily: "Tavily",
keenable: "Keenable",
searxng: "SearXNG",
};
const search = facts.search
Expand Down
27 changes: 26 additions & 1 deletion packages/brain/src/integrations/search/search-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
type BlockedPageReason,
DuckDuckGoError,
isProxyFailure,
SearchStatusError,
} from "@pibot/execution";
import { auditProviderName } from "../../core/audit-fields.ts";
import type { PreparedTool } from "../../core/local-types.ts";
Expand All @@ -27,7 +28,31 @@ export class SearchRunError extends Error {
return language === "zh" ? this.zh : this.en;
}
}
function failure(error: unknown, provider: string, receipt?: PreparedTool) {
/** Keenable's HTTP errors, each with something the user can do; never a silent empty result. */
function keenableStatus(status: number) {
if (status === 429)
return new SearchRunError(
"Keenable 搜索请求太频繁(429),请稍后再试,或在设置里换一个搜索服务",
"Keenable is rate limiting searches (429). Try again shortly, or switch the search service in settings",
);
if (status === 401 || status === 403)
return new SearchRunError(
`Keenable 拒绝了这个 API Key(${status}),请在设置里检查或更换 Key`,
`Keenable rejected the API key (${status}). Check or replace the key in settings`,
);
if (status === 402)
return new SearchRunError(
"Keenable 账户额度不足(402),请充值,或在设置里换一个搜索服务",
"The Keenable account is out of credits (402). Add credits, or switch the search service in settings",
);
return new SearchRunError(
`Keenable 搜索失败(HTTP ${status}),请稍后再试,或在设置里换一个搜索服务`,
`Keenable search failed (HTTP ${status}). Try again, or switch the search service in settings`,
);
}
export function failure(error: unknown, provider: string, receipt?: PreparedTool) {
if (provider === "Keenable" && error instanceof SearchStatusError)
return keenableStatus(error.status);
const reason =
error instanceof DuckDuckGoError || error instanceof BingError ? error.reason : "other";
return reason === "unavailable"
Expand Down
134 changes: 134 additions & 0 deletions packages/brain/src/integrations/search/search-service.keenable.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Offline: the HTTP layer is replaced, so no real network, key or user directory is touched.
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { DatabaseSync } from "node:sqlite";
import { SearchStatusError, type searchJson } from "@pibot/execution";
import { createRedactor, type SecretCipher } from "@pibot/secrets";
import { openDatabase, runMigrations } from "@pibot/storage";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { failure } from "./search-run.ts";
import { SearchService } from "./search-service.ts";

// A reversible test cipher, deliberately not suitable for production encryption.
const cipher: SecretCipher = {
isAvailable: async () => true,
encrypt: async (plain) => Uint8Array.from(Buffer.from(plain), (byte) => byte ^ 0xa5),
decrypt: async (encrypted) => Buffer.from(encrypted.map((byte) => byte ^ 0xa5)).toString(),
};
const KEY = "opaque-test-credential-1234";

let dir: string;
let db: DatabaseSync;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "pibot-keenable-"));
db = openDatabase(join(dir, "pibot.db"));
runMigrations(db);
}, 30_000);
afterEach(() => {
db.close();
rmSync(dir, { recursive: true, force: true });
});

const service = (http: typeof searchJson) =>
new SearchService(db, cipher, createRedactor(), () => {}, http);
const never = vi.fn(async () => {
throw new Error("network must not be used");
}) as unknown as typeof searchJson;

describe("Keenable search provider", () => {
it("is never the default: nothing changes until a key is saved", async () => {
const search = service(never);
expect(search.get()?.provider).toBe("keyless");
// Picking Keenable without a key is not configured, so the keyless default stays in effect.
await search.set({ provider: "keenable" });
expect(search.get()?.provider).toBe("keyless");
expect(never).not.toHaveBeenCalled();
});

it("sends a keyed POST with only the app name as identification", async () => {
const http = vi.fn(async (_input: Parameters<typeof searchJson>[0]) => ({
query: "q",
mode: "pro",
results: [
{
title: "A page",
url: "https://example.com/a",
description: "",
snippet: "Text from the page",
},
{ title: "Not http", url: "file:///etc/passwd", snippet: "x" },
],
}));
const search = service(http as unknown as typeof searchJson);
await search.set({ provider: "keenable", apiKey: KEY });
search.disclose("keenable");
const results = await search.query("pi bot", 5, new AbortController().signal);
expect(results).toEqual([
expect.objectContaining({
title: "A page",
url: "https://example.com/a",
snippet: "Text from the page",
}),
]);
const call = http.mock.calls[0]?.[0];
expect(call?.url).toBe("https://api.keenable.ai/v1/search");
expect(call?.method).toBe("POST");
expect(call?.headers).toEqual({
accept: "application/json",
"Content-Type": "application/json",
"X-API-Key": KEY,
"X-Keenable-Title": "Pi Bot",
});
expect(JSON.parse(call?.body ?? "{}")).toEqual({
query: "pi bot",
max_results: 5,
snippet_max_length: 1000,
});
});

it("does not send the Keenable header to other providers", async () => {
const http = vi.fn(async () => ({ results: [] }));
const search = service(http as unknown as typeof searchJson);
await search.set({ provider: "tavily", apiKey: KEY });
search.disclose("tavily");
await search.query("q", 3, new AbortController().signal);
const headers = (http.mock.calls[0] as unknown as [{ headers: Record<string, string> }])[0]
.headers;
expect(headers).not.toHaveProperty("X-Keenable-Title");
expect(headers).not.toHaveProperty("X-API-Key");
});

it("removes the stored key with the rest of the search configuration", async () => {
const search = service(never);
await search.set({ provider: "keenable", apiKey: KEY });
expect(search.secrets.has("search:keenable", "apiKey")).toBe(true);
search.remove();
expect(search.secrets.has("search:keenable", "apiKey")).toBe(false);
expect(search.get()?.provider).toBe("keyless");
});
});

describe("Keenable search errors", () => {
const text = (status: number) => failure(new SearchStatusError(status), "Keenable").en;

it("tells the user what to do on a 429", () => {
expect(text(429)).toMatch(/rate limiting.*switch the search service/);
});
it("asks for a different key on 401 and 403", () => {
expect(text(401)).toMatch(/rejected the API key.*key in settings/);
expect(text(403)).toMatch(/rejected the API key/);
});
it("reports missing credits on 402", () => {
expect(text(402)).toMatch(/out of credits/);
});
it("names the status for any other failure instead of returning an empty result", () => {
expect(text(500)).toMatch(/HTTP 500/);
expect(failure(new SearchStatusError(429), "Keenable").zh).toContain("429");
});
it("leaves other providers' error text alone", () => {
expect(failure(new SearchStatusError(429), "Tavily").en).toBe(
"Search could not complete; check the service configuration",
);
});
});
25 changes: 21 additions & 4 deletions packages/brain/src/integrations/search/search-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,16 @@ import { abortable } from "../../core/abort.ts";
import { endpoint } from "../../core/endpoint.ts";
import { SearchCircuit } from "./search-circuit.ts";

const KEENABLE_SEARCH_URL = "https://api.keenable.ai/v1/search";
// Providers that take an API key (stored like the Brave and Tavily keys).
const keyedProviders = ["brave", "tavily", "keenable"] as const;
const row = z.object({
title: z.string().max(8192),
url: z.string().max(32768),
description: z.string().max(65536).optional(),
content: z.string().max(65536).optional(),
// Keenable returns the page text in `snippet`; its `description` is always empty.
snippet: z.string().max(65536).optional(),
});
export type SearchRecipient = Exclude<SearchConfig["provider"], "keyless">;
export interface SearchResult {
Expand Down Expand Up @@ -119,7 +124,11 @@ export class SearchService {
this.secrets.has(`search:${input.provider}`, "apiKey"),
disclosed: false,
};
if ((input.provider === "brave" || input.provider === "tavily") && input.apiKey)
if (
(keyedProviders as readonly string[]).includes(input.provider) &&
"apiKey" in input &&
input.apiKey
)
await this.secrets.set(`search:${input.provider}`, "apiKey", input.apiKey);
const result = this.repo.set(config);
this.generation++;
Expand Down Expand Up @@ -155,7 +164,7 @@ export class SearchService {
}
remove() {
transaction(this.db, () => {
for (const p of ["brave", "tavily"]) this.secrets.remove(`search:${p}`, "apiKey");
for (const p of keyedProviders) this.secrets.remove(`search:${p}`, "apiKey");
this.repo.remove();
});
this.generation++;
Expand Down Expand Up @@ -210,7 +219,9 @@ export class SearchService {
? "https://html.duckduckgo.com/html/"
: config.provider === "brave"
? "https://api.search.brave.com/res/v1/web/search"
: "https://api.tavily.com/search";
: config.provider === "keenable"
? KEENABLE_SEARCH_URL
: "https://api.tavily.com/search";
}
policyRequest(recipient = this.recipient()): PolicyRequest {
const config = this.get();
Expand Down Expand Up @@ -298,6 +309,12 @@ export class SearchService {
headers["X-Subscription-Token"] = key ?? "";
url.searchParams.set("q", query);
url.searchParams.set("count", String(count));
} else if (config.provider === "keenable") {
headers["X-API-Key"] = key ?? "";
headers["Content-Type"] = "application/json";
// Only this app name goes out; no user or device information.
headers["X-Keenable-Title"] = "Pi Bot";
body = JSON.stringify({ query, max_results: Math.min(count, 50), snippet_max_length: 1000 });
} else if (config.provider === "tavily") {
headers.authorization = `Bearer ${key}`;
headers["Content-Type"] = "application/json";
Expand Down Expand Up @@ -334,7 +351,7 @@ export class SearchService {
title: r.title.slice(0, 500),
url: url.href,
proxy: this.proxy(),
snippet: (r.description ?? r.content ?? "").slice(0, 2000),
snippet: (r.snippet || r.description || r.content || "").slice(0, 2000),
},
];
} catch {
Expand Down
1 change: 1 addition & 0 deletions packages/client-core/src/audit/facts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ export function auditProvider(detail: AuditDetail, t: AuditT) {
"github-copilot": "GitHub Copilot",
brave: "Brave",
tavily: "Tavily",
keenable: "Keenable",
searxng: "SearXNG",
};
return (
Expand Down
2 changes: 1 addition & 1 deletion packages/execution/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ export { DuckDuckGoError, duckduckgoSearch } from "./web/duckduckgo.ts";
export { createNetworkFetch } from "./web/network-fetch.ts";
export * from "./web/network-proxy.ts";
export { PublicDownloadError, withPublicDownload } from "./web/public-download.ts";
export { searchJson } from "./web/search-http.ts";
export { SearchStatusError, searchJson } from "./web/search-http.ts";
export type { BlockedPageReason } from "./web/web.ts";
export { blockedPage, fetchPage } from "./web/web.ts";
export { assertPublicWebTarget } from "./web/web-address.ts";
Expand Down
8 changes: 7 additions & 1 deletion packages/execution/src/web/search-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ export class SearchHttpError extends Error {
super(`search_${reason}_failed`);
}
}
/** A non-2xx answer from a search API; carries the status so callers can say what to do next. */
export class SearchStatusError extends Error {
constructor(readonly status: number) {
super("Search request failed");
}
}
/** Only the user-selected search endpoint may opt into private addresses. No redirects. */
export async function searchResponse(input: {
url: string;
Expand Down Expand Up @@ -133,6 +139,6 @@ export async function searchResponse(input: {

export async function searchJson(input: Parameters<typeof searchResponse>[0]): Promise<unknown> {
const response = await searchResponse(input);
if (response.status < 200 || response.status >= 300) throw new Error("Search request failed");
if (response.status < 200 || response.status >= 300) throw new SearchStatusError(response.status);
return JSON.parse(response.text);
}
Loading
Loading