send-to-pi 1.0.1 → 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/README.md +24 -12
- package/README_CN.md +32 -18
- package/chrome-extension/background.js +376 -42
- package/chrome-extension/manifest.json +14 -3
- package/package.json +1 -1
- package/pi-extension/index.ts +158 -59
- package/scripts/start-win.vbs +1 -2
- package/server/src/config.js +8 -1
- package/server/src/index.js +125 -39
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[**简体中文**](./README_CN.md) | **English**
|
|
4
4
|
|
|
5
|
-
> Seamlessly bridge your web browser to the [Pi Coding Agent](https://github.com/earendil-works/pi-coding-agent). Send snippets, articles, or links directly into your Pi terminal prompt with one
|
|
5
|
+
> Seamlessly bridge your web browser to the [Pi Coding Agent](https://github.com/earendil-works/pi-coding-agent). Send snippets, articles, or links directly into your Pi terminal prompt with one click or keyboard shortcut.
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/send-to-pi)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -19,11 +19,15 @@ Traditionally, sending webpage context to an agent means:
|
|
|
19
19
|
1. Selecting text
|
|
20
20
|
2. Switching windows
|
|
21
21
|
3. Pasting into the terminal
|
|
22
|
-
4.
|
|
22
|
+
4. Dealing with broken indentation or destroyed tables, then typing instructions manually
|
|
23
23
|
|
|
24
24
|
**With `send-to-pi`:**
|
|
25
|
-
Right-click on any selected text, link, or page ➔ **The text is instantly prefilled into your Pi terminal input box**, with the source title & URL cleanly formatted.
|
|
25
|
+
Right-click on any selected text, link, or page ➔ **The text is instantly formatted into Markdown and prefilled into your Pi terminal input box**, with the source title & URL cleanly formatted.
|
|
26
26
|
- 🎯 **Prefill Mode (No Auto-Submit)**: The prompt is populated into the editor without auto-submitting. You can review, refine, or append instructions before pressing <kbd>Enter</kbd>.
|
|
27
|
+
- 📝 **HTML to Markdown Preservation**: Selection captures `<pre><code>` blocks, language tags, indentation, `<table>` grids, lists, quotes, and links without loss. Falls back gracefully when restricted.
|
|
28
|
+
- 📖 **Clean Article Extraction (Readability Mode)**: Extract clean article markdown stripped of navigation, footers, sidebars, and ads. Pi gets immediate full-text context without extra fetching.
|
|
29
|
+
- ⌨️ **Keyboard Shortcut**: Instant delivery with <kbd>Alt+Shift+S</kbd> (<kbd>Cmd+Shift+S</kbd> on macOS) right after highlighting text or code.
|
|
30
|
+
- 🔄 **Dynamic Port Discovery & Anti-Collision**: Pi sessions automatically probe 18091~18095 and track the most active session in `~/.pi/send-to-pi.json`.
|
|
27
31
|
- ⚡ **Cold-Start Auto-Wake**: If Pi isn't running, it automatically opens your terminal, starts Pi, and populates the text once the session boots up.
|
|
28
32
|
- 🍏 **True Cross-Platform**: Native terminal launch support for **macOS** (Terminal.app, iTerm2, Ghostty, WezTerm), **Windows** (Windows Terminal, PowerShell), and **Linux**.
|
|
29
33
|
- 🔒 **100% Local & Private**: All communication happens via `127.0.0.1`. No cloud proxy, no data logging.
|
|
@@ -38,12 +42,13 @@ sequenceDiagram
|
|
|
38
42
|
actor User as Developer
|
|
39
43
|
participant Browser as Chrome Extension
|
|
40
44
|
participant Bridge as Bridge Daemon (:18090)
|
|
41
|
-
participant Pi as Pi
|
|
45
|
+
participant Pi as Active Pi Session (18091~18095)
|
|
42
46
|
|
|
43
|
-
User->>Browser:
|
|
44
|
-
Browser->>Bridge: HTTP POST /send (
|
|
47
|
+
User->>Browser: Select or Extract Article (Menu / Shortcut)
|
|
48
|
+
Browser->>Bridge: HTTP POST /send (Markdown, URL, Title)
|
|
45
49
|
alt Active Pi Running
|
|
46
|
-
Bridge->>
|
|
50
|
+
Bridge->>Bridge: Read ~/.pi/send-to-pi.json or probe ports
|
|
51
|
+
Bridge->>Pi: Forward to port /receive
|
|
47
52
|
Pi->>Pi: ctx.ui.setEditorText() (Prefill)
|
|
48
53
|
Bridge-->>Browser: 200 OK (Prefilled)
|
|
49
54
|
else Pi Not Running (Cold Start)
|
|
@@ -100,15 +105,22 @@ This will print the exact folder path and **automatically open the extension dir
|
|
|
100
105
|
|
|
101
106
|
## ⌨️ How to Use
|
|
102
107
|
|
|
103
|
-
1. **Send Selected Text
|
|
104
|
-
|
|
105
|
-
|
|
108
|
+
1. **Send Selected Text / Code (Markdown)**:
|
|
109
|
+
- Highlight text or code ➔ Right-click ➔ Choose `🚀 Send Selection to Pi`;
|
|
110
|
+
- Or press shortcut <kbd>Alt+Shift+S</kbd> (<kbd>Cmd+Shift+S</kbd> on macOS).
|
|
111
|
+
2. **Send Clean Article (Readability Mode)**:
|
|
112
|
+
- Right-click anywhere on the webpage ➔ Choose `🚀 Send Clean Article to Pi`.
|
|
113
|
+
- The article body is parsed into clean Markdown without ads or navigation menus.
|
|
114
|
+
3. **Send Hyperlink**:
|
|
115
|
+
- Right-click any link ➔ Choose `🚀 Send Link to Pi`.
|
|
106
116
|
|
|
107
117
|
The formatted context will immediately appear at your terminal cursor:
|
|
108
118
|
```text
|
|
109
119
|
[Source]: GitHub - earendil-works/pi-coding-agent (https://github.com/...)
|
|
110
120
|
|
|
111
|
-
|
|
121
|
+
```typescript
|
|
122
|
+
export default function (pi: ExtensionAPI) { ... }
|
|
123
|
+
```
|
|
112
124
|
_ [Cursor waits here for your instructions]
|
|
113
125
|
```
|
|
114
126
|
|
|
@@ -121,7 +133,7 @@ You can configure options via environment variables when launching the daemon:
|
|
|
121
133
|
| Environment Variable | Default | Description |
|
|
122
134
|
| :--- | :--- | :--- |
|
|
123
135
|
| `PI_BRIDGE_PORT` | `18090` | Port listened by the Bridge Daemon |
|
|
124
|
-
| `PI_INTERNAL_PORT` | `18091` |
|
|
136
|
+
| `PI_INTERNAL_PORT` | `18091` | Starting port for active Pi sessions (probes 18091~18095) |
|
|
125
137
|
| `PI_WORKDIR` | Current directory | Default working directory when auto-launching Pi |
|
|
126
138
|
| `PI_TERMINAL` | Auto-detect | Preferred terminal: `iterm2`, `ghostty`, `terminal`, `wezterm`, `alacritty` |
|
|
127
139
|
|
package/README_CN.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
**简体中文** | [**English**](./README.md)
|
|
4
4
|
|
|
5
|
-
> 让你的网页浏览器与 [Pi 终端编程助手](https://github.com/earendil-works/pi-coding-agent)
|
|
5
|
+
> 让你的网页浏览器与 [Pi 终端编程助手](https://github.com/earendil-works/pi-coding-agent) 无缝打通。在网页上选中文字、提取整页文章或捕获链接,一键直达终端输入框,自动排版并预填上下文。
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/send-to-pi)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -19,12 +19,16 @@
|
|
|
19
19
|
1. 鼠标划词复制
|
|
20
20
|
2. Alt+Tab 切到终端窗口
|
|
21
21
|
3. 粘贴进输入框
|
|
22
|
-
4.
|
|
22
|
+
4. 代码缩进变形、表格散架、手动打字写“请参考以上网页/报错...”
|
|
23
23
|
|
|
24
24
|
**有了 `send-to-pi` 之后:**
|
|
25
|
-
|
|
25
|
+
在任何网页上划选文字、提取文章或点击链接 ➔ **内容自动携带网页标题与来源 URL,毫秒级预填进 Pi 终端输入框**。
|
|
26
26
|
- 🎯 **Prefill 预填模式(绝不自作主张回车)**:内容送到输入框后,光标停留在末尾,你可以从容补充具体指令(如“请根据这段代码重构...”),最后按回车自主发送。
|
|
27
|
-
-
|
|
27
|
+
- 📝 **HTML 智能转 Markdown(保留代码与表格格式)**:划词内容自动识别并还原 `<pre><code>` 语言/缩进、`<table>` 表格、列表、引用及超链接;页面受限时自动平滑降级。
|
|
28
|
+
- 📖 **整页正文提取(Readability 模式)**:右键点击“发送精简文章”,自动剔除页眉、页脚、侧边栏及广告噪声,将干净的正文转为 Markdown 一键交付,终端无需再额外发起网络请求。
|
|
29
|
+
- ⌨️ **快捷键一键直达**:支持全局划选快捷键(默认 <kbd>Alt+Shift+S</kbd> / Mac <kbd>Cmd+Shift+S</kbd>),无需右键鼠标二次点击。
|
|
30
|
+
- 🔄 **动态端口发现与防串台**:Pi 会话自动在 18091~18095 范围内探测可用端口,并通过 `~/.pi/send-to-pi.json` 维护活跃实例,多窗口共存不冲突。
|
|
31
|
+
- ⚡ **冷启动自动唤醒终端**:若当前未运行 Pi,自动为你拉起终端、启动 `pi`,并在会话初始化完成后自动填入内容!
|
|
28
32
|
- 🍏 **全平台终端适配**:原生支持 **macOS**(Terminal.app、iTerm2、Ghostty、WezTerm 等)、**Windows**(Windows Terminal、PowerShell)以及 **Linux**。
|
|
29
33
|
- 🔒 **纯本地与隐私安全**:全链路通过本地环回地址 `127.0.0.1` 传输,无云端中转,零数据收集。
|
|
30
34
|
|
|
@@ -36,14 +40,15 @@
|
|
|
36
40
|
sequenceDiagram
|
|
37
41
|
autonumber
|
|
38
42
|
actor User as 开发者
|
|
39
|
-
participant Browser as Chrome
|
|
40
|
-
participant Bridge as Bridge
|
|
41
|
-
participant Pi as Pi
|
|
42
|
-
|
|
43
|
-
User->>Browser:
|
|
44
|
-
Browser->>Bridge: HTTP POST /send (
|
|
45
|
-
alt Pi
|
|
46
|
-
Bridge->>
|
|
43
|
+
participant Browser as Chrome 扩展
|
|
44
|
+
participant Bridge as Bridge 守护进程 (:18090)
|
|
45
|
+
participant Pi as 活跃 Pi 终端 (18091~18095)
|
|
46
|
+
|
|
47
|
+
User->>Browser: 划选/文章提取 (右键或快捷键)
|
|
48
|
+
Browser->>Bridge: HTTP POST /send (Markdown、URL、标题)
|
|
49
|
+
alt 存在活跃 Pi 会话
|
|
50
|
+
Bridge->>Bridge: 读取 ~/.pi/send-to-pi.json 或端口探测
|
|
51
|
+
Bridge->>Pi: 转发至对应端口 /receive
|
|
47
52
|
Pi->>Pi: ctx.ui.setEditorText() (预填到输入框)
|
|
48
53
|
Bridge-->>Browser: 200 OK (已填入输入框)
|
|
49
54
|
else Pi 未运行 (冷启动模式)
|
|
@@ -68,6 +73,8 @@ pi install npm:send-to-pi
|
|
|
68
73
|
|
|
69
74
|
*(或者通过 GitHub 安装: `pi install git:github.com/Wude-m/send-to-pi`)*
|
|
70
75
|
|
|
76
|
+
### 第一步启动后,扩展会自动随 Pi 启动并在可用端口(18091~18095)监听接收。
|
|
77
|
+
|
|
71
78
|
### 第二步:启动 Bridge 守护进程
|
|
72
79
|
调度守护进程负责在后台监听浏览器请求并在需要时唤醒终端:
|
|
73
80
|
|
|
@@ -101,15 +108,22 @@ npx send-to-pi extension
|
|
|
101
108
|
|
|
102
109
|
## ⌨️ 日常使用演示
|
|
103
110
|
|
|
104
|
-
1.
|
|
105
|
-
|
|
106
|
-
|
|
111
|
+
1. **发送划选内容(Markdown 格式)**:
|
|
112
|
+
- 网页上鼠标选中任何代码或文本 ➔ 右键 ➔ 点击 `🚀 发送选中内容给 Pi`;
|
|
113
|
+
- 或划选后直接按下快捷键 <kbd>Alt+Shift+S</kbd>(Mac: <kbd>Cmd+Shift+S</kbd>)。
|
|
114
|
+
2. **发送精简正文(Readability 模式)**:
|
|
115
|
+
- 在网页任意空白处 ➔ 右键 ➔ 点击 `🚀 发送精简文章给 Pi`;
|
|
116
|
+
- 自动解析正文结构转为 Markdown,剔除无关导航和广告。
|
|
117
|
+
3. **发送超链接**:
|
|
118
|
+
- 在任意超链接上 ➔ 右键 ➔ 点击 `🚀 发送此链接给 Pi`。
|
|
107
119
|
|
|
108
|
-
终端输入框中会立即呈现带有来源标题与 URL
|
|
120
|
+
终端输入框中会立即呈现带有来源标题与 URL 的整洁 Markdown 内容:
|
|
109
121
|
```text
|
|
110
122
|
【来源】:GitHub - earendil-works/pi-coding-agent (https://github.com/...)
|
|
111
123
|
|
|
112
|
-
|
|
124
|
+
```typescript
|
|
125
|
+
export default function (pi: ExtensionAPI) { ... }
|
|
126
|
+
```
|
|
113
127
|
_ [光标停在此处,等待你补充提示词]
|
|
114
128
|
```
|
|
115
129
|
|
|
@@ -122,7 +136,7 @@ _ [光标停在此处,等待你补充提示词]
|
|
|
122
136
|
| 环境变量 | 默认值 | 说明 |
|
|
123
137
|
| :--- | :--- | :--- |
|
|
124
138
|
| `PI_BRIDGE_PORT` | `18090` | Bridge 调度进程监听的端口 |
|
|
125
|
-
| `PI_INTERNAL_PORT` | `18091` | 活跃 Pi
|
|
139
|
+
| `PI_INTERNAL_PORT` | `18091` | 活跃 Pi 会话内部起始端口(自动探测 18091~18095) |
|
|
126
140
|
| `PI_WORKDIR` | 当前目录 | 自动唤醒 Pi 时默认进入的工作目录 |
|
|
127
141
|
| `PI_TERMINAL` | 自动探测 | macOS/Linux 指定偏好终端(如 `iterm2`, `ghostty`, `terminal`, `alacritty`) |
|
|
128
142
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Send to Pi - Chrome Background Service Worker
|
|
3
|
+
* Version: 1.1.0
|
|
3
4
|
*/
|
|
4
5
|
|
|
5
6
|
const DEFAULT_PORT = 18090;
|
|
@@ -7,7 +8,7 @@ const isChinese = (navigator.language || '').toLowerCase().startsWith('zh');
|
|
|
7
8
|
|
|
8
9
|
const i18n = {
|
|
9
10
|
menuSelection: isChinese ? "🚀 发送选中内容给 Pi" : "🚀 Send Selection to Pi",
|
|
10
|
-
|
|
11
|
+
menuArticle: isChinese ? "🚀 发送精简文章给 Pi" : "🚀 Send Clean Article to Pi",
|
|
11
12
|
menuLink: isChinese ? "🚀 发送此链接给 Pi" : "🚀 Send Link to Pi",
|
|
12
13
|
notifyLaunchedTitle: isChinese ? "已唤起终端并预填内容" : "Terminal Launched & Prefilled",
|
|
13
14
|
notifyLaunchedMsg: (term) =>
|
|
@@ -23,6 +24,10 @@ const i18n = {
|
|
|
23
24
|
notifyNoConnMsg: isChinese
|
|
24
25
|
? "请确保本地后台 send-to-pi 守护进程已启动(默认端口 18090)。"
|
|
25
26
|
: "Please ensure the local send-to-pi daemon is running (default port: 18090).",
|
|
27
|
+
notifyNoSelectionTitle: isChinese ? "未检测到选中文本" : "No Selection Detected",
|
|
28
|
+
notifyNoSelectionMsg: isChinese
|
|
29
|
+
? "请先在页面上划选需要发送的文本或代码。"
|
|
30
|
+
: "Please select text or code on the webpage first.",
|
|
26
31
|
};
|
|
27
32
|
|
|
28
33
|
async function getBridgeUrl() {
|
|
@@ -34,49 +39,311 @@ async function getBridgeUrl() {
|
|
|
34
39
|
});
|
|
35
40
|
}
|
|
36
41
|
|
|
42
|
+
function showNotify(title, message) {
|
|
43
|
+
chrome.notifications.create({
|
|
44
|
+
type: "basic",
|
|
45
|
+
iconUrl: "icons/icon128.png",
|
|
46
|
+
title: title,
|
|
47
|
+
message: message,
|
|
48
|
+
priority: 1,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
37
52
|
// 注册右键菜单
|
|
38
53
|
chrome.runtime.onInstalled.addListener(() => {
|
|
39
|
-
chrome.contextMenus.
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
54
|
+
chrome.contextMenus.removeAll(() => {
|
|
55
|
+
chrome.contextMenus.create({
|
|
56
|
+
id: "send_selection",
|
|
57
|
+
title: i18n.menuSelection,
|
|
58
|
+
contexts: ["selection"],
|
|
59
|
+
});
|
|
44
60
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
61
|
+
chrome.contextMenus.create({
|
|
62
|
+
id: "send_article",
|
|
63
|
+
title: i18n.menuArticle,
|
|
64
|
+
contexts: ["page"],
|
|
65
|
+
});
|
|
50
66
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
67
|
+
chrome.contextMenus.create({
|
|
68
|
+
id: "send_link",
|
|
69
|
+
title: i18n.menuLink,
|
|
70
|
+
contexts: ["link"],
|
|
71
|
+
});
|
|
55
72
|
});
|
|
56
73
|
});
|
|
57
74
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
lang: isChinese ? "zh" : "en",
|
|
66
|
-
};
|
|
75
|
+
/**
|
|
76
|
+
* 在页面 DOM 上下文中执行的提取器(自包含函数)
|
|
77
|
+
* mode: 'selection' | 'article'
|
|
78
|
+
*/
|
|
79
|
+
function inPageExtractor(mode) {
|
|
80
|
+
function domToMarkdown(rootNode) {
|
|
81
|
+
if (!rootNode) return "";
|
|
67
82
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
83
|
+
function walk(node, depth) {
|
|
84
|
+
if (!node) return "";
|
|
85
|
+
|
|
86
|
+
if (node.nodeType === Node.TEXT_NODE) {
|
|
87
|
+
return node.textContent;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
91
|
+
return "";
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const tag = node.tagName.toLowerCase();
|
|
95
|
+
|
|
96
|
+
// 忽略不可视或干扰性标签
|
|
97
|
+
if (["script", "style", "noscript", "svg", "canvas", "template"].includes(tag)) {
|
|
98
|
+
return "";
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// 1. 代码块 <pre>
|
|
102
|
+
if (tag === "pre") {
|
|
103
|
+
const codeElem = node.querySelector("code") || node;
|
|
104
|
+
const langClass = (codeElem.getAttribute("class") || "") + " " + (node.getAttribute("class") || "");
|
|
105
|
+
const match = langClass.match(/(?:lang(?:uage)?-|hljs-?)([a-zA-Z0-9_-]+)/i);
|
|
106
|
+
const lang = match ? match[1] : "";
|
|
107
|
+
const codeText = (codeElem.textContent || "").replace(/\r\n/g, "\n").trimEnd();
|
|
108
|
+
return `\n\n\`\`\`${lang}\n${codeText}\n\`\`\`\n\n`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// 2. 行内代码 <code> (不在 pre 内)
|
|
112
|
+
if (tag === "code") {
|
|
113
|
+
if (node.closest("pre")) {
|
|
114
|
+
return node.textContent;
|
|
115
|
+
}
|
|
116
|
+
const text = node.textContent || "";
|
|
117
|
+
return text.includes("`") ? `\`\` ${text} \`\`` : `\`${text}\``;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// 3. 标题
|
|
121
|
+
if (/^h[1-6]$/.test(tag)) {
|
|
122
|
+
const level = parseInt(tag[1], 10);
|
|
123
|
+
const prefix = "#".repeat(level);
|
|
124
|
+
const text = getChildrenText(node, depth).trim();
|
|
125
|
+
return `\n\n${prefix} ${text}\n\n`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// 4. 引用
|
|
129
|
+
if (tag === "blockquote") {
|
|
130
|
+
const content = getChildrenText(node, depth).trim();
|
|
131
|
+
const quoted = content
|
|
132
|
+
.split("\n")
|
|
133
|
+
.map((line) => `> ${line}`)
|
|
134
|
+
.join("\n");
|
|
135
|
+
return `\n\n${quoted}\n\n`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// 5. 链接
|
|
139
|
+
if (tag === "a") {
|
|
140
|
+
const text = getChildrenText(node, depth).trim();
|
|
141
|
+
const href = node.getAttribute("href");
|
|
142
|
+
if (!text) return "";
|
|
143
|
+
if (href && !href.startsWith("javascript:")) {
|
|
144
|
+
return `[${text}](${href})`;
|
|
145
|
+
}
|
|
146
|
+
return text;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 6. 强调
|
|
150
|
+
if (tag === "strong" || tag === "b") {
|
|
151
|
+
const text = getChildrenText(node, depth).trim();
|
|
152
|
+
return text ? `**${text}**` : "";
|
|
153
|
+
}
|
|
154
|
+
if (tag === "em" || tag === "i") {
|
|
155
|
+
const text = getChildrenText(node, depth).trim();
|
|
156
|
+
return text ? `*${text}*` : "";
|
|
157
|
+
}
|
|
158
|
+
if (tag === "s" || tag === "del" || tag === "strike") {
|
|
159
|
+
const text = getChildrenText(node, depth).trim();
|
|
160
|
+
return text ? `~~${text}~~` : "";
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// 7. 分割线
|
|
164
|
+
if (tag === "hr") {
|
|
165
|
+
return "\n\n---\n\n";
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// 8. 换行
|
|
169
|
+
if (tag === "br") {
|
|
170
|
+
return "\n";
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 9. 图片
|
|
174
|
+
if (tag === "img") {
|
|
175
|
+
const alt = node.getAttribute("alt") || "";
|
|
176
|
+
const src = node.getAttribute("src") || "";
|
|
177
|
+
return src ? `` : "";
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// 10. 表格
|
|
181
|
+
if (tag === "table") {
|
|
182
|
+
return renderTable(node);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// 11. 列表
|
|
186
|
+
if (tag === "ul" || tag === "ol") {
|
|
187
|
+
const isOrdered = tag === "ol";
|
|
188
|
+
let idx = 1;
|
|
189
|
+
const items = [];
|
|
190
|
+
for (const child of node.children) {
|
|
191
|
+
if (child.tagName && child.tagName.toLowerCase() === "li") {
|
|
192
|
+
const itemText = walkLi(child, depth + 1).trim();
|
|
193
|
+
const indent = " ".repeat(depth);
|
|
194
|
+
const bullet = isOrdered ? `${idx++}. ` : "* ";
|
|
195
|
+
items.push(`${indent}${bullet}${itemText}`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return `\n\n${items.join("\n")}\n\n`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// 12. 常用块级元素
|
|
202
|
+
if (["p", "div", "section", "article"].includes(tag)) {
|
|
203
|
+
const text = getChildrenText(node, depth).trim();
|
|
204
|
+
return text ? `\n\n${text}\n\n` : "";
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return getChildrenText(node, depth);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function getChildrenText(node, depth) {
|
|
211
|
+
let result = "";
|
|
212
|
+
for (const child of node.childNodes) {
|
|
213
|
+
result += walk(child, depth);
|
|
214
|
+
}
|
|
215
|
+
return result;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function walkLi(liNode, depth) {
|
|
219
|
+
let result = "";
|
|
220
|
+
for (const child of liNode.childNodes) {
|
|
221
|
+
if (child.nodeType === Node.ELEMENT_NODE && ["ul", "ol"].includes(child.tagName.toLowerCase())) {
|
|
222
|
+
result += "\n" + walk(child, depth);
|
|
223
|
+
} else {
|
|
224
|
+
result += walk(child, depth);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function renderTable(table) {
|
|
231
|
+
const rows = Array.from(table.querySelectorAll("tr"));
|
|
232
|
+
if (!rows.length) return "";
|
|
233
|
+
|
|
234
|
+
const matrix = [];
|
|
235
|
+
let maxCols = 0;
|
|
236
|
+
|
|
237
|
+
for (const row of rows) {
|
|
238
|
+
const cells = Array.from(row.querySelectorAll("th, td")).map((cell) =>
|
|
239
|
+
(cell.textContent || "").replace(/\s+/g, " ").replace(/\|/g, "\\|").trim()
|
|
240
|
+
);
|
|
241
|
+
if (cells.length > maxCols) maxCols = cells.length;
|
|
242
|
+
matrix.push(cells);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (!matrix.length || maxCols === 0) return "";
|
|
246
|
+
|
|
247
|
+
const lines = [];
|
|
248
|
+
const header = matrix[0];
|
|
249
|
+
while (header.length < maxCols) header.push("");
|
|
250
|
+
lines.push(`| ${header.join(" | ")} |`);
|
|
251
|
+
|
|
252
|
+
const sep = Array(maxCols).fill("---");
|
|
253
|
+
lines.push(`| ${sep.join(" | ")} |`);
|
|
254
|
+
|
|
255
|
+
for (let i = 1; i < matrix.length; i++) {
|
|
256
|
+
const row = matrix[i];
|
|
257
|
+
while (row.length < maxCols) row.push("");
|
|
258
|
+
lines.push(`| ${row.join(" | ")} |`);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return `\n\n${lines.join("\n")}\n\n`;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const rawMd = walk(rootNode, 0);
|
|
265
|
+
return rawMd.replace(/\n{3,}/g, "\n\n").trim();
|
|
76
266
|
}
|
|
77
267
|
|
|
78
|
-
|
|
268
|
+
if (mode === "selection") {
|
|
269
|
+
const selection = window.getSelection();
|
|
270
|
+
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
const container = document.createElement("div");
|
|
274
|
+
for (let i = 0; i < selection.rangeCount; i++) {
|
|
275
|
+
container.appendChild(selection.getRangeAt(i).cloneContents());
|
|
276
|
+
}
|
|
277
|
+
const md = domToMarkdown(container);
|
|
278
|
+
return md || selection.toString();
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (mode === "article") {
|
|
282
|
+
// Readability 简版:整页正文提取
|
|
283
|
+
const clone = document.body.cloneNode(true);
|
|
284
|
+
|
|
285
|
+
const removeSelectors = [
|
|
286
|
+
"script", "style", "noscript", "nav", "header", "footer", "aside",
|
|
287
|
+
"iframe", "svg", "form", "[role='navigation']", "[role='banner']",
|
|
288
|
+
"[role='contentinfo']", ".nav", ".menu", ".sidebar", ".ad",
|
|
289
|
+
".advertisement", ".social-share", ".comments", ".comment-section"
|
|
290
|
+
];
|
|
291
|
+
removeSelectors.forEach((sel) => {
|
|
292
|
+
clone.querySelectorAll(sel).forEach((el) => el.remove());
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
let mainContainer =
|
|
296
|
+
clone.querySelector("article") ||
|
|
297
|
+
clone.querySelector("main") ||
|
|
298
|
+
clone.querySelector("[role='main']") ||
|
|
299
|
+
clone.querySelector(".post-content") ||
|
|
300
|
+
clone.querySelector(".article-content") ||
|
|
301
|
+
clone.querySelector(".entry-content") ||
|
|
302
|
+
clone.querySelector("#content");
|
|
303
|
+
|
|
304
|
+
if (!mainContainer) {
|
|
305
|
+
const candidates = Array.from(clone.querySelectorAll("div, section"));
|
|
306
|
+
let bestElem = clone;
|
|
307
|
+
let maxScore = 0;
|
|
308
|
+
|
|
309
|
+
for (const el of candidates) {
|
|
310
|
+
const pCount = el.querySelectorAll("p").length;
|
|
311
|
+
const textLen = (el.textContent || "").trim().length;
|
|
312
|
+
const score = pCount * 100 + textLen;
|
|
313
|
+
if (score > maxScore) {
|
|
314
|
+
maxScore = score;
|
|
315
|
+
bestElem = el;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
mainContainer = bestElem;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const md = domToMarkdown(mainContainer);
|
|
322
|
+
return md;
|
|
323
|
+
}
|
|
79
324
|
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async function extractFromTab(tabId, mode) {
|
|
329
|
+
try {
|
|
330
|
+
const results = await chrome.scripting.executeScript({
|
|
331
|
+
target: { tabId },
|
|
332
|
+
func: inPageExtractor,
|
|
333
|
+
args: [mode],
|
|
334
|
+
});
|
|
335
|
+
if (results && results[0] && results[0].result) {
|
|
336
|
+
return results[0].result;
|
|
337
|
+
}
|
|
338
|
+
return null;
|
|
339
|
+
} catch (err) {
|
|
340
|
+
console.warn("[SendToPi] executeScript extraction failed:", err);
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
async function sendPayload(payload) {
|
|
346
|
+
const endpoint = await getBridgeUrl();
|
|
80
347
|
try {
|
|
81
348
|
const res = await fetch(endpoint, {
|
|
82
349
|
method: "POST",
|
|
@@ -99,14 +366,81 @@ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
|
|
|
99
366
|
} catch (_err) {
|
|
100
367
|
showNotify(i18n.notifyNoConnTitle, i18n.notifyNoConnMsg);
|
|
101
368
|
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// 处理右键点击事件
|
|
372
|
+
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
|
|
373
|
+
const tabId = tab ? tab.id : null;
|
|
374
|
+
|
|
375
|
+
if (info.menuItemId === "send_selection") {
|
|
376
|
+
let markdown = null;
|
|
377
|
+
if (tabId) {
|
|
378
|
+
markdown = await extractFromTab(tabId, "selection");
|
|
379
|
+
}
|
|
380
|
+
// 平滑降级:若 HTML 提取失败则回退到 selectionText
|
|
381
|
+
const textToSend = markdown || info.selectionText || "";
|
|
382
|
+
|
|
383
|
+
const payload = {
|
|
384
|
+
type: "selection",
|
|
385
|
+
text: textToSend,
|
|
386
|
+
title: tab ? tab.title : "",
|
|
387
|
+
url: tab ? tab.url : "",
|
|
388
|
+
lang: isChinese ? "zh" : "en",
|
|
389
|
+
};
|
|
390
|
+
await sendPayload(payload);
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
if (info.menuItemId === "send_article") {
|
|
395
|
+
let articleText = null;
|
|
396
|
+
if (tabId) {
|
|
397
|
+
articleText = await extractFromTab(tabId, "article");
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const payload = {
|
|
401
|
+
type: articleText ? "article" : "page",
|
|
402
|
+
text: articleText || "",
|
|
403
|
+
title: tab ? tab.title : "",
|
|
404
|
+
url: tab ? tab.url : "",
|
|
405
|
+
lang: isChinese ? "zh" : "en",
|
|
406
|
+
};
|
|
407
|
+
await sendPayload(payload);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
if (info.menuItemId === "send_link") {
|
|
412
|
+
const payload = {
|
|
413
|
+
type: "link",
|
|
414
|
+
text: "",
|
|
415
|
+
title: tab ? tab.title : "",
|
|
416
|
+
url: info.linkUrl || (tab ? tab.url : ""),
|
|
417
|
+
lang: isChinese ? "zh" : "en",
|
|
418
|
+
};
|
|
419
|
+
await sendPayload(payload);
|
|
420
|
+
}
|
|
102
421
|
});
|
|
103
422
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
423
|
+
// 处理快捷键事件
|
|
424
|
+
chrome.commands.onCommand.addListener(async (command) => {
|
|
425
|
+
if (command === "send-selection") {
|
|
426
|
+
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
|
|
427
|
+
const tab = tabs[0];
|
|
428
|
+
if (!tab || !tab.id) return;
|
|
429
|
+
|
|
430
|
+
const extracted = await extractFromTab(tab.id, "selection");
|
|
431
|
+
if (!extracted || !extracted.trim()) {
|
|
432
|
+
showNotify(i18n.notifyNoSelectionTitle, i18n.notifyNoSelectionMsg);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const payload = {
|
|
437
|
+
type: "selection",
|
|
438
|
+
text: extracted.trim(),
|
|
439
|
+
title: tab.title || "",
|
|
440
|
+
url: tab.url || "",
|
|
441
|
+
lang: isChinese ? "zh" : "en",
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
await sendPayload(payload);
|
|
445
|
+
}
|
|
446
|
+
});
|
|
@@ -1,13 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"manifest_version": 3,
|
|
3
|
-
"name": "Send to Pi",
|
|
4
|
-
"version": "1.
|
|
3
|
+
"name": "Send to Pi (发送给 Pi)",
|
|
4
|
+
"version": "1.1.0",
|
|
5
5
|
"description": "Send webpage snippets, URLs, or articles directly to your local Pi coding agent terminal.",
|
|
6
6
|
"permissions": [
|
|
7
7
|
"contextMenus",
|
|
8
8
|
"notifications",
|
|
9
|
-
"storage"
|
|
9
|
+
"storage",
|
|
10
|
+
"scripting",
|
|
11
|
+
"activeTab"
|
|
10
12
|
],
|
|
13
|
+
"commands": {
|
|
14
|
+
"send-selection": {
|
|
15
|
+
"suggested_key": {
|
|
16
|
+
"default": "Alt+Shift+S",
|
|
17
|
+
"mac": "Command+Shift+S"
|
|
18
|
+
},
|
|
19
|
+
"description": "Send selected text/code to Pi"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
11
22
|
"host_permissions": [
|
|
12
23
|
"http://127.0.0.1:*/*"
|
|
13
24
|
],
|
package/package.json
CHANGED
package/pi-extension/index.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* send-to-pi Extension for Pi Coding Agent
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* Dynamically binds to an available internal port (18091 ~ 18095).
|
|
5
|
+
* Updates ~/.pi/send-to-pi.json with the active session metadata.
|
|
6
|
+
* Prefills incoming payloads into terminal input without immediate execution.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
@@ -12,19 +12,63 @@ import * as fs from "node:fs";
|
|
|
12
12
|
import * as path from "node:path";
|
|
13
13
|
import * as os from "node:os";
|
|
14
14
|
|
|
15
|
-
const
|
|
15
|
+
const DEFAULT_START_PORT = 18091;
|
|
16
|
+
const PORT_RANGE = 5; // 18091 ~ 18095
|
|
17
|
+
|
|
18
|
+
function getPiHomeDir(): string {
|
|
19
|
+
const dir = path.join(os.homedir(), ".pi");
|
|
20
|
+
if (!fs.existsSync(dir)) {
|
|
21
|
+
try {
|
|
22
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
23
|
+
} catch {}
|
|
24
|
+
}
|
|
25
|
+
return dir;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function getActiveSessionFilePath(): string {
|
|
29
|
+
return path.join(getPiHomeDir(), "send-to-pi.json");
|
|
30
|
+
}
|
|
16
31
|
|
|
17
32
|
function getPendingFilePaths(): string[] {
|
|
18
|
-
const piHome =
|
|
33
|
+
const piHome = getPiHomeDir();
|
|
19
34
|
return [
|
|
20
35
|
path.join(piHome, "pending-browser-input.txt"),
|
|
21
36
|
path.join(os.tmpdir(), "pi-pending-browser-input.txt"),
|
|
22
37
|
];
|
|
23
38
|
}
|
|
24
39
|
|
|
40
|
+
function recordActiveSession(port: number, workDir: string) {
|
|
41
|
+
try {
|
|
42
|
+
const sessionFile = getActiveSessionFilePath();
|
|
43
|
+
const data = {
|
|
44
|
+
pid: process.pid,
|
|
45
|
+
port,
|
|
46
|
+
workdir: workDir,
|
|
47
|
+
updatedAt: Date.now(),
|
|
48
|
+
};
|
|
49
|
+
fs.writeFileSync(sessionFile, JSON.stringify(data, null, 2), "utf8");
|
|
50
|
+
} catch (err: any) {
|
|
51
|
+
console.error("[SendToPi] Failed to write active session file:", err.message);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function clearActiveSession() {
|
|
56
|
+
try {
|
|
57
|
+
const sessionFile = getActiveSessionFilePath();
|
|
58
|
+
if (fs.existsSync(sessionFile)) {
|
|
59
|
+
const content = fs.readFileSync(sessionFile, "utf8");
|
|
60
|
+
const parsed = JSON.parse(content);
|
|
61
|
+
if (parsed.pid === process.pid) {
|
|
62
|
+
fs.unlinkSync(sessionFile);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
} catch {}
|
|
66
|
+
}
|
|
67
|
+
|
|
25
68
|
export default function (pi: ExtensionAPI) {
|
|
26
69
|
let server: http.Server | null = null;
|
|
27
70
|
let activeCtx: ExtensionContext | null = null;
|
|
71
|
+
let activePort: number | null = null;
|
|
28
72
|
|
|
29
73
|
function prefillEditor(ctx: ExtensionContext, textToInsert: string) {
|
|
30
74
|
if (!ctx || !ctx.ui) return;
|
|
@@ -42,6 +86,100 @@ export default function (pi: ExtensionAPI) {
|
|
|
42
86
|
}
|
|
43
87
|
}
|
|
44
88
|
|
|
89
|
+
function createServerInstance(ctx: ExtensionContext, port: number): Promise<http.Server> {
|
|
90
|
+
return new Promise((resolve, reject) => {
|
|
91
|
+
const app = http.createServer((req, res) => {
|
|
92
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
93
|
+
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
|
|
94
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
95
|
+
|
|
96
|
+
if (req.method === "OPTIONS") {
|
|
97
|
+
res.writeHead(204);
|
|
98
|
+
res.end();
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (req.method === "GET" && req.url === "/health") {
|
|
103
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
104
|
+
res.end(
|
|
105
|
+
JSON.stringify({
|
|
106
|
+
status: "alive",
|
|
107
|
+
port,
|
|
108
|
+
pid: process.pid,
|
|
109
|
+
workdir: ctx?.cwd || process.cwd(),
|
|
110
|
+
updatedAt: Date.now(),
|
|
111
|
+
})
|
|
112
|
+
);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (req.method === "POST" && req.url === "/receive") {
|
|
117
|
+
let body = "";
|
|
118
|
+
req.on("data", (chunk) => {
|
|
119
|
+
body += chunk;
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
req.on("end", () => {
|
|
123
|
+
try {
|
|
124
|
+
const data = JSON.parse(body || "{}");
|
|
125
|
+
const { content } = data;
|
|
126
|
+
|
|
127
|
+
if (content && activeCtx) {
|
|
128
|
+
prefillEditor(activeCtx, content);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// 每次成功接收更新活跃时间
|
|
132
|
+
recordActiveSession(port, ctx?.cwd || process.cwd());
|
|
133
|
+
|
|
134
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
135
|
+
res.end(JSON.stringify({ success: true, mode: "prefilled", port }));
|
|
136
|
+
} catch (err: any) {
|
|
137
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
138
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
145
|
+
res.end(JSON.stringify({ error: "Not Found" }));
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
const onError = (err: any) => {
|
|
149
|
+
app.removeListener("listening", onListening);
|
|
150
|
+
reject(err);
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const onListening = () => {
|
|
154
|
+
app.removeListener("error", onError);
|
|
155
|
+
resolve(app);
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
app.once("error", onError);
|
|
159
|
+
app.once("listening", onListening);
|
|
160
|
+
app.listen(port, "127.0.0.1");
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function startHttpServer(ctx: ExtensionContext): Promise<number> {
|
|
165
|
+
const startPort = parseInt(process.env.PI_INTERNAL_PORT || "", 10) || DEFAULT_START_PORT;
|
|
166
|
+
const endPort = startPort + PORT_RANGE - 1;
|
|
167
|
+
|
|
168
|
+
for (let currentPort = startPort; currentPort <= endPort; currentPort++) {
|
|
169
|
+
try {
|
|
170
|
+
const boundServer = await createServerInstance(ctx, currentPort);
|
|
171
|
+
server = boundServer;
|
|
172
|
+
activePort = currentPort;
|
|
173
|
+
return currentPort;
|
|
174
|
+
} catch (err: any) {
|
|
175
|
+
if (err.code !== "EADDRINUSE") {
|
|
176
|
+
throw err;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
throw new Error(`All ports in range ${startPort}-${endPort} are occupied.`);
|
|
181
|
+
}
|
|
182
|
+
|
|
45
183
|
pi.on("session_start", async (_event, ctx) => {
|
|
46
184
|
activeCtx = ctx;
|
|
47
185
|
|
|
@@ -61,61 +199,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
61
199
|
}
|
|
62
200
|
}
|
|
63
201
|
|
|
64
|
-
if (server)
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (req.method === "OPTIONS") {
|
|
72
|
-
res.writeHead(204);
|
|
73
|
-
res.end();
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
if (req.method === "GET" && req.url === "/health") {
|
|
78
|
-
res.writeHead(200, { "Content-Type": "application/json" });
|
|
79
|
-
res.end(JSON.stringify({ status: "alive", port: INTERNAL_PORT }));
|
|
80
|
-
return;
|
|
202
|
+
if (!server) {
|
|
203
|
+
try {
|
|
204
|
+
const boundPort = await startHttpServer(ctx);
|
|
205
|
+
recordActiveSession(boundPort, ctx?.cwd || process.cwd());
|
|
206
|
+
} catch (err: any) {
|
|
207
|
+
console.error("[SendToPi] Failed to bind internal port:", err.message);
|
|
81
208
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
req.on("data", (chunk) => {
|
|
86
|
-
body += chunk;
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
req.on("end", () => {
|
|
90
|
-
try {
|
|
91
|
-
const data = JSON.parse(body || "{}");
|
|
92
|
-
const { content } = data;
|
|
93
|
-
|
|
94
|
-
if (content && activeCtx) {
|
|
95
|
-
prefillEditor(activeCtx, content);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
res.writeHead(200, { "Content-Type": "application/json" });
|
|
99
|
-
res.end(JSON.stringify({ success: true, mode: "prefilled" }));
|
|
100
|
-
} catch (err: any) {
|
|
101
|
-
res.writeHead(400, { "Content-Type": "application/json" });
|
|
102
|
-
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
103
|
-
}
|
|
104
|
-
});
|
|
105
|
-
return;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
res.writeHead(404, { "Content-Type": "application/json" });
|
|
109
|
-
res.end(JSON.stringify({ error: "Not Found" }));
|
|
110
|
-
});
|
|
111
|
-
|
|
112
|
-
server.listen(INTERNAL_PORT, "127.0.0.1");
|
|
113
|
-
|
|
114
|
-
server.on("error", (e: any) => {
|
|
115
|
-
if (e.code !== "EADDRINUSE") {
|
|
116
|
-
console.error("[SendToPi Internal Server Error]:", e);
|
|
117
|
-
}
|
|
118
|
-
});
|
|
209
|
+
} else if (activePort) {
|
|
210
|
+
recordActiveSession(activePort, ctx?.cwd || process.cwd());
|
|
211
|
+
}
|
|
119
212
|
});
|
|
120
213
|
|
|
121
214
|
pi.on("session_shutdown", async () => {
|
|
@@ -123,6 +216,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
123
216
|
server.close();
|
|
124
217
|
server = null;
|
|
125
218
|
}
|
|
219
|
+
clearActiveSession();
|
|
126
220
|
activeCtx = null;
|
|
221
|
+
activePort = null;
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
process.on("exit", () => {
|
|
225
|
+
clearActiveSession();
|
|
127
226
|
});
|
|
128
227
|
}
|
package/scripts/start-win.vbs
CHANGED
|
@@ -2,10 +2,9 @@
|
|
|
2
2
|
Set WshShell = CreateObject("WScript.Shell")
|
|
3
3
|
Set fso = CreateObject("Scripting.FileSystemObject")
|
|
4
4
|
|
|
5
|
-
' 获取项目根目录
|
|
6
5
|
scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
|
|
7
6
|
rootDir = fso.GetParentFolderName(scriptDir)
|
|
8
7
|
targetScript = rootDir & "\server\src\index.js"
|
|
9
8
|
|
|
10
9
|
' 0 = 隐藏黑框静默运行
|
|
11
|
-
WshShell.Run "node """ & targetScript & """", 0, False
|
|
10
|
+
WshShell.Run "cmd.exe /c node """ & targetScript & """", 0, False
|
package/server/src/config.js
CHANGED
|
@@ -4,17 +4,21 @@ const fs = require('fs');
|
|
|
4
4
|
|
|
5
5
|
const BRIDGE_PORT = parseInt(process.env.PI_BRIDGE_PORT, 10) || 18090;
|
|
6
6
|
const PI_INTERNAL_PORT = parseInt(process.env.PI_INTERNAL_PORT, 10) || 18091;
|
|
7
|
+
const PI_INTERNAL_PORT_START = PI_INTERNAL_PORT;
|
|
8
|
+
const PI_INTERNAL_PORT_END = PI_INTERNAL_PORT + 4; // 18091 ~ 18095
|
|
7
9
|
|
|
8
10
|
// 确保 ~/.pi 目录存在
|
|
9
11
|
const piHomeDir = path.join(os.homedir(), '.pi');
|
|
10
12
|
if (!fs.existsSync(piHomeDir)) {
|
|
11
13
|
try {
|
|
12
14
|
fs.mkdirSync(piHomeDir, { recursive: true });
|
|
13
|
-
} catch (
|
|
15
|
+
} catch (_err) {
|
|
14
16
|
// 忽略创建失败(如权限受限),由操作系统临时目录兜底
|
|
15
17
|
}
|
|
16
18
|
}
|
|
17
19
|
|
|
20
|
+
const ACTIVE_SESSION_FILE = path.join(piHomeDir, 'send-to-pi.json');
|
|
21
|
+
|
|
18
22
|
const PENDING_FILE = fs.existsSync(piHomeDir)
|
|
19
23
|
? path.join(piHomeDir, 'pending-browser-input.txt')
|
|
20
24
|
: path.join(os.tmpdir(), 'pi-pending-browser-input.txt');
|
|
@@ -34,6 +38,9 @@ function getWorkDir() {
|
|
|
34
38
|
module.exports = {
|
|
35
39
|
BRIDGE_PORT,
|
|
36
40
|
PI_INTERNAL_PORT,
|
|
41
|
+
PI_INTERNAL_PORT_START,
|
|
42
|
+
PI_INTERNAL_PORT_END,
|
|
43
|
+
ACTIVE_SESSION_FILE,
|
|
37
44
|
PENDING_FILE,
|
|
38
45
|
getWorkDir,
|
|
39
46
|
};
|
package/server/src/index.js
CHANGED
|
@@ -2,34 +2,107 @@
|
|
|
2
2
|
* send-to-pi Bridge Daemon
|
|
3
3
|
*
|
|
4
4
|
* Listens on: 127.0.0.1:18090 (receives Chrome extension requests)
|
|
5
|
-
*
|
|
5
|
+
* Dynamically discovers active Pi sessions (18091 ~ 18095 or ~/.pi/send-to-pi.json)
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
const http = require('http');
|
|
9
9
|
const fs = require('fs');
|
|
10
|
-
const {
|
|
10
|
+
const {
|
|
11
|
+
BRIDGE_PORT,
|
|
12
|
+
PI_INTERNAL_PORT,
|
|
13
|
+
PI_INTERNAL_PORT_START,
|
|
14
|
+
PI_INTERNAL_PORT_END,
|
|
15
|
+
ACTIVE_SESSION_FILE,
|
|
16
|
+
PENDING_FILE,
|
|
17
|
+
getWorkDir,
|
|
18
|
+
} = require('./config');
|
|
11
19
|
const { launchTerminal } = require('./launchers');
|
|
12
20
|
|
|
13
|
-
function
|
|
21
|
+
function checkPiHealth(port) {
|
|
22
|
+
return new Promise((resolve) => {
|
|
23
|
+
const req = http.request(
|
|
24
|
+
{
|
|
25
|
+
hostname: '127.0.0.1',
|
|
26
|
+
port,
|
|
27
|
+
path: '/health',
|
|
28
|
+
method: 'GET',
|
|
29
|
+
timeout: 400,
|
|
30
|
+
},
|
|
31
|
+
(res) => {
|
|
32
|
+
if (res.statusCode === 200) {
|
|
33
|
+
let raw = '';
|
|
34
|
+
res.on('data', (c) => (raw += c));
|
|
35
|
+
res.on('end', () => {
|
|
36
|
+
try {
|
|
37
|
+
const info = JSON.parse(raw);
|
|
38
|
+
resolve({ ok: true, port, info });
|
|
39
|
+
} catch {
|
|
40
|
+
resolve({ ok: true, port });
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
} else {
|
|
44
|
+
resolve({ ok: false, port });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
req.on('error', () => resolve({ ok: false, port }));
|
|
50
|
+
req.on('timeout', () => {
|
|
51
|
+
req.destroy();
|
|
52
|
+
resolve({ ok: false, port });
|
|
53
|
+
});
|
|
54
|
+
req.end();
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function findActivePi() {
|
|
59
|
+
// 1. 优先读取 ~/.pi/send-to-pi.json 活跃单例信息
|
|
60
|
+
if (fs.existsSync(ACTIVE_SESSION_FILE)) {
|
|
61
|
+
try {
|
|
62
|
+
const raw = fs.readFileSync(ACTIVE_SESSION_FILE, 'utf8');
|
|
63
|
+
const session = JSON.parse(raw);
|
|
64
|
+
if (session && session.port) {
|
|
65
|
+
const health = await checkPiHealth(session.port);
|
|
66
|
+
if (health.ok) {
|
|
67
|
+
return { port: session.port, source: 'session-file', session };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
} catch (_e) {
|
|
71
|
+
// 忽略文件解析错误,继续范围扫描
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 2. 备用兜底:顺序探测端口范围 (18091 ~ 18095)
|
|
76
|
+
for (let port = PI_INTERNAL_PORT_START; port <= PI_INTERNAL_PORT_END; port++) {
|
|
77
|
+
const health = await checkPiHealth(port);
|
|
78
|
+
if (health.ok) {
|
|
79
|
+
return { port, source: 'port-scan', session: health.info };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function forwardToPi(port, content) {
|
|
14
87
|
return new Promise((resolve, reject) => {
|
|
15
88
|
const data = JSON.stringify({ content });
|
|
16
89
|
const req = http.request(
|
|
17
90
|
{
|
|
18
91
|
hostname: '127.0.0.1',
|
|
19
|
-
port
|
|
92
|
+
port,
|
|
20
93
|
path: '/receive',
|
|
21
94
|
method: 'POST',
|
|
22
95
|
headers: {
|
|
23
96
|
'Content-Type': 'application/json',
|
|
24
97
|
'Content-Length': Buffer.byteLength(data),
|
|
25
98
|
},
|
|
26
|
-
timeout:
|
|
99
|
+
timeout: 1500,
|
|
27
100
|
},
|
|
28
101
|
(res) => {
|
|
29
102
|
if (res.statusCode === 200) {
|
|
30
103
|
resolve(true);
|
|
31
104
|
} else {
|
|
32
|
-
reject(new Error(`Pi receiver responded with HTTP ${res.statusCode}`));
|
|
105
|
+
reject(new Error(`Pi receiver on port ${port} responded with HTTP ${res.statusCode}`));
|
|
33
106
|
}
|
|
34
107
|
}
|
|
35
108
|
);
|
|
@@ -37,7 +110,7 @@ function forwardToActivePi(content) {
|
|
|
37
110
|
req.on('error', (err) => reject(err));
|
|
38
111
|
req.on('timeout', () => {
|
|
39
112
|
req.destroy();
|
|
40
|
-
reject(new Error(
|
|
113
|
+
reject(new Error(`Pi receiver on port ${port} timed out`));
|
|
41
114
|
});
|
|
42
115
|
|
|
43
116
|
req.write(data);
|
|
@@ -53,6 +126,11 @@ function formatContent(payload) {
|
|
|
53
126
|
const label = isZh ? '【来源】' : '[Source]';
|
|
54
127
|
return `${label}: ${title || (isZh ? '网页摘录' : 'Web Snippet')} (${url || ''})\n\n${text}\n\n`;
|
|
55
128
|
}
|
|
129
|
+
if (type === 'article') {
|
|
130
|
+
const titleLabel = isZh ? '【网页文章】' : '[Web Article]';
|
|
131
|
+
const linkLabel = isZh ? '【网页链接】' : '[Link]';
|
|
132
|
+
return `${titleLabel}: ${title || (isZh ? '正文' : 'Article')}\n${linkLabel}: ${url || ''}\n\n${text}\n\n`;
|
|
133
|
+
}
|
|
56
134
|
if (type === 'link') {
|
|
57
135
|
const label = isZh ? '【网页链接】' : '[Link]';
|
|
58
136
|
return `${label}: ${url}\n\n`;
|
|
@@ -75,13 +153,15 @@ function createBridgeServer() {
|
|
|
75
153
|
}
|
|
76
154
|
|
|
77
155
|
if (req.method === 'GET' && req.url === '/health') {
|
|
156
|
+
const activePi = await findActivePi();
|
|
78
157
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
79
158
|
res.end(
|
|
80
159
|
JSON.stringify({
|
|
81
160
|
status: 'ok',
|
|
82
161
|
platform: process.platform,
|
|
83
162
|
bridgePort: BRIDGE_PORT,
|
|
84
|
-
|
|
163
|
+
defaultInternalPort: PI_INTERNAL_PORT,
|
|
164
|
+
activePi: activePi ? { port: activePi.port, source: activePi.source } : null,
|
|
85
165
|
workDir: getWorkDir(),
|
|
86
166
|
})
|
|
87
167
|
);
|
|
@@ -99,37 +179,43 @@ function createBridgeServer() {
|
|
|
99
179
|
const payload = JSON.parse(body || '{}');
|
|
100
180
|
const content = formatContent(payload);
|
|
101
181
|
|
|
102
|
-
// 1.
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
const launchResult = await launchTerminal(workDir);
|
|
122
|
-
|
|
123
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
124
|
-
res.end(
|
|
125
|
-
JSON.stringify({
|
|
126
|
-
success: true,
|
|
127
|
-
mode: 'launched',
|
|
128
|
-
terminal: launchResult.terminal || 'Default Terminal',
|
|
129
|
-
message: '已启动终端唤醒 Pi,内容已在输入框备好!',
|
|
130
|
-
})
|
|
131
|
-
);
|
|
182
|
+
// 1. 尝试动态发现当前活跃的 Pi 实例并转发
|
|
183
|
+
const activePi = await findActivePi();
|
|
184
|
+
if (activePi) {
|
|
185
|
+
try {
|
|
186
|
+
await forwardToPi(activePi.port, content);
|
|
187
|
+
console.log(`[Bridge] Successfully forwarded content to Pi terminal on port ${activePi.port}.`);
|
|
188
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
189
|
+
res.end(
|
|
190
|
+
JSON.stringify({
|
|
191
|
+
success: true,
|
|
192
|
+
mode: 'prefilled',
|
|
193
|
+
port: activePi.port,
|
|
194
|
+
message: '已直接填入活跃的 Pi 输入框!',
|
|
195
|
+
})
|
|
196
|
+
);
|
|
197
|
+
return;
|
|
198
|
+
} catch (err) {
|
|
199
|
+
console.warn(`[Bridge] Forward to port ${activePi.port} failed: ${err.message}, falling back to cold start.`);
|
|
200
|
+
}
|
|
132
201
|
}
|
|
202
|
+
|
|
203
|
+
// 2. 当前没有运行中的 Pi,进行冷启动唤醒流程
|
|
204
|
+
console.log('[Bridge] No active Pi detected. Writing pending file and launching terminal...');
|
|
205
|
+
fs.writeFileSync(PENDING_FILE, content, 'utf8');
|
|
206
|
+
|
|
207
|
+
const workDir = getWorkDir();
|
|
208
|
+
const launchResult = await launchTerminal(workDir);
|
|
209
|
+
|
|
210
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
211
|
+
res.end(
|
|
212
|
+
JSON.stringify({
|
|
213
|
+
success: true,
|
|
214
|
+
mode: 'launched',
|
|
215
|
+
terminal: launchResult.terminal || 'Default Terminal',
|
|
216
|
+
message: '已启动终端唤醒 Pi,内容已在输入框备好!',
|
|
217
|
+
})
|
|
218
|
+
);
|
|
133
219
|
} catch (e) {
|
|
134
220
|
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
135
221
|
res.end(JSON.stringify({ success: false, error: e.message }));
|
|
@@ -174,4 +260,4 @@ if (require.main === module) {
|
|
|
174
260
|
startDaemon();
|
|
175
261
|
}
|
|
176
262
|
|
|
177
|
-
module.exports = { startDaemon, createBridgeServer };
|
|
263
|
+
module.exports = { startDaemon, createBridgeServer, findActivePi, formatContent };
|