@eduardo191labs/opencode-actions 0.1.1 → 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,11 @@ 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";
13
+ import { reviewThreadPrompt, replyToReviewThread, threadContext, wantsFix } from "./review-thread.js";
11
14
  export async function reviewPullRequest(ctx, options) {
12
15
  const { github, repo, config } = ctx;
13
16
  const pull = await github.getPull(repo, options.prNumber);
@@ -212,15 +215,12 @@ export async function handleIssue(ctx, number, mode) {
212
215
  const result = await runWithPrompt(ctx, mode === "implement" ? "implement" : "issues", prompt, compiled.content);
213
216
  const parsed = result.resultJson;
214
217
  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}.`,
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 };
221
221
  });
222
- if (changed)
223
- return { implemented: true, pr: changed };
222
+ if (done.pr)
223
+ return { implemented: true, ...done };
224
224
  }
225
225
  const body = parsed && parsed.summary
226
226
  ? issueTriageBody(config, parsed, { model: compiled.model, cost: result.cost })
@@ -299,8 +299,13 @@ export async function handleWorkflowFailure(ctx, runId) {
299
299
  }
300
300
  return { fixable: false, diagnosis: parsed?.diagnosis };
301
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)}`;
302
307
  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)}`,
308
+ branch: bot(config).autofix?.open_pr === false ? run.head_branch : `${prefix}${slug}`,
304
309
  openPr: bot(config).autofix?.open_pr !== false,
305
310
  title: parsed.commit_message ?? `ci: fix ${run.name}`,
306
311
  base: bot(config).autofix?.open_pr === false ? run.head_branch : (bot(config).base_branch ?? "main"),
@@ -330,6 +335,9 @@ export async function handleComment(ctx, input) {
330
335
  ctx.log(`command rejected: ${allowed.reason}`);
331
336
  return { rejected: allowed.reason };
332
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);
333
341
  if (invocation.command === "help") {
334
342
  await github.comment(repo, input.issueNumber, helpText(config));
335
343
  return { replied: true };
@@ -342,6 +350,46 @@ export async function handleComment(ctx, input) {
342
350
  if (invocation.command === "merge") {
343
351
  return mergePull(ctx, input.issueNumber);
344
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
+ }
345
393
  if (invocation.command === "close" || invocation.command === "reopen") {
346
394
  const state = invocation.command === "close" ? "closed" : "open";
347
395
  if (permission(config, "manage_issues") !== "allow")
@@ -386,25 +434,28 @@ export async function handleComment(ctx, input) {
386
434
  context: `${issue.title}\n\n${issue.body ?? ""}\n\nFiles: ${(await listRootFiles(ctx)).slice(0, 200).join(", ")}`,
387
435
  });
388
436
  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),
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 };
396
441
  });
397
- if (changed)
398
- 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;
399
448
  }
400
449
  if (permission(config, "comment") === "allow") {
401
450
  await github.comment(repo, input.issueNumber, commandReplyBody(config, result.text, { actor: input.actor, command: invocation.command }));
402
451
  }
452
+ await react(github, repo, subjectFor({ number: input.issueNumber, isPull: input.kind === "pull_request" }), REACTIONS.done);
403
453
  return { replied: true };
404
454
  }
455
+ function compiledFor(config, mode) {
456
+ return compileConfig(config, { mode });
457
+ }
405
458
  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
459
  return parseInvocation(body, config);
409
460
  }
410
461
  export async function mergePull(ctx, number) {
@@ -416,8 +467,68 @@ export async function mergePull(ctx, number) {
416
467
  return { rejected: `merge requires bot.permissions.${isProtected ? "merge_protected" : "merge_pull_requests"} = "allow"` };
417
468
  if (pull.merged)
418
469
  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 };
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 };
421
532
  }
422
533
  export async function describePull(ctx, number) {
423
534
  const { github, repo, config } = ctx;
@@ -443,7 +554,7 @@ async function runWithPrompt(ctx, mode, prompt, content) {
443
554
  const env = { ...process.env, OPENCODE_RESULT_FILE: resultPath };
444
555
  const model = typeof content.model === "string" ? content.model : undefined;
445
556
  ctx.log(`opencode run (${mode})${model ? ` with ${model}` : ""}`);
446
- const result = await runOpencode({
557
+ let result = await runOpencode({
447
558
  message: `${prompt}\n\nThe result file is: ${resultPath}`,
448
559
  cwd: ctx.workspace,
449
560
  config: content,
@@ -453,6 +564,9 @@ async function runWithPrompt(ctx, mode, prompt, content) {
453
564
  env,
454
565
  live: feature(ctx.config, "live_log"),
455
566
  });
567
+ return attachResult(result, resultPath);
568
+ }
569
+ async function attachResult(result, resultPath) {
456
570
  let resultJson = null;
457
571
  try {
458
572
  resultJson = await readResult(resultPath);
@@ -462,7 +576,7 @@ async function runWithPrompt(ctx, mode, prompt, content) {
462
576
  /* the agent may not have written it */
463
577
  }
464
578
  if (!result.ok) {
465
- ctx.log(`run failed (exit ${result.exitCode}): ${result.error ?? ""}`);
579
+ process.stderr.write(`[opencode-actions] run failed (exit ${result.exitCode}): ${result.error ?? ""}\n`);
466
580
  }
467
581
  return Object.assign(result, { resultJson });
468
582
  }
@@ -508,6 +622,126 @@ async function listRootFiles(ctx) {
508
622
  return [];
509
623
  }
510
624
  }
625
+ // ------------------------------------------------------- review comments
626
+ /**
627
+ * Answer a comment left on a specific line of a pull request.
628
+ *
629
+ * This is the interaction Copilot users reach for most: a comment on a diff
630
+ * line, answered where it was written. The payload already carries the file,
631
+ * the line and the hunk, so no checkout reconstruction is needed.
632
+ */
633
+ export async function handleReviewComment(ctx, payload) {
634
+ const { github, repo, config } = ctx;
635
+ const comment = payload.comment;
636
+ const pullNumber = payload.pull_request.number;
637
+ // Never answer the bot's own reply, or a thread would grow by itself.
638
+ const self = (process.env.GITHUB_ACTOR ?? "github-actions[bot]").toLowerCase();
639
+ if (String(comment.user?.login ?? "").toLowerCase() === self)
640
+ return { skipped: true, reason: "own comment" };
641
+ const invocation = parseCommandBody(config, comment.body ?? "");
642
+ const fix = wantsFix(comment.body ?? "");
643
+ if (!invocation && !fix && !botMentioned(comment.body ?? "", config)) {
644
+ // A plain comment on a line is not necessarily addressed to the bot.
645
+ return { skipped: true, reason: "not addressed to the bot" };
646
+ }
647
+ if (permission(config, "comment") !== "allow")
648
+ return { rejected: "comment permission denied" };
649
+ const thread = await threadContext({
650
+ github,
651
+ repo,
652
+ pullNumber,
653
+ commentId: comment.id,
654
+ inReplyToId: comment.in_reply_to_id,
655
+ }).catch(() => "");
656
+ const compiled = compileConfig(config, { mode: fix ? "commands" : "review" });
657
+ const prompt = reviewThreadPrompt({
658
+ github,
659
+ repo,
660
+ path: comment.path,
661
+ line: comment.line ?? comment.original_line ?? 0,
662
+ diffHunk: comment.diff_hunk ?? "",
663
+ body: comment.body ?? "",
664
+ threadBody: thread,
665
+ author: comment.user.login,
666
+ pullNumber,
667
+ commentId: comment.id,
668
+ });
669
+ const result = await runWithPrompt(ctx, fix ? "commands" : "review", prompt, compiled.content);
670
+ let pushed = null;
671
+ if (fix) {
672
+ pushed = await pushChanges(ctx, compiled.content, {
673
+ branch: payload.pull_request.head.ref,
674
+ openPr: false,
675
+ base: payload.pull_request.base.ref,
676
+ title: `fix: address review comment on ${comment.path}`,
677
+ body: `Addresses the review comment on \`${comment.path}:${comment.line ?? "?"}\`.`,
678
+ });
679
+ }
680
+ const body = pushed
681
+ ? `${result.text.trim()}
682
+
683
+ ---
684
+ Pushed as a commit on \`${payload.pull_request.head.ref}\`.`
685
+ : result.text.trim() || "I could not produce an answer for this comment.";
686
+ await replyToReviewThread({ github, repo, pullNumber, commentId: comment.id, body });
687
+ ctx.log(`replied to review comment ${comment.id}${pushed ? " and pushed a fix" : ""}`);
688
+ return { replied: true, fixed: Boolean(pushed) };
689
+ }
690
+ /** True when the comment names the bot, e.g. "@opencode" or "/bot". */
691
+ export function botMentioned(body, config) {
692
+ const name = (bot(config).name ?? "opencode").toLowerCase();
693
+ const prefix = (bot(config).commands?.prefix ?? "/bot").toLowerCase();
694
+ const lower = body.toLowerCase();
695
+ return lower.includes(`@${name}`) || lower.includes(prefix);
696
+ }
697
+ // ------------------------------------------------------------- push review
698
+ /**
699
+ * Review a push directly on the commits.
700
+ *
701
+ * `commit_review` exists for repositories where changes do not always come
702
+ * through a pull request: a direct push still gets a review posted as a commit
703
+ * comment, with the same finding schema and the same suggestion blocks.
704
+ */
705
+ export async function reviewPush(ctx, payload) {
706
+ const { github, repo, config } = ctx;
707
+ const before = payload.before;
708
+ const after = payload.after;
709
+ if (!after || /^0+$/.test(after))
710
+ return { skipped: true, reason: "branch deleted" };
711
+ const base = after === before ? `${after}^` : before;
712
+ const comparison = await github.compare(repo, base, after).catch(() => null);
713
+ if (!comparison?.files?.length)
714
+ return { skipped: true, reason: "no changed files" };
715
+ const files = comparison.files.slice(0, 100);
716
+ const compiled = compileConfig(config, { mode: "review" });
717
+ const prompt = reviewPrompt({
718
+ config,
719
+ repo: `${repo.owner}/${repo.repo}`,
720
+ prNumber: 0,
721
+ title: comparison.commits?.[0]?.commit?.message?.split("\n")[0] ?? "direct push",
722
+ author: payload.pusher?.name ?? "unknown",
723
+ base,
724
+ head: after,
725
+ filesSummary: filesSummary(files),
726
+ diffDigest: diffDigest(files, (bot(config).review?.max_diff_kb ?? 256) * 1024),
727
+ facts: repoFacts(await listRootFiles(ctx)),
728
+ extraInstructions: bot(config).review?.instructions,
729
+ });
730
+ const result = await runWithPrompt(ctx, "review", prompt, compiled.content);
731
+ const review = parseReview(result, ctx);
732
+ if (!review.findings.length)
733
+ return { reviewed: true, findings: 0 };
734
+ const body = reviewSummaryBody(config, review, {
735
+ model: compiled.model,
736
+ cost: result.cost,
737
+ durationMs: result.durationMs,
738
+ });
739
+ if (permission(config, "comment") === "allow") {
740
+ // A commit comment has its own endpoint; the issues endpoint wants a number.
741
+ await github.post(`/repos/${repo.owner}/${repo.repo}/commits/${after}/comments`, { body });
742
+ }
743
+ return { reviewed: true, findings: review.findings.length };
744
+ }
511
745
  /** Route a decoded GitHub event to the matching handler. */
512
746
  export async function dispatch(ctx, event, payload) {
513
747
  switch (event) {
@@ -535,6 +769,13 @@ export async function dispatch(ctx, event, payload) {
535
769
  return { skipped: true };
536
770
  return handleIssue(ctx, payload.issue.number, "triage");
537
771
  }
772
+ case "pull_request_review_comment": {
773
+ if (payload.action !== "created")
774
+ return { skipped: true };
775
+ if (!feature(ctx.config, "review_comments"))
776
+ return { skipped: true };
777
+ return handleReviewComment(ctx, payload);
778
+ }
538
779
  case "workflow_run": {
539
780
  if (payload.action !== "completed")
540
781
  return { skipped: true };
@@ -543,7 +784,10 @@ export async function dispatch(ctx, event, payload) {
543
784
  case "push": {
544
785
  if (!feature(ctx.config, "commit_review"))
545
786
  return { skipped: true };
546
- return { skipped: true, reason: "commit_review is not implemented for push payloads yet" };
787
+ // A push with no commits (a tag or a branch delete) has nothing to review.
788
+ if (!payload.commits?.length)
789
+ return { skipped: true, reason: "no commits in the push" };
790
+ return reviewPush(ctx, payload);
547
791
  }
548
792
  case "workflow_dispatch": {
549
793
  const command = payload.inputs?.command ?? "review";
@@ -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
+ }