Docs Packages
@procedures/gh
npm install @procedures/gh
The GitHub CLI (gh) as procedures: pull requests, workflow runs, artifacts, releases, issues and the GitHub API. Each procedure runs gh through shell.run of @procedures/shell, with an argument list and no shell. The output is the JSON of gh --json.
gh must be on the PATH, with a login (gh auth login).
The procedures#
| Procedure | What it does | Effects |
|---|---|---|
gh.pr.list | The pull requests of a repository: state, author, base, head, search, limit | reads |
gh.pr.view | One pull request | reads |
gh.pr.checks | The checks of a pull request | reads |
gh.pr.create | Open a pull request | writes |
gh.run.list | The workflow runs: workflow, branch, status, limit | reads |
gh.run.view | One workflow run with its jobs | reads |
gh.run.rerun | Run a workflow run again, or only its failed jobs | writes |
gh.run.download | Download the artifacts of a run: names, patterns, folder | writes fs |
gh.workflow.run | Start a workflow run: workflow, ref, inputs | writes |
gh.release.list | The releases of a repository | reads |
gh.release.view | The release of a tag, or the latest release | reads |
gh.issue.list | The issues: state, label, author, search, limit | reads |
gh.issue.view | One issue, with its comments | reads |
gh.issue.create | Open an issue | writes |
gh.issue.comment | Add a comment to an issue or a pull request | writes |
gh.api | Send a request to the GitHub API: endpoint, method, fields, body, paginate | writes, destructive |
- A read declares
reads: ["network"]and changes nothing. A write declareswrites: ["network"]. It makes something new, so it is not destructive, and a second call makes a second one. - Each procedure takes
repo(owner/name),cwdandtimeoutMs. Withoutrepo,ghuses the repository of the folder. - A value that
ghreads as an argument (a number, a branch, a label) must not start with-. A title or a body is the value of its option, so it can start with-. - A failed command throws an error with the exit code and the text of
gh.gh.pr.checksreports a pending check as an error that tells you to ask again.
Workflow runs and artifacts#
gh.workflow.runsends each input as-f key=value. When GitHub gives the new run,ghprints its URL. Then the output hasurlandrun, the id of the run.- Without
runin the output, find the run withgh.run.list. Use theworkflowandbranchfilters. gh.run.downloadwrites the files of the artifacts intodir. It declareswrites: ["fs"].ghputs each artifact in a folder with its name. When the input selects one artifact, the files go directly intodir.ghdoes not replace a file that exists. The download then fails. Thus the procedure is not destructive.
The GitHub API#
gh.apialways sends--method. The default isGET. Without this option,ghchangesGETtoPOSTwhen the call has fields.- A string field goes as
-f, andghsends it as text. A number, a boolean ornullgoes as-F, andghconverts its type. GETsends the fields in the query. The other methods send them in the JSON body.bodyis a JSON value. The procedure writes it to a temporary file for--input, and removes the file after the call.gh apihas no--repooption. The procedure givesrepotoghasGH_REPO. Thenghreplaces{owner}and{repo}in the endpoint.- The output is
{ data }, the parsed JSON. An empty response (HTTP 204) givesnull. - With
paginate: true, the pages of an array become one array. The pages of an object become an array of the pages. - The method is an input, and
PUTorDELETEcan replace or remove data. Thusgh.apideclareswrites: ["network"]and keeps the default: destructive.
The REST client#
createRestClient is a client of the REST API for a program that sends many requests, for example a dispatcher of runners. It does not use gh, so a request starts no process.
import { createRestClient } from "@procedures/gh";
const github = createRestClient({ token: () => readToken() });
const answer = await github.request({ method: "GET", path: "/repos/owner/name/actions/runs", query: { status: "queued" } }, signal);
- The client sends each request with
httpRequestof@procedures/http, with its host policy and its limits of size and time. - The token is a text, or a function that gives it before each request. A token of a GitHub App changes each hour.
- Each status is an answer:
{ status, body, cached }. The client throws only when it gets no answer, or when a wait is too long. - A GET with a stored answer is a conditional request. For an answer 304, the client gives the stored answer with the status 200 and
cached: true. - GitHub does not count an answer 304 for the primary limit. The client keeps 1,000 answers. The option
cacheEntrieschanges the count. - A sliding window of
@mark1russell7/service/limiterholds the secondary limit: 900 points in each minute. - A GET costs 1 point. A POST, a PUT, a PATCH or a DELETE costs 5 points, and it waits one second after the write before it.
- After a refusal for the rate (429, or 403 with a sign of the rate), the client waits the time of
retry-afteror untilx-ratelimit-reset. - With no time in the headers, the wait is one minute. Each refusal in a sequence doubles it, to 16 minutes.
- A request whose wait is longer than
maxWaitMs(60 seconds) throws aRestRateErrorat once, and sends nothing. - The client refuses a path with a query, a segment
.or.., a backslash or a space. Thus a request stays on its endpoint. - No error text of the client has the token or the body of an answer.
state()gives the counts of the client: the requests, the answers 304, the refusals for the rate and the wait.
The billing reads#
The billing reads give the usage report of an account and the budgets of an organization. Each read has a request builder and an extractor, so a caller can send the request with its own client.
import { createRestClient, netAmountByProduct, readBillingUsage } from "@procedures/gh";
const github = createRestClient({ token: () => readToken() });
const items = await readBillingUsage(github, { kind: "organization", login: "lab" }, { year: 2026, month: 11 }, signal);
const cost = items === undefined ? undefined : netAmountByProduct(items).get("actions");
| Function | Request | Permission of a fine-grained token |
|---|---|---|
billingUsageRequest with the kind user | GET /users/{username}/settings/billing/usage | The user permission "Plan", read |
billingUsageRequest with the kind organization | GET /organizations/{org}/settings/billing/usage | The organization permission "Administration", read |
organizationBudgetsRequest | GET /organizations/{org}/settings/billing/budgets | The organization permission "Administration", read |
BILLING_PERMISSIONSgives the same permissions as data.- The period of a report is a year, a month of a year or a day of a month. The query has the numbers with no zero before them.
extractBillingUsagegives the items of a report: the product, the SKU, the date, the quantity and the amounts in USD.- An item also has its
repositoryand itsorganization, when GitHub names them. extractOrganizationBudgetsgives each budget: the scope, the entity, the product, the amount andstops.stopsis true when GitHub stops the paid use at the limit.- An extractor gives
undefinedfor an answer that it cannot read. A status that is not 200, a body of a different shape and a list with a next page are such answers. It does not give a part of a list. netAmountByProductadds the net amounts of each product.usageAmountsgives the sums of some items: the count, the cost before the discounts (gross), the discounts and the cost after them (net).usageAmountsBy(items, key)gives these sums for each group. The key of an item names its group, and an item with the keyundefinedis in no group.usageAmountsBy(items, (item) => item.repository)gives the cost of each repository.usageAmountsBy(items, usageDay)gives the cost of each day.- A sum is
undefinedwhen an item has no such amount. A sum of a part of the items is not a result. - A builder throws a
RangeErrorfor a text that is not a valid login of GitHub, or for a period that is not valid. Thus a request stays on its endpoint. - GitHub gives the usage report only to an account on the enhanced billing platform.
Use#
import { createRegistry, Client } from "@procedures/client";
import ghModule from "@procedures/gh/module";
const client = new Client(transport).useRegistry(createRegistry(ghModule));
const { items } = await client.exec(["gh", "run", "list"], { repo: "owner/name", status: "failure" });
mark gh run list --repo owner/name --status failure
const { run } = await client.exec(["gh", "workflow", "run"], { workflow: "ci.yml", ref: "main", inputs: { shards: "4" } });
const { data } = await client.exec(["gh", "api"], { endpoint: "repos/{owner}/{repo}/pulls", repo: "owner/name", paginate: true });
The root of the files#
Under the root of a host (mark --fs-root, procedure-server --fs-root, MCP_FS_ROOT), each gh procedure starts gh in a working folder of the root. The default cwd is the root. The dir of gh.run.download starts at cwd, and it must be in the root. GIT_DIR is the null device, so the git of gh finds no repository: give repo. gh reads its own login in the home folder.
Tests#
pnpm --filter @procedures/gh test runs the procedures with a fake shell. The tests examine each argument list, the JSON of gh, the failures and the values that cannot become options.
The tests of the REST client use a fake transport and a fake clock. They examine the headers, the stored answers, the window of points, the waits after a refusal and the checks of a path.