pr-shepherd 1.3.0 → 1.5.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 (48) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -0
  3. package/bin/api.mjs +4 -1
  4. package/bin/cli/api-usage-formatter.mjs +18 -8
  5. package/bin/cli/help-command-pages.d.mts +2 -2
  6. package/bin/cli/help-iterate-poll-pages.d.mts +2 -2
  7. package/bin/cli/help-iterate-poll-pages.mjs +3 -2
  8. package/bin/cli/help.d.mts +2 -2
  9. package/bin/cli-parser.mjs +5 -2
  10. package/bin/commands/poll-summary-explicit-instructions.mjs +1 -1
  11. package/bin/commands/tick.mjs +1 -0
  12. package/bin/github/api-telemetry-adopt.d.mts +4 -0
  13. package/bin/github/api-telemetry-adopt.mjs +52 -0
  14. package/bin/github/api-telemetry-aggregate.d.mts +6 -2
  15. package/bin/github/api-telemetry-aggregate.mjs +19 -52
  16. package/bin/github/api-telemetry-summary.d.mts +4 -0
  17. package/bin/github/api-telemetry-summary.mjs +63 -0
  18. package/bin/github/api-telemetry.d.mts +2 -0
  19. package/bin/github/api-telemetry.mjs +2 -43
  20. package/bin/github/app-eligibility.d.mts +9 -0
  21. package/bin/github/app-eligibility.mjs +21 -0
  22. package/bin/github/app-quota.d.mts +10 -0
  23. package/bin/github/app-quota.mjs +44 -0
  24. package/bin/github/auth-target.d.mts +16 -0
  25. package/bin/github/auth-target.mjs +29 -0
  26. package/bin/github/client.mjs +4 -2
  27. package/bin/github/github-app-config.d.mts +12 -0
  28. package/bin/github/github-app-config.mjs +102 -0
  29. package/bin/github/github-app-token.d.mts +13 -0
  30. package/bin/github/github-app-token.mjs +107 -0
  31. package/bin/github/graphql-http.mjs +18 -2
  32. package/bin/github/http-auth.d.mts +15 -2
  33. package/bin/github/http-auth.mjs +35 -4
  34. package/bin/github/http-intermediate.d.mts +1 -0
  35. package/bin/github/http-intermediate.mjs +1 -0
  36. package/bin/github/rest-http.mjs +19 -2
  37. package/bin/github/rest-text.mjs +22 -3
  38. package/bin/pr-reference.mjs +3 -0
  39. package/bin/types/api-usage.d.mts +14 -0
  40. package/package.json +1 -1
  41. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  42. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  43. package/plugins/pr-shepherd/.codex.mcp.json +1 -1
  44. package/plugins/pr-shepherd/.mcp.json +1 -1
  45. package/plugins/pr-shepherd/package-lock.json +4 -4
  46. package/plugins/pr-shepherd/package.json +1 -1
  47. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +2 -2
  48. package/plugins/pr-shepherd/skills/pr-shepherd/references/waiting.md +8 -0
@@ -1,5 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { aggregateEvents, aggregateStore, emptyAggregate, mergeAggregate, } from "./api-telemetry-aggregate.mjs";
3
+ import { summarizeAggregate } from "./api-telemetry-summary.mjs";
3
4
  const GRAPHQL_RATE_LIMIT_ALIAS = "_shepherdRateLimit";
4
5
  const eventStorage = new AsyncLocalStorage();
5
6
  function store() {
@@ -91,49 +92,7 @@ export function withRestCoreCredentialFingerprint(sample) {
91
92
  }
92
93
  export function summarizeApiTelemetry() {
93
94
  const active = store();
94
- if (active === undefined)
95
- return undefined;
96
- const selected = aggregateStore(active);
97
- if (selected.eventCount === 0)
98
- return undefined;
99
- const credentialSources = [...selected.credentialSources.entries()]
100
- .sort((left, right) => left[1] - right[1])
101
- .map(([source]) => source);
102
- const graphql = summarizeGraphql(selected.graphql);
103
- const rest = summarizeRest(selected.rest);
104
- const unmeteredRestRequestCount = selected.unmeteredRestRequestCount;
105
- return {
106
- credentialSources,
107
- ...(graphql !== undefined && { graphql }),
108
- ...(rest.length > 0 && { rest }),
109
- ...(unmeteredRestRequestCount > 0 && { unmeteredRestRequestCount }),
110
- };
111
- }
112
- function summarizeGraphql(selected) {
113
- if (selected.rateLimit === undefined)
114
- return undefined;
115
- return {
116
- ...resourceUsage(selected.rateLimit, selected.requestCount, "graphql"),
117
- measuredQueryCost: selected.measuredQueryCost,
118
- unmeasuredRequestCount: selected.unmeasuredRequestCount,
119
- nodeCount: selected.nodeCount,
120
- };
121
- }
122
- function summarizeRest(selected) {
123
- return [...selected.entries()].flatMap(([resource, group]) => group.rateLimit
124
- ? [resourceUsage(group.rateLimit, group.requestCount, resource, group.notModifiedCount)]
125
- : []);
126
- }
127
- function resourceUsage(rateLimit, requestCount, fallbackResource, notModified = 0) {
128
- return {
129
- resource: rateLimit.resource ?? fallbackResource,
130
- ...(requestCount > 0 && { requestCount }),
131
- ...(notModified > 0 && { notModified }),
132
- limit: rateLimit.limit,
133
- ...(rateLimit.used !== undefined && { used: rateLimit.used }),
134
- remaining: rateLimit.remaining,
135
- resetAt: rateLimit.resetAt,
136
- };
95
+ return active === undefined ? undefined : summarizeAggregate(aggregateStore(active));
137
96
  }
138
97
  function extractGraphqlRateLimit(data) {
139
98
  if (data === null || typeof data !== "object" || Array.isArray(data))
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The app answers only requests whose answer does not depend on who asks. Everything else
3
+ * (writes, `/user`, viewer fields) stays on the user's token, so identity semantics are the same
4
+ * as running without the app.
5
+ */
6
+ /** A GET or HEAD of a repository route. Caller-relative routes (`/user`, `/rate_limit`) are not. */
7
+ export declare function isAppEligibleRest(method: string, path: string): boolean;
8
+ /** A query that selects no viewer-relative field (`viewer`, `viewerCan*`, `isReadByViewer`, …). */
9
+ export declare function isAppEligibleGraphql(document: string): boolean;
@@ -0,0 +1,21 @@
1
+ import { isGraphQlMutationDocument } from "./graphql-internal-retry.mjs";
2
+ /**
3
+ * The app answers only requests whose answer does not depend on who asks. Everything else
4
+ * (writes, `/user`, viewer fields) stays on the user's token, so identity semantics are the same
5
+ * as running without the app.
6
+ */
7
+ /** A GET or HEAD of a repository route. Caller-relative routes (`/user`, `/rate_limit`) are not. */
8
+ export function isAppEligibleRest(method, path) {
9
+ return (method === "GET" || method === "HEAD") && path.startsWith("/repos/");
10
+ }
11
+ const VIEWER_RELATIVE = /\bviewer\w*|\w+ByViewer\b/;
12
+ const eligibility = new Map();
13
+ /** A query that selects no viewer-relative field (`viewer`, `viewerCan*`, `isReadByViewer`, …). */
14
+ export function isAppEligibleGraphql(document) {
15
+ const known = eligibility.get(document);
16
+ if (known !== undefined)
17
+ return known;
18
+ const eligible = !isGraphQlMutationDocument(document) && !VIEWER_RELATIVE.test(document.replace(/#[^\n]*/g, ""));
19
+ eligibility.set(document, eligible);
20
+ return eligible;
21
+ }
@@ -0,0 +1,10 @@
1
+ export type AppResource = "graphql" | "core";
2
+ export declare function _resetAppQuota(): void;
3
+ /** True while the installation's bucket for the resource is empty. */
4
+ export declare function isAppExhausted(installationId: number, resource: AppResource): boolean;
5
+ /**
6
+ * Re-run an app-authenticated request once with the user's token when the installation's own
7
+ * primary limit is spent. `work` re-resolves its credential on every call, so the second run
8
+ * sees the exhaustion mark and uses the user chain until GitHub resets the bucket.
9
+ */
10
+ export declare function withAppQuotaFallback<T>(resource: AppResource, work: () => Promise<T>): Promise<T>;
@@ -0,0 +1,44 @@
1
+ import { appendEntry } from "../log/log-file.mjs";
2
+ import { GitHubRequestError } from "./errors.mjs";
3
+ import { needsGraphQlQuotaProbe } from "./graphql-quota-probe.mjs";
4
+ import { rateLimitKind } from "./rate-limit-kind.mjs";
5
+ const APP_SOURCE = /^GitHub App \d+ \(installation (\d+)\)$/;
6
+ const FALLBACK_WINDOW_MS = 60_000;
7
+ /** `installation:resource` to the epoch milliseconds when GitHub resets that bucket. */
8
+ const exhausted = new Map();
9
+ export function _resetAppQuota() {
10
+ exhausted.clear();
11
+ }
12
+ /** True while the installation's bucket for the resource is empty. */
13
+ export function isAppExhausted(installationId, resource) {
14
+ const until = exhausted.get(`${installationId}:${resource}`);
15
+ return until !== undefined && until > Date.now();
16
+ }
17
+ /** Primary exhaustion only. Secondary (abuse) limits are never a reason to switch credentials. */
18
+ function isPrimaryExhaustion(error) {
19
+ return rateLimitKind(error) === "primary" || needsGraphQlQuotaProbe(error);
20
+ }
21
+ /**
22
+ * Re-run an app-authenticated request once with the user's token when the installation's own
23
+ * primary limit is spent. `work` re-resolves its credential on every call, so the second run
24
+ * sees the exhaustion mark and uses the user chain until GitHub resets the bucket.
25
+ */
26
+ export async function withAppQuotaFallback(resource, work) {
27
+ try {
28
+ return await work();
29
+ }
30
+ catch (error) {
31
+ const installation = APP_SOURCE.exec(error instanceof GitHubRequestError ? (error.authSource ?? "") : "")?.[1];
32
+ if (!(error instanceof GitHubRequestError) || !installation || !isPrimaryExhaustion(error)) {
33
+ throw error;
34
+ }
35
+ const resetAt = error.rateLimit?.resetAt;
36
+ const reset = resetAt ? resetAt * 1000 : 0;
37
+ const until = reset > Date.now() ? reset : Date.now() + FALLBACK_WINDOW_MS;
38
+ if (!isAppExhausted(Number(installation), resource)) {
39
+ appendEntry(`GitHub App installation ${installation} exhausted its ${resource} rate limit until ${new Date(until).toISOString()}; using the user token.\n`);
40
+ }
41
+ exhausted.set(`${installation}:${resource}`, until);
42
+ return work();
43
+ }
44
+ }
@@ -0,0 +1,16 @@
1
+ export interface AuthTarget {
2
+ owner: string;
3
+ repo: string;
4
+ }
5
+ /** Wrap a complete command so every request it makes shares one target record. */
6
+ export declare function runWithAuthScope<T>(work: () => Promise<T>): Promise<T>;
7
+ /** Record the command's repository; a no-op outside `runWithAuthScope`. */
8
+ export declare function setAuthTarget(repository: {
9
+ owner: string;
10
+ name: string;
11
+ }, kind: "explicit" | "inferred"): void;
12
+ export declare function currentAuthTarget(): AuthTarget | undefined;
13
+ /** `/repos/{owner}/{repo}/…` */
14
+ export declare function authTargetFromRestPath(path: string): AuthTarget | undefined;
15
+ /** `owner` plus `repo` (or `name`) string variables. */
16
+ export declare function authTargetFromGraphqlVars(vars: Record<string, unknown>): AuthTarget | undefined;
@@ -0,0 +1,29 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const scope = new AsyncLocalStorage();
3
+ /** Wrap a complete command so every request it makes shares one target record. */
4
+ export function runWithAuthScope(work) {
5
+ return scope.run({}, work);
6
+ }
7
+ /** Record the command's repository; a no-op outside `runWithAuthScope`. */
8
+ export function setAuthTarget(repository, kind) {
9
+ const current = scope.getStore();
10
+ if (current)
11
+ current[kind] = { owner: repository.owner, repo: repository.name };
12
+ }
13
+ export function currentAuthTarget() {
14
+ const current = scope.getStore();
15
+ return current?.explicit ?? current?.inferred;
16
+ }
17
+ /** `/repos/{owner}/{repo}/…` */
18
+ export function authTargetFromRestPath(path) {
19
+ const match = /^\/repos\/([^/?#]+)\/([^/?#]+)/.exec(path);
20
+ return match ? { owner: match[1], repo: match[2] } : undefined;
21
+ }
22
+ /** `owner` plus `repo` (or `name`) string variables. */
23
+ export function authTargetFromGraphqlVars(vars) {
24
+ const { owner, repo, name } = vars;
25
+ const repository = typeof repo === "string" ? repo : name;
26
+ return typeof owner === "string" && typeof repository === "string"
27
+ ? { owner, repo: repository }
28
+ : undefined;
29
+ }
@@ -15,6 +15,7 @@ import { promisify } from "node:util";
15
15
  import { graphql as httpGraphql, rest } from "./http.mjs";
16
16
  import { PR_NUMBER_BY_BRANCH_QUERY, GET_PR_HEAD_SHA_QUERY, GET_PR_BODY_QUERY, UPDATE_PR_BODY_MUTATION, } from "./queries.mjs";
17
17
  import { getExecutionCwd } from "../execution-context.mjs";
18
+ import { setAuthTarget } from "./auth-target.mjs";
18
19
  const execFile = promisify(execFileCb);
19
20
  // ---------------------------------------------------------------------------
20
21
  // GraphQL — thin re-exports so callers don't need to import http.mts directly
@@ -28,8 +29,9 @@ export async function getRepoInfo() {
28
29
  const { stdout } = await execFile("git", ["remote", "get-url", "origin"], {
29
30
  cwd: getExecutionCwd(),
30
31
  });
31
- const url = stdout.trim();
32
- return parseRemoteUrl(url);
32
+ const repository = parseRemoteUrl(stdout.trim());
33
+ setAuthTarget(repository, "inferred");
34
+ return repository;
33
35
  }
34
36
  /**
35
37
  * Derives the PR number for the current HEAD branch.
@@ -0,0 +1,12 @@
1
+ export interface GithubApp {
2
+ appId: number;
3
+ /** Absolute path of the PEM private key. */
4
+ privateKeyFile: string;
5
+ /** Lowercased `owner/*` or `owner/repo` patterns. */
6
+ repositories: string[];
7
+ }
8
+ export declare function _resetGithubApps(): void;
9
+ /** Read `github-apps.yml` once per process. A missing file turns the feature off. */
10
+ export declare function loadGithubApps(): GithubApp[];
11
+ /** First listed app whose patterns match the repository. Matching ignores case. */
12
+ export declare function findGithubApp(owner: string, repo: string): GithubApp | undefined;
@@ -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
- async function graphqlInner(query, vars, opts) {
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
- export type AuthSource = "GH_TOKEN" | "GITHUB_TOKEN" | "gh auth token" | "GITHUB_PERSONAL_ACCESS_TOKEN";
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>): Promise<{
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
  }>;
@@ -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 resolveToken();
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: credentialFingerprint(token),
96
+ fingerprint,
97
+ githubApp,
67
98
  headers: {
68
99
  Authorization: `Bearer ${token}`,
69
100
  Accept: "application/vnd.github+json",
@@ -7,4 +7,5 @@ export declare function recordIntermediateResponse(opts: {
7
7
  durationMs: number;
8
8
  authSource: string;
9
9
  credentialFingerprint?: string;
10
+ githubApp: boolean;
10
11
  }): void;
@@ -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
  }),