send-to-pi 1.1.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 -105
- package/README_CN.md +57 -108
- package/chrome-extension/background.js +275 -56
- 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 -16
- package/pi-extension/index.ts +334 -37
- package/server/bin/send-to-pi.js +97 -42
- package/server/src/clipboard.js +53 -0
- package/server/src/config.js +107 -10
- package/server/src/index.js +190 -46
- 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 +110 -43
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)) {
|
|
@@ -25,6 +57,22 @@ function getPiHomeDir(): string {
|
|
|
25
57
|
return dir;
|
|
26
58
|
}
|
|
27
59
|
|
|
60
|
+
function getSendToPiDir(): string {
|
|
61
|
+
const dir = path.join(getPiHomeDir(), "send-to-pi");
|
|
62
|
+
try {
|
|
63
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
64
|
+
} catch {}
|
|
65
|
+
return dir;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function getSessionRegistryFilePath(): string {
|
|
69
|
+
return path.join(getSendToPiDir(), "sessions.json");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function getLastTerminalFilePath(): string {
|
|
73
|
+
return path.join(getSendToPiDir(), "last-terminal.json");
|
|
74
|
+
}
|
|
75
|
+
|
|
28
76
|
function getActiveSessionFilePath(): string {
|
|
29
77
|
return path.join(getPiHomeDir(), "send-to-pi.json");
|
|
30
78
|
}
|
|
@@ -37,38 +85,249 @@ function getPendingFilePaths(): string[] {
|
|
|
37
85
|
];
|
|
38
86
|
}
|
|
39
87
|
|
|
40
|
-
function
|
|
88
|
+
function isProcessAlive(pid: number): boolean {
|
|
89
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
41
90
|
try {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
pid: process.pid,
|
|
45
|
-
port,
|
|
46
|
-
workdir: workDir,
|
|
47
|
-
updatedAt: Date.now(),
|
|
48
|
-
};
|
|
49
|
-
fs.writeFileSync(sessionFile, JSON.stringify(data, null, 2), "utf8");
|
|
91
|
+
process.kill(pid, 0);
|
|
92
|
+
return true;
|
|
50
93
|
} catch (err: any) {
|
|
51
|
-
|
|
94
|
+
return err && err.code === "EPERM";
|
|
52
95
|
}
|
|
53
96
|
}
|
|
54
97
|
|
|
55
|
-
function
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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;
|
|
64
119
|
}
|
|
65
|
-
}
|
|
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
|
+
}
|
|
238
|
+
|
|
239
|
+
function readSessionRecords(): SessionRecord[] {
|
|
240
|
+
try {
|
|
241
|
+
const registryFile = getSessionRegistryFilePath();
|
|
242
|
+
if (!fs.existsSync(registryFile)) return [];
|
|
243
|
+
const parsed = JSON.parse(fs.readFileSync(registryFile, "utf8"));
|
|
244
|
+
const sessions = Array.isArray(parsed) ? parsed : parsed?.sessions;
|
|
245
|
+
if (!Array.isArray(sessions)) return [];
|
|
246
|
+
return sessions.filter((s) => s && Number.isInteger(Number(s.port)) && isProcessAlive(Number(s.pid)));
|
|
247
|
+
} catch {
|
|
248
|
+
return [];
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function writeJsonAtomic(filePath: string, payload: unknown) {
|
|
253
|
+
const dir = path.dirname(filePath);
|
|
254
|
+
if (!fs.existsSync(dir)) {
|
|
255
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
256
|
+
}
|
|
257
|
+
const temporaryFile = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
258
|
+
fs.writeFileSync(temporaryFile, JSON.stringify(payload, null, 2), "utf8");
|
|
259
|
+
fs.renameSync(temporaryFile, filePath);
|
|
66
260
|
}
|
|
67
261
|
|
|
68
262
|
export default function (pi: ExtensionAPI) {
|
|
69
263
|
let server: http.Server | null = null;
|
|
70
264
|
let activeCtx: ExtensionContext | null = null;
|
|
71
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
|
+
}
|
|
72
331
|
|
|
73
332
|
function prefillEditor(ctx: ExtensionContext, textToInsert: string) {
|
|
74
333
|
if (!ctx || !ctx.ui) return;
|
|
@@ -100,48 +359,71 @@ export default function (pi: ExtensionAPI) {
|
|
|
100
359
|
}
|
|
101
360
|
|
|
102
361
|
if (req.method === "GET" && req.url === "/health") {
|
|
103
|
-
|
|
362
|
+
const workdir = activeCtx?.cwd || ctx?.cwd || process.cwd();
|
|
363
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
|
|
104
364
|
res.end(
|
|
105
365
|
JSON.stringify({
|
|
106
366
|
status: "alive",
|
|
367
|
+
version: "1.3.0",
|
|
107
368
|
port,
|
|
108
369
|
pid: process.pid,
|
|
109
|
-
workdir
|
|
110
|
-
|
|
370
|
+
workdir,
|
|
371
|
+
activeAt: lastActiveAt,
|
|
372
|
+
startedAt,
|
|
373
|
+
updatedAt: lastActiveAt,
|
|
374
|
+
terminal: terminalInfo.terminal,
|
|
375
|
+
appName: terminalInfo.appName,
|
|
376
|
+
window: terminalInfo.window,
|
|
111
377
|
})
|
|
112
378
|
);
|
|
113
379
|
return;
|
|
114
380
|
}
|
|
115
381
|
|
|
116
382
|
if (req.method === "POST" && req.url === "/receive") {
|
|
117
|
-
|
|
383
|
+
const chunks: Buffer[] = [];
|
|
118
384
|
req.on("data", (chunk) => {
|
|
119
|
-
|
|
385
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
120
386
|
});
|
|
121
387
|
|
|
122
388
|
req.on("end", () => {
|
|
123
389
|
try {
|
|
390
|
+
const body = Buffer.concat(chunks).toString("utf8");
|
|
124
391
|
const data = JSON.parse(body || "{}");
|
|
125
|
-
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
|
+
}
|
|
126
399
|
|
|
127
|
-
if (
|
|
400
|
+
if (activeCtx) {
|
|
128
401
|
prefillEditor(activeCtx, content);
|
|
129
402
|
}
|
|
130
403
|
|
|
131
|
-
|
|
132
|
-
recordActiveSession(port,
|
|
404
|
+
const workdir = activeCtx?.cwd || ctx?.cwd || process.cwd();
|
|
405
|
+
recordActiveSession(port, workdir);
|
|
133
406
|
|
|
134
|
-
res.writeHead(200, { "Content-Type": "application/json" });
|
|
135
|
-
res.end(
|
|
407
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
|
|
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
|
+
);
|
|
136
418
|
} catch (err: any) {
|
|
137
|
-
res.writeHead(400, { "Content-Type": "application/json" });
|
|
419
|
+
res.writeHead(400, { "Content-Type": "application/json; charset=utf-8" });
|
|
138
420
|
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
139
421
|
}
|
|
140
422
|
});
|
|
141
423
|
return;
|
|
142
424
|
}
|
|
143
425
|
|
|
144
|
-
res.writeHead(404, { "Content-Type": "application/json" });
|
|
426
|
+
res.writeHead(404, { "Content-Type": "application/json; charset=utf-8" });
|
|
145
427
|
res.end(JSON.stringify({ error: "Not Found" }));
|
|
146
428
|
});
|
|
147
429
|
|
|
@@ -211,17 +493,32 @@ export default function (pi: ExtensionAPI) {
|
|
|
211
493
|
}
|
|
212
494
|
});
|
|
213
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
|
+
|
|
214
511
|
pi.on("session_shutdown", async () => {
|
|
215
512
|
if (server) {
|
|
216
513
|
server.close();
|
|
217
514
|
server = null;
|
|
218
515
|
}
|
|
219
|
-
clearActiveSession();
|
|
516
|
+
clearActiveSession(activePort);
|
|
220
517
|
activeCtx = null;
|
|
221
518
|
activePort = null;
|
|
222
519
|
});
|
|
223
520
|
|
|
224
521
|
process.on("exit", () => {
|
|
225
|
-
clearActiveSession();
|
|
522
|
+
clearActiveSession(activePort);
|
|
226
523
|
});
|
|
227
524
|
}
|
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 {
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-platform clipboard fallback (zero external dependencies)
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
const { spawn } = require('child_process');
|
|
6
|
+
|
|
7
|
+
function pipeToCommand(cmd, args, text) {
|
|
8
|
+
return new Promise((resolve) => {
|
|
9
|
+
try {
|
|
10
|
+
const child = spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'] });
|
|
11
|
+
let settled = false;
|
|
12
|
+
const done = (ok) => {
|
|
13
|
+
if (!settled) {
|
|
14
|
+
settled = true;
|
|
15
|
+
resolve(ok);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
child.on('error', () => done(false));
|
|
19
|
+
child.on('close', (code) => done(code === 0));
|
|
20
|
+
child.stdin.on('error', () => done(false));
|
|
21
|
+
child.stdin.end(text, 'utf8');
|
|
22
|
+
} catch (_err) {
|
|
23
|
+
resolve(false);
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function copyToClipboard(text) {
|
|
29
|
+
if (!text) return false;
|
|
30
|
+
|
|
31
|
+
if (process.platform === 'darwin') {
|
|
32
|
+
return await pipeToCommand('pbcopy', [], text);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (process.platform === 'win32') {
|
|
36
|
+
// PowerShell Set-Clipboard preserves UTF-8 cleanly; fall back to clip.exe.
|
|
37
|
+
const psOk = await pipeToCommand(
|
|
38
|
+
'powershell.exe',
|
|
39
|
+
['-NoProfile', '-Command', '[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())'],
|
|
40
|
+
text
|
|
41
|
+
);
|
|
42
|
+
if (psOk) return true;
|
|
43
|
+
return await pipeToCommand('clip', [], text);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Linux / BSD
|
|
47
|
+
if (await pipeToCommand('wl-copy', [], text)) return true;
|
|
48
|
+
if (await pipeToCommand('xclip', ['-selection', 'clipboard'], text)) return true;
|
|
49
|
+
if (await pipeToCommand('xsel', ['--clipboard', '--input'], text)) return true;
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = { copyToClipboard };
|