Files
wang2 e0369f59ba search1api 0.1.3: Search1API as a web search API in Settings (#1219)
search1api 0.1.3 adds Search1API to magpie's Settings as a web search API. A search goes out as the Search1API account magpie picked (OAuth or API key, renewed before each search). The option key or SEARCH1API_API_KEY is used only when the host gives no account. A refusal (401, 402, 429) keeps its status and Retry-After, so magpie rests that account for search only. Results map title, url, snippet and date.

Thanks @fatwang2.

Run at the reviewed head d4bcb9da (mote, HOME=$(mktemp -d)):
- node --test tests/*.test.mjs: 27 pass.
- bun test: 27 pass.
- bun scripts/check.mjs search1api: ok.

Broken by hand: b54f3636c's src/index.ts with this head's tests fails the account-over-option-key test (3 pass, 1 fail). An earlier round with the main code made websearch.test fail 4 of 4.

Not run: tests/host.integration.mjs, or a real Search1API account.
2026-11-16 19:37:34 +08:00

214 lines
6.4 KiB
JavaScript

import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { stat, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { context, fixture } from "./helpers.mjs";
const root = fileURLToPath(new URL("../", import.meta.url));
const hostPath = process.env.MAGPIE_HOST_PATH;
const bun = process.env.MAGPIE_BUN_PATH ?? "bun";
async function host(t, f) {
const child = spawn(bun, [resolve(hostPath)], {
cwd: root,
stdio: ["pipe", "pipe", "pipe"],
env: { ...process.env, SEARCH1API_API_KEY: "" },
});
const pending = new Map();
let next = 0;
let errors = "";
child.stderr.on("data", (data) => {
errors += data;
});
createInterface({ input: child.stdout }).on("line", (line) => {
const msg = JSON.parse(line);
if (!("result" in msg) && !msg.error) return;
const waiter = pending.get(msg.id);
if (!waiter) return;
pending.delete(msg.id);
clearTimeout(waiter.timer);
if (msg.error) waiter.reject(new Error(msg.error.message));
else waiter.resolve(msg.result);
});
child.on("error", (error) => {
for (const p of pending.values()) {
clearTimeout(p.timer);
p.reject(error);
}
pending.clear();
});
child.on("exit", (code) => {
for (const p of pending.values()) {
clearTimeout(p.timer);
p.reject(new Error(`Host exited ${code}: ${errors}`));
}
pending.clear();
});
t.after(() => {
child.kill();
});
const rpc = (method, params = {}) =>
new Promise((resolve, reject) => {
const id = ++next;
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`${method} timed out: ${errors}`));
}, 15_000);
pending.set(id, { resolve, reject, timer });
child.stdin.write(JSON.stringify({ id, method, params }) + "\n");
});
const init = await rpc("init", {
authPath: f.authPath,
directory: f.directory,
plugins: [
{
spec: "@magpie-community/tools-search1api",
target: root,
options: { baseUrl: f.baseUrl },
},
],
});
assert.equal(init.plugins[0].error, undefined, JSON.stringify(init));
assert.equal(init.plugins[0].tools.length, 7);
assert.deepEqual(init.plugins[0].searches, [
{ id: "search1api", name: "Search1API", auth: "search1api" },
]);
return rpc;
}
test(
"actual Magpie Bun host: native OAuth → saved account → tools → refresh → logout",
{ timeout: 30_000 },
async (t) => {
assert.ok(
hostPath,
"Set MAGPIE_HOST_PATH to Magpie's internal/plugin/host.js (see README).",
);
const f = await fixture(t);
const rpc = await host(t, f);
const providers = await rpc("providers");
assert.equal(providers[0].id, "search1api");
assert.equal(providers[0].single, true);
assert.deepEqual(providers[0].models, []);
assert.deepEqual(
providers[0].methods.map((m) => m.type),
["oauth", "api"],
);
const signIn = await rpc("authorize", {
provider: "search1api",
method: 0,
});
assert.equal((await fetch(signIn.url)).status, 200);
const saved = await rpc("callback", { session: signIn.session });
assert.equal(saved.ok, true);
assert.equal(saved.account, "search1api");
assert.equal((await stat(f.authPath)).mode & 0o777, 0o600);
const call = () =>
rpc("tool", {
spec: "@magpie-community/tools-search1api",
name: "search",
args: { query: "Bun", searchService: "github", timeRange: "week" },
ms: 5000,
agent: "test",
});
const result = await call();
assert.equal(JSON.parse(result.text).results[0].metadata.stars, 0);
await assert.rejects(
rpc("tool", {
spec: "@magpie-community/tools-search1api",
name: "search",
args: { query: " " },
ms: 5000,
}),
/query|arguments are wrong/,
);
const all = await f.readAuth();
all.search1api.expires = Date.now() - 1;
await writeFile(f.authPath, JSON.stringify(all), { mode: 0o600 });
const second = await host(t, f);
await Promise.all([
call(),
second("tool", {
spec: "@magpie-community/tools-search1api",
name: "ask",
args: { query: "Bun" },
ms: 5000,
}),
]);
assert.equal(
f.state.refreshes,
1,
"rotating refresh tokens are shared safely across real Bun processes",
);
assert.equal((await f.readAuth()).search1api.access, "test-access-1");
await rpc("signOut", { provider: "search1api" });
await assert.rejects(call(), /Sign in/);
},
);
test(
"actual Magpie Bun host saves API keys using its native login path",
{ timeout: 20_000 },
async (t) => {
assert.ok(hostPath, "Set MAGPIE_HOST_PATH.");
const f = await fixture(t);
const rpc = await host(t, f);
const saved = await rpc("apiKey", {
provider: "search1api",
method: 1,
key: "test-native-api-key",
});
assert.equal(saved.ok, true);
const result = await rpc("tool", {
spec: "@magpie-community/tools-search1api",
name: "news",
args: { query: "test" },
ms: 5000,
});
assert.ok(JSON.parse(result.text).results.length);
assert.equal(
f.calls.at(-1).headers.authorization,
"Bearer test-native-api-key",
);
},
);
test(
"actual Magpie Bun host: web search signs in as the saved Search1API account",
{ timeout: 20_000 },
async (t) => {
assert.ok(hostPath, "Set MAGPIE_HOST_PATH.");
const f = await fixture(t);
const rpc = await host(t, f);
const saved = await rpc("apiKey", {
provider: "search1api",
method: 1,
key: "test-search-api-key",
});
assert.equal(saved.ok, true);
const result = await rpc("search", {
spec: "@magpie-community/tools-search1api",
id: "search1api",
query: "Bun",
count: 6,
account: "search1api",
ms: 5000,
});
assert.deepEqual(result.pages, [
{ title: "Example", url: "https://example.com", text: "Result", age: "2026-10-23" },
]);
const call = f.calls.at(-1);
assert.equal(call.path, "/search");
assert.equal(call.headers.authorization, "Bearer test-search-api-key");
assert.deepEqual(JSON.parse(call.raw), {
query: "Bun",
search_service: "google",
max_results: 6,
crawl_results: 0,
});
},
);