@chmouel/pi-pr 0.0.0-stage → 0.3.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
- # Temporary Holding Version
1
+ # pi-pr
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [pi](https://pi.dev) extension that shows the GitHub pull request for the current branch, like Copilot CLI's `/pr`.
4
+
5
+ <img width="1547" height="1044" alt="screenshot of the footer status and /pr table" src="https://github.com/user-attachments/assets/8f7f6d3a-d584-4e18-a05d-eefb8b5b773e" />
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pi install npm:@chmouel/pi-pr
11
+ pi install git:github.com/chmouel/pi-pr # straight from git
12
+ ```
13
+
14
+ You need the [`gh`](https://cli.github.com/) CLI installed and authenticated.
15
+
16
+ ## What you get
17
+
18
+ A status line under pi's footer, refreshed when a session starts, every minute, after each agent run, and as soon as you switch branch:
19
+
20
+ ```
21
+ ● PR #122 · 1 pending · review required · · +4084-17 · feat: Sync Vocabulary…
22
+ ```
23
+
24
+ A merged or closed PR stays on screen for a day, then the line clears. When `gh` is missing or not logged in, the line says so instead of going blank.
25
+
26
+ The line carries the CI state, a clickable `PR #N` (OSC 8 hyperlink), the CI tally, the review decision, each reviewer's state, merge conflicts, the diff size, and the PR title. The title sits last, so it is the part pi truncates when the terminal is narrow.
27
+
28
+ Reviewer states use [Nerd Font](https://www.nerdfonts.com/) Octicons for approved, changes requested, commented, requested and dismissed. Copilot gets its own glyph.
29
+
30
+ ## Commands
31
+
32
+ | Command | Does |
33
+ | --- | --- |
34
+ | `/pr` | Print a summary table: state, branch, URL, changes, reviews, CI |
35
+ | `/pr checks` | Print each check with its result |
36
+ | `/pr open` | Open the PR in the browser |
37
+ | `/pr refresh` | Refresh the footer status |
38
+
39
+ The summary lands in the transcript as a card. It is not sent to the model.
40
+
41
+ ## Finding the PR
42
+
43
+ `gh pr view` answers first. If it reports no PR, the extension falls back to `gh pr list --head <branch>`, which finds a PR opened from a different remote than the one the branch tracks. That case shows up when you push straight to the upstream repository while the branch tracks your fork.
44
+
45
+ ## Credits
46
+
47
+ The polling cadence, the branch-change watch, the one-day retention for merged PRs, the `gh` missing and `gh not logged in` states, and the control-character and hyperlink-capability guards come from [@narumitw/pi-github-pr](https://www.npmjs.com/package/@narumitw/pi-github-pr). Its plain-text status line is what led to this extension growing a command and a transcript card on top.
48
+
49
+ ## Similar packages
50
+
51
+ | Package | Scope |
52
+ | --- | --- |
53
+ | `@narumitw/pi-github-pr` | Shows PR review, check and comment status. Closest overlap with this extension. |
54
+ | `@henryqw/pi-pr` | `/pr` command that finds, creates, updates and merges PRs, then fixes CI from review feedback. |
55
+ | `pi-prs` | Pulls review feedback into the agent and watches PRs. |
56
+ | `@pikibun/pi-pr-flow` | Drives a change through the PR lifecycle, draft first, ready later. |
57
+ | `@sfroment/pi-gh-cli`, `@procedures/gh` | Wrap the `gh` CLI as tools, no PR status line. |
58
+
59
+ Use this one for the footer status, the transcript table and the fork-aware lookup. Use `@henryqw/pi-pr` if you want the agent to act on the PR rather than display it.
60
+
61
+ Development, releasing and layout notes live in [DEVELOPER.md](DEVELOPER.md).
62
+
63
+ ## License
64
+
65
+ Apache-2.0
@@ -0,0 +1,464 @@
1
+ /**
2
+ * /pr — show the GitHub PR attached to the current branch (like Copilot CLI's /pr).
3
+ *
4
+ * /pr show PR summary (title, state, review, checks, URL)
5
+ * /pr open open the PR in the browser
6
+ * /pr checks list individual checks
7
+ * /pr refresh refresh the footer status
8
+ *
9
+ * Also keeps a footer status for the current branch, refreshed every minute, after each agent
10
+ * run, and when the git branch changes. A merged or closed PR stays visible for a day.
11
+ *
12
+ * Requires the `gh` CLI, installed and authenticated.
13
+ * Refresh and retention behaviour was inspired by @narumitw/pi-github-pr.
14
+ */
15
+
16
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
17
+ import { getCapabilities, hyperlink, Text } from "@earendil-works/pi-tui";
18
+ import { watch, type FSWatcher } from "node:fs";
19
+ import { resolve } from "node:path";
20
+
21
+ type Check = { name?: string; context?: string; status?: string; conclusion?: string; state?: string };
22
+ type PR = {
23
+ number: number;
24
+ title: string;
25
+ state: string;
26
+ isDraft: boolean;
27
+ url: string;
28
+ headRefName: string;
29
+ baseRefName: string;
30
+ reviewDecision: string;
31
+ mergeable: string;
32
+ author: { login: string };
33
+ statusCheckRollup: Check[];
34
+ additions: number;
35
+ deletions: number;
36
+ changedFiles: number;
37
+ closedAt: string | null;
38
+ mergedAt: string | null;
39
+ reviews: { author: { login: string }; state: string }[];
40
+ latestReviews: { author: { login: string }; state: string }[];
41
+ reviewRequests: { login?: string; name?: string; slug?: string }[];
42
+ };
43
+
44
+ type Reviewer = { name: string; state: "approved" | "changes" | "commented" | "requested" | "dismissed" };
45
+
46
+ const BOT_ICONS: Record<string, string> = {
47
+ copilot: "\uf4b8", // nf-oct-copilot
48
+ "github-copilot": "\uf4b8",
49
+ };
50
+
51
+ const shortName = (login: string) => {
52
+ const n = login.replace(/-pull-request-reviewer$/, "").replace(/\[bot\]$/, "");
53
+ return BOT_ICONS[n.toLowerCase()] ?? n;
54
+ };
55
+
56
+ /** Latest state per reviewer; pending review requests (e.g. Copilot still reviewing) override older reviews. */
57
+ function reviewers(pr: PR): Reviewer[] {
58
+ const map = new Map<string, Reviewer["state"]>();
59
+ const states: Record<string, Reviewer["state"]> = {
60
+ APPROVED: "approved",
61
+ CHANGES_REQUESTED: "changes",
62
+ COMMENTED: "commented",
63
+ DISMISSED: "dismissed",
64
+ };
65
+ for (const r of pr.latestReviews ?? []) {
66
+ const st = states[r.state];
67
+ if (r.author?.login && st) map.set(shortName(r.author.login), st);
68
+ }
69
+ for (const rq of pr.reviewRequests ?? []) {
70
+ const n = rq.login || rq.slug || rq.name;
71
+ if (n) map.set(shortName(n), "requested");
72
+ }
73
+ return [...map].map(([name, state]) => ({ name, state }));
74
+ }
75
+
76
+ const REVIEW_ICON: Record<Reviewer["state"], string> = {
77
+ approved: "\uf42e", // nf-oct-check_circle
78
+ changes: "\uf52f", // nf-oct-file_diff
79
+ commented: "\uf41f", // nf-oct-comment
80
+ requested: "\uf43a", // nf-oct-clock
81
+ dismissed: "\uf468", // nf-oct-circle_slash
82
+ };
83
+ const REVIEW_COLOR = { approved: "success", changes: "error", commented: "muted", requested: "warning", dismissed: "dim" } as const;
84
+
85
+ /** Drops control characters so a hostile PR title cannot drive the terminal. */
86
+ function plain(value: string): string {
87
+ let out = "";
88
+ for (const ch of value.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "")) {
89
+ const cp = ch.codePointAt(0) ?? 0;
90
+ if (cp > 0x1f && cp !== 0x7f) out += ch;
91
+ }
92
+ return out;
93
+ }
94
+
95
+ const link = (text: string, url: string): string => {
96
+ const safeText = plain(text);
97
+ let parsed: URL;
98
+ try {
99
+ parsed = new URL(url);
100
+ } catch {
101
+ return safeText;
102
+ }
103
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return safeText;
104
+ try {
105
+ if (!getCapabilities().hyperlinks) return safeText;
106
+ } catch {
107
+ return safeText;
108
+ }
109
+ return hyperlink(safeText, plain(parsed.toString()));
110
+ };
111
+
112
+ // Value column wraps at this width so long lists (failed checks, reviewers) stay inside the border.
113
+ const CELL_MAX = 72;
114
+
115
+ function wrapCell(value: string, max: number): string[] {
116
+ const lines: string[] = [];
117
+ let cur = "";
118
+ for (const word of value.split(" ")) {
119
+ if (!cur) cur = word;
120
+ else if ([...cur].length + 1 + [...word].length <= max) cur += ` ${word}`;
121
+ else {
122
+ lines.push(cur);
123
+ cur = word;
124
+ }
125
+ }
126
+ lines.push(cur);
127
+ return lines;
128
+ }
129
+
130
+ type Row = [key: string, value: string, color?: string];
131
+
132
+ function table(t: ExtensionContext["ui"]["theme"], rows: Row[]): string {
133
+ const cells = rows.map(([k, v, c]) => [k, wrapCell(v, CELL_MAX), c] as const);
134
+ const w0 = Math.max(5, ...cells.map(([k]) => k.length));
135
+ const w1 = Math.max(7, ...cells.flatMap(([, lines]) => lines.map((l) => [...l].length)));
136
+ const paint = (text: string, color?: string) => (color ? t.fg(color as never, text) : text);
137
+ const bar = (l: string, m: string, r: string) => t.fg("dim", `${l}${"─".repeat(w0 + 2)}${m}${"─".repeat(w1 + 2)}${r}`);
138
+ const row = (k: string, lines: string[], color?: string) =>
139
+ lines.map((v, i) => `│ ${t.fg("dim", (i === 0 ? k : "").padEnd(w0))} │ ${paint(v + " ".repeat(w1 - [...v].length), color)} │`);
140
+
141
+ const out = [bar("┌", "┬", "┐"), ...row("Field", ["Details"])];
142
+ for (const [k, lines, color] of cells) out.push(bar("├", "┼", "┤"), ...row(k, lines, color));
143
+ out.push(bar("└", "┴", "┘"));
144
+ return out.join("\n");
145
+ }
146
+
147
+ const titleCase = (s: string) => (s ? s[0].toUpperCase() + s.slice(1).toLowerCase().replace(/_/g, " ") : s);
148
+
149
+ // Sorts last among footer statuses so the footer's "..." truncation cuts the PR title, not other statuses.
150
+ const STATUS_KEY = "zz-pr";
151
+ const REFRESH_MS = 60_000;
152
+ const TERMINAL_RETENTION_MS = 24 * 60 * 60 * 1000;
153
+ const FIELDS =
154
+ "number,title,state,isDraft,url,headRefName,baseRefName,reviewDecision,mergeable,author,statusCheckRollup,additions,deletions,changedFiles,closedAt,mergedAt,reviews,latestReviews,reviewRequests";
155
+
156
+ function checkResult(c: Check): "pass" | "fail" | "pending" | "skip" {
157
+ const v = (c.conclusion || c.state || c.status || "").toUpperCase();
158
+ if (["SUCCESS", "NEUTRAL"].includes(v)) return "pass";
159
+ if (["SKIPPED", "CANCELLED", "STALE"].includes(v)) return "skip";
160
+ if (["FAILURE", "ERROR", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"].includes(v)) return "fail";
161
+ return "pending";
162
+ }
163
+
164
+ function summarizeChecks(checks: Check[]) {
165
+ const counts = { pass: 0, fail: 0, pending: 0, skip: 0 };
166
+ for (const c of checks) counts[checkResult(c)]++;
167
+ return counts;
168
+ }
169
+
170
+ /** A merged or closed PR leaves the footer once the retention window is over. */
171
+ function stillWorthShowing(pr: PR, since: number): boolean {
172
+ if (pr.state === "OPEN") return true;
173
+ const at = Date.parse(pr.mergedAt || pr.closedAt || "");
174
+ const started = Number.isFinite(at) ? at : since;
175
+ return Date.now() - started < TERMINAL_RETENTION_MS;
176
+ }
177
+
178
+ export default function (pi: ExtensionAPI) {
179
+ let timer: ReturnType<typeof setTimeout> | undefined;
180
+ let inflight: AbortController | undefined;
181
+ let watcher: FSWatcher | undefined;
182
+ let watchedHead: string | undefined;
183
+ let terminalSince: number | undefined;
184
+ let generation = 0;
185
+ // The fallback lookup below costs two gh calls per refresh; the resolved number survives per branch.
186
+ let branchCache: { key: string; number: number } | undefined;
187
+
188
+ pi.registerEntryRenderer("pr-card", (entry, _opts, theme) => {
189
+ const { text, url, number, heading } = entry.data as { text: string; url?: string; number?: number; heading?: string };
190
+ let head = heading ? theme.bold(theme.fg("accent", heading)) : "";
191
+ if (url && head) head = head.replace(`PR #${number}`, link(`PR #${number}`, url));
192
+ const body = url ? text.replace(url, link(url, url)) : text;
193
+ return new Text(head ? `${head}\n${body}` : body, 1, 0);
194
+ });
195
+
196
+ async function ghJSON<T>(ctx: ExtensionContext, args: string[], signal?: AbortSignal): Promise<{ data?: T; error?: string }> {
197
+ let r: Awaited<ReturnType<typeof pi.exec>>;
198
+ try {
199
+ r = await pi.exec("gh", args, { cwd: ctx.cwd, timeout: 15000, signal });
200
+ } catch (e) {
201
+ return { error: String(e) };
202
+ }
203
+ if (r.code !== 0) return { error: (r.stderr || r.stdout).trim() || `gh exited with code ${r.code}` };
204
+ if (r.truncated) return { error: "gh output too large" };
205
+ try {
206
+ return { data: JSON.parse(r.stdout) as T };
207
+ } catch (e) {
208
+ return { error: `could not parse gh output: ${e}` };
209
+ }
210
+ }
211
+
212
+ async function fetchPR(ctx: ExtensionContext, signal?: AbortSignal): Promise<{ pr?: PR; error?: string }> {
213
+ const direct = await ghJSON<PR>(ctx, ["pr", "view", "--json", FIELDS], signal);
214
+ if (direct.data || !direct.error?.includes("no pull requests found")) return { pr: direct.data, error: direct.error };
215
+ // gh only matches the branch's tracked remote (e.g. chmouel:branch); the PR may come from another fork
216
+ // or the base repo itself, so search by branch name regardless of head owner.
217
+ let b: Awaited<ReturnType<typeof pi.exec>>;
218
+ try {
219
+ b = await pi.exec("git", ["branch", "--show-current"], { cwd: ctx.cwd, timeout: 5000, signal });
220
+ } catch {
221
+ return { error: direct.error };
222
+ }
223
+ const branch = b.stdout.trim();
224
+ if (b.code !== 0 || !branch) return { error: direct.error };
225
+ const cacheKey = `${ctx.cwd}\u0000${branch}`;
226
+ if (branchCache?.key === cacheKey) {
227
+ const cached = await ghJSON<PR>(ctx, ["pr", "view", String(branchCache.number), "--json", FIELDS], signal);
228
+ if (cached.data) return { pr: cached.data };
229
+ branchCache = undefined;
230
+ }
231
+ for (const state of ["open", "all"]) {
232
+ const list = await ghJSON<{ number: number }[]>(
233
+ ctx,
234
+ ["pr", "list", "--head", branch, "--state", state, "--limit", "1", "--json", "number"],
235
+ signal,
236
+ );
237
+ const num = list.data?.[0]?.number;
238
+ if (num) {
239
+ const v = await ghJSON<PR>(ctx, ["pr", "view", String(num), "--json", FIELDS], signal);
240
+ if (v.data) branchCache = { key: cacheKey, number: num };
241
+ return { pr: v.data, error: v.error };
242
+ }
243
+ }
244
+ return { error: direct.error };
245
+ }
246
+
247
+ function failureStatus(ctx: ExtensionContext, error: string | undefined) {
248
+ const t = ctx.ui.theme;
249
+ const msg = (error || "").toLowerCase();
250
+ if (!msg) {
251
+ ctx.ui.setStatus(STATUS_KEY, undefined);
252
+ } else if (msg.includes("no pull requests found") || msg.includes("no open pull request")) {
253
+ ctx.ui.setStatus(STATUS_KEY, undefined);
254
+ } else if (/enoent|not found|no such file|executable/.test(msg)) {
255
+ ctx.ui.setStatus(STATUS_KEY, t.fg("error", "gh missing"));
256
+ } else if (/auth|login|token|credential/.test(msg)) {
257
+ ctx.ui.setStatus(STATUS_KEY, t.fg("error", "gh not logged in"));
258
+ } else {
259
+ ctx.ui.setStatus(STATUS_KEY, t.fg("warning", "PR unavailable"));
260
+ }
261
+ }
262
+
263
+ async function refreshStatus(ctx: ExtensionContext) {
264
+ if (!ctx.hasUI) return;
265
+ inflight?.abort();
266
+ const controller = new AbortController();
267
+ inflight = controller;
268
+ const { pr, error } = await fetchPR(ctx, controller.signal);
269
+ if (controller.signal.aborted) return;
270
+
271
+ if (!pr) {
272
+ terminalSince = undefined;
273
+ failureStatus(ctx, error);
274
+ return;
275
+ }
276
+
277
+ if (pr.state === "OPEN") terminalSince = undefined;
278
+ else if (terminalSince === undefined) terminalSince = Date.now();
279
+ if (!stillWorthShowing(pr, terminalSince ?? Date.now())) {
280
+ ctx.ui.setStatus(STATUS_KEY, undefined);
281
+ return;
282
+ }
283
+
284
+ const t = ctx.ui.theme;
285
+ const checks = pr.statusCheckRollup ?? [];
286
+ const c = summarizeChecks(checks);
287
+ const icon = c.fail ? t.fg("error", "✗") : c.pending ? t.fg("warning", "●") : t.fg("success", "✓");
288
+ const label = pr.isDraft ? "draft " : pr.state !== "OPEN" ? `${pr.state.toLowerCase()} ` : "";
289
+ const sepDot = t.fg("dim", " · ");
290
+ const parts: string[] = [`${icon} ${t.fg("dim", label)}${link(t.fg("accent", `PR #${pr.number}`), pr.url)}`];
291
+ if (checks.length) {
292
+ const ciText = c.fail ? `${c.fail} failing` : c.pending ? `${c.pending} pending` : `${checks.length} passing`;
293
+ parts.push(t.fg(c.fail ? "error" : c.pending ? "warning" : "dim", ciText));
294
+ }
295
+ if (pr.reviewDecision === "APPROVED") parts.push(t.fg("success", "approved"));
296
+ else if (pr.reviewDecision === "CHANGES_REQUESTED") parts.push(t.fg("error", "changes requested"));
297
+ else if (pr.reviewDecision === "REVIEW_REQUIRED") parts.push(t.fg("dim", "review required"));
298
+ const revs = reviewers(pr);
299
+ if (revs.length)
300
+ parts.push(revs.map((r) => t.fg(REVIEW_COLOR[r.state], `${REVIEW_ICON[r.state]} ${r.name}`)).join(" "));
301
+ if (pr.mergeable === "CONFLICTING") parts.push(t.fg("error", "conflicts"));
302
+ parts.push(`${t.fg("success", `+${pr.additions}`)}${t.fg("error", `-${pr.deletions}`)}`);
303
+ parts.push(plain(pr.title));
304
+ ctx.ui.setStatus(STATUS_KEY, parts.join(sepDot));
305
+ }
306
+
307
+ function schedule(ctx: ExtensionContext, gen = generation) {
308
+ if (timer) clearTimeout(timer);
309
+ timer = setTimeout(() => {
310
+ if (gen !== generation) return;
311
+ void refreshStatus(ctx)
312
+ .catch(() => {})
313
+ .finally(() => {
314
+ if (gen === generation) schedule(ctx, gen);
315
+ });
316
+ }, REFRESH_MS);
317
+ timer.unref?.();
318
+ }
319
+
320
+ function stopTimers() {
321
+ generation++;
322
+ if (timer) clearTimeout(timer);
323
+ timer = undefined;
324
+ watcher?.close();
325
+ watcher = undefined;
326
+ watchedHead = undefined;
327
+ inflight?.abort();
328
+ inflight = undefined;
329
+ }
330
+
331
+ /** Refreshes as soon as the checked-out branch changes, without waiting for the poll. */
332
+ async function watchHead(ctx: ExtensionContext) {
333
+ let r: Awaited<ReturnType<typeof pi.exec>>;
334
+ try {
335
+ r = await pi.exec("git", ["rev-parse", "--git-path", "HEAD"], { cwd: ctx.cwd, timeout: 5000 });
336
+ } catch {
337
+ return;
338
+ }
339
+ if (r.code !== 0) return;
340
+ const head = resolve(ctx.cwd, r.stdout.trim());
341
+ if (head === watchedHead) return;
342
+ watcher?.close();
343
+ watchedHead = head;
344
+ try {
345
+ let debounce: ReturnType<typeof setTimeout> | undefined;
346
+ watcher = watch(head, () => {
347
+ if (debounce) clearTimeout(debounce);
348
+ debounce = setTimeout(() => {
349
+ refreshStatus(ctx).catch(() => {});
350
+ }, 300);
351
+ debounce.unref?.();
352
+ });
353
+ watcher.on("error", () => {
354
+ watcher?.close();
355
+ watcher = undefined;
356
+ watchedHead = undefined;
357
+ });
358
+ watcher.unref?.();
359
+ } catch {
360
+ watcher = undefined;
361
+ watchedHead = undefined;
362
+ }
363
+ }
364
+
365
+ pi.on("session_start", async (_e, ctx) => {
366
+ stopTimers();
367
+ terminalSince = undefined;
368
+ branchCache = undefined;
369
+ await watchHead(ctx);
370
+ refreshStatus(ctx).catch(() => {});
371
+ schedule(ctx);
372
+ });
373
+
374
+ pi.on("agent_end", async (_e, ctx) => {
375
+ refreshStatus(ctx).catch(() => {});
376
+ });
377
+
378
+ pi.on("session_shutdown", async () => {
379
+ stopTimers();
380
+ });
381
+
382
+ pi.registerCommand("pr", {
383
+ description: "Show the GitHub PR for the current branch (open | checks | refresh)",
384
+ getArgumentCompletions: (prefix: string) =>
385
+ ["open", "checks", "refresh"]
386
+ .filter((s) => s.startsWith(prefix.trim()))
387
+ .map((s) => ({ value: s, label: s })),
388
+ handler: async (args, ctx) => {
389
+ const t = ctx.ui.theme;
390
+ const sub = (args || "").trim();
391
+
392
+ if (sub === "open") {
393
+ const { pr, error } = await fetchPR(ctx);
394
+ if (!pr) return ctx.ui.notify(error || "No PR for the current branch", "error");
395
+ let r: Awaited<ReturnType<typeof pi.exec>>;
396
+ try {
397
+ r = await pi.exec("gh", ["pr", "view", pr.url, "--web"], { cwd: ctx.cwd, timeout: 15000 });
398
+ } catch (e) {
399
+ return ctx.ui.notify(String(e), "error");
400
+ }
401
+ if (r.code !== 0) ctx.ui.notify((r.stderr || "could not open browser").trim(), "error");
402
+ return;
403
+ }
404
+
405
+ const { pr, error } = await fetchPR(ctx);
406
+ if (!pr) {
407
+ failureStatus(ctx, error);
408
+ ctx.ui.notify(error?.includes("no pull requests found") ? "No PR for the current branch" : `gh: ${error}`, "warning");
409
+ return;
410
+ }
411
+ await refreshStatus(ctx);
412
+ if (sub === "refresh") return;
413
+
414
+ const checks = pr.statusCheckRollup ?? [];
415
+ const c = summarizeChecks(checks);
416
+ const lines: string[] = [];
417
+
418
+ if (sub === "checks") {
419
+ const icon = { pass: t.fg("success", "✓"), fail: t.fg("error", "✗"), pending: t.fg("warning", "●"), skip: t.fg("dim", "-") };
420
+ for (const ch of checks) lines.push(` ${icon[checkResult(ch)]} ${ch.name || ch.context}`);
421
+ if (!checks.length) lines.push(" (no checks)");
422
+ } else {
423
+ const revs = reviewers(pr);
424
+ let reviews = revs.length ? revs.map((r) => `${REVIEW_ICON[r.state]} ${r.name} (${r.state})`).join(", ") : "None";
425
+ if (pr.reviewDecision) reviews += ` · ${titleCase(pr.reviewDecision)}`;
426
+ let ci: string;
427
+ if (!checks.length) ci = "No checks";
428
+ else if (c.pass === checks.length) ci = `All ${checks.length} passing`;
429
+ else {
430
+ const parts = [`${c.pass} passing`];
431
+ if (c.fail) parts.push(`${c.fail} failing`);
432
+ if (c.pending) parts.push(`${c.pending} pending`);
433
+ if (c.skip) parts.push(`${c.skip} skipped`);
434
+ ci = parts.join(", ");
435
+ }
436
+ const stateColor = pr.isDraft ? "warning" : pr.state === "OPEN" ? "success" : pr.state === "MERGED" ? "accent" : "error";
437
+ const ciColor = !checks.length ? "dim" : c.fail ? "error" : c.pending ? "warning" : "success";
438
+ const reviewColor = revs.some((r) => r.state === "changes")
439
+ ? "error"
440
+ : revs.length && revs.every((r) => r.state === "approved")
441
+ ? "success"
442
+ : "dim";
443
+ const mergeColor = pr.mergeable === "CONFLICTING" ? "error" : pr.mergeable === "MERGEABLE" ? "success" : "warning";
444
+ const rows: Row[] = [
445
+ ["State", pr.isDraft ? "Draft" : titleCase(pr.state), stateColor],
446
+ ["Branch", `\ue0a0 ${pr.headRefName} → ${pr.baseRefName}`, "accent"],
447
+ ["URL", pr.url, "accent"],
448
+ ["Changes", `+${pr.additions} / -${pr.deletions} across ${pr.changedFiles} files`],
449
+ ["Author", `@${pr.author?.login}`],
450
+ ["Reviews", reviews, reviewColor],
451
+ ["Mergeable", titleCase(pr.mergeable), mergeColor],
452
+ ["CI Checks", ci, ciColor],
453
+ ];
454
+ if (c.fail) {
455
+ const failed = checks.filter((ch) => checkResult(ch) === "fail").map((ch) => ch.name || ch.context || "?");
456
+ rows.push(["Failed", failed.join(", "), "error"]);
457
+ }
458
+ lines.push("", table(t, rows));
459
+ }
460
+ const heading = sub === "checks" ? `Checks for PR #${pr.number}` : `PR #${pr.number} — ${plain(pr.title)}`;
461
+ pi.appendEntry("pr-card", { text: lines.join("\n"), url: pr.url, number: pr.number, heading });
462
+ },
463
+ });
464
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@chmouel/pi-pr",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.1",
4
+ "description": "Pi extension: /pr command and footer status for the GitHub pull request of the current branch",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "github",
9
+ "pull-request",
10
+ "gh"
11
+ ],
12
+ "license": "Apache-2.0",
13
+ "author": "Chmouel Boudjnah <chmouel@chmouel.com>",
14
+ "homepage": "https://github.com/chmouel/pi-pr",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/chmouel/pi-pr.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/chmouel/pi-pr/issues"
21
+ },
22
+ "files": [
23
+ "extensions",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "pi": {
28
+ "extensions": [
29
+ "./extensions/pr.ts"
30
+ ]
31
+ },
32
+ "peerDependencies": {
33
+ "@earendil-works/pi-coding-agent": "*",
34
+ "@earendil-works/pi-tui": "*"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ }
39
+ }