Files
plugins/packages/search1api/src/index.ts
T
wang2 6a2ade35ef search1api 0.1.1: Magpie attribution, reused OAuth client, send_feedback through Search1API (#424)
search1api 0.1.1 (fatwang2):
- Sign-ins carry utm_source=magpie and API requests send User-Agent search1api-magpie/0.1.1.
- The registered public OAuth client and its loopback port are saved in search1api-oauth-client.json (mode 600) and reused. A busy port, another issuer, or a sign-in that doesn't finish leads to a new registration.
- A send_feedback tool posts to Search1API's own POST /feedback with the caller's credential, on the same request path as the other tools, including the OAuth refresh on 401. Its description lists what is sent (message, intent, category, request_id, model) and says Search1API stores it on agentback.app, linked to the signed-in account. The plugin contacts no other host. A report that can't be sent returns a note and doesn't fail the task.

Run at the reviewed head d48c8c8 (sandbox HOME/TMPDIR, Bun 1.4.2):
- bun test packages/search1api/tests: 23 pass, 0 fail
- bun scripts/check.mjs search1api: ok
- PR CI (test, on-npm): pass
- grep of the package: the only host is api.search1api.com (plus 127.0.0.1 for the callback). No hard-coded keys. agentback.app appears only in the description, the README and a test.
- Drove the built plugin against my own loopback fake API:
  - OAuth access revoked (401): POST /feedback with the old bearer, then /token refresh_token, then POST /feedback with the new bearer. Got "Feedback recorded (fb_1)" and auth.set with the new token.
  - Bad API key: a 401 gives "not recorded ... (401)" with no refresh, and the error body is not echoed.
  - Body is exactly {message, intent, category, request_id, agent:{name:"Magpie", model}}, with UA search1api-magpie/0.1.1.
  - Unknown args and a non-string model are refused before any request.
- An unauthenticated probe of the real api.search1api.com: POST /feedback gives 401, and an unknown path gives 404. So the endpoint exists.
- The OAuth client reuse (unchanged since 95f236f) was run by hand in the previous review.

Not tried: a real Search1API account (none available).
2026-10-27 15:44:05 +08:00

115 lines
5.9 KiB
TypeScript

import { join } from "node:path";
import { Credentials } from "./auth.ts";
import { CATEGORIES, DESCRIPTION, feedbackBody } from "./feedback.ts";
import { startOAuth } from "./oauth.ts";
import { AuthenticationError, request } from "./request.ts";
import { filters, maxResults, query, searchBody, validate, type ArgumentsSchema, type Schema } from "./tools.ts";
import { API_BASE, PROVIDER, serviceURL, type Options, type PluginInput, type StoredOAuth } from "./types.ts";
export const Search1APIPlugin = async (input: PluginInput, options: Options = {}) => {
if (options.apiKey !== undefined && typeof options.apiKey !== "string")
throw new Error("apiKey must be a string.");
const baseUrl = serviceURL(options.baseUrl ?? API_BASE).href.replace(/\/$/, "");
const credentials = new Credentials(input, options);
async function send(name: string, payload: Record<string, unknown>, signal: AbortSignal) {
let auth = await credentials.token(signal);
signal.throwIfAborted();
try {
return await request(baseUrl, name, auth.token, payload, signal);
} catch (error) {
if (!(error instanceof AuthenticationError) || !auth.oauth) throw error;
const renewed = await credentials.renew(auth.oauth, signal);
auth = { token: renewed.access, oauth: renewed };
return await request(baseUrl, name, auth.token, payload, signal);
}
}
function tool(
name: string,
description: string,
properties: Record<string, Schema>,
required: string[],
body: (args: Record<string, unknown>) => Record<string, unknown>,
) {
const args: ArgumentsSchema = { type: "object", properties, required, additionalProperties: false };
return {
description,
args,
async execute(value: unknown, ctx: { abort: AbortSignal }) {
const result = await send(name, body(validate(args, value)), ctx.abort);
return JSON.stringify(result, null, 2);
},
};
}
const feedbackArgs: ArgumentsSchema = {
type: "object",
properties: {
message: { type: "string", minLength: 1, maxLength: 4000, description: "What went wrong or what was missing, in plain language." },
intent: { type: "string", maxLength: 2000, description: "The Search1API call you were making and what you expected from it. Not the user's request or conversation." },
category: { type: "string", enum: CATEGORIES },
request_id: { type: "string", maxLength: 256, description: "Request id of the call that had the problem, if known." },
model: { type: "string", maxLength: 128, description: "Your model name, if you know it." },
},
required: ["message"],
additionalProperties: false,
};
return {
config: async (config: { provider?: Record<string, unknown> }) => {
config.provider ??= {};
// This entry supplies sign-in, not chat models.
config.provider[PROVIDER] ??= { name: "Search1API", models: {} };
},
auth: {
provider: PROVIDER,
single: true,
methods: [
{ type: "oauth" as const, label: "Sign in to Search1API", authorize: () => startOAuth(baseUrl, undefined, join(input.directory, "search1api-oauth-client.json")) },
{ type: "api" as const, label: "Search1API API key" },
],
refreshLead: 60_000,
refresh: (auth: StoredOAuth) => credentials.renew(auth),
},
tool: {
search: tool("search",
"Search the live web for current facts, research, documentation, people, companies and sources. Credit Grokipedia results as Powered by xAI.",
{ query, ...filters,
searchService: { type: "string", enum: ["google", "bing", "bingcn", "duckduckgo", "yahoo", "yandex", "x", "reddit", "github", "youtube", "arxiv", "wechat", "bilibili", "imdb", "wikipedia", "grokipedia", "baidu", "360", "quark"] },
page: { type: "integer", minimum: 1, maximum: 100 },
}, ["query"], (args) => searchBody(args, "google")),
news: tool("news",
"Search current news and optionally retrieve full article content.",
{ query, ...filters, searchService: { type: "string", enum: ["google", "bing", "duckduckgo", "yahoo", "hackernews", "reuters"] } },
["query"], (args) => searchBody(args, "bing")),
ask: tool("ask",
"Describe what to find in natural language. Search1API chooses engines and a time window and returns results ranked by relevance. Costs 5 credits; returns search results rather than a generated answer.",
{ query: { ...query, maxLength: 500 } }, ["query"], ({ query }) => ({ query })),
crawl: tool("crawl", "Retrieve clean readable content from a public URL.",
{ url: { type: "string", format: "uri" } }, ["url"], ({ url }) => ({ url })),
sitemap: tool("sitemap", "Discover links related to a public URL or domain.",
{ url: { type: "string", format: "uri" } }, ["url"], ({ url }) => ({ url })),
trending: tool("trending", "Find trending repositories on GitHub or stories on Hacker News.",
{ service: { type: "string", enum: ["github", "hackernews"] }, maxResults },
["service"], ({ service, maxResults }) => ({ search_service: service, max_results: maxResults ?? 10 })),
send_feedback: {
description: DESCRIPTION,
args: feedbackArgs,
async execute(value: unknown, ctx: { abort: AbortSignal }) {
const payload = feedbackBody(validate(feedbackArgs, value));
// A report that cannot be sent must not fail the agent's task.
try {
const receipt = await send("feedback", payload, ctx.abort) as { id?: unknown };
return `Feedback recorded (${typeof receipt?.id === "string" ? receipt.id : "ok"}). Thank you.`;
} catch (error) {
ctx.abort.throwIfAborted();
const reason = error instanceof Error ? error.message : "Search1API feedback failed.";
return `Feedback was not recorded: ${reason} Continue the task.`;
}
},
},
},
};
};