pr-shepherd 1.2.0 → 1.4.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.
- package/.claude-plugin/plugin.json +24 -2
- package/README.md +1 -0
- package/bin/api.mjs +4 -1
- package/bin/cli/api-usage-formatter.mjs +18 -8
- package/bin/cli-parser.mjs +5 -2
- package/bin/github/api-telemetry-adopt.d.mts +4 -0
- package/bin/github/api-telemetry-adopt.mjs +52 -0
- package/bin/github/api-telemetry-aggregate.d.mts +6 -2
- package/bin/github/api-telemetry-aggregate.mjs +19 -52
- package/bin/github/api-telemetry-summary.d.mts +4 -0
- package/bin/github/api-telemetry-summary.mjs +63 -0
- package/bin/github/api-telemetry.d.mts +2 -0
- package/bin/github/api-telemetry.mjs +2 -43
- package/bin/github/app-eligibility.d.mts +9 -0
- package/bin/github/app-eligibility.mjs +21 -0
- package/bin/github/app-quota.d.mts +10 -0
- package/bin/github/app-quota.mjs +44 -0
- package/bin/github/auth-target.d.mts +16 -0
- package/bin/github/auth-target.mjs +29 -0
- package/bin/github/client.mjs +4 -2
- package/bin/github/github-app-config.d.mts +12 -0
- package/bin/github/github-app-config.mjs +102 -0
- package/bin/github/github-app-token.d.mts +13 -0
- package/bin/github/github-app-token.mjs +107 -0
- package/bin/github/graphql-http.mjs +18 -2
- package/bin/github/http-auth.d.mts +15 -2
- package/bin/github/http-auth.mjs +35 -4
- package/bin/github/http-intermediate.d.mts +1 -0
- package/bin/github/http-intermediate.mjs +1 -0
- package/bin/github/rest-http.mjs +19 -2
- package/bin/github/rest-text.mjs +22 -3
- package/bin/pr-reference.mjs +3 -0
- package/bin/types/api-usage.d.mts +14 -0
- package/package.json +1 -1
- package/plugins/pr-shepherd/.claude-plugin/plugin.json +10 -2
- package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
- package/plugins/pr-shepherd/.codex.mcp.json +1 -1
- package/plugins/pr-shepherd/.mcp.json +1 -1
- package/plugins/pr-shepherd/hooks/hooks.json +16 -0
- package/plugins/pr-shepherd/hooks/poll-guard-detect.d.mts +11 -0
- package/plugins/pr-shepherd/hooks/poll-guard-detect.mjs +84 -0
- package/plugins/pr-shepherd/hooks/poll-guard.d.mts +15 -0
- package/plugins/pr-shepherd/hooks/poll-guard.mjs +76 -0
- package/plugins/pr-shepherd/package-lock.json +4 -4
- package/plugins/pr-shepherd/package.json +1 -1
- package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +6 -4
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
import { parse } from "yaml";
|
|
5
|
+
import { EXIT, ShepherdError } from "../exit-codes.mjs";
|
|
6
|
+
const APP_KEYS = ["app-id", "private-key-file", "repositories"];
|
|
7
|
+
const PATTERN = /^[A-Za-z0-9._-]+\/(\*|[A-Za-z0-9._-]+)$/;
|
|
8
|
+
let cached;
|
|
9
|
+
export function _resetGithubApps() {
|
|
10
|
+
cached = undefined;
|
|
11
|
+
}
|
|
12
|
+
/** User-level state directory. `PR_SHEPHERD_HOME` exists so tests never touch the real home. */
|
|
13
|
+
function shepherdHome() {
|
|
14
|
+
return process.env["PR_SHEPHERD_HOME"] || join(homedir(), ".pr-shepherd");
|
|
15
|
+
}
|
|
16
|
+
function githubAppsFile() {
|
|
17
|
+
return join(shepherdHome(), "github-apps.yml");
|
|
18
|
+
}
|
|
19
|
+
function fail(file, message) {
|
|
20
|
+
throw new ShepherdError(`${file}: ${message}`, EXIT.CONFIG);
|
|
21
|
+
}
|
|
22
|
+
function isRecord(value) {
|
|
23
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24
|
+
}
|
|
25
|
+
function rejectUnknownKeys(file, where, node, keys) {
|
|
26
|
+
for (const key of Object.keys(node)) {
|
|
27
|
+
if (!keys.includes(key))
|
|
28
|
+
fail(file, `unknown key "${key}" in ${where}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function keyPath(file, where, value) {
|
|
32
|
+
if (typeof value !== "string" || value === "") {
|
|
33
|
+
fail(file, `${where}.private-key-file must be a non-empty path`);
|
|
34
|
+
}
|
|
35
|
+
if (value.startsWith("~/"))
|
|
36
|
+
return join(homedir(), value.slice(2));
|
|
37
|
+
return isAbsolute(value) ? value : join(shepherdHome(), value);
|
|
38
|
+
}
|
|
39
|
+
function patterns(file, where, value) {
|
|
40
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
41
|
+
fail(file, `${where}.repositories must be a non-empty list`);
|
|
42
|
+
}
|
|
43
|
+
return value.map((entry) => {
|
|
44
|
+
if (typeof entry !== "string" || !PATTERN.test(entry)) {
|
|
45
|
+
fail(file, `${where}.repositories entry ${JSON.stringify(entry)} must be "owner/*" or "owner/repo"`);
|
|
46
|
+
}
|
|
47
|
+
return entry.toLowerCase();
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function parseApp(file, index, node) {
|
|
51
|
+
const where = `apps[${index}]`;
|
|
52
|
+
if (!isRecord(node))
|
|
53
|
+
fail(file, `${where} must be a mapping`);
|
|
54
|
+
rejectUnknownKeys(file, where, node, APP_KEYS);
|
|
55
|
+
const appId = node["app-id"];
|
|
56
|
+
if (typeof appId !== "number" || !Number.isSafeInteger(appId) || appId <= 0) {
|
|
57
|
+
fail(file, `${where}.app-id must be a positive integer`);
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
appId,
|
|
61
|
+
privateKeyFile: keyPath(file, where, node["private-key-file"]),
|
|
62
|
+
repositories: patterns(file, where, node["repositories"]),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function parseApps(file, text) {
|
|
66
|
+
let doc;
|
|
67
|
+
try {
|
|
68
|
+
doc = parse(text);
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
return fail(file, `invalid YAML: ${error instanceof Error ? error.message : String(error)}`);
|
|
72
|
+
}
|
|
73
|
+
if (!isRecord(doc))
|
|
74
|
+
fail(file, "must be a mapping with an `apps` list");
|
|
75
|
+
rejectUnknownKeys(file, "the file", doc, ["apps"]);
|
|
76
|
+
const apps = doc["apps"];
|
|
77
|
+
if (!Array.isArray(apps) || apps.length === 0)
|
|
78
|
+
fail(file, "`apps` must be a non-empty list");
|
|
79
|
+
return apps.map((node, index) => parseApp(file, index, node));
|
|
80
|
+
}
|
|
81
|
+
/** Read `github-apps.yml` once per process. A missing file turns the feature off. */
|
|
82
|
+
export function loadGithubApps() {
|
|
83
|
+
if (cached)
|
|
84
|
+
return cached;
|
|
85
|
+
const file = githubAppsFile();
|
|
86
|
+
let text;
|
|
87
|
+
try {
|
|
88
|
+
text = readFileSync(file, "utf8");
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (error.code === "ENOENT")
|
|
92
|
+
return (cached = []);
|
|
93
|
+
return fail(file, `cannot read: ${error instanceof Error ? error.message : String(error)}`);
|
|
94
|
+
}
|
|
95
|
+
return (cached = parseApps(file, text));
|
|
96
|
+
}
|
|
97
|
+
/** First listed app whose patterns match the repository. Matching ignores case. */
|
|
98
|
+
export function findGithubApp(owner, repo) {
|
|
99
|
+
const full = `${owner}/${repo}`.toLowerCase();
|
|
100
|
+
const wildcard = `${owner.toLowerCase()}/*`;
|
|
101
|
+
return loadGithubApps().find((app) => app.repositories.some((pattern) => pattern === full || pattern === wildcard));
|
|
102
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AuthTarget } from "./auth-target.mts";
|
|
2
|
+
import type { GithubApp } from "./github-app-config.mts";
|
|
3
|
+
export interface AppCredential {
|
|
4
|
+
token: string;
|
|
5
|
+
appId: number;
|
|
6
|
+
installationId: number;
|
|
7
|
+
}
|
|
8
|
+
export declare function _resetAppTokens(): void;
|
|
9
|
+
export declare function hasAppTokens(): boolean;
|
|
10
|
+
/** Drop minted tokens so the next request mints fresh ones. */
|
|
11
|
+
export declare function clearAppTokens(): void;
|
|
12
|
+
/** Installation token for the app on the target's account, minted and refreshed in memory. */
|
|
13
|
+
export declare function appCredential(app: GithubApp, target: AuthTarget): Promise<AppCredential>;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { sign } from "node:crypto";
|
|
3
|
+
import { EXIT, ShepherdError } from "../exit-codes.mjs";
|
|
4
|
+
import { githubFetch } from "./github-fetch.mjs";
|
|
5
|
+
import { sanitizeBody } from "./http-utils.mjs";
|
|
6
|
+
const BASE_URL = "https://api.github.com";
|
|
7
|
+
const REFRESH_MARGIN_MS = 5 * 60 * 1000;
|
|
8
|
+
/** Installation id per app and lowercased owner: an account has one installation of an app. */
|
|
9
|
+
const installations = new Map();
|
|
10
|
+
const tokens = new Map();
|
|
11
|
+
const inflight = new Map();
|
|
12
|
+
export function _resetAppTokens() {
|
|
13
|
+
installations.clear();
|
|
14
|
+
tokens.clear();
|
|
15
|
+
inflight.clear();
|
|
16
|
+
}
|
|
17
|
+
export function hasAppTokens() {
|
|
18
|
+
return tokens.size > 0;
|
|
19
|
+
}
|
|
20
|
+
/** Drop minted tokens so the next request mints fresh ones. */
|
|
21
|
+
export function clearAppTokens() {
|
|
22
|
+
tokens.clear();
|
|
23
|
+
}
|
|
24
|
+
/** 429 and 5xx are GitHub's trouble, not a setup error: exit 75 so callers retry later. */
|
|
25
|
+
const exitFor = (status) => status === 429 || status >= 500 ? EXIT.TEMPFAIL : EXIT.NOPERM;
|
|
26
|
+
function fail(app, target, problem, fix, exitCode = EXIT.NOPERM) {
|
|
27
|
+
throw new ShepherdError(`GitHub App ${app.appId} cannot authenticate for ${target.owner}/${target.repo}: ${problem}. ${fix}`, exitCode);
|
|
28
|
+
}
|
|
29
|
+
const b64 = (value) => Buffer.from(value).toString("base64url");
|
|
30
|
+
/** RS256 JWT for the app: issued 60s ago for clock skew, valid 9 minutes. */
|
|
31
|
+
function signAppJwt(app, target) {
|
|
32
|
+
const fix = `Fix private-key-file (${app.privateKeyFile}) in github-apps.yml.`;
|
|
33
|
+
let pem;
|
|
34
|
+
try {
|
|
35
|
+
pem = readFileSync(app.privateKeyFile, "utf8");
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
return fail(app, target, `cannot read the private key (${error.message})`, fix);
|
|
39
|
+
}
|
|
40
|
+
const now = Math.floor(Date.now() / 1000);
|
|
41
|
+
const payload = { iat: now - 60, exp: now + 9 * 60, iss: app.appId };
|
|
42
|
+
const input = `${b64(JSON.stringify({ alg: "RS256", typ: "JWT" }))}.${b64(JSON.stringify(payload))}`;
|
|
43
|
+
try {
|
|
44
|
+
return `${input}.${b64(sign("RSA-SHA256", Buffer.from(input), pem))}`;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return fail(app, target, "the private key is not a valid RSA PEM key", fix);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async function appRequest(jwt, method, path) {
|
|
51
|
+
const res = await githubFetch(`${BASE_URL}${path}`, {
|
|
52
|
+
method,
|
|
53
|
+
headers: {
|
|
54
|
+
Authorization: `Bearer ${jwt}`,
|
|
55
|
+
Accept: "application/vnd.github+json",
|
|
56
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
57
|
+
"User-Agent": "pr-shepherd",
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
const text = await res.text();
|
|
61
|
+
let body;
|
|
62
|
+
try {
|
|
63
|
+
body = JSON.parse(text);
|
|
64
|
+
}
|
|
65
|
+
catch { }
|
|
66
|
+
return { status: res.status, body, text };
|
|
67
|
+
}
|
|
68
|
+
async function installationId(app, target, jwt) {
|
|
69
|
+
const key = `${app.appId}:${target.owner.toLowerCase()}`;
|
|
70
|
+
const known = installations.get(key);
|
|
71
|
+
if (known !== undefined)
|
|
72
|
+
return known;
|
|
73
|
+
const { status, body, text } = await appRequest(jwt, "GET", `/repos/${target.owner}/${target.repo}/installation`);
|
|
74
|
+
const id = body?.id;
|
|
75
|
+
if (status === 404) {
|
|
76
|
+
return fail(app, target, "the app is not installed there", "Install the app on that account.");
|
|
77
|
+
}
|
|
78
|
+
if (status !== 200 || typeof id !== "number") {
|
|
79
|
+
return fail(app, target, `GitHub answered ${status} ${sanitizeBody(text)}`, "Check app-id.", exitFor(status));
|
|
80
|
+
}
|
|
81
|
+
installations.set(key, id);
|
|
82
|
+
return id;
|
|
83
|
+
}
|
|
84
|
+
async function mint(app, target) {
|
|
85
|
+
const jwt = signAppJwt(app, target);
|
|
86
|
+
const id = await installationId(app, target, jwt);
|
|
87
|
+
const { status, body, text } = await appRequest(jwt, "POST", `/app/installations/${id}/access_tokens`);
|
|
88
|
+
const minted = body;
|
|
89
|
+
if (status !== 201 || typeof minted?.token !== "string") {
|
|
90
|
+
return fail(app, target, `token request answered ${status} ${sanitizeBody(text)}`, "Retry.", exitFor(status));
|
|
91
|
+
}
|
|
92
|
+
const expiresAt = Date.parse(String(minted.expires_at));
|
|
93
|
+
tokens.set(id, { token: minted.token, expiresAt });
|
|
94
|
+
return { token: minted.token, appId: app.appId, installationId: id };
|
|
95
|
+
}
|
|
96
|
+
/** Installation token for the app on the target's account, minted and refreshed in memory. */
|
|
97
|
+
export async function appCredential(app, target) {
|
|
98
|
+
const known = installations.get(`${app.appId}:${target.owner.toLowerCase()}`);
|
|
99
|
+
const cached = known === undefined ? undefined : tokens.get(known);
|
|
100
|
+
if (known !== undefined && cached && cached.expiresAt - Date.now() > REFRESH_MARGIN_MS) {
|
|
101
|
+
return { token: cached.token, appId: app.appId, installationId: known };
|
|
102
|
+
}
|
|
103
|
+
const key = `${app.appId}:${target.owner.toLowerCase()}`;
|
|
104
|
+
const pending = inflight.get(key) ?? mint(app, target).finally(() => inflight.delete(key));
|
|
105
|
+
inflight.set(key, pending);
|
|
106
|
+
return pending;
|
|
107
|
+
}
|
|
@@ -6,13 +6,19 @@ import { isGraphQlMutationDocument, withGraphQlInternalRetry } from "./graphql-i
|
|
|
6
6
|
import { githubFetch } from "./github-fetch.mjs";
|
|
7
7
|
import { formatGraphQlErrors, parseGraphQlPayload } from "./graphql-response.mjs";
|
|
8
8
|
import { CCR_GRAPHQL_REFUSAL_MESSAGE, isCcrGraphqlRefusal } from "./graphql-session-refusal.mjs";
|
|
9
|
+
import { isAppEligibleGraphql } from "./app-eligibility.mjs";
|
|
10
|
+
import { withAppQuotaFallback } from "./app-quota.mjs";
|
|
11
|
+
import { authTargetFromGraphqlVars } from "./auth-target.mjs";
|
|
9
12
|
import { makeAuthHeaders } from "./http-auth.mjs";
|
|
10
13
|
import { requestWithTokenRetry } from "./http-request.mjs";
|
|
11
14
|
import { parseRateLimit, parseRetryAfter, redactToken, sanitizeBody, } from "./http-utils.mjs";
|
|
12
15
|
import { mergeGraphqlRateLimit, recordApiTelemetry } from "./api-telemetry.mjs";
|
|
13
16
|
import { recordIntermediateResponse } from "./http-intermediate.mjs";
|
|
14
17
|
const BASE_URL = "https://api.github.com";
|
|
15
|
-
|
|
18
|
+
function graphqlInner(query, vars, opts) {
|
|
19
|
+
return withAppQuotaFallback("graphql", () => graphqlAttempt(query, vars, opts));
|
|
20
|
+
}
|
|
21
|
+
async function graphqlAttempt(query, vars, opts) {
|
|
16
22
|
const url = `${BASE_URL}/graphql`;
|
|
17
23
|
const n = nextEntry();
|
|
18
24
|
appendEntry(formatRequestEntry({
|
|
@@ -25,10 +31,16 @@ async function graphqlInner(query, vars, opts) {
|
|
|
25
31
|
const t0 = performance.now();
|
|
26
32
|
let authSource = "unknown";
|
|
27
33
|
let credentialFingerprint;
|
|
34
|
+
let githubApp = false;
|
|
28
35
|
const { res, attempt, retryT0 } = await requestWithTokenRetry(async () => {
|
|
29
|
-
const auth = await makeAuthHeaders(
|
|
36
|
+
const auth = await makeAuthHeaders(undefined, {
|
|
37
|
+
target: authTargetFromGraphqlVars(vars),
|
|
38
|
+
appEligible: isAppEligibleGraphql(query),
|
|
39
|
+
resource: "graphql",
|
|
40
|
+
});
|
|
30
41
|
authSource = auth.source;
|
|
31
42
|
credentialFingerprint = auth.fingerprint;
|
|
43
|
+
githubApp = auth.githubApp;
|
|
32
44
|
return githubFetch(url, {
|
|
33
45
|
method: "POST",
|
|
34
46
|
headers: auth.headers,
|
|
@@ -43,6 +55,7 @@ async function graphqlInner(query, vars, opts) {
|
|
|
43
55
|
durationMs,
|
|
44
56
|
authSource,
|
|
45
57
|
credentialFingerprint,
|
|
58
|
+
githubApp,
|
|
46
59
|
}), !isGraphQlMutationDocument(query), true);
|
|
47
60
|
const durationMs = Math.round(performance.now() - retryT0);
|
|
48
61
|
const headerRateLimit = parseRateLimit(res.headers);
|
|
@@ -67,6 +80,7 @@ async function graphqlInner(query, vars, opts) {
|
|
|
67
80
|
method: "POST",
|
|
68
81
|
authSource,
|
|
69
82
|
credentialFingerprint,
|
|
83
|
+
githubApp,
|
|
70
84
|
rateLimit: headerRateLimit ?? undefined,
|
|
71
85
|
});
|
|
72
86
|
throw new GitHubRequestError(isCcrGraphqlRefusal(res.status, body)
|
|
@@ -103,6 +117,7 @@ async function graphqlInner(query, vars, opts) {
|
|
|
103
117
|
method: "POST",
|
|
104
118
|
authSource,
|
|
105
119
|
credentialFingerprint,
|
|
120
|
+
githubApp,
|
|
106
121
|
rateLimit: headerRateLimit ?? undefined,
|
|
107
122
|
});
|
|
108
123
|
throw new GitHubRequestError(`GitHub GraphQL response was not valid JSON${detail}`, {
|
|
@@ -134,6 +149,7 @@ async function graphqlInner(query, vars, opts) {
|
|
|
134
149
|
method: "POST",
|
|
135
150
|
authSource,
|
|
136
151
|
credentialFingerprint,
|
|
152
|
+
githubApp,
|
|
137
153
|
rateLimit: rateLimit ?? undefined,
|
|
138
154
|
});
|
|
139
155
|
const payload = parseGraphQlPayload(parsed, res.status, rateLimit, retryAfterSeconds);
|
|
@@ -1,15 +1,28 @@
|
|
|
1
|
-
|
|
1
|
+
import { type AuthTarget } from "./auth-target.mts";
|
|
2
|
+
import { type AppResource } from "./app-quota.mts";
|
|
3
|
+
export type AuthSource = "GH_TOKEN" | "GITHUB_TOKEN" | "gh auth token" | "GITHUB_PERSONAL_ACCESS_TOKEN" | `GitHub App ${number} (installation ${number})`;
|
|
2
4
|
export declare function _resetTokenCache(): void;
|
|
3
5
|
export declare function hasCachedToken(): boolean;
|
|
6
|
+
/** Forget the user token and every minted installation token; the next request re-resolves. */
|
|
4
7
|
export declare function clearTokenCache(): void;
|
|
5
8
|
/** Truncated SHA-256. Callers persist this instead of the token or its full hash. */
|
|
6
9
|
export declare function credentialFingerprint(token: string): string;
|
|
10
|
+
/** What the request is, so the credential can be chosen for it. */
|
|
11
|
+
export interface AuthRequest {
|
|
12
|
+
/** The request's own repository; without one the command's auth scope decides. */
|
|
13
|
+
target?: AuthTarget;
|
|
14
|
+
/** True for identity-independent reads (see `app-eligibility.mts`). Default false. */
|
|
15
|
+
appEligible?: boolean;
|
|
16
|
+
/** Quota bucket the request draws on. Default `core`. */
|
|
17
|
+
resource?: AppResource;
|
|
18
|
+
}
|
|
7
19
|
/**
|
|
8
20
|
* `extra` lets callers layer additional headers (e.g. `If-None-Match` for
|
|
9
21
|
* conditional REST requests) on top of the standard auth/version headers.
|
|
10
22
|
*/
|
|
11
|
-
export declare function makeAuthHeaders(extra?: Record<string, string
|
|
23
|
+
export declare function makeAuthHeaders(extra?: Record<string, string>, request?: AuthRequest): Promise<{
|
|
12
24
|
headers: Record<string, string>;
|
|
13
25
|
source: AuthSource;
|
|
14
26
|
fingerprint: string;
|
|
27
|
+
githubApp: boolean;
|
|
15
28
|
}>;
|
package/bin/github/http-auth.mjs
CHANGED
|
@@ -2,19 +2,28 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { execFile as execFileCb } from "node:child_process";
|
|
3
3
|
import { promisify } from "node:util";
|
|
4
4
|
import { EXIT, ShepherdError } from "../exit-codes.mjs";
|
|
5
|
+
import { currentAuthTarget } from "./auth-target.mjs";
|
|
6
|
+
import { _resetAppQuota, isAppExhausted } from "./app-quota.mjs";
|
|
7
|
+
import { _resetGithubApps, findGithubApp } from "./github-app-config.mjs";
|
|
8
|
+
import { _resetAppTokens, appCredential, clearAppTokens, hasAppTokens, } from "./github-app-token.mjs";
|
|
5
9
|
const execFile = promisify(execFileCb);
|
|
6
10
|
let _token;
|
|
7
11
|
let _tokenSource;
|
|
8
12
|
export function _resetTokenCache() {
|
|
9
13
|
_token = undefined;
|
|
10
14
|
_tokenSource = undefined;
|
|
15
|
+
_resetGithubApps();
|
|
16
|
+
_resetAppTokens();
|
|
17
|
+
_resetAppQuota();
|
|
11
18
|
}
|
|
12
19
|
export function hasCachedToken() {
|
|
13
|
-
return _token !== undefined;
|
|
20
|
+
return _token !== undefined || hasAppTokens();
|
|
14
21
|
}
|
|
22
|
+
/** Forget the user token and every minted installation token; the next request re-resolves. */
|
|
15
23
|
export function clearTokenCache() {
|
|
16
24
|
_token = undefined;
|
|
17
25
|
_tokenSource = undefined;
|
|
26
|
+
clearAppTokens();
|
|
18
27
|
}
|
|
19
28
|
/** Truncated SHA-256. Callers persist this instead of the token or its full hash. */
|
|
20
29
|
export function credentialFingerprint(token) {
|
|
@@ -55,15 +64,37 @@ async function resolveToken() {
|
|
|
55
64
|
}
|
|
56
65
|
throw new ShepherdError("No GitHub token found. Set GH_TOKEN, GITHUB_TOKEN, or GITHUB_PERSONAL_ACCESS_TOKEN, or run `gh auth login`.", EXIT.NOPERM);
|
|
57
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* A configured GitHub App that covers the target repository answers eligible requests, ahead of
|
|
69
|
+
* every user token, until its installation's bucket for the resource is spent. Its fingerprint is
|
|
70
|
+
* a stable identity, because installation tokens rotate hourly.
|
|
71
|
+
*/
|
|
72
|
+
async function resolveCredential(request, target) {
|
|
73
|
+
const app = request.appEligible && target && findGithubApp(target.owner, target.repo);
|
|
74
|
+
if (app) {
|
|
75
|
+
const { token, appId, installationId } = await appCredential(app, target);
|
|
76
|
+
if (!isAppExhausted(installationId, request.resource ?? "core")) {
|
|
77
|
+
return {
|
|
78
|
+
token,
|
|
79
|
+
source: `GitHub App ${appId} (installation ${installationId})`,
|
|
80
|
+
fingerprint: credentialFingerprint(`github-app:${appId}:${installationId}`),
|
|
81
|
+
githubApp: true,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const { token, source } = await resolveToken();
|
|
86
|
+
return { token, source, fingerprint: credentialFingerprint(token), githubApp: false };
|
|
87
|
+
}
|
|
58
88
|
/**
|
|
59
89
|
* `extra` lets callers layer additional headers (e.g. `If-None-Match` for
|
|
60
90
|
* conditional REST requests) on top of the standard auth/version headers.
|
|
61
91
|
*/
|
|
62
|
-
export async function makeAuthHeaders(extra) {
|
|
63
|
-
const { token, source } = await
|
|
92
|
+
export async function makeAuthHeaders(extra, request = {}) {
|
|
93
|
+
const { token, source, fingerprint, githubApp } = await resolveCredential(request, request.target ?? currentAuthTarget());
|
|
64
94
|
return {
|
|
65
95
|
source,
|
|
66
|
-
fingerprint
|
|
96
|
+
fingerprint,
|
|
97
|
+
githubApp,
|
|
67
98
|
headers: {
|
|
68
99
|
Authorization: `Bearer ${token}`,
|
|
69
100
|
Accept: "application/vnd.github+json",
|
|
@@ -15,6 +15,7 @@ export function recordIntermediateResponse(opts) {
|
|
|
15
15
|
kind: opts.kind === "GraphQL" ? "GraphQL" : "REST",
|
|
16
16
|
method: opts.method,
|
|
17
17
|
authSource: opts.authSource,
|
|
18
|
+
githubApp: opts.githubApp,
|
|
18
19
|
...(opts.credentialFingerprint !== undefined && {
|
|
19
20
|
credentialFingerprint: opts.credentialFingerprint,
|
|
20
21
|
}),
|
package/bin/github/rest-http.mjs
CHANGED
|
@@ -4,6 +4,9 @@ import { formatRequestEntry, formatResponseEntry } from "../log/session.mjs";
|
|
|
4
4
|
import { loadEtagEntry, storeEtagEntry } from "../state/rest-cache.mjs";
|
|
5
5
|
import { GitHubRequestError } from "./errors.mjs";
|
|
6
6
|
import { githubFetch } from "./github-fetch.mjs";
|
|
7
|
+
import { isAppEligibleRest } from "./app-eligibility.mjs";
|
|
8
|
+
import { withAppQuotaFallback } from "./app-quota.mjs";
|
|
9
|
+
import { authTargetFromRestPath } from "./auth-target.mjs";
|
|
7
10
|
import { makeAuthHeaders } from "./http-auth.mjs";
|
|
8
11
|
import { requestWithTokenRetry } from "./http-request.mjs";
|
|
9
12
|
import { parseRateLimit, parseRetryAfter, redactToken, sanitizeBody, } from "./http-utils.mjs";
|
|
@@ -30,20 +33,28 @@ export async function rest(method, path, body) {
|
|
|
30
33
|
const { data } = await restWithRateLimit(method, path, body);
|
|
31
34
|
return data;
|
|
32
35
|
}
|
|
33
|
-
export
|
|
36
|
+
export function restWithRateLimit(method, path, body, opts) {
|
|
37
|
+
return withAppQuotaFallback("core", () => restAttempt(method, path, body, opts));
|
|
38
|
+
}
|
|
39
|
+
async function restAttempt(method, path, body, opts) {
|
|
34
40
|
const url = githubApiUrl(path);
|
|
35
41
|
const n = nextEntry();
|
|
36
42
|
appendEntry(formatRequestEntry({ n, kind: "REST", method, url, body }));
|
|
37
43
|
const t0 = performance.now();
|
|
38
44
|
let authSource = "unknown";
|
|
39
45
|
let credentialFingerprint;
|
|
46
|
+
let githubApp = false;
|
|
40
47
|
const cached = opts?.conditional && !opts.conditional.revalidate
|
|
41
48
|
? await loadEtagEntry(opts.conditional.key, opts.conditional.name)
|
|
42
49
|
: null;
|
|
43
50
|
const { res, attempt, retryT0 } = await requestWithTokenRetry(async () => {
|
|
44
|
-
const auth = await makeAuthHeaders(cached ? { "If-None-Match": cached.etag } : undefined
|
|
51
|
+
const auth = await makeAuthHeaders(cached ? { "If-None-Match": cached.etag } : undefined, {
|
|
52
|
+
target: authTargetFromRestPath(path),
|
|
53
|
+
appEligible: isAppEligibleRest(method, path),
|
|
54
|
+
});
|
|
45
55
|
authSource = auth.source;
|
|
46
56
|
credentialFingerprint = auth.fingerprint;
|
|
57
|
+
githubApp = auth.githubApp;
|
|
47
58
|
return githubFetch(url, {
|
|
48
59
|
method,
|
|
49
60
|
headers: auth.headers,
|
|
@@ -58,6 +69,7 @@ export async function restWithRateLimit(method, path, body, opts) {
|
|
|
58
69
|
durationMs,
|
|
59
70
|
authSource,
|
|
60
71
|
credentialFingerprint,
|
|
72
|
+
githubApp,
|
|
61
73
|
}), method === "GET" || method === "HEAD");
|
|
62
74
|
const durationMs = Math.round(performance.now() - retryT0);
|
|
63
75
|
const rateLimit = parseRateLimit(res.headers) ?? undefined;
|
|
@@ -84,6 +96,7 @@ export async function restWithRateLimit(method, path, body, opts) {
|
|
|
84
96
|
method,
|
|
85
97
|
authSource,
|
|
86
98
|
credentialFingerprint,
|
|
99
|
+
githubApp,
|
|
87
100
|
rateLimit,
|
|
88
101
|
notModified: true,
|
|
89
102
|
});
|
|
@@ -116,6 +129,7 @@ export async function restWithRateLimit(method, path, body, opts) {
|
|
|
116
129
|
method,
|
|
117
130
|
authSource,
|
|
118
131
|
credentialFingerprint,
|
|
132
|
+
githubApp,
|
|
119
133
|
rateLimit,
|
|
120
134
|
});
|
|
121
135
|
const responseMessage = isRestSessionRefusalResponse(res.status, text)
|
|
@@ -155,6 +169,7 @@ export async function restWithRateLimit(method, path, body, opts) {
|
|
|
155
169
|
method,
|
|
156
170
|
authSource,
|
|
157
171
|
credentialFingerprint,
|
|
172
|
+
githubApp,
|
|
158
173
|
rateLimit,
|
|
159
174
|
});
|
|
160
175
|
if (!res.ok) {
|
|
@@ -187,6 +202,7 @@ export async function restWithRateLimit(method, path, body, opts) {
|
|
|
187
202
|
method,
|
|
188
203
|
authSource,
|
|
189
204
|
credentialFingerprint,
|
|
205
|
+
githubApp,
|
|
190
206
|
rateLimit,
|
|
191
207
|
});
|
|
192
208
|
const etag = opts?.conditional ? (res.headers.get("etag") ?? undefined) : undefined;
|
|
@@ -227,6 +243,7 @@ export async function restWithRateLimit(method, path, body, opts) {
|
|
|
227
243
|
method,
|
|
228
244
|
authSource,
|
|
229
245
|
credentialFingerprint,
|
|
246
|
+
githubApp,
|
|
230
247
|
rateLimit,
|
|
231
248
|
});
|
|
232
249
|
return { data: undefined, rateLimit, status: res.status };
|
package/bin/github/rest-text.mjs
CHANGED
|
@@ -3,23 +3,34 @@ import { formatRequestEntry, formatResponseEntry } from "../log/session.mjs";
|
|
|
3
3
|
import { GitHubRequestError } from "./errors.mjs";
|
|
4
4
|
import { githubFetch } from "./github-fetch.mjs";
|
|
5
5
|
import { GITHUB_LOG_TIMEOUT_MS } from "./github-timeouts.mjs";
|
|
6
|
+
import { isAppEligibleRest } from "./app-eligibility.mjs";
|
|
7
|
+
import { withAppQuotaFallback } from "./app-quota.mjs";
|
|
8
|
+
import { authTargetFromRestPath } from "./auth-target.mjs";
|
|
6
9
|
import { makeAuthHeaders } from "./http-auth.mjs";
|
|
7
10
|
import { requestWithTokenRetry } from "./http-request.mjs";
|
|
8
11
|
import { parseRateLimit, parseRetryAfter, redactUrl, sanitizeBody, } from "./http-utils.mjs";
|
|
9
12
|
import { recordApiTelemetry } from "./api-telemetry.mjs";
|
|
10
13
|
import { recordIntermediateResponse } from "./http-intermediate.mjs";
|
|
11
14
|
const BASE_URL = "https://api.github.com";
|
|
12
|
-
export
|
|
15
|
+
export function restText(path, onRateLimit) {
|
|
16
|
+
return withAppQuotaFallback("core", () => restTextAttempt(path, onRateLimit));
|
|
17
|
+
}
|
|
18
|
+
async function restTextAttempt(path, onRateLimit) {
|
|
13
19
|
const url = `${BASE_URL}${path}`;
|
|
14
20
|
const n = nextEntry();
|
|
15
21
|
appendEntry(formatRequestEntry({ n, kind: "restText", method: "GET", url }));
|
|
16
22
|
const t0 = performance.now();
|
|
17
23
|
let authSource = "unknown";
|
|
18
24
|
let credentialFingerprint;
|
|
25
|
+
let githubApp = false;
|
|
19
26
|
const { res, attempt, retryT0 } = await requestWithTokenRetry(async () => {
|
|
20
|
-
const auth = await makeAuthHeaders(
|
|
27
|
+
const auth = await makeAuthHeaders(undefined, {
|
|
28
|
+
target: authTargetFromRestPath(path),
|
|
29
|
+
appEligible: isAppEligibleRest("GET", path),
|
|
30
|
+
});
|
|
21
31
|
authSource = auth.source;
|
|
22
32
|
credentialFingerprint = auth.fingerprint;
|
|
33
|
+
githubApp = auth.githubApp;
|
|
23
34
|
return githubFetch(url, { method: "GET", headers: auth.headers, redirect: "manual" }, GITHUB_LOG_TIMEOUT_MS);
|
|
24
35
|
}, t0, (response, durationMs) => recordIntermediateResponse({
|
|
25
36
|
n,
|
|
@@ -30,12 +41,20 @@ export async function restText(path, onRateLimit) {
|
|
|
30
41
|
durationMs,
|
|
31
42
|
authSource,
|
|
32
43
|
credentialFingerprint,
|
|
44
|
+
githubApp,
|
|
33
45
|
}));
|
|
34
46
|
const durationMs = Math.round(performance.now() - retryT0);
|
|
35
47
|
const rateLimit = parseRateLimit(res.headers) ?? undefined;
|
|
36
48
|
onRateLimit?.(rateLimit);
|
|
37
49
|
const retryAfterSeconds = parseRetryAfter(res.headers);
|
|
38
|
-
recordApiTelemetry({
|
|
50
|
+
recordApiTelemetry({
|
|
51
|
+
kind: "REST",
|
|
52
|
+
method: "GET",
|
|
53
|
+
authSource,
|
|
54
|
+
credentialFingerprint,
|
|
55
|
+
githubApp,
|
|
56
|
+
rateLimit,
|
|
57
|
+
});
|
|
39
58
|
if ([301, 302, 307, 308].includes(res.status)) {
|
|
40
59
|
const redirected = await followRestTextRedirect(res, {
|
|
41
60
|
n,
|
package/bin/pr-reference.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { setAuthTarget } from "./github/auth-target.mjs";
|
|
1
2
|
/** Parses API PR references without performing repository or GitHub I/O. */
|
|
2
3
|
export function parsePrReference(pr) {
|
|
3
4
|
if (pr === undefined)
|
|
@@ -42,6 +43,8 @@ export function resolveParsedPrTarget(parsed) {
|
|
|
42
43
|
const [owner, name] = parsed.repository.split("/");
|
|
43
44
|
if (!owner || !name)
|
|
44
45
|
throw new Error(`Invalid repository reference: ${parsed.repository}`);
|
|
46
|
+
// A repository the caller named selects the credential for the whole command.
|
|
47
|
+
setAuthTarget({ owner, name }, "explicit");
|
|
45
48
|
return {
|
|
46
49
|
prNumber: parsed.number,
|
|
47
50
|
targetRepository: { owner, name },
|
|
@@ -28,7 +28,19 @@ export interface QuotaWarningBudget {
|
|
|
28
28
|
used?: number;
|
|
29
29
|
resetAt: number;
|
|
30
30
|
}
|
|
31
|
+
/** One GitHub App installation's usage, accounted separately from the user's token chain. */
|
|
32
|
+
export interface GithubAppApiUsage {
|
|
33
|
+
/** `GitHub App <appId> (installation <id>)`. */
|
|
34
|
+
source: string;
|
|
35
|
+
graphql?: GraphqlApiUsage;
|
|
36
|
+
rest?: ApiResourceUsage[];
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Top-level fields describe only the user's token chain (non-App requests); quota state and
|
|
40
|
+
* warnings are driven by these alone.
|
|
41
|
+
*/
|
|
31
42
|
export interface ApiUsage {
|
|
43
|
+
/** User-chain credential sources; empty when only a GitHub App answered. */
|
|
32
44
|
credentialSources: string[];
|
|
33
45
|
graphql?: GraphqlApiUsage;
|
|
34
46
|
rest?: ApiResourceUsage[];
|
|
@@ -37,6 +49,8 @@ export interface ApiUsage {
|
|
|
37
49
|
* Code proxy's `ccr` routes). Omitted when 0.
|
|
38
50
|
*/
|
|
39
51
|
unmeteredRestRequestCount?: number;
|
|
52
|
+
/** One entry per GitHub App installation used, in order of first use. Omitted when none. */
|
|
53
|
+
githubApps?: GithubAppApiUsage[];
|
|
40
54
|
}
|
|
41
55
|
export interface GraphqlQuotaWarning {
|
|
42
56
|
resource: "graphql" | "core" | "combined";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pr-shepherd",
|
|
3
3
|
"description": "Autonomous PR CI monitor and review-comment resolver for agentic coding tools",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.4.0",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Jonathan Ong",
|
|
7
7
|
"email": "jonathanrichardong@gmail.com"
|
|
@@ -11,5 +11,13 @@
|
|
|
11
11
|
"license": "MIT",
|
|
12
12
|
"keywords": ["github", "pull-request", "ci", "code-review", "automation"],
|
|
13
13
|
"skills": "./skills/",
|
|
14
|
-
"mcpServers": "./.mcp.json"
|
|
14
|
+
"mcpServers": "./.mcp.json",
|
|
15
|
+
"userConfig": {
|
|
16
|
+
"poll_guard": {
|
|
17
|
+
"type": "string",
|
|
18
|
+
"title": "Poll guard",
|
|
19
|
+
"description": "What to do when a shell command polls GitHub PR or CI state instead of running pr-shepherd: disabled, advisory (run it and tell the agent), or fail (block it). The PR_SHEPHERD_POLL_GUARD environment variable overrides this.",
|
|
20
|
+
"default": "advisory"
|
|
21
|
+
}
|
|
22
|
+
}
|
|
15
23
|
}
|