@eduardo191labs/opencode-actions 0.1.2 → 0.1.3

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.
package/dist/actions.js CHANGED
@@ -6,8 +6,10 @@ import { compileConfig, repoFacts } from "./compile.js";
6
6
  import { runOpencode, readResult } from "./runner.js";
7
7
  import { autofixPrompt, commandPrompt, describePrompt, issuePrompt, reviewPrompt, } from "./prompts.js";
8
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";
9
+ import { assertBranchWrites, assertWorkflowWrites, commitAll, git, push, sanitize, state } from "./git.js";
10
+ import { helpText, canRun, parseInvocation } from "./commands.js";
11
+ import { findPullForBranch, implementIssue, issueFromText, workBranch } from "./implement.js";
12
+ import { closeLinkedIssues, commentMerge, mergeWithReason, react, REACTIONS, subjectFor } from "./signals.js";
11
13
  import { reviewThreadPrompt, replyToReviewThread, threadContext, wantsFix } from "./review-thread.js";
12
14
  export async function reviewPullRequest(ctx, options) {
13
15
  const { github, repo, config } = ctx;
@@ -213,15 +215,12 @@ export async function handleIssue(ctx, number, mode) {
213
215
  const result = await runWithPrompt(ctx, mode === "implement" ? "implement" : "issues", prompt, compiled.content);
214
216
  const parsed = result.resultJson;
215
217
  if (mode === "implement" && parsed?.fixable !== false) {
216
- const changed = await pushChanges(ctx, compiled.content, {
217
- branch: `${bot(config).autofix?.branch_prefix ?? "opencode/"}issue-${number}`,
218
- openPr: true,
219
- title: `fix: address #${number}`,
220
- base: bot(config).base_branch ?? "main",
221
- body: parsed?.summary ?? `Implements #${number}.`,
218
+ const done = await implementIssue({ github, repo, config, workspace: ctx.workspace, log: ctx.log }, { issueNumber: number, title: issue.title, body: issue.body ?? "", requestId: number }, async (implementPrompt) => {
219
+ const again = await runWithPrompt(ctx, "implement", implementPrompt, compiled.content);
220
+ return { text: again.text, resultJson: again.resultJson, model: compiled.model, cost: again.cost };
222
221
  });
223
- if (changed)
224
- return { implemented: true, pr: changed };
222
+ if (done.pr)
223
+ return { implemented: true, ...done };
225
224
  }
226
225
  const body = parsed && parsed.summary
227
226
  ? issueTriageBody(config, parsed, { model: compiled.model, cost: result.cost })
@@ -300,8 +299,13 @@ export async function handleWorkflowFailure(ctx, runId) {
300
299
  }
301
300
  return { fixable: false, diagnosis: parsed?.diagnosis };
302
301
  }
302
+ // The fix lands on a branch named after the failing workflow, the branch and
303
+ // the commit, so two failures never collide on one branch and re-running the
304
+ // same failure reuses it.
305
+ const prefix = bot(config).autofix?.branch_prefix ?? "opencode/autofix-";
306
+ const slug = `${run.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30)}-${run.head_branch.replace(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 40)}-${run.head_sha.slice(0, 7)}`;
303
307
  const changed = await pushChanges(ctx, compiled.content, {
304
- 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)}`,
308
+ branch: bot(config).autofix?.open_pr === false ? run.head_branch : `${prefix}${slug}`,
305
309
  openPr: bot(config).autofix?.open_pr !== false,
306
310
  title: parsed.commit_message ?? `ci: fix ${run.name}`,
307
311
  base: bot(config).autofix?.open_pr === false ? run.head_branch : (bot(config).base_branch ?? "main"),
@@ -331,6 +335,9 @@ export async function handleComment(ctx, input) {
331
335
  ctx.log(`command rejected: ${allowed.reason}`);
332
336
  return { rejected: allowed.reason };
333
337
  }
338
+ // The run takes minutes. An acknowledgement at the start is the difference
339
+ // between "working" and "ignored".
340
+ await react(github, repo, subjectFor({ number: input.issueNumber, isPull: input.kind === "pull_request" }), REACTIONS.accepted);
334
341
  if (invocation.command === "help") {
335
342
  await github.comment(repo, input.issueNumber, helpText(config));
336
343
  return { replied: true };
@@ -343,6 +350,46 @@ export async function handleComment(ctx, input) {
343
350
  if (invocation.command === "merge") {
344
351
  return mergePull(ctx, input.issueNumber);
345
352
  }
353
+ if (invocation.command === "rebase") {
354
+ if (input.kind !== "pull_request")
355
+ return { skipped: true, reason: "rebase needs a pull request" };
356
+ return resolveConflicts(ctx, input.issueNumber);
357
+ }
358
+ if (invocation.command === "sync") {
359
+ if (input.kind !== "pull_request")
360
+ return { skipped: true, reason: "sync needs a pull request" };
361
+ return describePull(ctx, input.issueNumber);
362
+ }
363
+ // `continue` is the second pass: the same issue, the same branch, one more
364
+ // attempt. It is what an author types when the first result was close.
365
+ if (invocation.command === "continue") {
366
+ if (input.kind !== "pull_request") {
367
+ // On an issue, continue means "finish the work you started".
368
+ const issue = await github.getIssue(repo, input.issueNumber);
369
+ const branch = workBranch(config, input.issueNumber, issue.title);
370
+ const linked = await findPullForBranch(github, repo, branch);
371
+ if (!linked)
372
+ return { skipped: true, reason: "no working branch for this issue yet" };
373
+ return implementIssue({ github, repo, config, workspace: ctx.workspace, log: ctx.log }, { issueNumber: input.issueNumber, title: issue.title, body: `${issue.body ?? ""}\n\n## Follow-up\n\n${invocation.args.join(" ") || "Another pass: finish what the previous run left."}`, requestId: input.issueNumber }, async (prompt) => {
374
+ const again = await runWithPrompt(ctx, "implement", prompt, compiledFor(config, "implement").content);
375
+ return { text: again.text, resultJson: again.resultJson };
376
+ });
377
+ }
378
+ const pull = await github.getPull(repo, input.issueNumber);
379
+ const issueNumber = issueFromText(`${pull.head.ref}\n${pull.body ?? ""}`);
380
+ if (!issueNumber)
381
+ return { skipped: true, reason: "this pull request has no issue to continue" };
382
+ const issue = await github.getIssue(repo, issueNumber);
383
+ return implementIssue({ github, repo, config, workspace: ctx.workspace, log: ctx.log }, {
384
+ issueNumber,
385
+ title: issue.title,
386
+ body: `${issue.body ?? ""}\n\n## Follow-up requested on the pull request\n\n${invocation.args.join(" ") || input.body}`,
387
+ requestId: issueNumber,
388
+ }, async (prompt) => {
389
+ const again = await runWithPrompt(ctx, "implement", prompt, compiledFor(config, "implement").content);
390
+ return { text: again.text, resultJson: again.resultJson };
391
+ });
392
+ }
346
393
  if (invocation.command === "close" || invocation.command === "reopen") {
347
394
  const state = invocation.command === "close" ? "closed" : "open";
348
395
  if (permission(config, "manage_issues") !== "allow")
@@ -387,25 +434,28 @@ export async function handleComment(ctx, input) {
387
434
  context: `${issue.title}\n\n${issue.body ?? ""}\n\nFiles: ${(await listRootFiles(ctx)).slice(0, 200).join(", ")}`,
388
435
  });
389
436
  const result = await runWithPrompt(ctx, mode, prompt, compiled.content);
390
- if (mode === "implement") {
391
- const changed = await pushChanges(ctx, compiled.content, {
392
- branch: `${bot(config).autofix?.branch_prefix ?? "opencode/"}cmd-${input.issueNumber}`,
393
- openPr: true,
394
- title: `feat: ${issue.title.slice(0, 60)}`,
395
- base: bot(config).base_branch ?? "main",
396
- body: result.text.slice(0, 4000),
437
+ if (invocation.command === "implement") {
438
+ const done = await implementIssue({ github, repo, config, workspace: ctx.workspace, log: ctx.log }, { issueNumber: input.issueNumber, title: issue.title, body: issue.body ?? "", requestId: input.issueNumber }, async (implementPrompt) => {
439
+ const again = await runWithPrompt(ctx, "implement", implementPrompt, compiled.content);
440
+ return { text: again.text, resultJson: again.resultJson, model: compiled.model, cost: again.cost };
397
441
  });
398
- if (changed)
399
- return { implemented: true, pr: changed.pr };
442
+ if (permission(config, "comment") === "allow" && !done.pr) {
443
+ await github.comment(repo, input.issueNumber, `I could not make the change.
444
+
445
+ ${result.text.slice(0, 4000)}`);
446
+ }
447
+ return done;
400
448
  }
401
449
  if (permission(config, "comment") === "allow") {
402
450
  await github.comment(repo, input.issueNumber, commandReplyBody(config, result.text, { actor: input.actor, command: invocation.command }));
403
451
  }
452
+ await react(github, repo, subjectFor({ number: input.issueNumber, isPull: input.kind === "pull_request" }), REACTIONS.done);
404
453
  return { replied: true };
405
454
  }
455
+ function compiledFor(config, mode) {
456
+ return compileConfig(config, { mode });
457
+ }
406
458
  function parseCommandBody(config, body) {
407
- // Imported lazily to keep the module graph small for the MCP entry point.
408
- const { parseInvocation } = require("./commands.js");
409
459
  return parseInvocation(body, config);
410
460
  }
411
461
  export async function mergePull(ctx, number) {
@@ -417,8 +467,68 @@ export async function mergePull(ctx, number) {
417
467
  return { rejected: `merge requires bot.permissions.${isProtected ? "merge_protected" : "merge_pull_requests"} = "allow"` };
418
468
  if (pull.merged)
419
469
  return { skipped: true, reason: "already merged" };
420
- const result = await github.mergePull(repo, number, { merge_method: "squash", commit_title: `${pull.title} (#${number})` });
421
- return { merged: true, result };
470
+ const attempt = await mergeWithReason(github, repo, number, "squash");
471
+ if (!attempt.merged) {
472
+ // A conflict is actionable, so it is resolved rather than reported. Anything
473
+ // else (checks, review, policy) is the author's to fix and is said plainly.
474
+ if (attempt.conflict) {
475
+ const fixed = await resolveConflicts(ctx, number);
476
+ if (fixed.resolved) {
477
+ const retry = await mergeWithReason(github, repo, number, "squash");
478
+ if (retry.merged) {
479
+ const closed = await closeLinkedIssues(github, repo, { number, body: pull.body, title: pull.title });
480
+ await commentMerge(github, repo, number, { sha: retry.sha, method: "squash", issues: closed.closed });
481
+ return { merged: true, conflictsResolved: true, sha: retry.sha };
482
+ }
483
+ return { merged: false, conflictsResolved: true, reason: retry.reason };
484
+ }
485
+ if (permission(config, "comment") === "allow") {
486
+ await github.comment(repo, number, `I could not resolve the conflicts automatically: ${fixed.reason}`);
487
+ }
488
+ return { merged: false, reason: fixed.reason };
489
+ }
490
+ if (permission(config, "comment") === "allow")
491
+ await github.comment(repo, number, `I cannot merge this yet: ${attempt.reason}`);
492
+ return { merged: false, reason: attempt.reason };
493
+ }
494
+ const closed = await closeLinkedIssues(github, repo, { number, body: pull.body, title: pull.title });
495
+ await commentMerge(github, repo, number, { sha: attempt.sha, method: "squash", issues: closed.closed });
496
+ return { merged: true, sha: attempt.sha, closedIssues: closed.closed };
497
+ }
498
+ /**
499
+ * Bring the branch up to date with its base and let the agent settle what git
500
+ * could not, then push. Git's automatic resolution is trusted first: a conflict
501
+ * that is only "both sides added a line" does not need a model.
502
+ */
503
+ export async function resolveConflicts(ctx, number) {
504
+ const { github, repo, config } = ctx;
505
+ if (permission(config, "push_pr_branch") !== "allow") {
506
+ return { resolved: false, reason: "push_pr_branch is not allowed" };
507
+ }
508
+ const pull = await github.getPull(repo, number);
509
+ const branch = pull.head.ref;
510
+ const base = pull.base.ref;
511
+ const fetch = await git(ctx.workspace, ["fetch", "origin", base, branch, "--depth", "50"]);
512
+ if (fetch.code !== 0)
513
+ return { resolved: false, reason: "could not fetch the branches" };
514
+ await git(ctx.workspace, ["checkout", "-B", branch, `origin/${branch}`]);
515
+ const merge = await git(ctx.workspace, ["merge", "--no-edit", `origin/${base}`]);
516
+ if (merge.code !== 0) {
517
+ const conflicts = await git(ctx.workspace, ["diff", "--name-only", "--diff-filter=U"]);
518
+ const files = conflicts.stdout.split("\n").filter(Boolean);
519
+ if (!files.length)
520
+ return { resolved: false, reason: sanitize(merge.stderr, process.env.GITHUB_TOKEN ?? "").slice(0, 400) };
521
+ const compiled = compileConfig(config, { mode: "commands" });
522
+ const result = await runWithPrompt(ctx, "commands", `# Task: resolve a merge conflict\n\nThe branch \`${branch}\` conflicts with \`${base}\`. The conflicted files are checked out with conflict markers:\n\n${files.map((f) => `- \`${f}\``).join("\n")}\n\nResolve them so both changes survive. Keep the intent of each side; never delete a change just to make the conflict go away. Remove every conflict marker. Then answer in one short paragraph about what you decided.`, compiled.content);
523
+ ctx.log(`conflict resolution: ${result.text.slice(0, 120)}`);
524
+ const left = await git(ctx.workspace, ["diff", "--name-only", "--diff-filter=U"]);
525
+ if (left.stdout.trim())
526
+ return { resolved: false, reason: `conflicts remain in ${left.stdout.trim().split("\n").join(", ")}` };
527
+ }
528
+ const commit = await commitAll(ctx.workspace, `chore: merge ${base} into ${branch}\n\n[skip commits]`, config);
529
+ if (commit)
530
+ await git(ctx.workspace, ["push", "origin", `HEAD:refs/heads/${branch}`]);
531
+ return { resolved: true, files: commit?.files.length ?? 0 };
422
532
  }
423
533
  export async function describePull(ctx, number) {
424
534
  const { github, repo, config } = ctx;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * GitHub App authentication, with no dependencies.
3
+ *
4
+ * A GitHub App authenticates in two steps:
5
+ * 1. sign a short-lived RS256 JWT with the app's private key, to speak as the
6
+ * app itself (`/app`, `/app/installations`, `/installation/repositories`);
7
+ * 2. exchange the app JWT for an *installation token*, which is the credential
8
+ * that can actually touch a repository.
9
+ *
10
+ * The difference matters. The installation token is scoped to the repositories
11
+ * the app was installed on and to the permissions granted to it, so a workflow
12
+ * that discovers repositories through the app can only ever write to the ones
13
+ * the owner approved. `GITHUB_TOKEN` cannot do that: it is bound to the single
14
+ * repository running the workflow.
15
+ */
16
+ import { GitHub } from "./github.js";
17
+ export interface AppCredentials {
18
+ /** App id, not the client id. */
19
+ appId: string;
20
+ /** PEM private key, with real newlines or escaped `\n`. */
21
+ privateKey: string;
22
+ }
23
+ /**
24
+ * Sign the JWT GitHub accepts for an app.
25
+ *
26
+ * `iat` is backdated a minute because GitHub rejects a token issued in the
27
+ * future, and the clock of the runner is not always exact. `exp` stays under
28
+ * the ten-minute maximum.
29
+ */
30
+ export declare function appJwt(credentials: AppCredentials, now?: number): string;
31
+ /** A client that speaks as the app itself. */
32
+ export declare function appClient(credentials: AppCredentials): GitHub;
33
+ export interface Installation {
34
+ id: number;
35
+ account: string | null;
36
+ repositorySelection: string;
37
+ }
38
+ /** Map an installed account to its installation id. */
39
+ export declare function findInstallation(app: GitHub, owner: string, repo?: string): Promise<Installation | null>;
40
+ export interface InstallationToken {
41
+ token: string;
42
+ expiresAt: string;
43
+ }
44
+ /** Exchange the app JWT for the token that acts on repositories. */
45
+ export declare function installationToken(credentials: AppCredentials, installationId: number): Promise<InstallationToken>;
46
+ /**
47
+ * Every repository the app can reach.
48
+ *
49
+ * `GET /installation/repositories` does **not** accept the app JWT: it answers
50
+ * `401 Bad credentials` even though `/app/installations` works with the same
51
+ * token. It needs an installation token, so one is minted per installation.
52
+ *
53
+ * This is also the honest discovery primitive: the list is exactly what the
54
+ * owner granted, so a repository the app was not given can never be found.
55
+ */
56
+ export declare function installationRepos(app: GitHub, credentials: AppCredentials): Promise<{
57
+ owner: string;
58
+ repo: string;
59
+ private: boolean;
60
+ archived: boolean;
61
+ disabled: boolean;
62
+ fork: boolean;
63
+ }[]>;
64
+ /**
65
+ * Credentials from the environment, when the workflow carries them.
66
+ *
67
+ * Returns `null` rather than throwing so every entry point keeps working with a
68
+ * plain token: the app is an upgrade, not a hard requirement.
69
+ */
70
+ export declare function appCredentialsFromEnv(env?: NodeJS.ProcessEnv): AppCredentials | null;
@@ -0,0 +1,137 @@
1
+ /**
2
+ * GitHub App authentication, with no dependencies.
3
+ *
4
+ * A GitHub App authenticates in two steps:
5
+ * 1. sign a short-lived RS256 JWT with the app's private key, to speak as the
6
+ * app itself (`/app`, `/app/installations`, `/installation/repositories`);
7
+ * 2. exchange the app JWT for an *installation token*, which is the credential
8
+ * that can actually touch a repository.
9
+ *
10
+ * The difference matters. The installation token is scoped to the repositories
11
+ * the app was installed on and to the permissions granted to it, so a workflow
12
+ * that discovers repositories through the app can only ever write to the ones
13
+ * the owner approved. `GITHUB_TOKEN` cannot do that: it is bound to the single
14
+ * repository running the workflow.
15
+ */
16
+ import { createSign } from "node:crypto";
17
+ import { GitHub } from "./github.js";
18
+ function base64url(input) {
19
+ return Buffer.from(input)
20
+ .toString("base64")
21
+ .replace(/=+$/, "")
22
+ .replace(/\+/g, "-")
23
+ .replace(/\//g, "_");
24
+ }
25
+ /**
26
+ * Sign the JWT GitHub accepts for an app.
27
+ *
28
+ * `iat` is backdated a minute because GitHub rejects a token issued in the
29
+ * future, and the clock of the runner is not always exact. `exp` stays under
30
+ * the ten-minute maximum.
31
+ */
32
+ export function appJwt(credentials, now = Date.now()) {
33
+ if (!/^\d+$/.test(String(credentials.appId).trim())) {
34
+ throw new Error(`OPENCODE_APP_ID must be the numeric app id, got "${credentials.appId}"`);
35
+ }
36
+ const issued = Math.floor(now / 1000);
37
+ const header = base64url(JSON.stringify({ alg: "RS256", typ: "JWT" }));
38
+ const payload = base64url(JSON.stringify({
39
+ iat: issued - 60,
40
+ exp: issued + 540,
41
+ iss: String(credentials.appId).trim(),
42
+ }));
43
+ const signer = createSign("RSA-SHA256");
44
+ signer.update(`${header}.${payload}`);
45
+ const signature = signer.sign(credentials.privateKey.replace(/\\n/g, "\n"));
46
+ return `${header}.${payload}.${base64url(signature)}`;
47
+ }
48
+ /** A client that speaks as the app itself. */
49
+ export function appClient(credentials) {
50
+ return new GitHub({ token: appJwt(credentials), userAgent: "opencode-actions-app" });
51
+ }
52
+ /** Map an installed account to its installation id. */
53
+ export async function findInstallation(app, owner, repo) {
54
+ const path = repo ? `/repos/${owner}/${repo}/installation` : `/users/${owner}/installation`;
55
+ try {
56
+ const data = await app.get(path);
57
+ return {
58
+ id: data.id,
59
+ account: data.account?.login ?? null,
60
+ repositorySelection: data.repository_selection ?? "selected",
61
+ };
62
+ }
63
+ catch (error) {
64
+ if (error?.status === 404)
65
+ return null;
66
+ throw error;
67
+ }
68
+ }
69
+ /** Exchange the app JWT for the token that acts on repositories. */
70
+ export async function installationToken(credentials, installationId) {
71
+ const app = appClient(credentials);
72
+ const data = await app.post(`/app/installations/${installationId}/access_tokens`, {});
73
+ return { token: data.token, expiresAt: data.expires_at };
74
+ }
75
+ /**
76
+ * Every repository the app can reach.
77
+ *
78
+ * `GET /installation/repositories` does **not** accept the app JWT: it answers
79
+ * `401 Bad credentials` even though `/app/installations` works with the same
80
+ * token. It needs an installation token, so one is minted per installation.
81
+ *
82
+ * This is also the honest discovery primitive: the list is exactly what the
83
+ * owner granted, so a repository the app was not given can never be found.
84
+ */
85
+ export async function installationRepos(app, credentials) {
86
+ const installations = await app.get("/app/installations?per_page=100");
87
+ const out = [];
88
+ for (const installation of installations ?? []) {
89
+ const owner = installation.account?.login;
90
+ if (!owner)
91
+ continue;
92
+ let token;
93
+ try {
94
+ token = (await installationToken(credentials, installation.id)).token;
95
+ }
96
+ catch {
97
+ // An installation that cannot mint a token (suspended, revoked) is
98
+ // skipped rather than failing discovery for every other account.
99
+ continue;
100
+ }
101
+ const client = new GitHub({ token, userAgent: "opencode-actions-app" });
102
+ let page = 1;
103
+ for (;;) {
104
+ const data = await client.get(`/installation/repositories?per_page=100&page=${page}`);
105
+ const repos = data.repositories ?? [];
106
+ for (const repo of repos) {
107
+ out.push({
108
+ owner: repo.owner?.login ?? owner,
109
+ repo: repo.name,
110
+ private: Boolean(repo.private),
111
+ archived: Boolean(repo.archived),
112
+ disabled: Boolean(repo.disabled),
113
+ fork: Boolean(repo.fork),
114
+ });
115
+ }
116
+ if (repos.length < 100)
117
+ break;
118
+ page++;
119
+ if (page > 20)
120
+ break;
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ /**
126
+ * Credentials from the environment, when the workflow carries them.
127
+ *
128
+ * Returns `null` rather than throwing so every entry point keeps working with a
129
+ * plain token: the app is an upgrade, not a hard requirement.
130
+ */
131
+ export function appCredentialsFromEnv(env = process.env) {
132
+ const appId = env.OPENCODE_APP_ID ?? env.INPUT_APP_ID;
133
+ const privateKey = env.OPENCODE_APP_PRIVATE_KEY ?? env.INPUT_APP_PRIVATE_KEY;
134
+ if (!appId || !privateKey)
135
+ return null;
136
+ return { appId: appId.trim(), privateKey: privateKey.trim() };
137
+ }
package/dist/cli.js CHANGED
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { existsSync } from "node:fs";
4
4
  import { GitHub, repoFromEnv, tokenFromEnv } from "./github.js";
5
+ import { appClient, appCredentialsFromEnv, findInstallation, installationToken } from "./app-auth.js";
5
6
  import { loadConfig, resolveSecretEnv, providerAuthPlan } from "./loader.js";
6
7
  import { compileConfig, describeCapabilities } from "./compile.js";
7
8
  import { createRenderer } from "./runner.js";
@@ -10,9 +11,26 @@ import { helpText } from "./commands.js";
10
11
  async function main() {
11
12
  const options = parseArgs(process.argv.slice(2));
12
13
  const workspace = options.workspace ?? process.env.GITHUB_WORKSPACE ?? process.cwd();
13
- const token = tokenFromEnv();
14
- const github = new GitHub({ token });
15
14
  const repo = repoFromEnv();
15
+ // A GitHub App installation token is preferred when the workflow carries the
16
+ // app credentials: it is scoped to the installed repositories and to the
17
+ // permissions the owner granted, so it cannot write anywhere else. The token
18
+ // is also exported as GITHUB_TOKEN because `git push` reads it from there.
19
+ const app = appCredentialsFromEnv();
20
+ let token;
21
+ if (app) {
22
+ const installation = await findInstallation(appClient(app), repo.owner, repo.repo);
23
+ if (!installation) {
24
+ const slug = process.env.OPENCODE_APP_SLUG ?? "opencode-actions-bot-new";
25
+ throw new Error(`the GitHub App is not installed on ${repo.owner}/${repo.repo}; install it at https://github.com/apps/${slug}/installations/new`);
26
+ }
27
+ token = (await installationToken(app, installation.id)).token;
28
+ process.env.GITHUB_TOKEN = token;
29
+ }
30
+ else {
31
+ token = tokenFromEnv();
32
+ }
33
+ const github = new GitHub({ token });
16
34
  const { config, sources } = await loadConfig({
17
35
  workspace,
18
36
  github,
@@ -80,11 +98,22 @@ async function main() {
80
98
  const result = await dispatch(ctx, options.event, payload);
81
99
  process.stdout.write(JSON.stringify(result ?? { ok: true }) + "\n");
82
100
  }
101
+ /**
102
+ * Read the event payload.
103
+ *
104
+ * Two shapes reach this function: GitHub's native payload, and the one the
105
+ * Cloudflare worker forwards, which is `{ event, payload }`. Unwrapping here
106
+ * means the workflow can pass the file as-is and no step needs a JSON parser of
107
+ * its own: one parser, one schema, one place to fix a bug.
108
+ */
83
109
  async function readPayload(path) {
84
110
  const file = path ?? process.env.GITHUB_EVENT_PATH;
85
111
  if (!file || !existsSync(file))
86
112
  return null;
87
- return JSON.parse(await readFile(file, "utf8"));
113
+ const data = JSON.parse(await readFile(file, "utf8"));
114
+ if (data && typeof data === "object" && "payload" in data && "event" in data)
115
+ return data.payload;
116
+ return data;
88
117
  }
89
118
  function parseArgs(argv) {
90
119
  const options = {
@@ -167,6 +196,8 @@ Flags:
167
196
 
168
197
  Environment:
169
198
  GITHUB_TOKEN Required
199
+ OPENCODE_APP_ID GitHub App id (preferred over GITHUB_TOKEN)
200
+ OPENCODE_APP_PRIVATE_KEY GitHub App private key (PEM)
170
201
  GITHUB_REPOSITORY Required, "owner/repo"
171
202
  GITHUB_EVENT_PATH Event payload path
172
203
  OPENCODE_BOT_MODEL Override the model
@@ -1,7 +1,9 @@
1
1
  import type { BotConfig, CommandInvocation } from "./config.js";
2
- export declare const KNOWN_COMMANDS: readonly ["review", "fix", "explain", "test", "docs", "describe", "triage", "answer", "merge", "close", "reopen", "label", "assign", "implement", "help", "stop"];
2
+ export declare const KNOWN_COMMANDS: readonly ["review", "fix", "explain", "test", "docs", "describe", "triage", "answer", "merge", "close", "reopen", "label", "assign", "implement", "continue", "rebase", "sync", "help", "stop"];
3
3
  export type KnownCommand = (typeof KNOWN_COMMANDS)[number];
4
4
  export declare function parseCommand(body: string, config: BotConfig): CommandInvocation | null;
5
+ /** Every way the bot answers to, longest first so `@opencode-actions-bot-new` wins over `@opencode`. */
6
+ export declare function botHandles(config: BotConfig): string[];
5
7
  export declare function parseInvocation(body: string, config: BotConfig): CommandInvocation | null;
6
8
  export interface ActorContext {
7
9
  login: string;
package/dist/commands.js CHANGED
@@ -14,6 +14,9 @@ export const KNOWN_COMMANDS = [
14
14
  "label",
15
15
  "assign",
16
16
  "implement",
17
+ "continue",
18
+ "rebase",
19
+ "sync",
17
20
  "help",
18
21
  "stop",
19
22
  ];
@@ -26,7 +29,10 @@ const COMMAND_HELP = {
26
29
  describe: "Rewrite the PR description from the actual diff.",
27
30
  triage: "Classify an issue: labels, severity and a plan.",
28
31
  answer: "Answer an issue question with repository context.",
29
- merge: "Merge the pull request (respects the merge permission).",
32
+ merge: "Merge the pull request, resolving conflicts first if needed (respects the merge permission).",
33
+ continue: "Another pass on the working branch: fix what the last run left, amend the PR.",
34
+ rebase: "Bring the branch up to date with its base and settle any conflict.",
35
+ sync: "Rewrite the PR body and title from the current diff.",
30
36
  close: "Close an issue or pull request.",
31
37
  reopen: "Reopen an issue or pull request.",
32
38
  label: "Add or remove labels: `label +bug -docs`.",
@@ -42,31 +48,65 @@ function stripFences(body) {
42
48
  export function parseCommand(body, config) {
43
49
  return parseInvocation(body, config);
44
50
  }
51
+ /** Every way the bot answers to, longest first so `@opencode-actions-bot-new` wins over `@opencode`. */
52
+ export function botHandles(config) {
53
+ const layer = botLayer(config);
54
+ const handles = new Set();
55
+ handles.add(`@${(layer.name ?? "opencode-actions-bot-new").toLowerCase()}`);
56
+ for (const alias of layer.aliases ?? [])
57
+ handles.add(alias.startsWith("@") ? alias.toLowerCase() : `@${alias.toLowerCase()}`);
58
+ return [...handles].sort((a, b) => b.length - a.length);
59
+ }
45
60
  export function parseInvocation(body, config) {
46
61
  if (!body)
47
62
  return null;
48
- const prefix = botLayer(config).commands?.prefix ?? "/bot";
63
+ const layer = botLayer(config);
64
+ const prefix = (layer.commands?.prefix ?? "/bot").toLowerCase();
49
65
  const cleaned = stripFences(body);
50
- const enabled = new Set(botLayer(config).commands?.enabled ?? KNOWN_COMMANDS);
66
+ const enabled = new Set(layer.commands?.enabled ?? KNOWN_COMMANDS);
67
+ const handles = botHandles(config);
68
+ const invocation = (command, args, raw) => enabled.has(command) ? { command, args, raw, actor: "", source: "issue_comment" } : null;
51
69
  for (const line of cleaned.split(/\r?\n/)) {
52
70
  const trimmed = line.trim();
53
- if (!trimmed.toLowerCase().startsWith(prefix.toLowerCase()))
54
- continue;
55
- const rest = trimmed.slice(prefix.length).trim();
56
- if (!rest)
71
+ const lower = trimmed.toLowerCase();
72
+ // `/bot review` and `/oc review`.
73
+ if (lower.startsWith(prefix)) {
74
+ const [head = "", ...args] = trimmed.slice(prefix.length).trim().split(/\s+/);
75
+ if (!head)
76
+ continue;
77
+ const found = invocation(head.replace(/^@/, "").toLowerCase(), args, trimmed);
78
+ if (found)
79
+ return found;
57
80
  continue;
58
- // Support "/bot review" and "@bot review" style invocations.
59
- const [head = "", ...args] = rest.split(/\s+/);
60
- const command = head.replace(/^@/, "").toLowerCase();
61
- if (!enabled.has(command))
62
- continue;
63
- return {
64
- command,
65
- args,
66
- raw: trimmed,
67
- actor: "",
68
- source: "issue_comment",
69
- };
81
+ }
82
+ // `@opencode-actions-bot-new review`. A mention with no command is still a
83
+ // mention, so it falls back to `answer`: "how does this work?" is the most
84
+ // common thing anyone types at a bot, and it needs no keyword.
85
+ for (const handle of handles) {
86
+ const at = lower.indexOf(handle);
87
+ if (at === -1)
88
+ continue;
89
+ // Not `foo@bar.com` or `user@opencode-actions-bot`: the mention must be a
90
+ // token of its own, or every email address would trigger a run.
91
+ const before = lower.slice(Math.max(0, at - 1), at);
92
+ const after = lower[at + handle.length] ?? " ";
93
+ if (before && !/[\s([{>|,;:!?"'`*_~-]/.test(before))
94
+ continue;
95
+ if (!/[\s,;:!?.()\[\]{}]/.test(after))
96
+ continue;
97
+ const rest = trimmed.slice(at + handle.length).trim().replace(/^[,;:!?.]+/, "").trim();
98
+ const [head = "", ...args] = rest.split(/\s+/);
99
+ const command = head.replace(/^@/, "").toLowerCase();
100
+ if (command) {
101
+ const found = invocation(command, args, trimmed);
102
+ if (found)
103
+ return found;
104
+ }
105
+ // A bare mention, or a mention of something that is not a command.
106
+ const answer = invocation("answer", rest ? [rest] : [], trimmed);
107
+ if (answer)
108
+ return answer;
109
+ }
70
110
  }
71
111
  return null;
72
112
  }
package/dist/config.d.ts CHANGED
@@ -165,12 +165,16 @@ export interface DescribeConfig {
165
165
  }
166
166
  /** GitHub-side behaviour. Never forwarded to OpenCode. */
167
167
  export interface BotLayer {
168
- /** Display name used in comments and commit trailers. */
168
+ /** Display name used in comments and commit trailers, and the `@mention`. */
169
169
  name?: string;
170
+ /** Extra `@handles` the bot answers to, e.g. the app slug and a short form. */
171
+ aliases?: string[];
170
172
  /** Emoji used in the comment header. */
171
173
  emoji?: string;
172
174
  /** Base branch for autofix PRs and issue implementations. */
173
175
  base_branch?: string;
176
+ /** Prefix for the branch that carries an issue implementation. */
177
+ work_branch_prefix?: string;
174
178
  /** Master switch for any write operation. */
175
179
  write?: boolean;
176
180
  /** Branches that count as protected for `merge_protected`. */
package/dist/config.js CHANGED
@@ -126,7 +126,7 @@ export function bot(config) {
126
126
  return config.bot ?? {};
127
127
  }
128
128
  export function feature(config, key) {
129
- return config.bot?.features?.[key] ?? false;
129
+ return config.bot?.features?.[key] === true;
130
130
  }
131
131
  export function permission(config, key) {
132
132
  return config.bot?.permissions?.[key] ?? "deny";