xonecas.io
56101
Df

dotfiles / commit aa2cf26

feat: consolidate hax and pi configs here too

xonecas2026-09-02 aa2cf26791a43bbe5668048a4cea5f957de1a20c parent b3db9c4

17 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

README.md+25−8
@@ -2,18 +2,35 @@
22
33 Personal configuration files for my development environment.
44
5+Each folder is a config. Symlink it to the path the tool already discovers.
6+
57 ## Contents
68
7-- `nvim/` — Neovim configuration
8-- `ghostty/` — Ghostty terminal configuration
9-- `bash/` — Bash configuration and related setup files
9+- `nvim/` — Neovim → `~/.config/nvim`
10+- `ghostty/` — Ghostty → `~/.config/ghostty`
11+- `bash/` — Bash setup files
12+- `hunk/` — Hunk → `~/.config/hunk/config.toml`
13+- `hax/` — Hax agent, skills, prompts, helper scripts → `~/.config/hax`
14+- `pi/` — Pi agent, prompts, extensions → `~/.pi/agent`
1015
1116 ## Usage
1217
13-Clone this repository and symlink or copy the configuration files into the appropriate locations in your home directory.
14-
1518 ```sh
16-git clone <repo-url> ~/src/dotfiles
17-```
19+git clone git@github.com:sacenox/dotfiles.git ~/src/dotfiles
1820
19-Review each directory before applying changes, as these files are tailored to my personal workflow.
21+ln -s ~/src/dotfiles/nvim ~/.config/nvim
22+ln -s ~/src/dotfiles/ghostty ~/.config/ghostty
23+ln -s ~/src/dotfiles/hunk/config.toml ~/.config/hunk/config.toml
24+
25+ln -s ~/src/dotfiles/hax ~/.config/hax
26+ln -s ~/src/dotfiles/hax/bin/hax-adversary ~/.local/bin/hax-adversary
27+ln -s ~/src/dotfiles/hax/bin/hax-loop ~/.local/bin/hax-loop
28+
29+mkdir -p ~/.pi/agent/extensions ~/.agents
30+ln -s ~/src/dotfiles/pi/AGENTS.md ~/.agents/AGENTS.md
31+ln -s ~/.agents/AGENTS.md ~/.pi/agent/AGENTS.md
32+ln -s ~/src/dotfiles/pi/settings.json ~/.pi/agent/settings.json
33+ln -s ~/src/dotfiles/pi/prompts ~/.pi/agent/prompts
34+ln -s ~/src/dotfiles/pi/extensions/adversary ~/.pi/agent/extensions/adversary
35+ln -s ~/src/dotfiles/pi/extensions/exa ~/.pi/agent/extensions/exa
36+```
ghostty/config+5−0
@@ -18,3 +18,8 @@ unfocused-split-opacity = 1
1818 # theme = 0x96f
1919 # theme = Zenwritten Dark
2020 theme = Gruvbox Dark Hard
21+
22+# Send a literal LF for Shift+Enter so terminal agents (hax, etc.) can insert
23+# newlines; Ghostty otherwise sends the CSI sequence [27;2;13~ which they
24+# ignore.
25+keybind = shift+enter=text:\n
hax/AGENTS.md+6−0
@@ -0,0 +1,6 @@
1+# Rules for AGENTS
2+
3+- Always return exactly what was asked. Do not add scope, backwards compatibility or extras without the user explicitly asking.
4+- Use `gh` for Github (it's already authenticated as me).
5+- Use `uvx hf` for HuggingFace (also already authenticated as me).
6+- Use `curl` and the environment's `EXA_API_KEY` to search and read web contents.
hax/bin/hax-adversary+23−0
@@ -0,0 +1,23 @@
1+#!/usr/bin/env bash
2+# hax-adversary — run the adversarial reviewer as an isolated hax -p subprocess.
3+#
4+# Usage:
5+# hax-adversary <review brief...>
6+# echo "<brief>" | hax-adversary
7+# hax-adversary < brief.txt
8+#
9+# The reviewer model and instructions come from the `adversary` preset in
10+# ~/.config/hax/config.json. --bare strips project instructions, skills, and
11+# subagent guidance; --no-session keeps the child out of session history.
12+set -euo pipefail
13+
14+if [ "$#" -gt 0 ]; then
15+ exec hax -p --preset=adversary --no-session --bare "$@"
16+fi
17+
18+if [ ! -t 0 ]; then
19+ exec hax -p --preset=adversary --no-session --bare
20+fi
21+
22+echo "usage: hax-adversary <review brief> (or pipe the brief via stdin)" >&2
23+exit 1
hax/bin/hax-loop+45−0
@@ -0,0 +1,45 @@
1+#!/usr/bin/env bash
2+# hax-loop — one-shot implementer → diff → adversary. No retry, no commit.
3+#
4+# Usage:
5+# hax-loop <task...>
6+# echo "<task>" | hax-loop
7+# hax-loop < task.txt
8+#
9+# Run from the project directory. The caller's task is passed verbatim.
10+# Implementer and adversary models come from presets in ~/.config/hax/config.json.
11+set -euo pipefail
12+
13+if [ -n "${HAX_LOOP:-}" ]; then
14+ echo "hax-loop: refused to nest" >&2
15+ exit 1
16+fi
17+export HAX_LOOP=1
18+
19+if [ "$#" -gt 0 ]; then
20+ TASK="$*"
21+elif [ ! -t 0 ]; then
22+ TASK=$(cat)
23+else
24+ echo "usage: hax-loop <task> (or pipe the task via stdin)" >&2
25+ exit 1
26+fi
27+
28+if [ -z "$TASK" ]; then
29+ echo "hax-loop: empty task" >&2
30+ exit 1
31+fi
32+
33+echo "==== implement ===="
34+# Skills and subagent presets stay with the overseer; the implementer would
35+# otherwise see this workflow and call hax-loop instead of doing the work.
36+printf '%s\n' "$TASK" | HAX_NO_SKILLS=1 HAX_NO_SUBAGENTS=1 \
37+ hax -p --preset=implementer --no-session
38+
39+echo "==== diff ===="
40+git status --short
41+git --no-pager diff
42+
43+echo "==== review ===="
44+printf '%s\n\nReview the uncommitted diff against that task.\n' "$TASK" |
45+ hax -p --preset=adversary --no-session --bare
hax/config.json+20−0
@@ -0,0 +1,20 @@
1+{
2+ "presets": {
3+ "adversary": {
4+ "description": "independent adversarial reviewer (read-only)",
5+ "provider": "opencode-go",
6+ "model": "deepseek-v4-flash",
7+ "effort": "high",
8+ "system_prompt_append": "@~/.config/hax/prompts/adversary.md",
9+ "tint": "rose"
10+ },
11+ "implementer": {
12+ "description": "fast implementer: do the given task, nothing else",
13+ "provider": "opencode-go",
14+ "model": "glm-5.3-flash",
15+ "effort": "low",
16+ "system_prompt_append": "Implement the given task. Do not add scope, extras, or compatibility the task did not ask for. Do not commit. The caller's task is the requirement; repository docs constrain how, they do not replace the task.",
17+ "tint": "sage"
18+ }
19+ }
20+}
hax/prompts/adversary.md+28−0
@@ -0,0 +1,28 @@
1+# Adversarial Reviewer
2+
3+Review the requested change with a skeptical, evidence-driven mindset.
4+
5+Your job is to identify issues that would matter to the author before the change ships. Do not summarize or praise the implementation.
6+
7+Ensure that the change contains neither:
8+
9+- Poor architectural decisions.
10+- Inconsistencies with repository practices and guidelines.
11+
12+You are strictly read-only:
13+
14+- Do not edit files.
15+- Use the read/search tools and `bash` to inspect the repository, run tests, and gather evidence.
16+
17+## Standards
18+
19+- Report only concrete, actionable findings. Do not invent hypothetical concerns without a plausible failure path.
20+- Treat the stated requirements and established repository behavior as the source of truth.
21+- Do not downgrade a real issue because it existed before the change; identify it when the change introduces or worsens it.
22+- Focus on correctness and avoid nit-picking.
23+- Do not propose or apply code changes.
24+- 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.
25+
26+## Output
27+
28+A short and concise report of the review findings or a clear statement that nothing was found.
hax/skills/adversary/SKILL.md+51−0
@@ -0,0 +1,51 @@
1+# Adversary review
2+
3+Delegate a focused, read-only adversarial review to an isolated hax process running a
4+different model.
5+
6+## When to use
7+
8+- The user asks for an adversarial, skeptical, or independent review of work.
9+- The work is significant enough (a changeset, a design, a plan) to justify a second,
10+ isolated pass with different eyes.
11+
12+## How to run
13+
14+1. Build a **review brief** containing, in prose:
15+
16+ - the intended behavior and requirements;
17+ - the scope of the change (files, commands, tests involved);
18+ - any constraints or repository practices the review should check against;
19+ - pointers to the relevant context (paths) the reviewer should inspect.
20+
21+ The reviewer does not have this conversation's context, so everything it needs to
22+ evaluate the change must be in the brief or reachable from the working directory.
23+
24+2. Run it with:
25+
26+ ```sh
27+ hax-adversary "$BRIEF"
28+ ```
29+
30+ or, for a long brief, pipe it:
31+
32+ ```sh
33+ cat <<'EOF' | hax-adversary
34+ <review brief>
35+ EOF
36+ ```
37+
38+ `hax-adversary` is a wrapper around `hax -p --preset=adversary --no-session --bare`.
39+ The preset (in `~/.config/hax/config.json`) fixes the reviewer model and injects the
40+ reviewer instructions; `--bare` strips project instructions, skills, and subagent
41+ guidance so the reviewer sees only the brief and the repository.
42+
43+3. Report the findings to the user, citing the exact code locations the reviewer gives.
44+
45+## Notes
46+
47+- The reviewer is instructed to be read-only and it runs with tools in a bare context,
48+ but there is no hard tool restriction — treat its output as findings to verify, not
49+ as a gate.
50+- A review may take a while: if the command detaches into a background task, wait on it
51+ and collect the output before reporting.
hax/skills/loop/SKILL.md+51−0
@@ -0,0 +1,51 @@
1+# Implementer / adversary loop
2+
3+Delegate a unit of work to an isolated implementer, then an isolated adversarial
4+review. This session stays the overseer: it writes the task, calls the loop, and
5+audits the result with the user.
6+
7+## When to use
8+
9+- The user asks to use this workflow, the implementer/adversary loop, or `hax-loop`.
10+- The user describes a goal, feature, or change and wants it implemented that way
11+ rather than in this session.
12+
13+## How to run
14+
15+1. Stay the overseer. Do not implement the work yourself. Do not ask a subagent
16+ in this session to do it either.
17+
18+2. Write the **task** in prose: intended behavior, scope, constraints, and any
19+ paths that matter. Pass it **verbatim**. Do not have another model restate it
20+ from the repository — that is how a wrong GOAL.md becomes the spec again.
21+
22+3. From the project directory:
23+
24+ ```sh
25+ hax-loop "$TASK"
26+ ```
27+
28+ or, for a long task, pipe it:
29+
30+ ```sh
31+ cat <<'EOF' | hax-loop
32+ <task>
33+ EOF
34+ ```
35+
36+ `hax-loop` runs `hax -p --preset=implementer`, prints `git status` / `git diff`,
37+ then `hax -p --preset=adversary --bare`. Presets live in `~/.config/hax/config.json`.
38+ The implementer is launched without skills or subagent guidance so it cannot
39+ see this workflow. Nested `hax-loop` is refused.
40+
41+4. Report the diff and the review to the user. Audit with them. If the generation
42+ is wrong, call `hax-loop` again with a corrected task. Do not auto-retry until
43+ the review is empty.
44+
45+## Notes
46+
47+- Never call `hax-loop` from an implementer or reviewer.
48+- The task is the requirement; repository docs constrain how, they do not replace
49+ the task.
50+- A loop run may take a while: if the command detaches into a background task,
51+ wait on it and collect the output before reporting.
hunk/config.toml+1−1
@@ -1,4 +1,4 @@
1-theme = "gruvbox-dark-hard"
1+theme = "aurora-x"
22 mode = "auto"
33 line_numbers = true
44 wrap_lines = true
pi/AGENTS.md+6−0
@@ -0,0 +1,6 @@
1+# Rules for AGENTS
2+
3+- Do not invent project infrastructure or requirements. Verify claims from the repository. Mark unverified ideas as proposals. Do not add unrequested scope.
4+- Always write in Simplified Technical English (ASD-STE100).
5+- Use `gh` for Github (it's already authenticated as me).
6+- Use `uvx hf` for HuggingFace (also already authenticated as me).
pi/extensions/adversary/adversary.md+33−0
@@ -0,0 +1,33 @@
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+269−0
@@ -0,0 +1,269 @@
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+499−0
@@ -0,0 +1,499 @@
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+ );
Cut short: this commit's diff is over 1000 lines.
pi/prompts/hunk.md+5−0
Cut short: this commit's diff is over 1000 lines.
pi/prompts/review.md+4−0
Cut short: this commit's diff is over 1000 lines.
pi/settings.json+15−0
Cut short: this commit's diff is over 1000 lines.