summaryrefslogtreecommitdiff
path: root/config/pi/extensions/parallel-search.ts
blob: 3bca820c88cc5bb38865d46abb9733eedd91b55a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/**
 * Parallel Search Extension - Web search via Parallel.ai
 *
 * Provides the search tool for searching the web using natural language objectives or keyword queries.
 *
 * Requires PARALLEL_API_KEY environment variable.
 *
 * https://docs.parallel.ai
 */

import {
    DEFAULT_MAX_BYTES,
    DEFAULT_MAX_LINES,
    type ExtensionAPI,
    formatSize,
    getMarkdownTheme,
    keyHint,
    type Theme,
    truncateHead,
} from "@mariozechner/pi-coding-agent";
import { Container, Markdown, Spacer, Text } from "@mariozechner/pi-tui";
import { Type } from "typebox";

const API_BASE = "https://api.parallel.ai";
const BETA_HEADER = "search-extract-2025-10-10";

function getApiKey(): string {
    const key = process.env.PARALLEL_API_KEY;
    if (!key) {
        throw new Error(
            "PARALLEL_API_KEY environment variable is not set. " +
                "Get your API key at https://platform.parallel.ai",
        );
    }
    return key;
}

// ── API types ──────────────────────────────────────────────────────────────

interface SearchResult {
    url: string;
    title?: string | null;
    publish_date?: string | null;
    excerpts?: string[] | null;
}

interface SearchResponse {
    search_id: string;
    results: SearchResult[];
}

// ── API helper ─────────────────────────────────────────────────────────────

async function parallelSearch(
    params: {
        objective?: string;
        search_queries?: string[];
        max_results?: number;
        mode?: string;
        include_domains?: string[];
        exclude_domains?: string[];
        after_date?: string;
        max_chars_per_result?: number;
        max_chars_total?: number;
    },
    signal?: AbortSignal,
): Promise<SearchResponse> {
    const body: Record<string, unknown> = {
        mode: params.mode ?? "agentic",
    };
    if (params.objective) body.objective = params.objective;
    if (params.search_queries) body.search_queries = params.search_queries;
    if (params.max_results) body.max_results = params.max_results;

    if (params.max_chars_per_result || params.max_chars_total) {
        const excerpts: Record<string, unknown> = {};
        if (params.max_chars_per_result) excerpts.max_chars_per_result = params.max_chars_per_result;
        if (params.max_chars_total) excerpts.max_chars_total = params.max_chars_total;
        body.excerpts = excerpts;
    }

    if (params.include_domains || params.exclude_domains || params.after_date) {
        const sourcePolicy: Record<string, unknown> = {};
        if (params.include_domains) sourcePolicy.include_domains = params.include_domains;
        if (params.exclude_domains) sourcePolicy.exclude_domains = params.exclude_domains;
        if (params.after_date) sourcePolicy.after_date = params.after_date;
        body.source_policy = sourcePolicy;
    }

    const resp = await fetch(`${API_BASE}/v1beta/search`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "x-api-key": getApiKey(),
            "parallel-beta": BETA_HEADER,
        },
        body: JSON.stringify(body),
        signal,
    });

    if (!resp.ok) {
        const text = await resp.text().catch(() => "");
        throw new Error(`Parallel search API error ${resp.status}: ${text}`);
    }

    return (await resp.json()) as SearchResponse;
}

// ── Formatting helper ──────────────────────────────────────────────────────

function formatSearchResults(results: SearchResult[]): string {
    if (results.length === 0) return "No results found.";

    const parts: string[] = [];
    for (let i = 0; i < results.length; i++) {
        const r = results[i];
        let entry = `[${i + 1}] ${r.title ?? "(no title)"}\n    ${r.url}`;
        if (r.publish_date) entry += `\n    Published: ${r.publish_date}`;
        if (r.excerpts?.length) {
            entry += "\n" + r.excerpts.map((e) => `    ${e}`).join("\n");
        }
        parts.push(entry);
    }
    return parts.join("\n\n");
}

// ── Tool details types ─────────────────────────────────────────────────────

interface SearchResultDetail {
    url: string;
    title?: string | null;
    publish_date?: string | null;
    excerpts?: string[] | null;
}

interface SearchDetails {
    objective?: string;
    search_queries?: string[];
    resultCount: number;
    searchId: string;
    results?: SearchResultDetail[];
    spinnerFrame?: number;
}

// ── Spinner ─────────────────────────────────────────────────────────────────

const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];

type SpinnerUpdate = (partial: {
    content: { type: "text"; text: string }[];
    details?: SearchDetails;
}) => void;

function startSpinner(
    onUpdate: SpinnerUpdate | undefined,
    baseDetails: SearchDetails,
    signal?: AbortSignal,
): () => void {
    if (!onUpdate) return () => {};
    let frame = 0;
    const interval = setInterval(() => {
        if (signal?.aborted) {
            clearInterval(interval);
            return;
        }
        onUpdate({
            content: [{ type: "text", text: "Running..." }],
            details: { ...baseDetails, spinnerFrame: frame },
        });
        frame = (frame + 1) % SPINNER_FRAMES.length;
    }, 80);
    return () => clearInterval(interval);
}

function renderSpinner(details: SearchDetails | undefined, theme: Theme, label: string): Text {
    const frame = details?.spinnerFrame ?? 0;
    const spinner = SPINNER_FRAMES[frame % SPINNER_FRAMES.length];
    return new Text(`\n${theme.fg("dim", `${spinner} ${label} (escape/ctrl+c to cancel)`)}`, 0, 0);
}

// ── Extension entry point ──────────────────────────────────────────────────

export default function (pi: ExtensionAPI) {
    if (!process.env.PARALLEL_API_KEY) return;

    const searchCountCache = new Map<string, number>();
    function searchCacheKey(objective?: string, search_queries?: string[]): string {
        return JSON.stringify({ objective, search_queries });
    }

    pi.registerTool({
        name: "search",
        label: "Search",
        description:
            `Search the web. Provide a natural language objective describing what you're looking for, ` +
            `and/or keyword search queries. Returns relevant results with titles, URLs, and excerpts. ` +
            `Output truncated to ${DEFAULT_MAX_LINES} lines or ${formatSize(DEFAULT_MAX_BYTES)}.`,
        promptSnippet: "Search the web via Parallel.ai (objective and/or keyword queries)",
        parameters: Type.Object({
            objective: Type.Optional(
                Type.String({
                    description:
                        "Natural language description of what to find. At least one of objective or search_queries is required.",
                }),
            ),
            search_queries: Type.Optional(
                Type.Array(Type.String(), {
                    description:
                        "Keyword search queries. May contain search operators. At least one of objective or search_queries is required.",
                }),
            ),
            max_results: Type.Optional(
                Type.Number({
                    description: "Max results to return (default: 5)",
                }),
            ),
            mode: Type.Optional(
                Type.String({
                    description:
                        'Search mode: "agentic" (default, concise), "one-shot" (comprehensive), or "fast" (lower latency)',
                }),
            ),
            include_domains: Type.Optional(
                Type.Array(Type.String(), {
                    description: 'Restrict results to these domains (e.g. ["wikipedia.org", ".gov"])',
                }),
            ),
            exclude_domains: Type.Optional(
                Type.Array(Type.String(), {
                    description: 'Exclude results from these domains (e.g. ["reddit.com"])',
                }),
            ),
            after_date: Type.Optional(
                Type.String({
                    description: "Only return results published on or after this date (YYYY-MM-DD)",
                }),
            ),
            max_chars_per_result: Type.Optional(
                Type.Number({
                    description: "Max characters of excerpts per result (min 1000)",
                }),
            ),
            max_chars_total: Type.Optional(
                Type.Number({
                    description: "Max total characters of excerpts across all results (min 1000)",
                }),
            ),
        }),

        async execute(_toolCallId, params, signal, onUpdate) {
            const {
                objective,
                search_queries,
                max_results,
                mode,
                include_domains,
                exclude_domains,
                after_date,
                max_chars_per_result,
                max_chars_total,
            } = params;

            if (!objective && (!search_queries || search_queries.length === 0)) {
                throw new Error("at least one of objective or search_queries must be provided.");
            }

            const baseDetails: SearchDetails = {
                objective,
                search_queries,
                resultCount: 0,
                searchId: "",
            };
            const stopSpinner = startSpinner(onUpdate as SpinnerUpdate | undefined, baseDetails, signal);

            let response: SearchResponse;
            try {
                response = await parallelSearch(
                    {
                        objective,
                        search_queries,
                        max_results: max_results ?? 5,
                        mode,
                        include_domains,
                        exclude_domains,
                        after_date,
                        max_chars_per_result: max_chars_per_result ?? 500,
                        max_chars_total: max_chars_total ?? 2500,
                    },
                    signal,
                );
            } finally {
                stopSpinner();
            }

            let resultText = formatSearchResults(response.results);

            const truncation = truncateHead(resultText, {
                maxLines: DEFAULT_MAX_LINES,
                maxBytes: DEFAULT_MAX_BYTES,
            });

            resultText = truncation.content;
            if (truncation.truncated) {
                resultText += `\n\n[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines `;
                resultText += `(${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)})]`;
            }

            searchCountCache.set(searchCacheKey(objective, search_queries), response.results.length);

            const details: SearchDetails = {
                objective,
                search_queries,
                resultCount: response.results.length,
                searchId: response.search_id,
                results: response.results.map((r) => ({
                    url: r.url,
                    title: r.title,
                    publish_date: r.publish_date,
                    excerpts: r.excerpts,
                })),
            };

            return {
                content: [{ type: "text", text: resultText }],
                details,
            };
        },

        renderCall(args, theme) {
            let text = theme.fg("toolTitle", theme.bold("search "));
            if (args.objective) {
                text += theme.fg("accent", `${args.objective}`);
            } else if (args.search_queries?.length) {
                text += theme.fg("accent", args.search_queries.join(", "));
            }
            if (args.include_domains?.length) {
                text += theme.fg("muted", ` site:${args.include_domains.join(",")}`);
            }
            const count = searchCountCache.get(searchCacheKey(args.objective, args.search_queries));
            if (count !== undefined) {
                text += theme.fg("dim", ` [${count} results]`);
            }
            return new Text(text, 0, 0);
        },

        renderResult(result, { expanded, isPartial }, theme) {
            const details = result.details as SearchDetails | undefined;

            if (isPartial) {
                return renderSpinner(details, theme, "Searching...");
            }

            if (!details || !details.resultCount) {
                const content = result.content[0];
                const msg = content?.type === "text" ? content.text : "No results found";
                return new Text(theme.fg("warning", msg), 0, 0);
            }

            if (!expanded) {
                let text = "\n";
                if (details.results?.length) {
                    for (let i = 0; i < details.results.length; i++) {
                        const r = details.results[i];
                        if (i > 0) text += "\n";
                        const url = r.url.replace(/^https?:\/\//, "");
                        text += `${theme.fg("dim", `${i + 1}.`)} ${theme.fg("accent", url)}`;
                    }
                }
                text += `\n\n(${keyHint("app.tools.expand", "to expand")})`;
                return new Text(text, 0, 0);
            }

            const container = new Container();
            container.addChild(new Spacer(1));

            if (details.results?.length) {
                const mdTheme = getMarkdownTheme();
                for (let i = 0; i < details.results.length; i++) {
                    if (i > 0) {
                        container.addChild(new Spacer(1));
                    }
                    const r = details.results[i];
                    const url = r.url.replace(/^https?:\/\//, "");
                    const header = `${theme.fg("dim", `${i + 1}.`)} ${theme.fg("accent", url)}`;
                    container.addChild(new Text(header, 0, 0));

                    if (r.excerpts?.length) {
                        const excerptMd = r.excerpts.join("\n\n---\n\n");
                        container.addChild(
                            new Markdown(excerptMd, 3, 0, mdTheme, { color: (t) => theme.fg("dim", t) }),
                        );
                    }
                }
            }

            container.addChild(new Spacer(1));
            container.addChild(new Text(`(${keyHint("app.tools.expand", "to collapse")})`, 0, 0));
            return container;
        },
    });
}