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,404 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { Agent, type AgentEvent, type AgentMessage } from "@earendil-works/pi-agent-core";
|
||||
import { type Api, getModels, type Message, type Model, streamSimple } from "@earendil-works/pi-ai";
|
||||
import {
|
||||
DEFAULT_MAX_TURNS,
|
||||
DEFAULT_MODEL_ID,
|
||||
DEFAULT_OUTPUT_DIR,
|
||||
DEFAULT_PROVIDER,
|
||||
ENV_LLM_MODEL,
|
||||
ENV_OPENROUTER_API_KEY,
|
||||
ENV_TAVILY_API_KEY,
|
||||
MIN_REPORT_LENGTH,
|
||||
} from "./config.ts";
|
||||
import { buildSystemPrompt } from "./system-prompt.ts";
|
||||
import { createNoteStore, createResearchTools } from "./tools/index.ts";
|
||||
import type { NoteStore, ResearchAgentOptions, ResearchResult } from "./types.ts";
|
||||
|
||||
export class ResearchAgent {
|
||||
private agent: Agent;
|
||||
private notes: NoteStore;
|
||||
private turnCount = 0;
|
||||
private maxTurns: number;
|
||||
private report = "";
|
||||
private forcedSynthesis = false;
|
||||
private synthesisRequested = false;
|
||||
private reportGenerationStopped = false;
|
||||
private turnsAfterSynthesis = 0;
|
||||
private topic = "";
|
||||
private outputDir: string;
|
||||
private saveResults: boolean;
|
||||
|
||||
constructor(options: ResearchAgentOptions = {}) {
|
||||
this.notes = createNoteStore();
|
||||
this.maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS;
|
||||
this.outputDir = options.outputDir ?? DEFAULT_OUTPUT_DIR;
|
||||
this.saveResults = options.saveResults ?? true;
|
||||
|
||||
const tavilyApiKey = options.tavilyApiKey ?? process.env[ENV_TAVILY_API_KEY];
|
||||
if (!tavilyApiKey) {
|
||||
throw new Error(
|
||||
`Tavily API key is required. Set ${ENV_TAVILY_API_KEY} environment variable or pass tavilyApiKey option.`,
|
||||
);
|
||||
}
|
||||
|
||||
const llmApiKey = options.llmApiKey ?? process.env[ENV_OPENROUTER_API_KEY];
|
||||
if (!llmApiKey) {
|
||||
throw new Error(
|
||||
`LLM API key is required. Set ${ENV_OPENROUTER_API_KEY} environment variable or pass llmApiKey option.`,
|
||||
);
|
||||
}
|
||||
|
||||
const model = options.model ?? this.resolveModel();
|
||||
const tools = createResearchTools(this.notes, tavilyApiKey);
|
||||
const systemPrompt = buildSystemPrompt(options.skills);
|
||||
|
||||
this.agent = new Agent({
|
||||
initialState: {
|
||||
systemPrompt,
|
||||
model,
|
||||
thinkingLevel: options.thinkingLevel ?? "medium",
|
||||
tools,
|
||||
},
|
||||
streamFn: async (streamModel, context, opts) => {
|
||||
return streamSimple(streamModel, context, {
|
||||
...opts,
|
||||
apiKey: llmApiKey,
|
||||
});
|
||||
},
|
||||
convertToLlm: (messages: AgentMessage[]): Message[] => {
|
||||
return messages.filter(
|
||||
(m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult",
|
||||
) as Message[];
|
||||
},
|
||||
});
|
||||
|
||||
this.agent.subscribe((event: AgentEvent) => {
|
||||
// Log assistant message generation for debugging
|
||||
if (event.type === "message_end" && event.message.role === "assistant") {
|
||||
const textContent = event.message.content.find((c) => c.type === "text");
|
||||
if (textContent && textContent.type === "text" && textContent.text.length > 0) {
|
||||
console.error(`[Assistant message generated, length: ${textContent.text.length}]`);
|
||||
}
|
||||
}
|
||||
|
||||
// Track when synthesize_report tool completes successfully
|
||||
if (event.type === "tool_execution_end" && event.toolName === "synthesize_report") {
|
||||
if (event.result?.details && event.result.details.synthesisRequested === true) {
|
||||
this.synthesisRequested = true;
|
||||
this.turnsAfterSynthesis = 0;
|
||||
console.error(`\n[synthesize_report called, waiting for report generation...]`);
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "turn_end") {
|
||||
this.turnCount++;
|
||||
|
||||
// After synthesize_report was called, track turns and check for report
|
||||
if (this.synthesisRequested && !this.reportGenerationStopped) {
|
||||
this.turnsAfterSynthesis++;
|
||||
|
||||
const lastMsg = this.getLastAssistantMessage();
|
||||
const reportLength = lastMsg ? this.getTextLength(lastMsg) : 0;
|
||||
const hasReport = reportLength >= MIN_REPORT_LENGTH;
|
||||
|
||||
// Stop after 2 turns OR if we have a substantial report after at least 1 turn
|
||||
if (this.turnsAfterSynthesis >= 2 || (hasReport && this.turnsAfterSynthesis >= 1)) {
|
||||
this.reportGenerationStopped = true;
|
||||
console.error(`\n[Report generation complete. Stopping agent.]`);
|
||||
this.agent.abort();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// When reaching max turns, inject a steering message to force synthesis
|
||||
if (this.turnCount >= this.maxTurns && !this.forcedSynthesis && !this.synthesisRequested) {
|
||||
this.forcedSynthesis = true;
|
||||
console.error(`\n[Max turns (${this.maxTurns}) reached. Forcing report synthesis.]`);
|
||||
this.agent.steer({
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `You have reached the maximum number of research turns (${this.maxTurns}). You MUST now call the synthesize_report tool immediately with all the notes you have collected. Do not search or read more - synthesize what you have now.`,
|
||||
},
|
||||
],
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private resolveModel(): Model<Api> {
|
||||
const modelId = process.env[ENV_LLM_MODEL] ?? DEFAULT_MODEL_ID;
|
||||
const models = getModels(DEFAULT_PROVIDER);
|
||||
const model = models.find((m) => m.id === modelId);
|
||||
if (!model) {
|
||||
throw new Error(`Model not found: ${DEFAULT_PROVIDER}/${modelId}`);
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
subscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {
|
||||
return this.agent.subscribe(listener);
|
||||
}
|
||||
|
||||
get state() {
|
||||
return this.agent.state;
|
||||
}
|
||||
|
||||
getNoteCount(): number {
|
||||
return this.notes.count();
|
||||
}
|
||||
|
||||
getTurnCount(): number {
|
||||
return this.turnCount;
|
||||
}
|
||||
|
||||
async research(topic: string): Promise<ResearchResult> {
|
||||
this.turnCount = 0;
|
||||
this.notes.clear();
|
||||
this.report = "";
|
||||
this.forcedSynthesis = false;
|
||||
this.synthesisRequested = false;
|
||||
this.reportGenerationStopped = false;
|
||||
this.turnsAfterSynthesis = 0;
|
||||
this.topic = topic;
|
||||
|
||||
await this.agent.prompt(topic);
|
||||
|
||||
this.extractReport();
|
||||
|
||||
// Fallback: if no report was generated, create one from notes
|
||||
if (!this.report || this.report.trim() === "") {
|
||||
this.report = this.generateFallbackReport();
|
||||
}
|
||||
|
||||
const result: ResearchResult = {
|
||||
topic,
|
||||
notes: this.notes.getAll(),
|
||||
report: this.report,
|
||||
turnsUsed: this.turnCount,
|
||||
};
|
||||
|
||||
if (this.saveResults) {
|
||||
await this.saveToDisk(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private getLastAssistantMessage(): AgentMessage | undefined {
|
||||
const messages = this.agent.state.messages;
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const msg = messages[i];
|
||||
if (msg.role === "assistant" && "content" in msg) {
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private getTextLength(msg: AgentMessage): number {
|
||||
if ("content" in msg && msg.content) {
|
||||
const textContent = (msg.content as Array<{ type: string; text?: string }>).find((c) => c.type === "text");
|
||||
if (textContent?.text) {
|
||||
return textContent.text.length;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private extractReport(): void {
|
||||
const messages = this.agent.state.messages;
|
||||
|
||||
console.error(`\n[Extracting report from ${messages.length} messages...]`);
|
||||
|
||||
// Strategy 1: Look for assistant message AFTER synthesize_report tool result (correct flow)
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const msg = messages[i];
|
||||
|
||||
if (msg.role === "toolResult") {
|
||||
const content = msg.content;
|
||||
if (Array.isArray(content)) {
|
||||
const textContent = content.find((c: any) => c.type === "text");
|
||||
if (
|
||||
textContent &&
|
||||
textContent.type === "text" &&
|
||||
textContent.text.includes("Research synthesis requested for")
|
||||
) {
|
||||
console.error(`[Found synthesize_report at index ${i}]`);
|
||||
// Found synthesize_report result, look for assistant message after it
|
||||
for (let j = i + 1; j < messages.length; j++) {
|
||||
const nextMsg = messages[j];
|
||||
if (nextMsg.role === "assistant" && nextMsg.content) {
|
||||
const nextTextContent = nextMsg.content.find((c) => c.type === "text");
|
||||
if (nextTextContent && nextTextContent.type === "text" && nextTextContent.text.length > 200) {
|
||||
console.error(
|
||||
`[Extracted report from assistant message at index ${j}, length: ${nextTextContent.text.length}]`,
|
||||
);
|
||||
this.report = nextTextContent.text;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.error(`[No report found after synthesize_report, trying fallback strategies...]`);
|
||||
|
||||
// Strategy 2: Look for the longest assistant message in the last 5 messages (fallback)
|
||||
const lastMessages = messages.slice(-5);
|
||||
let longestText = "";
|
||||
for (const msg of lastMessages) {
|
||||
if (msg.role === "assistant" && msg.content) {
|
||||
const textContent = msg.content.find((c) => c.type === "text");
|
||||
if (textContent && textContent.type === "text" && textContent.text.length > longestText.length) {
|
||||
longestText = textContent.text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (longestText.length > 200) {
|
||||
console.error(`[Extracted longest report from last 5 messages, length: ${longestText.length}]`);
|
||||
this.report = longestText;
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(`[No substantial report found in last 5 messages, trying any long message...]`);
|
||||
|
||||
// Strategy 3: Look for any assistant message with substantial text
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const msg = messages[i];
|
||||
if (msg.role === "assistant" && msg.content) {
|
||||
const textContent = msg.content.find((c) => c.type === "text");
|
||||
if (textContent && textContent.type === "text" && textContent.text.length > 100) {
|
||||
console.error(
|
||||
`[Extracted fallback report from assistant message at index ${i}, length: ${textContent.text.length}]`,
|
||||
);
|
||||
this.report = textContent.text;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.error(`[No report found in messages, trying longest message from all...]`);
|
||||
|
||||
// Strategy 4: Find the longest assistant message in ALL messages
|
||||
let longestMsg = "";
|
||||
let longestIndex = -1;
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
const msg = messages[i];
|
||||
if (msg.role === "assistant" && msg.content) {
|
||||
const textContent = msg.content.find((c) => c.type === "text");
|
||||
if (textContent && textContent.type === "text" && textContent.text.length > longestMsg.length) {
|
||||
longestMsg = textContent.text;
|
||||
longestIndex = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (longestMsg.length > MIN_REPORT_LENGTH) {
|
||||
console.error(
|
||||
`[Extracted longest report from all messages at index ${longestIndex}, length: ${longestMsg.length}]`,
|
||||
);
|
||||
this.report = longestMsg;
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(`[No report found in messages]`);
|
||||
this.report = "";
|
||||
}
|
||||
|
||||
private generateFallbackReport(): string {
|
||||
const notes = this.notes.getAll();
|
||||
if (notes.length === 0) {
|
||||
return "Research completed but no notes were collected.";
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`# Research Report: ${this.topic}`,
|
||||
"",
|
||||
"## Executive Summary",
|
||||
"",
|
||||
`This research collected ${notes.length} findings on "${this.topic}".`,
|
||||
"",
|
||||
"## Key Findings",
|
||||
"",
|
||||
];
|
||||
|
||||
// Group notes by confidence
|
||||
const highConfidence = notes.filter((n) => n.confidence === "high");
|
||||
const mediumConfidence = notes.filter((n) => n.confidence === "medium");
|
||||
const lowConfidence = notes.filter((n) => n.confidence === "low");
|
||||
|
||||
if (highConfidence.length > 0) {
|
||||
lines.push("### High Confidence Findings");
|
||||
lines.push("");
|
||||
for (const note of highConfidence) {
|
||||
lines.push(`- **${note.topic}**: ${note.finding}`);
|
||||
lines.push(` - Source: ${note.source_url}`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
if (mediumConfidence.length > 0) {
|
||||
lines.push("### Medium Confidence Findings");
|
||||
lines.push("");
|
||||
for (const note of mediumConfidence) {
|
||||
lines.push(`- **${note.topic}**: ${note.finding}`);
|
||||
lines.push(` - Source: ${note.source_url}`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
if (lowConfidence.length > 0) {
|
||||
lines.push("### Low Confidence Findings");
|
||||
lines.push("");
|
||||
for (const note of lowConfidence) {
|
||||
lines.push(`- **${note.topic}**: ${note.finding}`);
|
||||
lines.push(` - Source: ${note.source_url}`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
lines.push("## Notes");
|
||||
lines.push("");
|
||||
lines.push(
|
||||
"*This report was auto-generated from collected notes as the agent reached the turn limit before synthesizing a full report.*",
|
||||
);
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
private async saveToDisk(result: ResearchResult): Promise<void> {
|
||||
try {
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
||||
const slug = result.topic
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 50);
|
||||
const dir = join(this.outputDir, `${timestamp}-${slug}`);
|
||||
|
||||
await mkdir(dir, { recursive: true });
|
||||
await writeFile(join(dir, "report.md"), result.report, "utf-8");
|
||||
await writeFile(join(dir, "report.json"), JSON.stringify(result, null, 2), "utf-8");
|
||||
await writeFile(join(dir, "notes.json"), JSON.stringify(result.notes, null, 2), "utf-8");
|
||||
|
||||
console.error(`\n[Results saved to ${dir}]`);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`\n[Warning: Failed to save results to disk: ${error instanceof Error ? error.message : String(error)}]`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
abort(): void {
|
||||
this.agent.abort();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env node
|
||||
import { loadEnvFile } from "./utils/env.ts";
|
||||
|
||||
// Load .env file before anything else
|
||||
loadEnvFile();
|
||||
|
||||
import { APP_NAME } from "./config.ts";
|
||||
import { main } from "./main.ts";
|
||||
|
||||
process.title = APP_NAME;
|
||||
process.emitWarning = (() => {}) as typeof process.emitWarning;
|
||||
|
||||
main(process.argv.slice(2));
|
||||
@@ -0,0 +1,18 @@
|
||||
export const VERSION = "0.78.0";
|
||||
export const APP_NAME = "pi-research";
|
||||
|
||||
export const DEFAULT_MAX_TURNS = 15;
|
||||
export const DEFAULT_MAX_RESULTS = 10;
|
||||
export const DEFAULT_MAX_CONTENT_LENGTH = 10000;
|
||||
|
||||
export const ENV_TAVILY_API_KEY = "TAVILY_API_KEY";
|
||||
export const ENV_OPENROUTER_API_KEY = "OPENROUTER_API_KEY";
|
||||
export const ENV_LLM_MODEL = "LLM_MODEL";
|
||||
|
||||
export const DEFAULT_MODEL_ID = "minimax/minimax-m3";
|
||||
export const DEFAULT_PROVIDER = "openrouter";
|
||||
|
||||
export const TAVILY_API_URL = "https://api.tavily.com/search";
|
||||
|
||||
export const DEFAULT_OUTPUT_DIR = "./research-output";
|
||||
export const MIN_REPORT_LENGTH = 500;
|
||||
@@ -0,0 +1,8 @@
|
||||
export { ResearchAgent } from "./agent.ts";
|
||||
export { DEFAULT_MODEL_ID, DEFAULT_PROVIDER, VERSION } from "./config.ts";
|
||||
export { createResearchMcpServer } from "./mcp-server.ts";
|
||||
export { loadResearchSkills } from "./skills/loader.ts";
|
||||
export type { ResearchSkill } from "./skills/types.ts";
|
||||
export { BASE_SYSTEM_PROMPT, buildSystemPrompt } from "./system-prompt.ts";
|
||||
export { createNoteStore, createResearchTools } from "./tools/index.ts";
|
||||
export type { NoteStore, ResearchAgentOptions, ResearchNote, ResearchResult } from "./types.ts";
|
||||
@@ -0,0 +1,141 @@
|
||||
import chalk from "chalk";
|
||||
import { ResearchAgent } from "./agent.ts";
|
||||
import { APP_NAME, VERSION } from "./config.ts";
|
||||
import { runInteractiveMode, runPrintMode } from "./modes/index.ts";
|
||||
import { loadResearchSkills } from "./skills/loader.ts";
|
||||
|
||||
interface ParsedArgs {
|
||||
help: boolean;
|
||||
version: boolean;
|
||||
print: boolean;
|
||||
maxTurns?: number;
|
||||
model?: string;
|
||||
topic?: string;
|
||||
save: boolean;
|
||||
outputDir?: string;
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): ParsedArgs {
|
||||
const parsed: ParsedArgs = {
|
||||
help: false,
|
||||
version: false,
|
||||
print: false,
|
||||
save: true,
|
||||
};
|
||||
|
||||
const positional: string[] = [];
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg === "--help" || arg === "-h") {
|
||||
parsed.help = true;
|
||||
} else if (arg === "--version" || arg === "-v") {
|
||||
parsed.version = true;
|
||||
} else if (arg === "--print" || arg === "-p") {
|
||||
parsed.print = true;
|
||||
} else if (arg === "--max-turns" || arg === "-t") {
|
||||
const value = args[++i];
|
||||
if (value) {
|
||||
parsed.maxTurns = Number.parseInt(value, 10);
|
||||
}
|
||||
} else if (arg === "--model" || arg === "-m") {
|
||||
parsed.model = args[++i];
|
||||
} else if (arg === "--no-save") {
|
||||
parsed.save = false;
|
||||
} else if (arg === "--output-dir" || arg === "-o") {
|
||||
parsed.outputDir = args[++i];
|
||||
} else if (!arg.startsWith("-")) {
|
||||
positional.push(arg);
|
||||
}
|
||||
}
|
||||
|
||||
if (positional.length > 0) {
|
||||
parsed.topic = positional.join(" ");
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function printHelp(): void {
|
||||
console.log(`
|
||||
${chalk.bold(APP_NAME)} - Autonomous Research Agent
|
||||
|
||||
${chalk.bold("Usage:")}
|
||||
${APP_NAME} [options] <topic>
|
||||
|
||||
${chalk.bold("Options:")}
|
||||
-h, --help Show this help message
|
||||
-v, --version Show version number
|
||||
-p, --print Use print mode (no interactive TUI)
|
||||
-t, --max-turns <n> Maximum research turns (default: 15)
|
||||
-m, --model <model> Model to use (default: minimax/minimax-m3)
|
||||
-o, --output-dir <p> Output directory for results (default: ./research-output)
|
||||
--no-save Do not save results to disk
|
||||
|
||||
${chalk.bold("Environment Variables:")}
|
||||
TAVILY_API_KEY Required - Tavily API key for web search
|
||||
OPENROUTER_API_KEY Required - OpenRouter API key for LLM
|
||||
LLM_MODEL Optional - Override default model
|
||||
|
||||
${chalk.bold("Examples:")}
|
||||
${APP_NAME} "quantum computing breakthroughs 2026"
|
||||
${APP_NAME} --print "AI safety research"
|
||||
${APP_NAME} --max-turns 15 "climate change solutions"
|
||||
${APP_NAME} -m openai/gpt-4o "renewable energy trends"
|
||||
${APP_NAME} --no-save "quick research topic"
|
||||
${APP_NAME} -o ./my-reports "saved to custom directory"
|
||||
|
||||
${chalk.bold("Output:")}
|
||||
Results are automatically saved to <output-dir>/<timestamp>-<topic>/
|
||||
- report.md - Final research report in markdown
|
||||
- report.json - Full results (report + notes + metadata)
|
||||
- notes.json - Collected research notes
|
||||
|
||||
${chalk.bold("Skills:")}
|
||||
Research skills are loaded from ~/.pi/skills/research/ directory.
|
||||
Create .md files with YAML frontmatter to customize research behavior.
|
||||
`);
|
||||
}
|
||||
|
||||
export async function main(args: string[]): Promise<void> {
|
||||
const parsed = parseArgs(args);
|
||||
|
||||
if (parsed.help) {
|
||||
printHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.version) {
|
||||
console.log(`${APP_NAME} ${VERSION}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parsed.topic) {
|
||||
console.error(chalk.red("Error: Research topic is required."));
|
||||
console.error(chalk.dim(`Run '${APP_NAME} --help' for usage information.`));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const skills = await loadResearchSkills();
|
||||
|
||||
let agent: ResearchAgent;
|
||||
try {
|
||||
agent = new ResearchAgent({
|
||||
maxTurns: parsed.maxTurns,
|
||||
skills,
|
||||
saveResults: parsed.save,
|
||||
outputDir: parsed.outputDir,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const mode = parsed.print || !process.stdin.isTTY ? "print" : "interactive";
|
||||
|
||||
const exitCode =
|
||||
mode === "interactive" ? await runInteractiveMode(agent, parsed.topic) : await runPrintMode(agent, parsed.topic);
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env node
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import { createResearchMcpServer } from "./mcp-server.ts";
|
||||
import { loadEnvFile } from "./utils/env.ts";
|
||||
|
||||
loadEnvFile();
|
||||
|
||||
async function main() {
|
||||
const server = createResearchMcpServer();
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error("Fatal error:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
import { ResearchAgent } from "./agent.ts";
|
||||
import { VERSION } from "./config.ts";
|
||||
|
||||
const researchSchema = {
|
||||
topic: z.string().describe("The research topic to investigate"),
|
||||
maxTurns: z
|
||||
.number()
|
||||
.optional()
|
||||
.default(15)
|
||||
.describe("Maximum number of research turns (default: 15). More turns = deeper research."),
|
||||
format: z
|
||||
.enum(["markdown", "json", "bullet"])
|
||||
.optional()
|
||||
.default("markdown")
|
||||
.describe("Output format for the report (default: markdown)"),
|
||||
};
|
||||
|
||||
const quickSearchSchema = {
|
||||
query: z.string().describe("Search query"),
|
||||
maxResults: z.number().optional().default(10).describe("Maximum number of results (default: 10)"),
|
||||
};
|
||||
|
||||
const readUrlSchema = {
|
||||
url: z.string().describe("URL to read"),
|
||||
maxLength: z.number().optional().default(10000).describe("Maximum characters to extract (default: 10000)"),
|
||||
};
|
||||
|
||||
export function createResearchMcpServer(): McpServer {
|
||||
const server = new McpServer({
|
||||
name: "pi-research-agent",
|
||||
version: VERSION,
|
||||
});
|
||||
|
||||
server.registerTool(
|
||||
"research",
|
||||
{
|
||||
description:
|
||||
"Perform deep autonomous research on a topic. Searches the web, reads sources, saves findings, and generates a comprehensive report with citations.",
|
||||
inputSchema: researchSchema as any,
|
||||
},
|
||||
async (params: any) => {
|
||||
const { topic, maxTurns = 15, format = "markdown" } = params;
|
||||
const agent = new ResearchAgent({
|
||||
maxTurns,
|
||||
saveResults: false,
|
||||
});
|
||||
|
||||
// Suppress console output during MCP execution
|
||||
const originalError = console.error;
|
||||
console.error = () => {};
|
||||
|
||||
try {
|
||||
const result = await agent.research(topic);
|
||||
|
||||
console.error = originalError;
|
||||
|
||||
const reportWithMeta = [
|
||||
`# Research Report: ${topic}`,
|
||||
"",
|
||||
`**Turns used:** ${result.turnsUsed}`,
|
||||
`**Notes collected:** ${result.notes.length}`,
|
||||
`**Format:** ${format}`,
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
result.report,
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
"## Raw Research Notes",
|
||||
"",
|
||||
...result.notes.flatMap((note) => [
|
||||
`### ${note.topic}`,
|
||||
`- **Confidence:** ${note.confidence}`,
|
||||
`- **Source:** ${note.source_url}`,
|
||||
`- **Finding:** ${note.finding}`,
|
||||
"",
|
||||
]),
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: reportWithMeta }],
|
||||
};
|
||||
} catch (error) {
|
||||
console.error = originalError;
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return {
|
||||
content: [{ type: "text" as const, text: `Research failed: ${message}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"quick_search",
|
||||
{
|
||||
description:
|
||||
"Quick web search on a topic. Returns search results without full research flow. Use for fast information lookup.",
|
||||
inputSchema: quickSearchSchema as any,
|
||||
},
|
||||
async (params: any) => {
|
||||
const { query, maxResults = 10 } = params;
|
||||
try {
|
||||
const { tavilySearch } = await import("./utils/tavily.ts");
|
||||
const { formatSearchResults } = await import("./utils/formatter.ts");
|
||||
|
||||
const apiKey = process.env.TAVILY_API_KEY;
|
||||
if (!apiKey) {
|
||||
return {
|
||||
content: [{ type: "text" as const, text: "Error: TAVILY_API_KEY environment variable is not set" }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
const results = await tavilySearch(query, {
|
||||
apiKey,
|
||||
maxResults,
|
||||
});
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: formatSearchResults(results.results) }],
|
||||
};
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return {
|
||||
content: [{ type: "text" as const, text: `Search failed: ${message}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"read_url",
|
||||
{
|
||||
description: "Fetch and extract content from a URL. Useful for reading specific articles or pages.",
|
||||
inputSchema: readUrlSchema as any,
|
||||
},
|
||||
async (params: any) => {
|
||||
const { url, maxLength = 10000 } = params;
|
||||
try {
|
||||
const { fetchAndExtract } = await import("./utils/fetcher.ts");
|
||||
const content = await fetchAndExtract(url, maxLength);
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: `Content from ${url}:\n\n${content}` }],
|
||||
};
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return {
|
||||
content: [{ type: "text" as const, text: `Failed to read URL: ${message}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return server;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { runInteractiveMode } from "./interactive.ts";
|
||||
export { runPrintMode } from "./print.ts";
|
||||
@@ -0,0 +1,87 @@
|
||||
import chalk from "chalk";
|
||||
import type { ResearchAgent } from "../agent.ts";
|
||||
|
||||
export async function runInteractiveMode(agent: ResearchAgent, topic: string): Promise<number> {
|
||||
console.log(chalk.bold.cyan("\n╔══════════════════════════════════════════════════════════╗"));
|
||||
console.log(chalk.bold.cyan("║ Pi Research Agent - Interactive ║"));
|
||||
console.log(chalk.bold.cyan("╚══════════════════════════════════════════════════════════╝"));
|
||||
console.log();
|
||||
|
||||
console.log(chalk.bold(`Topic: ${topic}\n`));
|
||||
|
||||
let currentPhase = "";
|
||||
|
||||
agent.subscribe((event) => {
|
||||
switch (event.type) {
|
||||
case "turn_start": {
|
||||
const turnNum = agent.getTurnCount() + 1;
|
||||
console.log(chalk.bold.yellow(`\n┌─── Turn ${turnNum} ───────────────────────────────────`));
|
||||
break;
|
||||
}
|
||||
case "tool_execution_start": {
|
||||
const toolName = event.toolName;
|
||||
const args = event.args as Record<string, unknown>;
|
||||
if (toolName === "web_search") {
|
||||
currentPhase = "search";
|
||||
console.log(chalk.cyan(` 🔍 Searching: "${args.query}"`));
|
||||
} else if (toolName === "read_url") {
|
||||
currentPhase = "read";
|
||||
console.log(chalk.blue(` 📖 Reading: ${args.url}`));
|
||||
} else if (toolName === "save_note") {
|
||||
currentPhase = "note";
|
||||
console.log(chalk.green(` 💾 Saving note: "${args.topic}" (${args.confidence} confidence)`));
|
||||
} else if (toolName === "synthesize_report") {
|
||||
currentPhase = "synthesize";
|
||||
console.log(chalk.magenta(" 📊 Synthesizing final report..."));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "tool_execution_end": {
|
||||
if (event.isError) {
|
||||
console.log(chalk.red(` ⚠️ Error: ${event.toolName}`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "turn_end": {
|
||||
console.log(chalk.dim(` └── Notes: ${agent.getNoteCount()} | Turn ${agent.getTurnCount()} complete`));
|
||||
break;
|
||||
}
|
||||
case "message_start": {
|
||||
if (currentPhase !== "synthesize") {
|
||||
console.log(chalk.dim(" 🤔 Thinking..."));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "message_update": {
|
||||
if (event.assistantMessageEvent.type === "text_delta") {
|
||||
process.stdout.write(chalk.white(event.assistantMessageEvent.delta));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "message_end": {
|
||||
process.stdout.write("\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await agent.research(topic);
|
||||
|
||||
console.log(chalk.bold.green("\n\n╔══════════════════════════════════════════════════════════╗"));
|
||||
console.log(chalk.bold.green("║ Research Complete! ║"));
|
||||
console.log(chalk.bold.green("╚══════════════════════════════════════════════════════════╝"));
|
||||
console.log();
|
||||
|
||||
console.log(chalk.dim(` Turns used: ${result.turnsUsed}`));
|
||||
console.log(chalk.dim(` Notes collected: ${result.notes.length}`));
|
||||
console.log(chalk.dim(`\n${"─".repeat(60)}\n`));
|
||||
|
||||
console.log(result.report);
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`\n\nResearch failed: ${error instanceof Error ? error.message : String(error)}`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import chalk from "chalk";
|
||||
import type { ResearchAgent } from "../agent.ts";
|
||||
|
||||
export async function runPrintMode(agent: ResearchAgent, topic: string): Promise<number> {
|
||||
console.log(chalk.bold(`\nResearching: ${topic}\n`));
|
||||
console.log(chalk.dim("─".repeat(60)));
|
||||
|
||||
agent.subscribe((event) => {
|
||||
switch (event.type) {
|
||||
case "tool_execution_start": {
|
||||
const toolName = event.toolName;
|
||||
const args = event.args as Record<string, unknown>;
|
||||
if (toolName === "web_search") {
|
||||
console.error(chalk.cyan(`\n[Searching: ${args.query}]`));
|
||||
} else if (toolName === "read_url") {
|
||||
console.error(chalk.blue(`\n[Reading: ${args.url}]`));
|
||||
} else if (toolName === "save_note") {
|
||||
console.error(chalk.green(`\n[Saving note: ${args.topic}]`));
|
||||
} else if (toolName === "synthesize_report") {
|
||||
console.error(chalk.magenta("\n[Synthesizing report...]"));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "turn_end": {
|
||||
console.error(
|
||||
chalk.dim(`\n[Turn ${agent.getTurnCount()} complete, ${agent.getNoteCount()} notes collected]`),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "message_update": {
|
||||
if (event.assistantMessageEvent.type === "text_delta") {
|
||||
process.stdout.write(event.assistantMessageEvent.delta);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await agent.research(topic);
|
||||
|
||||
console.log("\n");
|
||||
console.log(chalk.dim("─".repeat(60)));
|
||||
console.log(chalk.bold.green("\nResearch Complete!"));
|
||||
console.log(chalk.dim(`Turns used: ${result.turnsUsed}`));
|
||||
console.log(chalk.dim(`Notes collected: ${result.notes.length}`));
|
||||
console.log(chalk.dim("─".repeat(60)));
|
||||
console.log(`\n${result.report}`);
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`\nResearch failed: ${error instanceof Error ? error.message : String(error)}`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { parse as parseYaml } from "yaml";
|
||||
import type { ResearchSkill } from "./types.ts";
|
||||
|
||||
export type { ResearchSkill };
|
||||
|
||||
export async function loadResearchSkills(skillsDir?: string): Promise<ResearchSkill[]> {
|
||||
const dir = skillsDir ?? join(homedir(), ".pi", "skills", "research");
|
||||
|
||||
if (!existsSync(dir)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let files: string[];
|
||||
try {
|
||||
files = await readdir(dir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
const skills: ResearchSkill[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
if (!file.endsWith(".md")) continue;
|
||||
|
||||
try {
|
||||
const content = await readFile(join(dir, file), "utf-8");
|
||||
const parsed = parseSkillFrontmatter(content);
|
||||
if (parsed) {
|
||||
skills.push(parsed);
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return skills;
|
||||
}
|
||||
|
||||
function parseSkillFrontmatter(content: string): ResearchSkill | null {
|
||||
const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
|
||||
if (!match) return null;
|
||||
|
||||
try {
|
||||
const frontmatter = parseYaml(match[1]) as Record<string, unknown>;
|
||||
return {
|
||||
name: (frontmatter.name as string) ?? "unnamed",
|
||||
description: (frontmatter.description as string) ?? "",
|
||||
content: match[2].trim(),
|
||||
maxTurns: frontmatter.max_turns as number | undefined,
|
||||
tools: frontmatter.tools as string[] | undefined,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export interface ResearchSkill {
|
||||
name: string;
|
||||
description: string;
|
||||
content: string;
|
||||
maxTurns?: number;
|
||||
tools?: string[];
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
export const BASE_SYSTEM_PROMPT = `You are an autonomous research agent. Your task is to thoroughly research topics by searching the web, reading sources, and synthesizing findings into comprehensive reports.
|
||||
|
||||
## Research Methodology
|
||||
|
||||
1. **Break down the topic** into key sub-questions that need answering
|
||||
2. **Search systematically** using web_search for each sub-question
|
||||
3. **Read relevant sources** using read_url to get detailed information from promising URLs
|
||||
4. **Save important findings** using save_note with appropriate confidence levels
|
||||
5. **Identify gaps** in your knowledge and search for additional information
|
||||
6. **Cross-reference** findings from multiple sources to verify accuracy
|
||||
7. **Synthesize** when you have enough information using synthesize_report
|
||||
|
||||
## Available Tools
|
||||
|
||||
- **web_search**: Search the web using Tavily. Use specific, targeted queries.
|
||||
- **read_url**: Fetch and read content from a URL. Use for sources found in search results.
|
||||
- **save_note**: Save a research finding with topic, content, source URL, and confidence level.
|
||||
- **synthesize_report**: Prepare all collected notes for report generation. Call this tool when you have gathered sufficient information. After calling this tool, you MUST generate the final comprehensive report in your next response.
|
||||
|
||||
## Guidelines
|
||||
|
||||
- Start with 2-3 broad searches to understand the topic landscape
|
||||
- Then narrow down with specific queries for each sub-question
|
||||
- Read at least 3-5 primary sources for comprehensive coverage
|
||||
- **CRITICAL**: You MUST call save_note for every significant finding from each source you read
|
||||
- Save at least 5-10 notes before calling synthesize_report
|
||||
- Use confidence levels appropriately:
|
||||
- **high**: well-established facts from authoritative sources (academic papers, official reports)
|
||||
- **medium**: recent information or facts from reputable but less authoritative sources
|
||||
- **low**: speculative claims, single-source information, or unverified data
|
||||
- **IMPORTANT**: Do NOT call synthesize_report until you have saved at least 5 notes with save_note
|
||||
- Call synthesize_report only after you have gathered sufficient information and saved multiple notes (typically after 5-10 searches and reading key sources)
|
||||
|
||||
## Report Generation Process
|
||||
|
||||
**CRITICAL**: Follow this exact sequence:
|
||||
|
||||
1. **Research phase**: Search, read, and save notes
|
||||
2. **Call synthesize_report**: When ready, call the tool
|
||||
3. **Generate report IMMEDIATELY**: In your NEXT response, generate the full report
|
||||
- Do NOT call any more tools
|
||||
- Do NOT search or read more sources
|
||||
- Generate the complete markdown report (2000+ words)
|
||||
- Include executive summary, findings, citations, confidence, gaps
|
||||
|
||||
**WRONG**: Calling synthesize_report, then searching more
|
||||
**RIGHT**: Calling synthesize_report, then generating the report immediately
|
||||
|
||||
The synthesize_report tool will return all your saved notes in a structured format. Use this information to write your final report.
|
||||
|
||||
## Output Format
|
||||
|
||||
Your final report should include:
|
||||
- Executive summary (2-3 paragraphs)
|
||||
- Key findings organized by theme
|
||||
- Source citations with URLs
|
||||
- Confidence assessment of the overall research
|
||||
- Identified gaps or areas for further research
|
||||
|
||||
Be thorough but efficient. Do not repeat searches for the same information.`;
|
||||
|
||||
export function buildSystemPrompt(skills?: Array<{ name: string; content: string }>): string {
|
||||
let prompt = BASE_SYSTEM_PROMPT;
|
||||
|
||||
if (skills && skills.length > 0) {
|
||||
prompt += "\n\n## Additional Research Skills\n\n";
|
||||
for (const skill of skills) {
|
||||
prompt += `### ${skill.name}\n${skill.content}\n\n`;
|
||||
}
|
||||
}
|
||||
|
||||
return prompt;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
||||
import type { NoteStore } from "../types.ts";
|
||||
import { createReadUrlTool } from "./read-url.ts";
|
||||
import { createSaveNoteTool } from "./save-note.ts";
|
||||
import { createSynthesizeTool } from "./synthesize.ts";
|
||||
import { createWebSearchTool } from "./web-search.ts";
|
||||
|
||||
export type { NoteStore, ResearchNote } from "../types.ts";
|
||||
export { createNoteStore } from "./save-note.ts";
|
||||
|
||||
export function createResearchTools(notes: NoteStore, tavilyApiKey: string): AgentTool[] {
|
||||
return [
|
||||
createWebSearchTool(tavilyApiKey),
|
||||
createReadUrlTool(),
|
||||
createSaveNoteTool(notes),
|
||||
createSynthesizeTool(notes),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
||||
import { type Static, Type } from "typebox";
|
||||
import { DEFAULT_MAX_CONTENT_LENGTH } from "../config.ts";
|
||||
import { fetchAndExtract } from "../utils/fetcher.ts";
|
||||
|
||||
const readUrlSchema = Type.Object({
|
||||
url: Type.String({ description: "URL of the web page to read" }),
|
||||
max_length: Type.Optional(
|
||||
Type.Number({
|
||||
description: `Maximum characters to extract (default: ${DEFAULT_MAX_CONTENT_LENGTH})`,
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export type ReadUrlInput = Static<typeof readUrlSchema>;
|
||||
|
||||
interface ReadUrlDetails {
|
||||
url: string;
|
||||
length: number;
|
||||
}
|
||||
|
||||
export function createReadUrlTool(): AgentTool<typeof readUrlSchema, ReadUrlDetails> {
|
||||
return {
|
||||
name: "read_url",
|
||||
label: "Read URL",
|
||||
description: "Fetch and read the content of a web page. Extracts main text content from HTML pages.",
|
||||
parameters: readUrlSchema,
|
||||
execute: async (_toolCallId, params: ReadUrlInput) => {
|
||||
const maxLength = params.max_length ?? DEFAULT_MAX_CONTENT_LENGTH;
|
||||
|
||||
// Try with default User-Agent, then retry with alternative if it fails
|
||||
let content: string;
|
||||
let lastError: Error | null = null;
|
||||
|
||||
try {
|
||||
content = await fetchAndExtract(params.url, maxLength);
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error(String(error));
|
||||
|
||||
// Retry with alternative User-Agent
|
||||
try {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second
|
||||
content = await fetchAndExtract(params.url, maxLength, true); // true = use alternative UA
|
||||
} catch (_retryError) {
|
||||
throw new Error(`Failed to fetch ${params.url} after 2 attempts: ${lastError.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: `Content from ${params.url}:\n\n${content}`,
|
||||
},
|
||||
],
|
||||
details: { url: params.url, length: content.length },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
||||
import { type Static, Type } from "typebox";
|
||||
import type { NoteStore, ResearchNote } from "../types.ts";
|
||||
|
||||
const saveNoteSchema = Type.Object({
|
||||
topic: Type.String({ description: "Topic or sub-question this note addresses" }),
|
||||
finding: Type.String({ description: "The key finding or information extracted" }),
|
||||
source_url: Type.String({ description: "URL of the source where this finding came from" }),
|
||||
confidence: Type.Union([Type.Literal("high"), Type.Literal("medium"), Type.Literal("low")], {
|
||||
description:
|
||||
"Confidence level: high for well-established facts, medium for recent info, low for speculative claims",
|
||||
}),
|
||||
});
|
||||
|
||||
export type SaveNoteInput = Static<typeof saveNoteSchema>;
|
||||
|
||||
export function createNoteStore(): NoteStore {
|
||||
const notes: ResearchNote[] = [];
|
||||
return {
|
||||
add(note: ResearchNote) {
|
||||
notes.push(note);
|
||||
},
|
||||
getAll() {
|
||||
return notes.slice();
|
||||
},
|
||||
clear() {
|
||||
notes.length = 0;
|
||||
},
|
||||
count() {
|
||||
return notes.length;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createSaveNoteTool(notes: NoteStore): AgentTool<typeof saveNoteSchema, ResearchNote> {
|
||||
return {
|
||||
name: "save_note",
|
||||
label: "Save Note",
|
||||
description: "Save a research note or finding for later synthesis into the final report",
|
||||
parameters: saveNoteSchema,
|
||||
execute: async (_toolCallId, params: SaveNoteInput) => {
|
||||
const note: ResearchNote = {
|
||||
topic: params.topic,
|
||||
finding: params.finding,
|
||||
source_url: params.source_url,
|
||||
confidence: params.confidence,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
notes.add(note);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: `Note saved successfully. Topic: "${params.topic}". Total notes collected: ${notes.count()}`,
|
||||
},
|
||||
],
|
||||
details: note,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
||||
import { type Static, Type } from "typebox";
|
||||
import type { NoteStore } from "../types.ts";
|
||||
import { formatNotes } from "../utils/formatter.ts";
|
||||
|
||||
const synthesizeSchema = Type.Object({
|
||||
topic: Type.String({ description: "The main research topic to synthesize" }),
|
||||
format: Type.Optional(
|
||||
Type.Union([Type.Literal("markdown"), Type.Literal("json"), Type.Literal("bullet")], {
|
||||
description: "Output format for the report (default: markdown)",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export type SynthesizeInput = Static<typeof synthesizeSchema>;
|
||||
|
||||
interface SynthesizeDetails {
|
||||
notes_count: number;
|
||||
topic: string;
|
||||
format: string;
|
||||
synthesisRequested: boolean;
|
||||
}
|
||||
|
||||
export function createSynthesizeTool(notes: NoteStore): AgentTool<typeof synthesizeSchema, SynthesizeDetails> {
|
||||
return {
|
||||
name: "synthesize_report",
|
||||
label: "Synthesize Report",
|
||||
description:
|
||||
"Synthesize all collected research notes into a structured report. Call this when you have gathered sufficient information to produce the final research report.",
|
||||
parameters: synthesizeSchema,
|
||||
execute: async (_toolCallId, params: SynthesizeInput) => {
|
||||
const allNotes = notes.getAll();
|
||||
const format = params.format ?? "markdown";
|
||||
|
||||
// Warn if too few notes were collected
|
||||
if (allNotes.length === 0) {
|
||||
const warning = [
|
||||
`WARNING: No research notes were collected for topic "${params.topic}".`,
|
||||
"",
|
||||
"You must use the save_note tool to save findings from your research before calling synthesize_report.",
|
||||
"Please go back and:",
|
||||
"1. Read sources using read_url",
|
||||
"2. Save key findings using save_note with topic, finding, source_url, and confidence",
|
||||
"3. Call synthesize_report again after saving at least 5 notes",
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: warning }],
|
||||
details: {
|
||||
notes_count: 0,
|
||||
topic: params.topic,
|
||||
format,
|
||||
synthesisRequested: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (allNotes.length < 3) {
|
||||
const warning = [
|
||||
`WARNING: Only ${allNotes.length} note(s) collected for topic "${params.topic}". This is insufficient for a comprehensive report.`,
|
||||
"",
|
||||
"Please continue researching and save more notes using save_note before calling synthesize_report again.",
|
||||
"Aim for at least 5-10 notes covering different aspects of the topic.",
|
||||
"",
|
||||
"=== COLLECTED RESEARCH NOTES ===",
|
||||
"",
|
||||
formatNotes(allNotes),
|
||||
"",
|
||||
"=== END OF NOTES ===",
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: warning }],
|
||||
details: {
|
||||
notes_count: allNotes.length,
|
||||
topic: params.topic,
|
||||
format,
|
||||
synthesisRequested: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const summary = [
|
||||
`Research synthesis requested for: "${params.topic}"`,
|
||||
`Format: ${format}`,
|
||||
`Notes collected: ${allNotes.length}`,
|
||||
"",
|
||||
"=== COLLECTED RESEARCH NOTES ===",
|
||||
"",
|
||||
formatNotes(allNotes),
|
||||
"",
|
||||
"=== END OF NOTES ===",
|
||||
"",
|
||||
"IMPORTANT: You MUST now generate the complete research report in your NEXT response.",
|
||||
"Do NOT call any more tools. Do NOT search or read more sources.",
|
||||
"Generate the full comprehensive report with:",
|
||||
"- Executive summary (2-3 paragraphs)",
|
||||
"- Key findings organized by theme",
|
||||
"- Source citations with URLs",
|
||||
"- Confidence assessment",
|
||||
"- Identified gaps for further research",
|
||||
"",
|
||||
"The report should be at least 2000 words and include all details from the notes above.",
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: summary }],
|
||||
details: {
|
||||
notes_count: allNotes.length,
|
||||
topic: params.topic,
|
||||
format,
|
||||
synthesisRequested: true,
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
||||
import { type Static, Type } from "typebox";
|
||||
import { DEFAULT_MAX_RESULTS } from "../config.ts";
|
||||
import type { TavilySearchResponse } from "../types.ts";
|
||||
import { formatSearchResults } from "../utils/formatter.ts";
|
||||
import { tavilySearch } from "../utils/tavily.ts";
|
||||
|
||||
const webSearchSchema = Type.Object({
|
||||
query: Type.String({ description: "Search query to find information on the web" }),
|
||||
max_results: Type.Optional(
|
||||
Type.Number({
|
||||
description: `Maximum number of results to return (default: ${DEFAULT_MAX_RESULTS})`,
|
||||
}),
|
||||
),
|
||||
search_depth: Type.Optional(
|
||||
Type.Union([Type.Literal("basic"), Type.Literal("advanced")], {
|
||||
description: "Search depth: basic for quick overview, advanced for comprehensive results",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export type WebSearchInput = Static<typeof webSearchSchema>;
|
||||
|
||||
export function createWebSearchTool(apiKey: string): AgentTool<typeof webSearchSchema, TavilySearchResponse> {
|
||||
return {
|
||||
name: "web_search",
|
||||
label: "Web Search",
|
||||
description:
|
||||
"Search the web for information on a given query using Tavily. Returns titles, URLs, and content snippets.",
|
||||
parameters: webSearchSchema,
|
||||
execute: async (_toolCallId, params: WebSearchInput) => {
|
||||
const results = await tavilySearch(params.query, {
|
||||
apiKey,
|
||||
maxResults: params.max_results ?? DEFAULT_MAX_RESULTS,
|
||||
searchDepth: params.search_depth ?? "basic",
|
||||
});
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: formatSearchResults(results.results) }],
|
||||
details: results,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
export interface ResearchNote {
|
||||
topic: string;
|
||||
finding: string;
|
||||
source_url: string;
|
||||
confidence: "high" | "medium" | "low";
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface NoteStore {
|
||||
add(note: ResearchNote): void;
|
||||
getAll(): ResearchNote[];
|
||||
clear(): void;
|
||||
count(): number;
|
||||
}
|
||||
|
||||
export interface SearchResult {
|
||||
title: string;
|
||||
url: string;
|
||||
content: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export interface TavilySearchResponse {
|
||||
query: string;
|
||||
results: SearchResult[];
|
||||
answer?: string;
|
||||
}
|
||||
|
||||
export interface ResearchResult {
|
||||
topic: string;
|
||||
notes: ResearchNote[];
|
||||
report: string;
|
||||
turnsUsed: number;
|
||||
}
|
||||
|
||||
export interface ResearchAgentOptions {
|
||||
model?: import("@earendil-works/pi-ai").Model<any>;
|
||||
thinkingLevel?: import("@earendil-works/pi-agent-core").ThinkingLevel;
|
||||
maxTurns?: number;
|
||||
tavilyApiKey?: string;
|
||||
llmApiKey?: string;
|
||||
skills?: import("./skills/types.ts").ResearchSkill[];
|
||||
outputDir?: string;
|
||||
saveResults?: boolean;
|
||||
}
|
||||
@@ -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