omp-pr-tracker 0.0.0-stage → 1.0.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +48 -2
  3. package/package.json +17 -5
  4. package/pr-tracker.ts +335 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ryok90
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # omp-pr-tracker
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
+ An [oh-my-pi (omp)](https://github.com/can1357/oh-my-pi) extension that lists the GitHub pull requests opened or pushed to during the current session, in a widget above the prompt.
4
+
5
+ ## What it detects
6
+
7
+ - **Created PRs**: `gh pr create` (via `bash` or `eval`), and the `github` tool's `pr_create` op (directly or through `write xd://github`).
8
+ - **Pushes**: `git push` output (`To <remote>` + ref lines) on GitHub remotes, resolved to the branch's PR with `gh pr list --head`; and the `github` tool's `pr_push` op.
9
+ - **Subagents**: PRs found by in-process subagents show up in the main session's list.
10
+
11
+ Tracked PRs are saved as session entries, so they survive resume and rewinds. Each row shows state (`OPEN`, `DRAFT`, `MERGED`, …) and title.
12
+
13
+ ## Commands
14
+
15
+ | Command | Effect |
16
+ | --- | --- |
17
+ | `/prs` | Refresh title/state of every tracked PR |
18
+ | `/prs add <url> [url…]` | Track PRs the detector missed |
19
+ | `/prs toggle` | Hide or show the list |
20
+
21
+ ## Requirements
22
+
23
+ - omp
24
+ - [`gh`](https://cli.github.com/) installed and authenticated. Lookups that fail only log a warning.
25
+ - GitHub only (including Enterprise hosts reachable by `gh`).
26
+
27
+ ## Install
28
+
29
+ ```sh
30
+ omp plugin install github:ryok90/omp-pr-tracker
31
+ ```
32
+
33
+ Restart omp afterwards. Upgrade with `omp plugin upgrade omp-pr-tracker`; turn it off with `omp plugin disable omp-pr-tracker`.
34
+
35
+ For local development, clone and link instead:
36
+
37
+ ```sh
38
+ git clone https://github.com/ryok90/omp-pr-tracker.git
39
+ omp plugin link ./omp-pr-tracker
40
+ ```
41
+
42
+ ## Notes
43
+
44
+ - The divider above the list follows the prompt's border colour by lazily importing an internal omp module. If a future omp moves it, the divider falls back to the theme's `border` colour; nothing else breaks.
45
+ - Session entries use the type `pr-tracker.opened`; it is kept stable for compatibility with existing sessions.
46
+
47
+ ## License
48
+
49
+ MIT
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
- "name": "omp-pr-tracker",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "omp-pr-tracker",
3
+ "version": "1.0.0",
4
+ "description": "omp extension: track GitHub PRs opened or pushed to during a session",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "ryok90",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ryok90/omp-pr-tracker.git"
11
+ },
12
+ "homepage": "https://github.com/ryok90/omp-pr-tracker#readme",
13
+ "keywords": ["omp", "oh-my-pi", "omp-plugin", "github", "pull-requests"],
14
+ "files": ["pr-tracker.ts", "README.md", "LICENSE"],
15
+ "omp": {
16
+ "extensions": ["./pr-tracker.ts"]
17
+ }
18
+ }
package/pr-tracker.ts ADDED
@@ -0,0 +1,335 @@
1
+ /**
2
+ * pr-tracker: lists the pull requests opened or pushed to during the current omp session.
3
+ *
4
+ * Detects PR creation from tool results (`gh pr create` via bash/eval, the `github`
5
+ * tool's `pr_create` op, directly or through `write xd://github`) and pushes (`git push`
6
+ * via bash/eval, resolved to the branch's PR with `gh pr list --head`; the `github` tool's
7
+ * `pr_push` op). Each PR is persisted as a session entry so it survives resume, and shown
8
+ * in a widget below the editor. `/prs` refreshes title/state from GitHub; `/prs toggle`
9
+ * hides/shows it.
10
+ */
11
+ import type { ExtensionAPI, ExtensionContext, ToolResultEvent } from "@oh-my-pi/pi-coding-agent";
12
+
13
+ // Name kept from when only created PRs were tracked: existing (and backfilled) sessions use it.
14
+ const ENTRY_TYPE = "pr-tracker.opened";
15
+ const WIDGET_KEY = "pr-tracker";
16
+ const MAX_ROWS = 10;
17
+ const PR_URL = /https:\/\/[^\s/]+\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
18
+ const GH_PR_CREATE = /\bgh\s+pr\s+create\b/;
19
+ const GITHUB_PR_CREATE_OP = /["']?op["']?\s*:\s*["']pr_create["']/;
20
+ const GIT_PUSH = /\bgit\b[^\n|;&]*\bpush\b/;
21
+ const GITHUB_PR_PUSH_OP = /["']?op["']?\s*:\s*["']pr_push["']/;
22
+ const PUSH_TARGET = /^To\s+(\S+)/;
23
+ // ` * [new branch] a -> b`, ` 1a2b..3c4d a -> b`, ` + 1a2b...3c4d a -> b (forced update)`
24
+ const PUSHED_REF = /^\s*[*+ ]?\s*(?:\[new branch\]|[0-9a-f]+\.\.\.?[0-9a-f]+)\s+\S+\s+->\s+(\S+)/;
25
+ const GITHUB_REMOTE = /github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/;
26
+
27
+ interface PushedBranch {
28
+ repo: string;
29
+ branch: string;
30
+ }
31
+
32
+ interface TrackedPr {
33
+ url: string;
34
+ openedAt: number;
35
+ }
36
+
37
+ interface PrMetadata {
38
+ title: string;
39
+ state: string;
40
+ isDraft: boolean;
41
+ }
42
+
43
+ // Module scope is shared between the main session and its in-process subagents
44
+ // (factories are rebound per session), so subagent detections reach the main widget here.
45
+ const mainSessionSinks = new Set<(url: string) => void>();
46
+
47
+ function isPrCreateCall(toolName: string, input: Record<string, unknown>): boolean {
48
+ switch (toolName) {
49
+ case "bash":
50
+ return GH_PR_CREATE.test(String(input.command ?? ""));
51
+ case "eval": {
52
+ const code = String(input.code ?? "");
53
+ return GH_PR_CREATE.test(code) || GITHUB_PR_CREATE_OP.test(code);
54
+ }
55
+ case "github":
56
+ return input.op === "pr_create";
57
+ case "write":
58
+ return String(input.path ?? "").startsWith("xd://github") && GITHUB_PR_CREATE_OP.test(String(input.content ?? ""));
59
+ default:
60
+ return false;
61
+ }
62
+ }
63
+
64
+ function resultText(event: ToolResultEvent): string {
65
+ return event.content.map(part => (part.type === "text" ? part.text : "")).join("\n");
66
+ }
67
+
68
+ function createdPrUrls(event: ToolResultEvent): string[] {
69
+ // No `isError` gate: a compound command (`gh pr create … ; pkill …`) can exit non-zero after the
70
+ // PR was opened. A URL in a create call's output is a real PR, even gh's "already exists" one.
71
+ if (!isPrCreateCall(event.toolName, event.input)) return [];
72
+ // One call can open several PRs (e.g. `gh pr create` per branch in a loop), so keep every URL.
73
+ return [...new Set(resultText(event).match(PR_URL))];
74
+ }
75
+
76
+ function isPushCall(toolName: string, input: Record<string, unknown>): boolean {
77
+ switch (toolName) {
78
+ case "bash":
79
+ return GIT_PUSH.test(String(input.command ?? ""));
80
+ case "eval":
81
+ return GIT_PUSH.test(String(input.code ?? ""));
82
+ default:
83
+ return false;
84
+ }
85
+ }
86
+
87
+ function isPrPushCall(toolName: string, input: Record<string, unknown>): boolean {
88
+ if (toolName === "github") return input.op === "pr_push";
89
+ if (toolName === "write") {
90
+ return String(input.path ?? "").startsWith("xd://github") && GITHUB_PR_PUSH_OP.test(String(input.content ?? ""));
91
+ }
92
+ return toolName === "eval" && GITHUB_PR_PUSH_OP.test(String(input.code ?? ""));
93
+ }
94
+
95
+ /** Branches updated on GitHub remotes, read from git's own push report (`To <remote>` + ref lines). */
96
+ function pushedBranches(text: string): PushedBranch[] {
97
+ const found = new Map<string, PushedBranch>();
98
+ let repo: string | undefined;
99
+ for (const line of text.split("\n")) {
100
+ const target = PUSH_TARGET.exec(line);
101
+ if (target) {
102
+ const remote = GITHUB_REMOTE.exec(target[1]);
103
+ repo = remote ? `${remote[1]}/${remote[2]}` : undefined;
104
+ continue;
105
+ }
106
+ const ref = repo ? PUSHED_REF.exec(line) : null;
107
+ if (!repo || !ref) continue;
108
+ const branch = ref[1].replace(/^refs\/heads\//, "");
109
+ found.set(`${repo}:${branch}`, { repo, branch });
110
+ }
111
+ return [...found.values()];
112
+ }
113
+
114
+ function loadTrackedPrs(ctx: ExtensionContext): TrackedPr[] {
115
+ // All entries, not just the active branch: a PR stays open on GitHub after a rewind.
116
+ const byUrl = new Map<string, TrackedPr>();
117
+ for (const entry of ctx.sessionManager.getEntries()) {
118
+ if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE) continue;
119
+ const pr = entry.data as TrackedPr | undefined;
120
+ if (pr?.url && !byUrl.has(pr.url)) byUrl.set(pr.url, pr);
121
+ }
122
+ return [...byUrl.values()];
123
+ }
124
+
125
+ interface ComposerBorderColorInput {
126
+ sessionName?: string;
127
+ thinkingLevel?: string;
128
+ }
129
+
130
+ // omp's own composer border rule: a theme key from the thinking level, or a hex derived from the
131
+ // session name. Internal module, so it's loaded lazily and the widget falls back to "border" if
132
+ // a later omp moves it, instead of the whole extension failing to load.
133
+ let composerBorderColor: ((input: ComposerBorderColorInput) => string) | undefined;
134
+ void import("@oh-my-pi/pi-coding-agent/modes/interactive/border-color")
135
+ .then((mod: object) => {
136
+ if ("composerBorderColor" in mod && typeof mod.composerBorderColor === "function") {
137
+ composerBorderColor = mod.composerBorderColor as (input: ComposerBorderColorInput) => string;
138
+ }
139
+ })
140
+ .catch(() => undefined);
141
+
142
+ function paintHex(hex: string, text: string): string {
143
+ const value = Number.parseInt(hex.slice(1), 16);
144
+ return `\x1b[38;2;${(value >> 16) & 255};${(value >> 8) & 255};${value & 255}m${text}\x1b[39m`;
145
+ }
146
+
147
+ export default function prTracker(pi: ExtensionAPI): void {
148
+ let prs: TrackedPr[] = [];
149
+ const metadata = new Map<string, PrMetadata>();
150
+ let visible = true;
151
+ let mainCtx: ExtensionContext | undefined;
152
+
153
+ function stateLabel(ctx: ExtensionContext, meta: PrMetadata | undefined): string {
154
+ const theme = ctx.ui.theme;
155
+ if (!meta) return theme.fg("dim", "… ");
156
+ if (meta.isDraft && meta.state === "OPEN") return theme.fg("warning", "DRAFT ");
157
+ switch (meta.state) {
158
+ case "OPEN":
159
+ return theme.fg("success", "OPEN ");
160
+ case "MERGED":
161
+ return theme.fg("accent", "MERGED");
162
+ default:
163
+ return theme.fg("muted", meta.state.padEnd(6));
164
+ }
165
+ }
166
+
167
+ function render(): void {
168
+ const ctx = mainCtx;
169
+ if (!ctx?.hasUI) return;
170
+ if (!visible || prs.length === 0) {
171
+ ctx.ui.setWidget(WIDGET_KEY, undefined);
172
+ return;
173
+ }
174
+ const theme = ctx.ui.theme;
175
+ const shown = prs.slice(0, MAX_ROWS);
176
+ const lines = [
177
+ theme.fg("muted", `PRs of this session (${prs.length})`),
178
+ ...shown.map(pr => {
179
+ const meta = metadata.get(pr.url);
180
+ const title = meta ? ` ${theme.fg("dim", meta.title)}` : "";
181
+ return `${stateLabel(ctx, meta)} ${pr.url}${title}`;
182
+ }),
183
+ ];
184
+ if (prs.length > shown.length) lines.push(theme.fg("dim", `… ${prs.length - shown.length} more (/prs)`));
185
+ // Docked above the prompt; the leading rule separates the list from the transcript above it.
186
+ // omp takes a string array or a factory; the factory returns a `{ render(width) }` rows object
187
+ // so the rule can span the full width. A bare rows object (no factory) crashes the TUI.
188
+ const rule = theme.symbols.box.horizontal;
189
+ // Colour is resolved per frame so it follows the prompt's when the session is renamed or the
190
+ // thinking level changes. Bash/python/vim input modes recolour the prompt but aren't visible here.
191
+ const paintRule = (text: string): string => {
192
+ const color = composerBorderColor?.({ sessionName: pi.getSessionName(), thinkingLevel: pi.getThinkingLevel() });
193
+ if (color?.startsWith("#")) return paintHex(color, text);
194
+ try {
195
+ return theme.fg((color ?? "border") as Parameters<typeof theme.fg>[0], text);
196
+ } catch {
197
+ return theme.fg("border", text);
198
+ }
199
+ };
200
+ ctx.ui.setWidget(
201
+ WIDGET_KEY,
202
+ // Rows indented one column, like the prompt's own padding; the rule stays full width.
203
+ () => ({ render: (width: number): string[] => [paintRule(rule.repeat(width)), ...lines.map(line => ` ${line}`)] }),
204
+ { placement: "aboveEditor" },
205
+ );
206
+ }
207
+
208
+ async function fetchMetadata(url: string): Promise<void> {
209
+ try {
210
+ const result = await pi.exec("gh", ["pr", "view", url, "--json", "title,state,isDraft"], { timeout: 15_000 });
211
+ if (result.code !== 0) {
212
+ pi.logger.warn("pr-tracker: gh pr view failed", { url, stderr: result.stderr });
213
+ return;
214
+ }
215
+ metadata.set(url, JSON.parse(result.stdout) as PrMetadata);
216
+ } catch (error) {
217
+ pi.logger.warn("pr-tracker: metadata fetch failed", { url, error: String(error) });
218
+ }
219
+ }
220
+
221
+ async function refreshAll(): Promise<void> {
222
+ await Promise.all(prs.map(pr => fetchMetadata(pr.url)));
223
+ render();
224
+ }
225
+
226
+ function record(url: string): void {
227
+ if (prs.some(pr => pr.url === url)) return;
228
+ const pr: TrackedPr = { url, openedAt: Date.now() };
229
+ prs.push(pr);
230
+ pi.appendEntry(ENTRY_TYPE, pr);
231
+ render();
232
+ void fetchMetadata(url).then(render);
233
+ }
234
+
235
+ function restore(ctx: ExtensionContext): void {
236
+ if (ctx.agent.kind !== "main") return;
237
+ // Re-registered on every restore: switch/branch/tree can follow a shutdown without a new start.
238
+ mainSessionSinks.add(record);
239
+ mainCtx = ctx;
240
+ prs = loadTrackedPrs(ctx);
241
+ render();
242
+ void refreshAll();
243
+ }
244
+
245
+ pi.on("session_start", (_event, ctx) => restore(ctx));
246
+ pi.on("session_switch", (_event, ctx) => restore(ctx));
247
+ pi.on("session_branch", (_event, ctx) => restore(ctx));
248
+ pi.on("session_tree", (_event, ctx) => restore(ctx));
249
+ pi.on("session_shutdown", () => {
250
+ mainSessionSinks.delete(record);
251
+ });
252
+
253
+ async function prForBranch({ repo, branch }: PushedBranch): Promise<string | undefined> {
254
+ try {
255
+ const result = await pi.exec(
256
+ "gh",
257
+ ["pr", "list", "--repo", repo, "--head", branch, "--state", "all", "--json", "url", "--limit", "1"],
258
+ { timeout: 15_000 },
259
+ );
260
+ if (result.code !== 0) {
261
+ pi.logger.warn("pr-tracker: gh pr list failed", { repo, branch, stderr: result.stderr });
262
+ return undefined;
263
+ }
264
+ return (JSON.parse(result.stdout) as { url: string }[])[0]?.url;
265
+ } catch (error) {
266
+ pi.logger.warn("pr-tracker: PR lookup failed", { repo, branch, error: String(error) });
267
+ return undefined;
268
+ }
269
+ }
270
+
271
+ function deliver(url: string, ctx: ExtensionContext): void {
272
+ if (ctx.agent.kind === "main") record(url);
273
+ else for (const sink of mainSessionSinks) sink(url);
274
+ }
275
+
276
+ pi.on("tool_result", (event, ctx) => {
277
+ for (const url of createdPrUrls(event)) deliver(url, ctx);
278
+ if (event.isError) return;
279
+ if (isPrPushCall(event.toolName, event.input)) {
280
+ for (const url of new Set(resultText(event).match(PR_URL))) deliver(url, ctx);
281
+ }
282
+ if (!isPushCall(event.toolName, event.input)) return;
283
+ // Lookup runs detached so the tool result isn't held up by `gh`; a push before the PR
284
+ // exists finds nothing, and the later `gh pr create` records it instead.
285
+ for (const pushed of pushedBranches(resultText(event))) {
286
+ void prForBranch(pushed).then(url => {
287
+ if (url) deliver(url, ctx);
288
+ });
289
+ }
290
+ });
291
+
292
+ const SUBCOMMANDS = [
293
+ { value: "add", label: "add", description: "Track PR URLs this session missed: /prs add <url> [url…]" },
294
+ { value: "toggle", label: "toggle", description: "Hide or show the PR list" },
295
+ ];
296
+
297
+ pi.registerCommand("prs", {
298
+ description: "Refresh the PRs of this session; `/prs add <url>` tracks a PR; `/prs toggle` hides or shows the list",
299
+ getArgumentCompletions: prefix => {
300
+ const matches = SUBCOMMANDS.filter(sub => sub.value.startsWith(prefix));
301
+ return matches.length > 0 ? matches : null;
302
+ },
303
+ handler: async (args, ctx) => {
304
+ const [sub = "", ...rest] = args.trim().split(/\s+/);
305
+ if (sub === "toggle") {
306
+ visible = !visible;
307
+ render();
308
+ return;
309
+ }
310
+ if (sub === "add") {
311
+ const urls = [...new Set(rest.join(" ").match(PR_URL))];
312
+ if (urls.length === 0) {
313
+ ctx.ui.notify("Usage: /prs add https://github.com/<owner>/<repo>/pull/<n> [more URLs]", "warning");
314
+ return;
315
+ }
316
+ const added = urls.filter(url => !prs.some(pr => pr.url === url));
317
+ visible = true;
318
+ for (const url of added) record(url);
319
+ const skipped = urls.length - added.length;
320
+ ctx.ui.notify(
321
+ `Added ${added.length} PR${added.length === 1 ? "" : "s"}${skipped > 0 ? `, ${skipped} already tracked` : ""}`,
322
+ "info",
323
+ );
324
+ return;
325
+ }
326
+ if (prs.length === 0) {
327
+ ctx.ui.notify("No PRs in this session yet", "info");
328
+ return;
329
+ }
330
+ visible = true;
331
+ await refreshAll();
332
+ ctx.ui.notify(`Refreshed ${prs.length} PR${prs.length === 1 ? "" : "s"}`, "info");
333
+ },
334
+ });
335
+ }