Files
plugins/packages/search1api/src/index.ts
T
wang2 6188ab5be7 search1api 0.1.0: Search1API's six tools with API key or OAuth sign-in (#384)
Adds packages/search1api as @magpie-community/tools-search1api 0.1.0
(fatwang2, replacing #340). It has six tools: search, news, ask, crawl,
sitemap and trending. Sign-in is one account by API key or OAuth: PKCE
S256, dynamic client registration and a loopback callback. Tokens refresh
through auth.refresh and on a 401. scripts/check.mjs now accepts a tools
plugin with auth and no loader, as long as its config gives the provider
no npm and no models.

Run at 7cf6a5c merged onto main, in a sandbox HOME, with HTTPS_PROXY
pointed at a dead port:
- bun test packages/search1api scripts/check.test.mjs: 19 pass.
- node --test on the package's own tests: 16 pass.
- tests/host.integration.mjs against main magpie's host.js: 2 pass.
- bun test across the whole repo: 2647 pass, 0 fail. This needs 017f05c.
  Before it, gcp-ai's fetch guard refused this package's loopback
  fixtures in the shared bun process.
- bun scripts/check.mjs: all ok.

Broken by hand, each one red:
- Dropping the SAME_SESSION check before a refresh: 1 test.
- Never refreshing an expired token: 3 tests.
- Ignoring the apiKey option: 4 tests.
- Not red: dropping the second check, which catches a logout during an
  in-flight refresh. The first check covers it in the logout test.

Real use:
- A sandbox magpie took the package with `plugin add`. `plugin list`
  shows its 6 tools. `plugin login search1api 2` with a key showed
  Providers as "Search1API · signed in as API key …-384 · no models
  exposed".
- The search tool ran against the real api.search1api.com with a fake
  key and got 401.
- OAuth discovery is live: oauth-protected-resource points to
  clerk.s1.dev, which has a registration endpoint and S256.

Not tried:
- A real OAuth consent, or a search with a real key. There is no
  Search1API account here.

Notes:
- The plugin reads the signed-in record from
  `<directory>/plugin-auth.json` itself, since tools get no getAuth.
  magpie writes that file by temp-and-rename, so a read never sees half a
  write.
- magpie's login line says "its models are search1api/<model>" for a
  provider with no models. That is magpie's wording, not this PR's.
2026-10-25 17:53:00 +08:00

83 lines
4.2 KiB
TypeScript

import { Credentials } from "./auth.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);
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 payload = body(validate(args, value));
const signal = ctx.abort;
let auth = await credentials.token(signal);
signal.throwIfAborted();
let result: unknown;
try {
result = 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 };
result = await request(baseUrl, name, auth.token, payload, signal);
}
return JSON.stringify(result, null, 2);
},
};
}
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) },
{ 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 })),
},
};
};