pi-clickable-links 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bbjson
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,165 @@
1
- # Temporary Holding Version
1
+ # pi-clickable-links
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
+ Clickable **file paths** and **URLs** in [pi](https://pi.dev) transcripts.
4
+
5
+ - **Path** → opens the containing folder in your file manager with the file selected
6
+ (never guesses which application should open it).
7
+ - **URL** → opens in your default browser.
8
+
9
+ Nothing is sent anywhere; the extension only rewrites Markdown for display, so the
10
+ session and the model context stay untouched.
11
+
12
+ ```
13
+ see /home/you/projects/api/src/server.ts:42 ← click: file manager at src/, server.ts selected
14
+ docs: https://example.com/guide ← click: default browser
15
+ ```
16
+
17
+ ## Why an extension and a URI handler
18
+
19
+ A terminal can only "click" URLs that pi emits as [OSC 8](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda)
20
+ hyperlinks, and the terminal hands those URIs to the desktop's default handler.
21
+ So there are two halves:
22
+
23
+ | Half | File | Job |
24
+ |---|---|---|
25
+ | pi extension | `src/open-links.ts` | rewrites `[text](url)` links into the transcript: local paths become `pi-open://open?p=…`, URLs stay `http(s)` |
26
+ | URI handler | `bin/pi-open` | receives the click, resolves the path, reveals it in the file manager (`nautilus --select`), or calls `xdg-open` for URLs |
27
+
28
+ ## Requirements
29
+
30
+ - pi 1.7 or newer
31
+ - A terminal with OSC 8 hyperlink support (GNOME Terminal / VTE, kitty, foot,
32
+ WezTerm, iTerm2, …)
33
+ - `python3` (the handler is a small stdlib-only script)
34
+ - Linux desktop with `xdg-mime`; Nautilus is used when present, otherwise `xdg-open`
35
+
36
+ ## Install
37
+
38
+ ### 1. The extension
39
+
40
+ ```bash
41
+ # from GitHub
42
+ pi install git:github.com/bbjson/pi-clickable-links
43
+
44
+ # or from npm
45
+ pi install npm:pi-clickable-links
46
+
47
+ # or from a local checkout
48
+ git clone https://github.com/bbjson/pi-clickable-links
49
+ cd pi-clickable-links
50
+ ./install.sh --link-extension
51
+ ```
52
+
53
+ ### 2. The URI handler
54
+
55
+ On the first session after installing, the extension installs the handler and the
56
+ desktop entry itself and tells you in the status area — no manual step needed.
57
+ Run the installer yourself to do it up front (or to redo it after moving files):
58
+
59
+ ```bash
60
+ ./install.sh
61
+ ```
62
+
63
+ It will:
64
+
65
+ 1. copy `bin/pi-open` to `~/.local/bin/pi-open`
66
+ 2. write `~/.local/share/applications/pi-open.desktop` and register the
67
+ `pi-open://` scheme with `xdg-mime`
68
+ 3. set `terminal.hyperlinks: true` in `~/.pi/agent/settings.json` (a timestamped
69
+ backup is written first; skip with `--no-settings`)
70
+
71
+ Doing the same steps by hand is fine too:
72
+
73
+ ```bash
74
+ install -m 0755 bin/pi-open ~/.local/bin/pi-open
75
+ sed "s|@PI_OPEN_BIN@|$HOME/.local/bin/pi-open|" share/pi-open.desktop.in \
76
+ > ~/.local/share/applications/pi-open.desktop
77
+ update-desktop-database ~/.local/share/applications
78
+ xdg-mime default pi-open.desktop x-scheme-handler/pi-open
79
+ ```
80
+
81
+ ### 3. Restart pi
82
+
83
+ Extensions and settings are read at startup. Run `/reload` or restart pi.
84
+
85
+ > ### Why `terminal.hyperlinks: true` is required
86
+ > pi decides whether it may emit OSC 8 links from `TERM_PROGRAM`. GNOME Terminal
87
+ > (VTE) does not set that variable, so pi disables hyperlinks by default and the
88
+ > transcript contains no links at all — even for plain `https://` URLs. Forcing
89
+ > the setting on fixes both. If your terminal sets `TERM_PROGRAM` (kitty, WezTerm,
90
+ > iTerm2, …), the setting is redundant but harmless.
91
+
92
+ ## Usage
93
+
94
+ Click any path or URL in the transcript.
95
+
96
+ Also available from the keyboard, which works even without OSC 8 support:
97
+
98
+ ```
99
+ /open /home/you/projects/api/src/server.ts
100
+ /open https://example.com/guide
101
+ /open ~/Downloads
102
+ ```
103
+
104
+ ## What gets linked
105
+
106
+ | Input in a transcript | Result |
107
+ |---|---|
108
+ | `/home/you/app/main.py` | clickable → file manager opens `app/`, `main.py` selected |
109
+ | `~/Downloads` | clickable → file manager opens `~/Downloads` |
110
+ | `/home/you/app/main.py:42` | clickable, `:42` kept in the label, file selected |
111
+ | `/home/you/My Documents/notes.md` | clickable (spaces handled) |
112
+ | `/home/you/视频/第八集.mp4` | clickable (non-ASCII percent-encoded in the URI) |
113
+ | `https://example.com` | clickable by pi itself, pointing at the URL |
114
+ | `` `cat /home/you/file` `` / fenced code | **left as code**, not linked |
115
+ | `[docs](/home/you/file.md)` (already a link) | **left alone** |
116
+ | `/home/you/does-not-exist.txt` | not linked, stays plain text |
117
+ | `src/app.ts` (relative) | not linked — a relative path cannot be resolved at click time |
118
+
119
+ ## Configuration
120
+
121
+ | Variable | Effect |
122
+ |---|---|
123
+ | `PI_OPEN_DRY=1` | make the handler print what it would run instead of opening anything |
124
+ | `PI_OPEN_BIN` | path to the handler, if you did not install it under `~/.local/bin` |
125
+
126
+ The file manager is chosen at the top of `bin/pi-open` (`nautilus` is used when
127
+ present, otherwise `xdg-open`). Change `FM` there for Thunar, Nemo, Dolphin, …
128
+
129
+ ## Troubleshooting
130
+
131
+ | Symptom | Cause / fix |
132
+ |---|---|
133
+ | No link styling at all, not even on `https://` URLs | `terminal.hyperlinks` is off: rerun `./install.sh`, restart pi |
134
+ | Link is styled but clicking does nothing | the terminal cannot open the scheme: check `xdg-mime query default x-scheme-handler/pi-open` |
135
+ | Clicking opens a text editor instead of the folder | pi rendered its own `file://` link (tool output paths), which bypasses this handler; click the path in the assistant text instead |
136
+ | Nothing happens on paths with spaces | the path must exist at render time — the extension only links existing absolute paths |
137
+ | `pi-open: command not found` | run `./install.sh` (step 2) |
138
+ | Fullscreen mode swallows clicks | hold `Ctrl+Shift` while clicking to use the terminal's native link handling |
139
+
140
+ Run the handler directly to debug:
141
+
142
+ ```bash
143
+ PI_OPEN_DRY=1 ~/.local/bin/pi-open 'pi-open://open?p=/home/you/Desktop'
144
+ ```
145
+
146
+ ## Tests
147
+
148
+ ```bash
149
+ npm test # node >= 22: TypeScript is stripped natively
150
+ ```
151
+
152
+ - `test/linkify.mjs` — Markdown transformer (paths, code fences, spaces, CJK, `:line` suffixes)
153
+ - `test/setup.mjs` — self-install path, in a throwaway `$HOME`
154
+
155
+ ## Uninstall
156
+
157
+ ```bash
158
+ ./uninstall.sh
159
+ pi remove git:github.com/bbjson/pi-clickable-links
160
+ # optionally revert terminal.hyperlinks in ~/.pi/agent/settings.json
161
+ ```
162
+
163
+ ## License
164
+
165
+ MIT — see [LICENSE](LICENSE).
package/bin/pi-open ADDED
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env python3
2
+ """pi-open —— 处理 pi 会话里点击的链接(OSC 8 → xdg scheme handler)
3
+
4
+ 用法:
5
+ pi-open 'pi-open://open?p=%2Fhome%2Fowl%2FDesktop%2Fhandbook%2FREADME.md'
6
+ pi-open 'https://example.com'
7
+ pi-open '/abs/path' # 直接给路径也行(/open 命令走这条)
8
+
9
+ 行为:
10
+ - http(s)/其它普通 URI → 本机默认浏览器(xdg-open)
11
+ - 目录 → 文件管理器打开该目录
12
+ - 文件 → 文件管理器打开所在目录并选中该文件(nautilus --select)
13
+ - 路径不存在 → 打开最近的已存在上级目录,并 notify-send 提示
14
+
15
+ 调试:PI_OPEN_DRY=1 只打印将要执行的动作,不真的打开。
16
+ """
17
+ import os
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import urllib.parse
22
+
23
+ DRY = os.environ.get("PI_OPEN_DRY") == "1"
24
+ FM = shutil.which("nautilus") # 本机是 Nautilus;没有就退回 xdg-open
25
+
26
+
27
+ def log(msg: str) -> None:
28
+ print(msg, file=sys.stderr)
29
+
30
+
31
+ def run(argv: list[str]) -> int:
32
+ if DRY:
33
+ log("[dry] " + " ".join(argv))
34
+ return 0
35
+ try:
36
+ subprocess.Popen(
37
+ argv,
38
+ stdout=subprocess.DEVNULL,
39
+ stderr=subprocess.DEVNULL,
40
+ start_new_session=True,
41
+ )
42
+ return 0
43
+ except FileNotFoundError:
44
+ log(f"pi-open: 找不到 {argv[0]}")
45
+ return 1
46
+
47
+
48
+ def notify(msg: str) -> None:
49
+ if DRY or not shutil.which("notify-send"):
50
+ log(msg)
51
+ return
52
+ run(["notify-send", "-a", "pi", "打开链接", msg])
53
+
54
+
55
+ def open_dir(path: str) -> int:
56
+ if not os.path.isdir(path):
57
+ path = os.path.dirname(path) or "/"
58
+ if FM:
59
+ return run([FM, path])
60
+ return run(["xdg-open", path])
61
+
62
+
63
+ def open_file(path: str) -> int:
64
+ """打开文件所在文件夹并选中该文件。"""
65
+ parent = os.path.dirname(path) or "/"
66
+ if FM:
67
+ # Nautilus 的 --select 需要文件存在
68
+ rc = run([FM, "--select", path])
69
+ if rc == 0:
70
+ return 0
71
+ return run(["xdg-open", parent])
72
+
73
+
74
+ def nearest_existing(path: str) -> str | None:
75
+ cur = path
76
+ while True:
77
+ if os.path.exists(cur):
78
+ return cur
79
+ nxt = os.path.dirname(cur)
80
+ if nxt == cur:
81
+ return None
82
+ cur = nxt
83
+
84
+
85
+ def handle_uri(uri: str) -> int:
86
+ # 支持 pi-open://open?p=... 与 pi-open:?p=...
87
+ parsed = urllib.parse.urlparse(uri)
88
+ if parsed.scheme in ("pi-open", "pifile"):
89
+ qs = urllib.parse.parse_qs(parsed.query)
90
+ raw = (qs.get("p") or qs.get("path") or [""])[0]
91
+ if not raw:
92
+ # 也允许 pi-open:///abs/path 这种形式
93
+ raw = urllib.parse.unquote(parsed.path)
94
+ return handle_path(raw)
95
+
96
+ if parsed.scheme == "file":
97
+ return handle_path(urllib.parse.unquote(parsed.path))
98
+
99
+ if parsed.scheme in ("http", "https", "ftp", "mailto"):
100
+ return run(["xdg-open", uri])
101
+
102
+ # 防递归:任何其它自定义 scheme 都不交给 xdg-open(否则会绕回自己)
103
+ notify(f"不认识的链接类型:{uri[:80]}")
104
+ return 3
105
+
106
+
107
+ def handle_path(raw: str) -> int:
108
+ if not raw:
109
+ notify("没有解析出路径")
110
+ return 2
111
+
112
+ path = os.path.expandvars(os.path.expanduser(urllib.parse.unquote(raw)))
113
+ if not os.path.isabs(path):
114
+ path = os.path.abspath(path)
115
+
116
+ if os.path.isdir(path):
117
+ return open_dir(path)
118
+ if os.path.isfile(path):
119
+ return open_file(path)
120
+
121
+ exist = nearest_existing(os.path.dirname(path))
122
+ if exist:
123
+ notify(f"路径不存在,已打开上级目录:{path}")
124
+ return open_dir(exist)
125
+ notify(f"路径不存在:{path}")
126
+ return 1
127
+
128
+
129
+ def main(argv: list[str]) -> int:
130
+ if len(argv) < 2:
131
+ log(__doc__)
132
+ return 2
133
+ target = argv[1]
134
+ if "://" in target or target.startswith("mailto:"):
135
+ return handle_uri(target)
136
+ return handle_path(target)
137
+
138
+
139
+ if __name__ == "__main__":
140
+ sys.exit(main(sys.argv))
package/install.sh ADDED
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env bash
2
+ # pi-clickable-links installer
3
+ #
4
+ # Installs the pi-open:// URI handler and (optionally) enables OSC 8
5
+ # hyperlinks in pi's settings.
6
+ #
7
+ # ./install.sh # handler + desktop entry + settings
8
+ # ./install.sh --no-settings # skip settings.json patch
9
+ # ./install.sh --link-extension # also symlink the extension into ~/.pi/agent/extensions
10
+ # ./install.sh --prefix "$HOME/.local"
11
+ set -euo pipefail
12
+
13
+ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
14
+ PREFIX="${PREFIX:-$HOME/.local}"
15
+ EXT_DIR="$HOME/.pi/agent/extensions"
16
+ SETTINGS="$HOME/.pi/agent/settings.json"
17
+ PATCH_SETTINGS=1
18
+ LINK_EXTENSION=0
19
+
20
+ while [ $# -gt 0 ]; do
21
+ case "$1" in
22
+ --prefix) PREFIX="$2"; shift 2 ;;
23
+ --no-settings) PATCH_SETTINGS=0; shift ;;
24
+ --link-extension) LINK_EXTENSION=1; shift ;;
25
+ -h|--help) sed -n '2,12p' "$0"; exit 0 ;;
26
+ *) echo "unknown option: $1" >&2; exit 2 ;;
27
+ esac
28
+ done
29
+
30
+ BIN_DIR="$PREFIX/bin"
31
+ APPS_DIR="$HOME/.local/share/applications"
32
+ HANDLER="$BIN_DIR/pi-open"
33
+
34
+ command -v python3 >/dev/null || { echo "python3 is required" >&2; exit 1; }
35
+
36
+ echo "==> Installing handler to $HANDLER"
37
+ mkdir -p "$BIN_DIR"
38
+ install -m 0755 "$REPO_DIR/bin/pi-open" "$HANDLER"
39
+
40
+ echo "==> Registering pi-open:// scheme handler"
41
+ mkdir -p "$APPS_DIR"
42
+ sed "s|@PI_OPEN_BIN@|$HANDLER|" "$REPO_DIR/share/pi-open.desktop.in" \
43
+ > "$APPS_DIR/pi-open.desktop"
44
+ chmod 0644 "$APPS_DIR/pi-open.desktop"
45
+ if command -v update-desktop-database >/dev/null; then
46
+ update-desktop-database "$APPS_DIR" >/dev/null 2>&1 || true
47
+ fi
48
+ if command -v xdg-mime >/dev/null; then
49
+ xdg-mime default pi-open.desktop x-scheme-handler/pi-open
50
+ fi
51
+
52
+ if [ "$PATCH_SETTINGS" = 1 ]; then
53
+ echo "==> Enabling OSC 8 hyperlinks in $SETTINGS"
54
+ mkdir -p "$(dirname "$SETTINGS")"
55
+ [ -f "$SETTINGS" ] || echo '{}' > "$SETTINGS"
56
+ cp "$SETTINGS" "$SETTINGS.bak-$(date +%Y%m%d-%H%M%S)"
57
+ python3 - "$SETTINGS" <<'PY'
58
+ import json, sys
59
+ path = sys.argv[1]
60
+ with open(path) as fh:
61
+ data = json.load(fh)
62
+ data.setdefault("terminal", {})["hyperlinks"] = True
63
+ with open(path, "w") as fh:
64
+ json.dump(data, fh, indent=2, ensure_ascii=False)
65
+ fh.write("\n")
66
+ print(" terminal.hyperlinks = true")
67
+ PY
68
+ else
69
+ echo "==> Skipping settings.json (set terminal.hyperlinks: true yourself)"
70
+ fi
71
+
72
+ if [ "$LINK_EXTENSION" = 1 ]; then
73
+ echo "==> Linking extension into $EXT_DIR"
74
+ mkdir -p "$EXT_DIR"
75
+ ln -sfn "$REPO_DIR/src/open-links.ts" "$EXT_DIR/open-links.ts"
76
+ fi
77
+
78
+ cat <<EOF
79
+
80
+ Done.
81
+
82
+ Next steps:
83
+ 1. Install the extension (pick one):
84
+ pi install git:github.com/bbjson/pi-clickable-links # from GitHub
85
+ ./install.sh --link-extension # from this checkout
86
+ 2. Restart pi (or run /reload) so the extension and the hyperlink
87
+ setting are picked up.
88
+ 3. Click a path in a transcript, or use /open <path or URL>.
89
+
90
+ Verify the handler without clicking:
91
+ PI_OPEN_DRY=1 "$HANDLER" 'pi-open://open?p=$HOME/Desktop/README.md'
92
+
93
+ EOF
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "pi-clickable-links",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Clickable file paths and URLs in pi transcripts: paths reveal in the file manager, URLs open in the default browser.",
5
+ "type": "module",
6
+ "keywords": [
7
+ "pi-package",
8
+ "pi-extension",
9
+ "hyperlink",
10
+ "osc8"
11
+ ],
12
+ "license": "MIT",
13
+ "author": "bbjson",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/bbjson/pi-clickable-links.git"
17
+ },
18
+ "homepage": "https://github.com/bbjson/pi-clickable-links#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/bbjson/pi-clickable-links/issues"
21
+ },
22
+ "bin": {
23
+ "pi-open": "bin/pi-open"
24
+ },
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "pi": {
29
+ "extensions": [
30
+ "./src/open-links.ts"
31
+ ]
32
+ },
33
+ "scripts": {
34
+ "test": "node test/linkify.mjs && node test/setup.mjs"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "registry": "https://registry.npmjs.org"
39
+ },
40
+ "files": [
41
+ "src",
42
+ "bin",
43
+ "share",
44
+ "test",
45
+ "install.sh",
46
+ "uninstall.sh",
47
+ "README.md",
48
+ "LICENSE"
49
+ ]
50
+ }
@@ -0,0 +1,10 @@
1
+ [Desktop Entry]
2
+ Type=Application
3
+ Name=Pi Link Opener
4
+ Comment=Open files, folders and URLs clicked in pi transcripts
5
+ Exec=@PI_OPEN_BIN@ %u
6
+ Icon=utilities-terminal
7
+ Terminal=false
8
+ NoDisplay=true
9
+ Categories=Utility;
10
+ MimeType=x-scheme-handler/pi-open;
@@ -0,0 +1,218 @@
1
+ /**
2
+ * pi-clickable-links
3
+ *
4
+ * Makes file paths and URLs in pi transcripts clickable.
5
+ *
6
+ * - URLs (http/https): wrapped in explicit Markdown links so the terminal
7
+ * emits an OSC 8 hyperlink; clicking opens the default browser.
8
+ * - Local paths (`/abs/...`, `~/...`): rewritten to `pi-open://open?p=...`
9
+ * links handled by `bin/pi-open`, which reveals the path in the file
10
+ * manager (file selected) instead of guessing an application.
11
+ *
12
+ * Display-only: the session and the model context are never modified.
13
+ * Code fences, inline code and pre-existing Markdown links are left alone.
14
+ */
15
+
16
+ import { existsSync, readFileSync } from "node:fs";
17
+ import { homedir } from "node:os";
18
+ import { isAbsolute, join } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
21
+
22
+ const MAX_LINKS_PER_MESSAGE = 80;
23
+ const SCHEME = "pi-open://open?p=";
24
+
25
+ /** Candidate path: starts with "/" or "~/", stops at whitespace and common wrappers. */
26
+ const PATH_RE = /(?:~\/|\/)[^\s"'`<>|*?\\[\]{}(),。;:!?、]+/g;
27
+
28
+ /** Characters that would otherwise break a Markdown link label. */
29
+ function escapeLabel(text: string): string {
30
+ return text.replace(/([\\`*_[\]|<>])/g, "\\$1");
31
+ }
32
+
33
+ /** Encode a path so it survives inside a Markdown link target. */
34
+ export function encodeTarget(path: string): string {
35
+ return encodeURIComponent(path)
36
+ .replace(/\(/g, "%28")
37
+ .replace(/\)/g, "%29")
38
+ .replace(/'/g, "%27")
39
+ .replace(/%2F/g, "/");
40
+ }
41
+
42
+ function expand(path: string): string {
43
+ if (path.startsWith("~/")) return join(homedir(), path.slice(2));
44
+ return path;
45
+ }
46
+
47
+ /** Strip sentence punctuation and split a trailing `:line[:col]` suffix. */
48
+ function splitTrailing(raw: string): { path: string; suffix: string } {
49
+ let path = raw.replace(/[.,;:!?,。;:!?、]+$/, "");
50
+ let suffix = "";
51
+ const match = /^(.*?)(:\d+(?::\d+)?)$/.exec(path);
52
+ if (match) {
53
+ path = match[1];
54
+ suffix = match[2];
55
+ }
56
+ return { path, suffix };
57
+ }
58
+
59
+ /** Analyse a candidate: build the link and report how many source chars it used. */
60
+ function analyze(raw: string): { markdown: string; used: number } | null {
61
+ const { path, suffix } = splitTrailing(raw);
62
+ if (!path || path.length < 3) return null;
63
+ const absolute = expand(path);
64
+ if (!isAbsolute(absolute) || !existsSync(absolute)) return null;
65
+ return {
66
+ markdown: `[${escapeLabel(path + suffix)}](${SCHEME}${encodeTarget(absolute)})`,
67
+ used: path.length + suffix.length,
68
+ };
69
+ }
70
+
71
+ const TRAILING_WORDS = /^(?:\s+[^\s"'`<>|*?\\[\]{}()]+)+/;
72
+
73
+ function replacePaths(text: string, budget: { left: number }): string {
74
+ const scanner = new RegExp(PATH_RE.source, "g");
75
+ let out = "";
76
+ let cursor = 0;
77
+ let match: RegExpExecArray | null;
78
+
79
+ while ((match = scanner.exec(text)) !== null) {
80
+ if (budget.left <= 0) break;
81
+ const start = match.index;
82
+ let result = analyze(match[0]);
83
+
84
+ // Paths may contain spaces ("Application Support"). Grow the candidate word
85
+ // by word and keep the first extension that exists on disk.
86
+ if (!result) {
87
+ const tail = text.slice(start + match[0].length).match(TRAILING_WORDS)?.[0] ?? "";
88
+ let grown = match[0];
89
+ for (const word of tail.match(/\s+\S+/g) ?? []) {
90
+ grown += word;
91
+ if (grown.length - match[0].length > 200) break;
92
+ const extended = analyze(grown.trimEnd());
93
+ if (extended) {
94
+ result = extended;
95
+ break;
96
+ }
97
+ }
98
+ }
99
+
100
+ if (!result) continue;
101
+ const end = start + result.used;
102
+ budget.left -= 1;
103
+ out += text.slice(cursor, start) + result.markdown;
104
+ cursor = end;
105
+ scanner.lastIndex = end;
106
+ }
107
+
108
+ return out + text.slice(cursor);
109
+ }
110
+
111
+ /** Protect inline code and existing Markdown links, linkify the rest. */
112
+ function linkifyInline(text: string, budget: { left: number }): string {
113
+ const tokens = text.split(/(`[^`\n]*`|!?\[[^\]]*\]\([^)]*\))/g);
114
+ return tokens.map((token, i) => (i % 2 === 1 ? token : replacePaths(token, budget))).join("");
115
+ }
116
+
117
+ /** Protect fenced code blocks, then apply the inline rules. */
118
+ export function linkify(markdown: string): string {
119
+ const budget = { left: MAX_LINKS_PER_MESSAGE };
120
+ const parts = markdown.split(/(```[\s\S]*?```|~~~[\s\S]*?~~~)/g);
121
+ return parts.map((chunk, i) => (i % 2 === 1 ? chunk : linkifyInline(chunk, budget))).join("");
122
+ }
123
+
124
+ type ExecLike = {
125
+ exec: (
126
+ command: string,
127
+ args: string[],
128
+ options?: { timeout?: number },
129
+ ) => Promise<{ code: number; stderr?: string; stdout?: string }>;
130
+ };
131
+
132
+ export const HANDLER_RELATIVE = join(".local", "bin", "pi-open");
133
+
134
+ /** Is pi allowed to emit OSC 8 hyperlinks? */
135
+ export function hyperlinksEnabled(home = homedir()): boolean {
136
+ try {
137
+ const settings = JSON.parse(readFileSync(join(home, ".pi", "agent", "settings.json"), "utf8"));
138
+ return settings?.terminal?.hyperlinks === true;
139
+ } catch {
140
+ return false;
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Install the `pi-open` URI handler on first use, so `pi install` alone is enough.
146
+ * Returns what happened so callers (and tests) can report it.
147
+ */
148
+ export async function ensureHandler(
149
+ pi: ExecLike,
150
+ options: { home?: string; root?: string } = {},
151
+ ): Promise<{ installed: boolean; reason: string; stderr?: string }> {
152
+ const home = options.home ?? homedir();
153
+ const handler = join(home, HANDLER_RELATIVE);
154
+ if (existsSync(handler)) return { installed: false, reason: "already-installed" };
155
+
156
+ const root = options.root ?? fileURLToPath(new URL("..", import.meta.url));
157
+ const installer = join(root, "install.sh");
158
+ if (!existsSync(installer)) return { installed: false, reason: "installer-missing" };
159
+
160
+ // Scoping HOME keeps the installer writing into `home` (used by tests).
161
+ const result = await pi.exec("env", [`HOME=${home}`, "bash", installer, "--no-settings"], {
162
+ timeout: 30_000,
163
+ });
164
+ return {
165
+ installed: result.code === 0,
166
+ reason: result.code === 0 ? "installed" : `exit-${result.code}`,
167
+ stderr: result.stderr,
168
+ };
169
+ }
170
+
171
+ export default function (pi: ExtensionAPI) {
172
+ // Self-healing setup: the URI handler and the hyperlink setting are required
173
+ // for clicks to work, so check them once per session.
174
+ pi.on("session_start", async (_event, ctx) => {
175
+ const result = await ensureHandler(pi);
176
+ if (result.installed) {
177
+ ctx.ui.notify("pi-clickable-links: installed the pi-open URI handler", "info");
178
+ } else if (result.reason !== "already-installed") {
179
+ ctx.ui.notify(
180
+ `pi-clickable-links: could not install the handler (${result.reason}). Run install.sh manually.`,
181
+ "warning",
182
+ );
183
+ }
184
+ if (!hyperlinksEnabled()) {
185
+ ctx.ui.notify(
186
+ "pi-clickable-links: terminal.hyperlinks is not enabled — links will not be clickable. Run install.sh.",
187
+ "warning",
188
+ );
189
+ }
190
+ });
191
+
192
+ pi.registerMarkdownTransformer((markdown, ctx) => {
193
+ // Streaming updates are re-rendered constantly; thinking blocks are not worth clicking.
194
+ if (ctx.isStreaming) return markdown;
195
+ if (ctx.messageType === "assistant-thinking") return markdown;
196
+ return linkify(markdown);
197
+ });
198
+
199
+ // Keyboard fallback: works even when the terminal does not support OSC 8.
200
+ pi.registerCommand("open", {
201
+ description: "Reveal a path in the file manager, or open a URL in the browser",
202
+ handler: async (args, ctx) => {
203
+ const target = (args || "").trim().replace(/^["']|["']$/g, "");
204
+ if (!target) {
205
+ ctx.ui.notify("Usage: /open <path or URL>", "warning");
206
+ return;
207
+ }
208
+ const script = process.env.PI_OPEN_BIN || join(homedir(), HANDLER_RELATIVE);
209
+ if (!existsSync(script)) {
210
+ ctx.ui.notify(`Missing ${script} — run install.sh from pi-clickable-links`, "error");
211
+ return;
212
+ }
213
+ const result = await pi.exec(script, [target], { timeout: 10_000 });
214
+ if (result.code === 0) ctx.ui.notify(`Opened: ${target}`, "info");
215
+ else ctx.ui.notify(`Failed: ${result.stderr || result.stdout || `exit ${result.code}`}`, "error");
216
+ },
217
+ });
218
+ }
@@ -0,0 +1,66 @@
1
+ // Minimal assertions for the Markdown transformer.
2
+ // Run with: node test/linkify.mjs (needs Node >= 22 for TypeScript stripping)
3
+ import assert from "node:assert/strict";
4
+ import { existsSync, mkdtempSync, mkdirSync, writeFileSync } from "node:fs";
5
+ import { homedir, tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { linkify, encodeTarget } from "../src/open-links.ts";
8
+
9
+ const target = (p) => `pi-open://open?p=${encodeTarget(p)}`;
10
+ let passed = 0;
11
+
12
+ function eq(name, actual, expected) {
13
+ assert.equal(actual, expected, `${name}\n got: ${actual}\n expected: ${expected}`);
14
+ passed++;
15
+ }
16
+
17
+ // Fixtures that exist on any machine running the test.
18
+ const dir = mkdtempSync(join(tmpdir(), "pcl-"));
19
+ const fileWithSpace = join(dir, "my file.md");
20
+ writeFileSync(fileWithSpace, "x");
21
+ const cjkDir = join(dir, "视频");
22
+ mkdirSync(cjkDir);
23
+
24
+ // 1. existing absolute path becomes a pi-open link
25
+ eq("absolute path", linkify(`see ${dir} here`), `see [${dir}](${target(dir)}) here`);
26
+
27
+ // 2. missing path stays plain text
28
+ eq("missing path", linkify("/definitely/not/here.txt"), "/definitely/not/here.txt");
29
+
30
+ // 3. fenced code blocks untouched
31
+ const fence = "```\nls " + dir + "\n```";
32
+ eq("fenced code", linkify(fence), fence);
33
+
34
+ // 4. inline code untouched
35
+ const inline = "`cat " + dir + "`";
36
+ eq("inline code", linkify(inline), inline);
37
+
38
+ // 5. existing markdown link untouched
39
+ const existing = `[dir](${dir})`;
40
+ eq("existing link", linkify(existing), existing);
41
+
42
+ // 6. URLs are not rewritten (pi autolinks them)
43
+ eq("url untouched", linkify("https://pi.dev/docs"), "https://pi.dev/docs");
44
+
45
+ // 7. `:42` line suffix stays in the label, not in the target
46
+ eq("line suffix", linkify(`${dir}:42`), `[${dir}:42](${target(dir)})`);
47
+
48
+ // 8. paths with spaces are encoded in the target
49
+ eq("space in path", linkify(fileWithSpace), `[${fileWithSpace}](${target(fileWithSpace)})`);
50
+
51
+ // 9. non-ASCII paths are percent-encoded but readable in the label
52
+ eq("cjk path", linkify(cjkDir), `[${cjkDir}](${target(cjkDir)})`);
53
+
54
+ // 10. ~ is expanded for the target, kept in the label
55
+ const tilde = "~/";
56
+ eq("tilde", linkify("~/Desktop"), `[~/Desktop](pi-open://open?p=${encodeTarget(join(homedir(), "Desktop"))})`);
57
+
58
+ // 11. encodeTarget keeps slashes, escapes parentheses and spaces
59
+ eq("encoded slashes", encodeTarget("/a b/c(1).mp4"), "/a%20b/c%281%29.mp4");
60
+
61
+ // 12. trailing sentence punctuation is not part of the path
62
+ eq("trailing dot", linkify(`look at ${dir}.`), `look at [${dir}](${target(dir)}).`);
63
+
64
+ assert.ok(existsSync(dir));
65
+
66
+ console.log(`ok - ${passed} assertions passed`);
package/test/setup.mjs ADDED
@@ -0,0 +1,48 @@
1
+ // Tests for the self-healing setup path: uses a throwaway HOME and a real shell.
2
+ import assert from "node:assert/strict";
3
+ import { execFile } from "node:child_process";
4
+ import { existsSync, mkdtempSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { promisify } from "node:util";
8
+ import { ensureHandler, hyperlinksEnabled } from "../src/open-links.ts";
9
+
10
+ const run = promisify(execFile);
11
+ let passed = 0;
12
+
13
+ const pi = {
14
+ exec: async (command, args, options = {}) => {
15
+ try {
16
+ const { stdout, stderr } = await run(command, args, { timeout: options.timeout ?? 10_000 });
17
+ return { code: 0, stdout, stderr };
18
+ } catch (error) {
19
+ return { code: error.code ?? 1, stdout: "", stderr: String(error.message ?? error) };
20
+ }
21
+ },
22
+ };
23
+
24
+ const home = mkdtempSync(join(tmpdir(), "pcl-home-"));
25
+ const root = new URL("..", import.meta.url).pathname;
26
+
27
+ // 1. missing handler gets installed from this checkout
28
+ const first = await ensureHandler(pi, { home, root });
29
+ assert.equal(first.reason, "installed", `unexpected: ${JSON.stringify(first)}`);
30
+ assert.ok(existsSync(join(home, ".local", "bin", "pi-open")), "handler should exist now");
31
+ passed++;
32
+
33
+ // 2. second run is a no-op
34
+ const second = await ensureHandler(pi, { home, root });
35
+ assert.equal(second.reason, "already-installed");
36
+ passed++;
37
+
38
+ // 3. hyperlinksEnabled() reads settings.json
39
+ assert.equal(hyperlinksEnabled(home), false, "no settings -> disabled");
40
+ passed++;
41
+
42
+ const { mkdirSync, writeFileSync } = await import("node:fs");
43
+ mkdirSync(join(home, ".pi", "agent"), { recursive: true });
44
+ writeFileSync(join(home, ".pi", "agent", "settings.json"), JSON.stringify({ terminal: { hyperlinks: true } }));
45
+ assert.equal(hyperlinksEnabled(home), true, "explicit true -> enabled");
46
+ passed++;
47
+
48
+ console.log(`ok - ${passed} assertions passed`);
package/uninstall.sh ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env bash
2
+ # Remove the pi-open:// handler, its desktop entry and the extension symlink.
3
+ # Leaves pi's settings.json untouched.
4
+ set -euo pipefail
5
+
6
+ PREFIX="${PREFIX:-$HOME/.local}"
7
+ BIN_DIR="$PREFIX/bin"
8
+ APPS_DIR="$HOME/.local/share/applications"
9
+
10
+ rm -f "$BIN_DIR/pi-open"
11
+ rm -f "$APPS_DIR/pi-open.desktop"
12
+ [ -L "$HOME/.pi/agent/extensions/open-links.ts" ] && rm -f "$HOME/.pi/agent/extensions/open-links.ts"
13
+
14
+ command -v update-desktop-database >/dev/null && update-desktop-database "$APPS_DIR" >/dev/null 2>&1 || true
15
+ echo "Removed handler and desktop entry."
16
+ echo "If you installed the extension with 'pi install', remove it with: pi remove <source>"