@juicesharp/rpiv-web-tools 1.20.0 → 2.0.0
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.
- package/README.md +15 -3
- package/package.json +6 -5
- package/providers/config.ts +7 -2
- package/providers/exa.ts +7 -1
- package/web-tools.ts +78 -9
- package/providers/config.test.ts +0 -129
- package/providers/interceptors/chain.test.ts +0 -209
- package/providers/interceptors/github.test.ts +0 -933
package/README.md
CHANGED
|
@@ -47,8 +47,7 @@ Then restart your Pi session.
|
|
|
47
47
|
|
|
48
48
|
## Tools
|
|
49
49
|
|
|
50
|
-
- **`web_search`** - query
|
|
51
|
-
1–10 results per call.
|
|
50
|
+
- **`web_search`** - query a search provider's API and return titled snippets. Defaults to the active provider set via `/web-tools`; pass `provider` to target a different backend on a single call without switching the persisted default. 1–10 results per call.
|
|
52
51
|
- **`web_fetch`** - read an http/https URL. Lookup order: opt-in URL interceptors
|
|
53
52
|
(see [§GitHub URL interceptor](#github-url-interceptor)), then the active provider's native
|
|
54
53
|
fetch endpoint when it has one (Tavily/Exa/You.com/Jina/Firecrawl/Ollama → vendor extraction;
|
|
@@ -61,6 +60,9 @@ Then restart your Pi session.
|
|
|
61
60
|
web_search({
|
|
62
61
|
query: string, // natural-language query
|
|
63
62
|
max_results?: number, // 1-10, default 5
|
|
63
|
+
provider?: // per-call provider override; see below
|
|
64
|
+
| "brave" | "tavily" | "serper" | "exa" | "youcom" | "jina"
|
|
65
|
+
| "firecrawl" | "perplexity" | "searxng" | "ollama",
|
|
64
66
|
})
|
|
65
67
|
```
|
|
66
68
|
|
|
@@ -78,7 +80,17 @@ Returns:
|
|
|
78
80
|
}
|
|
79
81
|
```
|
|
80
82
|
|
|
81
|
-
Throws when the
|
|
83
|
+
Throws when the resolved provider's API key is unset (e.g. `EXA_API_KEY is not set`), the provider's API returns a non-2xx response, or an explicit `provider` names a provider with no configured credentials (no silent fallback — the caller can detect the misconfiguration).
|
|
84
|
+
|
|
85
|
+
#### Per-call `provider` override
|
|
86
|
+
|
|
87
|
+
The optional `provider` parameter routes a single call to a different backend than the active provider set via `/web-tools`, without mutating persisted config or restarting the session. Resolution:
|
|
88
|
+
|
|
89
|
+
1. `params.provider` (if present) — must be one of the literal provider names listed above. Unknown names throw `Unknown web_search provider: "<name>"`.
|
|
90
|
+
2. `config.provider` (the active provider selected via `/web-tools`).
|
|
91
|
+
3. `brave` (default when `config.provider` is absent).
|
|
92
|
+
|
|
93
|
+
The named provider must have its own API key / base URL configured (via env var or `/web-tools`); the override does not inherit credentials from the active provider. A request for an unconfigured provider throws the provider's usual `… is not set` error rather than silently falling back, so agents can detect and react. Use this for provider comparison, falling back to a second backend when the active one returns poor results, or any multi-provider workflow that previously required a config switch and session restart.
|
|
82
94
|
|
|
83
95
|
### Schema - `web_fetch`
|
|
84
96
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juicesharp/rpiv-web-tools",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Pi extension. Web search and fetch for the model with pluggable providers (Brave, Tavily, Serper, Exa, You.com, Jina, Firecrawl, Perplexity, SearXNG, Ollama).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -51,7 +51,8 @@
|
|
|
51
51
|
"web-tools.ts",
|
|
52
52
|
"providers/",
|
|
53
53
|
"README.md",
|
|
54
|
-
"LICENSE"
|
|
54
|
+
"LICENSE",
|
|
55
|
+
"!**/*.test.ts"
|
|
55
56
|
],
|
|
56
57
|
"pi": {
|
|
57
58
|
"extensions": [
|
|
@@ -59,11 +60,11 @@
|
|
|
59
60
|
]
|
|
60
61
|
},
|
|
61
62
|
"dependencies": {
|
|
62
|
-
"@juicesharp/rpiv-config": "^
|
|
63
|
+
"@juicesharp/rpiv-config": "^2.0.0",
|
|
64
|
+
"typebox": "^1.1.24"
|
|
63
65
|
},
|
|
64
66
|
"peerDependencies": {
|
|
65
67
|
"@earendil-works/pi-coding-agent": "*",
|
|
66
|
-
"@earendil-works/pi-tui": "*"
|
|
67
|
-
"typebox": "*"
|
|
68
|
+
"@earendil-works/pi-tui": "*"
|
|
68
69
|
}
|
|
69
70
|
}
|
package/providers/config.ts
CHANGED
|
@@ -13,7 +13,12 @@
|
|
|
13
13
|
* startup."
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
configPath,
|
|
18
|
+
GuidanceFieldsSchema,
|
|
19
|
+
loadJsonConfigWithLegacyFallback,
|
|
20
|
+
saveJsonConfig,
|
|
21
|
+
} from "@juicesharp/rpiv-config";
|
|
17
22
|
import { type Static, Type } from "typebox";
|
|
18
23
|
import { Value } from "typebox/value";
|
|
19
24
|
|
|
@@ -76,7 +81,7 @@ export function getConfigPath(): string {
|
|
|
76
81
|
// `Value.Clean` (would strip unknown fields like the released `otherField`
|
|
77
82
|
// pass-through contract).
|
|
78
83
|
export function readConfig(): WebToolsConfig {
|
|
79
|
-
const raw =
|
|
84
|
+
const raw = loadJsonConfigWithLegacyFallback<unknown>("rpiv-web-tools");
|
|
80
85
|
if (!Value.Check(WebToolsConfigSchema, raw)) {
|
|
81
86
|
return {} as WebToolsConfig;
|
|
82
87
|
}
|
package/providers/exa.ts
CHANGED
|
@@ -10,7 +10,13 @@ export const EXA_PROVIDER_META = {
|
|
|
10
10
|
roles: ["search", "fetch"] as const,
|
|
11
11
|
} as const;
|
|
12
12
|
const EXA_MAX_SNIPPET_CHARACTERS = 300;
|
|
13
|
-
|
|
13
|
+
// Exa's documented maximum is 10 000 characters (OpenAPI schema has
|
|
14
|
+
// `maximum: 10000`), but the live API accepts up to 1 000 000.
|
|
15
|
+
// Using the higher value lets rpiv-web-tools' own truncation
|
|
16
|
+
// (DEFAULT_MAX_BYTES = 50 KiB) take over, which appends a
|
|
17
|
+
// truncation footer and spills full content to a temp file so
|
|
18
|
+
// the model can recover it with the read tool.
|
|
19
|
+
const EXA_MAX_FETCH_CHARACTERS = 1_000_000;
|
|
14
20
|
|
|
15
21
|
interface ExaRawResult {
|
|
16
22
|
title?: string;
|
package/web-tools.ts
CHANGED
|
@@ -130,13 +130,68 @@ function resolveProviderBaseUrl(meta: ProviderMeta, config: WebToolsConfig): str
|
|
|
130
130
|
return meta.defaultBaseUrl ?? "";
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
-
//
|
|
134
|
-
// the
|
|
135
|
-
|
|
133
|
+
// Known provider names — derived once from PROVIDERS so the schema enum,
|
|
134
|
+
// the per-call override validation, and the error messages all stay in sync
|
|
135
|
+
// when a provider is added or removed.
|
|
136
|
+
const KNOWN_PROVIDER_NAMES = PROVIDERS.map((p) => p.name) as readonly string[];
|
|
137
|
+
|
|
138
|
+
// Uniform "unknown provider" error for both the per-call override path and the
|
|
139
|
+
// WEB_SEARCH_PROVIDER env path so misconfiguration surfaces the same shape.
|
|
140
|
+
function assertKnownProvider(name: string): void {
|
|
141
|
+
if (!KNOWN_PROVIDER_NAMES.includes(name)) {
|
|
142
|
+
throw new Error(`Unknown web_search provider: "${name}". Valid providers: ${KNOWN_PROVIDER_NAMES.join(", ")}.`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Active-provider resolution for display + selection surfaces (env over config
|
|
147
|
+
// over default). Returns the raw name + its source — does NOT validate. A bogus
|
|
148
|
+
// WEB_SEARCH_PROVIDER renders in --show/picker (honest display) and only throws
|
|
149
|
+
// on the next web_search, via instantiateProvider's assertKnownProvider.
|
|
150
|
+
function resolveActiveProviderName(config: WebToolsConfig): {
|
|
151
|
+
name: string;
|
|
152
|
+
source: "env" | "config" | "default";
|
|
153
|
+
} {
|
|
154
|
+
const envProvider = process.env.WEB_SEARCH_PROVIDER?.trim();
|
|
155
|
+
if (envProvider) return { name: envProvider, source: "env" };
|
|
156
|
+
if (config.provider) return { name: config.provider, source: "config" };
|
|
157
|
+
return { name: DEFAULT_PROVIDER_NAME, source: "default" };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Centralized instantiation: resolve provider name + creds, build via the
|
|
161
|
+
// factory. Called by both registerWebSearchTool and registerWebFetchTool.
|
|
162
|
+
//
|
|
163
|
+
// `override` lets a single tool call target a different provider than the
|
|
164
|
+
// active one without mutating persisted state. Resolution (4-tier, first wins):
|
|
165
|
+
// providerName = override ?? WEB_SEARCH_PROVIDER ?? config.provider ?? DEFAULT_PROVIDER_NAME
|
|
166
|
+
// 1. override (per-call `provider` param) — validated against PROVIDERS;
|
|
167
|
+
// unknown names throw so callers can detect misconfiguration.
|
|
168
|
+
// 2. WEB_SEARCH_PROVIDER env var — validated like the override, but ONLY
|
|
169
|
+
// when it is the resolving tier: an override wins without consulting
|
|
170
|
+
// (or validating) the env, so a bogus env var cannot defeat a valid
|
|
171
|
+
// per-call override. Lets an operator pin a backend without editing
|
|
172
|
+
// config.json.
|
|
173
|
+
// 3. config.provider (the /web-tools-selected default)
|
|
174
|
+
// 4. DEFAULT_PROVIDER_NAME ("brave")
|
|
175
|
+
// Key/baseURL resolution always reads from env/config under the resolved
|
|
176
|
+
// provider name, so an override/env pin still needs its own credentials.
|
|
177
|
+
function instantiateProvider(
|
|
178
|
+
config: WebToolsConfig,
|
|
179
|
+
override?: string,
|
|
180
|
+
): {
|
|
136
181
|
providerName: string;
|
|
137
182
|
provider: SearchProvider | FullProvider;
|
|
138
183
|
} {
|
|
139
|
-
|
|
184
|
+
let providerName: string;
|
|
185
|
+
if (override !== undefined) {
|
|
186
|
+
assertKnownProvider(override);
|
|
187
|
+
providerName = override;
|
|
188
|
+
} else {
|
|
189
|
+
// Single env read via the shared resolver (one snapshot — no double
|
|
190
|
+
// read), validated only when env actually won the resolution.
|
|
191
|
+
const active = resolveActiveProviderName(config);
|
|
192
|
+
if (active.source === "env") assertKnownProvider(active.name);
|
|
193
|
+
providerName = active.name;
|
|
194
|
+
}
|
|
140
195
|
const apiKey = resolveProviderApiKey(providerName, config);
|
|
141
196
|
const meta = PROVIDERS.find((p) => p.name === providerName);
|
|
142
197
|
const baseUrl = meta?.baseUrlEnvVar ? resolveProviderBaseUrl(meta, config) : undefined;
|
|
@@ -275,12 +330,23 @@ export function registerWebSearchTool(pi: ExtensionAPI): void {
|
|
|
275
330
|
maximum: MAX_SEARCH_RESULTS,
|
|
276
331
|
}),
|
|
277
332
|
),
|
|
333
|
+
provider: Type.Optional(
|
|
334
|
+
Type.Union(
|
|
335
|
+
KNOWN_PROVIDER_NAMES.map((name) => Type.Literal(name)),
|
|
336
|
+
{
|
|
337
|
+
description:
|
|
338
|
+
"Search provider to use for this call only, overriding the active provider set via /web-tools. " +
|
|
339
|
+
`Valid values: ${KNOWN_PROVIDER_NAMES.join(", ")}. ` +
|
|
340
|
+
"Omit to use the configured active provider. The named provider must have its API key/URL configured (via env var or /web-tools) or the call throws — there is no silent fallback.",
|
|
341
|
+
},
|
|
342
|
+
),
|
|
343
|
+
),
|
|
278
344
|
}),
|
|
279
345
|
|
|
280
346
|
async execute(_toolCallId, params, signal, onUpdate, _ctx) {
|
|
281
347
|
const maxResults = clampSearchResultCount(params.max_results);
|
|
282
348
|
const config = loadConfig();
|
|
283
|
-
const { providerName, provider } =
|
|
349
|
+
const { providerName, provider } = instantiateProvider(config, params.provider);
|
|
284
350
|
|
|
285
351
|
onUpdate?.({
|
|
286
352
|
content: [{ type: "text", text: `Searching ${provider.label} for: "${params.query}"...` }],
|
|
@@ -307,6 +373,9 @@ export function registerWebSearchTool(pi: ExtensionAPI): void {
|
|
|
307
373
|
renderCall(args, theme, _context) {
|
|
308
374
|
let text = theme.fg("toolTitle", theme.bold("WebSearch "));
|
|
309
375
|
text += theme.fg("accent", `"${args.query}"`);
|
|
376
|
+
if (args.provider) {
|
|
377
|
+
text += theme.fg("dim", ` via ${args.provider}`);
|
|
378
|
+
}
|
|
310
379
|
return new Text(text, 0, 0);
|
|
311
380
|
},
|
|
312
381
|
|
|
@@ -368,7 +437,7 @@ export function registerWebFetchTool(pi: ExtensionAPI): void {
|
|
|
368
437
|
});
|
|
369
438
|
|
|
370
439
|
const config = loadConfig();
|
|
371
|
-
const { provider } =
|
|
440
|
+
const { provider } = instantiateProvider(config);
|
|
372
441
|
|
|
373
442
|
// Three-way capability dispatch:
|
|
374
443
|
// 1. URL interceptors (currently just GitHub) — opt-in URL specialists
|
|
@@ -465,8 +534,8 @@ function renderFetchedContentPreview(content: string, theme: Theme): string {
|
|
|
465
534
|
function formatShowConfigMessage(current: WebToolsConfig): string {
|
|
466
535
|
const lines = ["Web search config:", ` config file: ${CONFIG_PATH}`];
|
|
467
536
|
|
|
468
|
-
const providerName = current
|
|
469
|
-
lines.push(` active provider: ${providerName}`);
|
|
537
|
+
const { name: providerName, source: providerSource } = resolveActiveProviderName(current);
|
|
538
|
+
lines.push(` active provider: ${providerName} (source: ${providerSource})`);
|
|
470
539
|
|
|
471
540
|
for (const meta of PROVIDERS) {
|
|
472
541
|
const envKey = meta.envVar ? process.env[meta.envVar]?.trim() : undefined;
|
|
@@ -524,7 +593,7 @@ export function registerWebSearchConfigCommand(pi: ExtensionAPI): void {
|
|
|
524
593
|
return;
|
|
525
594
|
}
|
|
526
595
|
|
|
527
|
-
const activeProvider = current.
|
|
596
|
+
const activeProvider = resolveActiveProviderName(current).name;
|
|
528
597
|
const orderedMetas = [
|
|
529
598
|
...PROVIDERS.filter((p) => p.name === activeProvider),
|
|
530
599
|
...PROVIDERS.filter((p) => p.name !== activeProvider),
|
package/providers/config.test.ts
DELETED
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { dirname } from "node:path";
|
|
3
|
-
import { configPath } from "@juicesharp/rpiv-config";
|
|
4
|
-
import { beforeEach, describe, expect, it } from "vitest";
|
|
5
|
-
import { getConfigPath, readConfig, WebToolsConfigSchema, writeConfig } from "./config.js";
|
|
6
|
-
|
|
7
|
-
const CONFIG_PATH = configPath("rpiv-web-tools");
|
|
8
|
-
|
|
9
|
-
beforeEach(() => {
|
|
10
|
-
rmSync(CONFIG_PATH, { force: true });
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
function writeRaw(contents: string): void {
|
|
14
|
-
mkdirSync(dirname(CONFIG_PATH), { recursive: true });
|
|
15
|
-
writeFileSync(CONFIG_PATH, contents, "utf-8");
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
describe("getConfigPath", () => {
|
|
19
|
-
it("returns the canonical ~/.config/rpiv-web-tools/config.json", () => {
|
|
20
|
-
expect(getConfigPath()).toBe(CONFIG_PATH);
|
|
21
|
-
});
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
describe("readConfig — fail-soft posture", () => {
|
|
25
|
-
it("returns {} when the file does not exist", () => {
|
|
26
|
-
expect(readConfig()).toEqual({});
|
|
27
|
-
});
|
|
28
|
-
|
|
29
|
-
it("returns {} on malformed JSON (matches loadJsonConfig tolerance)", () => {
|
|
30
|
-
writeRaw("{ not valid json");
|
|
31
|
-
expect(readConfig()).toEqual({});
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
it("returns {} when the file is a directory (EISDIR)", () => {
|
|
35
|
-
mkdirSync(CONFIG_PATH, { recursive: true });
|
|
36
|
-
try {
|
|
37
|
-
expect(readConfig()).toEqual({});
|
|
38
|
-
} finally {
|
|
39
|
-
rmSync(CONFIG_PATH, { recursive: true, force: true });
|
|
40
|
-
}
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
it("returns {} when the schema validation fails hard (e.g. provider is a number)", () => {
|
|
44
|
-
writeRaw(JSON.stringify({ provider: 123 }));
|
|
45
|
-
expect(readConfig()).toEqual({});
|
|
46
|
-
});
|
|
47
|
-
});
|
|
48
|
-
|
|
49
|
-
describe("readConfig — released-shape compatibility", () => {
|
|
50
|
-
it("loads a minimal { provider, apiKeys } config unchanged", () => {
|
|
51
|
-
writeRaw(JSON.stringify({ provider: "brave", apiKeys: { brave: "k" } }));
|
|
52
|
-
expect(readConfig()).toEqual({ provider: "brave", apiKeys: { brave: "k" } });
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
it("loads the legacy top-level apiKey field", () => {
|
|
56
|
-
writeRaw(JSON.stringify({ apiKey: "legacy" }));
|
|
57
|
-
expect(readConfig()).toMatchObject({ apiKey: "legacy" });
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
it("preserves unknown top-level keys (otherField round-trip contract)", () => {
|
|
61
|
-
// The released /web-tools migrate-legacy-apiKey test relies on this:
|
|
62
|
-
// unknown keys MUST NOT be stripped by the schema reader.
|
|
63
|
-
writeRaw(JSON.stringify({ apiKey: "k", otherField: "keep" }));
|
|
64
|
-
const cfg = readConfig() as { otherField?: string };
|
|
65
|
-
expect(cfg.otherField).toBe("keep");
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
it("loads the guidance subtree with web_search + web_fetch", () => {
|
|
69
|
-
writeRaw(
|
|
70
|
-
JSON.stringify({
|
|
71
|
-
guidance: {
|
|
72
|
-
web_search: { promptSnippet: "snip", promptGuidelines: ["a", "b"] },
|
|
73
|
-
web_fetch: { promptSnippet: "snip2" },
|
|
74
|
-
},
|
|
75
|
-
}),
|
|
76
|
-
);
|
|
77
|
-
const cfg = readConfig();
|
|
78
|
-
expect(cfg.guidance?.web_search?.promptSnippet).toBe("snip");
|
|
79
|
-
expect(cfg.guidance?.web_fetch?.promptSnippet).toBe("snip2");
|
|
80
|
-
});
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
describe("readConfig — interceptors.github union", () => {
|
|
84
|
-
it("accepts the boolean true shorthand", () => {
|
|
85
|
-
writeRaw(JSON.stringify({ interceptors: { github: true } }));
|
|
86
|
-
expect(readConfig().interceptors?.github).toBe(true);
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
it("accepts the boolean false shorthand", () => {
|
|
90
|
-
writeRaw(JSON.stringify({ interceptors: { github: false } }));
|
|
91
|
-
expect(readConfig().interceptors?.github).toBe(false);
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
it("accepts the object override form", () => {
|
|
95
|
-
writeRaw(
|
|
96
|
-
JSON.stringify({
|
|
97
|
-
interceptors: { github: { maxRepoSizeMB: 1000, clonePath: "/x" } },
|
|
98
|
-
}),
|
|
99
|
-
);
|
|
100
|
-
const gh = readConfig().interceptors?.github;
|
|
101
|
-
expect(gh).toEqual({ maxRepoSizeMB: 1000, clonePath: "/x" });
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
it("falls back to {} when interceptors.github has a type-incompatible shape", () => {
|
|
105
|
-
// A number is neither boolean nor a GitHubInterceptorOptions object —
|
|
106
|
-
// hard schema failure → fail-soft to {}.
|
|
107
|
-
writeRaw(JSON.stringify({ interceptors: { github: 42 } }));
|
|
108
|
-
expect(readConfig()).toEqual({});
|
|
109
|
-
});
|
|
110
|
-
});
|
|
111
|
-
|
|
112
|
-
describe("writeConfig", () => {
|
|
113
|
-
it("round-trips a config through readConfig", () => {
|
|
114
|
-
expect(writeConfig({ provider: "brave", apiKeys: { brave: "k" } })).toBe(true);
|
|
115
|
-
expect(readConfig()).toEqual({ provider: "brave", apiKeys: { brave: "k" } });
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
it("preserves the interceptors.github stanza across save+load", () => {
|
|
119
|
-
expect(writeConfig({ interceptors: { github: { maxRepoSizeMB: 500 } } })).toBe(true);
|
|
120
|
-
expect(readConfig().interceptors?.github).toEqual({ maxRepoSizeMB: 500 });
|
|
121
|
-
});
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
describe("WebToolsConfigSchema — schema-only sanity", () => {
|
|
125
|
-
it("exists and is a TypeBox object", () => {
|
|
126
|
-
expect(WebToolsConfigSchema).toBeDefined();
|
|
127
|
-
expect(WebToolsConfigSchema.type).toBe("object");
|
|
128
|
-
});
|
|
129
|
-
});
|
|
@@ -1,209 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tests the interceptor chain dispatch in registerWebTools: first-match-wins,
|
|
3
|
-
* empty-chain fall-through, and the consumer×user-config opt-in resolution.
|
|
4
|
-
* Exercises the chain end-to-end via the registered web_fetch tool rather
|
|
5
|
-
* than the GitHubInterceptor class directly.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
-
import { dirname } from "node:path";
|
|
10
|
-
import { configPath } from "@juicesharp/rpiv-config";
|
|
11
|
-
import { createMockCtx, createMockPi, stubFetch } from "@juicesharp/rpiv-test-utils";
|
|
12
|
-
import { beforeEach, describe, expect, it } from "vitest";
|
|
13
|
-
import registerWebTools from "../../index.js";
|
|
14
|
-
|
|
15
|
-
const CONFIG_PATH = configPath("rpiv-web-tools");
|
|
16
|
-
|
|
17
|
-
function writeConfig(contents: unknown) {
|
|
18
|
-
mkdirSync(dirname(CONFIG_PATH), { recursive: true });
|
|
19
|
-
writeFileSync(CONFIG_PATH, JSON.stringify(contents), "utf-8");
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
beforeEach(() => {
|
|
23
|
-
delete process.env.BRAVE_SEARCH_API_KEY;
|
|
24
|
-
delete process.env.GITHUB_TOKEN;
|
|
25
|
-
rmSync(CONFIG_PATH, { force: true });
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
describe("interceptor chain — opt-in resolution", () => {
|
|
29
|
-
it("default OFF: github URL hits provider fetch when neither user nor consumer opts in", async () => {
|
|
30
|
-
process.env.BRAVE_SEARCH_API_KEY = "k";
|
|
31
|
-
writeConfig({ provider: "brave" });
|
|
32
|
-
stubFetch([
|
|
33
|
-
{
|
|
34
|
-
match: () => true,
|
|
35
|
-
response: () =>
|
|
36
|
-
new Response("<html><body>plain page</body></html>", {
|
|
37
|
-
status: 200,
|
|
38
|
-
headers: { "content-type": "text/html" },
|
|
39
|
-
}),
|
|
40
|
-
},
|
|
41
|
-
]);
|
|
42
|
-
const { pi, captured } = createMockPi();
|
|
43
|
-
registerWebTools(pi);
|
|
44
|
-
const r = await captured.tools
|
|
45
|
-
.get("web_fetch")
|
|
46
|
-
?.execute?.(
|
|
47
|
-
"tc",
|
|
48
|
-
{ url: "https://github.com/owner/repo" },
|
|
49
|
-
undefined as never,
|
|
50
|
-
undefined as never,
|
|
51
|
-
createMockCtx(),
|
|
52
|
-
);
|
|
53
|
-
expect(r?.content[0]).toMatchObject({ text: expect.stringContaining("plain page") });
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
it("consumer:true enables the interceptor when user config is absent", async () => {
|
|
57
|
-
// The interceptor is built; for github.com/owner/repo without gh available
|
|
58
|
-
// the interceptor returns null (clone+API both fail) and we fall through
|
|
59
|
-
// to provider.fetch. We assert the chain didn't short-circuit the fall-through.
|
|
60
|
-
process.env.BRAVE_SEARCH_API_KEY = "k";
|
|
61
|
-
writeConfig({ provider: "brave" });
|
|
62
|
-
stubFetch([
|
|
63
|
-
{
|
|
64
|
-
match: () => true,
|
|
65
|
-
response: () =>
|
|
66
|
-
new Response("<html><body>provider fallback</body></html>", {
|
|
67
|
-
status: 200,
|
|
68
|
-
headers: { "content-type": "text/html" },
|
|
69
|
-
}),
|
|
70
|
-
},
|
|
71
|
-
]);
|
|
72
|
-
const { pi, captured } = createMockPi();
|
|
73
|
-
registerWebTools(pi, { interceptors: { github: true } });
|
|
74
|
-
// owner/repo/issues → parseGitHubUrl returns null → intercept null → provider runs.
|
|
75
|
-
const r = await captured.tools
|
|
76
|
-
.get("web_fetch")
|
|
77
|
-
?.execute?.(
|
|
78
|
-
"tc",
|
|
79
|
-
{ url: "https://github.com/owner/repo/issues" },
|
|
80
|
-
undefined as never,
|
|
81
|
-
undefined as never,
|
|
82
|
-
createMockCtx(),
|
|
83
|
-
);
|
|
84
|
-
expect(r?.content[0]).toMatchObject({ text: expect.stringContaining("provider fallback") });
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
it("user config false beats consumer true (explicit user disable)", async () => {
|
|
88
|
-
process.env.BRAVE_SEARCH_API_KEY = "k";
|
|
89
|
-
writeConfig({ provider: "brave", interceptors: { github: false } });
|
|
90
|
-
stubFetch([
|
|
91
|
-
{
|
|
92
|
-
match: () => true,
|
|
93
|
-
response: () =>
|
|
94
|
-
new Response("<html><body>provider only</body></html>", {
|
|
95
|
-
status: 200,
|
|
96
|
-
headers: { "content-type": "text/html" },
|
|
97
|
-
}),
|
|
98
|
-
},
|
|
99
|
-
]);
|
|
100
|
-
const { pi, captured } = createMockPi();
|
|
101
|
-
registerWebTools(pi, { interceptors: { github: true } });
|
|
102
|
-
const r = await captured.tools
|
|
103
|
-
.get("web_fetch")
|
|
104
|
-
?.execute?.(
|
|
105
|
-
"tc",
|
|
106
|
-
{ url: "https://github.com/owner/repo/blob/main/x.ts" },
|
|
107
|
-
undefined as never,
|
|
108
|
-
undefined as never,
|
|
109
|
-
createMockCtx(),
|
|
110
|
-
);
|
|
111
|
-
// Interceptor is off — provider handled it.
|
|
112
|
-
expect(r?.content[0]).toMatchObject({ text: expect.stringContaining("provider only") });
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
it("user object form implies opt-in even when consumer left it unset", async () => {
|
|
116
|
-
// With the interceptor active and gh CLI absent in test env, the interceptor
|
|
117
|
-
// tries clone+API, both fail, and intercept() returns null. The chain falls
|
|
118
|
-
// through to the provider — i.e. the interceptor *ran* (rather than being
|
|
119
|
-
// skipped entirely as it would be when disabled). We verify this indirectly
|
|
120
|
-
// via no provider fetch happening when intercept actually succeeds in tests
|
|
121
|
-
// that use real network mocks; here we just confirm registration accepts it.
|
|
122
|
-
process.env.BRAVE_SEARCH_API_KEY = "k";
|
|
123
|
-
writeConfig({ provider: "brave", interceptors: { github: { maxRepoSizeMB: 999 } } });
|
|
124
|
-
stubFetch([
|
|
125
|
-
{
|
|
126
|
-
match: () => true,
|
|
127
|
-
response: () =>
|
|
128
|
-
new Response("<html><body>provider fallback</body></html>", {
|
|
129
|
-
status: 200,
|
|
130
|
-
headers: { "content-type": "text/html" },
|
|
131
|
-
}),
|
|
132
|
-
},
|
|
133
|
-
]);
|
|
134
|
-
const { pi, captured } = createMockPi();
|
|
135
|
-
registerWebTools(pi);
|
|
136
|
-
const r = await captured.tools
|
|
137
|
-
.get("web_fetch")
|
|
138
|
-
?.execute?.(
|
|
139
|
-
"tc",
|
|
140
|
-
{ url: "https://github.com/owner/repo/issues" },
|
|
141
|
-
undefined as never,
|
|
142
|
-
undefined as never,
|
|
143
|
-
createMockCtx(),
|
|
144
|
-
);
|
|
145
|
-
expect(r?.content[0]).toMatchObject({ text: expect.stringContaining("provider fallback") });
|
|
146
|
-
});
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
describe("interceptor chain — fall-through semantics", () => {
|
|
150
|
-
it("interceptor returning null falls through to provider fetch", async () => {
|
|
151
|
-
// owner/repo/issues → NON_CODE_SEGMENTS → parseGitHubUrl returns null,
|
|
152
|
-
// intercept short-circuits to null → provider handles the URL.
|
|
153
|
-
process.env.BRAVE_SEARCH_API_KEY = "k";
|
|
154
|
-
writeConfig({ provider: "brave", interceptors: { github: true } });
|
|
155
|
-
stubFetch([
|
|
156
|
-
{
|
|
157
|
-
match: () => true,
|
|
158
|
-
response: () =>
|
|
159
|
-
new Response("<html><body>fallback body</body></html>", {
|
|
160
|
-
status: 200,
|
|
161
|
-
headers: { "content-type": "text/html" },
|
|
162
|
-
}),
|
|
163
|
-
},
|
|
164
|
-
]);
|
|
165
|
-
const { pi, captured } = createMockPi();
|
|
166
|
-
registerWebTools(pi);
|
|
167
|
-
const r = await captured.tools
|
|
168
|
-
.get("web_fetch")
|
|
169
|
-
?.execute?.(
|
|
170
|
-
"tc",
|
|
171
|
-
{ url: "https://github.com/owner/repo/issues" },
|
|
172
|
-
undefined as never,
|
|
173
|
-
undefined as never,
|
|
174
|
-
createMockCtx(),
|
|
175
|
-
);
|
|
176
|
-
expect(r?.content[0]).toMatchObject({ text: expect.stringContaining("fallback body") });
|
|
177
|
-
});
|
|
178
|
-
|
|
179
|
-
it("empty chain (interceptor disabled) is a no-op — every URL hits the provider", async () => {
|
|
180
|
-
process.env.BRAVE_SEARCH_API_KEY = "k";
|
|
181
|
-
writeConfig({ provider: "brave" });
|
|
182
|
-
stubFetch([
|
|
183
|
-
{
|
|
184
|
-
match: () => true,
|
|
185
|
-
response: () =>
|
|
186
|
-
new Response("<html><body>vanilla</body></html>", {
|
|
187
|
-
status: 200,
|
|
188
|
-
headers: { "content-type": "text/html" },
|
|
189
|
-
}),
|
|
190
|
-
},
|
|
191
|
-
]);
|
|
192
|
-
const { pi, captured } = createMockPi();
|
|
193
|
-
registerWebTools(pi);
|
|
194
|
-
const r1 = await captured.tools
|
|
195
|
-
.get("web_fetch")
|
|
196
|
-
?.execute?.("tc", { url: "https://example.com/" }, undefined as never, undefined as never, createMockCtx());
|
|
197
|
-
const r2 = await captured.tools
|
|
198
|
-
.get("web_fetch")
|
|
199
|
-
?.execute?.(
|
|
200
|
-
"tc",
|
|
201
|
-
{ url: "https://github.com/owner/repo/blob/main/file.ts" },
|
|
202
|
-
undefined as never,
|
|
203
|
-
undefined as never,
|
|
204
|
-
createMockCtx(),
|
|
205
|
-
);
|
|
206
|
-
expect(r1?.content[0]).toMatchObject({ text: expect.stringContaining("vanilla") });
|
|
207
|
-
expect(r2?.content[0]).toMatchObject({ text: expect.stringContaining("vanilla") });
|
|
208
|
-
});
|
|
209
|
-
});
|