send-to-pi 1.2.0 → 1.3.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 +57 -113
- package/README_CN.md +57 -116
- package/chrome-extension/background.js +237 -65
- package/chrome-extension/manifest.json +10 -1
- package/chrome-extension/options.html +8 -2
- package/chrome-extension/options.js +22 -11
- package/chrome-extension/popup.html +160 -0
- package/chrome-extension/popup.js +145 -0
- package/package.json +3 -2
- package/pi-extension/README.md +9 -17
- package/pi-extension/index.ts +309 -79
- package/server/bin/send-to-pi.js +97 -42
- package/server/src/clipboard.js +53 -0
- package/server/src/config.js +99 -11
- package/server/src/index.js +153 -67
- package/server/src/launchers/custom.js +55 -0
- package/server/src/launchers/darwin.js +289 -45
- package/server/src/launchers/index.js +51 -8
- package/server/src/launchers/linux.js +60 -36
- package/server/src/launchers/win32.js +112 -66
package/pi-extension/index.ts
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* send-to-pi Extension for Pi Coding Agent
|
|
3
3
|
*
|
|
4
4
|
* Dynamically binds to an available internal port (18091 ~ 18095).
|
|
5
|
-
*
|
|
6
|
-
*
|
|
5
|
+
* Registers active sessions in ~/.pi/send-to-pi/sessions.json (and legacy ~/.pi/send-to-pi.json),
|
|
6
|
+
* persists the most recently used terminal profile in ~/.pi/send-to-pi/last-terminal.json,
|
|
7
|
+
* and prefills incoming browser payloads into the Pi editor without auto-submitting.
|
|
7
8
|
*/
|
|
8
9
|
|
|
9
10
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
@@ -15,6 +16,37 @@ import * as os from "node:os";
|
|
|
15
16
|
const DEFAULT_START_PORT = 18091;
|
|
16
17
|
const PORT_RANGE = 5; // 18091 ~ 18095
|
|
17
18
|
|
|
19
|
+
type TerminalInfo = {
|
|
20
|
+
terminal: string | null;
|
|
21
|
+
appName: string | null;
|
|
22
|
+
window: string | null;
|
|
23
|
+
rexBin?: string | null;
|
|
24
|
+
termProgram?: string | null;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
type SessionRecord = {
|
|
28
|
+
id: string;
|
|
29
|
+
pid: number;
|
|
30
|
+
port: number;
|
|
31
|
+
workdir: string;
|
|
32
|
+
activeAt: number;
|
|
33
|
+
startedAt: number;
|
|
34
|
+
updatedAt: number;
|
|
35
|
+
terminal: string | null;
|
|
36
|
+
appName: string | null;
|
|
37
|
+
window: string | null;
|
|
38
|
+
rexBin?: string | null;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
type LastTerminalRecord = {
|
|
42
|
+
terminal: string | null;
|
|
43
|
+
appName: string | null;
|
|
44
|
+
workdir: string;
|
|
45
|
+
rexBin?: string | null;
|
|
46
|
+
platform: NodeJS.Platform;
|
|
47
|
+
updatedAt: number;
|
|
48
|
+
};
|
|
49
|
+
|
|
18
50
|
function getPiHomeDir(): string {
|
|
19
51
|
const dir = path.join(os.homedir(), ".pi");
|
|
20
52
|
if (!fs.existsSync(dir)) {
|
|
@@ -37,6 +69,10 @@ function getSessionRegistryFilePath(): string {
|
|
|
37
69
|
return path.join(getSendToPiDir(), "sessions.json");
|
|
38
70
|
}
|
|
39
71
|
|
|
72
|
+
function getLastTerminalFilePath(): string {
|
|
73
|
+
return path.join(getSendToPiDir(), "last-terminal.json");
|
|
74
|
+
}
|
|
75
|
+
|
|
40
76
|
function getActiveSessionFilePath(): string {
|
|
41
77
|
return path.join(getPiHomeDir(), "send-to-pi.json");
|
|
42
78
|
}
|
|
@@ -49,17 +85,156 @@ function getPendingFilePaths(): string[] {
|
|
|
49
85
|
];
|
|
50
86
|
}
|
|
51
87
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
88
|
+
function isProcessAlive(pid: number): boolean {
|
|
89
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
90
|
+
try {
|
|
91
|
+
process.kill(pid, 0);
|
|
92
|
+
return true;
|
|
93
|
+
} catch (err: any) {
|
|
94
|
+
return err && err.code === "EPERM";
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function detectTerminalInfo(): TerminalInfo {
|
|
99
|
+
const env = process.env;
|
|
100
|
+
const termProgram = (env.TERM_PROGRAM || "").trim();
|
|
101
|
+
const termProgramLower = termProgram.toLowerCase();
|
|
102
|
+
const term = (env.TERM || "").toLowerCase();
|
|
103
|
+
const explicit = (env.PI_TERMINAL || "").trim().toLowerCase();
|
|
104
|
+
const windowId =
|
|
105
|
+
env.PI_WINDOW_ID ||
|
|
106
|
+
env.REX_BLOCK ||
|
|
107
|
+
env.KITTY_WINDOW_ID ||
|
|
108
|
+
env.WEZTERM_PANE ||
|
|
109
|
+
env.ITERM_SESSION_ID ||
|
|
110
|
+
env.WT_SESSION ||
|
|
111
|
+
env.TMUX_PANE ||
|
|
112
|
+
null;
|
|
113
|
+
|
|
114
|
+
let rexBin: string | null = null;
|
|
115
|
+
if (env.REX_BIN_DIR) {
|
|
116
|
+
const candidate = path.join(env.REX_BIN_DIR, process.platform === "win32" ? "rex.exe" : "rex");
|
|
117
|
+
if (fs.existsSync(candidate)) {
|
|
118
|
+
rexBin = candidate;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const knownApps: Record<string, string> = {
|
|
123
|
+
rex: "Rex",
|
|
124
|
+
ghostty: "Ghostty",
|
|
125
|
+
iterm2: "iTerm",
|
|
126
|
+
iterm: "iTerm",
|
|
127
|
+
warp: "Warp",
|
|
128
|
+
wezterm: "WezTerm",
|
|
129
|
+
kitty: "kitty",
|
|
130
|
+
alacritty: "Alacritty",
|
|
131
|
+
terminal: "Terminal",
|
|
132
|
+
vscode: "Visual Studio Code",
|
|
133
|
+
cursor: "Cursor",
|
|
134
|
+
zed: "Zed",
|
|
135
|
+
tabby: "Tabby",
|
|
136
|
+
hyper: "Hyper",
|
|
137
|
+
wt: "Windows Terminal",
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
if (explicit) {
|
|
141
|
+
return {
|
|
142
|
+
terminal: explicit,
|
|
143
|
+
appName: knownApps[explicit] || termProgram || explicit,
|
|
144
|
+
window: windowId,
|
|
145
|
+
rexBin,
|
|
146
|
+
termProgram: termProgram || null,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (termProgramLower === "rex" || env.REX_SERVER || env.REX_BIN_DIR) {
|
|
151
|
+
return { terminal: "rex", appName: "Rex", window: windowId, rexBin, termProgram: termProgram || "rex" };
|
|
152
|
+
}
|
|
153
|
+
if (termProgramLower === "ghostty" || env.GHOSTTY_RESOURCES_DIR) {
|
|
154
|
+
return { terminal: "ghostty", appName: "Ghostty", window: windowId, termProgram: termProgram || "ghostty" };
|
|
155
|
+
}
|
|
156
|
+
if (termProgramLower === "iterm.app" || env.ITERM_SESSION_ID) {
|
|
157
|
+
return { terminal: "iterm2", appName: "iTerm", window: windowId, termProgram: termProgram || "iTerm.app" };
|
|
158
|
+
}
|
|
159
|
+
if (termProgramLower === "warpterminal" || env.WARP_IS_LOCAL_SHELL_SESSION) {
|
|
160
|
+
return { terminal: "warp", appName: "Warp", window: windowId, termProgram: termProgram || "WarpTerminal" };
|
|
161
|
+
}
|
|
162
|
+
if (termProgramLower === "wezterm" || env.WEZTERM_EXECUTABLE) {
|
|
163
|
+
return { terminal: "wezterm", appName: "WezTerm", window: windowId, termProgram: termProgram || "WezTerm" };
|
|
164
|
+
}
|
|
165
|
+
if (env.KITTY_WINDOW_ID || term.includes("kitty")) {
|
|
166
|
+
return { terminal: "kitty", appName: "kitty", window: windowId, termProgram: termProgram || "kitty" };
|
|
167
|
+
}
|
|
168
|
+
if (env.ALACRITTY_SOCKET || env.ALACRITTY_LOG || term === "alacritty") {
|
|
169
|
+
return { terminal: "alacritty", appName: "Alacritty", window: windowId, termProgram: termProgram || "Alacritty" };
|
|
170
|
+
}
|
|
171
|
+
if (termProgramLower === "apple_terminal") {
|
|
172
|
+
return { terminal: "terminal", appName: "Terminal", window: windowId, termProgram: termProgram || "Apple_Terminal" };
|
|
173
|
+
}
|
|
174
|
+
if (termProgramLower === "vscode" || env.VSCODE_IPC_HOOK_CLI) {
|
|
175
|
+
const isCursor =
|
|
176
|
+
Boolean(env.CURSOR_TRACE_ID) ||
|
|
177
|
+
(env.VSCODE_GIT_ASKPASS_NODE || "").toLowerCase().includes("cursor") ||
|
|
178
|
+
(env.TERM_PROGRAM_VERSION || "").toLowerCase().includes("cursor");
|
|
179
|
+
return {
|
|
180
|
+
terminal: isCursor ? "cursor" : "vscode",
|
|
181
|
+
appName: isCursor ? "Cursor" : "Visual Studio Code",
|
|
182
|
+
window: windowId,
|
|
183
|
+
termProgram: termProgram || "vscode",
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
if (termProgramLower === "zed") {
|
|
187
|
+
return { terminal: "zed", appName: "Zed", window: windowId, termProgram };
|
|
188
|
+
}
|
|
189
|
+
if (termProgramLower === "tabby") {
|
|
190
|
+
return { terminal: "tabby", appName: "Tabby", window: windowId, termProgram };
|
|
191
|
+
}
|
|
192
|
+
if (termProgramLower === "hyper") {
|
|
193
|
+
return { terminal: "hyper", appName: "Hyper", window: windowId, termProgram };
|
|
194
|
+
}
|
|
195
|
+
if (env.WT_SESSION) {
|
|
196
|
+
return { terminal: "wt", appName: "Windows Terminal", window: windowId, termProgram: termProgram || "wt" };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (termProgram) {
|
|
200
|
+
return {
|
|
201
|
+
terminal: termProgramLower,
|
|
202
|
+
appName: termProgram,
|
|
203
|
+
window: windowId,
|
|
204
|
+
termProgram,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return { terminal: null, appName: null, window: windowId, termProgram: null };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function formatIncomingPayload(data: any): string {
|
|
212
|
+
if (typeof data?.content === "string" && data.content.length > 0) {
|
|
213
|
+
return data.content;
|
|
214
|
+
}
|
|
215
|
+
const { type, text, title, url, lang } = data || {};
|
|
216
|
+
const isZh = lang === "zh";
|
|
217
|
+
|
|
218
|
+
if (type === "selection") {
|
|
219
|
+
const label = isZh ? "【来源】" : "[Source]";
|
|
220
|
+
return `${label}: ${title || (isZh ? "网页摘录" : "Web Snippet")} (${url || ""})\n\n${text || ""}\n\n`;
|
|
221
|
+
}
|
|
222
|
+
if (type === "article") {
|
|
223
|
+
const titleLabel = isZh ? "【网页文章】" : "[Web Article]";
|
|
224
|
+
const linkLabel = isZh ? "【网页链接】" : "[Link]";
|
|
225
|
+
return `${titleLabel}: ${title || (isZh ? "正文" : "Article")}\n${linkLabel}: ${url || ""}\n\n${text || ""}\n\n`;
|
|
226
|
+
}
|
|
227
|
+
if (type === "link") {
|
|
228
|
+
const label = isZh ? "【网页链接】" : "[Link]";
|
|
229
|
+
return `${label}: ${url || ""}\n\n`;
|
|
230
|
+
}
|
|
231
|
+
if (url || title || text) {
|
|
232
|
+
const titleLabel = isZh ? "【网页标题】" : "[Title]";
|
|
233
|
+
const linkLabel = isZh ? "【网页链接】" : "[Link]";
|
|
234
|
+
return `${titleLabel}: ${title || (isZh ? "网页" : "Page")}\n${linkLabel}: ${url || ""}\n\n${text ? `${text}\n\n` : ""}`;
|
|
235
|
+
}
|
|
236
|
+
return "";
|
|
237
|
+
}
|
|
63
238
|
|
|
64
239
|
function readSessionRecords(): SessionRecord[] {
|
|
65
240
|
try {
|
|
@@ -67,74 +242,92 @@ function readSessionRecords(): SessionRecord[] {
|
|
|
67
242
|
if (!fs.existsSync(registryFile)) return [];
|
|
68
243
|
const parsed = JSON.parse(fs.readFileSync(registryFile, "utf8"));
|
|
69
244
|
const sessions = Array.isArray(parsed) ? parsed : parsed?.sessions;
|
|
70
|
-
|
|
245
|
+
if (!Array.isArray(sessions)) return [];
|
|
246
|
+
return sessions.filter((s) => s && Number.isInteger(Number(s.port)) && isProcessAlive(Number(s.pid)));
|
|
71
247
|
} catch {
|
|
72
248
|
return [];
|
|
73
249
|
}
|
|
74
250
|
}
|
|
75
251
|
|
|
76
|
-
function
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
temporaryFile,
|
|
81
|
-
JSON.stringify({ version: 1, sessions }, null, 2),
|
|
82
|
-
"utf8"
|
|
83
|
-
);
|
|
84
|
-
fs.renameSync(temporaryFile, registryFile);
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function recordActiveSession(port: number, workDir: string) {
|
|
88
|
-
try {
|
|
89
|
-
const now = Date.now();
|
|
90
|
-
const sessionId = `${process.pid}-${port}`;
|
|
91
|
-
const existingSessions = readSessionRecords();
|
|
92
|
-
const sessions = existingSessions.filter((session) => session.id !== sessionId);
|
|
93
|
-
const data: SessionRecord = {
|
|
94
|
-
id: sessionId,
|
|
95
|
-
pid: process.pid,
|
|
96
|
-
port,
|
|
97
|
-
workdir: workDir,
|
|
98
|
-
activeAt: now,
|
|
99
|
-
startedAt: now,
|
|
100
|
-
updatedAt: now,
|
|
101
|
-
terminal: process.env.PI_TERMINAL || null,
|
|
102
|
-
window: process.env.PI_WINDOW_ID || null,
|
|
103
|
-
};
|
|
104
|
-
const previous = existingSessions.find((session) => session.id === sessionId);
|
|
105
|
-
if (previous) data.startedAt = previous.startedAt;
|
|
106
|
-
sessions.push(data);
|
|
107
|
-
writeSessionRecords(sessions);
|
|
108
|
-
|
|
109
|
-
// Keep the pre-1.2.0 single-session file for older Bridge versions.
|
|
110
|
-
fs.writeFileSync(getActiveSessionFilePath(), JSON.stringify(data, null, 2), "utf8");
|
|
111
|
-
} catch (err: any) {
|
|
112
|
-
console.error("[SendToPi] Failed to write session registry:", err.message);
|
|
252
|
+
function writeJsonAtomic(filePath: string, payload: unknown) {
|
|
253
|
+
const dir = path.dirname(filePath);
|
|
254
|
+
if (!fs.existsSync(dir)) {
|
|
255
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
113
256
|
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
try {
|
|
118
|
-
const sessionId = port === null ? null : `${process.pid}-${port}`;
|
|
119
|
-
const sessions = readSessionRecords().filter(
|
|
120
|
-
(session) => session.id !== sessionId && !(session.pid === process.pid && session.port === port)
|
|
121
|
-
);
|
|
122
|
-
writeSessionRecords(sessions);
|
|
123
|
-
|
|
124
|
-
const sessionFile = getActiveSessionFilePath();
|
|
125
|
-
if (fs.existsSync(sessionFile)) {
|
|
126
|
-
const parsed = JSON.parse(fs.readFileSync(sessionFile, "utf8"));
|
|
127
|
-
if (parsed.pid === process.pid && (port === null || parsed.port === port)) {
|
|
128
|
-
fs.unlinkSync(sessionFile);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
} catch {}
|
|
257
|
+
const temporaryFile = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
258
|
+
fs.writeFileSync(temporaryFile, JSON.stringify(payload, null, 2), "utf8");
|
|
259
|
+
fs.renameSync(temporaryFile, filePath);
|
|
132
260
|
}
|
|
133
261
|
|
|
134
262
|
export default function (pi: ExtensionAPI) {
|
|
135
263
|
let server: http.Server | null = null;
|
|
136
264
|
let activeCtx: ExtensionContext | null = null;
|
|
137
265
|
let activePort: number | null = null;
|
|
266
|
+
const startedAt = Date.now();
|
|
267
|
+
let lastActiveAt = startedAt;
|
|
268
|
+
const terminalInfo = detectTerminalInfo();
|
|
269
|
+
|
|
270
|
+
function recordActiveSession(port: number, workDir: string) {
|
|
271
|
+
try {
|
|
272
|
+
const now = Date.now();
|
|
273
|
+
lastActiveAt = now;
|
|
274
|
+
const sessionId = `${process.pid}-${port}`;
|
|
275
|
+
const existingSessions = readSessionRecords();
|
|
276
|
+
const sessions = existingSessions.filter((session) => session.id !== sessionId);
|
|
277
|
+
const previous = existingSessions.find((session) => session.id === sessionId);
|
|
278
|
+
|
|
279
|
+
const data: SessionRecord = {
|
|
280
|
+
id: sessionId,
|
|
281
|
+
pid: process.pid,
|
|
282
|
+
port,
|
|
283
|
+
workdir: workDir,
|
|
284
|
+
activeAt: now,
|
|
285
|
+
startedAt: previous ? previous.startedAt : startedAt,
|
|
286
|
+
updatedAt: now,
|
|
287
|
+
terminal: terminalInfo.terminal,
|
|
288
|
+
appName: terminalInfo.appName,
|
|
289
|
+
window: terminalInfo.window,
|
|
290
|
+
...(terminalInfo.rexBin ? { rexBin: terminalInfo.rexBin } : {}),
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
sessions.push(data);
|
|
294
|
+
writeJsonAtomic(getSessionRegistryFilePath(), { version: 2, sessions });
|
|
295
|
+
|
|
296
|
+
// Keep the pre-1.2.0 single-session file for older Bridge versions.
|
|
297
|
+
fs.writeFileSync(getActiveSessionFilePath(), JSON.stringify(data, null, 2), "utf8");
|
|
298
|
+
|
|
299
|
+
// Persist last known terminal & workdir so cold-start launches match the user's real client.
|
|
300
|
+
const lastTerminal: LastTerminalRecord = {
|
|
301
|
+
terminal: terminalInfo.terminal,
|
|
302
|
+
appName: terminalInfo.appName,
|
|
303
|
+
workdir: workDir,
|
|
304
|
+
...(terminalInfo.rexBin ? { rexBin: terminalInfo.rexBin } : {}),
|
|
305
|
+
platform: process.platform,
|
|
306
|
+
updatedAt: now,
|
|
307
|
+
};
|
|
308
|
+
writeJsonAtomic(getLastTerminalFilePath(), lastTerminal);
|
|
309
|
+
} catch (err: any) {
|
|
310
|
+
console.error("[SendToPi] Failed to write session registry:", err.message);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function clearActiveSession(port: number | null) {
|
|
315
|
+
try {
|
|
316
|
+
const sessionId = port === null ? null : `${process.pid}-${port}`;
|
|
317
|
+
const sessions = readSessionRecords().filter(
|
|
318
|
+
(session) => session.id !== sessionId && !(session.pid === process.pid && (port === null || session.port === port))
|
|
319
|
+
);
|
|
320
|
+
writeJsonAtomic(getSessionRegistryFilePath(), { version: 2, sessions });
|
|
321
|
+
|
|
322
|
+
const sessionFile = getActiveSessionFilePath();
|
|
323
|
+
if (fs.existsSync(sessionFile)) {
|
|
324
|
+
const parsed = JSON.parse(fs.readFileSync(sessionFile, "utf8"));
|
|
325
|
+
if (parsed.pid === process.pid && (port === null || parsed.port === port)) {
|
|
326
|
+
fs.unlinkSync(sessionFile);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
} catch {}
|
|
330
|
+
}
|
|
138
331
|
|
|
139
332
|
function prefillEditor(ctx: ExtensionContext, textToInsert: string) {
|
|
140
333
|
if (!ctx || !ctx.ui) return;
|
|
@@ -166,14 +359,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
166
359
|
}
|
|
167
360
|
|
|
168
361
|
if (req.method === "GET" && req.url === "/health") {
|
|
169
|
-
|
|
362
|
+
const workdir = activeCtx?.cwd || ctx?.cwd || process.cwd();
|
|
363
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
|
|
170
364
|
res.end(
|
|
171
365
|
JSON.stringify({
|
|
172
366
|
status: "alive",
|
|
367
|
+
version: "1.3.0",
|
|
173
368
|
port,
|
|
174
369
|
pid: process.pid,
|
|
175
|
-
workdir
|
|
176
|
-
|
|
370
|
+
workdir,
|
|
371
|
+
activeAt: lastActiveAt,
|
|
372
|
+
startedAt,
|
|
373
|
+
updatedAt: lastActiveAt,
|
|
374
|
+
terminal: terminalInfo.terminal,
|
|
375
|
+
appName: terminalInfo.appName,
|
|
376
|
+
window: terminalInfo.window,
|
|
177
377
|
})
|
|
178
378
|
);
|
|
179
379
|
return;
|
|
@@ -189,26 +389,41 @@ export default function (pi: ExtensionAPI) {
|
|
|
189
389
|
try {
|
|
190
390
|
const body = Buffer.concat(chunks).toString("utf8");
|
|
191
391
|
const data = JSON.parse(body || "{}");
|
|
192
|
-
const
|
|
392
|
+
const content = formatIncomingPayload(data);
|
|
393
|
+
|
|
394
|
+
if (!content) {
|
|
395
|
+
res.writeHead(400, { "Content-Type": "application/json; charset=utf-8" });
|
|
396
|
+
res.end(JSON.stringify({ success: false, error: "Empty content" }));
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
193
399
|
|
|
194
|
-
if (
|
|
400
|
+
if (activeCtx) {
|
|
195
401
|
prefillEditor(activeCtx, content);
|
|
196
402
|
}
|
|
197
403
|
|
|
198
|
-
|
|
199
|
-
recordActiveSession(port,
|
|
404
|
+
const workdir = activeCtx?.cwd || ctx?.cwd || process.cwd();
|
|
405
|
+
recordActiveSession(port, workdir);
|
|
200
406
|
|
|
201
407
|
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
|
|
202
|
-
res.end(
|
|
408
|
+
res.end(
|
|
409
|
+
JSON.stringify({
|
|
410
|
+
success: true,
|
|
411
|
+
mode: "prefilled",
|
|
412
|
+
port,
|
|
413
|
+
workdir,
|
|
414
|
+
terminal: terminalInfo.terminal,
|
|
415
|
+
appName: terminalInfo.appName,
|
|
416
|
+
})
|
|
417
|
+
);
|
|
203
418
|
} catch (err: any) {
|
|
204
|
-
res.writeHead(400, { "Content-Type": "application/json" });
|
|
419
|
+
res.writeHead(400, { "Content-Type": "application/json; charset=utf-8" });
|
|
205
420
|
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
206
421
|
}
|
|
207
422
|
});
|
|
208
423
|
return;
|
|
209
424
|
}
|
|
210
425
|
|
|
211
|
-
res.writeHead(404, { "Content-Type": "application/json" });
|
|
426
|
+
res.writeHead(404, { "Content-Type": "application/json; charset=utf-8" });
|
|
212
427
|
res.end(JSON.stringify({ error: "Not Found" }));
|
|
213
428
|
});
|
|
214
429
|
|
|
@@ -278,6 +493,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
278
493
|
}
|
|
279
494
|
});
|
|
280
495
|
|
|
496
|
+
// 实时追踪最近交互的会话,确保多窗口/多终端时精准路由到用户正在使用的窗口
|
|
497
|
+
pi.on("input", async (_event, ctx) => {
|
|
498
|
+
activeCtx = ctx;
|
|
499
|
+
if (activePort) {
|
|
500
|
+
recordActiveSession(activePort, ctx?.cwd || process.cwd());
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
pi.on("agent_start", async (_event, ctx) => {
|
|
505
|
+
activeCtx = ctx;
|
|
506
|
+
if (activePort) {
|
|
507
|
+
recordActiveSession(activePort, ctx?.cwd || process.cwd());
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
|
|
281
511
|
pi.on("session_shutdown", async () => {
|
|
282
512
|
if (server) {
|
|
283
513
|
server.close();
|
package/server/bin/send-to-pi.js
CHANGED
|
@@ -4,50 +4,102 @@
|
|
|
4
4
|
* CLI Entry point for send-to-pi
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
const { startDaemon } = require('../src/index');
|
|
7
|
+
const { startDaemon, discoverAllActivePis } = require('../src/index');
|
|
8
8
|
const http = require('http');
|
|
9
|
-
const {
|
|
9
|
+
const {
|
|
10
|
+
BRIDGE_PORT,
|
|
11
|
+
USER_CONFIG_FILE,
|
|
12
|
+
LAST_TERMINAL_FILE,
|
|
13
|
+
loadUserConfig,
|
|
14
|
+
readLastTerminal,
|
|
15
|
+
} = require('../src/config');
|
|
10
16
|
|
|
11
17
|
const args = process.argv.slice(2);
|
|
12
18
|
const command = args[0] || 'start';
|
|
13
19
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
20
|
+
function checkBridge() {
|
|
21
|
+
return new Promise((resolve) => {
|
|
22
|
+
const req = http.request(
|
|
23
|
+
{
|
|
24
|
+
hostname: '127.0.0.1',
|
|
25
|
+
port: BRIDGE_PORT,
|
|
26
|
+
path: '/health',
|
|
27
|
+
method: 'GET',
|
|
28
|
+
timeout: 1200,
|
|
29
|
+
},
|
|
30
|
+
(res) => {
|
|
31
|
+
let data = '';
|
|
32
|
+
res.on('data', (c) => (data += c));
|
|
33
|
+
res.on('end', () => {
|
|
34
|
+
try {
|
|
35
|
+
resolve({ ok: true, statusCode: res.statusCode, info: JSON.parse(data) });
|
|
36
|
+
} catch {
|
|
37
|
+
resolve({ ok: true, statusCode: res.statusCode, info: null });
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
);
|
|
42
|
+
req.on('error', () => resolve({ ok: false }));
|
|
43
|
+
req.on('timeout', () => {
|
|
44
|
+
req.destroy();
|
|
45
|
+
resolve({ ok: false, timeout: true });
|
|
46
|
+
});
|
|
47
|
+
req.end();
|
|
42
48
|
});
|
|
49
|
+
}
|
|
43
50
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
51
|
+
if (command === 'status' || command === 'check') {
|
|
52
|
+
(async () => {
|
|
53
|
+
const [bridge, directSessions] = await Promise.all([
|
|
54
|
+
checkBridge(),
|
|
55
|
+
discoverAllActivePis(),
|
|
56
|
+
]);
|
|
49
57
|
|
|
50
|
-
|
|
58
|
+
if (bridge.ok) {
|
|
59
|
+
console.log(`✅ Bridge daemon is running on http://127.0.0.1:${BRIDGE_PORT}`);
|
|
60
|
+
if (bridge.info) {
|
|
61
|
+
console.log(JSON.stringify(bridge.info, null, 2));
|
|
62
|
+
}
|
|
63
|
+
} else {
|
|
64
|
+
console.log(`ℹ️ Bridge daemon is NOT running on port ${BRIDGE_PORT} (optional: needed only for cold-start launch).`);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (directSessions.length > 0) {
|
|
68
|
+
console.log(`\n✅ Active Pi sessions ready for zero-daemon direct send (${directSessions.length}):`);
|
|
69
|
+
for (const s of directSessions) {
|
|
70
|
+
const term = s.appName || s.terminal || 'unknown';
|
|
71
|
+
console.log(` - :${s.port} [${term}] ${s.workdir || ''} (pid ${s.pid})`);
|
|
72
|
+
}
|
|
73
|
+
process.exit(0);
|
|
74
|
+
} else {
|
|
75
|
+
console.log('\n⚠️ No active Pi sessions detected on ports 18091~18095.');
|
|
76
|
+
process.exit(bridge.ok ? 0 : 1);
|
|
77
|
+
}
|
|
78
|
+
})();
|
|
79
|
+
} else if (command === 'config') {
|
|
80
|
+
const cfg = loadUserConfig();
|
|
81
|
+
const last = readLastTerminal();
|
|
82
|
+
console.log(`Config file: ${USER_CONFIG_FILE}`);
|
|
83
|
+
console.log(`Last terminal file: ${LAST_TERMINAL_FILE}`);
|
|
84
|
+
console.log('\nEffective config:');
|
|
85
|
+
console.log(JSON.stringify(cfg, null, 2));
|
|
86
|
+
if (last) {
|
|
87
|
+
console.log('\nLast detected Pi terminal:');
|
|
88
|
+
console.log(JSON.stringify(last, null, 2));
|
|
89
|
+
}
|
|
90
|
+
console.log(`\nExample ${USER_CONFIG_FILE}:`);
|
|
91
|
+
console.log(
|
|
92
|
+
JSON.stringify(
|
|
93
|
+
{
|
|
94
|
+
terminal: 'rex',
|
|
95
|
+
launchCommand: 'rex run --interactive --cwd "{workdir}" --keep-open -- pi',
|
|
96
|
+
focusOnSend: false,
|
|
97
|
+
},
|
|
98
|
+
null,
|
|
99
|
+
2
|
|
100
|
+
)
|
|
101
|
+
);
|
|
102
|
+
process.exit(0);
|
|
51
103
|
} else if (command === 'extension' || command === 'ext' || command === 'open-extension') {
|
|
52
104
|
const path = require('path');
|
|
53
105
|
const { spawn } = require('child_process');
|
|
@@ -72,19 +124,22 @@ if (command === 'status' || command === 'check') {
|
|
|
72
124
|
process.exit(0);
|
|
73
125
|
} else if (command === 'help' || command === '--help' || command === '-h') {
|
|
74
126
|
console.log(`
|
|
75
|
-
Usage: send-to-pi [command]
|
|
127
|
+
Usage: send-to-pi [command]
|
|
76
128
|
|
|
77
129
|
Commands:
|
|
78
|
-
start Start the bridge daemon (
|
|
79
|
-
status Check
|
|
130
|
+
start Start the bridge daemon (optional: enables cold-start launch)
|
|
131
|
+
status Check bridge daemon and active Pi sessions (direct mode)
|
|
132
|
+
config Show config file path and effective settings
|
|
80
133
|
extension Open the Chrome extension folder to load in browser
|
|
81
134
|
help Show this help message
|
|
82
135
|
|
|
83
|
-
Options via Environment Variables:
|
|
136
|
+
Options via Environment Variables (or ~/.pi/send-to-pi/config.json):
|
|
84
137
|
PI_BRIDGE_PORT Daemon listening port (default: 18090)
|
|
85
|
-
PI_INTERNAL_PORT Pi session receiver port (default: 18091)
|
|
138
|
+
PI_INTERNAL_PORT Pi session receiver start port (default: 18091)
|
|
86
139
|
PI_WORKDIR Working directory to launch Pi terminal in
|
|
87
|
-
PI_TERMINAL Preferred terminal
|
|
140
|
+
PI_TERMINAL Preferred terminal (rex, ghostty, iterm2, warp, wezterm, kitty, alacritty, wt, terminal)
|
|
141
|
+
PI_LAUNCH_CMD Custom launch command template, supports {workdir}
|
|
142
|
+
PI_FOCUS_ON_SEND Set to "true" to focus the terminal app after sending (macOS)
|
|
88
143
|
`);
|
|
89
144
|
process.exit(0);
|
|
90
145
|
} else {
|