Turns #123 in Claude's replies into a clickable link to that PR, in the repo the conversation is about.

A Claude Code plugin marketplace with my mods.
claude plugin marketplace add AydinHassan/claude-mods
claude plugin install pr-links@aydin-mods
Turns #123 in Claude's replies into a clickable link to that pull request on GitHub.
Each bare #123 is linked to the repo the conversation was about when the reply was written, taken from the transcript up to that reply:
gh pr create);--repo/-R owner/repo, GitHub MCP owner/repo arguments, a github.com/owner/repo/pull|issues/N URL, a cd or git -C directory in a Bash command, or the directory of a file read or edited (directories go through git remote get-url origin);owner/repo#123 is always linked to owner/repo. Links point at /pull/123, which GitHub redirects to the issue when the number belongs to an issue.
Limits:
gh pr list result, is left as it is.#333 outside code is linked like a PR number.hooks/register.ts 99 lines1import type { EngineInterface as Engine, Register } from 'claude-code'
2import { bareNumbers, linkify, repoUrlFromRemote, type Signal, signalsFrom } from './linkify'
3
4const MAX_DIR_LOOKUPS = 20
5const MAX_REMEMBERED = 500
6
7const remotes = new Map<string, Promise<string | undefined>>()
8const linked = new Map<string, Promise<string>>()
9
10function remoteOf($: Engine, dir: string, cwd: string): Promise<string | undefined> {
11 let remote = remotes.get(dir)
12
13 if (remote === undefined) {
14 remote = $.process
15 .run(['sh', '-c', 'p=$1; case $p in "~"*) p="$HOME${p#"~"}";; esac; git -C "$p" remote get-url origin', 'sh', dir], {
16 cwd,
17 })
18 .then(ran => (ran.exitCode === 0 ? repoUrlFromRemote(ran.stdout) : undefined))
19 .catch(() => undefined)
20 remotes.set(dir, remote)
21 }
22
23 return remote
24}
25
26/**
27 * The newest repo the signals point at, else the session directory's remote.
28 */
29async function latestRepo($: Engine, signals: Signal[], cwd: string): Promise<string | undefined> {
30 let lookups = 0
31
32 for (const signal of signals) {
33 if ('repoUrl' in signal) {
34 return signal.repoUrl
35 }
36
37 if (lookups++ < MAX_DIR_LOOKUPS) {
38 const remote = await remoteOf($, signal.dir, cwd)
39
40 if (remote !== undefined) {
41 return remote
42 }
43 }
44 }
45
46 return remoteOf($, cwd, cwd)
47}
48
49/**
50 * Links each bare `#N` to the repo the conversation was about when the block
51 * was written: a PR or issue URL seen with that number, else the newest repo
52 * the transcript points at, else the session directory's remote.
53 */
54async function resolve($: Engine, text: string): Promise<string> {
55 const cwd = await $.session.cwd()
56 const messages = await $.session.messages().catch(() => [])
57 const probe = text.trim().slice(0, 200)
58 const at = messages.findLastIndex(message => message.role === 'assistant' && message.text.includes(probe))
59 const signals = signalsFrom(at === -1 ? messages : messages.slice(0, at + 1)).reverse()
60 const urls = new Map<string, string>()
61 let latest: Promise<string | undefined> | undefined
62
63 for (const number of bareNumbers(text)) {
64 const exact = signals.find(signal => 'repoUrl' in signal && signal.number === number)
65 const url = exact !== undefined && 'repoUrl' in exact ? exact.repoUrl : await (latest ??= latestRepo($, signals, cwd))
66
67 if (url !== undefined) {
68 urls.set(number, url)
69 }
70 }
71
72 return linkify(text, number => urls.get(number))
73}
74
75function linkedText($: Engine, text: string): Promise<string> {
76 let rewritten = linked.get(text)
77
78 if (rewritten === undefined) {
79 rewritten = resolve($, text).catch(() => text)
80 linked.set(text, rewritten)
81
82 if (linked.size > MAX_REMEMBERED) {
83 linked.delete(linked.keys().next().value!)
84 }
85 }
86
87 return rewritten
88}
89
90export const register: Register = on => {
91 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
92 if (!/#\d/.test(e.props.text)) {
93 return next(e)
94 }
95
96 return next({ ...e, props: { ...e.props, text: await linkedText($, e.props.text) } })
97 })
98}
99hooks/linkify.ts 134 lines1import type { SessionMessage } from 'claude-code'
2
3// Code fences, inline code, existing markdown links and bare URLs are matched
4// first so a number inside them is left alone. `owner/repo#12` names its repo.
5const PATTERN =
6 /(```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|`[^`\n]*`|\[[^\]\n]*\]\([^)\n]*\)|https?:\/\/\S+)|(?<![\w./-])([\w.-]+\/[\w.-]+)#(\d{1,6})\b|(?<![\w&#/])#(\d{1,6})\b/g
7
8const QUALIFIED_REF = /(?<![\w./-])([\w.-]+\/[\w.-]+)#(\d{1,6})\b/g
9const GITHUB_REF = /github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/(?:pull|issues)\/(\d+)/g
10const REPO_FLAG = /(?:--repo[= ]|-R ?)["']?([\w.-]+)\/([\w.-]+?)["']?(?=[\s;&|)]|$)/g
11const CD = /(?:^|[;&|(]\s*)cd\s+("[^"]+"|'[^']+'|[^\s;&|)]+)/g
12const GIT_C = /\bgit\s+-C\s+("[^"]+"|'[^']+'|\S+)/g
13
14/**
15 * Something in the transcript that points at a repository: its URL outright
16 * (with the PR or issue number it was seen with, if any), or a directory whose
17 * git remote names it.
18 */
19export type Signal = { repoUrl: string; number?: string } | { dir: string }
20
21export function linkify(text: string, urlFor: (number: string) => string | undefined): string {
22 return text.replace(
23 PATTERN,
24 (match, skipped: string | undefined, repo: string | undefined, repoNumber: string, number: string) => {
25 if (skipped !== undefined) {
26 return match
27 }
28
29 if (repo !== undefined) {
30 return `[${repo}#${repoNumber}](https://github.com/${repo}/pull/${repoNumber})`
31 }
32
33 const repoUrl = urlFor(number)
34
35 return repoUrl === undefined ? match : `[#${number}](${repoUrl}/pull/${number})`
36 },
37 )
38}
39
40/**
41 * The bare `#N` numbers in the text that linkify would link.
42 */
43export function bareNumbers(text: string): string[] {
44 const numbers = new Set<string>()
45
46 for (const found of text.matchAll(PATTERN)) {
47 if (found[4] !== undefined) {
48 numbers.add(found[4])
49 }
50 }
51
52 return [...numbers]
53}
54
55export function repoUrlFromRemote(remote: string): string | undefined {
56 const found = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?\s*$/.exec(remote)
57
58 return found === null ? undefined : `https://github.com/${found[1]}/${found[2]}`
59}
60
61/**
62 * Every repository signal in the messages, oldest first.
63 */
64export function signalsFrom(messages: SessionMessage[]): Signal[] {
65 const signals: Signal[] = []
66
67 for (const message of messages) {
68 signals.push(...githubRefs(message.text), ...qualifiedRefs(message.text))
69
70 for (const use of message.toolUses) {
71 signals.push(...signalsInToolInput(use.input), ...githubRefs(use.text ?? ''))
72 }
73 }
74
75 return signals
76}
77
78function signalsInToolInput(input: Record<string, unknown>): Signal[] {
79 const signals: Signal[] = []
80
81 if (typeof input.owner === 'string' && typeof input.repo === 'string') {
82 const number = input.pull_number ?? input.pullNumber ?? input.issue_number ?? input.number
83
84 signals.push({
85 repoUrl: `https://github.com/${input.owner}/${input.repo}`,
86 number: number === undefined ? undefined : String(number),
87 })
88 }
89
90 for (const key of ['file_path', 'notebook_path', 'path']) {
91 const path = input[key]
92
93 if (typeof path === 'string' && path.startsWith('/')) {
94 signals.push({ dir: key === 'path' ? path : path.replace(/\/[^/]*$/, '') || '/' })
95 }
96 }
97
98 if (typeof input.command === 'string') {
99 const command = input.command
100 const found: { index: number; signal: Signal }[] = [
101 ...[...command.matchAll(CD), ...command.matchAll(GIT_C)].map(match => ({
102 index: match.index ?? 0,
103 signal: { dir: unquote(match[1] ?? '') },
104 })),
105 ...[...command.matchAll(REPO_FLAG)].map(match => ({
106 index: match.index ?? 0,
107 signal: { repoUrl: `https://github.com/${match[1]}/${match[2]}` },
108 })),
109 ]
110
111 signals.push(...found.sort((a, b) => a.index - b.index).map(entry => entry.signal), ...githubRefs(command))
112 }
113
114 return signals
115}
116
117function githubRefs(text: string): Signal[] {
118 return [...text.matchAll(GITHUB_REF)].map(found => ({
119 repoUrl: `https://github.com/${found[1]}/${found[2]}`,
120 number: found[3],
121 }))
122}
123
124function qualifiedRefs(text: string): Signal[] {
125 return [...text.matchAll(QUALIFIED_REF)].map(found => ({
126 repoUrl: `https://github.com/${found[1]}`,
127 number: found[2],
128 }))
129}
130
131function unquote(value: string): string {
132 return value.replace(/^(["'])(.*)\1$/, '$2')
133}
134