xonecas.io
56101
Df

dotfiles / commit 12096e5

chore: new models; new configs

xonecas2026-09-08 12096e55cbb8f99256b507ecda9ea8f9d6cc0c56 parent 901014f

10 files changed

agents/AGENTS.md+4−3
@@ -1,9 +1,10 @@
11 # Rules for AGENTS
22
3-- Always return exactly what was asked. Do not add scope, backwards compatibility or extras without the user explicitly asking.
3+- Always return exactly what was asked.
4+- Do not add scope, backwards compatibility or extras without the user explicitly asking.
45 - Do not add tests unless explicitly told to.
5-- Use `gh` for Github (it's already authenticated as me).
6-- Use `uvx hf` for HuggingFace (also already authenticated as me).
6+- Use `gh` for Github.
7+- Use `uvx hf` for HuggingFace.
78 - Use `curl` and the environment's `EXA_API_KEY` to search and read web contents.
89
910 ## Golden rule for coding
hax/bin/hax-adversary+0−20
@@ -1,20 +0,0 @@
1-#!/usr/bin/env bash
2-# hax-adversary — run the adversarial agent as an isolated hax -p subprocess.
3-#
4-# Usage:
5-# hax-adversary <brief...>
6-# echo "<brief>" | hax-adversary
7-# hax-adversary < brief.txt
8-#
9-set -euo pipefail
10-
11-if [ "$#" -gt 0 ]; then
12- exec hax -p --preset=adversary --no-session "$@"
13-fi
14-
15-if [ ! -t 0 ]; then
16- exec hax -p --preset=adversary --no-session
17-fi
18-
19-echo "usage: hax-adversary <brief> (or pipe the brief via stdin)" >&2
20-exit 1
hax/bin/hax-worker+0−20
@@ -1,20 +0,0 @@
1-#!/usr/bin/env bash
2-# hax-worker — run the worker agent as an isolated hax -p subprocess.
3-#
4-# Usage:
5-# hax-worker <brief...>
6-# echo "<brief>" | hax-worker
7-# hax-worker < brief.txt
8-#
9-set -euo pipefail
10-
11-if [ "$#" -gt 0 ]; then
12- exec hax -p --preset=implementer --no-session "$@"
13-fi
14-
15-if [ ! -t 0 ]; then
16- exec hax -p --preset=implementer --no-session
17-fi
18-
19-echo "usage: hax-worker <brief> (or pipe the brief via stdin)" >&2
20-exit 1
hax/skills/adversary/SKILL.md+0−17
@@ -1,17 +0,0 @@
1-# Adversary review
2-
3-Create a summary of the conversation with the user, then call the adversary with that summary as the brief.
4-
5-Run it with:
6-
7-```sh
8-hax-adversary "$BRIEF"
9-```
10-
11-or, for a long brief, pipe it:
12-
13-```sh
14-cat <<'EOF' | hax-adversary
15-<brief>
16-EOF
17-```
hax/skills/loop/SKILL.md+0−13
@@ -1,13 +0,0 @@
1----
2-description: Use when the user explicitly asks to run the worker/adversary loop.
3----
4-
5-# Worker / adversary loop
6-
7-Coordinate the `worker` and `adversary` skills to work through the user's request from opposing perspectives.
8-
9-Use the `worker` skill to produce or update the solution. Then use the `adversary` skill to challenge its direction, assumptions, and result from an independent point of view. Do not frame the adversary as a code reviewer or limit it to finding defects.
10-
11-Feed useful challenges, alternatives, and missed considerations back through the `worker` skill while preserving the user's original intent and scope. Alternate between the two skills until another pass produces no meaningful change, or progress requires a decision from the user.
12-
13-Do not introduce scope or change the solution away from the user request during the loop.
hax/skills/worker/SKILL.md+0−17
@@ -1,17 +0,0 @@
1-# Implementer
2-
3-Create a summary of the conversation with the user, then call the worker with that summary as the brief.
4-
5-Run it with:
6-
7-```sh
8-hax-worker "$BRIEF"
9-```
10-
11-or, for a long brief, pipe it:
12-
13-```sh
14-cat <<'EOF' | hax-worker
15-<brief>
16-EOF
17-```
pi/extensions/adversary/adversary.md+0−33
@@ -1,33 +0,0 @@
1----
2-model: opencode-go/glm-5.3-flash
3-thinking: high
4----
5-
6-# Adversarial Reviewer
7-
8-Review the requested change with a skeptical, evidence-driven mindset.
9-
10-Your job is to identify issues that would matter to the author before the change ships. Do not summarize or praise the implementation.
11-
12-Ensure that the change contains neither:
13-
14-- Poor architectural decisions.
15-- Inconsistencies with repository practices and guidelines.
16-
17-You are strictly read-only:
18-
19-- Do not edit files.
20-- Use the read/search tools and `bash` to inspect the repository, run tests, and gather evidence.
21-
22-## Standards
23-
24-- Report only concrete, actionable findings. Do not invent hypothetical concerns without a plausible failure path.
25-- Treat the stated requirements and established repository behavior as the source of truth.
26-- Do not downgrade a real issue because it existed before the change; identify it when the change introduces or worsens it.
27-- Focus on correctness and avoid nit-picking.
28-- Do not propose or apply code changes.
29-- Do not make up a severity scale or any scale of importance at all, simply state your finding and reference the exact code locations of the issue.
30-
31-## Output
32-
33-A short and concise report of the review findings or a clear statement that nothing was found.
pi/extensions/adversary/index.ts+0−269
@@ -1,269 +0,0 @@
1-import { readFile } from "node:fs/promises";
2-import path from "node:path";
3-import { fileURLToPath } from "node:url";
4-import type { AssistantMessage, Usage } from "@earendil-works/pi-ai";
5-import {
6- type ExtensionAPI,
7- getPackageDir,
8- parseFrontmatter,
9- RpcClient,
10-} from "@earendil-works/pi-coding-agent";
11-import { Type } from "typebox";
12-
13-const TIMEOUT_MS = 30 * 60 * 1_000;
14-const THINKING_LEVELS = [
15- "off",
16- "minimal",
17- "low",
18- "medium",
19- "high",
20- "xhigh",
21- "max",
22-] as const;
23-
24-type ThinkingLevel = (typeof THINKING_LEVELS)[number];
25-type ProgressUpdate = (text: string, details: Record<string, unknown>) => void;
26-
27-interface AdversaryConfig {
28- model: string;
29- thinking: ThinkingLevel;
30- systemPrompt: string;
31-}
32-
33-const extensionPath = fileURLToPath(import.meta.url);
34-const promptPath = path.join(path.dirname(extensionPath), "adversary.md");
35-
36-const AdversaryParams = Type.Object({
37- task: Type.String({
38- description:
39- "Review brief containing the intended behavior, scope, constraints, and relevant context from the main conversation",
40- }),
41-});
42-
43-async function loadAdversaryConfig(): Promise<AdversaryConfig> {
44- const content = await readFile(promptPath, "utf8");
45- const { frontmatter, body } =
46- parseFrontmatter<Record<string, unknown>>(content);
47- const model =
48- typeof frontmatter.model === "string" ? frontmatter.model.trim() : "";
49- const thinking = frontmatter.thinking;
50-
51- if (!model) {
52- throw new Error(
53- `${promptPath} must declare a non-empty "model" in its frontmatter`,
54- );
55- }
56- if (
57- typeof thinking !== "string" ||
58- !THINKING_LEVELS.includes(thinking as ThinkingLevel)
59- ) {
60- throw new Error(
61- `${promptPath} must declare "thinking" as one of: ${THINKING_LEVELS.join(", ")}`,
62- );
63- }
64- if (!body.trim()) {
65- throw new Error(
66- `${promptPath} must contain reviewer instructions after its frontmatter`,
67- );
68- }
69-
70- return {
71- model,
72- thinking: thinking as ThinkingLevel,
73- systemPrompt: body.trim(),
74- };
75-}
76-
77-function compactAction(value: unknown, maxLength = 120): string {
78- const text =
79- typeof value === "string"
80- ? value.replace(/\s+/g, " ").trim()
81- : JSON.stringify(value);
82- if (!text) return "";
83- return text.length > maxLength ? `${text.slice(0, maxLength - 1)}…` : text;
84-}
85-
86-function describeToolAction(toolName: string, args: unknown): string {
87- if (args && typeof args === "object") {
88- const input = args as Record<string, unknown>;
89- if (toolName === "bash" && typeof input.command === "string") {
90- return `${toolName}: ${compactAction(input.command)}`;
91- }
92- if (toolName === "read" && typeof input.path === "string") {
93- return `${toolName}: ${compactAction(input.path)}`;
94- }
95- }
96- const detail = compactAction(args);
97- return detail && detail !== "{}" ? `${toolName}: ${detail}` : toolName;
98-}
99-
100-function emptyUsage(): Usage {
101- return {
102- input: 0,
103- output: 0,
104- cacheRead: 0,
105- cacheWrite: 0,
106- totalTokens: 0,
107- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
108- };
109-}
110-
111-function addUsage(total: Usage, next: Usage): void {
112- total.input += next.input;
113- total.output += next.output;
114- total.cacheRead += next.cacheRead;
115- total.cacheWrite += next.cacheWrite;
116- total.totalTokens += next.totalTokens;
117- total.cost.input += next.cost.input;
118- total.cost.output += next.cost.output;
119- total.cost.cacheRead += next.cost.cacheRead;
120- total.cost.cacheWrite += next.cost.cacheWrite;
121- total.cost.total += next.cost.total;
122- if (next.cacheWrite1h !== undefined) {
123- total.cacheWrite1h = (total.cacheWrite1h ?? 0) + next.cacheWrite1h;
124- }
125- if (next.reasoning !== undefined) {
126- total.reasoning = (total.reasoning ?? 0) + next.reasoning;
127- }
128-}
129-
130-function finalText(messages: AssistantMessage[]): string {
131- for (let index = messages.length - 1; index >= 0; index--) {
132- const text = messages[index]?.content
133- .filter(
134- (part): part is { type: "text"; text: string } => part.type === "text",
135- )
136- .map((part) => part.text)
137- .join("\n")
138- .trim();
139- if (text) return text;
140- }
141- return "";
142-}
143-
144-async function runAdversary(
145- task: string,
146- cwd: string,
147- signal?: AbortSignal,
148- onProgress?: ProgressUpdate,
149-) {
150- const config = await loadAdversaryConfig();
151- const client = new RpcClient({
152- cliPath: path.join(getPackageDir(), "dist", "cli.js"),
153- cwd,
154- model: config.model,
155- args: [
156- "--no-session",
157- "--no-skills",
158- "--no-prompt-templates",
159- "--no-extensions",
160- "--tools",
161- "read,grep,find,ls,bash",
162- "--thinking",
163- config.thinking,
164- "--append-system-prompt",
165- config.systemPrompt,
166- ],
167- });
168- const abort = () => void client.abort().catch(() => undefined);
169- let unsubscribe: (() => void) | undefined;
170-
171- try {
172- if (signal?.aborted) throw new Error("Adversarial review aborted");
173- onProgress?.("Adversary is starting…", {
174- model: config.model,
175- thinking: config.thinking,
176- status: "starting",
177- });
178- await client.start();
179- signal?.addEventListener("abort", abort, { once: true });
180- unsubscribe = client.onEvent((event) => {
181- if (event.type === "tool_execution_start") {
182- const action = describeToolAction(event.toolName, event.args);
183- onProgress?.(action, {
184- model: config.model,
185- thinking: config.thinking,
186- status: "running",
187- action,
188- });
189- } else if (
190- event.type === "message_update" &&
191- event.assistantMessageEvent.type === "text_start"
192- ) {
193- onProgress?.("Adversary is working...", {
194- model: config.model,
195- thinking: config.thinking,
196- status: "writing",
197- });
198- }
199- });
200- const events = await client.promptAndWait(
201- task,
202- undefined,
203- TIMEOUT_MS,
204- );
205-
206- const messages: AssistantMessage[] = [];
207- const usage = emptyUsage();
208- for (const event of events) {
209- if (event.type !== "message_end" || event.message.role !== "assistant")
210- continue;
211- messages.push(event.message);
212- addUsage(usage, event.message.usage);
213- }
214-
215- const last = messages[messages.length - 1];
216- if (!last) throw new Error("Adversary returned no response");
217- if (last.stopReason === "error" || last.stopReason === "aborted") {
218- throw new Error(
219- last.errorMessage || `Adversary stopped: ${last.stopReason}`,
220- );
221- }
222-
223- return {
224- text: finalText(messages) || "No findings.",
225- usage,
226- turns: messages.length,
227- model: config.model,
228- thinking: config.thinking,
229- };
230- } finally {
231- unsubscribe?.();
232- signal?.removeEventListener("abort", abort);
233- await client.stop();
234- }
235-}
236-
237-export default function adversaryExtension(pi: ExtensionAPI): void {
238- pi.registerTool({
239- name: "adversary_review",
240- label: "Adversary Review",
241- description:
242- "Delegate a focused, read-only adversarial review.",
243- promptSnippet:
244- "Run a read-only adversarial review in an isolated reviewer context",
245- promptGuidelines: [
246- "Use adversary_review only when the user asks for an adversarial or independent review; include the intended behavior and constraints in its task.",
247- ],
248- parameters: AdversaryParams,
249- async execute(_toolCallId, params, signal, onUpdate, ctx) {
250- const result = await runAdversary(
251- params.task,
252- ctx.cwd,
253- signal,
254- (text, details) => {
255- onUpdate?.({ content: [{ type: "text", text }], details });
256- },
257- );
258- return {
259- content: [{ type: "text", text: result.text }],
260- details: {
261- model: result.model,
262- thinking: result.thinking,
263- turns: result.turns,
264- },
265- usage: result.usage,
266- };
267- },
268- });
269-}
pi/extensions/exa/index.ts+0−499
@@ -1,499 +0,0 @@
1-import { mkdtemp, writeFile } from "node:fs/promises";
2-import { tmpdir } from "node:os";
3-import path from "node:path";
4-import { StringEnum } from "@earendil-works/pi-ai";
5-import {
6- DEFAULT_MAX_BYTES,
7- DEFAULT_MAX_LINES,
8- formatSize,
9- truncateHead,
10- type ExtensionAPI,
11- withFileMutationQueue,
12-} from "@earendil-works/pi-coding-agent";
13-import { Type } from "typebox";
14-
15-const EXA_MCP_URL =
16- "https://mcp.exa.ai/mcp?tools=web_search_exa,web_fetch_exa";
17-const MCP_PROTOCOL_VERSION = "2025-06-18";
18-const DEFAULT_RATE_LIMIT_WAIT_MS = 1000;
19-const MAX_RATE_LIMIT_WAIT_MS = 5000;
20-const DEFAULT_CONTENTS_MAX_CHARACTERS = 3000;
21-const SEARCH_TYPES = [
22- "auto",
23- "fast",
24- "instant",
25- "deep-lite",
26- "deep",
27- "deep-reasoning",
28-] as const;
29-
30-const SearchParams = Type.Object({
31- query: Type.String({ description: "Natural-language web search query" }),
32- type: Type.Optional(
33- StringEnum(SEARCH_TYPES, {
34- description: "Search depth and latency tradeoff (default: auto)",
35- }),
36- ),
37- numResults: Type.Optional(
38- Type.Integer({
39- minimum: 1,
40- maximum: 10,
41- description: "Number of results to return (default: 10)",
42- }),
43- ),
44-});
45-
46-const ContentsParams = Type.Object({
47- urls: Type.Array(Type.String({ description: "A URL to read" }), {
48- minItems: 1,
49- maxItems: 10,
50- description: "URLs to read (1-10). Batch multiple URLs in one call.",
51- }),
52- maxCharacters: Type.Optional(
53- Type.Integer({
54- minimum: 1,
55- description: `Maximum characters to extract per page (default: ${DEFAULT_CONTENTS_MAX_CHARACTERS})`,
56- }),
57- ),
58-});
59-
60-interface JsonRpcResponse {
61- jsonrpc: "2.0";
62- id?: number;
63- result?: unknown;
64- error?: { code: number; message: string };
65-}
66-
67-interface McpToolResult {
68- content?: Array<{ type: string; text?: string }>;
69- isError?: boolean;
70-}
71-
72-interface McpCallOutcome {
73- text: string;
74- keyed: boolean;
75- rateLimitRetries: number;
76-}
77-
78-class McpError extends Error {
79- readonly status: number | undefined;
80- readonly rpcCode: number | undefined;
81- readonly retryAfterMs: number | undefined;
82-
83- constructor(
84- message: string,
85- options?: {
86- status?: number;
87- rpcCode?: number;
88- retryAfterMs?: number;
89- },
90- ) {
91- super(message);
92- this.name = "McpError";
93- this.status = options?.status;
94- this.rpcCode = options?.rpcCode;
95- this.retryAfterMs = options?.retryAfterMs;
96- }
97-}
98-
99-function isRecord(value: unknown): value is Record<string, unknown> {
100- return typeof value === "object" && value !== null && !Array.isArray(value);
101-}
102-
103-function isMcpToolResult(value: unknown): value is McpToolResult {
104- if (!isRecord(value)) return false;
105- if (value.content !== undefined) {
106- if (!Array.isArray(value.content)) return false;
107- if (
108- !value.content.every(
109- (block) =>
110- isRecord(block) &&
111- typeof block.type === "string" &&
112- (block.text === undefined || typeof block.text === "string"),
113- )
114- ) {
115- return false;
116- }
117- }
118- return value.isError === undefined || typeof value.isError === "boolean";
119-}
120-
121-function apiError(body: string): string {
122- try {
123- const parsed: unknown = JSON.parse(body);
124- if (isRecord(parsed)) {
125- if (typeof parsed.error === "string") return parsed.error;
126- if (
127- isRecord(parsed.error) &&
128- typeof parsed.error.message === "string"
129- ) {
130- return parsed.error.message;
131- }
132- }
133- } catch {
134- // Fall back to the response body below.
135- }
136- return body.trim() || "Empty response";
137-}
138-
139-function parseMcpResponse(
140- body: string,
141- contentType: string,
142- requestId: number,
143-): JsonRpcResponse {
144- const candidates = contentType.includes("text/event-stream")
145- ? body
146- .split("\n")
147- .filter((line) => line.startsWith("data:"))
148- .map((line) => line.slice(5).trim())
149- : [body];
150-
151- for (const candidate of candidates.reverse()) {
152- if (!candidate || candidate === "[DONE]") continue;
153- try {
154- const parsed = JSON.parse(candidate) as JsonRpcResponse;
155- if (parsed.jsonrpc === "2.0" && parsed.id === requestId) return parsed;
156- } catch {
157- // Ignore non-JSON SSE data and continue looking for our response.
158- }
159- }
160- throw new Error("Exa MCP returned no matching JSON-RPC response");
161-}
162-
163-function parseRetryAfterMs(header: string | null): number | undefined {
164- if (!header) return undefined;
165- const seconds = Number.parseFloat(header);
166- if (!Number.isFinite(seconds) || seconds < 0) return undefined;
167- return seconds * 1000;
168-}
169-
170-function rateLimitWaitMs(error: unknown): number | undefined {
171- if (!(error instanceof McpError)) return undefined;
172- if (error.status === 429) {
173- return error.retryAfterMs ?? DEFAULT_RATE_LIMIT_WAIT_MS;
174- }
175- // The server has returned code -32000 with a rate-limit message before;
176- // catch it if it ever arrives wrapped in an HTTP 200. The message check
177- // requires an HTTP or RPC signal, so tool-level content that mentions
178- // "rate limit" does not trigger a paid retry.
179- if (
180- error.rpcCode === -32000 ||
181- ((error.status !== undefined || error.rpcCode !== undefined) &&
182- /rate.?limit/i.test(error.message))
183- ) {
184- return error.retryAfterMs ?? DEFAULT_RATE_LIMIT_WAIT_MS;
185- }
186- return undefined;
187-}
188-
189-function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
190- return new Promise((resolve, reject) => {
191- if (signal?.aborted) {
192- reject(new Error("Aborted"));
193- return;
194- }
195- const timer = setTimeout(() => {
196- signal?.removeEventListener("abort", onAbort);
197- resolve();
198- }, ms);
199- function onAbort() {
200- clearTimeout(timer);
201- reject(new Error("Aborted"));
202- }
203- signal?.addEventListener("abort", onAbort, { once: true });
204- });
205-}
206-
207-function mcpHeaders(apiKey: string | undefined): Record<string, string> {
208- const headers: Record<string, string> = {
209- "Content-Type": "application/json",
210- Accept: "application/json, text/event-stream",
211- };
212- if (apiKey) headers["x-api-key"] = apiKey;
213- return headers;
214-}
215-
216-async function mcpRequest(
217- endpoint: string,
218- requestId: number,
219- method: string,
220- params: Record<string, unknown>,
221- sessionId: string | undefined,
222- apiKey: string | undefined,
223- signal: AbortSignal | undefined,
224-): Promise<{ response: JsonRpcResponse; sessionId?: string }> {
225- const headers = mcpHeaders(apiKey);
226- if (sessionId) headers["Mcp-Session-Id"] = sessionId;
227-
228- const httpResponse = await fetch(endpoint, {
229- method: "POST",
230- headers,
231- body: JSON.stringify({
232- jsonrpc: "2.0",
233- id: requestId,
234- method,
235- params,
236- }),
237- signal,
238- });
239- const body = await httpResponse.text();
240- if (!httpResponse.ok) {
241- throw new McpError(
242- `Exa MCP failed (${httpResponse.status} ${httpResponse.statusText}): ${apiError(body)}`,
243- {
244- status: httpResponse.status,
245- retryAfterMs: parseRetryAfterMs(
246- httpResponse.headers.get("Retry-After"),
247- ),
248- },
249- );
250- }
251-
252- const response = parseMcpResponse(
253- body,
254- httpResponse.headers.get("Content-Type") ?? "",
255- requestId,
256- );
257- if (response.error) {
258- throw new McpError(
259- `Exa MCP error ${response.error.code}: ${response.error.message}`,
260- {
261- rpcCode: response.error.code,
262- retryAfterMs: parseRetryAfterMs(
263- httpResponse.headers.get("Retry-After"),
264- ),
265- },
266- );
267- }
268- return {
269- response,
270- sessionId:
271- httpResponse.headers.get("Mcp-Session-Id") ?? sessionId ?? undefined,
272- };
273-}
274-
275-async function notifyMcpInitialized(
276- endpoint: string,
277- sessionId: string,
278- apiKey: string | undefined,
279- signal: AbortSignal | undefined,
280-): Promise<void> {
281- const headers = mcpHeaders(apiKey);
282- headers["Mcp-Session-Id"] = sessionId;
283-
284- const response = await fetch(endpoint, {
285- method: "POST",
286- headers,
287- body: JSON.stringify({
288- jsonrpc: "2.0",
289- method: "notifications/initialized",
290- params: {},
291- }),
292- signal,
293- });
294- const body = await response.text();
295- if (!response.ok) {
296- throw new McpError(
297- `Exa MCP initialization failed (${response.status} ${response.statusText}): ${apiError(body)}`,
298- {
299- status: response.status,
300- retryAfterMs: parseRetryAfterMs(
301- response.headers.get("Retry-After"),
302- ),
303- },
304- );
305- }
306-}
307-
308-async function mcpToolCall(
309- toolName: string,
310- args: Record<string, unknown>,
311- urlParams: Record<string, string>,
312- apiKey: string | undefined,
313- signal: AbortSignal | undefined,
314-): Promise<string> {
315- const endpoint = new URL(EXA_MCP_URL);
316- for (const [name, value] of Object.entries(urlParams)) {
317- endpoint.searchParams.set(name, value);
318- }
319-
320- const initialized = await mcpRequest(
321- endpoint.toString(),
322- 1,
323- "initialize",
324- {
325- protocolVersion: MCP_PROTOCOL_VERSION,
326- capabilities: {},
327- clientInfo: { name: "pi-exa-extension", version: "1.0.0" },
328- },
329- undefined,
330- apiKey,
331- signal,
332- );
333- if (!initialized.sessionId) {
334- throw new Error("Exa MCP did not return a session ID");
335- }
336- await notifyMcpInitialized(
337- endpoint.toString(),
338- initialized.sessionId,
339- apiKey,
340- signal,
341- );
342-
343- const called = await mcpRequest(
344- endpoint.toString(),
345- 2,
346- "tools/call",
347- { name: toolName, arguments: args },
348- initialized.sessionId,
349- apiKey,
350- signal,
351- );
352- if (!isMcpToolResult(called.response.result)) {
353- throw new Error("Exa MCP returned an invalid tool result");
354- }
355- const result = called.response.result;
356- const text = (result.content ?? [])
357- .filter(
358- (block): block is { type: string; text: string } =>
359- block.type === "text" && typeof block.text === "string",
360- )
361- .map((block) => block.text)
362- .join("\n")
363- .trim();
364- if (result.isError) throw new McpError(text || "Exa MCP tool call failed");
365- return text || "No results found.";
366-}
367-
368-async function callMcpTool(
369- toolName: string,
370- args: Record<string, unknown>,
371- urlParams: Record<string, string>,
372- signal: AbortSignal | undefined,
373-): Promise<McpCallOutcome> {
374- const apiKey = process.env.EXA_API_KEY?.trim() || undefined;
375- if (!apiKey) {
376- const text = await mcpToolCall(
377- toolName,
378- args,
379- urlParams,
380- undefined,
381- signal,
382- );
383- return { text, keyed: false, rateLimitRetries: 0 };
384- }
385-
386- // Prefer the free anonymous tier. On a rate limit, wait and retry once,
387- // then fall back to the API key. Other errors and keyed failures surface
388- // without further fallbacks.
389- let rateLimitRetries = 0;
390- for (;;) {
391- try {
392- const text = await mcpToolCall(
393- toolName,
394- args,
395- urlParams,
396- undefined,
397- signal,
398- );
399- return { text, keyed: false, rateLimitRetries };
400- } catch (error) {
401- const waitMs = rateLimitWaitMs(error);
402- if (waitMs === undefined) throw error;
403- rateLimitRetries += 1;
404- if (rateLimitRetries > 1) break;
405- await sleep(Math.min(waitMs, MAX_RATE_LIMIT_WAIT_MS), signal);
406- }
407- }
408- const text = await mcpToolCall(toolName, args, urlParams, apiKey, signal);
409- return { text, keyed: true, rateLimitRetries };
410-}
411-
412-async function buildToolOutput(
413- output: string,
414-): Promise<{ text: string; fullOutputPath?: string }> {
415- const truncation = truncateHead(output, {
416- maxLines: DEFAULT_MAX_LINES,
417- maxBytes: DEFAULT_MAX_BYTES,
418- });
419- let text = truncation.content;
420- let fullOutputPath: string | undefined;
421-
422- if (truncation.truncated) {
423- const directory = await mkdtemp(path.join(tmpdir(), "pi-exa-"));
424- const tempFile = path.join(directory, "results.txt");
425- fullOutputPath = tempFile;
426- await withFileMutationQueue(tempFile, () =>
427- writeFile(tempFile, output, "utf8"),
428- );
429- text += `\n\n[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}). Full output saved to: ${fullOutputPath}]`;
430- }
431- return { text, fullOutputPath };
432-}
433-
434-export default function exaExtension(pi: ExtensionAPI): void {
435- pi.registerTool({
436- name: "exa_search",
437- label: "Exa Search",
438- description: `Search the web with Exa and return URLs plus relevant highlights. Output is truncated to ${DEFAULT_MAX_LINES} lines or ${formatSize(DEFAULT_MAX_BYTES)}. Uses Exa's free hosted MCP service; EXA_API_KEY is optional and only used as a rate-limit fallback.`,
439- promptSnippet:
440- "Search the web with Exa and return relevant excerpts and source URLs",
441- promptGuidelines: [
442- "Use exa_search for current information and web research, and cite the returned source URLs in the answer.",
443- ],
444- parameters: SearchParams,
445- async execute(_toolCallId, params, signal) {
446- const searchType = params.type ?? "auto";
447- const result = await callMcpTool(
448- "web_search_exa",
449- { query: params.query, numResults: params.numResults ?? 10 },
450- { defaultSearchType: searchType },
451- signal,
452- );
453- const { text, fullOutputPath } = await buildToolOutput(result.text);
454- return {
455- content: [{ type: "text", text }],
456- details: {
457- keyed: result.keyed,
458- rateLimitRetries: result.rateLimitRetries,
459- requestedSearchType: searchType,
460- fullOutputPath,
461- },
462- };
463- },
464- });
465-
466- pi.registerTool({
467- name: "exa_contents",
468- label: "Exa Contents",
469- description:
470- "Read the full content of web pages as clean markdown with Exa, when you know the URLs.",
471- promptSnippet: "Read full web page content for known URLs with Exa",
472- promptGuidelines: [
473- "Use exa_contents to read the full content of pages whose URLs you know.",
474- ],
475- parameters: ContentsParams,
476- async execute(_toolCallId, params, signal) {
477- const result = await callMcpTool(
478- "web_fetch_exa",
479- {
480- urls: params.urls,
481- maxCharacters:
482- params.maxCharacters ?? DEFAULT_CONTENTS_MAX_CHARACTERS,
483- },
484- {},
485- signal,
486- );
487- const { text, fullOutputPath } = await buildToolOutput(result.text);
488- return {
489- content: [{ type: "text", text }],
490- details: {
491- keyed: result.keyed,
492- rateLimitRetries: result.rateLimitRetries,
493- urlCount: params.urls.length,
494- fullOutputPath,
495- },
496- };
497- },
498- });
499-}
pi/prompts/review.md+0−4
@@ -1,4 +0,0 @@
1-Use the adversary tool to perform a review.
2-Give it only a summary of our conversation and a request for review. Do not steer the review in any way.
3-Address the adversary's actionable feedback.
4-Repeat this process until both you and the adversary approve the changeset.