@openhands/extensions 0.20.0 → 0.21.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.
Files changed (59) hide show
  1. package/.github/workflows/check-extensions.yml +4 -0
  2. package/.github/workflows/pr-artifacts.yml +294 -0
  3. package/.github/workflows/pr-description-check.yml +4 -2
  4. package/.release-please-manifest.json +1 -1
  5. package/AGENTS.md +27 -3
  6. package/README.md +5 -2
  7. package/automations/bundle-index.js +13 -3
  8. package/automations/catalog/github-agents-md-maintainer/manifest.json +2 -1
  9. package/automations/catalog/github-issue-to-pr/manifest.json +2 -1
  10. package/automations/catalog/github-issue-triage/manifest.json +72 -0
  11. package/automations/catalog/github-pr-reviewer/manifest.json +2 -1
  12. package/automations/catalog/gitlab-issue-to-mr/manifest.json +124 -0
  13. package/automations/catalog-index.js +15 -11
  14. package/integrations/catalog/reportportal.json +76 -0
  15. package/integrations/catalog-index.js +6 -4
  16. package/marketplaces/openhands-extensions.json +36 -0
  17. package/package.json +1 -1
  18. package/pyproject.toml +2 -2
  19. package/python/openhands_extensions/_version.py +1 -1
  20. package/skills/github/scripts/github_client.py +204 -0
  21. package/skills/github-agents-md-maintainer/SKILL.md +7 -1
  22. package/skills/github-agents-md-maintainer/scripts/main.py +4 -40
  23. package/skills/github-issue-to-pr/SKILL.md +8 -1
  24. package/skills/github-issue-to-pr/scripts/main.py +3 -40
  25. package/skills/github-issue-triage/.plugin/plugin.json +9 -0
  26. package/skills/github-issue-triage/README.md +9 -0
  27. package/skills/github-issue-triage/SKILL.md +37 -0
  28. package/skills/github-issue-triage/commands/github-issue-triage.md +8 -0
  29. package/skills/github-issue-triage/scripts/worker.py +123 -0
  30. package/skills/github-pr-reviewer/SKILL.md +8 -1
  31. package/skills/github-pr-reviewer/scripts/main.py +3 -41
  32. package/skills/github-repo-monitor/SKILL.md +7 -1
  33. package/skills/github-repo-monitor/scripts/main.py +4 -46
  34. package/skills/gitlab-issue-to-mr/.plugin/plugin.json +19 -0
  35. package/skills/gitlab-issue-to-mr/README.md +92 -0
  36. package/skills/gitlab-issue-to-mr/SKILL.md +408 -0
  37. package/skills/gitlab-issue-to-mr/commands/issue-to-mr-setup.md +8 -0
  38. package/skills/gitlab-issue-to-mr/references/state-schema.md +140 -0
  39. package/skills/gitlab-issue-to-mr/scripts/main.py +1448 -0
  40. package/skills/index.js +43 -6
  41. package/skills/openhands-automation/README.md +1 -1
  42. package/skills/openhands-automation/SKILL.md +18 -8
  43. package/skills/openhands-enterprise-troubleshooting/.plugin/plugin.json +20 -0
  44. package/skills/openhands-enterprise-troubleshooting/README.md +79 -0
  45. package/skills/openhands-enterprise-troubleshooting/SKILL.md +339 -0
  46. package/skills/openhands-enterprise-troubleshooting/references/diagnostics.md +698 -0
  47. package/skills/openhands-enterprise-troubleshooting/references/support-bundle-analysis.md +570 -0
  48. package/skills/openhands-enterprise-troubleshooting/scripts/bundle_triage.py +532 -0
  49. package/skills/openhands-sdk/SKILL.md +2 -0
  50. package/tests/github_automation_helpers.py +25 -0
  51. package/tests/test_github_automation_foundation.py +73 -0
  52. package/tests/test_github_skill_installation.py +63 -0
  53. package/tests/test_github_triage_delivery.py +53 -0
  54. package/tests/test_gitlab_issue_to_mr.py +823 -0
  55. package/.pr/custom-automation-event-trigger.png +0 -0
  56. package/.pr/custom-automation-plugin-fields.png +0 -0
  57. package/.pr/custom-automation-prompt-review.png +0 -0
  58. package/.pr/custom-automation-prompt-scheduled.png +0 -0
  59. package/.pr/custom-automation-upload-fields.png +0 -0
@@ -88,7 +88,8 @@
88
88
  "entrypoint": "python3 main.py",
89
89
  "timeout": 900,
90
90
  "files": {
91
- "main.py": "skills/github-agents-md-maintainer/scripts/main.py"
91
+ "main.py": "skills/github-agents-md-maintainer/scripts/main.py",
92
+ "github_client.py": "skills/github/scripts/github_client.py"
92
93
  },
93
94
  "config": {
94
95
  "repos": "{{form.repositories}}",
@@ -98,7 +98,8 @@
98
98
  "entrypoint": "python3 main.py",
99
99
  "timeout": 900,
100
100
  "files": {
101
- "main.py": "skills/github-issue-to-pr/scripts/main.py"
101
+ "main.py": "skills/github-issue-to-pr/scripts/main.py",
102
+ "github_client.py": "skills/github/scripts/github_client.py"
102
103
  },
103
104
  "config": {
104
105
  "repos": "{{form.repositories}}",
@@ -0,0 +1,72 @@
1
+ {
2
+ "id": "github-issue-triage",
3
+ "version": "1.0.0",
4
+ "name": "GitHub issue triage",
5
+ "category": "Project management",
6
+ "description": "Prioritize open issues and establish acceptance criteria before marking them ready for development.",
7
+ "requires": {
8
+ "integrations": {},
9
+ "features": [
10
+ "customTarball",
11
+ "agentProfiles"
12
+ ]
13
+ },
14
+ "estimatedSetupMinutes": 3,
15
+ "exampleImplementation": "Select an agent profile with Issues: read and write. Run this workflow independently on a schedule.",
16
+ "setup": {
17
+ "version": "1.0",
18
+ "mode": "direct",
19
+ "form": {
20
+ "triggers": {
21
+ "cron": {
22
+ "schedule": {
23
+ "type": "cron",
24
+ "label": "Check frequency",
25
+ "help": "How often to check repository progress.",
26
+ "default": "*/5 * * * *",
27
+ "required": true
28
+ },
29
+ "timezone": {
30
+ "type": "timezone",
31
+ "label": "Timezone",
32
+ "help": "Timezone for the schedule.",
33
+ "default": "UTC",
34
+ "required": true
35
+ }
36
+ }
37
+ },
38
+ "args": {
39
+ "repositories": {
40
+ "type": "repo-picker",
41
+ "provider": "github",
42
+ "multiple": true,
43
+ "label": "Repositories",
44
+ "help": "Repositories this automation may work on.",
45
+ "required": true
46
+ },
47
+ "githubTokenSecret": {
48
+ "type": "text",
49
+ "label": "GitHub token secret",
50
+ "help": "Name of a saved secret allowed by the selected agent profile. Enter its name, not its value.",
51
+ "default": "GITHUB_PERSONAL_ACCESS_TOKEN",
52
+ "required": true
53
+ }
54
+ }
55
+ },
56
+ "bundle": {
57
+ "version": "1.0.0",
58
+ "entrypoint": "python3 worker.py",
59
+ "timeout": 3000,
60
+ "files": {
61
+ "worker.py": "skills/github-issue-triage/scripts/worker.py",
62
+ "github_client.py": "skills/github/scripts/github_client.py"
63
+ },
64
+ "config": {
65
+ "repos": "{{form.repositories}}",
66
+ "github_token_secret": "{{form.githubTokenSecret}}"
67
+ }
68
+ },
69
+ "message": "Select an agent profile and configure this scheduled automation in the conversation."
70
+ },
71
+ "popularityRank": 80
72
+ }
@@ -92,7 +92,8 @@
92
92
  "entrypoint": "python3 main.py",
93
93
  "timeout": 600,
94
94
  "files": {
95
- "main.py": "skills/github-pr-reviewer/scripts/main.py"
95
+ "main.py": "skills/github-pr-reviewer/scripts/main.py",
96
+ "github_client.py": "skills/github/scripts/github_client.py"
96
97
  },
97
98
  "config": {
98
99
  "repos": "{{form.repositories}}",
@@ -0,0 +1,124 @@
1
+ {
2
+ "id": "gitlab-issue-to-mr",
3
+ "name": "GitLab issue to MR",
4
+ "category": "Software development",
5
+ "description": "Watch for a configurable label on GitLab issues, implement the issue in a clone of the default branch, and open a merge request for each label event.",
6
+ "requires": {
7
+ "integrations": {
8
+ "gitlab": {
9
+ "message": "Used to read labelled issues, push the branch, and open the merge request."
10
+ }
11
+ },
12
+ "features": [
13
+ "customTarball"
14
+ ]
15
+ },
16
+ "popularityRank": 88,
17
+ "estimatedSetupMinutes": 4,
18
+ "exampleImplementation": "Trigger: cron polling for open GitLab issues with a configured label such as openhands\nRequired secret: GITLAB_TOKEN, a personal or project access token with the api scope and at least the Developer role\n\n1. Read the projects, trigger label, branch prefix, merge request mode, GitLab API URL, and polling schedule from setup.\n2. Poll each project independently, with its own state, so issue IIDs never collide.\n3. List open labelled issues and find the latest matching GitLab label resource event for each.\n4. Deduplicate on the label event ID so every label application queues exactly one attempt.\n5. Clone the default branch into a directory of its own, create the working branch, and start an OpenHands conversation with that directory as its workspace. The clone carries no credential and the agent is handed no secrets, because the prompt is built from an issue body that anyone can write.\n6. Comment on the issue with the branch and the conversation link.\n7. Once the conversation has stopped, commit whatever the agent left, push the branch, open a merge request titled after the issue and prefixed with Draft:, and comment the link on the issue. An agent that made no changes gets its answer posted instead.\n8. Remove the clone once the conversation has stopped, so nothing accumulates between runs.",
19
+ "impact": {
20
+ "basis": "completed-runs",
21
+ "one": "1 issue sweep completed",
22
+ "other": "{{count}} issue sweeps completed"
23
+ },
24
+ "setup": {
25
+ "version": "1.0",
26
+ "mode": "direct",
27
+ "form": {
28
+ "triggers": {
29
+ "cron": {
30
+ "schedule": {
31
+ "type": "cron",
32
+ "label": "Check frequency",
33
+ "help": "How often to look for newly labelled issues.",
34
+ "default": "*/15 * * * *",
35
+ "required": true
36
+ },
37
+ "timezone": {
38
+ "type": "timezone",
39
+ "label": "Timezone",
40
+ "help": "Timezone the schedule is interpreted in.",
41
+ "default": "UTC",
42
+ "required": true
43
+ }
44
+ }
45
+ },
46
+ "args": {
47
+ "projects": {
48
+ "type": "repo-picker",
49
+ "label": "Projects",
50
+ "help": "The GitLab projects whose labelled issues are implemented. Each is polled independently and keeps its own state, so issue numbers never collide between them.",
51
+ "provider": "gitlab",
52
+ "multiple": true,
53
+ "required": true
54
+ },
55
+ "triggerLabel": {
56
+ "type": "text",
57
+ "label": "Trigger label",
58
+ "help": "Only issues carrying this label are worked on.",
59
+ "default": "openhands",
60
+ "required": true,
61
+ "constraints": {
62
+ "minLength": 1,
63
+ "maxLength": 50
64
+ }
65
+ },
66
+ "branchPrefix": {
67
+ "type": "text",
68
+ "label": "Branch prefix",
69
+ "help": "Branches are named after this prefix and the issue number, such as openhands/issue-42.",
70
+ "default": "openhands/issue",
71
+ "required": true,
72
+ "constraints": {
73
+ "minLength": 1,
74
+ "maxLength": 50
75
+ }
76
+ },
77
+ "mergeRequestMode": {
78
+ "type": "select",
79
+ "label": "Merge request mode",
80
+ "help": "Whether the merge request is opened as a draft or ready for review. GitLab marks a draft by prefixing its title with Draft:.",
81
+ "default": "draft",
82
+ "required": true,
83
+ "options": [
84
+ {
85
+ "value": "draft",
86
+ "label": "Draft"
87
+ },
88
+ {
89
+ "value": "ready",
90
+ "label": "Ready for review"
91
+ }
92
+ ]
93
+ },
94
+ "gitlabApiUrl": {
95
+ "type": "text",
96
+ "label": "GitLab API URL",
97
+ "help": "The API root of the GitLab instance. Change it for a self-managed instance, such as https://gitlab.example.com/api/v4.",
98
+ "default": "https://gitlab.com/api/v4",
99
+ "required": true,
100
+ "constraints": {
101
+ "minLength": 1,
102
+ "maxLength": 200
103
+ }
104
+ }
105
+ }
106
+ },
107
+ "bundle": {
108
+ "version": "1.0.0",
109
+ "entrypoint": "python3 main.py",
110
+ "timeout": 900,
111
+ "files": {
112
+ "main.py": "skills/gitlab-issue-to-mr/scripts/main.py"
113
+ },
114
+ "config": {
115
+ "projects": "{{form.projects}}",
116
+ "trigger_label": "{{form.triggerLabel}}",
117
+ "branch_prefix": "{{form.branchPrefix}}",
118
+ "merge_request_mode": "{{form.mergeRequestMode}}",
119
+ "gitlab_api_url": "{{form.gitlabApiUrl}}"
120
+ }
121
+ },
122
+ "message": "This deployment cannot run the scheduled issue-to-MR automation directly. Set it up in this conversation instead: confirm the GitLab projects to watch, the trigger label, the branch prefix, whether merge requests open as drafts, the GitLab API URL, and the polling schedule, then create the automation."
123
+ }
124
+ }
@@ -10,17 +10,19 @@ import entry4 from "./catalog/slack-standup-digest/manifest.json" with { type: "
10
10
  import entry5 from "./catalog/slack-channel-monitor/manifest.json" with { type: "json" };
11
11
  import entry6 from "./catalog/linear-triage-assistant/manifest.json" with { type: "json" };
12
12
  import entry7 from "./catalog/linear-issue-to-github-pr/manifest.json" with { type: "json" };
13
- import entry8 from "./catalog/linear-issue-to-gitlab-mr/manifest.json" with { type: "json" };
14
- import entry9 from "./catalog/linear-issue-to-bitbucket-pr/manifest.json" with { type: "json" };
15
- import entry10 from "./catalog/jira-issue-to-pr/manifest.json" with { type: "json" };
16
- import entry11 from "./catalog/qa-changes/manifest.json" with { type: "json" };
17
- import entry12 from "./catalog/jira-issue-to-gitlab-mr/manifest.json" with { type: "json" };
18
- import entry13 from "./catalog/research-brief-writer/manifest.json" with { type: "json" };
19
- import entry14 from "./catalog/jira-issue-to-bitbucket-pr/manifest.json" with { type: "json" };
20
- import entry15 from "./catalog/github-agents-md-maintainer/manifest.json" with { type: "json" };
21
- import entry16 from "./catalog/upstream-fork-sync/manifest.json" with { type: "json" };
22
- import entry17 from "./catalog/incident-retrospective-drafter/manifest.json" with { type: "json" };
23
- import entry18 from "./catalog/news-digest/manifest.json" with { type: "json" };
13
+ import entry8 from "./catalog/gitlab-issue-to-mr/manifest.json" with { type: "json" };
14
+ import entry9 from "./catalog/linear-issue-to-gitlab-mr/manifest.json" with { type: "json" };
15
+ import entry10 from "./catalog/linear-issue-to-bitbucket-pr/manifest.json" with { type: "json" };
16
+ import entry11 from "./catalog/jira-issue-to-pr/manifest.json" with { type: "json" };
17
+ import entry12 from "./catalog/qa-changes/manifest.json" with { type: "json" };
18
+ import entry13 from "./catalog/jira-issue-to-gitlab-mr/manifest.json" with { type: "json" };
19
+ import entry14 from "./catalog/research-brief-writer/manifest.json" with { type: "json" };
20
+ import entry15 from "./catalog/jira-issue-to-bitbucket-pr/manifest.json" with { type: "json" };
21
+ import entry16 from "./catalog/github-agents-md-maintainer/manifest.json" with { type: "json" };
22
+ import entry17 from "./catalog/github-issue-triage/manifest.json" with { type: "json" };
23
+ import entry18 from "./catalog/upstream-fork-sync/manifest.json" with { type: "json" };
24
+ import entry19 from "./catalog/incident-retrospective-drafter/manifest.json" with { type: "json" };
25
+ import entry20 from "./catalog/news-digest/manifest.json" with { type: "json" };
24
26
 
25
27
  export const AUTOMATION_CATALOG_ENTRIES = [
26
28
  entry0,
@@ -42,4 +44,6 @@ export const AUTOMATION_CATALOG_ENTRIES = [
42
44
  entry16,
43
45
  entry17,
44
46
  entry18,
47
+ entry19,
48
+ entry20,
45
49
  ];
@@ -0,0 +1,76 @@
1
+ {
2
+ "id": "reportportal",
3
+ "name": "ReportPortal",
4
+ "description": "Query test launches, test items, history, and analysis from your ReportPortal test automation dashboard.",
5
+ "categories": [
6
+ "Engineering",
7
+ "Analytics"
8
+ ],
9
+ "appUrl": "https://reportportal.io",
10
+ "docsUrl": "https://reportportal.io/docs/external-integrations/MCPServer/",
11
+ "notes": "Uses ReportPortal's official MCP Server, run locally as a Docker container in the default stdio mode. ReportPortal is self-hosted, so there is no public MCP endpoint; the container connects to your own instance. Provide your ReportPortal host URL and an API token from your ReportPortal Profile page.",
12
+ "installHint": "RP_HOST (the URL of your ReportPortal instance) and RP_API_TOKEN (from your ReportPortal Profile page) are required. RP_PROJECT (a default project name) is optional. Requires a container runtime such as Docker.",
13
+ "connectionOptions": [
14
+ {
15
+ "id": "api",
16
+ "provider": "mcp",
17
+ "transport": {
18
+ "kind": "stdio",
19
+ "serverName": "reportportal",
20
+ "command": "docker",
21
+ "args": [
22
+ "run",
23
+ "--init",
24
+ "--pull=always",
25
+ "-i",
26
+ "--rm",
27
+ "-e",
28
+ "RP_API_TOKEN",
29
+ "-e",
30
+ "RP_HOST",
31
+ "-e",
32
+ "RP_PROJECT",
33
+ "reportportal/mcp-server"
34
+ ],
35
+ "envFields": [
36
+ {
37
+ "key": "RP_API_TOKEN",
38
+ "label": "ReportPortal API token",
39
+ "type": "password",
40
+ "required": true,
41
+ "helperText": "API token generated on your ReportPortal Profile page.",
42
+ "helperLink": "https://reportportal.io/docs/external-integrations/MCPServer/"
43
+ },
44
+ {
45
+ "key": "RP_HOST",
46
+ "label": "ReportPortal host URL",
47
+ "type": "text",
48
+ "required": true,
49
+ "placeholder": "https://your-reportportal-instance.com",
50
+ "helperText": "The base URL of your ReportPortal instance."
51
+ },
52
+ {
53
+ "key": "RP_PROJECT",
54
+ "label": "Default project name",
55
+ "type": "text",
56
+ "required": false,
57
+ "placeholder": "my-project",
58
+ "helperText": "Optional default ReportPortal project name to use for requests."
59
+ }
60
+ ]
61
+ },
62
+ "auth": {
63
+ "strategy": "api_key"
64
+ }
65
+ }
66
+ ],
67
+ "iconBg": "#00B4D5",
68
+ "keywords": [
69
+ "test reporting",
70
+ "test automation",
71
+ "qa",
72
+ "launches",
73
+ "test analytics",
74
+ "quality gate"
75
+ ]
76
+ }
@@ -75,10 +75,11 @@ import entry69 from "./catalog/obsidian.json" with { type: "json" };
75
75
  import entry70 from "./catalog/paypal.json" with { type: "json" };
76
76
  import entry71 from "./catalog/playwright.json" with { type: "json" };
77
77
  import entry72 from "./catalog/redis.json" with { type: "json" };
78
- import entry73 from "./catalog/resend.json" with { type: "json" };
79
- import entry74 from "./catalog/sequential-thinking.json" with { type: "json" };
80
- import entry75 from "./catalog/superhuman-mail.json" with { type: "json" };
81
- import entry76 from "./catalog/time.json" with { type: "json" };
78
+ import entry73 from "./catalog/reportportal.json" with { type: "json" };
79
+ import entry74 from "./catalog/resend.json" with { type: "json" };
80
+ import entry75 from "./catalog/sequential-thinking.json" with { type: "json" };
81
+ import entry76 from "./catalog/superhuman-mail.json" with { type: "json" };
82
+ import entry77 from "./catalog/time.json" with { type: "json" };
82
83
 
83
84
  export const INTEGRATION_CATALOG_ENTRIES = [
84
85
  entry0,
@@ -158,4 +159,5 @@ export const INTEGRATION_CATALOG_ENTRIES = [
158
159
  entry74,
159
160
  entry75,
160
161
  entry76,
162
+ entry77,
161
163
  ];
@@ -721,6 +721,19 @@
721
721
  "integration"
722
722
  ]
723
723
  },
724
+ {
725
+ "name": "gitlab-issue-to-mr",
726
+ "source": "./skills/gitlab-issue-to-mr",
727
+ "description": "Create an automation that implements GitLab issues when a configurable trigger label is applied. Clones the default branch for the agent, then commits, pushes, and opens the merge request itself - the agent is handed no push credential.",
728
+ "category": "automations",
729
+ "keywords": [
730
+ "gitlab",
731
+ "issue",
732
+ "merge-request",
733
+ "automation",
734
+ "integration"
735
+ ]
736
+ },
724
737
  {
725
738
  "name": "incident-retrospective",
726
739
  "source": "./skills/incident-retrospective",
@@ -834,6 +847,29 @@
834
847
  "pull-request",
835
848
  "automation"
836
849
  ]
850
+ },
851
+ {
852
+ "name": "openhands-enterprise-troubleshooting",
853
+ "source": "./skills/openhands-enterprise-troubleshooting",
854
+ "description": "Diagnose and resolve common issues on OpenHands Enterprise self-hosted installations. Covers sandbox startup failures, auth issues, certificate errors, LLM connectivity, Keycloak login, Replicated Admin Console access, upgrade failures, and resource exhaustion. Includes support bundle generation, offline bundle analysis with a bundled triage script, and escalation handoffs.",
855
+ "category": "integrations",
856
+ "keywords": [
857
+ "openhands",
858
+ "enterprise",
859
+ "troubleshooting",
860
+ "debugging",
861
+ "replicated",
862
+ "support",
863
+ "diagnostics",
864
+ "support-bundle",
865
+ "kubernetes"
866
+ ]
867
+ },
868
+ {
869
+ "name": "github-issue-triage",
870
+ "source": "./skills/github-issue-triage",
871
+ "description": "Prioritize open issues and establish acceptance criteria before marking them ready for development.",
872
+ "category": "automations"
837
873
  }
838
874
  ]
839
875
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openhands/extensions",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "Public OpenHands extension catalogs for skills, plugins, integrations, and automation templates.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "openhands-extensions"
3
- version = "0.20.0"
3
+ version = "0.21.0"
4
4
  description = "OpenHands extensions, plugins, and skills (Python bindings for the integration catalog)"
5
5
  requires-python = ">=3.12"
6
6
  dependencies = [
@@ -28,5 +28,5 @@ test = [
28
28
  ]
29
29
 
30
30
  [tool.pytest.ini_options]
31
- pythonpath = ["python"]
31
+ pythonpath = ["python", "skills/github/scripts"]
32
32
  testpaths = ["tests"]
@@ -18,7 +18,7 @@ from importlib.metadata import PackageNotFoundError, version
18
18
  #: Kept in lock-step with pyproject.toml/package.json by the version test.
19
19
  #: release-please only rewrites a semver found on the annotated line itself, so
20
20
  #: the annotation must stay on the assignment; on its own line it is a no-op.
21
- _FALLBACK_VERSION = "0.20.0" # x-release-please-version
21
+ _FALLBACK_VERSION = "0.21.0" # x-release-please-version
22
22
 
23
23
  try:
24
24
  __version__: str = version("openhands-extensions")
@@ -0,0 +1,204 @@
1
+ """Shared GitHub transport and repository operations for GitHub automations."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import re
7
+ import subprocess
8
+ from functools import cached_property
9
+ from pathlib import Path
10
+ from urllib.error import HTTPError
11
+ from urllib.parse import parse_qsl, urlencode, urlsplit
12
+ from urllib.request import Request, urlopen
13
+
14
+
15
+ def github_request(
16
+ token: str,
17
+ method: str,
18
+ path: str,
19
+ params: dict | None = None,
20
+ body: dict | None = None,
21
+ accept: str = "application/vnd.github+json",
22
+ ) -> tuple:
23
+ url = f"https://api.github.com{path}"
24
+ if params:
25
+ url = f"{url}?{urlencode(params)}"
26
+ headers = {
27
+ "Authorization": f"Bearer {token}",
28
+ "Accept": accept,
29
+ "X-GitHub-Api-Version": "2022-11-28",
30
+ "Content-Type": "application/json",
31
+ }
32
+ data = json.dumps(body).encode() if body is not None else None
33
+ req = Request(url, data=data, headers=headers, method=method)
34
+ with urlopen(req, timeout=90) as r:
35
+ raw = r.read()
36
+ return (json.loads(raw) if raw.strip() else {}), dict(r.headers)
37
+
38
+
39
+ def github_paginate(token: str, path: str, params: dict | None = None) -> list:
40
+ results = []
41
+ base_params = dict(params or {})
42
+ base_params.setdefault("per_page", 100)
43
+ for page in range(1, 101):
44
+ base_params["page"] = page
45
+ data, _ = github_request(token, "GET", path, params=base_params)
46
+ if not isinstance(data, list):
47
+ raise TypeError("Expected a paginated GitHub list")
48
+ results.extend(data)
49
+ if len(data) < int(base_params["per_page"]):
50
+ return results
51
+ raise RuntimeError("GitHub pagination exceeded limit")
52
+
53
+
54
+ class GitHubRepository:
55
+ name = "GitHub automation"
56
+
57
+ def __init__(
58
+ self,
59
+ config_path=Path("config.json"),
60
+ *,
61
+ github_token_secret,
62
+ repository=None,
63
+ conversation=None,
64
+ ):
65
+ self.config = json.loads(Path(config_path).read_text())
66
+ self.repository = repository or self.config["repository"]
67
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", self.repository):
68
+ raise ValueError("repository must be owner/repo")
69
+ if not re.fullmatch(r"[A-Z_][A-Z0-9_]*", github_token_secret):
70
+ raise ValueError(
71
+ "Expected the environment variable containing the GitHub token"
72
+ )
73
+ self.token_name = github_token_secret
74
+ self.token = os.environ[github_token_secret]
75
+ if not self.token:
76
+ raise ValueError("The GitHub credential is empty")
77
+ self.conversation = conversation
78
+ self.conversation_id = str(conversation.id) if conversation else None
79
+ self.workspace = Path(os.environ["WORKSPACE_BASE"])
80
+ self.project = self.workspace
81
+ self.evidence = self.workspace / "evidence"
82
+ self.evidence.mkdir(exist_ok=True)
83
+ self._completed_dependencies = {}
84
+
85
+ @cached_property
86
+ def base_branch(self):
87
+ return self.config.get("base_branch") or self.gh("GET", "")["default_branch"]
88
+
89
+ @property
90
+ def github_instructions(self):
91
+ return (
92
+ f"Use `GH_TOKEN=${self.token_name} gh api` for GitHub requests. "
93
+ "Never print the credential value. "
94
+ f"Only {self.repository} is in scope. Work in {self.project}. "
95
+ "Do not modify the automation bundle or its configuration."
96
+ )
97
+
98
+ def gh(self, method, path, body=None):
99
+ return github_request(
100
+ self.token, method, f"/repos/{self.repository}" + path, body=body
101
+ )[0]
102
+
103
+ def shell(self, args, cwd=None, timeout=300):
104
+ result = subprocess.run(
105
+ args,
106
+ cwd=cwd or self.project,
107
+ text=True,
108
+ stdout=subprocess.PIPE,
109
+ stderr=subprocess.STDOUT,
110
+ timeout=timeout,
111
+ check=False,
112
+ )
113
+ if result.returncode:
114
+ raise RuntimeError(
115
+ f"{args[0]} failed: {result.stdout[-4000:].replace(self.token, '[REDACTED]')}"
116
+ )
117
+ return result.stdout.strip()
118
+
119
+ def comment(self, number, text):
120
+ return self.gh(
121
+ "POST",
122
+ f"/issues/{number}/comments",
123
+ {
124
+ "body": text
125
+ + f"\n\nFactory role: `{self.name}`; conversation: `{self.conversation_id}`."
126
+ + "\n\n_This comment was posted by an AI agent (OpenHands)._"
127
+ },
128
+ )
129
+
130
+ def open_issues(self):
131
+ return [
132
+ i for i in self.gh_pages("/issues?state=open") if "pull_request" not in i
133
+ ]
134
+
135
+ def statuses(self, sha):
136
+ result = {}
137
+ for item in self.gh_pages(f"/commits/{sha}/statuses"):
138
+ result.setdefault(item["context"], item["state"])
139
+ return result
140
+
141
+ def completed_dependency(self, number):
142
+ if number in self._completed_dependencies:
143
+ return self._completed_dependencies[number]
144
+ try:
145
+ dependency = self.gh("GET", f"/issues/{number}")
146
+ except HTTPError as exc:
147
+ if exc.code == 404:
148
+ return False
149
+ raise
150
+ completed = (
151
+ dependency["state"] == "closed"
152
+ and dependency.get("state_reason") == "completed"
153
+ )
154
+ self._completed_dependencies[number] = completed
155
+ return completed
156
+
157
+ def dependencies_complete(self, issue):
158
+ """Honor explicit Depends on lines; unknown/incomplete issues remain blocked."""
159
+ for line in re.findall(
160
+ "^Depends on:\\s*(.+)$",
161
+ issue.get("body") or "",
162
+ re.MULTILINE | re.IGNORECASE,
163
+ ):
164
+ for number in re.findall("#(\\d+)", line):
165
+ if not self.completed_dependency(number):
166
+ return False
167
+ return True
168
+
169
+ def gh_pages(self, endpoint):
170
+ split = urlsplit(endpoint)
171
+ return github_paginate(
172
+ self.token,
173
+ f"/repos/{self.repository}" + split.path,
174
+ params=dict(parse_qsl(split.query)),
175
+ )
176
+
177
+
178
+ def run_repositories(automation_type, conversation=None):
179
+ parser = argparse.ArgumentParser(description=automation_type.__doc__)
180
+ parser.add_argument("--github-token-secret")
181
+ args = parser.parse_args()
182
+ config = json.loads(Path("config.json").read_text())
183
+ token_name = args.github_token_secret or config.get(
184
+ "github_token_secret", "GITHUB_PERSONAL_ACCESS_TOKEN"
185
+ )
186
+ repositories = config.get("repos") or [config["repository"]]
187
+ failures = []
188
+ for repository in repositories:
189
+ automation = automation_type(
190
+ github_token_secret=token_name,
191
+ repository=repository,
192
+ conversation=conversation,
193
+ )
194
+ try:
195
+ automation.run()
196
+ except Exception as exc: # noqa: BLE001 - one repository must not block others
197
+ failures.append(repository)
198
+ print(
199
+ json.dumps({"repository": repository, "error": type(exc).__name__}),
200
+ flush=True,
201
+ )
202
+ if failures:
203
+ raise RuntimeError("Automation failed for: " + ", ".join(failures))
204
+ return str(conversation.id) if conversation else None