Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0a7a38a9a5 | |||
| 72a040aafa | |||
| cc59a16472 | |||
| 8db0c40487 | |||
| 7fb788a883 | |||
| 0cf88e1752 | |||
| dcb672b5be | |||
| 7103f5f991 | |||
| c518e8b6fd | |||
| 615a3bc8e1 | |||
| 17ad3bd0e7 | |||
| 25896559f0 | |||
| 5353d80388 | |||
| 2dea842981 |
+17
-5
@@ -19,7 +19,7 @@ export const claude = agent({
|
||||
delete process.env.ANTHROPIC_API_KEY;
|
||||
|
||||
const prompt = addInstructions({ payload, repo });
|
||||
log.group("» Full prompt", () => log.info(prompt));
|
||||
log.group("Full prompt", () => log.info(prompt));
|
||||
|
||||
// configure sandbox mode if enabled
|
||||
const sandboxOptions: Options = payload.sandbox
|
||||
@@ -56,6 +56,7 @@ export const claude = agent({
|
||||
options: {
|
||||
...sandboxOptions,
|
||||
mcpServers,
|
||||
model: "claude-opus-4-5",
|
||||
pathToClaudeCodeExecutable: cliPath,
|
||||
env: createAgentEnv({ ANTHROPIC_API_KEY: apiKey }),
|
||||
},
|
||||
@@ -146,16 +147,27 @@ const messageHandlers: SDKMessageHandlers = {
|
||||
},
|
||||
result: async (data) => {
|
||||
if (data.subtype === "success") {
|
||||
const usage = data.usage;
|
||||
const inputTokens = usage?.input_tokens || 0;
|
||||
const cacheRead = usage?.cache_read_input_tokens || 0;
|
||||
const cacheWrite = usage?.cache_creation_input_tokens || 0;
|
||||
const outputTokens = usage?.output_tokens || 0;
|
||||
const totalInput = inputTokens + cacheRead + cacheWrite;
|
||||
|
||||
await log.summaryTable([
|
||||
[
|
||||
{ data: "Cost", header: true },
|
||||
{ data: "Input Tokens", header: true },
|
||||
{ data: "Output Tokens", header: true },
|
||||
{ data: "Input", header: true },
|
||||
{ data: "Cache Read", header: true },
|
||||
{ data: "Cache Write", header: true },
|
||||
{ data: "Output", header: true },
|
||||
],
|
||||
[
|
||||
`$${data.total_cost_usd?.toFixed(4) || "0.0000"}`,
|
||||
String(data.usage?.input_tokens || 0),
|
||||
String(data.usage?.output_tokens || 0),
|
||||
String(totalInput),
|
||||
String(cacheRead),
|
||||
String(cacheWrite),
|
||||
String(outputTokens),
|
||||
],
|
||||
]);
|
||||
} else if (data.subtype === "error_max_turns") {
|
||||
|
||||
+1
-1
@@ -167,7 +167,7 @@ export const cursor = agent({
|
||||
|
||||
try {
|
||||
const fullPrompt = addInstructions({ payload, repo });
|
||||
log.group("» Full prompt", () => log.info(fullPrompt));
|
||||
log.group("Full prompt", () => log.info(fullPrompt));
|
||||
|
||||
// configure sandbox mode if enabled
|
||||
// in sandbox mode: remove --force flag and rely on cli-config.json sandbox settings
|
||||
|
||||
+1
-1
@@ -162,7 +162,7 @@ export const gemini = agent({
|
||||
}
|
||||
|
||||
const sessionPrompt = addInstructions({ payload, repo });
|
||||
log.group("» Full prompt", () => log.info(sessionPrompt));
|
||||
log.group("Full prompt", () => log.info(sessionPrompt));
|
||||
|
||||
// configure sandbox mode if enabled
|
||||
// --allowed-tools restricts which tools are available (removes others from registry entirely)
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ export const opencode = agent({
|
||||
configureOpenCode({ mcpServers, sandbox: payload.sandbox ?? false });
|
||||
|
||||
const prompt = addInstructions({ payload, repo });
|
||||
log.group("» Full prompt", () => log.info(prompt));
|
||||
log.group("Full prompt", () => log.info(prompt));
|
||||
|
||||
// message positional must come right after "run", before flags
|
||||
const args = ["run", prompt, "--format", "json"];
|
||||
|
||||
@@ -45360,14 +45360,14 @@ var require_retry_agent = __commonJS({
|
||||
this.#options = options;
|
||||
}
|
||||
dispatch(opts, handler2) {
|
||||
const retry = new RetryHandler({
|
||||
const retry2 = new RetryHandler({
|
||||
...opts,
|
||||
retryOptions: this.#options
|
||||
}, {
|
||||
dispatch: this.#agent.dispatch.bind(this.#agent),
|
||||
handler: handler2
|
||||
});
|
||||
return this.#agent.dispatch(opts, retry);
|
||||
return this.#agent.dispatch(opts, retry2);
|
||||
}
|
||||
close() {
|
||||
return this.#agent.close();
|
||||
@@ -83328,7 +83328,7 @@ function query({
|
||||
// package.json
|
||||
var package_default = {
|
||||
name: "@pullfrog/action",
|
||||
version: "0.0.151",
|
||||
version: "0.0.154",
|
||||
type: "module",
|
||||
files: [
|
||||
"index.js",
|
||||
@@ -92563,7 +92563,7 @@ function getModes({ disableProgressComment }) {
|
||||
{
|
||||
name: "Build",
|
||||
description: "Implement, build, create, or develop code changes; make specific changes to files or features; execute a plan; or handle tasks with specific implementation details",
|
||||
prompt: `Follow these steps:
|
||||
prompt: `Follow these steps. THINK HARDER.
|
||||
1. If this is a PR event, the PR branch is already checked out - skip branch creation. Otherwise, create a branch using ${ghPullfrogMcpName}/create_branch. The branch name should be prefixed with "pullfrog/". The rest of the name should reflect the exact changes you are making. It should be specific to avoid collisions with other branches. Never commit directly to main, master, or production. Do NOT use git commands directly (including \`git branch\`, \`git status\`, \`git log\`) - always use ${ghPullfrogMcpName} MCP tools for git operations.
|
||||
|
||||
${dependencyInstallationGuidance}
|
||||
@@ -92601,7 +92601,7 @@ ${dependencyInstallationGuidance}
|
||||
{
|
||||
name: "Address Reviews",
|
||||
description: "Address PR review feedback; respond to reviewer comments; make requested changes to an existing PR",
|
||||
prompt: `Follow these steps:
|
||||
prompt: `Follow these steps. THINK HARDER.
|
||||
1. Checkout the PR using ${ghPullfrogMcpName}/checkout_pr with the PR number. This fetches the PR branch and configures push settings (including for fork PRs).
|
||||
|
||||
${dependencyInstallationGuidance}
|
||||
@@ -92627,42 +92627,34 @@ ${disableProgressComment ? "" : `
|
||||
{
|
||||
name: "Review",
|
||||
description: "Review code, PRs, or implementations; provide feedback or suggestions; identify issues; or check code quality, style, and correctness",
|
||||
prompt: `Follow these steps:
|
||||
1. Checkout the PR using ${ghPullfrogMcpName}/checkout_pr with the PR number. This fetches the PR branch and returns the PR diff in the \`diff\` field of the response. Use this diff for your review - it shows exactly what's in the PR (fetched via GitHub API, so it's not affected by main advancing after the branch was created).
|
||||
prompt: `Follow these steps to review the PR. Think hard. Do not nitpick.
|
||||
|
||||
2. Start review session using ${ghPullfrogMcpName}/start_review. This creates a pending review on GitHub and returns analysis guidance. Follow the guidance before adding comments.
|
||||
1. **CHECKOUT** - Call ${ghPullfrogMcpName}/checkout_pr with the PR number. This should give you all PR metadata you need, including a \`diffPath\`: a path to a temp file containing the PR diff.
|
||||
|
||||
3. **ANALYZE** - Before adding any comments, think through:
|
||||
- What does this PR change? Summarize in 1-2 sentences.
|
||||
- Is the approach sound? If not, **stop here** and comment on the approach first. Don't waste time on implementation details if the approach is wrong.
|
||||
- What bugs, edge cases, or security issues exist?
|
||||
|
||||
4. **BEFORE COMMENTING** - For each potential comment, ask yourself:
|
||||
- Is this a nitpick? Skip it unless explicitly requested.
|
||||
- Would the codebase maintainer care about this feedback, based on what you can infer about the code quality standards in this repo?
|
||||
2. **ANALYZE**
|
||||
- Read the modified files to understand the changes in context. Make sure you understand what's being changed.
|
||||
- Is it a good idea? Think about the tradeoffs.
|
||||
- Is the approach sound? If not, focus on the approach first. Don't waste time on implementation details if the approach is wrong.
|
||||
- Can you imagine a better approach? If so, explain. Make sure it's strictly better, not just different.
|
||||
- Are there bugs, edge cases, security issues, or usability issues? Use your imagination.
|
||||
|
||||
5. Add inline review comments one-by-one using ${ghPullfrogMcpName}/add_review_comment
|
||||
- Use **relative paths** from repo root (e.g., \`packages/core/src/utils.ts\`)
|
||||
- Use the NEW file line number from the diff (shown after \`+\` in hunk headers like \`@@ -10,5 +12,8 @@\` means new file starts at line 12)
|
||||
- Only comment on lines that appear in the diff. GitHub will reject comments on unchanged lines.
|
||||
- For issues appearing in multiple places, comment on the FIRST occurrence and reference others (e.g., "also at lines X, Y")
|
||||
3. **DRAFT** - For each inline comment, find the line in the diff. Each code line shows: \`| OLD | NEW | TYPE | CODE\`. Use the NEW line number (second column).
|
||||
|
||||
6. Submit the review using ${ghPullfrogMcpName}/submit_review
|
||||
- The "body" field is ONLY for: (1) a 1-3 sentence high-level overview, (2) urgency level (e.g., "minor suggestions" vs "blocking issues"), (3) critical security callouts (e.g., API key exposure)
|
||||
4. **FILTER COMMENTS** - Do not nitpick! Do not leave compliments that are not actionable. Do not critique the code hygiene or anything stylistic.
|
||||
|
||||
**GENERAL GUIDANCE**
|
||||
5. **SUBMIT** \u2014 Use ${ghPullfrogMcpName}/create_pull_request_review with:
|
||||
- \`comments\`: Array of all inline comments with file paths and line numbers
|
||||
- \`body\`: Everything else. Aim for a 1-3 sentence summary of the urgency level (e.g., "minor suggestions" vs "blocking issues") and any critical callouts (e.g., API key exposure). It can be longer if there are concerns that do not lend themselves to inline comments.
|
||||
- If you have no substantive feedback, submit an empty comments array with a brief approving body.
|
||||
- Again, do not nitpick.
|
||||
|
||||
- Do not leave any comments that are not potentially actionable. Do not leave complimentary comments just to be nice.
|
||||
- Do not nitpick unless instructed explicitly to do so by the user's additional instructions. This includes: requesting documentation/docstrings/JSDoc.
|
||||
- **CRITICAL: Prioritize per-line feedback over summary text.**
|
||||
- All specific feedback MUST go in inline review comments with file paths and line numbers from the diff
|
||||
- The vast majority of review content should be in inline review comments; the body should be brief and only summarize the urgency of the review and any cross-cutting concerns.
|
||||
`
|
||||
`
|
||||
},
|
||||
{
|
||||
name: "Plan",
|
||||
description: "Create plans, break down tasks, outline steps, analyze requirements, understand scope of work, or provide task breakdowns",
|
||||
prompt: `Follow these steps:
|
||||
prompt: `Follow these steps. THINK HARDER.
|
||||
1. If the request requires understanding the codebase structure or conventions, gather relevant context (read AGENTS.md if it exists). Skip this step if the prompt is trivial and self-contained.
|
||||
|
||||
2. Analyze the request and break it down into clear, actionable tasks
|
||||
@@ -92676,7 +92668,7 @@ ${disableProgressComment ? "" : `
|
||||
{
|
||||
name: "Prompt",
|
||||
description: "Fallback for tasks that don't fit other workflows, e.g. direct prompts via comments, or requests requiring general assistance",
|
||||
prompt: `Follow these steps:
|
||||
prompt: `Follow these steps. THINK HARDER.
|
||||
1. Perform the requested task. Only take action if you have high confidence that you understand what is being asked. If you are not sure, ask for clarification. Take stock of the tools at your disposal.${disableProgressComment ? "" : "\n\n2. When creating comments, always use report_progress. Do not use create_issue_comment."}
|
||||
|
||||
2. If the task involves making code changes:
|
||||
@@ -92866,6 +92858,35 @@ import { pipeline } from "node:stream/promises";
|
||||
// utils/github.ts
|
||||
var core2 = __toESM(require_core(), 1);
|
||||
import { createSign } from "node:crypto";
|
||||
|
||||
// utils/retry.ts
|
||||
var defaultShouldRetry = (error41) => {
|
||||
if (!(error41 instanceof Error)) return false;
|
||||
return error41.name === "AbortError" || error41.message.includes("fetch failed") || error41.message.includes("ECONNRESET") || error41.message.includes("ETIMEDOUT");
|
||||
};
|
||||
async function retry(fn2, options = {}) {
|
||||
const maxAttempts = options.maxAttempts ?? 3;
|
||||
const delayMs = options.delayMs ?? 1e3;
|
||||
const shouldRetry = options.shouldRetry ?? defaultShouldRetry;
|
||||
const label = options.label ?? "operation";
|
||||
let lastError;
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
try {
|
||||
return await fn2();
|
||||
} catch (error41) {
|
||||
lastError = error41;
|
||||
if (attempt === maxAttempts || !shouldRetry(error41)) {
|
||||
throw error41;
|
||||
}
|
||||
const delay2 = delayMs * attempt;
|
||||
log.warning(`\xBB ${label} failed (attempt ${attempt}/${maxAttempts}), retrying in ${delay2}ms...`);
|
||||
await new Promise((resolve2) => setTimeout(resolve2, delay2));
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
// utils/github.ts
|
||||
function isGitHubActionsEnvironment() {
|
||||
return Boolean(process.env.GITHUB_ACTIONS);
|
||||
}
|
||||
@@ -92998,7 +93019,7 @@ async function acquireTokenViaGitHubApp() {
|
||||
}
|
||||
async function acquireNewToken() {
|
||||
if (isGitHubActionsEnvironment()) {
|
||||
return await acquireTokenViaOIDC();
|
||||
return await retry(() => acquireTokenViaOIDC(), { label: "token exchange" });
|
||||
} else {
|
||||
return await acquireTokenViaGitHubApp();
|
||||
}
|
||||
@@ -93281,7 +93302,7 @@ var claude = agent({
|
||||
run: async ({ payload, mcpServers, apiKey, cliPath, repo }) => {
|
||||
delete process.env.ANTHROPIC_API_KEY;
|
||||
const prompt = addInstructions({ payload, repo });
|
||||
log.group("\xBB Full prompt", () => log.info(prompt));
|
||||
log.group("Full prompt", () => log.info(prompt));
|
||||
const sandboxOptions = payload.sandbox ? {
|
||||
permissionMode: "default",
|
||||
disallowedTools: ["Bash", "WebSearch", "WebFetch", "Write"],
|
||||
@@ -93309,6 +93330,7 @@ var claude = agent({
|
||||
options: {
|
||||
...sandboxOptions,
|
||||
mcpServers,
|
||||
model: "claude-opus-4-5",
|
||||
pathToClaudeCodeExecutable: cliPath,
|
||||
env: createAgentEnv({ ANTHROPIC_API_KEY: apiKey })
|
||||
}
|
||||
@@ -93369,16 +93391,26 @@ var messageHandlers = {
|
||||
},
|
||||
result: async (data) => {
|
||||
if (data.subtype === "success") {
|
||||
const usage = data.usage;
|
||||
const inputTokens = usage?.input_tokens || 0;
|
||||
const cacheRead = usage?.cache_read_input_tokens || 0;
|
||||
const cacheWrite = usage?.cache_creation_input_tokens || 0;
|
||||
const outputTokens = usage?.output_tokens || 0;
|
||||
const totalInput = inputTokens + cacheRead + cacheWrite;
|
||||
await log.summaryTable([
|
||||
[
|
||||
{ data: "Cost", header: true },
|
||||
{ data: "Input Tokens", header: true },
|
||||
{ data: "Output Tokens", header: true }
|
||||
{ data: "Input", header: true },
|
||||
{ data: "Cache Read", header: true },
|
||||
{ data: "Cache Write", header: true },
|
||||
{ data: "Output", header: true }
|
||||
],
|
||||
[
|
||||
`$${data.total_cost_usd?.toFixed(4) || "0.0000"}`,
|
||||
String(data.usage?.input_tokens || 0),
|
||||
String(data.usage?.output_tokens || 0)
|
||||
String(totalInput),
|
||||
String(cacheRead),
|
||||
String(cacheWrite),
|
||||
String(outputTokens)
|
||||
]
|
||||
]);
|
||||
} else if (data.subtype === "error_max_turns") {
|
||||
@@ -93963,7 +93995,7 @@ var cursor = agent({
|
||||
};
|
||||
try {
|
||||
const fullPrompt = addInstructions({ payload, repo });
|
||||
log.group("\xBB Full prompt", () => log.info(fullPrompt));
|
||||
log.group("Full prompt", () => log.info(fullPrompt));
|
||||
const cursorArgs = payload.sandbox ? [
|
||||
"--print",
|
||||
fullPrompt,
|
||||
@@ -94274,7 +94306,7 @@ var gemini = agent({
|
||||
throw new Error("google_api_key or gemini_api_key is required for gemini agent");
|
||||
}
|
||||
const sessionPrompt = addInstructions({ payload, repo });
|
||||
log.group("\xBB Full prompt", () => log.info(sessionPrompt));
|
||||
log.group("Full prompt", () => log.info(sessionPrompt));
|
||||
const args3 = payload.sandbox ? [
|
||||
"--allowed-tools",
|
||||
"read_file,list_directory,search_file_content,glob,save_memory,write_todos",
|
||||
@@ -94397,7 +94429,7 @@ var opencode = agent({
|
||||
mkdirSync4(configDir, { recursive: true });
|
||||
configureOpenCode({ mcpServers, sandbox: payload.sandbox ?? false });
|
||||
const prompt = addInstructions({ payload, repo });
|
||||
log.group("\xBB Full prompt", () => log.info(prompt));
|
||||
log.group("Full prompt", () => log.info(prompt));
|
||||
const args3 = ["run", prompt, "--format", "json"];
|
||||
if (payload.sandbox) {
|
||||
log.info("\u{1F512} sandbox mode enabled: restricting to read-only operations");
|
||||
@@ -94721,7 +94753,7 @@ var agents = {
|
||||
// main.ts
|
||||
import { mkdtemp as mkdtemp2 } from "node:fs/promises";
|
||||
import { tmpdir as tmpdir2 } from "node:os";
|
||||
import { join as join10 } from "node:path";
|
||||
import { join as join11 } from "node:path";
|
||||
|
||||
// node_modules/.pnpm/universal-user-agent@7.0.3/node_modules/universal-user-agent/index.js
|
||||
function getUserAgent() {
|
||||
@@ -98256,13 +98288,9 @@ function stripExistingFooter(body) {
|
||||
// mcp/shared.ts
|
||||
var tool = (toolDef) => toolDef;
|
||||
var handleToolSuccess = (data) => {
|
||||
const text = typeof data === "string" ? data : encode(data);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(data, null, 2)
|
||||
}
|
||||
]
|
||||
content: [{ type: "text", text }]
|
||||
};
|
||||
};
|
||||
var handleToolError = (error41) => {
|
||||
@@ -122940,6 +122968,10 @@ var FastMCP = class extends FastMCPEventEmitter {
|
||||
}
|
||||
};
|
||||
|
||||
// mcp/checkout.ts
|
||||
import { writeFileSync as writeFileSync4 } from "node:fs";
|
||||
import { join as join8 } from "node:path";
|
||||
|
||||
// utils/shell.ts
|
||||
import { spawnSync as spawnSync4 } from "node:child_process";
|
||||
function $(cmd, args3, options) {
|
||||
@@ -122983,6 +123015,55 @@ function $(cmd, args3, options) {
|
||||
}
|
||||
|
||||
// mcp/checkout.ts
|
||||
function formatFilesWithLineNumbers(files) {
|
||||
const output = [];
|
||||
for (const file of files) {
|
||||
output.push(`diff --git a/${file.filename} b/${file.filename}`);
|
||||
output.push(`--- a/${file.filename}`);
|
||||
output.push(`+++ b/${file.filename}`);
|
||||
if (!file.patch) {
|
||||
output.push("(binary file or no changes)");
|
||||
output.push("");
|
||||
continue;
|
||||
}
|
||||
const lines = file.patch.split("\n");
|
||||
let oldLine = 0;
|
||||
let newLine = 0;
|
||||
for (const line of lines) {
|
||||
const hunkMatch = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
||||
if (hunkMatch) {
|
||||
oldLine = parseInt(hunkMatch[1], 10);
|
||||
newLine = parseInt(hunkMatch[2], 10);
|
||||
output.push(line);
|
||||
continue;
|
||||
}
|
||||
const changeType = line[0] || " ";
|
||||
const code = line.slice(1);
|
||||
if (changeType === "-") {
|
||||
output.push(`| ${padNum(oldLine)} | | - | ${code}`);
|
||||
oldLine++;
|
||||
} else if (changeType === "+") {
|
||||
output.push(`| | ${padNum(newLine)} | + | ${code}`);
|
||||
newLine++;
|
||||
} else if (changeType === " " || changeType === "\\") {
|
||||
if (changeType === "\\") {
|
||||
output.push(line);
|
||||
} else {
|
||||
output.push(`| ${padNum(oldLine)} | ${padNum(newLine)} | | ${code}`);
|
||||
oldLine++;
|
||||
newLine++;
|
||||
}
|
||||
} else {
|
||||
output.push(line);
|
||||
}
|
||||
}
|
||||
output.push("");
|
||||
}
|
||||
return output.join("\n");
|
||||
}
|
||||
function padNum(n) {
|
||||
return n.toString().padStart(4, " ");
|
||||
}
|
||||
var CheckoutPr = type({
|
||||
pull_number: type.number.describe("the pull request number to checkout")
|
||||
});
|
||||
@@ -123023,10 +123104,10 @@ async function checkoutPrBranch(params) {
|
||||
const remoteName = `pr-${pullNumber}`;
|
||||
const forkUrl = `https://x-access-token:${token}@github.com/${headRepo.full_name}.git`;
|
||||
try {
|
||||
$("git", ["remote", "add", remoteName, forkUrl]);
|
||||
$("git", ["remote", "add", remoteName, forkUrl], { log: false });
|
||||
log.debug(`\u{1F4CC} added remote '${remoteName}' for fork ${headRepo.full_name}`);
|
||||
} catch {
|
||||
$("git", ["remote", "set-url", remoteName, forkUrl]);
|
||||
$("git", ["remote", "set-url", remoteName, forkUrl], { log: false });
|
||||
log.debug(`\u{1F4CC} updated remote '${remoteName}' for fork ${headRepo.full_name}`);
|
||||
}
|
||||
$("git", ["config", `branch.${localBranch}.pushRemote`, remoteName]);
|
||||
@@ -123046,7 +123127,7 @@ async function checkoutPrBranch(params) {
|
||||
function CheckoutPrTool(ctx) {
|
||||
return tool({
|
||||
name: "checkout_pr",
|
||||
description: "Checkout a pull request branch locally. This fetches the PR branch and sets up push configuration for fork PRs. Use this when you need to work on an existing PR.",
|
||||
description: "Checkout a pull request branch locally. This fetches the PR branch and sets up push configuration for fork PRs. Returns diffPath pointing to the formatted diff file.",
|
||||
parameters: CheckoutPr,
|
||||
execute: execute(async ({ pull_number }) => {
|
||||
const result = await checkoutPrBranch({
|
||||
@@ -123066,12 +123147,25 @@ function CheckoutPrTool(ctx) {
|
||||
if (!headRepo) {
|
||||
throw new Error(`PR #${pull_number} source repository was deleted`);
|
||||
}
|
||||
const diffResponse = await ctx.octokit.rest.pulls.get({
|
||||
const filesResponse = await ctx.octokit.rest.pulls.listFiles({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
mediaType: { format: "diff" }
|
||||
per_page: 100
|
||||
});
|
||||
const diffContent = formatFilesWithLineNumbers(filesResponse.data);
|
||||
const diffPreview = diffContent.split("\n").slice(0, 100).join("\n");
|
||||
log.debug(`formatted diff preview (first 100 lines):
|
||||
${diffPreview}`);
|
||||
const tempDir = process.env.PULLFROG_TEMP_DIR;
|
||||
if (!tempDir) {
|
||||
throw new Error(
|
||||
"PULLFROG_TEMP_DIR not set - checkout_pr must run in pullfrog action context"
|
||||
);
|
||||
}
|
||||
const diffPath = join8(tempDir, `pr-${pull_number}.diff`);
|
||||
writeFileSync4(diffPath, diffContent);
|
||||
log.debug(`wrote diff to ${diffPath} (${diffContent.length} bytes)`);
|
||||
return {
|
||||
success: true,
|
||||
number: pr.data.number,
|
||||
@@ -123082,7 +123176,7 @@ function CheckoutPrTool(ctx) {
|
||||
maintainerCanModify: pr.data.maintainer_can_modify,
|
||||
url: pr.data.html_url,
|
||||
headRepo: headRepo.full_name,
|
||||
diff: diffResponse.data
|
||||
diffPath
|
||||
};
|
||||
})
|
||||
});
|
||||
@@ -123191,7 +123285,7 @@ function DebugShellCommandTool(_ctx) {
|
||||
|
||||
// prep/installNodeDependencies.ts
|
||||
import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
|
||||
import { join as join8 } from "node:path";
|
||||
import { join as join9 } from "node:path";
|
||||
|
||||
// node_modules/.pnpm/package-manager-detector@1.6.0/node_modules/package-manager-detector/dist/commands.mjs
|
||||
function dashDashArg(agent2, agentCommand) {
|
||||
@@ -123503,7 +123597,7 @@ async function isCommandAvailable(command) {
|
||||
return result.exitCode === 0;
|
||||
}
|
||||
function getPackageManagerFromPackageJson() {
|
||||
const packageJsonPath = join8(process.cwd(), "package.json");
|
||||
const packageJsonPath = join9(process.cwd(), "package.json");
|
||||
try {
|
||||
const content = readFileSync2(packageJsonPath, "utf-8");
|
||||
const pkg = JSON.parse(content);
|
||||
@@ -123534,7 +123628,7 @@ async function installPackageManager(name, installSpec) {
|
||||
return result.stderr || `failed to install ${name}`;
|
||||
}
|
||||
if (name === "deno") {
|
||||
const denoPath = join8(process.env.HOME || "", ".deno", "bin");
|
||||
const denoPath = join9(process.env.HOME || "", ".deno", "bin");
|
||||
process.env.PATH = `${denoPath}:${process.env.PATH}`;
|
||||
}
|
||||
log.info(`\u2705 installed ${name}`);
|
||||
@@ -123543,7 +123637,7 @@ async function installPackageManager(name, installSpec) {
|
||||
var installNodeDependencies = {
|
||||
name: "installNodeDependencies",
|
||||
shouldRun: () => {
|
||||
const packageJsonPath = join8(process.cwd(), "package.json");
|
||||
const packageJsonPath = join9(process.cwd(), "package.json");
|
||||
return existsSync3(packageJsonPath);
|
||||
},
|
||||
run: async () => {
|
||||
@@ -123606,7 +123700,7 @@ var installNodeDependencies = {
|
||||
|
||||
// prep/installPythonDependencies.ts
|
||||
import { existsSync as existsSync4 } from "node:fs";
|
||||
import { join as join9 } from "node:path";
|
||||
import { join as join10 } from "node:path";
|
||||
var PYTHON_CONFIGS = [
|
||||
{
|
||||
file: "requirements.txt",
|
||||
@@ -123678,11 +123772,11 @@ var installPythonDependencies = {
|
||||
return false;
|
||||
}
|
||||
const cwd2 = process.cwd();
|
||||
return PYTHON_CONFIGS.some((config2) => existsSync4(join9(cwd2, config2.file)));
|
||||
return PYTHON_CONFIGS.some((config2) => existsSync4(join10(cwd2, config2.file)));
|
||||
},
|
||||
run: async () => {
|
||||
const cwd2 = process.cwd();
|
||||
const config2 = PYTHON_CONFIGS.find((c) => existsSync4(join9(cwd2, c.file)));
|
||||
const config2 = PYTHON_CONFIGS.find((c) => existsSync4(join10(cwd2, c.file)));
|
||||
if (!config2) {
|
||||
return {
|
||||
language: "python",
|
||||
@@ -124175,11 +124269,7 @@ function GetIssueCommentsTool(ctx) {
|
||||
id: comment.id,
|
||||
body: comment.body,
|
||||
user: comment.user?.login,
|
||||
created_at: comment.created_at,
|
||||
updated_at: comment.updated_at,
|
||||
html_url: comment.html_url,
|
||||
author_association: comment.author_association,
|
||||
reactions: comment.reactions
|
||||
author_association: comment.author_association
|
||||
})),
|
||||
count: comments.length
|
||||
};
|
||||
@@ -124352,7 +124442,7 @@ function buildPrBodyWithFooter(ctx, body) {
|
||||
const bodyWithoutFooter = stripExistingFooter(body);
|
||||
return `${bodyWithoutFooter}${footer}`;
|
||||
}
|
||||
function PullRequestTool(ctx) {
|
||||
function CreatePullRequestTool(ctx) {
|
||||
return tool({
|
||||
name: "create_pull_request",
|
||||
description: "Create a pull request from the current branch",
|
||||
@@ -124426,209 +124516,98 @@ function PullRequestInfoTool(ctx) {
|
||||
}
|
||||
|
||||
// mcp/review.ts
|
||||
var ADD_PULL_REQUEST_REVIEW_THREAD = `
|
||||
mutation AddPullRequestReviewThread($pullRequestReviewId: ID!, $path: String!, $line: Int!, $body: String!, $side: DiffSide) {
|
||||
addPullRequestReviewThread(input: {
|
||||
pullRequestReviewId: $pullRequestReviewId,
|
||||
path: $path,
|
||||
line: $line,
|
||||
body: $body,
|
||||
side: $side
|
||||
}) {
|
||||
thread {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
async function findPendingReview(ctx, pull_number) {
|
||||
const reviews = await ctx.octokit.rest.pulls.listReviews({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
per_page: 100
|
||||
});
|
||||
const pendingReview = reviews.data.find((r) => r.state === "PENDING");
|
||||
if (pendingReview) {
|
||||
return { id: pendingReview.id, node_id: pendingReview.node_id };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
var StartReview = type({
|
||||
pull_number: type.number.describe("The pull request number to review")
|
||||
});
|
||||
function StartReviewTool(ctx) {
|
||||
return tool({
|
||||
name: "start_review",
|
||||
description: "Start a new review session for a pull request. Creates a pending review on GitHub. Must be called before add_review_comment.",
|
||||
parameters: StartReview,
|
||||
execute: execute(async ({ pull_number }) => {
|
||||
if (ctx.toolState.review) {
|
||||
throw new Error(
|
||||
`Review session already in progress. Call submit_review first to finish it.`
|
||||
);
|
||||
}
|
||||
const pr = await ctx.octokit.rest.pulls.get({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number
|
||||
});
|
||||
let reviewId;
|
||||
let reviewNodeId;
|
||||
log.debug(`creating pending review for PR #${pull_number}...`);
|
||||
try {
|
||||
const result = await ctx.octokit.rest.pulls.createReview({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
commit_id: pr.data.head.sha
|
||||
// no 'event' = PENDING review
|
||||
});
|
||||
reviewId = result.data.id;
|
||||
reviewNodeId = result.data.node_id;
|
||||
log.debug(`created new pending review: id=${reviewId}`);
|
||||
} catch (error41) {
|
||||
const errorMessage = error41 instanceof Error ? error41.message : String(error41);
|
||||
log.debug(`createReview failed: ${errorMessage}`);
|
||||
if (errorMessage.includes("pending review")) {
|
||||
log.debug(`pending review already exists, fetching existing review...`);
|
||||
const existing = await findPendingReview(ctx, pull_number);
|
||||
if (!existing) {
|
||||
throw new Error(
|
||||
"GitHub says a pending review exists but we couldn't find it. Try again or check the PR reviews."
|
||||
);
|
||||
}
|
||||
reviewId = existing.id;
|
||||
reviewNodeId = existing.node_id;
|
||||
log.debug(`reusing existing pending review: id=${reviewId}`);
|
||||
} else {
|
||||
throw error41;
|
||||
}
|
||||
}
|
||||
ctx.toolState.prNumber = pull_number;
|
||||
ctx.toolState.review = {
|
||||
nodeId: reviewNodeId,
|
||||
id: reviewId
|
||||
};
|
||||
log.debug(`review session started: id=${reviewId}, nodeId=${reviewNodeId}`);
|
||||
return {
|
||||
message: `Review session started for PR #${pull_number}.`,
|
||||
instructions: "Analyze: What does this PR change? Is the approach sound? What bugs, edge cases, or security issues exist? Before commenting: Skip nitpicks unless requested. Only comment if the codebase maintainer would care."
|
||||
};
|
||||
})
|
||||
});
|
||||
}
|
||||
var AddReviewComment = type({
|
||||
path: type.string.describe("The file path to comment on (relative to repo root)"),
|
||||
line: type.number.describe(
|
||||
"The line number in the file (use line numbers from the diff - the NEW file line number)"
|
||||
),
|
||||
body: type.string.describe("The comment text for this specific line"),
|
||||
side: type.enumerated("LEFT", "RIGHT").describe("Side of the diff: LEFT (old code) or RIGHT (new code). Defaults to RIGHT.").optional()
|
||||
});
|
||||
function AddReviewCommentTool(ctx) {
|
||||
return tool({
|
||||
name: "add_review_comment",
|
||||
description: "Add a comment to the current review session. Must call start_review first. Comments are stored in draft state until submit_review is called.",
|
||||
parameters: AddReviewComment,
|
||||
execute: execute(async ({ path: path4, line, body, side }) => {
|
||||
if (!ctx.toolState.review) {
|
||||
throw new Error("No review session started. Call start_review first.");
|
||||
}
|
||||
log.debug(
|
||||
`adding review comment: reviewNodeId=${ctx.toolState.review.nodeId}, path=${path4}, line=${line}, side=${side || "RIGHT"}`
|
||||
);
|
||||
const result = await ctx.octokit.graphql(
|
||||
ADD_PULL_REQUEST_REVIEW_THREAD,
|
||||
{
|
||||
pullRequestReviewId: ctx.toolState.review.nodeId,
|
||||
path: path4,
|
||||
line,
|
||||
body,
|
||||
side: side || "RIGHT"
|
||||
}
|
||||
);
|
||||
log.debug(`review comment added: threadId=${result.addPullRequestReviewThread.thread.id}`);
|
||||
return {
|
||||
success: true,
|
||||
message: `Comment added to ${path4}:${line}`,
|
||||
threadId: result.addPullRequestReviewThread.thread.id
|
||||
};
|
||||
})
|
||||
});
|
||||
}
|
||||
var SubmitReview = type({
|
||||
body: type.string.describe(
|
||||
"Review body text. Typically 1-3 sentences with high-level overview and urgency level. Action links are auto-appended."
|
||||
).optional()
|
||||
});
|
||||
function SubmitReviewTool(ctx) {
|
||||
return tool({
|
||||
name: "submit_review",
|
||||
description: "Submit the current review session. All comments added via add_review_comment will be published. Must call start_review first.",
|
||||
parameters: SubmitReview,
|
||||
execute: execute(async ({ body }) => {
|
||||
if (!ctx.toolState.review) {
|
||||
throw new Error("No review session started. Call start_review first.");
|
||||
}
|
||||
if (ctx.toolState.prNumber === void 0) {
|
||||
throw new Error("No PR context. Call checkout_pr or start_review first.");
|
||||
}
|
||||
const reviewId = ctx.toolState.review.id;
|
||||
log.debug(
|
||||
`submitting review: id=${reviewId}, nodeId=${ctx.toolState.review.nodeId}, prNumber=${ctx.toolState.prNumber}`
|
||||
);
|
||||
const apiUrl = process.env.API_URL || "https://pullfrog.com";
|
||||
const fixAllUrl = `${apiUrl}/trigger/${ctx.owner}/${ctx.name}/${ctx.toolState.prNumber}?action=fix&review_id=${reviewId}`;
|
||||
const fixApprovedUrl = `${apiUrl}/trigger/${ctx.owner}/${ctx.name}/${ctx.toolState.prNumber}?action=fix-approved&review_id=${reviewId}`;
|
||||
const footer = buildPullfrogFooter({
|
||||
workflowRun: { owner: ctx.owner, repo: ctx.name, runId: ctx.runId, jobId: ctx.jobId },
|
||||
customParts: [`[Fix all \u2794](${fixAllUrl})`, `[Fix \u{1F44D}s \u2794](${fixApprovedUrl})`]
|
||||
});
|
||||
const bodyWithFooter = (body || "") + footer;
|
||||
const result = await ctx.octokit.rest.pulls.submitReview({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number: ctx.toolState.prNumber,
|
||||
review_id: reviewId,
|
||||
event: "COMMENT",
|
||||
body: bodyWithFooter
|
||||
});
|
||||
log.debug(`review submitted: reviewId=${result.data.id}, state=${result.data.state}`);
|
||||
delete ctx.toolState.review;
|
||||
await deleteProgressComment(ctx);
|
||||
return {
|
||||
success: true,
|
||||
reviewId: result.data.id,
|
||||
html_url: result.data.html_url,
|
||||
state: result.data.state
|
||||
};
|
||||
})
|
||||
});
|
||||
}
|
||||
var Review = type({
|
||||
var CreatePullRequestReview = type({
|
||||
pull_number: type.number.describe("The pull request number to review"),
|
||||
body: type.string.describe(
|
||||
"1-2 sentence high-level summary ONLY. Include urgency level and critical callouts (e.g., API key leak). ALL specific feedback MUST go in 'comments' array instead."
|
||||
"1-2 sentence high-level summary with urgency level, critical callouts, and feedback about code outside the diff. Specific feedback on diff lines goes in 'comments' array."
|
||||
).optional(),
|
||||
commit_id: type.string.describe("Optional SHA of the commit being reviewed. Defaults to latest.").optional(),
|
||||
comments: type({
|
||||
path: type.string.describe("The file path to comment on (relative to repo root)"),
|
||||
line: type.number.describe(
|
||||
"The line number in the file (use line numbers from the diff - usually the RIGHT side/new code)"
|
||||
"Line number from the diff. Each code line shows 'OLD | NEW | TYPE | CODE'. Use the NEW column (second column)."
|
||||
),
|
||||
side: type.enumerated("LEFT", "RIGHT").describe(
|
||||
"Side of the diff: LEFT (old code) or RIGHT (new code). Defaults to RIGHT if not provided."
|
||||
"Side of the diff: LEFT (old code, lines starting with -) or RIGHT (new code, lines starting with + or unchanged). Defaults to RIGHT."
|
||||
).optional(),
|
||||
body: type.string.describe(
|
||||
"The comment text for this specific line. For issues appearing multiple times, comment on the first occurrence and reference others."
|
||||
),
|
||||
start_line: type.number.describe("Start line for multi-line comments (optional, for commenting on ranges)").optional()
|
||||
}).array().describe(
|
||||
// FORK PR NOTE: checkout_pr returns the diff via GitHub API - use that for line numbers
|
||||
"PRIMARY location for ALL feedback. 95%+ of review content should be here. Use the diff returned from checkout_pr to find correct line numbers (RIGHT side for new code, LEFT for old)."
|
||||
"Inline comments on lines within diff hunks. Feedback about code outside the diff goes in 'body' instead."
|
||||
).optional()
|
||||
});
|
||||
function CreatePullRequestReviewTool(ctx) {
|
||||
return tool({
|
||||
name: "create_pull_request_review",
|
||||
description: "Submit a review for an existing pull request. IMPORTANT: 95%+ of feedback should be in 'comments' array with file paths and line numbers. Only use 'body' for a 1-2 sentence summary with urgency and critical callouts.",
|
||||
parameters: CreatePullRequestReview,
|
||||
execute: execute(async ({ pull_number, body, commit_id, comments = [] }) => {
|
||||
ctx.toolState.prNumber = pull_number;
|
||||
const pr = await ctx.octokit.rest.pulls.get({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number
|
||||
});
|
||||
const params = {
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
event: "COMMENT"
|
||||
};
|
||||
if (body) params.body = body;
|
||||
if (commit_id) {
|
||||
params.commit_id = commit_id;
|
||||
} else {
|
||||
params.commit_id = pr.data.head.sha;
|
||||
}
|
||||
if (comments.length > 0) {
|
||||
params.comments = comments.map((comment) => {
|
||||
const reviewComment = {
|
||||
...comment
|
||||
};
|
||||
reviewComment.side = comment.side || "RIGHT";
|
||||
if (comment.start_line) {
|
||||
reviewComment.start_line = comment.start_line;
|
||||
reviewComment.start_side = comment.side || "RIGHT";
|
||||
}
|
||||
return reviewComment;
|
||||
});
|
||||
}
|
||||
const result = await ctx.octokit.rest.pulls.createReview(params);
|
||||
log.debug(`createReview response: ${JSON.stringify(result.data)}`);
|
||||
if (!result.data.id) {
|
||||
throw new Error(`createReview returned invalid data: ${JSON.stringify(result.data)}`);
|
||||
}
|
||||
const reviewId = result.data.id;
|
||||
const apiUrl = process.env.API_URL || "https://pullfrog.com";
|
||||
const fixAllUrl = `${apiUrl}/trigger/${ctx.owner}/${ctx.name}/${pull_number}?action=fix&review_id=${reviewId}`;
|
||||
const fixApprovedUrl = `${apiUrl}/trigger/${ctx.owner}/${ctx.name}/${pull_number}?action=fix-approved&review_id=${reviewId}`;
|
||||
const footer = buildPullfrogFooter({
|
||||
workflowRun: { owner: ctx.owner, repo: ctx.name, runId: ctx.runId, jobId: ctx.jobId },
|
||||
customParts: [`[Fix all \u2794](${fixAllUrl})`, `[Fix \u{1F44D}s \u2794](${fixApprovedUrl})`]
|
||||
});
|
||||
const updatedBody = (body || "") + footer;
|
||||
await ctx.octokit.rest.pulls.updateReview({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
review_id: reviewId,
|
||||
body: updatedBody
|
||||
});
|
||||
await deleteProgressComment(ctx);
|
||||
return {
|
||||
success: true,
|
||||
reviewId,
|
||||
html_url: result.data.html_url,
|
||||
state: result.data.state,
|
||||
user: result.data.user?.login,
|
||||
submitted_at: result.data.submitted_at
|
||||
};
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// mcp/reviewComments.ts
|
||||
var REVIEW_THREADS_QUERY = `
|
||||
@@ -124839,11 +124818,8 @@ async function startMcpHttpServer(ctx) {
|
||||
IssueInfoTool(ctx),
|
||||
GetIssueCommentsTool(ctx),
|
||||
GetIssueEventsTool(ctx),
|
||||
PullRequestTool(ctx),
|
||||
// ReviewTool(ctx),
|
||||
StartReviewTool(ctx),
|
||||
AddReviewCommentTool(ctx),
|
||||
SubmitReviewTool(ctx),
|
||||
CreatePullRequestTool(ctx),
|
||||
CreatePullRequestReviewTool(ctx),
|
||||
PullRequestInfoTool(ctx),
|
||||
CheckoutPrTool(ctx),
|
||||
GetReviewCommentsTool(ctx),
|
||||
@@ -125248,7 +125224,7 @@ function resolveAgent({
|
||||
return agent2;
|
||||
}
|
||||
async function createTempDirectory() {
|
||||
const sharedTempDir = await mkdtemp2(join10(tmpdir2(), "pullfrog-"));
|
||||
const sharedTempDir = await mkdtemp2(join11(tmpdir2(), "pullfrog-"));
|
||||
process.env.PULLFROG_TEMP_DIR = sharedTempDir;
|
||||
log.info(`\u{1F4C2} PULLFROG_TEMP_DIR has been created at ${sharedTempDir}`);
|
||||
return sharedTempDir;
|
||||
|
||||
+98
-10
@@ -1,10 +1,85 @@
|
||||
import type { Octokit } from "@octokit/rest";
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { Octokit, RestEndpointMethodTypes } from "@octokit/rest";
|
||||
import { type } from "arktype";
|
||||
import type { ToolContext } from "../main.ts";
|
||||
import { log } from "../utils/cli.ts";
|
||||
import { $ } from "../utils/shell.ts";
|
||||
import { execute, tool } from "./shared.ts";
|
||||
|
||||
type PullFile = RestEndpointMethodTypes["pulls"]["listFiles"]["response"]["data"][number];
|
||||
|
||||
/**
|
||||
* formats PR files with explicit line numbers for each code line.
|
||||
* preserves all original diff info (file headers, hunk headers) and adds:
|
||||
* | OLD | NEW | TYPE | code
|
||||
*/
|
||||
export function formatFilesWithLineNumbers(files: PullFile[]): string {
|
||||
const output: string[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
// file header
|
||||
output.push(`diff --git a/${file.filename} b/${file.filename}`);
|
||||
output.push(`--- a/${file.filename}`);
|
||||
output.push(`+++ b/${file.filename}`);
|
||||
|
||||
if (!file.patch) {
|
||||
output.push("(binary file or no changes)");
|
||||
output.push("");
|
||||
continue;
|
||||
}
|
||||
|
||||
// parse and format the patch with line numbers
|
||||
const lines = file.patch.split("\n");
|
||||
let oldLine = 0;
|
||||
let newLine = 0;
|
||||
|
||||
for (const line of lines) {
|
||||
// hunk header: @@ -OLD,COUNT +NEW,COUNT @@ optional context
|
||||
const hunkMatch = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
||||
if (hunkMatch) {
|
||||
oldLine = parseInt(hunkMatch[1], 10);
|
||||
newLine = parseInt(hunkMatch[2], 10);
|
||||
output.push(line); // pass through unchanged
|
||||
continue;
|
||||
}
|
||||
|
||||
// code lines within hunks
|
||||
const changeType = line[0] || " ";
|
||||
const code = line.slice(1);
|
||||
|
||||
if (changeType === "-") {
|
||||
// removed line: show old line number, no new line number
|
||||
output.push(`| ${padNum(oldLine)} | | - | ${code}`);
|
||||
oldLine++;
|
||||
} else if (changeType === "+") {
|
||||
// added line: no old line number, show new line number
|
||||
output.push(`| | ${padNum(newLine)} | + | ${code}`);
|
||||
newLine++;
|
||||
} else if (changeType === " " || changeType === "\\") {
|
||||
// context line or "\ No newline at end of file"
|
||||
if (changeType === "\\") {
|
||||
output.push(line); // pass through as-is
|
||||
} else {
|
||||
output.push(`| ${padNum(oldLine)} | ${padNum(newLine)} | | ${code}`);
|
||||
oldLine++;
|
||||
newLine++;
|
||||
}
|
||||
} else {
|
||||
// unknown line type, pass through
|
||||
output.push(line);
|
||||
}
|
||||
}
|
||||
output.push(""); // blank line between files
|
||||
}
|
||||
|
||||
return output.join("\n");
|
||||
}
|
||||
|
||||
function padNum(n: number): string {
|
||||
return n.toString().padStart(4, " ");
|
||||
}
|
||||
|
||||
export const CheckoutPr = type({
|
||||
pull_number: type.number.describe("the pull request number to checkout"),
|
||||
});
|
||||
@@ -19,7 +94,7 @@ export type CheckoutPrResult = {
|
||||
maintainerCanModify: boolean;
|
||||
url: string;
|
||||
headRepo: string;
|
||||
diff: string;
|
||||
diffPath: string;
|
||||
};
|
||||
|
||||
interface CheckoutPrBranchParams {
|
||||
@@ -104,13 +179,13 @@ export async function checkoutPrBranch(
|
||||
const remoteName = `pr-${pullNumber}`;
|
||||
const forkUrl = `https://x-access-token:${token}@github.com/${headRepo.full_name}.git`;
|
||||
|
||||
// add fork as a named remote (ignore error if already exists)
|
||||
// add fork as a named remote (suppress logging to avoid "error: remote already exists" spam)
|
||||
try {
|
||||
$("git", ["remote", "add", remoteName, forkUrl]);
|
||||
$("git", ["remote", "add", remoteName, forkUrl], { log: false });
|
||||
log.debug(`📌 added remote '${remoteName}' for fork ${headRepo.full_name}`);
|
||||
} catch {
|
||||
// remote already exists, update its URL
|
||||
$("git", ["remote", "set-url", remoteName, forkUrl]);
|
||||
$("git", ["remote", "set-url", remoteName, forkUrl], { log: false });
|
||||
log.debug(`📌 updated remote '${remoteName}' for fork ${headRepo.full_name}`);
|
||||
}
|
||||
|
||||
@@ -140,7 +215,8 @@ export function CheckoutPrTool(ctx: ToolContext) {
|
||||
return tool({
|
||||
name: "checkout_pr",
|
||||
description:
|
||||
"Checkout a pull request branch locally. This fetches the PR branch and sets up push configuration for fork PRs. Use this when you need to work on an existing PR.",
|
||||
"Checkout a pull request branch locally. This fetches the PR branch and sets up push configuration for fork PRs. " +
|
||||
"Returns diffPath pointing to the formatted diff file.",
|
||||
parameters: CheckoutPr,
|
||||
execute: execute(async ({ pull_number }) => {
|
||||
const result = await checkoutPrBranch({
|
||||
@@ -166,13 +242,25 @@ export function CheckoutPrTool(ctx: ToolContext) {
|
||||
throw new Error(`PR #${pull_number} source repository was deleted`);
|
||||
}
|
||||
|
||||
// fetch PR diff via API (authoritative source - not affected by main advancing)
|
||||
const diffResponse = await ctx.octokit.rest.pulls.get({
|
||||
// fetch PR files and format with line numbers
|
||||
const filesResponse = await ctx.octokit.rest.pulls.listFiles({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
mediaType: { format: "diff" },
|
||||
per_page: 100,
|
||||
});
|
||||
const diffContent = formatFilesWithLineNumbers(filesResponse.data);
|
||||
const diffPreview = diffContent.split("\n").slice(0, 100).join("\n");
|
||||
log.debug(`formatted diff preview (first 100 lines):\n${diffPreview}`);
|
||||
const tempDir = process.env.PULLFROG_TEMP_DIR;
|
||||
if (!tempDir) {
|
||||
throw new Error(
|
||||
"PULLFROG_TEMP_DIR not set - checkout_pr must run in pullfrog action context"
|
||||
);
|
||||
}
|
||||
const diffPath = join(tempDir, `pr-${pull_number}.diff`);
|
||||
writeFileSync(diffPath, diffContent);
|
||||
log.debug(`wrote diff to ${diffPath} (${diffContent.length} bytes)`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
@@ -184,7 +272,7 @@ export function CheckoutPrTool(ctx: ToolContext) {
|
||||
maintainerCanModify: pr.data.maintainer_can_modify,
|
||||
url: pr.data.html_url,
|
||||
headRepo: headRepo.full_name,
|
||||
diff: diffResponse.data as unknown as string,
|
||||
diffPath,
|
||||
} satisfies CheckoutPrResult;
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -28,11 +28,7 @@ export function GetIssueCommentsTool(ctx: ToolContext) {
|
||||
id: comment.id,
|
||||
body: comment.body,
|
||||
user: comment.user?.login,
|
||||
created_at: comment.created_at,
|
||||
updated_at: comment.updated_at,
|
||||
html_url: comment.html_url,
|
||||
author_association: comment.author_association,
|
||||
reactions: comment.reactions,
|
||||
})),
|
||||
count: comments.length,
|
||||
};
|
||||
|
||||
@@ -29,7 +29,7 @@ function buildPrBodyWithFooter(ctx: ToolContext, body: string): string {
|
||||
return `${bodyWithoutFooter}${footer}`;
|
||||
}
|
||||
|
||||
export function PullRequestTool(ctx: ToolContext) {
|
||||
export function CreatePullRequestTool(ctx: ToolContext) {
|
||||
return tool({
|
||||
name: "create_pull_request",
|
||||
description: "Create a pull request from the current branch",
|
||||
|
||||
+192
-142
@@ -6,16 +6,149 @@ import { log } from "../utils/cli.ts";
|
||||
import { deleteProgressComment } from "./comment.ts";
|
||||
import { execute, tool } from "./shared.ts";
|
||||
|
||||
// one-shot review tool
|
||||
export const CreatePullRequestReview = type({
|
||||
pull_number: type.number.describe("The pull request number to review"),
|
||||
body: type.string
|
||||
.describe(
|
||||
"1-2 sentence high-level summary with urgency level, critical callouts, and feedback about code outside the diff. Specific feedback on diff lines goes in 'comments' array."
|
||||
)
|
||||
.optional(),
|
||||
commit_id: type.string
|
||||
.describe("Optional SHA of the commit being reviewed. Defaults to latest.")
|
||||
.optional(),
|
||||
comments: type({
|
||||
path: type.string.describe("The file path to comment on (relative to repo root)"),
|
||||
line: type.number.describe(
|
||||
"Line number from the diff. Each code line shows 'OLD | NEW | TYPE | CODE'. Use the NEW column (second column)."
|
||||
),
|
||||
side: type
|
||||
.enumerated("LEFT", "RIGHT")
|
||||
.describe(
|
||||
"Side of the diff: LEFT (old code, lines starting with -) or RIGHT (new code, lines starting with + or unchanged). Defaults to RIGHT."
|
||||
)
|
||||
.optional(),
|
||||
body: type.string.describe(
|
||||
"The comment text for this specific line. For issues appearing multiple times, comment on the first occurrence and reference others."
|
||||
),
|
||||
start_line: type.number
|
||||
.describe("Start line for multi-line comments (optional, for commenting on ranges)")
|
||||
.optional(),
|
||||
})
|
||||
.array()
|
||||
.describe(
|
||||
"Inline comments on lines within diff hunks. Feedback about code outside the diff goes in 'body' instead."
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export function CreatePullRequestReviewTool(ctx: ToolContext) {
|
||||
return tool({
|
||||
name: "create_pull_request_review",
|
||||
description:
|
||||
"Submit a review for an existing pull request. " +
|
||||
"IMPORTANT: 95%+ of feedback should be in 'comments' array with file paths and line numbers. " +
|
||||
"Only use 'body' for a 1-2 sentence summary with urgency and critical callouts.",
|
||||
parameters: CreatePullRequestReview,
|
||||
execute: execute(async ({ pull_number, body, commit_id, comments = [] }) => {
|
||||
// set PR context
|
||||
ctx.toolState.prNumber = pull_number;
|
||||
|
||||
// get the PR to determine the head commit if commit_id not provided
|
||||
const pr = await ctx.octokit.rest.pulls.get({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
});
|
||||
|
||||
// compose the request
|
||||
const params: RestEndpointMethodTypes["pulls"]["createReview"]["parameters"] = {
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
event: "COMMENT",
|
||||
};
|
||||
if (body) params.body = body;
|
||||
if (commit_id) {
|
||||
params.commit_id = commit_id;
|
||||
} else {
|
||||
params.commit_id = pr.data.head.sha;
|
||||
}
|
||||
if (comments.length > 0) {
|
||||
type ReviewComment = (typeof params.comments & {})[number];
|
||||
// convert comments to the format expected by GitHub API
|
||||
params.comments = comments.map((comment) => {
|
||||
const reviewComment: ReviewComment = {
|
||||
...comment,
|
||||
};
|
||||
reviewComment.side = comment.side || "RIGHT";
|
||||
if (comment.start_line) {
|
||||
reviewComment.start_line = comment.start_line;
|
||||
reviewComment.start_side = comment.side || "RIGHT";
|
||||
}
|
||||
return reviewComment;
|
||||
});
|
||||
}
|
||||
const result = await ctx.octokit.rest.pulls.createReview(params);
|
||||
log.debug(`createReview response: ${JSON.stringify(result.data)}`);
|
||||
if (!result.data.id) {
|
||||
throw new Error(`createReview returned invalid data: ${JSON.stringify(result.data)}`);
|
||||
}
|
||||
const reviewId = result.data.id;
|
||||
|
||||
// build quick links footer and update the review body
|
||||
const apiUrl = process.env.API_URL || "https://pullfrog.com";
|
||||
const fixAllUrl = `${apiUrl}/trigger/${ctx.owner}/${ctx.name}/${pull_number}?action=fix&review_id=${reviewId}`;
|
||||
const fixApprovedUrl = `${apiUrl}/trigger/${ctx.owner}/${ctx.name}/${pull_number}?action=fix-approved&review_id=${reviewId}`;
|
||||
|
||||
const footer = buildPullfrogFooter({
|
||||
workflowRun: { owner: ctx.owner, repo: ctx.name, runId: ctx.runId, jobId: ctx.jobId },
|
||||
customParts: [`[Fix all ➔](${fixAllUrl})`, `[Fix 👍s ➔](${fixApprovedUrl})`],
|
||||
});
|
||||
|
||||
const updatedBody = (body || "") + footer;
|
||||
|
||||
// update the review with the footer
|
||||
await ctx.octokit.rest.pulls.updateReview({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
review_id: reviewId,
|
||||
body: updatedBody,
|
||||
});
|
||||
|
||||
await deleteProgressComment(ctx);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
reviewId,
|
||||
html_url: result.data.html_url,
|
||||
state: result.data.state,
|
||||
user: result.data.user?.login,
|
||||
submitted_at: result.data.submitted_at,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// COMMENTED OUT: Three-step review flow (start_review, add_review_comment, submit_review)
|
||||
// This approach used GraphQL to add comments to a pending review one-by-one,
|
||||
// but GitHub's API was returning null for valid lines. Keeping for reference.
|
||||
// =============================================================================
|
||||
|
||||
/*
|
||||
// graphql mutation to add a comment thread to a pending review
|
||||
// note: REST API doesn't support adding comments to an existing pending review
|
||||
const ADD_PULL_REQUEST_REVIEW_THREAD = `
|
||||
mutation AddPullRequestReviewThread($pullRequestReviewId: ID!, $path: String!, $line: Int!, $body: String!, $side: DiffSide) {
|
||||
mutation AddPullRequestReviewThread($pullRequestReviewId: ID!, $path: String!, $line: Int!, $body: String!, $side: DiffSide, $subjectType: PullRequestReviewThreadSubjectType) {
|
||||
addPullRequestReviewThread(input: {
|
||||
pullRequestReviewId: $pullRequestReviewId,
|
||||
path: $path,
|
||||
line: $line,
|
||||
body: $body,
|
||||
side: $side
|
||||
side: $side,
|
||||
subjectType: $subjectType
|
||||
}) {
|
||||
thread {
|
||||
id
|
||||
@@ -92,6 +225,13 @@ export function StartReviewTool(ctx: ToolContext) {
|
||||
commit_id: pr.data.head.sha,
|
||||
// no 'event' = PENDING review
|
||||
});
|
||||
log.debug(`createReview response: ${JSON.stringify(result.data)}`);
|
||||
if (!result.data.id || !result.data.node_id) {
|
||||
log.debug(result);
|
||||
throw new Error(
|
||||
`createReview returned invalid data: id=${result.data.id}, node_id=${result.data.node_id}`
|
||||
);
|
||||
}
|
||||
reviewId = result.data.id;
|
||||
reviewNodeId = result.data.node_id;
|
||||
log.debug(`created new pending review: id=${reviewId}`);
|
||||
@@ -126,10 +266,7 @@ export function StartReviewTool(ctx: ToolContext) {
|
||||
log.debug(`review session started: id=${reviewId}, nodeId=${reviewNodeId}`);
|
||||
|
||||
return {
|
||||
message: `Review session started for PR #${pull_number}.`,
|
||||
instructions:
|
||||
"Analyze: What does this PR change? Is the approach sound? What bugs, edge cases, or security issues exist? " +
|
||||
"Before commenting: Skip nitpicks unless requested. Only comment if the codebase maintainer would care.",
|
||||
message: `Review session started for PR #${pull_number}. Add comments with add_review_comment, then submit with submit_review.`,
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -160,28 +297,59 @@ export function AddReviewCommentTool(ctx: ToolContext) {
|
||||
throw new Error("No review session started. Call start_review first.");
|
||||
}
|
||||
|
||||
const reviewNodeId = ctx.toolState.review.nodeId;
|
||||
log.debug(
|
||||
`adding review comment: reviewNodeId=${ctx.toolState.review.nodeId}, path=${path}, line=${line}, side=${side || "RIGHT"}`
|
||||
`adding review comment: reviewNodeId=${reviewNodeId}, path=${path}, line=${line}, side=${side || "RIGHT"}`
|
||||
);
|
||||
|
||||
// add comment thread via GraphQL (REST doesn't support adding to existing pending review)
|
||||
const result = await ctx.octokit.graphql<AddPullRequestReviewThreadResponse>(
|
||||
ADD_PULL_REQUEST_REVIEW_THREAD,
|
||||
{
|
||||
pullRequestReviewId: ctx.toolState.review.nodeId,
|
||||
path,
|
||||
line,
|
||||
body,
|
||||
side: side || "RIGHT",
|
||||
}
|
||||
);
|
||||
let result: AddPullRequestReviewThreadResponse;
|
||||
try {
|
||||
result = await ctx.octokit.graphql<AddPullRequestReviewThreadResponse>(
|
||||
ADD_PULL_REQUEST_REVIEW_THREAD,
|
||||
{
|
||||
pullRequestReviewId: reviewNodeId,
|
||||
path,
|
||||
line,
|
||||
body,
|
||||
side: side || "RIGHT",
|
||||
subjectType: "LINE",
|
||||
}
|
||||
);
|
||||
log.debug(`addPullRequestReviewThread response: ${JSON.stringify(result)}`);
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
log.debug(`addPullRequestReviewThread error: ${errorMsg}`);
|
||||
throw new Error(
|
||||
`Failed to add comment to ${path}:${line}. GraphQL error: ${errorMsg}. ` +
|
||||
`Ensure the line is part of the diff and the path is correct.`
|
||||
);
|
||||
}
|
||||
|
||||
log.debug(`review comment added: threadId=${result.addPullRequestReviewThread.thread.id}`);
|
||||
// check if the mutation succeeded - null means the line is not in the diff
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
`Failed to add comment to ${path}:${line}. GraphQL returned null response.`
|
||||
);
|
||||
}
|
||||
if (!result.addPullRequestReviewThread) {
|
||||
throw new Error(
|
||||
`Failed to add comment to ${path}:${line}. addPullRequestReviewThread is null. Response: ${JSON.stringify(result)}`
|
||||
);
|
||||
}
|
||||
if (!result.addPullRequestReviewThread.thread) {
|
||||
throw new Error(
|
||||
`Failed to add comment to ${path}:${line}. thread is null. The line must be part of the diff. Response: ${JSON.stringify(result)}`
|
||||
);
|
||||
}
|
||||
|
||||
const threadId = result.addPullRequestReviewThread.thread.id;
|
||||
log.debug(`review comment added: threadId=${threadId}`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Comment added to ${path}:${line}`,
|
||||
threadId: result.addPullRequestReviewThread.thread.id,
|
||||
threadId,
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -238,6 +406,10 @@ export function SubmitReviewTool(ctx: ToolContext) {
|
||||
body: bodyWithFooter,
|
||||
});
|
||||
|
||||
log.debug(`submitReview response: ${JSON.stringify(result.data)}`);
|
||||
if (!result.data.id) {
|
||||
throw new Error(`submitReview returned invalid data: ${JSON.stringify(result.data)}`);
|
||||
}
|
||||
log.debug(`review submitted: reviewId=${result.data.id}, state=${result.data.state}`);
|
||||
|
||||
// clear review state
|
||||
@@ -255,126 +427,4 @@ export function SubmitReviewTool(ctx: ToolContext) {
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
// legacy tool - kept for backwards compatibility
|
||||
export const Review = type({
|
||||
pull_number: type.number.describe("The pull request number to review"),
|
||||
body: type.string
|
||||
.describe(
|
||||
"1-2 sentence high-level summary ONLY. Include urgency level and critical callouts (e.g., API key leak). ALL specific feedback MUST go in 'comments' array instead."
|
||||
)
|
||||
.optional(),
|
||||
commit_id: type.string
|
||||
.describe("Optional SHA of the commit being reviewed. Defaults to latest.")
|
||||
.optional(),
|
||||
comments: type({
|
||||
path: type.string.describe("The file path to comment on (relative to repo root)"),
|
||||
line: type.number.describe(
|
||||
"The line number in the file (use line numbers from the diff - usually the RIGHT side/new code)"
|
||||
),
|
||||
side: type
|
||||
.enumerated("LEFT", "RIGHT")
|
||||
.describe(
|
||||
"Side of the diff: LEFT (old code) or RIGHT (new code). Defaults to RIGHT if not provided."
|
||||
)
|
||||
.optional(),
|
||||
body: type.string.describe(
|
||||
"The comment text for this specific line. For issues appearing multiple times, comment on the first occurrence and reference others."
|
||||
),
|
||||
start_line: type.number
|
||||
.describe("Start line for multi-line comments (optional, for commenting on ranges)")
|
||||
.optional(),
|
||||
})
|
||||
.array()
|
||||
.describe(
|
||||
// FORK PR NOTE: checkout_pr returns the diff via GitHub API - use that for line numbers
|
||||
"PRIMARY location for ALL feedback. 95%+ of review content should be here. Use the diff returned from checkout_pr to find correct line numbers (RIGHT side for new code, LEFT for old)."
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export function ReviewTool(ctx: ToolContext) {
|
||||
return tool({
|
||||
name: "submit_pull_request_review",
|
||||
description:
|
||||
"DEPRECATED: Use start_review, add_review_comment, and submit_review instead for iterative review workflow. " +
|
||||
"Submit a review for an existing pull request. " +
|
||||
"IMPORTANT: 95%+ of feedback should be in 'comments' array with file paths and line numbers. " +
|
||||
"Only use 'body' for a 1-2 sentence summary with urgency and critical callouts.",
|
||||
parameters: Review,
|
||||
execute: execute(async ({ pull_number, body, commit_id, comments = [] }) => {
|
||||
// set PR context
|
||||
ctx.toolState.prNumber = pull_number;
|
||||
|
||||
// get the PR to determine the head commit if commit_id not provided
|
||||
const pr = await ctx.octokit.rest.pulls.get({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
});
|
||||
|
||||
// compose the request
|
||||
const params: RestEndpointMethodTypes["pulls"]["createReview"]["parameters"] = {
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
event: "COMMENT",
|
||||
};
|
||||
if (body) params.body = body;
|
||||
if (commit_id) {
|
||||
params.commit_id = commit_id;
|
||||
} else {
|
||||
params.commit_id = pr.data.head.sha;
|
||||
}
|
||||
if (comments.length > 0) {
|
||||
type ReviewComment = (typeof params.comments & {})[number];
|
||||
// convert comments to the format expected by GitHub API
|
||||
params.comments = comments.map((comment) => {
|
||||
const reviewComment: ReviewComment = {
|
||||
...comment,
|
||||
};
|
||||
reviewComment.side = comment.side || "RIGHT";
|
||||
if (comment.start_line) {
|
||||
reviewComment.start_line = comment.start_line;
|
||||
reviewComment.start_side = comment.side || "RIGHT";
|
||||
}
|
||||
return reviewComment;
|
||||
});
|
||||
}
|
||||
const result = await ctx.octokit.rest.pulls.createReview(params);
|
||||
const reviewId = result.data.id;
|
||||
|
||||
// build quick links footer and update the review body
|
||||
const apiUrl = process.env.API_URL || "https://pullfrog.com";
|
||||
const fixAllUrl = `${apiUrl}/trigger/${ctx.owner}/${ctx.name}/${pull_number}?action=fix&review_id=${reviewId}`;
|
||||
const fixApprovedUrl = `${apiUrl}/trigger/${ctx.owner}/${ctx.name}/${pull_number}?action=fix-approved&review_id=${reviewId}`;
|
||||
|
||||
const footer = buildPullfrogFooter({
|
||||
workflowRun: { owner: ctx.owner, repo: ctx.name, runId: ctx.runId, jobId: ctx.jobId },
|
||||
customParts: [`[Fix all ➔](${fixAllUrl})`, `[Fix 👍s ➔](${fixApprovedUrl})`],
|
||||
});
|
||||
|
||||
const updatedBody = (body || "") + footer;
|
||||
|
||||
// update the review with the footer
|
||||
await ctx.octokit.rest.pulls.updateReview({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.name,
|
||||
pull_number,
|
||||
review_id: reviewId,
|
||||
body: updatedBody,
|
||||
});
|
||||
|
||||
await deleteProgressComment(ctx);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
reviewId,
|
||||
html_url: result.data.html_url,
|
||||
state: result.data.state,
|
||||
user: result.data.user?.login,
|
||||
submitted_at: result.data.submitted_at,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
*/
|
||||
|
||||
+4
-7
@@ -24,9 +24,9 @@ import { GetIssueCommentsTool } from "./issueComments.ts";
|
||||
import { GetIssueEventsTool } from "./issueEvents.ts";
|
||||
import { IssueInfoTool } from "./issueInfo.ts";
|
||||
import { AddLabelsTool } from "./labels.ts";
|
||||
import { PullRequestTool } from "./pr.ts";
|
||||
import { CreatePullRequestTool } from "./pr.ts";
|
||||
import { PullRequestInfoTool } from "./prInfo.ts";
|
||||
import { AddReviewCommentTool, StartReviewTool, SubmitReviewTool } from "./review.ts";
|
||||
import { CreatePullRequestReviewTool } from "./review.ts";
|
||||
import { GetReviewCommentsTool, ListPullRequestReviewsTool } from "./reviewComments.ts";
|
||||
import { SelectModeTool } from "./selectMode.ts";
|
||||
import { addTools } from "./shared.ts";
|
||||
@@ -83,11 +83,8 @@ export async function startMcpHttpServer(
|
||||
IssueInfoTool(ctx),
|
||||
GetIssueCommentsTool(ctx),
|
||||
GetIssueEventsTool(ctx),
|
||||
PullRequestTool(ctx),
|
||||
// ReviewTool(ctx),
|
||||
StartReviewTool(ctx),
|
||||
AddReviewCommentTool(ctx),
|
||||
SubmitReviewTool(ctx),
|
||||
CreatePullRequestTool(ctx),
|
||||
CreatePullRequestReviewTool(ctx),
|
||||
PullRequestInfoTool(ctx),
|
||||
CheckoutPrTool(ctx),
|
||||
GetReviewCommentsTool(ctx),
|
||||
|
||||
+5
-8
@@ -1,4 +1,5 @@
|
||||
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
||||
import { encode as toonEncode } from "@toon-format/toon";
|
||||
import type { FastMCP, Tool } from "fastmcp";
|
||||
import type { ToolContext } from "../main.ts";
|
||||
|
||||
@@ -12,14 +13,10 @@ export interface ToolResult {
|
||||
isError?: boolean;
|
||||
}
|
||||
|
||||
export const handleToolSuccess = (data: Record<string, any>): ToolResult => {
|
||||
export const handleToolSuccess = (data: Record<string, any> | string): ToolResult => {
|
||||
const text = typeof data === "string" ? data : toonEncode(data);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(data, null, 2),
|
||||
},
|
||||
],
|
||||
content: [{ type: "text", text }],
|
||||
};
|
||||
};
|
||||
|
||||
@@ -40,7 +37,7 @@ export const handleToolError = (error: unknown): ToolResult => {
|
||||
* Helper to wrap a tool execute function with error handling.
|
||||
* Captures ctx in closure so tools don't need to handle try/catch.
|
||||
*/
|
||||
export const execute = <T>(fn: (params: T) => Promise<Record<string, any>>) => {
|
||||
export const execute = <T>(fn: (params: T) => Promise<Record<string, any> | string>) => {
|
||||
return async (params: T): Promise<ToolResult> => {
|
||||
try {
|
||||
const result = await fn(params);
|
||||
|
||||
@@ -29,7 +29,7 @@ export function getModes({ disableProgressComment }: GetModesParams): Mode[] {
|
||||
name: "Build",
|
||||
description:
|
||||
"Implement, build, create, or develop code changes; make specific changes to files or features; execute a plan; or handle tasks with specific implementation details",
|
||||
prompt: `Follow these steps:
|
||||
prompt: `Follow these steps. THINK HARDER.
|
||||
1. If this is a PR event, the PR branch is already checked out - skip branch creation. Otherwise, create a branch using ${ghPullfrogMcpName}/create_branch. The branch name should be prefixed with "pullfrog/". The rest of the name should reflect the exact changes you are making. It should be specific to avoid collisions with other branches. Never commit directly to main, master, or production. Do NOT use git commands directly (including \`git branch\`, \`git status\`, \`git log\`) - always use ${ghPullfrogMcpName} MCP tools for git operations.
|
||||
|
||||
${dependencyInstallationGuidance}
|
||||
@@ -68,7 +68,7 @@ ${dependencyInstallationGuidance}
|
||||
name: "Address Reviews",
|
||||
description:
|
||||
"Address PR review feedback; respond to reviewer comments; make requested changes to an existing PR",
|
||||
prompt: `Follow these steps:
|
||||
prompt: `Follow these steps. THINK HARDER.
|
||||
1. Checkout the PR using ${ghPullfrogMcpName}/checkout_pr with the PR number. This fetches the PR branch and configures push settings (including for fork PRs).
|
||||
|
||||
${dependencyInstallationGuidance}
|
||||
@@ -99,43 +99,35 @@ ${
|
||||
name: "Review",
|
||||
description:
|
||||
"Review code, PRs, or implementations; provide feedback or suggestions; identify issues; or check code quality, style, and correctness",
|
||||
prompt: `Follow these steps:
|
||||
1. Checkout the PR using ${ghPullfrogMcpName}/checkout_pr with the PR number. This fetches the PR branch and returns the PR diff in the \`diff\` field of the response. Use this diff for your review - it shows exactly what's in the PR (fetched via GitHub API, so it's not affected by main advancing after the branch was created).
|
||||
prompt: `Follow these steps to review the PR. Think hard. Do not nitpick.
|
||||
|
||||
2. Start review session using ${ghPullfrogMcpName}/start_review. This creates a pending review on GitHub and returns analysis guidance. Follow the guidance before adding comments.
|
||||
1. **CHECKOUT** - Call ${ghPullfrogMcpName}/checkout_pr with the PR number. This should give you all PR metadata you need, including a \`diffPath\`: a path to a temp file containing the PR diff.
|
||||
|
||||
3. **ANALYZE** - Before adding any comments, think through:
|
||||
- What does this PR change? Summarize in 1-2 sentences.
|
||||
- Is the approach sound? If not, **stop here** and comment on the approach first. Don't waste time on implementation details if the approach is wrong.
|
||||
- What bugs, edge cases, or security issues exist?
|
||||
|
||||
4. **BEFORE COMMENTING** - For each potential comment, ask yourself:
|
||||
- Is this a nitpick? Skip it unless explicitly requested.
|
||||
- Would the codebase maintainer care about this feedback, based on what you can infer about the code quality standards in this repo?
|
||||
2. **ANALYZE**
|
||||
- Read the modified files to understand the changes in context. Make sure you understand what's being changed.
|
||||
- Is it a good idea? Think about the tradeoffs.
|
||||
- Is the approach sound? If not, focus on the approach first. Don't waste time on implementation details if the approach is wrong.
|
||||
- Can you imagine a better approach? If so, explain. Make sure it's strictly better, not just different.
|
||||
- Are there bugs, edge cases, security issues, or usability issues? Use your imagination.
|
||||
|
||||
5. Add inline review comments one-by-one using ${ghPullfrogMcpName}/add_review_comment
|
||||
- Use **relative paths** from repo root (e.g., \`packages/core/src/utils.ts\`)
|
||||
- Use the NEW file line number from the diff (shown after \`+\` in hunk headers like \`@@ -10,5 +12,8 @@\` means new file starts at line 12)
|
||||
- Only comment on lines that appear in the diff. GitHub will reject comments on unchanged lines.
|
||||
- For issues appearing in multiple places, comment on the FIRST occurrence and reference others (e.g., "also at lines X, Y")
|
||||
3. **DRAFT** - For each inline comment, find the line in the diff. Each code line shows: \`| OLD | NEW | TYPE | CODE\`. Use the NEW line number (second column).
|
||||
|
||||
6. Submit the review using ${ghPullfrogMcpName}/submit_review
|
||||
- The "body" field is ONLY for: (1) a 1-3 sentence high-level overview, (2) urgency level (e.g., "minor suggestions" vs "blocking issues"), (3) critical security callouts (e.g., API key exposure)
|
||||
4. **FILTER COMMENTS** - Do not nitpick! Do not leave compliments that are not actionable. Do not critique the code hygiene or anything stylistic.
|
||||
|
||||
**GENERAL GUIDANCE**
|
||||
5. **SUBMIT** — Use ${ghPullfrogMcpName}/create_pull_request_review with:
|
||||
- \`comments\`: Array of all inline comments with file paths and line numbers
|
||||
- \`body\`: Everything else. Aim for a 1-3 sentence summary of the urgency level (e.g., "minor suggestions" vs "blocking issues") and any critical callouts (e.g., API key exposure). It can be longer if there are concerns that do not lend themselves to inline comments.
|
||||
- If you have no substantive feedback, submit an empty comments array with a brief approving body.
|
||||
- Again, do not nitpick.
|
||||
|
||||
- Do not leave any comments that are not potentially actionable. Do not leave complimentary comments just to be nice.
|
||||
- Do not nitpick unless instructed explicitly to do so by the user's additional instructions. This includes: requesting documentation/docstrings/JSDoc.
|
||||
- **CRITICAL: Prioritize per-line feedback over summary text.**
|
||||
- All specific feedback MUST go in inline review comments with file paths and line numbers from the diff
|
||||
- The vast majority of review content should be in inline review comments; the body should be brief and only summarize the urgency of the review and any cross-cutting concerns.
|
||||
`,
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "Plan",
|
||||
description:
|
||||
"Create plans, break down tasks, outline steps, analyze requirements, understand scope of work, or provide task breakdowns",
|
||||
prompt: `Follow these steps:
|
||||
prompt: `Follow these steps. THINK HARDER.
|
||||
1. If the request requires understanding the codebase structure or conventions, gather relevant context (read AGENTS.md if it exists). Skip this step if the prompt is trivial and self-contained.
|
||||
|
||||
2. Analyze the request and break it down into clear, actionable tasks
|
||||
@@ -148,7 +140,7 @@ ${
|
||||
name: "Prompt",
|
||||
description:
|
||||
"Fallback for tasks that don't fit other workflows, e.g. direct prompts via comments, or requests requiring general assistance",
|
||||
prompt: `Follow these steps:
|
||||
prompt: `Follow these steps. THINK HARDER.
|
||||
1. Perform the requested task. Only take action if you have high confidence that you understand what is being asked. If you are not sure, ask for clarification. Take stock of the tools at your disposal.${disableProgressComment ? "" : "\n\n2. When creating comments, always use report_progress. Do not use create_issue_comment."}
|
||||
|
||||
2. If the task involves making code changes:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@pullfrog/action",
|
||||
"version": "0.0.151",
|
||||
"version": "0.0.155",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"index.js",
|
||||
|
||||
+1
-1
@@ -278,7 +278,7 @@ export const log = {
|
||||
/**
|
||||
* Print debug message (only if LOG_LEVEL=debug)
|
||||
*/
|
||||
debug: (message: string): void => {
|
||||
debug: (message: string | unknown): void => {
|
||||
if (isDebugEnabled()) {
|
||||
if (isGitHubActions) {
|
||||
// using this instead of core.debug
|
||||
|
||||
+2
-2
@@ -1,6 +1,7 @@
|
||||
import { createSign } from "node:crypto";
|
||||
import * as core from "@actions/core";
|
||||
import { log } from "./cli.ts";
|
||||
import { retry } from "./retry.ts";
|
||||
|
||||
export interface InstallationToken {
|
||||
token: string;
|
||||
@@ -56,7 +57,6 @@ async function acquireTokenViaOIDC(): Promise<string> {
|
||||
|
||||
log.info("» exchanging OIDC token for installation token...");
|
||||
|
||||
// Add timeout to prevent long waits (30 seconds)
|
||||
const timeoutMs = 30000;
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
||||
@@ -234,7 +234,7 @@ async function acquireTokenViaGitHubApp(): Promise<string> {
|
||||
|
||||
async function acquireNewToken(): Promise<string> {
|
||||
if (isGitHubActionsEnvironment()) {
|
||||
return await acquireTokenViaOIDC();
|
||||
return await retry(() => acquireTokenViaOIDC(), { label: "token exchange" });
|
||||
} else {
|
||||
return await acquireTokenViaGitHubApp();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { log } from "./cli.ts";
|
||||
|
||||
export type RetryOptions = {
|
||||
maxAttempts?: number;
|
||||
delayMs?: number;
|
||||
shouldRetry?: (error: unknown) => boolean;
|
||||
label?: string;
|
||||
};
|
||||
|
||||
const defaultShouldRetry = (error: unknown): boolean => {
|
||||
if (!(error instanceof Error)) return false;
|
||||
// retry on transient network errors
|
||||
return (
|
||||
error.name === "AbortError" ||
|
||||
error.message.includes("fetch failed") ||
|
||||
error.message.includes("ECONNRESET") ||
|
||||
error.message.includes("ETIMEDOUT")
|
||||
);
|
||||
};
|
||||
|
||||
export async function retry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
|
||||
const maxAttempts = options.maxAttempts ?? 3;
|
||||
const delayMs = options.delayMs ?? 1000;
|
||||
const shouldRetry = options.shouldRetry ?? defaultShouldRetry;
|
||||
const label = options.label ?? "operation";
|
||||
|
||||
let lastError: unknown;
|
||||
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
|
||||
if (attempt === maxAttempts || !shouldRetry(error)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const delay = delayMs * attempt;
|
||||
log.warning(`» ${label} failed (attempt ${attempt}/${maxAttempts}), retrying in ${delay}ms...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user