蓝色天空.知识 · 实践 · 创造
我的收藏
OpenCode 教程目录 28章
OpenCode / LEARN BY DOING

用 GitHub 事件触发 OpenCode 任务

区分会话评论、代码行评论和自动触发,用本地 Git 验证分支与权限边界。

学完这一章,你能够

  • 区分会话评论、代码行评论和自动触发,用本地 Git 验证分支与权限边界。

把事件、动作和输出分别定义

OpenCode V1 的 GitHub 集成由 GitHub Actions Runner 执行。评论可通过 /opencode 或 /oc 提交明确任务。Issue 中可要求定位复现步骤或提供建议,也可另行授权创建修复分支和 PR。Runner 执行代码的位置与模型请求发往哪家提供商是两个问题。

Issue 与 PR 主讨论区的评论都可由 issue_comment 进入。读取事件的 issue.pull_request 字段可判断评论是否属于 PR。审查中的行评论用 pull_request_review_comment,需保留文件路径、行号和 diff 语境。行号含义随 diff 位置和是否过期而变。

例如用评论解释缺货记录,用另一条评论请求修复重复预留。请求修改现有 PR 时要区分目标分支与分叉的权限,在代码行评论中可只针对一处空订单处理。本站用独立数据验证评论匹配和这些上下文分支;本地 Git 实际提交一份只改库存文件的变更。

安装、工作流与认证

V1 可在已经关联 GitHub 的项目中运行 opencode github install,按提示核对 GitHub App 的安装仓库、生成的工作流与模型密钥。手动方式在目标仓库安装 OpenCode GitHub App,再将工作流置于 .github/workflows/ 下,按所选事件声明 types 并选择运行环境。

GitHub App 默认用 OIDC 换取安装令牌。Actions 作业的 id-token: write 用于请求 OIDC token,checkout 私有仓库还需要 contents: read。App 允许的评论、分支和 PR 操作取决于应用安装权限。默认示例的 checkout 使用浅克隆并关闭持久化凭据,需要比较历史时单独选择深度。

如果明确改用 use_github_token,需把 GITHUB_TOKEN 作为环境变量传入并按具体动作配置权限。需要提交时还要设置 Git 身份并核对 checkout 对 Git 凭据的处理。采用 PAT 或其他 App 令牌时让 checkout 的 token 与步骤所用令牌对应。模型 API Key 放在 Actions Secrets,单独核对模型提供商及 model 的 provider/model 标识。

变更或外部评论都按不可信输入处理。尽量给仅输出报告的任务保留只读权限,将写分支与发评论的权限按任务授权。固定第三方 action 到已核对提交。普通 fork 的 pull_request 运行一般没有仓库 secrets,且 GITHUB_TOKEN 只读;避免用高权限上下文检出并执行不可信分支。

自动运行和提示约束

pull_request 可用 opened、synchronize 等动作自动触发审查。明确需要检查的边界条件、是否允许修改、结果输出位置。issues 用 opened 或 edited 自动分类时显式提供 prompt,可按项目规则先过滤,再回复复现建议或文档链接。

schedule 与 workflow_dispatch 没有评论文本可用。为作业指定固定 prompt,并分开配置报告和写入权限。练习的 schedule 使用每周一 09:23 UTC,日志只显示本站匹配的任务类别。定时执行没有现成 Issue 作为评论目标。

自定义 prompt 可以要求检查空订单、错误处理并给出可复查的建议。本站只读工作流示例读取 GitHub 提供的事件文件,使用默认分支的检查脚本并输出任务类别。真正调用 OpenCode、安装 App 或创建线上 PR 需按上节设置并在隔离目标仓库验证。

选择 Action 输入

输入或历史记号用法与约束
model必填,写 provider/model 并使用该提供商的密钥。
agent选择主智能体,省略时由默认角色配置或 V1 回退决定。
prompt明确覆盖内置任务文字;定时、手动和 Issue 自动分类须单独给任务。
share旧资料的分享项。当前 V1 Action 配置参考未列此项,按实际版本及会话分享策略确认。
token旧资料统称令牌。当前需区分 OIDC/App、use_github_token 和秘密变量里的 PAT。

根据事件选择上下文

事件动作及输入
issue_comment新建 Issue 或 PR 讨论评论,读取命令和 Issue 类型。
pull_request_review_comment新建行评论,保留路径、行号与差异。
issues创建或编辑 Issue,提供分类提示,必要时做参与者筛选。
pull_requestPR 建立或更新时审查;检查是否来源于 fork。
schedule按 cron 触发,使用固定 prompt,并明确报告或写入权限。
workflow_dispatch从 Actions 手动运行一个可复查的任务,固定 prompt 或定义受控输入。

选择仓库任务并复查本地修复分支

含完整源码 · 165 行
展开查看收起
python
"""Run an offline GitHub event-policy exercise with temporary Git history."""

import argparse
from copy import deepcopy
import json
import os
from pathlib import Path
import re
import subprocess
import sys
from tempfile import TemporaryDirectory


COMMENT_EVENTS = {"issue_comment", "pull_request_review_comment"}
TRUSTED_ASSOCIATIONS = {"OWNER", "MEMBER", "COLLABORATOR"}
TRIGGER = re.compile(r"(?:^|\s)/(?:opencode|oc)(?=\s|$)", re.IGNORECASE)
FIXED_PROMPTS = {
    "issues": "Classify the reported inventory fault and propose a reproduction.",
    "pull_request": "Inspect the change for incorrect handling of empty orders.",
    "schedule": "List unresolved inventory TODOs and summarize them in the log.",
    "workflow_dispatch": "Explain what the inventory check does.",
}


def plan(event, payload):
    """Resolve only a local teaching plan. Never invoke a shell from event text."""
    action = payload.get("action")
    if event in COMMENT_EVENTS:
        comment = payload.get("comment", {})
        if action != "created" or comment.get("author_association") not in TRUSTED_ASSOCIATIONS:
            return None
        body = comment.get("body", "")
        match = TRIGGER.search(body)
        if not match:
            return None
        prompt = (body[:match.start()] + " " + body[match.end():]).strip()
        if not prompt:
            return None
        if event == "pull_request_review_comment":
            return dict(kind="inline_review", prompt=prompt, path=comment.get("path"), line=comment.get("line"))
        kind = "pull_request_discussion" if payload.get("issue", {}).get("pull_request") else "issue_discussion"
        return dict(kind=kind, prompt=prompt)
    if event == "issues" and action not in {"opened", "edited"}:
        return None
    if event == "pull_request":
        pr = payload.get("pull_request", {})
        if action not in {"opened", "synchronize", "reopened"}:
            return None
        head_repo = pr.get("head", {}).get("repo") or {}
        base_repo = payload.get("repository", {}).get("full_name")
        if not base_repo or head_repo.get("full_name") != base_repo:
            return None
    if event in FIXED_PROMPTS:
        return dict(kind=event, prompt=FIXED_PROMPTS[event])
    return None


def git(repo, *args):
    environment = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")}
    environment.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT="0")
    return subprocess.check_output(["git", *args], cwd=repo, env=environment, encoding="utf-8", timeout=8).strip()


def isolated_branch(route):
    assert route["kind"] == "issue_discussion" and route["prompt"] == "fix duplicate reservation"
    with TemporaryDirectory(prefix="mbsky-github-event-") as path:
        repo = Path(path)
        git(repo, "init", "-q", "-b", "main")
        git(repo, "config", "user.name", "Inventory Fixture")
        git(repo, "config", "user.email", "inventory@example.invalid")
        git(repo, "config", "core.hooksPath", str(repo / "empty-hooks"))
        stock = repo / "inventory.txt"
        stock.write_text("reserve twice\n", encoding="utf-8")
        (repo / "unrelated.txt").write_text("unchanged\n", encoding="utf-8")
        git(repo, "add", "inventory.txt", "unrelated.txt")
        git(repo, "commit", "-qm", "Prepare sample inventory")
        git(repo, "switch", "-qc", "review/issue-37")
        stock.write_text("reserve once\n", encoding="utf-8")
        git(repo, "add", "inventory.txt")
        git(repo, "commit", "-qm", "Fix fixture reservation")
        return dict(
            branch=git(repo, "branch", "--show-current"),
            changed=git(repo, "diff", "--name-only", "main...HEAD").splitlines(),
            original=git(repo, "show", "main:inventory.txt"),
            fixed=git(repo, "show", "HEAD:inventory.txt"),
            remotes=git(repo, "remote").splitlines(),
        )


def examples():
    issue = {"action": "created", "issue": {"number": 37},
             "comment": {"author_association": "MEMBER", "body": "/opencode explain reservation 37"}}
    fix = deepcopy(issue)
    fix["comment"]["body"] = "/OPENCODE fix duplicate reservation"
    discussion = deepcopy(issue)
    discussion["issue"]["pull_request"] = {"url": "https://example.invalid/pulls/42"}
    discussion["comment"]["body"] = "Check the unit conversion /oc"
    inline = deepcopy(issue)
    inline["comment"].update(body="/oc handle empty order here", path="src/orders.py", line=18)
    outsider = deepcopy(issue)
    outsider["comment"]["author_association"] = "NONE"
    false_match = deepcopy(issue)
    false_match["comment"]["body"] = "/ocean data"
    edited = deepcopy(issue)
    edited["action"] = "edited"
    pr = {"action": "synchronize", "repository": {"full_name": "mbsky/inventory"},
          "pull_request": {"head": {"repo": {"full_name": "mbsky/inventory"}}}}
    fork = deepcopy(pr)
    fork["pull_request"]["head"]["repo"]["full_name"] = "external/inventory"
    unsupported = deepcopy(pr)
    unsupported["action"] = "closed"
    examples = [
        ("issue_explain", "issue_comment", issue, dict(kind="issue_discussion", prompt="explain reservation 37")),
        ("issue_fix", "issue_comment", fix, dict(kind="issue_discussion", prompt="fix duplicate reservation")),
        ("pr_discussion", "issue_comment", discussion, dict(kind="pull_request_discussion", prompt="Check the unit conversion")),
        ("line_comment", "pull_request_review_comment", inline,
         dict(kind="inline_review", prompt="handle empty order here", path="src/orders.py", line=18)),
        ("outsider", "issue_comment", outsider, None),
        ("token_boundary", "issue_comment", false_match, None),
        ("edited_comment", "issue_comment", edited, None),
        ("pr_review", "pull_request", pr,
         dict(kind="pull_request", prompt="Inspect the change for incorrect handling of empty orders.")),
        ("fork", "pull_request", fork, None),
        ("closed_pr", "pull_request", unsupported, None),
        ("issue_triage", "issues", {"action": "opened"},
         dict(kind="issues", prompt="Classify the reported inventory fault and propose a reproduction.")),
        ("scheduled_task", "schedule", {},
         dict(kind="schedule", prompt="List unresolved inventory TODOs and summarize them in the log.")),
        ("manual_dispatch", "workflow_dispatch", {},
         dict(kind="workflow_dispatch", prompt="Explain what the inventory check does.")),
    ]
    cases = []
    for name, event, inputs, expected in examples:
        actual = plan(event, inputs)
        assert actual == expected, (name, actual)
        cases.append(dict(name=name, inputs={"event": event, "payload": inputs}, expected=expected, actual=actual,
                          operation="读取独立事件数据并构造本站任务计划"))
    actual = isolated_branch(plan("issue_comment", fix))
    expected = dict(branch="review/issue-37", changed=["inventory.txt"], original="reserve twice", fixed="reserve once", remotes=[])
    assert actual == expected, actual
    cases.append(dict(name="git_branch", inputs={"branch": "main", "issue": 37, "file": "inventory.txt"},
                      expected=expected, actual=actual,
                      operation="用真实 Git 在临时仓库创建分支、提交及核对合并基点差异"))
    return dict(cases=cases, python_version=sys.version.split()[0], git_version=git(Path.cwd(),"--version"))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--event")
    parser.add_argument("--payload", type=Path)
    opts = parser.parse_args()
    if opts.event or opts.payload:
        if not opts.event or not opts.payload:
            parser.error("--event and --payload must be supplied together")
        payload = json.loads(opts.payload.read_bytes())
        route = plan(opts.event, payload)
        result = None if route is None else {"kind": route["kind"]}
    else:
        result = examples()
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
不同评论和自动事件产生不同任务类别,越界触发不生成任务。本地修复分支只改 inventory.txt,main 仍保留原行为。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

运行事件练习

解压后运行 python github_event.py。另附只读流程示例,用于读取事件 JSON 并输出任务类别。

下载本章实验包 (mbskycom202612a244.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:OpenCode

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a244.zip

下载课程关联工程包:OpenCode

课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a236.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

主讨论需要从 issue.pull_request 辨别 PR;行评论有单独的路径与差异上下文。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习