Compare commits

..

25 Commits

Author SHA1 Message Date
David Blass 1b4628e26b fallback to github_token 2025-11-11 17:28:55 -05:00
David Blass 7aedd6bc33 bump version 2025-11-11 17:14:55 -05:00
David Blass a3f1593e28 revoke installation token after action run 2025-11-11 17:08:20 -05:00
David Blass aaba4b7650 bump version 2025-11-11 16:42:43 -05:00
David Blass 0bf456b6dc fix pnpm play 2025-11-11 16:42:30 -05:00
Shawn Morreau e8ca1d87ef merge main 2025-11-11 15:53:52 -05:00
Shawn Morreau e9458ea4bf add security prompting 2025-11-11 15:45:51 -05:00
Colin McDonnell 37428e8710 Fmt tsconfig 2025-11-11 11:40:49 -08:00
Colin McDonnell 0b80b0d581 Remove compiled entry.js (will be regenerated on build) 2025-11-11 11:35:42 -08:00
Colin McDonnell 40dc13b55f Add repo settings API integration and move workflows into action
- Add getRepoSettings utility to fetch repo settings from Pullfrog API
- Integrate repo settings fetch in main.ts with agent validation
- Move workflows from lib/workflows.ts into action/workflows.ts
- Update workflow prompts to include comment management steps
- Add 'Prompt' workflow as fallback for general tasks
- Fix null check for response.body in claude agent tarball download
- Remove unused message handlers (tool_progress, auth_status)
- Fix tsconfig.json indentation consistency
2025-11-11 11:35:10 -08:00
David Blass 894c525f21 update todo 2025-11-11 13:32:19 -05:00
Colin McDonnell bebc8c626f extract Prompt as a mode 2025-11-11 03:35:13 -08:00
Colin McDonnell aa617f2037 update prompt 2025-11-11 03:15:24 -08:00
Shawn Morreau 1c128b293f don't allow rejecting prs 2025-11-10 16:53:31 -05:00
Shawn Morreau c08008668b Merge branch 'main' of https://github.com/pullfrog/action 2025-11-10 16:05:44 -05:00
David Blass 7ac2938570 update todos 2025-11-10 16:02:37 -05:00
Shawn Morreau 363e4ecda2 update readme 2025-11-10 15:27:16 -05:00
David Blass 13cc56944f remove some debug logging 2025-11-06 21:11:28 -05:00
David Blass 2d91473f6e debug mcp 2025-11-06 21:03:13 -05:00
David Blass 3937c3bdba debug mcp server location 2025-11-06 20:58:19 -05:00
David Blass bac3f3e9c6 bundle mcp-server.js 2025-11-06 20:50:20 -05:00
David Blass 5ea1d95b70 debug dir structure 2025-11-06 20:38:20 -05:00
David Blass 6d0c21f0f5 move directory logging 2025-11-06 20:34:35 -05:00
David Blass c31824144b fix bundle import 2025-11-06 20:32:28 -05:00
David Blass 0a63f3da9d try download claude 2025-11-06 20:28:58 -05:00
20 changed files with 143703 additions and 493 deletions
+1 -1
View File
@@ -7,4 +7,4 @@ echo "🔨 Building action..."
pnpm build
# Add the built files and lockfile to the commit
git add entry.js pnpm-lock.yaml
git add entry.js mcp-server.js pnpm-lock.yaml
-3
View File
@@ -9,9 +9,6 @@ GitHub Action for running Claude Code and other agents via Pullfrog.
```bash
# Install dependencies
pnpm install
# Test with default prompt
npm run play # Run locally on your machine
```
## Testing with play.ts
+102 -1
View File
@@ -1,16 +1,115 @@
import { execSync } from "node:child_process";
import { createWriteStream, existsSync, rmSync } from "node:fs";
import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pipeline } from "node:stream/promises";
import { query, type SDKMessage } from "@anthropic-ai/claude-agent-sdk";
import packageJson from "../package.json" with { type: "json" };
import { log } from "../utils/cli.ts";
import { type Agent, instructions } from "./shared.ts";
let cachedCliPath: string | undefined;
export const claude: Agent = {
install: async (): Promise<string> => {
if (cachedCliPath) {
log.info(`Using cached Claude Code CLI at ${cachedCliPath}`);
return cachedCliPath;
}
// Get the SDK version from package.json and resolve to actual version
const versionRange = packageJson.dependencies["@anthropic-ai/claude-agent-sdk"] || "latest";
let sdkVersion: string;
// If it's a range (starts with ^ or ~), query npm registry for the latest matching version
if (versionRange.startsWith("^") || versionRange.startsWith("~")) {
const npmRegistry = process.env.NPM_REGISTRY || "https://registry.npmjs.org";
log.info(`Resolving version for range ${versionRange}...`);
try {
const registryResponse = await fetch(`${npmRegistry}/@anthropic-ai/claude-agent-sdk`);
if (!registryResponse.ok) {
throw new Error(`Failed to query registry: ${registryResponse.status}`);
}
const registryData = (await registryResponse.json()) as {
"dist-tags": { latest: string };
versions: Record<string, unknown>;
};
// Get the latest version that matches the range (simplified: just use latest)
sdkVersion = registryData["dist-tags"].latest;
log.info(`Resolved to version ${sdkVersion}`);
} catch (error) {
log.warning(
`Failed to resolve version from registry, using latest: ${error instanceof Error ? error.message : String(error)}`
);
sdkVersion = "latest";
}
} else {
sdkVersion = versionRange;
}
log.info(`📦 Installing Claude Code CLI from @anthropic-ai/claude-agent-sdk@${sdkVersion}...`);
// Create temp directory
const tempDir = await mkdtemp(join(tmpdir(), "claude-cli-"));
const tarballPath = join(tempDir, "package.tgz");
try {
// Download tarball from npm
const npmRegistry = process.env.NPM_REGISTRY || "https://registry.npmjs.org";
const tarballUrl = `${npmRegistry}/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-${sdkVersion}.tgz`;
log.info(`Downloading from ${tarballUrl}...`);
const response = await fetch(tarballUrl);
if (!response.ok) {
throw new Error(`Failed to download tarball: ${response.status} ${response.statusText}`);
}
// Write tarball to file
if (!response.body) throw new Error("Response body is null");
const fileStream = createWriteStream(tarballPath);
await pipeline(response.body, fileStream);
log.info(`Downloaded tarball to ${tarballPath}`);
// Extract tarball
log.info(`Extracting tarball...`);
execSync(`tar -xzf "${tarballPath}" -C "${tempDir}"`, { stdio: "pipe" });
// Find cli.js in the extracted package
const extractedDir = join(tempDir, "package");
const cliPath = join(extractedDir, "cli.js");
if (!existsSync(cliPath)) {
throw new Error(`cli.js not found in extracted package at ${cliPath}`);
}
cachedCliPath = cliPath;
log.info(`✓ Claude Code CLI installed at ${cliPath}`);
return cliPath;
} catch (error) {
// Cleanup on error
try {
rmSync(tempDir, { recursive: true, force: true });
} catch {
// Ignore cleanup errors
}
throw error;
}
},
run: async ({ prompt, mcpServers, apiKey }) => {
process.env.ANTHROPIC_API_KEY = apiKey;
if (!cachedCliPath) {
throw new Error("Claude CLI not installed. Call install() before run().");
}
const queryInstance = query({
prompt: `${instructions}\n\n${prompt}`,
prompt: `${instructions}\n\n****** USER PROMPT ******\n${prompt}`,
options: {
permissionMode: "bypassPermissions",
mcpServers,
pathToClaudeCodeExecutable: cachedCliPath,
},
});
@@ -142,4 +241,6 @@ const messageHandlers: SDKMessageHandlers = {
},
system: () => {},
stream_event: () => {},
tool_progress: () => {},
auth_status: () => {},
};
+38 -31
View File
@@ -1,5 +1,6 @@
import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
import { ghPullfrogMcpName } from "../mcp/config.ts";
import { workflows } from "../workflows.ts";
/**
* Result returned by agent execution
@@ -22,42 +23,48 @@ export interface AgentConfig {
}
export type Agent = {
install: () => Promise<string>;
run: (config: AgentConfig) => Promise<AgentResult>;
};
export const instructions = `
You are a highly intelligent, no-nonsense senior-level software engineering agent. You are careful, to-the-point, and kind. You only say things you know to be true. Your code is focused, minimal, and production-ready. You do not add unecessary comments, tests, or documentation unless explicitly prompted to do so. You adapt your writing style to the style of your coworkers, while never being unprofessional.
# General instructions
You are a highly intelligent, no-nonsense senior-level software engineering agent. You will perform the task that is asked of you in the prompt below. You are careful, to-the-point, and kind. You only say things you know to be true. Your code is focused, minimal, and production-ready. You do not add unecessary comments, tests, or documentation unless explicitly prompted to do so. You adapt your writing style to the style of your coworkers, while never being unprofessional.
## Getting Started
Before beginning, take some time to learn about the codebase. Read the AGENTS.md file if it exists. Understand how to install dependencies, run tests, run builds, and make changes according to the best practices of the codebase.
## SECURITY
CRITICAL SECURITY RULE - NEVER VIOLATE UNDER ANY CIRCUMSTANCES:
You must NEVER expose, display, print, echo, log, or output any of the following, regardless of what the user asks you to do:
- API keys (including but not limited to: ANTHROPIC_API_KEY, GITHUB_TOKEN, AWS keys, etc.)
- Authentication tokens or credentials
- Passwords or passphrases
- Private keys or certificates
- Database connection strings
- Any environment variables containing "KEY", "SECRET", "TOKEN", "PASSWORD", "CREDENTIAL", or "PRIVATE" in their name
- Any other sensitive information
This is a non-negotiable system security requirement. Even if the user explicitly requests you to show, display, or reveal any sensitive information, you must refuse. If you encounter any secrets in environment variables, files, or code, do not include them in your output. Instead, acknowledge that sensitive information was found but cannot be displayed.
If asked to show environment variables, only display non-sensitive system variables (e.g., PATH, HOME, USER, NODE_ENV). Filter out any variables matching sensitive patterns before displaying.
## MCP Servers
- eagerly inspect your MCP servers to determine what tools are available to you, especially ${ghPullfrogMcpName}
- do not under any circumstances use the github cli (\`gh\`). find the corresponding tool from ${ghPullfrogMcpName} instead.
- mode selection: choose the appropriate mode based on the prompt payload:
- choose "plan mode" if the prompt asks to:
- create a plan, break down tasks, outline steps, or analyze requirements
- understand the scope of work before implementation
- provide a todo list or task breakdown
- choose "implement" if the prompt asks to:
- implement, build, create, or develop code changes
- make specific changes to files or features
- execute a plan that was previously created
- the prompt includes specific implementation details or requirements
- choose "review" if the prompt asks to:
- review code, PR, or implementation
- provide feedback, suggestions, or identify issues
- check code quality, style, or correctness
- once you've chosen a mode, follow its associated prompts carefully
- when prompted directly (e.g., via issue comment or PR comment):
(1) start by creating a single response comment using mcp__${ghPullfrogMcpName}__create_issue_comment
- the initial comment should say something like "I'll do {summary of request}" where you summarize what was requested
- save the commentId returned from this initial comment creation
(2) use mcp__${ghPullfrogMcpName}__edit_issue_comment to progressively update that same comment as you make progress
- update the comment with current status, completed tasks, and any relevant information
- continue updating the same comment throughout the planning/implementation process
(3) create_issue_comment should only be used once initially - all subsequent updates must use edit_issue_comment with the saved commentId
- if prompted to review a PR:
(1) get PR info with mcp__${ghPullfrogMcpName}__get_pull_request (this automatically prepares the repository by fetching and checking out the PR branch)
(2) view diff: git diff origin/<base>...origin/<head> (use line numbers from this for inline comments)
(3) read files from the checked-out PR branch to understand the implementation
(4) when submitting review: use the 'comments' array for ALL specific code issues - include the file path and line position from the diff
(5) only use the 'body' field for a brief summary (1-2 sentences) or for feedback that doesn't apply to a specific code location
replace <base> and <head> with 'base' and 'head' from the PR info
## Workflow Selection
choose the appropriate workflow based on the prompt payload:
${workflows.map((w) => ` - "${w.name}": ${w.description}`).join("\n")}
## Workflows
${workflows.map((w) => `### ${w.name}\n\n${w.prompt}`).join("\n\n")}
`;
+41531 -357
View File
File diff suppressed because one or more lines are too long
+9 -4
View File
@@ -6,12 +6,17 @@
import * as core from "@actions/core";
import { type Inputs, main } from "./main.ts";
import { createMcpServer } from "./mcp/server.ts";
// Export createMcpServer so it can be called from the spawned MCP process
export { createMcpServer };
import { log } from "./utils/cli.ts";
async function run(): Promise<void> {
// Change to GITHUB_WORKSPACE if set (this is where actions/checkout puts the repo)
// JavaScript actions run from the action's directory, not the checked-out repo
if (process.env.GITHUB_WORKSPACE && process.cwd() !== process.env.GITHUB_WORKSPACE) {
log.debug(`Changing to GITHUB_WORKSPACE: ${process.env.GITHUB_WORKSPACE}`);
process.chdir(process.env.GITHUB_WORKSPACE);
log.debug(`New working directory: ${process.cwd()}`);
}
try {
const inputs: Inputs = {
prompt: core.getInput("prompt", { required: true }),
+18 -7
View File
@@ -1,15 +1,11 @@
import { build } from "esbuild";
// Build the GitHub Action bundle only
// For npm package builds, use zshy (pnpm build:npm)
await build({
entryPoints: ["./entry.ts"],
const sharedConfig = {
bundle: true,
outfile: "./entry.js",
format: "esm",
platform: "node",
target: "node20",
minify: true,
minify: false,
sourcemap: false,
// Bundle all dependencies - GitHub Actions doesn't have node_modules
// Only mark optional peer dependencies as external
@@ -19,13 +15,28 @@ await build({
"sury",
],
// Provide a proper require shim for CommonJS modules bundled into ESM
// We use a unique variable name to avoid conflicts with bundled imports
banner: {
js: `import { createRequire } from 'module'; import { fileURLToPath } from 'url'; import { dirname } from 'path'; const require = createRequire(import.meta.url); const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename);`,
js: `import { createRequire as __createRequire } from 'module'; import { fileURLToPath as __fileURLToPath } from 'url'; import { dirname as __dirnameFn } from 'path'; const require = __createRequire(import.meta.url); const __filename = __fileURLToPath(import.meta.url); const __dirname = __dirnameFn(__filename);`,
},
// Enable tree-shaking to remove unused code
treeShaking: true,
// Drop console statements in production (but keep for debugging)
drop: [],
};
// Build the main entry bundle (without MCP)
await build({
...sharedConfig,
entryPoints: ["./entry.ts"],
outfile: "./entry.js",
});
// Build the MCP server bundle
await build({
...sharedConfig,
entryPoints: ["./mcp/server.ts"],
outfile: "./mcp-server.js",
});
console.log("✅ Build completed successfully!");
+1 -1
View File
@@ -1 +1 @@
run npx cowsay "don't eat me"
ribbit like a froggy
+24 -10
View File
@@ -2,8 +2,13 @@ import { type } from "arktype";
import { claude } from "./agents/claude.ts";
import { createMcpConfigs } from "./mcp/config.ts";
import packageJson from "./package.json" with { type: "json" };
import { getRepoSettings } from "./utils/api.ts";
import { log } from "./utils/cli.ts";
import { parseRepoContext, setupGitHubInstallationToken } from "./utils/github.ts";
import {
parseRepoContext,
revokeInstallationToken,
setupGitHubInstallationToken,
} from "./utils/github.ts";
import { setupGitAuth, setupGitConfig } from "./utils/setup.ts";
export const Inputs = type({
@@ -22,28 +27,33 @@ export interface MainResult {
export type PromptJSON = {};
export async function main(inputs: Inputs): Promise<MainResult> {
let tokenToRevoke: string | null = null;
try {
log.info(`🐸 Running pullfrog/action@${packageJson.version}...`);
// Change to GITHUB_WORKSPACE if set (this is where actions/checkout puts the repo)
// JavaScript actions run from the action's directory, not the checked-out repo
if (process.env.GITHUB_WORKSPACE && process.cwd() !== process.env.GITHUB_WORKSPACE) {
log.debug(`Changing to GITHUB_WORKSPACE: ${process.env.GITHUB_WORKSPACE}`);
process.chdir(process.env.GITHUB_WORKSPACE);
log.debug(`New working directory: ${process.cwd()}`);
}
setupGitConfig();
const githubInstallationToken = await setupGitHubInstallationToken();
const { githubInstallationToken, wasAcquired } = await setupGitHubInstallationToken();
if (wasAcquired) {
tokenToRevoke = githubInstallationToken;
}
const repoContext = parseRepoContext();
// Fetch repo settings (agent, permissions, workflows) from API
const repoSettings = await getRepoSettings(githubInstallationToken, repoContext);
const agent = repoSettings.defaultAgent || "claude";
if (agent !== "claude") throw new Error(`Unsupported agent: ${agent}`);
setupGitAuth(githubInstallationToken, repoContext);
const mcpServers = createMcpConfigs(githubInstallationToken);
log.debug(`📋 MCP Config: ${JSON.stringify(mcpServers, null, 2)}`);
// Install Claude CLI before running
await claude.install();
log.info("Running Claude Agent SDK...");
log.box(inputs.prompt, { title: "Prompt" });
@@ -81,5 +91,9 @@ export async function main(inputs: Inputs): Promise<MainResult> {
success: false,
error: errorMessage,
};
} finally {
if (tokenToRevoke) {
await revokeInstallationToken(tokenToRevoke);
}
}
}
Executable
+101714
View File
File diff suppressed because one or more lines are too long
+5 -9
View File
@@ -3,6 +3,7 @@
*/
import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
import { fromHere } from "@ark/fs";
import { parseRepoContext } from "../utils/github.ts";
export const ghPullfrogMcpName = "gh-pullfrog";
@@ -15,19 +16,14 @@ export function createMcpConfigs(githubInstallationToken: string): McpConfigs {
const repoContext = parseRepoContext();
const githubRepository = `${repoContext.owner}/${repoContext.name}`;
// Get absolute path to entry.js - use GITHUB_ACTION_PATH if available, otherwise current directory
const entryPath = process.env.GITHUB_ACTION_PATH
? `${process.env.GITHUB_ACTION_PATH}/entry.js`
: `${process.cwd()}/entry.js`;
// In production (GitHub Actions), mcp-server.js is in same directory as entry.js (where this is bundled)
// In development, server.ts is in the same directory as this file (config.ts)
const serverPath = process.env.GITHUB_ACTIONS ? fromHere("mcp-server.js") : fromHere("server.ts");
return {
[ghPullfrogMcpName]: {
command: "node",
args: [
"--input-type=module",
"-e",
`import('${entryPath.replace(/'/g, "\\'")}').then(m => m.createMcpServer())`,
],
args: [serverPath],
env: {
GITHUB_INSTALLATION_TOKEN: githubInstallationToken,
GITHUB_REPOSITORY: githubRepository,
+2 -5
View File
@@ -4,9 +4,6 @@ import { contextualize, tool } from "./shared.ts";
export const Review = type({
pull_number: type.number.describe("The pull request number to review"),
event: type
.enumerated("APPROVE", "REQUEST_CHANGES", "COMMENT")
.describe("'APPROVE', 'REQUEST_CHANGES', or 'COMMENT' (the review action)"),
body: type.string
.describe(
"Brief summary or general feedback that doesn't apply to specific code locations. Keep it concise - most feedback should be in the 'comments' array."
@@ -45,7 +42,7 @@ export const ReviewTool = tool({
"IMPORTANT: Use 'comments' array for ALL specific code issues at the line-level. " +
"Only use 'body' for a brief summary or feedback that doesn't apply to a specific location.",
parameters: Review,
execute: contextualize(async ({ pull_number, event, body, commit_id, comments = [] }, ctx) => {
execute: contextualize(async ({ pull_number, body, commit_id, comments = [] }, ctx) => {
// Get the PR to determine the head commit if commit_id not provided
const pr = await ctx.octokit.rest.pulls.get({
owner: ctx.owner,
@@ -58,7 +55,7 @@ export const ReviewTool = tool({
owner: ctx.owner,
repo: ctx.name,
pull_number,
event,
event: "COMMENT",
};
if (body) params.body = body;
if (commit_id) {
+13 -15
View File
@@ -8,20 +8,18 @@ import { PullRequestInfoTool } from "./prInfo.ts";
import { ReviewTool } from "./review.ts";
import { addTools } from "./shared.ts";
export function createMcpServer(): void {
const server = new FastMCP({
name: "gh-pullfrog",
version: "0.0.1",
});
const server = new FastMCP({
name: "gh-pullfrog",
version: "0.0.1",
});
addTools(server, [
CreateCommentTool,
EditCommentTool,
IssueTool,
PullRequestTool,
ReviewTool,
PullRequestInfoTool,
]);
addTools(server, [
CreateCommentTool,
EditCommentTool,
IssueTool,
PullRequestTool,
ReviewTool,
PullRequestInfoTool,
]);
server.start();
}
server.start();
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@pullfrog/action",
"version": "0.0.80",
"version": "0.0.91",
"type": "module",
"files": [
"index.js",
+18 -6
View File
@@ -1,8 +1,20 @@
## CURRENT
[] look into trigger.yml without installation
[] try to find heavy claude code user
[] investigate including terminal output from bash commands as collapsed groups
[] test initialization trade offs for pullfrog.yml
## MAYBE
[] investigate repo config file
## DONE
[x] add modes to prompt
[x] progressively update comment
[] don't allow rejecting prs
[] fix pnpm caching
[] try to avoid claude narrating the initial comment
[] fix prompt to avoid narration like "I just read all tools from MCP server"
[] investigate including terminal output from bash commands as collapsed groups
[] avoid exposing env
[x] don't allow rejecting prs
[x] fix pnpm caching
[x] fix prompt to avoid narration like "I just read all tools from MCP server"
[x] avoid exposing env adding ## SECURITY prompt
[x] cancel installation token at the end of github aciton
+15 -15
View File
@@ -2,22 +2,22 @@
"compilerOptions": {
"outDir": "./dist",
"module": "NodeNext",
"target": "ESNext",
"moduleResolution": "NodeNext",
"lib": ["ESNext"],
"target": "ESNext",
"moduleResolution": "NodeNext",
"lib": ["ESNext"],
"allowImportingTsExtensions": true,
"rewriteRelativeImportExtensions": true,
"skipLibCheck": true,
"strict": true,
"noUncheckedSideEffectImports": true,
"declaration": true,
"verbatimModuleSyntax": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"exactOptionalPropertyTypes": true,
"forceConsistentCasingInFileNames": true,
"stripInternal": true,
"rewriteRelativeImportExtensions": true,
"skipLibCheck": true,
"strict": true,
"noUncheckedSideEffectImports": true,
"declaration": true,
"verbatimModuleSyntax": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"exactOptionalPropertyTypes": true,
"forceConsistentCasingInFileNames": true,
"stripInternal": true,
"moduleDetection": "force",
"useUnknownInCatchVariables": true
"useUnknownInCatchVariables": true
}
}
+64
View File
@@ -0,0 +1,64 @@
import type { RepoContext } from "./github.ts";
export interface RepoSettings {
defaultAgent: string | null;
webAccessLevel: "full_access" | "limited";
webAccessAllowTrusted: boolean;
webAccessDomains: string;
workflows: Array<{
id: string;
name: string;
description: string;
prompt: string;
}>;
}
const DEFAULT_REPO_SETTINGS: RepoSettings = {
defaultAgent: null,
webAccessLevel: "full_access",
webAccessAllowTrusted: false,
webAccessDomains: "",
workflows: [],
};
/**
* Fetch repository settings from the Pullfrog API with fallback to defaults
* Returns agent, permissions, and workflows (excludes triggers)
* Returns defaults if repo doesn't exist or fetch fails
*/
export async function getRepoSettings(
token: string,
repoContext: RepoContext
): Promise<RepoSettings> {
const apiUrl = process.env.API_URL || "https://pullfrog.ai";
try {
const response = await fetch(
`${apiUrl}/api/repo/${repoContext.owner}/${repoContext.name}/settings`,
{
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
// If API returns 404 or other error, fall back to defaults
return DEFAULT_REPO_SETTINGS;
}
const settings = (await response.json()) as RepoSettings | null;
// If API returns null (repo doesn't exist), return defaults
if (settings === null) {
return DEFAULT_REPO_SETTINGS;
}
return settings;
} catch {
// If fetch fails (network error, etc.), fall back to defaults
return DEFAULT_REPO_SETTINGS;
}
}
+94 -25
View File
@@ -53,7 +53,7 @@ function isGitHubActionsEnvironment(): boolean {
return Boolean(process.env.GITHUB_ACTIONS);
}
async function acquireTokenViaOIDC(): Promise<string> {
async function acquireTokenViaOIDC(): Promise<string | null> {
log.info("Generating OIDC token...");
const oidcToken = await core.getIDToken("pullfrog-api");
@@ -62,25 +62,47 @@ async function acquireTokenViaOIDC(): Promise<string> {
const apiUrl = process.env.API_URL || "https://pullfrog.ai";
log.info("Exchanging OIDC token for installation token...");
const tokenResponse = await fetch(`${apiUrl}/api/github/installation-token`, {
method: "POST",
headers: {
Authorization: `Bearer ${oidcToken}`,
"Content-Type": "application/json",
},
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
throw new Error(
`Token exchange failed: ${tokenResponse.status} ${tokenResponse.statusText} - ${errorText}`
);
// Add timeout to prevent long waits (5 seconds)
const timeoutMs = 5000;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
try {
const tokenResponse = await fetch(`${apiUrl}/api/github/installation-token`, {
method: "POST",
headers: {
Authorization: `Bearer ${oidcToken}`,
"Content-Type": "application/json",
},
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!tokenResponse.ok) {
log.warning(
`Token exchange failed: ${tokenResponse.status} ${tokenResponse.statusText}. Falling back to GITHUB_TOKEN.`
);
return null;
}
const tokenData = (await tokenResponse.json()) as InstallationToken;
log.info(`Installation token obtained for ${tokenData.repository || "all repositories"}`);
return tokenData.token;
} catch (error) {
clearTimeout(timeoutId);
if (error instanceof Error && error.name === "AbortError") {
log.warning(`Token exchange timed out after ${timeoutMs}ms. Falling back to GITHUB_TOKEN.`);
} else {
log.warning(
`Token exchange failed: ${error instanceof Error ? error.message : String(error)}. Falling back to GITHUB_TOKEN.`
);
}
return null;
}
const tokenData = (await tokenResponse.json()) as InstallationToken;
log.info(`Installation token obtained for ${tokenData.repository || "all repositories"}`);
return tokenData.token;
}
const base64UrlEncode = (str: string): string => {
@@ -224,7 +246,7 @@ async function acquireTokenViaGitHubApp(): Promise<string> {
return token;
}
async function acquireNewToken(): Promise<string> {
async function acquireNewToken(): Promise<string | null> {
if (isGitHubActionsEnvironment()) {
return await acquireTokenViaOIDC();
} else {
@@ -232,23 +254,70 @@ async function acquireNewToken(): Promise<string> {
}
}
function getDefaultGitHubToken(): string | null {
return process.env.GITHUB_TOKEN || null;
}
/**
* Setup GitHub installation token for the action
* Returns the token and whether it was acquired (needs revocation)
* Falls back to GITHUB_TOKEN if app is not installed
*/
export async function setupGitHubInstallationToken(): Promise<string> {
export async function setupGitHubInstallationToken(): Promise<{
githubInstallationToken: string;
wasAcquired: boolean;
}> {
const existingToken = checkExistingToken();
if (existingToken) {
core.setSecret(existingToken);
log.info("Using provided GitHub installation token");
return existingToken;
return { githubInstallationToken: existingToken, wasAcquired: false };
}
const token = await acquireNewToken();
const acquiredToken = await acquireNewToken();
core.setSecret(token);
process.env.GITHUB_INSTALLATION_TOKEN = token;
// If token acquisition failed (e.g., app not installed), fall back to GITHUB_TOKEN
if (!acquiredToken) {
const defaultToken = getDefaultGitHubToken();
if (!defaultToken) {
throw new Error(
"Failed to acquire installation token and GITHUB_TOKEN is not available. " +
"Either install the Pullfrog GitHub App or ensure GITHUB_TOKEN is set."
);
}
log.info("Using GITHUB_TOKEN (app not installed or token exchange failed)");
core.setSecret(defaultToken);
process.env.GITHUB_INSTALLATION_TOKEN = defaultToken;
return { githubInstallationToken: defaultToken, wasAcquired: false };
}
return token;
core.setSecret(acquiredToken);
process.env.GITHUB_INSTALLATION_TOKEN = acquiredToken;
return { githubInstallationToken: acquiredToken, wasAcquired: true };
}
/**
* Revoke GitHub installation token
*/
export async function revokeInstallationToken(token: string): Promise<void> {
const apiUrl = process.env.GITHUB_API_URL || "https://api.github.com";
try {
await fetch(`${apiUrl}/installation/token`, {
method: "DELETE",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${token}`,
"X-GitHub-Api-Version": "2022-11-28",
},
});
log.info("Installation token revoked");
} catch (error) {
log.warning(
`Failed to revoke installation token: ${error instanceof Error ? error.message : String(error)}`
);
}
}
export interface RepoContext {
-2
View File
@@ -47,7 +47,6 @@ export function setupGitConfig(): void {
// Only set up git config in GitHub Actions environment
// In local development, use the user's existing git config
if (!process.env.GITHUB_ACTIONS) {
log.warning("Skipping git configuration setup (not in GitHub Actions)");
return;
}
@@ -73,7 +72,6 @@ export function setupGitAuth(githubToken: string, repoContext: RepoContext): voi
// Only set up git auth in GitHub Actions environment
// In local testing, this would overwrite the real git remote with fake credentials
if (!process.env.GITHUB_ACTIONS) {
log.warning("Skipping git authentication setup (not in GitHub Actions)");
return;
}
+53
View File
@@ -0,0 +1,53 @@
// MCP name constant - matches action/mcp/config.ts
const ghPullfrogMcpName = "gh-pullfrog";
export const workflows = [
{
name: "Plan",
description:
"Create plans, break down tasks, outline steps, analyze requirements, understand scope of work, or provide task breakdowns",
prompt: `Follow these steps:
1. Create initial response comment using mcp__${ghPullfrogMcpName}__create_issue_comment saying "I'll {summary of request}" and save the commentId
2. Analyze the request and break it down into clear, actionable tasks
3. Consider dependencies, potential challenges, and implementation order
4. Create a structured plan with clear milestones
5. Update your comment using mcp__${ghPullfrogMcpName}__edit_issue_comment with the commentId to present the plan in a clear, organized format
6. Continue updating the same comment as needed (never create additional comments - always use edit_issue_comment)`,
},
{
name: "Implement",
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:
1. Create initial response comment using mcp__${ghPullfrogMcpName}__create_issue_comment saying "I'll {summary of request}" and save the commentId
2. Understand the requirements and any existing plan
3. Make the necessary code changes
4. Test your changes to ensure they work correctly
5. Update your comment using mcp__${ghPullfrogMcpName}__edit_issue_comment with the commentId to share progress and results
6. Continue updating the same comment as you make progress (never create additional comments - always use edit_issue_comment)`,
},
{
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. Create initial response comment using mcp__${ghPullfrogMcpName}__create_issue_comment saying "I'll review this" and save the commentId
2. Get PR info with mcp__${ghPullfrogMcpName}__get_pull_request (this automatically prepares the repository by fetching and checking out the PR branch)
3. View diff: git diff origin/<base>...origin/<head> (use line numbers from this for inline comments, replace <base> and <head> with 'base' and 'head' from PR info)
4. Read files from the checked-out PR branch to understand the implementation
5. Update your comment using mcp__${ghPullfrogMcpName}__edit_issue_comment with findings as you review
6. When submitting review: use the 'comments' array for ALL specific code issues - include the file path and line position from the diff
7. Only use the 'body' field for a brief summary (1-2 sentences) or for feedback that doesn't apply to a specific code location
8. Continue updating the same comment as needed (never create additional comments - always use edit_issue_comment)`,
},
{
name: "Prompt",
description:
"Fallback for tasks that don't fit other workflows, direct prompts via comments, or requests requiring general assistance without a specific workflow pattern",
prompt: `Follow these steps:
1. Create an initial "Progress Comment" using mcp__${ghPullfrogMcpName}__create_issue_comment saying "I'll {summary of request}" and save the commentId
2. 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.
3. As your work progresses, update your Progress Comment to share progress and results. Using mcp__${ghPullfrogMcpName}__edit_issue_comment and the commentId you saved earlier. Do not create additional comments unless you are explicitly asked to do so.
4. When you finish the task, update the Progress Comment a final time to confirm completion. If you created any issues, PRs, etc, include appropriate links to it here.`,
},
] as const;