Docs Packages

@procedures/gh

packages/gh/README.md on GitHub · Package map · Procedures

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#

ProcedureWhat it doesEffects
gh.pr.listThe pull requests of a repository: state, author, base, head, search, limitreads
gh.pr.viewOne pull requestreads
gh.pr.checksThe checks of a pull requestreads
gh.pr.createOpen a pull requestwrites
gh.run.listThe workflow runs: workflow, branch, status, limitreads
gh.run.viewOne workflow run with its jobsreads
gh.run.rerunRun a workflow run again, or only its failed jobswrites
gh.run.downloadDownload the artifacts of a run: names, patterns, folderwrites fs
gh.workflow.runStart a workflow run: workflow, ref, inputswrites
gh.release.listThe releases of a repositoryreads
gh.release.viewThe release of a tag, or the latest releasereads
gh.issue.listThe issues: state, label, author, search, limitreads
gh.issue.viewOne issue, with its commentsreads
gh.issue.createOpen an issuewrites
gh.issue.commentAdd a comment to an issue or a pull requestwrites
gh.apiSend a request to the GitHub API: endpoint, method, fields, body, paginatewrites, destructive
  • A read declares reads: ["network"] and changes nothing. A write declares writes: ["network"]. It makes something new, so it is not destructive, and a second call makes a second one.
  • Each procedure takes repo (owner/name), cwd and timeoutMs. Without repo, gh uses the repository of the folder.
  • A value that gh reads 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.checks reports a pending check as an error that tells you to ask again.

Workflow runs and artifacts#

  • gh.workflow.run sends each input as -f key=value. When GitHub gives the new run, gh prints its URL. Then the output has url and run, the id of the run.
  • Without run in the output, find the run with gh.run.list. Use the workflow and branch filters.
  • gh.run.download writes the files of the artifacts into dir. It declares writes: ["fs"].
  • gh puts each artifact in a folder with its name. When the input selects one artifact, the files go directly into dir.
  • gh does not replace a file that exists. The download then fails. Thus the procedure is not destructive.

The GitHub API#

  • gh.api always sends --method. The default is GET. Without this option, gh changes GET to POST when the call has fields.
  • A string field goes as -f, and gh sends it as text. A number, a boolean or null goes as -F, and gh converts its type.
  • GET sends the fields in the query. The other methods send them in the JSON body.
  • body is a JSON value. The procedure writes it to a temporary file for --input, and removes the file after the call.
  • gh api has no --repo option. The procedure gives repo to gh as GH_REPO. Then gh replaces {owner} and {repo} in the endpoint.
  • The output is { data }, the parsed JSON. An empty response (HTTP 204) gives null.
  • 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 PUT or DELETE can replace or remove data. Thus gh.api declares writes: ["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 httpRequest of @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 cacheEntries changes the count.
  • A sliding window of @mark1russell7/service/limiter holds 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-after or until x-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 a RestRateError at 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");
FunctionRequestPermission of a fine-grained token
billingUsageRequest with the kind userGET /users/{username}/settings/billing/usageThe user permission "Plan", read
billingUsageRequest with the kind organizationGET /organizations/{org}/settings/billing/usageThe organization permission "Administration", read
organizationBudgetsRequestGET /organizations/{org}/settings/billing/budgetsThe organization permission "Administration", read
  • BILLING_PERMISSIONS gives 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.
  • extractBillingUsage gives the items of a report: the product, the SKU, the date, the quantity and the amounts in USD.
  • An item also has its repository and its organization, when GitHub names them.
  • extractOrganizationBudgets gives each budget: the scope, the entity, the product, the amount and stops. stops is true when GitHub stops the paid use at the limit.
  • An extractor gives undefined for 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.
  • netAmountByProduct adds the net amounts of each product.
  • usageAmounts gives 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 key undefined is 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 undefined when an item has no such amount. A sum of a part of the items is not a result.
  • A builder throws a RangeError for 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.