An open-source, faster Devin alternative
TypeScript
feat(cli): add PR review readiness template (#598)
Mohamed Habib274673fd3a4c
diff --git a/cli/src/api.ts b/cli/src/api.tsindex 1feaf09a..7d51f696 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -234,7 +234,7 @@ export class OpenComputerClient {);}- linkGoogle(service: string, label: string) {+ linkManagedConnection(service: string, label: string) {return this.request<{connectionId: string;label: string;@@ -244,13 +244,14 @@ export class OpenComputerClient {connectedAccountId?: string;authorizationUrl?: string;expiresAt?: string;- }>("/api/managed-agents/connections/google/link", {+ }>("/api/managed-agents/connections/link", {method: "POST",body: JSON.stringify({ service, label }),});}- googleConnection(connectionId: string, service: string) {+ managedConnection(connectionId: string, service: string) {+ const provider = service === "github" ? "github" : "google";return this.request<{connectionId: string;label: string;@@ -261,11 +262,12 @@ export class OpenComputerClient {authorizationUrl?: string;expiresAt?: string;}>(- `/api/managed-agents/connections/google/status?service=${encodeURIComponent(service)}&connectionId=${encodeURIComponent(connectionId)}`,+ `/api/managed-agents/connections/${provider}/status?service=${encodeURIComponent(service)}&connectionId=${encodeURIComponent(connectionId)}`,);}- disconnectGoogle(connectionId: string, service: string) {+ disconnectManagedConnection(connectionId: string, service: string) {+ const provider = service === "github" ? "github" : "google";return this.request<{connectionId: string;label: string;@@ -274,7 +276,7 @@ export class OpenComputerClient {status: "disconnected";connectedAccountId?: string;}>(- `/api/managed-agents/connections/google?service=${encodeURIComponent(service)}&connectionId=${encodeURIComponent(connectionId)}`,+ `/api/managed-agents/connections/${provider}?service=${encodeURIComponent(service)}&connectionId=${encodeURIComponent(connectionId)}`,{ method: "DELETE" },);}diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 4dcf61e2..68bf6254 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -68,13 +68,14 @@ async function requireAgentRoot(): Promise<string> {return root;}-async function connectGoogle(+async function connectManagedService(client: OpenComputerClient,- service: "gmail" | "calendar",+ service: "gmail" | "calendar" | "github",label = "default",): Promise<void> {- const displayName = service === "calendar" ? "Google Calendar" : "Gmail";- const started = await client.linkGoogle(service, label);+ const displayName =+ service === "calendar" ? "Google Calendar" : service === "github" ? "GitHub" : "Gmail";+ const started = await client.linkManagedConnection(service, label);if (started.status === "connected") {process.stdout.write(`${displayName} connection "${label}" is already connected.\n`,@@ -92,7 +93,7 @@ async function connectGoogle(while (Date.now() < deadline) {await new Promise((resolve) => setTimeout(resolve, 1_500));if (- (await client.googleConnection(started.connectionId, service)).status ===+ (await client.managedConnection(started.connectionId, service)).status ==="connected") {process.stdout.write(`${displayName} connection "${label}" connected.\n`);@@ -669,7 +670,7 @@ export async function runCommand(if ((provider !== "google" && provider !== "gmail") || args.length) {throw new Error("Usage: opencomputer connect google");}- await connectGoogle(client, "gmail", "default");+ await connectManagedService(client, "gmail", "default");return;}@@ -679,12 +680,15 @@ export async function runCommand(const provider = args.shift();const alias = option(args, "--alias") ?? "default";const service = provider === "google" ? "gmail" : provider;- if ((service !== "gmail" && service !== "calendar") || args.length) {+ if (+ (service !== "gmail" && service !== "calendar" && service !== "github") ||+ args.length+ ) {throw new Error(- "Usage: opencomputer connection add <gmail|calendar> [--alias <name>]",+ "Usage: opencomputer connection add <gmail|calendar|github> [--alias <name>]",);}- await connectGoogle(client, service, alias);+ await connectManagedService(client, service, alias);return;}if (action === "remove" || action === "disconnect") {@@ -714,9 +718,10 @@ export async function runCommand()? "calendar": "gmail";+ const managedService = connection.provider === "github" ? "github" : googleService;const disconnected =- connection.provider === "google"- ? await client.disconnectGoogle(connection.id, googleService)+ connection.provider === "google" || connection.provider === "github"+ ? await client.disconnectManagedConnection(connection.id, managedService): await client.disconnectConnection(connection.id);if (globals.json) printJSON(disconnected);else process.stdout.write(`Removed connection "${connection.label}".\n`);diff --git a/cli/src/index.ts b/cli/src/index.tsindex 1b5bb38f..507ce286 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -51,7 +51,7 @@ Usage:opencomputer session send <session-id> <prompt> [--keep]opencomputer session end <session-id>opencomputer tools add <gmail|calendar>- opencomputer connection add <gmail|calendar> [--alias <name>]+ opencomputer connection add <gmail|calendar|github> [--alias <name>]opencomputer connection listopencomputer connection remove <alias|connection-id>opencomputer channels list [--local|--remote]diff --git a/cli/src/local.test.ts b/cli/src/local.test.tsindex 6fd12731..dce54d59 100644--- a/cli/src/local.test.ts+++ b/cli/src/local.test.ts@@ -49,7 +49,7 @@ test("the local gateway proxies connection list and calendar requests", async ()assert.equal(requested.status, 200);assert.equal(upstream[1]?.url,- "https://mo-oc-dev.com/api/managed-agents/connections/google/link",+ "https://mo-oc-dev.com/api/managed-agents/connections/link",);assert.equal(upstream[1]?.init?.method, "POST");assert.deepEqual(JSON.parse(String(upstream[1]?.init?.body)), {diff --git a/cli/src/local.ts b/cli/src/local.tsindex ecbc2d19..58aafd8b 100644--- a/cli/src/local.ts+++ b/cli/src/local.ts@@ -138,8 +138,12 @@ export async function startGateway(config: ResolvedConfig): Promise<{let target: string;let upstreamMethod = request.method;let upstreamBody: Buffer | string | undefined;- if (request.method === "POST" && url.pathname === "/google/fetch") {- target = `${config.apiUrl}/api/managed-agents/connections/google/fetch`;+ if (+ request.method === "POST" &&+ (url.pathname === "/google/fetch" || url.pathname === "/github/fetch")+ ) {+ const provider = url.pathname.startsWith("/github/") ? "github" : "google";+ target = `${config.apiUrl}/api/managed-agents/connections/${provider}/fetch`;upstreamBody = await readBody(request);} else if (request.method === "POST" &&@@ -166,12 +170,12 @@ export async function startGateway(config: ResolvedConfig): Promise<{const service = input.service;if (typeof service !== "string" ||- !["gmail", "calendar", "drive", "sheets"].includes(service)+ !["gmail", "calendar", "drive", "sheets", "github"].includes(service)) {sendJSON(response, 400, {error: {message:- "Expected one of gmail, calendar, drive, or sheets",+ "Expected one of gmail, calendar, drive, sheets, or github",},});return;@@ -185,7 +189,7 @@ export async function startGateway(config: ResolvedConfig): Promise<{(input.newAccount === true? `${service}-${randomUUID().slice(0, 8)}`: "default");- target = `${config.apiUrl}/api/managed-agents/connections/google/link`;+ target = `${config.apiUrl}/api/managed-agents/connections/link`;upstreamMethod = "POST";upstreamBody = JSON.stringify({ service, label });} else {diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex fb5d3a07..bae9ef93 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -43,6 +43,15 @@ const ptoTemplate: ManagedAgentTemplate = {suggestedPrompts: ["Prepare PTO and check conflicts."],};+const prReviewTemplate: ManagedAgentTemplate = {+ id: "pr-review-readiness",+ name: "PR review readiness",+ description: "Decide whether a connected PR is ready for human review.",+ category: "Coding",+ integrations: ["GitHub"],+ suggestedPrompts: ["Review this pull request."],+};+test("a template creates a flat agent repository with stable identity", async () => {const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-agent-"));const original = resolve(parent, "my-inbox-agent");@@ -122,7 +131,7 @@ test("the compiler maps flat source into an OpenCode runtime", async () => {assert.match(connectionTool, /newAccount/);assert.match(connectionTool,- /schema\.enum\(\["gmail", "calendar", "drive", "sheets"\]\)/,+ /schema\.enum\(\["gmail", "calendar", "drive", "sheets", "github"\]\)/,);assert.equal(connectionTool.includes('base.replace(/\\\/$/, "")'), true);const transpiledConnectionTool = ts.transpileModule(connectionTool, {@@ -312,3 +321,66 @@ test("an incomplete PTO project cannot be packaged without Calendar tools", asynawait rm(root, { recursive: true, force: true });}});++test("the PR readiness template creates brokered read-only GitHub tools", async () => {+ const root = await mkdtemp(resolve(tmpdir(), "pr-review-readiness-"));+ try {+ const initialized = await initializeAgentProject(prReviewTemplate, root);+ assert.ok(initialized.files.includes("tools/github.ts"));+ const githubTool = await readFile(+ resolve(root, "tools", "github.ts"),+ "utf8",+ );+ assert.match(githubTool, /export const pr_context = tool/);+ assert.match(githubTool, /export const checkout = tool/);+ assert.match(githubTool, /issues\/.*\/comments/);+ assert.match(githubTool, /pulls\/.*\/reviews/);+ assert.match(githubTool, /pulls\/.*\/files/);+ assert.match(githubTool, /application\/vnd\.github\.v3\.diff/);+ assert.match(githubTool, /OPENCOMPUTER_CONNECTIONS_URL/);+ assert.match(githubTool, /\/github\/fetch/);+ assert.match(githubTool, /method: "GET"/);+ assert.match(githubTool, /\/contents\//);+ assert.match(githubTool, /MAX_CHECKOUT_FILES = 100/);+ assert.match(githubTool, /resolve\(context\.directory\)/);+ assert.doesNotMatch(githubTool, /destination: tool\.schema\.string/);+ assert.doesNotMatch(githubTool, /\/tarball\//);+ assert.match(githubTool, /remoteConfigured: false/);+ assert.doesNotMatch(githubTool, /api\.github\.com/);+ assert.doesNotMatch(githubTool, /git push/i);+ const transpiledGithubTool = ts.transpileModule(githubTool, {+ compilerOptions: {+ module: ts.ModuleKind.ESNext,+ target: ts.ScriptTarget.ES2022,+ },+ reportDiagnostics: true,+ });+ assert.equal(+ transpiledGithubTool.diagnostics?.length ?? 0,+ 0,+ transpiledGithubTool.diagnostics+ ?.map((diagnostic) =>+ ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),+ )+ .join("\n"),+ );++ const instructions = await readFile(+ resolve(root, "instructions.md"),+ "utf8",+ );+ assert.match(instructions, /READY_FOR_HUMAN_REVIEW/);+ assert.match(instructions, /NOT_READY/);+ assert.match(instructions, /NEEDS_INFORMATION/);+ assert.match(instructions, /credentials remain in the OpenComputer control plane/);+ assert.match(instructions, /Never push/);+ assert.match(instructions, /current OpenComputer session/);++ const built = await buildAgentArtifact(root);+ assert.deepEqual(built.connections, ["github"]);+ assert.deepEqual(built.channels, []);+ assert.match(built.body.toString("utf8"), /tools\/github\.ts/);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/cli/src/project.ts b/cli/src/project.tsindex 3ff00f09..689cc931 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -90,6 +90,14 @@ async function prepareInitializationTarget("package.json","agent.ts","instructions.md",+ ...(template.id === "pr-review-readiness"+ ? [+ "tools/github.ts",+ "connections/github.json",+ "skills/review-pr/SKILL.md",+ "evals/pr-review-cases.md",+ ]+ : []),...(template.integrations.includes("Gmail")? ["tools/gmail.ts", "connections/google.json"]: []),@@ -256,6 +264,63 @@ user's managed connection and cannot authenticate as that user.## Example requests+${template.suggestedPrompts.map((prompt) => `- ${prompt}`).join("\n")}+`;+ }+ if (template.id === "pr-review-readiness") {+ return `# ${template.name}++You are a code-review readiness agent. Decide whether a connected GitHub pull+request is ready to consume a human reviewer's attention.++${template.description}++## Required workflow++1. Require an exact GitHub pull request URL and a connected GitHub account with+ access to its repository.+2. Call the \`github_pr_context\` tool. Record the current head SHA and treat+ every conclusion as applying only to that SHA.+3. Read every returned issue comment, submitted review, inline review comment,+ changed-file record, and available diff hunk. Group inline replies using+ their reply relationships.+4. Do not call \`github_checkout\` by default. Use it only when the returned+ diff and file patches are insufficient and surrounding repository guidance+ is needed. It materializes a bounded exact-head working set containing the+ changed files plus relevant instructions and manifests; it does not download+ the entire repository or create a Git remote. Read materialized files from+ the relative \`destination\` returned by the tool.+5. Reconcile every substantive prior review finding against the current head.+ A resolved conversation is evidence, not proof: verify the current code.+6. Review the complete available change for correctness, security, regressions,+ error handling, test coverage, and repository conventions. Run focused local+ tests when practical, but never claim a test passed unless it completed.+7. Return exactly one verdict:+ - \`READY_FOR_HUMAN_REVIEW\`: no known blocking issue remains and the change+ has adequate validation for a human to review efficiently.+ - \`NOT_READY\`: one or more actionable blocking issues remain.+ - \`NEEDS_INFORMATION\`: required code, diff content, repository access, or+ validation is unavailable.++## Output++Lead with the verdict and head SHA. Then provide blocking findings, prior+review-comment status, validation performed, non-blocking notes, and the+recommended next action. Cite file paths and lines when evidence allows it.+Return the complete report in the current OpenComputer session.++## Immutable safety boundary++GitHub credentials remain in the OpenComputer control plane. The runtime gets+only a session-scoped broker token, and the broker permits only allowlisted GET+requests even though GitHub's classic private-repository OAuth scope is broad.+Never push, create a branch, approve, merge, request changes, dismiss a review,+or post/edit/delete a GitHub comment. Never add a Git remote or attempt to+discover credentials. If the connected account cannot access the PR, return+\`NEEDS_INFORMATION\` with the exact limitation.++## Example requests+${template.suggestedPrompts.map((prompt) => `- ${prompt}`).join("\n")}`;}@@ -618,6 +683,292 @@ export const create_time_off = tool({`;}+function githubReviewToolSource(): string {+ return `import { mkdir, writeFile } from "node:fs/promises";+import { resolve, sep } from "node:path";+import { tool } from "@opencode-ai/plugin";++const MAX_PAGES = 10;+const MAX_CHECKOUT_FILES = 100;+const MAX_CHECKOUT_BYTES = 20 * 1024 * 1024;++function parsePullRequestUrl(value: string): {+ repository: string;+ number: number;+} {+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ throw new Error("pullRequestUrl must be a complete GitHub pull request URL");+ }+ const parts = url.pathname.split("/").filter(Boolean);+ const number = Number(parts[3]);+ if (+ url.protocol !== "https:" ||+ url.hostname.toLowerCase() !== "github.com" ||+ parts.length !== 4 ||+ parts[2] !== "pull" ||+ !Number.isSafeInteger(number) ||+ number < 1 ||+ !/^[A-Za-z0-9_.-]+$/.test(parts[0] ?? "") ||+ !/^[A-Za-z0-9_.-]+$/.test(parts[1] ?? "")+ ) {+ throw new Error("Expected https://github.com/<owner>/<repository>/pull/<number>");+ }+ return { repository: parts[0] + "/" + parts[1], number };+}++async function githubFetch(path: string, accept = "application/vnd.github+json") {+ const base = process.env.OPENCOMPUTER_CONNECTIONS_URL;+ const token = process.env.OPENCOMPUTER_CONNECTION_TOKEN;+ if (!base || !token) {+ throw new Error("OpenComputer GitHub connection is unavailable");+ }+ const response = await fetch(base.replace(/\\\/$/, "") + "/github/fetch", {+ method: "POST",+ headers: {+ authorization: "Bearer " + token,+ "content-type": "application/json",+ },+ body: JSON.stringify({+ service: "github",+ method: "GET",+ path,+ headers: { accept, "x-github-api-version": "2022-11-28" },+ }),+ });+ if (!response.ok) {+ const failure = (await response.json().catch(() => ({}))) as {+ error?: { message?: string };+ };+ throw new Error(failure.error?.message ?? "GitHub connection request failed");+ }+ const result = (await response.json()) as {+ status?: number;+ body?: string;+ };+ if (!result.status || result.status >= 400) {+ throw new Error(result.body ?? "GitHub request failed");+ }+ return result.body ?? "";+}++async function githubJson(path: string): Promise<Record<string, unknown>> {+ return JSON.parse(await githubFetch(path)) as Record<string, unknown>;+}++async function githubPages(path: string): Promise<{+ items: Record<string, unknown>[];+ truncated: boolean;+}> {+ const items: Record<string, unknown>[] = [];+ let lastPageWasFull = false;+ for (let page = 1; page <= MAX_PAGES; page += 1) {+ const separator = path.includes("?") ? "&" : "?";+ const batch = JSON.parse(+ await githubFetch(path + separator + "per_page=100&page=" + String(page)),+ ) as Record<string, unknown>[];+ items.push(...batch);+ lastPageWasFull = batch.length === 100;+ if (!lastPageWasFull) break;+ }+ return { items, truncated: lastPageWasFull };+}++export const pr_context = tool({+ description:+ "Read-only: fetch an accessible GitHub PR, all available issue comments, reviews, inline review comments, changed files, and the full available diff through the connection broker.",+ args: {+ pullRequestUrl: tool.schema.string(),+ },+ async execute(args) {+ const { repository, number } = parsePullRequestUrl(args.pullRequestUrl);+ const prefix = "/repos/" + repository;+ const [pull, comments, reviews, reviewComments, files] = await Promise.all([+ githubJson(prefix + "/pulls/" + String(number)),+ githubPages(prefix + "/issues/" + String(number) + "/comments"),+ githubPages(prefix + "/pulls/" + String(number) + "/reviews"),+ githubPages(prefix + "/pulls/" + String(number) + "/comments"),+ githubPages(prefix + "/pulls/" + String(number) + "/files"),+ ]);+ let diff: string | undefined;+ try {+ diff = await githubFetch(+ prefix + "/pulls/" + String(number),+ "application/vnd.github.v3.diff",+ );+ } catch {+ // Per-file patches remain available. The completeness marker below tells+ // the reviewer that it must not claim full-diff coverage.+ }+ const head =+ pull.head && typeof pull.head === "object"+ ? (pull.head as Record<string, unknown>)+ : {};+ const base =+ pull.base && typeof pull.base === "object"+ ? (pull.base as Record<string, unknown>)+ : {};+ const maximumDiff = 2_000_000;+ return JSON.stringify({+ repository,+ number,+ url: args.pullRequestUrl,+ pull: {+ title: pull.title,+ body: pull.body,+ state: pull.state,+ draft: pull.draft,+ mergeable: pull.mergeable,+ mergeableState: pull.mergeable_state,+ author: pull.user,+ additions: pull.additions,+ deletions: pull.deletions,+ changedFiles: pull.changed_files,+ head: { ref: head.ref, sha: head.sha },+ base: { ref: base.ref, sha: base.sha },+ },+ comments: comments.items,+ reviews: reviews.items,+ reviewComments: reviewComments.items,+ files: files.items,+ diff: diff?.slice(0, maximumDiff),+ completeness: {+ comments: !comments.truncated,+ reviews: !reviews.truncated,+ reviewComments: !reviewComments.truncated,+ files: !files.truncated,+ diff: Boolean(diff) && (diff?.length ?? 0) <= maximumDiff,+ },+ });+ },+});++export const checkout = tool({+ description:+ "Read-only: materialize changed files plus relevant repository instructions and manifests from the exact PR head into a bounded session-workspace directory, without downloading the whole repository or creating a Git remote. Use the destination returned by this tool for subsequent file reads.",+ args: {+ pullRequestUrl: tool.schema.string(),+ },+ async execute(args, context) {+ const { repository, number } = parsePullRequestUrl(args.pullRequestUrl);+ const pull = await githubJson(+ "/repos/" + repository + "/pulls/" + String(number),+ );+ const head =+ pull.head && typeof pull.head === "object"+ ? (pull.head as Record<string, unknown>)+ : {};+ if (typeof head.sha !== "string" || !/^[a-f0-9]{40}$/i.test(head.sha)) {+ throw new Error("GitHub did not return a valid PR head SHA");+ }+ const workspace = resolve(context.directory);+ const destinationName =+ "github-pr-" + number + "-" + head.sha.slice(0, 12).toLowerCase();+ const destination = resolve(workspace, destinationName);+ if (!destination.startsWith(workspace + sep)) {+ throw new Error("generated checkout destination escaped the workspace");+ }+ const changed = await githubPages(+ "/repos/" + repository + "/pulls/" + String(number) + "/files",+ );+ const changedPaths = new Set(+ changed.items+ .map((file) => file.filename)+ .filter((path): path is string => typeof path === "string"),+ );+ const candidates = new Set(changedPaths);+ const guidanceNames = [+ "AGENTS.md",+ "README.md",+ "CONTRIBUTING.md",+ "package.json",+ "pnpm-workspace.yaml",+ "go.mod",+ "go.work",+ "Cargo.toml",+ "pyproject.toml",+ "requirements.txt",+ ];+ for (const name of guidanceNames) candidates.add(name);+ for (const path of changedPaths) {+ const parts = path.split("/");+ for (let depth = 1; depth < parts.length; depth += 1) {+ const directory = parts.slice(0, depth).join("/");+ for (const name of ["AGENTS.md", "README.md", "package.json"]) {+ candidates.add(directory + "/" + name);+ }+ }+ }+ const requested = [...candidates].slice(0, MAX_CHECKOUT_FILES);+ await mkdir(destination, { recursive: true });+ const materialized: string[] = [];+ const missingChanged: string[] = [];+ let totalBytes = 0;+ let limitExceeded = false;+ for (let offset = 0; offset < requested.length; offset += 8) {+ const batch = requested.slice(offset, offset + 8);+ await Promise.all(+ batch.map(async (path) => {+ const encodedPath = path.split("/").map(encodeURIComponent).join("/");+ try {+ const file = await githubJson(+ "/repos/" + repository + "/contents/" + encodedPath + "?ref=" + head.sha,+ );+ let content: Buffer;+ if (file.encoding === "base64" && typeof file.content === "string") {+ content = Buffer.from(file.content.replace(/\\s+/g, ""), "base64");+ } else if (typeof file.sha === "string" && /^[a-f0-9]{40}$/i.test(file.sha)) {+ const blob = await githubJson(+ "/repos/" + repository + "/git/blobs/" + file.sha,+ );+ if (blob.encoding !== "base64" || typeof blob.content !== "string") {+ throw new Error("unsupported GitHub content encoding");+ }+ content = Buffer.from(blob.content.replace(/\\s+/g, ""), "base64");+ } else {+ throw new Error("GitHub did not return file content");+ }+ totalBytes += content.byteLength;+ if (totalBytes > MAX_CHECKOUT_BYTES) {+ limitExceeded = true;+ throw new Error("bounded checkout exceeds 20 MiB");+ }+ const output = resolve(destination, path);+ if (!output.startsWith(destination + sep)) {+ throw new Error("GitHub returned an unsafe repository path");+ }+ await mkdir(resolve(output, ".."), { recursive: true });+ await writeFile(output, content);+ materialized.push(path);+ } catch (error) {+ if (changedPaths.has(path)) missingChanged.push(path);+ }+ }),+ );+ }+ return JSON.stringify({+ repository,+ pullRequestNumber: number,+ headSha: head.sha,+ destination: destinationName,+ materialized: materialized.sort(),+ bytes: totalBytes,+ missingChanged: missingChanged.sort(),+ complete:+ !changed.truncated &&+ candidates.size <= MAX_CHECKOUT_FILES &&+ !limitExceeded &&+ missingChanged.length === 0,+ scope: "changed files plus relevant instructions and manifests",+ remoteConfigured: false,+ });+ },+});+`;+}+function connectionControlToolSource(): string {return `import { tool } from "@opencode-ai/plugin";@@ -691,7 +1042,7 @@ export const request = tool({description:"Ask the current user to connect an account. Use gmail for an email account. Set newAccount=true when the user asks for another account of the same service. In a messaging channel OpenComputer privately sends the authorization link to that user; otherwise the result includes the link.",args: {- service: tool.schema.enum(["gmail", "calendar", "drive", "sheets"]),+ service: tool.schema.enum(["gmail", "calendar", "drive", "sheets", "github"]),label: tool.schema.string().optional(),newAccount: tool.schema.boolean().optional(),},@@ -845,6 +1196,24 @@ export async function addCalendarTools(root: string): Promise<string[]> {return ["tools/calendar.ts", "connections/google.json"];}+export async function addGithubReviewTools(root: string): Promise<string[]> {+ await mkdir(resolve(root, "tools"), { recursive: true });+ await mkdir(resolve(root, "connections"), { recursive: true });+ await writeFile(+ resolve(root, "tools", "github.ts"),+ githubReviewToolSource(),+ );+ await writeFile(+ resolve(root, "connections", "github.json"),+ `${JSON.stringify(+ { provider: "github", services: ["github"], scopes: ["repo"] },+ null,+ 2,+ )}\n`,+ );+ return ["tools/github.ts", "connections/github.json"];+}+export async function addSlackChannel(root: string): Promise<string[]> {await mkdir(resolve(root, "channels"), { recursive: true });await mkdir(resolve(root, "slack"), { recursive: true });@@ -1013,6 +1382,72 @@ export async function initializeAgentProject(if (template.integrations.includes("Google Calendar")) {files.push(...(await addCalendarTools(root)));}+ if (template.id === "pr-review-readiness") {+ files.push(...(await addGithubReviewTools(root)));+ await mkdir(resolve(root, "skills", "review-pr"), { recursive: true });+ await writeFile(+ resolve(root, "skills", "review-pr", "SKILL.md"),+ `---+name: review-pr+description: Decide whether a connected GitHub pull request is ready for human review.+---++# Review PR readiness++1. Call \`github_pr_context\` with the exact PR URL.+2. Record the returned head SHA and completeness markers.+3. Read all prior review feedback and map it to the current code.+4. Call \`github_checkout\` only when the diff is insufficient and surrounding+ repository instructions are required. It creates a bounded exact-head+ working set and no Git remote. Read files from its returned relative+ \`destination\`.+5. Verify every prior finding against the current head.+6. Return \`NEEDS_INFORMATION\` if any context required for a sound conclusion+ is unavailable or marked incomplete.+7. Otherwise return \`READY_FOR_HUMAN_REVIEW\` or \`NOT_READY\` using the rubric+ in the agent instructions.++Never use GitHub write APIs, add a Git remote, or search for credentials.+`,+ );+ await writeFile(+ resolve(root, "evals", "pr-review-cases.md"),+ `# PR review readiness acceptance cases++## Addressed prior feedback++Prompt: Review a PR whose latest head fixes every earlier blocker.++Pass criteria:++- Reads PR metadata, all comment sources, changed files, and the available diff.+- Records the exact head SHA and checks response completeness.+- Verifies fixes in current code rather than trusting resolved-thread state.+- Returns READY_FOR_HUMAN_REVIEW only when no blocker remains.+- Performs no GitHub write and creates no Git remote.++## Remaining blocker++Prompt: Review a PR with an unresolved correctness regression.++Pass criteria:++- Returns NOT_READY and leads with the concrete blocker.+- Cites the affected file and explains the failure mode.+- Distinguishes prior-review status from newly discovered findings.++## Inaccessible or incomplete PR++Prompt: Review a PR that the connected account cannot access or whose response has incomplete pagination.++Pass criteria:++- Returns NEEDS_INFORMATION rather than guessing readiness.+- Identifies the exact access, content, or validation limitation.+`,+ );+ files.push("skills/review-pr/SKILL.md", "evals/pr-review-cases.md");+ }if (template.id === "email-triage") {await mkdir(resolve(root, "skills", "triage-inbox"), {recursive: true,@@ -1284,6 +1719,19 @@ async function validateTemplateRequirements(root: string,manifest: AgentManifest,): Promise<void> {+ if (manifest.template === "pr-review-readiness") {+ for (const path of [+ "tools/github.ts",+ "connections/github.json",+ "skills/review-pr/SKILL.md",+ "evals/pr-review-cases.md",+ ]) {+ if (!(await exists(resolve(root, path)))) {+ throw new Error(`PR review readiness file is missing: ${path}`);+ }+ }+ return;+ }if (manifest.template !== "pto-calendar") return;let calendarDeclared = false;try {diff --git a/web/src/managed-agents/Home.tsx b/web/src/managed-agents/Home.tsxindex fc806f19..44dad14e 100644--- a/web/src/managed-agents/Home.tsx+++ b/web/src/managed-agents/Home.tsx@@ -9,6 +9,7 @@ import {Clock3,Clipboard,ClipboardCheck,+ Code2,Lightbulb,Loader2,MessageSquareText,@@ -46,6 +47,7 @@ import {const categories = ['Comms',+ 'Coding','Operations','Admin','Growth',@@ -58,15 +60,29 @@ type CliStep = {commands: string[]}-const availableTemplateIds = new Set(['email-triage', 'pto-calendar'])+const availableTemplateIds = new Set([+ 'email-triage',+ 'pr-review-readiness',+ 'pto-calendar',+])function templateSetup(template: ManagedAgentTemplate) {+ if (template.id === 'pr-review-readiness') {+ return {+ directory: 'pr-review-readiness',+ connectionName: 'GitHub',+ connectionCommand: 'connection add github --alias default',+ toolCommand: '',+ requiresConnection: true,+ }+ }if (template.id === 'pto-calendar') {return {directory: 'pto-calendar',connectionName: 'Google Calendar',connectionCommand: 'connection add calendar --alias work-calendar',toolCommand: 'tools add calendar',+ requiresConnection: true,}}return {@@ -74,6 +90,7 @@ function templateSetup(template: ManagedAgentTemplate) {connectionName: 'Gmail',connectionCommand: 'connection add gmail --alias personal',toolCommand: 'tools add gmail',+ requiresConnection: true,}}@@ -106,6 +123,7 @@ const starterCopy = [const categoryIcons = {Comms: MessageSquareText,+ Coding: Code2,Operations: Workflow,Admin: BriefcaseBusiness,Growth: TrendingUp,@@ -132,6 +150,10 @@ function buildSetupPrompt(template: ManagedAgentTemplate, origin: string) {const integrations = template.integrations.join(', ')const firstPrompt =template.suggestedPrompts[0] ?? `Help me configure ${template.name}.`+ const connectionCommands = [setup.toolCommand, setup.connectionCommand]+ .filter(Boolean)+ .map((command) => `\`${cliCommand(origin, command)}\``)+ .join(' and ')return `Create a local "${template.name}" OpenComputer agent repository for me.The agent's job:@@ -150,7 +172,11 @@ Use the OpenComputer CLI and keep the agent as editable source code in this work4. Run \`npm install\` in the repository.5. Inspect and tailor the checked-in source: \`opencomputer.toml\`, \`instructions.md\`, \`agent.ts\`, \`tools/\`, \`connections/\`, \`skills/\`, \`workspace/\`, and \`evals/\`.6. Keep the stable \`id\` in \`opencomputer.toml\`; future deployments of this repository must create new versions of that same agent.-7. Add and authorize the ${setup.connectionName} connection with \`${cliCommand(origin, setup.toolCommand)}\` and \`${cliCommand(origin, setup.connectionCommand)}\`. Connect Slack from the deployed agent's Channels tab after deployment.+7. ${+ setup.requiresConnection+ ? `Add and authorize the ${setup.connectionName} connection with ${connectionCommands}.`+ : 'Connect GitHub to review public or private pull requests. GitHub credentials stay in the control plane, and the agent can use only allowlisted read requests.'+ }8. Test the editable agent locally with the OpenComputer CLI:\`opencomputer session "${firstPrompt.replace(/"/g, '\\"')}"\`9. Make any necessary source changes and test again.@@ -185,10 +211,14 @@ function buildCliSteps('npm install',],},- {- title: `Connect your ${setup.connectionName} account`,- commands: [cliCommand(origin, setup.connectionCommand)],- },+ ...(setup.requiresConnection+ ? [+ {+ title: `Connect your ${setup.connectionName} account`,+ commands: [cliCommand(origin, setup.connectionCommand)],+ },+ ]+ : []),{title: 'Test the agent locally',commands: [