@eduardo191labs/opencode-actions 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,561 @@
1
+ import { rm } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { bot, feature, permission } from "./config.js";
5
+ import { compileConfig, repoFacts } from "./compile.js";
6
+ import { runOpencode, readResult } from "./runner.js";
7
+ import { autofixPrompt, commandPrompt, describePrompt, issuePrompt, reviewPrompt, } from "./prompts.js";
8
+ import { autofixBody, commandReplyBody, diffDigest, filesSummary, findingBody, issueTriageBody, reviewSummaryBody, severityRank, } from "./format.js";
9
+ import { assertBranchWrites, assertWorkflowWrites, commitAll, git, push, state } from "./git.js";
10
+ import { helpText, canRun } from "./commands.js";
11
+ export async function reviewPullRequest(ctx, options) {
12
+ const { github, repo, config } = ctx;
13
+ const pull = await github.getPull(repo, options.prNumber);
14
+ if (!feature(config, "pull_request_review")) {
15
+ ctx.log("pull_request_review is disabled");
16
+ return { skipped: true };
17
+ }
18
+ if (isSkipped(config, pull)) {
19
+ ctx.log(`PR #${pull.number} is excluded by review filters`);
20
+ return { skipped: true };
21
+ }
22
+ // A review is read-only by contract. It reads the checkout, never writes to it,
23
+ // and the only GitHub write it performs is posting comments with suggestions.
24
+ const before = await state(ctx.workspace).catch(() => null);
25
+ const files = await github.listPullFiles(repo, pull.number);
26
+ const filtered = filterFiles(config, files);
27
+ ctx.log(`reviewing ${filtered.length}/${files.length} changed files`);
28
+ const facts = repoFacts(await listRootFiles(ctx));
29
+ const compiled = compileConfig(config, { mode: "review" });
30
+ for (const warning of compiled.warnings)
31
+ ctx.log(`config: ${warning}`);
32
+ const prompt = reviewPrompt({
33
+ config,
34
+ repo: `${repo.owner}/${repo.repo}`,
35
+ prNumber: pull.number,
36
+ title: pull.title,
37
+ author: pull.user.login,
38
+ base: pull.base.ref,
39
+ head: pull.head.ref,
40
+ filesSummary: filesSummary(filtered),
41
+ diffDigest: diffDigest(filtered, (bot(config).review?.max_diff_kb ?? 256) * 1024),
42
+ facts,
43
+ extraInstructions: bot(config).review?.instructions,
44
+ });
45
+ const result = await runWithPrompt(ctx, "review", prompt, compiled.content);
46
+ const review = parseReview(result, ctx);
47
+ const meta = { model: compiled.model, cost: result.cost, durationMs: result.durationMs };
48
+ const body = reviewSummaryBody(config, review, meta);
49
+ const event = reviewEvent(config, review);
50
+ const comments = options.inline === false ? [] : buildInlineComments(config, files, review);
51
+ if (permission(config, "comment") === "allow") {
52
+ await github.createReview(repo, pull.number, { body, event, comments });
53
+ ctx.log(`posted review: ${comments.length} suggestion comment(s), verdict ${event}`);
54
+ }
55
+ else {
56
+ ctx.log("comment permission denied; not posting the review");
57
+ }
58
+ // Defence in depth: if anything touched the tree, undo it. A review must never
59
+ // leave the workspace modified, no matter what the agent tried to do.
60
+ if (before?.dirty === false) {
61
+ const after = await state(ctx.workspace).catch(() => null);
62
+ if (after?.dirty) {
63
+ ctx.log(`WARNING: review modified ${after.changedFiles.length} file(s); this should not happen`);
64
+ await git(ctx.workspace, ["checkout", "--", "."]).catch(() => { });
65
+ await git(ctx.workspace, ["clean", "-fd"]).catch(() => { });
66
+ }
67
+ }
68
+ return { review, posted: event, inline: comments.length };
69
+ }
70
+ function isSkipped(config, pull) {
71
+ const review = bot(config).review ?? {};
72
+ if (pull.draft && review.draft !== true)
73
+ return true;
74
+ if (review.ignore_titles?.some((pattern) => new RegExp(pattern).test(pull.title)))
75
+ return true;
76
+ const labels = new Set(pull.labels?.map((label) => label.name) ?? []);
77
+ if (review.skip_labels?.some((label) => labels.has(label)))
78
+ return true;
79
+ if (review.require_labels?.length && !review.require_labels.every((label) => labels.has(label)))
80
+ return true;
81
+ return false;
82
+ }
83
+ function filterFiles(config, files) {
84
+ const review = bot(config).review ?? {};
85
+ const maxKb = review.max_file_kb ?? 512;
86
+ return files.filter((file) => {
87
+ if (review.include?.length && !review.include.some((pattern) => matchGlob(pattern, file.filename)))
88
+ return false;
89
+ if (review.exclude?.some((pattern) => matchGlob(pattern, file.filename)))
90
+ return false;
91
+ if ((file.changes ?? 0) * 40 > maxKb * 1024)
92
+ return false;
93
+ return true;
94
+ });
95
+ }
96
+ export function matchGlob(pattern, value) {
97
+ const escaped = pattern
98
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
99
+ .replace(/\*\*/g, "@@")
100
+ .replace(/\*/g, "[^/]*")
101
+ .replace(/@@/g, ".*");
102
+ return new RegExp(`^${escaped}$`).test(value);
103
+ }
104
+ function parseReview(result, ctx) {
105
+ const parsed = result.resultJson;
106
+ if (!parsed) {
107
+ ctx.log("the agent did not write a structured review; falling back to its text");
108
+ return { summary: result.text.trim() || "No review produced.", verdict: "COMMENT", findings: [] };
109
+ }
110
+ const review = bot(ctx.config).review ?? {};
111
+ const min = severityRank(review.min_severity ?? "low");
112
+ const findings = (parsed.findings ?? [])
113
+ .filter((finding) => severityRank(finding.severity) <= min)
114
+ .slice(0, review.max_comments ?? 25)
115
+ .map((finding) => ({ ...finding, line: Number(finding.line) }));
116
+ return {
117
+ summary: parsed.summary?.trim() || "Review complete.",
118
+ verdict: parsed.verdict ?? "COMMENT",
119
+ findings,
120
+ strengths: parsed.strengths,
121
+ };
122
+ }
123
+ /**
124
+ * A review posts inline comments only. It never approves and never requests
125
+ * changes by default: the author decides what to accept, and every finding
126
+ * carries a one-click ```suggestion block when a concrete fix exists.
127
+ */
128
+ function reviewEvent(config, review) {
129
+ const cfg = bot(config).review ?? {};
130
+ if (review.verdict === "APPROVE" && cfg.approve_when_clean === true)
131
+ return "APPROVE";
132
+ switch (cfg.on_findings) {
133
+ // Opt-in blocking modes, for teams that want the review to gate the merge button.
134
+ case "request_changes":
135
+ case "comment_and_request_changes":
136
+ return "REQUEST_CHANGES";
137
+ case "approve":
138
+ return review.verdict === "APPROVE" ? "APPROVE" : "COMMENT";
139
+ // Default: a plain review comment. GitHub renders suggestions as
140
+ // "Commit suggestion" buttons the author can apply one at a time.
141
+ default:
142
+ return "COMMENT";
143
+ }
144
+ }
145
+ /**
146
+ * GitHub rejects an inline comment whose line is not part of the diff, and one
147
+ * bad comment fails the whole review. Keep only lines we can prove are in the
148
+ * patch, so a single hallucinated line never discards a valid review.
149
+ */
150
+ export function buildInlineComments(config, files, review) {
151
+ const linesByFile = new Map();
152
+ for (const file of files) {
153
+ linesByFile.set(file.filename, rightSideLines(file.patch ?? ""));
154
+ }
155
+ const comments = [];
156
+ for (const finding of review.findings) {
157
+ const lines = linesByFile.get(finding.path);
158
+ if (!lines || !lines.has(finding.line))
159
+ continue;
160
+ comments.push({ path: finding.path, line: finding.line, side: "RIGHT", body: findingBody(config, finding) });
161
+ }
162
+ return comments;
163
+ }
164
+ /** Extract line numbers that exist on the new side of a unified diff. */
165
+ export function rightSideLines(patch) {
166
+ const lines = new Set();
167
+ if (!patch)
168
+ return lines;
169
+ let current = 0;
170
+ for (const raw of patch.split("\n")) {
171
+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw);
172
+ if (hunk) {
173
+ current = Number(hunk[1]) - 1;
174
+ continue;
175
+ }
176
+ if (raw.startsWith("+")) {
177
+ current += 1;
178
+ lines.add(current);
179
+ }
180
+ else if (raw.startsWith(" ")) {
181
+ current += 1;
182
+ lines.add(current);
183
+ }
184
+ }
185
+ return lines;
186
+ }
187
+ // --------------------------------------------------------------------- issues
188
+ export async function handleIssue(ctx, number, mode) {
189
+ const { github, repo, config } = ctx;
190
+ if (!feature(config, "issues"))
191
+ return { skipped: true };
192
+ const issue = await github.getIssue(repo, number);
193
+ if (issue.pull_request)
194
+ return { skipped: true, reason: "this is a pull request" };
195
+ const comments = await github.paginate(`/repos/${repo.owner}/${repo.repo}/issues/${number}/comments?per_page=100`, 3);
196
+ const discussion = comments
197
+ .slice(-20)
198
+ .map((comment) => `**@${comment.user.login}:** ${comment.body}`)
199
+ .join("\n\n");
200
+ const compiled = compileConfig(config, { mode: mode === "implement" ? "implement" : "issues" });
201
+ const prompt = issuePrompt({
202
+ config,
203
+ repo: `${repo.owner}/${repo.repo}`,
204
+ number: issue.number,
205
+ title: issue.title,
206
+ body: issue.body ?? "",
207
+ labels: issue.labels.map((label) => label.name),
208
+ comments: discussion,
209
+ facts: repoFacts(await listRootFiles(ctx)),
210
+ mode,
211
+ });
212
+ const result = await runWithPrompt(ctx, mode === "implement" ? "implement" : "issues", prompt, compiled.content);
213
+ const parsed = result.resultJson;
214
+ if (mode === "implement" && parsed?.fixable !== false) {
215
+ const changed = await pushChanges(ctx, compiled.content, {
216
+ branch: `${bot(config).autofix?.branch_prefix ?? "opencode/"}issue-${number}`,
217
+ openPr: true,
218
+ title: `fix: address #${number}`,
219
+ base: bot(config).base_branch ?? "main",
220
+ body: parsed?.summary ?? `Implements #${number}.`,
221
+ });
222
+ if (changed)
223
+ return { implemented: true, pr: changed };
224
+ }
225
+ const body = parsed && parsed.summary
226
+ ? issueTriageBody(config, parsed, { model: compiled.model, cost: result.cost })
227
+ : commandReplyBody(config, result.text, { actor: "opencode", command: mode });
228
+ if (parsed?.labels?.length && permission(config, "manage_issues") === "allow") {
229
+ const labels = bot(config).labels ?? [];
230
+ const allowed = parsed.labels.filter((label) => labels.length === 0 || labels.includes(label));
231
+ if (allowed.length)
232
+ await github.addLabels(repo, number, allowed).catch((error) => ctx.log(`labels: ${error.message}`));
233
+ }
234
+ if (permission(config, "comment") === "allow")
235
+ await github.comment(repo, number, body);
236
+ return { triaged: true, labels: parsed?.labels };
237
+ }
238
+ // -------------------------------------------------------------------- autofix
239
+ export async function handleWorkflowFailure(ctx, runId) {
240
+ const { github, repo, config } = ctx;
241
+ if (!feature(config, "workflow_autofix"))
242
+ return { skipped: true };
243
+ if (bot(config).autofix?.on_failure === false)
244
+ return { skipped: true };
245
+ const run = await github.getWorkflowRun(repo, runId);
246
+ if (run.conclusion !== "failure")
247
+ return { skipped: true, reason: `conclusion is ${run.conclusion}` };
248
+ const autofix = bot(config).autofix ?? {};
249
+ if (autofix.ignore_workflows?.some((pattern) => matchGlob(pattern, run.path))) {
250
+ return { skipped: true, reason: "workflow is ignored" };
251
+ }
252
+ if (autofix.workflows?.length && !autofix.workflows.some((p) => matchGlob(p, run.path))) {
253
+ return { skipped: true, reason: "workflow is not in the watched list" };
254
+ }
255
+ const jobs = await github.getWorkflowRunJobs(repo, runId);
256
+ const failed = jobs.jobs.filter((job) => job.conclusion === "failure");
257
+ if (!failed.length)
258
+ return { skipped: true, reason: "no failed jobs" };
259
+ const failedJobs = failed
260
+ .map((job) => `- ${job.name}\n${job.steps.filter((s) => s.conclusion === "failure").map((s) => ` - step ${s.number}: ${s.name}`).join("\n")}`)
261
+ .join("\n");
262
+ let logExcerpt = "";
263
+ for (const job of failed.slice(0, 2)) {
264
+ try {
265
+ const log = await github.getJobLog(repo, job.id);
266
+ logExcerpt += `\n### ${job.name}\n` + tail(log, 4000);
267
+ }
268
+ catch (error) {
269
+ logExcerpt += `\n### ${job.name}\n(could not read log: ${error.message})\n`;
270
+ }
271
+ }
272
+ const workflowFile = await github
273
+ .getFile(repo, run.path.startsWith(".github/") ? run.path : `.github/workflows/${run.path.split("/").pop()}`, run.head_sha)
274
+ .then((file) => file?.content ?? null)
275
+ .catch(() => null);
276
+ const compiled = compileConfig(config, { mode: "autofix" });
277
+ const prompt = autofixPrompt({
278
+ config,
279
+ repo: `${repo.owner}/${repo.repo}`,
280
+ runUrl: run.html_url,
281
+ workflow: run.name,
282
+ branch: run.head_branch,
283
+ sha: run.head_sha,
284
+ failedJobs,
285
+ logExcerpt,
286
+ workflowFile,
287
+ });
288
+ const result = await runWithPrompt(ctx, "autofix", prompt, compiled.content);
289
+ const parsed = result.resultJson;
290
+ if (!parsed?.fixable) {
291
+ if (permission(config, "comment") === "allow" && run.pull_requests[0]) {
292
+ await github.comment(repo, run.pull_requests[0].number, autofixBody(config, {
293
+ diagnosis: parsed?.diagnosis ?? result.text,
294
+ fixable: false,
295
+ summary: "",
296
+ explanation: "",
297
+ commit_message: "",
298
+ }, { runUrl: run.html_url, branch: run.head_branch }));
299
+ }
300
+ return { fixable: false, diagnosis: parsed?.diagnosis };
301
+ }
302
+ const changed = await pushChanges(ctx, compiled.content, {
303
+ branch: bot(config).autofix?.open_pr === false ? run.head_branch : `${bot(config).autofix?.branch_prefix ?? "opencode/autofix-"}${run.head_branch}-${run.head_sha.slice(0, 7)}`,
304
+ openPr: bot(config).autofix?.open_pr !== false,
305
+ title: parsed.commit_message ?? `ci: fix ${run.name}`,
306
+ base: bot(config).autofix?.open_pr === false ? run.head_branch : (bot(config).base_branch ?? "main"),
307
+ body: autofixBody(config, parsed, { runUrl: run.html_url, branch: run.head_branch }),
308
+ });
309
+ if (changed?.pr && permission(config, "comment") === "allow") {
310
+ await github.comment(repo, changed.pr, autofixBody(config, parsed, { runUrl: run.html_url, branch: run.head_branch }));
311
+ }
312
+ return { fixable: true, pr: changed?.pr };
313
+ }
314
+ /** Read the tail of a long log without loading it all into the prompt. */
315
+ export function tail(text, max) {
316
+ const cleaned = text.replace(/\u001b\[[0-9;]*m/g, "");
317
+ if (cleaned.length <= max)
318
+ return cleaned;
319
+ return "…(truncated)…\n" + cleaned.slice(-max);
320
+ }
321
+ // ------------------------------------------------------------------ commands
322
+ export async function handleComment(ctx, input) {
323
+ const { github, repo, config } = ctx;
324
+ const invocation = parseCommandBody(ctx.config, input.body);
325
+ if (!invocation)
326
+ return { skipped: true };
327
+ const actor = { login: input.actor, permission: input.permission, teams: input.teams };
328
+ const allowed = canRun(config, invocation, actor);
329
+ if (!allowed.ok) {
330
+ ctx.log(`command rejected: ${allowed.reason}`);
331
+ return { rejected: allowed.reason };
332
+ }
333
+ if (invocation.command === "help") {
334
+ await github.comment(repo, input.issueNumber, helpText(config));
335
+ return { replied: true };
336
+ }
337
+ if (invocation.command === "review") {
338
+ if (input.kind !== "pull_request")
339
+ return { skipped: true };
340
+ return reviewPullRequest(ctx, { prNumber: input.issueNumber, extra: invocation.args.join(" ") });
341
+ }
342
+ if (invocation.command === "merge") {
343
+ return mergePull(ctx, input.issueNumber);
344
+ }
345
+ if (invocation.command === "close" || invocation.command === "reopen") {
346
+ const state = invocation.command === "close" ? "closed" : "open";
347
+ if (permission(config, "manage_issues") !== "allow")
348
+ return { rejected: "manage_issues is not allowed" };
349
+ await github.updateIssue(repo, input.issueNumber, { state });
350
+ return { state };
351
+ }
352
+ if (invocation.command === "label") {
353
+ if (permission(config, "manage_issues") !== "allow")
354
+ return { rejected: "manage_issues is not allowed" };
355
+ const add = invocation.args.filter((a) => !a.startsWith("-")).map((a) => a.replace(/^\+/, ""));
356
+ const remove = invocation.args.filter((a) => a.startsWith("-")).map((a) => a.slice(1));
357
+ if (add.length)
358
+ await github.addLabels(repo, input.issueNumber, add);
359
+ for (const label of remove) {
360
+ await github.delete(`/repos/${repo.owner}/${repo.repo}/issues/${input.issueNumber}/labels/${encodeURIComponent(label)}`).catch(() => { });
361
+ }
362
+ return { labels: { add, remove } };
363
+ }
364
+ if (invocation.command === "assign") {
365
+ if (permission(config, "manage_issues") !== "allow")
366
+ return { rejected: "manage_issues is not allowed" };
367
+ const users = invocation.args.map((a) => a.replace(/^@/, ""));
368
+ await github.addAssignees(repo, input.issueNumber, users);
369
+ return { assigned: users };
370
+ }
371
+ if (invocation.command === "describe") {
372
+ return describePull(ctx, input.issueNumber);
373
+ }
374
+ // Everything else is an agent task: explain, fix, test, docs, triage, answer, implement.
375
+ const issue = await github.getIssue(repo, input.issueNumber);
376
+ const mode = invocation.command === "implement" ? "implement" : "commands";
377
+ const compiled = compileConfig(config, { mode });
378
+ const prompt = commandPrompt({
379
+ config,
380
+ command: invocation.command,
381
+ args: invocation.args,
382
+ repo: `${repo.owner}/${repo.repo}`,
383
+ target: input.kind === "pull_request" ? `pull request #${input.issueNumber}` : `issue #${input.issueNumber}`,
384
+ actor: input.actor,
385
+ body: input.body,
386
+ context: `${issue.title}\n\n${issue.body ?? ""}\n\nFiles: ${(await listRootFiles(ctx)).slice(0, 200).join(", ")}`,
387
+ });
388
+ const result = await runWithPrompt(ctx, mode, prompt, compiled.content);
389
+ if (mode === "implement") {
390
+ const changed = await pushChanges(ctx, compiled.content, {
391
+ branch: `${bot(config).autofix?.branch_prefix ?? "opencode/"}cmd-${input.issueNumber}`,
392
+ openPr: true,
393
+ title: `feat: ${issue.title.slice(0, 60)}`,
394
+ base: bot(config).base_branch ?? "main",
395
+ body: result.text.slice(0, 4000),
396
+ });
397
+ if (changed)
398
+ return { implemented: true, pr: changed.pr };
399
+ }
400
+ if (permission(config, "comment") === "allow") {
401
+ await github.comment(repo, input.issueNumber, commandReplyBody(config, result.text, { actor: input.actor, command: invocation.command }));
402
+ }
403
+ return { replied: true };
404
+ }
405
+ function parseCommandBody(config, body) {
406
+ // Imported lazily to keep the module graph small for the MCP entry point.
407
+ const { parseInvocation } = require("./commands.js");
408
+ return parseInvocation(body, config);
409
+ }
410
+ export async function mergePull(ctx, number) {
411
+ const { github, repo, config } = ctx;
412
+ const pull = await github.getPull(repo, number);
413
+ const isProtected = (bot(config).protected_branches ?? []).some((pattern) => matchGlob(pattern, pull.base.ref));
414
+ const gate = isProtected ? permission(config, "merge_protected") : permission(config, "merge_pull_requests");
415
+ if (gate !== "allow")
416
+ return { rejected: `merge requires bot.permissions.${isProtected ? "merge_protected" : "merge_pull_requests"} = "allow"` };
417
+ if (pull.merged)
418
+ return { skipped: true, reason: "already merged" };
419
+ const result = await github.mergePull(repo, number, { merge_method: "squash", commit_title: `${pull.title} (#${number})` });
420
+ return { merged: true, result };
421
+ }
422
+ export async function describePull(ctx, number) {
423
+ const { github, repo, config } = ctx;
424
+ const pull = await github.getPull(repo, number);
425
+ const compiled = compileConfig(config, { mode: "describe" });
426
+ const result = await runWithPrompt(ctx, "describe", describePrompt({
427
+ config,
428
+ repo: `${repo.owner}/${repo.repo}`,
429
+ prNumber: number,
430
+ base: pull.base.ref,
431
+ head: pull.head.ref,
432
+ currentBody: pull.body ?? "",
433
+ title: pull.title,
434
+ }), compiled.content);
435
+ if (permission(config, "manage_pull_requests") !== "allow")
436
+ return { rejected: "manage_pull_requests is not allowed" };
437
+ await github.updatePull(repo, number, { body: result.text.trim() });
438
+ return { described: true };
439
+ }
440
+ // ------------------------------------------------------------------- helpers
441
+ async function runWithPrompt(ctx, mode, prompt, content) {
442
+ const resultPath = join(tmpdir(), `opencode-result-${Date.now()}.json`);
443
+ const env = { ...process.env, OPENCODE_RESULT_FILE: resultPath };
444
+ const model = typeof content.model === "string" ? content.model : undefined;
445
+ ctx.log(`opencode run (${mode})${model ? ` with ${model}` : ""}`);
446
+ const result = await runOpencode({
447
+ message: `${prompt}\n\nThe result file is: ${resultPath}`,
448
+ cwd: ctx.workspace,
449
+ config: content,
450
+ model,
451
+ agent: "opencode-bot",
452
+ auto: true,
453
+ env,
454
+ live: feature(ctx.config, "live_log"),
455
+ });
456
+ let resultJson = null;
457
+ try {
458
+ resultJson = await readResult(resultPath);
459
+ await rm(resultPath, { force: true });
460
+ }
461
+ catch {
462
+ /* the agent may not have written it */
463
+ }
464
+ if (!result.ok) {
465
+ ctx.log(`run failed (exit ${result.exitCode}): ${result.error ?? ""}`);
466
+ }
467
+ return Object.assign(result, { resultJson });
468
+ }
469
+ /** Commit whatever the agent produced and push it to a branch, optionally opening a PR. */
470
+ async function pushChanges(ctx, _content, options) {
471
+ const { github, repo, config } = ctx;
472
+ if (bot(config).write === false) {
473
+ ctx.log("bot.write is false; refusing to push");
474
+ return null;
475
+ }
476
+ const current = await state(ctx.workspace);
477
+ if (!current.dirty) {
478
+ ctx.log("the agent produced no file changes");
479
+ return null;
480
+ }
481
+ assertWorkflowWrites(config, current.changedFiles);
482
+ assertBranchWrites(config, options.branch);
483
+ const commit = await commitAll(ctx.workspace, options.title, config);
484
+ if (!commit)
485
+ return null;
486
+ ctx.log(`committed ${commit.files.length} file(s) as ${commit.sha.slice(0, 7)}`);
487
+ // Create the branch from the base, then push the commit onto it.
488
+ const base = await github.getRef(repo, options.base);
489
+ await github.createRef(repo, options.branch, base.object.sha).catch(() => { });
490
+ await push(ctx.workspace, options.branch, config);
491
+ if (!options.openPr)
492
+ return { branch: options.branch, pr: null };
493
+ const pull = await github.createPull(repo, {
494
+ title: options.title.slice(0, 200),
495
+ head: options.branch,
496
+ base: options.base,
497
+ body: options.body,
498
+ });
499
+ ctx.log(`opened PR #${pull.number}`);
500
+ return { branch: options.branch, pr: pull.number };
501
+ }
502
+ async function listRootFiles(ctx) {
503
+ try {
504
+ const entries = await ctx.github.listDir(ctx.repo, "");
505
+ return entries.filter((entry) => entry.type === "file").map((entry) => entry.name);
506
+ }
507
+ catch {
508
+ return [];
509
+ }
510
+ }
511
+ /** Route a decoded GitHub event to the matching handler. */
512
+ export async function dispatch(ctx, event, payload) {
513
+ switch (event) {
514
+ case "pull_request": {
515
+ const action = payload.action;
516
+ if (!["opened", "reopened", "synchronize", "ready_for_review"].includes(action))
517
+ return { skipped: true };
518
+ return reviewPullRequest(ctx, { prNumber: payload.pull_request.number });
519
+ }
520
+ case "issue_comment": {
521
+ if (payload.action !== "created")
522
+ return { skipped: true };
523
+ const isPull = Boolean(payload.issue.pull_request);
524
+ return handleComment(ctx, {
525
+ body: payload.comment.body ?? "",
526
+ actor: payload.comment.user.login,
527
+ issueNumber: payload.issue.number,
528
+ kind: isPull ? "pull_request" : "issue",
529
+ permission: null,
530
+ teams: [],
531
+ });
532
+ }
533
+ case "issues": {
534
+ if (!["opened", "reopened"].includes(payload.action))
535
+ return { skipped: true };
536
+ return handleIssue(ctx, payload.issue.number, "triage");
537
+ }
538
+ case "workflow_run": {
539
+ if (payload.action !== "completed")
540
+ return { skipped: true };
541
+ return handleWorkflowFailure(ctx, payload.workflow_run.id);
542
+ }
543
+ case "push": {
544
+ if (!feature(ctx.config, "commit_review"))
545
+ return { skipped: true };
546
+ return { skipped: true, reason: "commit_review is not implemented for push payloads yet" };
547
+ }
548
+ case "workflow_dispatch": {
549
+ const command = payload.inputs?.command ?? "review";
550
+ if (command === "review" && payload.inputs?.pr) {
551
+ return reviewPullRequest(ctx, { prNumber: Number(payload.inputs.pr) });
552
+ }
553
+ if (payload.inputs?.issue) {
554
+ return handleIssue(ctx, Number(payload.inputs.issue), command);
555
+ }
556
+ return { skipped: true };
557
+ }
558
+ default:
559
+ return { skipped: true };
560
+ }
561
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { describePull, dispatch, handleComment, handleWorkflowFailure, mergePull, reviewPullRequest, type Context, type EventName } from "./actions.js";
2
+ export { reviewPullRequest, handleComment, handleWorkflowFailure, describePull, mergePull, dispatch };
3
+ export type { Context, EventName };