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.
@@ -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 };
@@ -2,18 +2,12 @@ const path = require('path');
2
2
  const os = require('os');
3
3
  const fs = require('fs');
4
4
 
5
- const BRIDGE_PORT = parseInt(process.env.PI_BRIDGE_PORT, 10) || 18090;
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
9
-
10
- // 确保 ~/.pi 目录存在
11
5
  const piHomeDir = path.join(os.homedir(), '.pi');
12
6
  if (!fs.existsSync(piHomeDir)) {
13
7
  try {
14
8
  fs.mkdirSync(piHomeDir, { recursive: true });
15
9
  } catch (_err) {
16
- // 忽略创建失败(如权限受限),由操作系统临时目录兜底
10
+ // Fallback to OS temp dir if ~/.pi cannot be created.
17
11
  }
18
12
  }
19
13
 
@@ -21,20 +15,91 @@ const SEND_TO_PI_DIR = path.join(piHomeDir, 'send-to-pi');
21
15
  try {
22
16
  fs.mkdirSync(SEND_TO_PI_DIR, { recursive: true });
23
17
  } catch (_err) {
24
- // Ignore creation failures and let callers use the legacy path or temp file.
18
+ // Ignore creation errors.
25
19
  }
26
20
 
21
+ const USER_CONFIG_FILE = path.join(SEND_TO_PI_DIR, 'config.json');
27
22
  const SESSION_REGISTRY_FILE = path.join(SEND_TO_PI_DIR, 'sessions.json');
23
+ const LAST_TERMINAL_FILE = path.join(SEND_TO_PI_DIR, 'last-terminal.json');
28
24
  const ACTIVE_SESSION_FILE = path.join(piHomeDir, 'send-to-pi.json');
29
25
 
30
26
  const PENDING_FILE = fs.existsSync(piHomeDir)
31
27
  ? path.join(piHomeDir, 'pending-browser-input.txt')
32
28
  : path.join(os.tmpdir(), 'pi-pending-browser-input.txt');
33
29
 
34
- // 默认工作目录:环境变量优先,其次当前工作目录,兜底家目录
30
+ function readJsonSafe(filePath) {
31
+ try {
32
+ if (!fs.existsSync(filePath)) return null;
33
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
34
+ } catch (_err) {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ function readUserConfigFile() {
40
+ const parsed = readJsonSafe(USER_CONFIG_FILE);
41
+ return parsed && typeof parsed === 'object' ? parsed : {};
42
+ }
43
+
44
+ function readLastTerminal() {
45
+ const parsed = readJsonSafe(LAST_TERMINAL_FILE);
46
+ return parsed && typeof parsed === 'object' ? parsed : null;
47
+ }
48
+
49
+ function loadUserConfig() {
50
+ const fileCfg = readUserConfigFile();
51
+ const bridgePort =
52
+ parseInt(process.env.PI_BRIDGE_PORT, 10) ||
53
+ parseInt(fileCfg.bridgePort, 10) ||
54
+ 18090;
55
+ const internalPort =
56
+ parseInt(process.env.PI_INTERNAL_PORT, 10) ||
57
+ parseInt(fileCfg.internalPort, 10) ||
58
+ 18091;
59
+ const terminal = (
60
+ process.env.PI_TERMINAL ||
61
+ fileCfg.terminal ||
62
+ ''
63
+ ).trim().toLowerCase();
64
+ const launchCommand = (
65
+ process.env.PI_LAUNCH_CMD ||
66
+ fileCfg.launchCommand ||
67
+ ''
68
+ ).trim();
69
+ const workDir = (process.env.PI_WORKDIR || fileCfg.workDir || '').trim();
70
+ const focusEnv = (process.env.PI_FOCUS_ON_SEND || '').trim().toLowerCase();
71
+ const focusOnSend =
72
+ focusEnv !== ''
73
+ ? focusEnv === '1' || focusEnv === 'true' || focusEnv === 'yes'
74
+ : Boolean(fileCfg.focusOnSend);
75
+
76
+ return {
77
+ bridgePort,
78
+ internalPort,
79
+ internalPortStart: internalPort,
80
+ internalPortEnd: internalPort + 4,
81
+ terminal,
82
+ launchCommand,
83
+ workDir,
84
+ focusOnSend,
85
+ };
86
+ }
87
+
88
+ const initialCfg = loadUserConfig();
89
+ const BRIDGE_PORT = initialCfg.bridgePort;
90
+ const PI_INTERNAL_PORT = initialCfg.internalPort;
91
+ const PI_INTERNAL_PORT_START = initialCfg.internalPortStart;
92
+ const PI_INTERNAL_PORT_END = initialCfg.internalPortEnd;
93
+
94
+ // Workdir priority: PI_WORKDIR -> config.json -> last active Pi workdir -> cwd -> homedir
35
95
  function getWorkDir() {
36
- if (process.env.PI_WORKDIR && fs.existsSync(process.env.PI_WORKDIR)) {
37
- return process.env.PI_WORKDIR;
96
+ const cfg = loadUserConfig();
97
+ if (cfg.workDir && fs.existsSync(cfg.workDir)) {
98
+ return cfg.workDir;
99
+ }
100
+ const last = readLastTerminal();
101
+ if (last && last.workdir && fs.existsSync(last.workdir)) {
102
+ return last.workdir;
38
103
  }
39
104
  const cwd = process.cwd();
40
105
  if (cwd && fs.existsSync(cwd) && cwd !== '/' && !cwd.endsWith('\\Windows\\system32')) {
@@ -43,13 +108,36 @@ function getWorkDir() {
43
108
  return os.homedir();
44
109
  }
45
110
 
111
+ function getPreferredTerminal() {
112
+ const cfg = loadUserConfig();
113
+ return cfg.terminal || '';
114
+ }
115
+
116
+ function getCustomLaunchCommand() {
117
+ const cfg = loadUserConfig();
118
+ return cfg.launchCommand || '';
119
+ }
120
+
121
+ function shouldFocusOnSend() {
122
+ const cfg = loadUserConfig();
123
+ return cfg.focusOnSend;
124
+ }
125
+
46
126
  module.exports = {
47
127
  BRIDGE_PORT,
48
128
  PI_INTERNAL_PORT,
49
129
  PI_INTERNAL_PORT_START,
50
130
  PI_INTERNAL_PORT_END,
131
+ SEND_TO_PI_DIR,
132
+ USER_CONFIG_FILE,
51
133
  ACTIVE_SESSION_FILE,
52
134
  SESSION_REGISTRY_FILE,
135
+ LAST_TERMINAL_FILE,
53
136
  PENDING_FILE,
137
+ loadUserConfig,
138
+ readLastTerminal,
54
139
  getWorkDir,
140
+ getPreferredTerminal,
141
+ getCustomLaunchCommand,
142
+ shouldFocusOnSend,
55
143
  };
@@ -3,6 +3,7 @@
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/sessions.json)
6
+ * Supports 4-layer adaptive cold-start terminal launching & clipboard fallback.
6
7
  */
7
8
 
8
9
  const http = require('http');
@@ -17,8 +18,11 @@ const {
17
18
  SESSION_REGISTRY_FILE,
18
19
  PENDING_FILE,
19
20
  getWorkDir,
21
+ readLastTerminal,
22
+ shouldFocusOnSend,
20
23
  } = require('./config');
21
- const { launchTerminal } = require('./launchers');
24
+ const { launchTerminal, focusTerminal } = require('./launchers');
25
+ const { copyToClipboard } = require('./clipboard');
22
26
 
23
27
  function checkPiHealth(port) {
24
28
  return new Promise((resolve) => {
@@ -74,67 +78,82 @@ function writeSessionRegistry(sessions) {
74
78
  try {
75
79
  const directory = path.dirname(SESSION_REGISTRY_FILE);
76
80
  fs.mkdirSync(directory, { recursive: true });
77
- const temporaryFile = `${SESSION_REGISTRY_FILE}.tmp-${process.pid}`;
81
+ const temporaryFile = `${SESSION_REGISTRY_FILE}.tmp-${process.pid}-${Date.now()}`;
78
82
  fs.writeFileSync(
79
83
  temporaryFile,
80
- JSON.stringify({ version: 1, sessions }, null, 2),
84
+ JSON.stringify({ version: 2, sessions }, null, 2),
81
85
  'utf8'
82
86
  );
83
87
  fs.renameSync(temporaryFile, SESSION_REGISTRY_FILE);
84
88
  } catch (_e) {
85
- // Registry cleanup is best effort. The legacy file and port scan remain available.
89
+ // Registry cleanup is best effort.
86
90
  }
87
91
  }
88
92
 
89
- async function findActivePi() {
90
- // 1. 优先读取会话注册表,并按最近活跃时间路由。
91
- const registeredSessions = readSessionRegistry();
92
- if (registeredSessions) {
93
- const candidates = [...registeredSessions].sort(
94
- (a, b) => Number(b.activeAt || b.updatedAt || 0) - Number(a.activeAt || a.updatedAt || 0)
95
- );
96
- const activeSessions = [];
97
- let selected = null;
98
-
99
- for (const session of candidates) {
100
- const port = Number(session.port);
101
- const health = await checkPiHealth(port);
102
- if (!health.ok) continue;
103
-
104
- const activeSession = { ...session, ...(health.info || {}), port };
105
- activeSessions.push(activeSession);
106
- if (!selected) {
107
- selected = { port, source: 'session-registry', session: activeSession };
108
- }
109
- }
93
+ async function discoverAllActivePis(portStart = PI_INTERNAL_PORT_START, portEnd = PI_INTERNAL_PORT_END) {
94
+ const byPort = new Map();
110
95
 
111
- if (activeSessions.length !== registeredSessions.length) {
112
- writeSessionRegistry(activeSessions);
113
- }
114
- if (selected) return selected;
96
+ // Probe full port range in parallel so no live Pi is ever missed.
97
+ const ports = [];
98
+ for (let p = portStart; p <= portEnd; p++) ports.push(p);
99
+
100
+ const registeredSessions = readSessionRegistry() || [];
101
+ for (const s of registeredSessions) {
102
+ const p = Number(s.port);
103
+ if (Number.isInteger(p) && !ports.includes(p)) ports.push(p);
104
+ }
105
+
106
+ const healthResults = await Promise.all(ports.map((p) => checkPiHealth(p)));
107
+ const registryByPort = new Map(registeredSessions.map((s) => [Number(s.port), s]));
108
+
109
+ for (const h of healthResults) {
110
+ if (!h.ok) continue;
111
+ const reg = registryByPort.get(h.port) || {};
112
+ const merged = {
113
+ ...reg,
114
+ ...(h.info || {}),
115
+ port: h.port,
116
+ activeAt: Math.max(
117
+ Number((h.info && (h.info.activeAt || h.info.updatedAt)) || 0),
118
+ Number(reg.activeAt || reg.updatedAt || 0)
119
+ ),
120
+ };
121
+ byPort.set(h.port, merged);
122
+ }
123
+
124
+ const alive = Array.from(byPort.values()).sort(
125
+ (a, b) => Number(b.activeAt || b.updatedAt || 0) - Number(a.activeAt || a.updatedAt || 0)
126
+ );
127
+
128
+ // Clean stale dead sessions from registry if it existed.
129
+ if (registeredSessions.length > 0 && alive.length !== registeredSessions.length) {
130
+ writeSessionRegistry(alive);
131
+ }
132
+
133
+ return alive;
134
+ }
135
+
136
+ async function findActivePi() {
137
+ const all = await discoverAllActivePis();
138
+ if (all.length > 0) {
139
+ return { port: all[0].port, source: 'active-discovery', session: all[0] };
115
140
  }
116
141
 
117
- // 2. 兼容旧版 ~/.pi/send-to-pi.json 活跃单例信息。
142
+ // Legacy fallback file check (in case user runs on a custom port outside 18091~18095).
118
143
  if (fs.existsSync(ACTIVE_SESSION_FILE)) {
119
144
  try {
120
145
  const session = JSON.parse(fs.readFileSync(ACTIVE_SESSION_FILE, 'utf8'));
121
146
  if (session && session.port) {
122
147
  const health = await checkPiHealth(Number(session.port));
123
148
  if (health.ok) {
124
- return { port: Number(session.port), source: 'session-file', session };
149
+ return {
150
+ port: Number(session.port),
151
+ source: 'session-file',
152
+ session: { ...session, ...(health.info || {}) },
153
+ };
125
154
  }
126
155
  }
127
- } catch (_e) {
128
- // 忽略文件解析错误,继续范围扫描。
129
- }
130
- }
131
-
132
- // 3. 备用兜底:顺序探测端口范围 (18091 ~ 18095)。
133
- for (let port = PI_INTERNAL_PORT_START; port <= PI_INTERNAL_PORT_END; port++) {
134
- const health = await checkPiHealth(port);
135
- if (health.ok) {
136
- return { port, source: 'port-scan', session: health.info };
137
- }
156
+ } catch (_e) {}
138
157
  }
139
158
 
140
159
  return null;
@@ -156,11 +175,19 @@ function forwardToPi(port, content) {
156
175
  timeout: 1500,
157
176
  },
158
177
  (res) => {
159
- if (res.statusCode === 200) {
160
- resolve(true);
161
- } else {
162
- reject(new Error(`Pi receiver on port ${port} responded with HTTP ${res.statusCode}`));
163
- }
178
+ let raw = '';
179
+ res.on('data', (c) => (raw += c));
180
+ res.on('end', () => {
181
+ if (res.statusCode === 200) {
182
+ try {
183
+ resolve(JSON.parse(raw || '{}'));
184
+ } catch {
185
+ resolve({ success: true, port });
186
+ }
187
+ } else {
188
+ reject(new Error(`Pi receiver on port ${port} responded with HTTP ${res.statusCode}`));
189
+ }
190
+ });
164
191
  }
165
192
  );
166
193
 
@@ -197,7 +224,13 @@ function formatContent(payload) {
197
224
  return `${titleLabel}: ${title || (isZh ? '网页' : 'Page')}\n${linkLabel}: ${url || ''}\n\n`;
198
225
  }
199
226
 
200
- function createBridgeServer() {
227
+ function createBridgeServer(deps = {}) {
228
+ const launch = deps.launchTerminal || launchTerminal;
229
+ const focus = deps.focusTerminal || focusTerminal;
230
+ const clipboard = deps.copyToClipboard || copyToClipboard;
231
+ const discover = deps.findActivePi || findActivePi;
232
+ const discoverAll = deps.discoverAllActivePis || discoverAllActivePis;
233
+
201
234
  const server = http.createServer(async (req, res) => {
202
235
  res.setHeader('Access-Control-Allow-Origin', '*');
203
236
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
@@ -210,15 +243,28 @@ function createBridgeServer() {
210
243
  }
211
244
 
212
245
  if (req.method === 'GET' && req.url === '/health') {
213
- const activePi = await findActivePi();
214
- res.writeHead(200, { 'Content-Type': 'application/json' });
246
+ const sessions = await discoverAll();
247
+ const activePi = sessions[0] || null;
248
+ const lastTerminal = readLastTerminal();
249
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
215
250
  res.end(
216
251
  JSON.stringify({
217
252
  status: 'ok',
253
+ version: '1.3.0',
218
254
  platform: process.platform,
219
255
  bridgePort: BRIDGE_PORT,
220
256
  defaultInternalPort: PI_INTERNAL_PORT,
221
- activePi: activePi ? { port: activePi.port, source: activePi.source } : null,
257
+ activePi: activePi
258
+ ? {
259
+ port: activePi.port,
260
+ workdir: activePi.workdir,
261
+ terminal: activePi.terminal || null,
262
+ appName: activePi.appName || null,
263
+ activeAt: activePi.activeAt || null,
264
+ }
265
+ : null,
266
+ sessions,
267
+ lastTerminal,
222
268
  workDir: getWorkDir(),
223
269
  })
224
270
  );
@@ -237,18 +283,25 @@ function createBridgeServer() {
237
283
  const payload = JSON.parse(body || '{}');
238
284
  const content = formatContent(payload);
239
285
 
240
- // 1. 尝试动态发现当前活跃的 Pi 实例并转发
241
- const activePi = await findActivePi();
286
+ // 1. Hot delivery to the most recently active Pi session (100% terminal-agnostic).
287
+ const activePi = await discover();
242
288
  if (activePi) {
243
289
  try {
244
- await forwardToPi(activePi.port, content);
245
- console.log(`[Bridge] Successfully forwarded content to Pi terminal on port ${activePi.port}.`);
246
- res.writeHead(200, { 'Content-Type': 'application/json' });
290
+ const reply = await forwardToPi(activePi.port, content);
291
+ const sessionMeta = { ...(activePi.session || {}), ...(reply || {}) };
292
+ if (shouldFocusOnSend()) {
293
+ focus(sessionMeta).catch(() => {});
294
+ }
295
+ console.log(`[Bridge] Forwarded content to Pi on port ${activePi.port} (${sessionMeta.terminal || 'unknown'}).`);
296
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
247
297
  res.end(
248
298
  JSON.stringify({
249
299
  success: true,
250
300
  mode: 'prefilled',
251
301
  port: activePi.port,
302
+ workdir: sessionMeta.workdir || null,
303
+ terminal: sessionMeta.terminal || null,
304
+ appName: sessionMeta.appName || null,
252
305
  message: '已直接填入活跃的 Pi 输入框!',
253
306
  })
254
307
  );
@@ -258,31 +311,58 @@ function createBridgeServer() {
258
311
  }
259
312
  }
260
313
 
261
- // 2. 当前没有运行中的 Pi,进行冷启动唤醒流程
314
+ // 2. Cold-start flow: write pending file and launch terminal via 4-layer adaptive launcher.
262
315
  console.log('[Bridge] No active Pi detected. Writing pending file and launching terminal...');
263
316
  fs.writeFileSync(PENDING_FILE, content, 'utf8');
264
317
 
265
318
  const workDir = getWorkDir();
266
- const launchResult = await launchTerminal(workDir);
319
+ const launchResult = await launch(workDir);
320
+
321
+ if (launchResult && launchResult.success) {
322
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
323
+ res.end(
324
+ JSON.stringify({
325
+ success: true,
326
+ mode: 'launched',
327
+ terminal: launchResult.terminal || 'Default Terminal',
328
+ message: '已启动终端唤醒 Pi,内容已在输入框备好!',
329
+ })
330
+ );
331
+ return;
332
+ }
333
+
334
+ // 3. Layer 4 fallback: copy formatted Markdown to clipboard so content is never lost.
335
+ const copied = await clipboard(content);
336
+ if (copied) {
337
+ console.warn('[Bridge] Terminal launch failed; copied content to system clipboard as fallback.');
338
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
339
+ res.end(
340
+ JSON.stringify({
341
+ success: true,
342
+ mode: 'clipboard',
343
+ error: launchResult && launchResult.error,
344
+ message: '未能自动拉起终端,已复制到剪贴板,请直接粘贴!',
345
+ })
346
+ );
347
+ return;
348
+ }
267
349
 
268
- res.writeHead(200, { 'Content-Type': 'application/json' });
350
+ res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
269
351
  res.end(
270
352
  JSON.stringify({
271
- success: true,
272
- mode: 'launched',
273
- terminal: launchResult.terminal || 'Default Terminal',
274
- message: '已启动终端唤醒 Pi,内容已在输入框备好!',
353
+ success: false,
354
+ error: (launchResult && launchResult.error) || 'Failed to launch terminal and clipboard fallback failed.',
275
355
  })
276
356
  );
277
357
  } catch (e) {
278
- res.writeHead(400, { 'Content-Type': 'application/json' });
358
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
279
359
  res.end(JSON.stringify({ success: false, error: e.message }));
280
360
  }
281
361
  });
282
362
  return;
283
363
  }
284
364
 
285
- res.writeHead(404, { 'Content-Type': 'application/json' });
365
+ res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
286
366
  res.end(JSON.stringify({ error: 'Not Found' }));
287
367
  });
288
368
 
@@ -294,7 +374,7 @@ function startDaemon() {
294
374
 
295
375
  server.listen(BRIDGE_PORT, '127.0.0.1', () => {
296
376
  console.log(`===============================================`);
297
- console.log(`🚀 send-to-pi Bridge Daemon is running!`);
377
+ console.log(`🚀 send-to-pi Bridge Daemon v1.3.0 is running!`);
298
378
  console.log(`📡 Listening on: http://127.0.0.1:${BRIDGE_PORT}`);
299
379
  console.log(`💻 Platform: ${process.platform}`);
300
380
  console.log(`📂 Work Dir: ${getWorkDir()}`);
@@ -318,4 +398,10 @@ if (require.main === module) {
318
398
  startDaemon();
319
399
  }
320
400
 
321
- module.exports = { startDaemon, createBridgeServer, findActivePi, formatContent };
401
+ module.exports = {
402
+ startDaemon,
403
+ createBridgeServer,
404
+ findActivePi,
405
+ discoverAllActivePis,
406
+ formatContent,
407
+ };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Layer 1 Escape Hatch: Custom user-defined terminal launch command template.
3
+ *
4
+ * Example (~/.pi/send-to-pi/config.json or PI_LAUNCH_CMD):
5
+ * rex run --interactive --cwd "{workdir}" --keep-open -- pi
6
+ * kitty --directory "{workdir}" pi
7
+ */
8
+
9
+ const { spawn } = require('child_process');
10
+
11
+ function shellEscape(value) {
12
+ if (process.platform === 'win32') {
13
+ return String(value).replace(/"/g, '""');
14
+ }
15
+ return String(value).replace(/(["\\$`])/g, '\\$1');
16
+ }
17
+
18
+ function launchCustomCommand(template, workDir) {
19
+ return new Promise((resolve) => {
20
+ const trimmed = (template || '').trim();
21
+ if (!trimmed) {
22
+ resolve({ success: false, error: 'Empty custom launch command' });
23
+ return;
24
+ }
25
+
26
+ const command = trimmed.replace(/\{workdir\}/gi, shellEscape(workDir));
27
+
28
+ try {
29
+ const child = spawn(command, {
30
+ cwd: workDir,
31
+ env: { ...process.env, PI_WORKDIR: workDir },
32
+ shell: true,
33
+ detached: true,
34
+ stdio: 'ignore',
35
+ });
36
+
37
+ let failed = false;
38
+ child.on('error', (err) => {
39
+ failed = true;
40
+ resolve({ success: false, error: err.message });
41
+ });
42
+
43
+ child.unref();
44
+ setTimeout(() => {
45
+ if (!failed) {
46
+ resolve({ success: true, terminal: 'Custom Command', command });
47
+ }
48
+ }, 250);
49
+ } catch (err) {
50
+ resolve({ success: false, error: err.message });
51
+ }
52
+ });
53
+ }
54
+
55
+ module.exports = { launchCustomCommand };