@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.
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The small signals that make a bot feel present: a reaction while it works, an
3
+ * emoji when it is done, and an issue closed when its pull request merges.
4
+ *
5
+ * GitHub Copilot never leaves an author guessing whether a request was heard. A
6
+ * run takes minutes, and without an acknowledgement the comment looks ignored.
7
+ * The reaction is the acknowledgement, and the emoji at the end is the receipt.
8
+ */
9
+ /** What the bot reacts with, in order of meaning. */
10
+ export const REACTIONS = {
11
+ /** Accepted: the request was understood and is running. */
12
+ accepted: "eyes",
13
+ /** Finished, with a change. */
14
+ done: "+1",
15
+ /** Finished, nothing to do or the request was refused. */
16
+ nothing: "-1",
17
+ /** Failed. */
18
+ failed: "confused",
19
+ };
20
+ /**
21
+ * React to a comment or issue.
22
+ *
23
+ * GitHub accepts a fixed set of reaction names; anything else is a 422, which is
24
+ * why the set is enumerated rather than free text. A failure is swallowed: a
25
+ * missing reaction must never fail the work the reaction was acknowledging.
26
+ */
27
+ export async function react(github, repo, subject, reaction) {
28
+ const path = subject.kind === "comment"
29
+ ? `/repos/${repo.owner}/${repo.repo}/issues/comments/${subject.commentId}/reactions`
30
+ : `/repos/${repo.owner}/${repo.repo}/issues/${subject.number}/reactions`;
31
+ return github.post(path, { content: reaction }).catch(() => null);
32
+ }
33
+ /** Pull requests and issues share the same issue-number space. */
34
+ export function subjectFor(input) {
35
+ if (input.commentId)
36
+ return { kind: "comment", number: input.number, commentId: input.commentId };
37
+ return { kind: input.isPull ? "pull" : "issue", number: input.number };
38
+ }
39
+ /**
40
+ * Close the issue a pull request belongs to, when the pull request closes it.
41
+ *
42
+ * GitHub does this itself for `Closes #n` in a merged PR body, but only for the
43
+ * default branch and only when the body was written correctly. Doing it
44
+ * explicitly covers the cases GitHub skips: a bot-written body, a merge into a
45
+ * release branch, and a PR whose body a person edited.
46
+ */
47
+ export async function closeLinkedIssues(github, repo, pull) {
48
+ const numbers = new Set();
49
+ const text = `${pull.title ?? ""}\n${pull.body ?? ""}`;
50
+ for (const match of text.matchAll(/\b(?:closes|fixes|resolves|refs)\s+#(\d+)/gi)) {
51
+ numbers.add(Number(match[1]));
52
+ }
53
+ for (const match of text.matchAll(/\/issues\/(\d+)/g))
54
+ numbers.add(Number(match[1]));
55
+ if (!numbers.size)
56
+ return { closed: [] };
57
+ const closed = [];
58
+ for (const number of numbers) {
59
+ const issue = await github.getIssue(repo, number).catch(() => null);
60
+ // Never close a pull request by mistake: they share the number space.
61
+ if (!issue || issue.pull_request || issue.state === "closed")
62
+ continue;
63
+ await github.updateIssue(repo, number, {
64
+ state: "closed",
65
+ state_reason: "completed",
66
+ });
67
+ await github
68
+ .comment(repo, number, `Closed by #${pull.number}, which is merged.`)
69
+ .catch(() => { });
70
+ closed.push(number);
71
+ }
72
+ return { closed };
73
+ }
74
+ /**
75
+ * Announce a merge inside the pull request, so the thread ends with a result
76
+ * rather than a merge commit nobody reads.
77
+ */
78
+ export async function commentMerge(github, repo, pullNumber, detail) {
79
+ const issues = detail.issues.length ? `\n\nCloses ${detail.issues.map((n) => `#${n}`).join(", ")}.` : "";
80
+ const body = `Merged${detail.method ? ` with ${detail.method}` : ""}${detail.sha ? ` as ${detail.sha.slice(0, 7)}` : ""}.${issues}`;
81
+ return github.comment(repo, pullNumber, body).catch(() => null);
82
+ }
83
+ /**
84
+ * Merge, and when GitHub refuses because the branch is behind or conflicting,
85
+ * say exactly which, because "merge failed" tells the author nothing.
86
+ *
87
+ * A conflict is not something a merge call can resolve: the branch has to be
88
+ * updated and the conflict committed. Returning the reason lets the caller run
89
+ * that step instead of retrying the same merge.
90
+ */
91
+ export async function mergeWithReason(github, repo, pullNumber, method = "squash") {
92
+ const pull = await github.getPull(repo, pullNumber);
93
+ if (pull.merged)
94
+ return { merged: true, already: true, sha: pull.merge_commit_sha ?? undefined };
95
+ const mergeable = pull.mergeable;
96
+ const state = pull.mergeable_state;
97
+ if (mergeable === false || state === "dirty") {
98
+ return { merged: false, conflict: true, reason: "the branch has conflicts with its base" };
99
+ }
100
+ if (state === "behind") {
101
+ return { merged: false, behind: true, reason: "the branch is behind its base and needs an update" };
102
+ }
103
+ if (state === "blocked") {
104
+ return { merged: false, blocked: true, reason: "a required check or review has not passed" };
105
+ }
106
+ try {
107
+ const result = await github.mergePull(repo, pullNumber, {
108
+ merge_method: method,
109
+ commit_title: `${pull.title} (#${pullNumber})`,
110
+ });
111
+ return { merged: Boolean(result?.merged), sha: result?.sha, method };
112
+ }
113
+ catch (error) {
114
+ // A 405 carries GitHub's own explanation, usually the conflict or the check.
115
+ return { merged: false, reason: error?.body?.split("\n")[0] ?? error?.message ?? "merge refused" };
116
+ }
117
+ }
package/dist/summary.js CHANGED
@@ -39,6 +39,8 @@ else if (result.rejected) {
39
39
  else if (result.review) {
40
40
  const review = result.review;
41
41
  const findings = review.findings ?? [];
42
+ // `posted` is the verdict, not the GitHub review state: every review is sent as
43
+ // COMMENT, so the icon must not imply a block that does not exist.
42
44
  const icon = result.posted === "APPROVE" ? "✅" : result.posted === "REQUEST_CHANGES" ? "🚧" : "💬";
43
45
  lines.push(`${icon} **${result.posted ?? "COMMENT"}**`, "");
44
46
  lines.push(review.summary ?? "", "");
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@eduardo191labs/opencode-actions",
4
- "version": "0.1.1",
4
+ "version": "0.1.3",
5
5
  "description": "GitHub Copilot-equivalent bot for OpenCode: PRs, reviews, issues, workflow autofix, MCP tools and comment commands.",
6
6
  "type": "module",
7
7
  "license": "MIT",
@@ -39,7 +39,9 @@
39
39
  "action.yml",
40
40
  "schemas",
41
41
  "README.md",
42
- "LICENSE"
42
+ "LICENSE",
43
+ "scripts/install-opencode.sh",
44
+ "scripts/check-marketplace.js"
43
45
  ],
44
46
  "engines": {
45
47
  "node": ">=20"
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Checks action.yml against the rules GitHub Marketplace applies at publish
4
+ * time. A violation there fails the listing with a vague message, so catching
5
+ * it in CI is the only way to find out before a release is tagged.
6
+ *
7
+ * Rules enforced (docs.github.com, "Publishing actions in GitHub Marketplace"):
8
+ * - action.yml must exist at the repository root and be named exactly that;
9
+ * - `name` is present, unique in spirit, and is not a reserved Marketplace name;
10
+ * - `description` is present and shorter than 125 characters;
11
+ * - `branding.icon` is a Feather icon name and `branding.color` is one of the
12
+ * eight accepted colours;
13
+ * - the repository is public.
14
+ *
15
+ * What cannot be checked offline is reported instead of implied: global name
16
+ * uniqueness, and whether the icon exists in the current Feather set.
17
+ */
18
+ import { readFileSync, existsSync } from "node:fs"
19
+
20
+ const LIMITS = { description: 125, name: 65 }
21
+ const COLORS = ["white", "yellow", "blue", "green", "orange", "red", "purple", "gray-dark"]
22
+ const RESERVED = [
23
+ "actions",
24
+ "marketplace",
25
+ "github",
26
+ "github actions",
27
+ "workflow",
28
+ "apps",
29
+ ]
30
+
31
+ const errors = []
32
+ const warnings = []
33
+
34
+ if (!existsSync("action.yml")) {
35
+ console.error("action.yml is missing from the repository root")
36
+ process.exit(1)
37
+ }
38
+
39
+ // A minimal parser keeps this dependency-free; the file is small and the fields
40
+ // are flat, so an indentation-aware reader is enough and does not risk pulling
41
+ // a YAML engine into the release path.
42
+ const lines = readFileSync("action.yml", "utf8").replace(/\r\n/g, "\n").split("\n")
43
+ const fields = {}
44
+ let section = null
45
+ for (const line of lines) {
46
+ if (/^[a-z]/.test(line)) {
47
+ const [key, ...rest] = line.split(":")
48
+ section = key.trim()
49
+ const value = rest.join(":").trim()
50
+ if (value) fields[section] = unquote(value)
51
+ continue
52
+ }
53
+ const match = /^\s{2}([a-z-]+):\s*(.*)$/.exec(line)
54
+ if (match && section) {
55
+ const key = `${section}.${match[1]}`
56
+ if (match[2].trim()) fields[key] = unquote(match[2].trim())
57
+ }
58
+ }
59
+
60
+ function unquote(value) {
61
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
62
+ return value.slice(1, -1)
63
+ }
64
+ return value
65
+ }
66
+
67
+ const name = fields.name
68
+ const description = fields.description
69
+ const icon = fields["branding.icon"]
70
+ const color = fields["branding.color"]
71
+
72
+ if (!name) errors.push("`name` is missing")
73
+ else {
74
+ if (name.length > LIMITS.name) errors.push(`\`name\` is ${name.length} characters (limit ${LIMITS.name})`)
75
+ if (RESERVED.includes(name.toLowerCase())) errors.push(`\`name\` "${name}" is reserved by GitHub`)
76
+ }
77
+
78
+ if (!description) errors.push("`description` is missing")
79
+ else if (description.length >= LIMITS.description) {
80
+ errors.push(`\`description\` is ${description.length} characters; Marketplace requires fewer than ${LIMITS.description}`)
81
+ }
82
+
83
+ if (!icon) errors.push("`branding.icon` is missing")
84
+ else if (!/^[a-z][a-z0-9-]*$/.test(icon)) errors.push(`\`branding.icon\` "${icon}" is not shaped like a Feather icon name`)
85
+
86
+ if (!color) errors.push("`branding.color` is missing")
87
+ else if (!COLORS.includes(color)) errors.push(`\`branding.color\` "${color}" must be one of ${COLORS.join(", ")}`)
88
+
89
+ if (fields.runs && !existsSync("action.yml")) errors.push("action metadata disappeared during the check")
90
+
91
+ if (!/^composite$|^node\d*$|^docker$/m.test(fields["runs.using"] ?? "")) {
92
+ errors.push("`runs.using` must be composite, node20/node22, or docker")
93
+ }
94
+
95
+ if (!fields["runs.using"]) errors.push("`runs.using` is missing")
96
+
97
+ warnings.push("global name uniqueness cannot be verified offline")
98
+ warnings.push(`icon "${icon ?? "?"}" shape is checked, not membership in the current Feather set`)
99
+
100
+ for (const warning of warnings) console.log(`· ${warning}`)
101
+
102
+ if (errors.length) {
103
+ for (const error of errors) console.error(`✗ ${error}`)
104
+ console.error(`\n${errors.length} Marketplace rule(s) violated`)
105
+ process.exit(1)
106
+ }
107
+
108
+ console.log(`✓ action.yml satisfies the checkable Marketplace rules`)
109
+ console.log(` name: ${name} (${name.length}/${LIMITS.name})`)
110
+ console.log(` description: ${description.length}/${LIMITS.description - 1} characters`)
111
+ console.log(` branding: ${icon} / ${color}`)
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env bash
2
+ # install-opencode.sh — installs the official OpenCode CLI and guarantees that
3
+ # `opencode2` (the V2 runtime) is available.
4
+ #
5
+ # Why npm and not the curl installer:
6
+ # - @opencode/cli ships both `opencode` and `opencode2` as bin entries pointing
7
+ # at the native binary, so installing the package gives us both names for the
8
+ # same runtime without guessing a release URL.
9
+ # - The version is pinned so a CI run is reproducible, and a floating channel
10
+ # can be requested when that is what we want.
11
+ #
12
+ # Environment:
13
+ # OPENCODE_CHANNEL "stable" (default) or an exact version such as 2.4.2
14
+ # OPENCODE_BIN output: the resolved binary path
15
+ set -euo pipefail
16
+
17
+ CHANNEL="${OPENCODE_CHANNEL:-stable}"
18
+
19
+ if [ "${CHANNEL}" = "stable" ]; then
20
+ SPEC="@opencode/cli@latest"
21
+ else
22
+ SPEC="@opencode/cli@${CHANNEL}"
23
+ fi
24
+
25
+ echo "→ installing ${SPEC} from npm"
26
+ npm install -g "${SPEC}" --no-audit --no-fund
27
+
28
+ PREFIX="$(npm prefix -g)"
29
+ BIN_DIR="${PREFIX}/bin"
30
+
31
+ # Prefer the V2 entry point: everything this bot emits targets the V2 config
32
+ # schema (the `permissions` ruleset), which V1 rejects outright.
33
+ CANDIDATES=(
34
+ "${BIN_DIR}/opencode2"
35
+ "${BIN_DIR}/opencode"
36
+ )
37
+
38
+ RESOLVED=""
39
+ for candidate in "${CANDIDATES[@]}"; do
40
+ if [ -x "${candidate}" ]; then
41
+ RESOLVED="${candidate}"
42
+ break
43
+ fi
44
+ done
45
+
46
+ if [ -z "${RESOLVED}" ]; then
47
+ echo "::error::could not find an opencode binary under ${BIN_DIR}"
48
+ ls -la "${BIN_DIR}" >&2 || true
49
+ exit 1
50
+ fi
51
+
52
+ # The native package may expose the binary under a different name; a symlink
53
+ # keeps `opencode2` working for callers that expect the V2 name.
54
+ if [ ! -x "${BIN_DIR}/opencode2" ]; then
55
+ ln -sf "${RESOLVED}" "${BIN_DIR}/opencode2"
56
+ echo "→ linked opencode2 -> ${RESOLVED}"
57
+ fi
58
+
59
+ echo "→ resolved ${RESOLVED}"
60
+ "${BIN_DIR}/opencode2" --version
61
+
62
+ # Fail loudly rather than letting the bot run on a V1 runtime, because a V1
63
+ # runtime rejects the configuration this bot generates.
64
+ VERSION_OUTPUT="$("${BIN_DIR}/opencode2" --version 2>&1 || true)"
65
+ if [[ "${VERSION_OUTPUT}" =~ ^opencode\ v?([0-9]+) ]]; then
66
+ MAJOR="${BASH_REMATCH[1]}"
67
+ if [ "${MAJOR}" -lt 2 ]; then
68
+ echo "::error::opencode2 reports v${MAJOR}; this bot requires the V2 runtime"
69
+ exit 1
70
+ fi
71
+ fi
72
+
73
+ echo "OPENCODE_BIN=${BIN_DIR}/opencode2" >> "${GITHUB_ENV:-/dev/null}"
74
+ echo "${BIN_DIR}" >> "${GITHUB_PATH:-/dev/null}"