Add Pi Research Agent package
Autonomous research agent with web search, source analysis, and report synthesis. Built on Pi agent core. Available as CLI, programmatic API, and MCP server. Features: - 4 built-in tools: web_search, read_url, save_note, synthesize_report - CLI with TUI and print modes - Programmatic API via ResearchAgent class - MCP server with 3 tools: research, quick_search, read_url - Skills system for custom research behavior - Automatic .env file loading for API keys - Configurable max turns, output formats (markdown/JSON/bullet) - Automatic report saving to research-output/
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
/**
|
||||
* Simple .env file parser
|
||||
* Supports:
|
||||
* - KEY=VALUE
|
||||
* - KEY="VALUE" (double quotes)
|
||||
* - KEY='VALUE' (single quotes)
|
||||
* - # comments
|
||||
* - Empty lines
|
||||
* - Multiline values with quotes
|
||||
*/
|
||||
export function parseEnvFile(content: string): Record<string, string> {
|
||||
const result: Record<string, string> = {};
|
||||
const lines = content.split("\n");
|
||||
let currentKey = "";
|
||||
let currentValue = "";
|
||||
let inMultiline = false;
|
||||
let quoteChar = "";
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
|
||||
// Handle multiline values
|
||||
if (inMultiline) {
|
||||
if (line.endsWith(quoteChar)) {
|
||||
currentValue += `\n${line.slice(0, -1)}`;
|
||||
result[currentKey] = currentValue;
|
||||
inMultiline = false;
|
||||
currentKey = "";
|
||||
currentValue = "";
|
||||
} else {
|
||||
currentValue += `\n${line}`;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip empty lines and comments
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Parse KEY=VALUE
|
||||
const eqIndex = trimmed.indexOf("=");
|
||||
if (eqIndex === -1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = trimmed.slice(0, eqIndex).trim();
|
||||
let value = trimmed.slice(eqIndex + 1).trim();
|
||||
|
||||
// Handle quoted values
|
||||
if (value.startsWith('"') || value.startsWith("'")) {
|
||||
quoteChar = value[0];
|
||||
value = value.slice(1);
|
||||
|
||||
// Check if it's a multiline value
|
||||
if (!value.endsWith(quoteChar)) {
|
||||
currentKey = key;
|
||||
currentValue = value;
|
||||
inMultiline = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Single-line quoted value
|
||||
value = value.slice(0, -1);
|
||||
}
|
||||
|
||||
// Unescape common escape sequences
|
||||
value = value
|
||||
.replace(/\\n/g, "\n")
|
||||
.replace(/\\r/g, "\r")
|
||||
.replace(/\\t/g, "\t")
|
||||
.replace(/\\"/g, '"')
|
||||
.replace(/\\'/g, "'");
|
||||
|
||||
result[key] = value;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load .env file and set variables in process.env
|
||||
* Only sets variables that are not already defined in process.env
|
||||
* (environment variables take precedence)
|
||||
*/
|
||||
export function loadEnvFile(envPath?: string): void {
|
||||
const paths: string[] = [];
|
||||
|
||||
if (envPath) {
|
||||
paths.push(envPath);
|
||||
} else {
|
||||
// Try current working directory
|
||||
paths.push(join(process.cwd(), ".env"));
|
||||
paths.push(join(process.cwd(), "packages/research-agent/.env"));
|
||||
|
||||
// Try relative to this script's location
|
||||
try {
|
||||
const currentFile = fileURLToPath(import.meta.url);
|
||||
const scriptDir = dirname(currentFile);
|
||||
|
||||
// Go up from dist/utils to research-agent root
|
||||
const researchAgentDir = dirname(scriptDir);
|
||||
paths.push(join(researchAgentDir, ".env"));
|
||||
|
||||
// Go up to project root (pi-research)
|
||||
const projectRoot = dirname(researchAgentDir);
|
||||
paths.push(join(projectRoot, ".env"));
|
||||
} catch {
|
||||
// Ignore errors if import.meta.url is not available
|
||||
}
|
||||
}
|
||||
|
||||
for (const path of paths) {
|
||||
if (!existsSync(path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(path, "utf-8");
|
||||
const vars = parseEnvFile(content);
|
||||
|
||||
for (const [key, value] of Object.entries(vars)) {
|
||||
// Don't override existing environment variables
|
||||
if (process.env[key] === undefined) {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
// Successfully loaded from first found file
|
||||
return;
|
||||
} catch (error) {
|
||||
console.warn(`Warning: Failed to load .env file from ${path}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { fetch } from "undici";
|
||||
|
||||
const USER_AGENT =
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
|
||||
|
||||
const ALTERNATIVE_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0";
|
||||
|
||||
export async function fetchAndExtract(url: string, maxLength: number, useAlternativeUA = false): Promise<string> {
|
||||
const userAgent = useAlternativeUA ? ALTERNATIVE_USER_AGENT : USER_AGENT;
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
"User-Agent": userAgent,
|
||||
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Accept-Language": "en-US,en;q=0.9",
|
||||
},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
const html = await response.text();
|
||||
|
||||
let text: string;
|
||||
if (contentType.includes("text/html")) {
|
||||
text = extractTextFromHtml(html);
|
||||
} else {
|
||||
text = html;
|
||||
}
|
||||
|
||||
text = collapseWhitespace(text);
|
||||
|
||||
if (text.length > maxLength) {
|
||||
text = `${text.slice(0, maxLength)}\n\n[... content truncated ...]`;
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
function extractTextFromHtml(html: string): string {
|
||||
let text = html;
|
||||
|
||||
text = text.replace(/<script[\s\S]*?<\/script>/gi, "");
|
||||
text = text.replace(/<style[\s\S]*?<\/style>/gi, "");
|
||||
text = text.replace(/<nav[\s\S]*?<\/nav>/gi, "");
|
||||
text = text.replace(/<footer[\s\S]*?<\/footer>/gi, "");
|
||||
text = text.replace(/<header[\s\S]*?<\/header>/gi, "");
|
||||
|
||||
const articleMatch = text.match(/<article[^>]*>([\s\S]*?)<\/article>/i);
|
||||
const mainMatch = text.match(/<main[^>]*>([\s\S]*?)<\/main>/i);
|
||||
|
||||
if (articleMatch) {
|
||||
text = articleMatch[1];
|
||||
} else if (mainMatch) {
|
||||
text = mainMatch[1];
|
||||
}
|
||||
|
||||
text = text.replace(/<[^>]+>/g, " ");
|
||||
|
||||
text = decodeHtmlEntities(text);
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
function decodeHtmlEntities(text: string): string {
|
||||
return text
|
||||
.replace(/ /g, " ")
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&#(\d+);/g, (_, code) => String.fromCharCode(Number.parseInt(code, 10)));
|
||||
}
|
||||
|
||||
function collapseWhitespace(text: string): string {
|
||||
return text
|
||||
.split("\n")
|
||||
.map((line) => line.replace(/\s+/g, " ").trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { ResearchNote, SearchResult } from "../types.ts";
|
||||
|
||||
export function formatSearchResults(results: SearchResult[]): string {
|
||||
if (results.length === 0) {
|
||||
return "No results found.";
|
||||
}
|
||||
|
||||
const lines: string[] = [`Found ${results.length} results:\n`];
|
||||
|
||||
for (let i = 0; i < results.length; i++) {
|
||||
const r = results[i];
|
||||
lines.push(`[${i + 1}] ${r.title}`);
|
||||
lines.push(` URL: ${r.url}`);
|
||||
lines.push(` Relevance: ${(r.score * 100).toFixed(0)}%`);
|
||||
lines.push(` Snippet: ${r.content.slice(0, 500)}${r.content.length > 500 ? "..." : ""}`);
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function formatNotes(notes: ResearchNote[]): string {
|
||||
if (notes.length === 0) {
|
||||
return "No notes collected.";
|
||||
}
|
||||
|
||||
const lines: string[] = [`Collected ${notes.length} research notes:\n`];
|
||||
|
||||
for (let i = 0; i < notes.length; i++) {
|
||||
const note = notes[i];
|
||||
lines.push(`--- Note ${i + 1} ---`);
|
||||
lines.push(`Topic: ${note.topic}`);
|
||||
lines.push(`Confidence: ${note.confidence}`);
|
||||
lines.push(`Source: ${note.source_url}`);
|
||||
lines.push(`Finding: ${note.finding}`);
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { fetch } from "undici";
|
||||
import { TAVILY_API_URL } from "../config.ts";
|
||||
import type { SearchResult, TavilySearchResponse } from "../types.ts";
|
||||
|
||||
export interface TavilySearchOptions {
|
||||
apiKey: string;
|
||||
maxResults?: number;
|
||||
searchDepth?: "basic" | "advanced";
|
||||
includeAnswer?: boolean;
|
||||
}
|
||||
|
||||
export async function tavilySearch(query: string, options: TavilySearchOptions): Promise<TavilySearchResponse> {
|
||||
const response = await fetch(TAVILY_API_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_key: options.apiKey,
|
||||
query,
|
||||
max_results: options.maxResults ?? 10,
|
||||
search_depth: options.searchDepth ?? "basic",
|
||||
include_answer: options.includeAnswer ?? false,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Tavily API error (${response.status}): ${errorText}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as {
|
||||
query: string;
|
||||
results: Array<{
|
||||
title: string;
|
||||
url: string;
|
||||
content: string;
|
||||
score: number;
|
||||
}>;
|
||||
answer?: string;
|
||||
};
|
||||
|
||||
return {
|
||||
query: data.query,
|
||||
results: data.results.map(
|
||||
(r): SearchResult => ({
|
||||
title: r.title,
|
||||
url: r.url,
|
||||
content: r.content,
|
||||
score: r.score,
|
||||
}),
|
||||
),
|
||||
answer: data.answer,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user