@dmsdc-ai/aigentry-telepty 0.1.8 → 0.1.10
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 +13 -0
- package/cli.js +85 -39
- package/daemon-control.js +223 -0
- package/daemon.js +43 -0
- package/install.js +16 -1
- package/install.ps1 +7 -1
- package/install.sh +6 -1
- package/interactive-terminal.js +18 -1
- package/package.json +5 -4
- package/runtime-info.js +41 -0
package/README.md
CHANGED
|
@@ -20,7 +20,14 @@ Open PowerShell as Administrator and run:
|
|
|
20
20
|
iwr -useb https://raw.githubusercontent.com/dmsdc-ai/aigentry-telepty/main/install.ps1 | iex
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
+
You can also launch the installer through npm without downloading the script first:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npx --yes @dmsdc-ai/aigentry-telepty@latest
|
|
27
|
+
```
|
|
28
|
+
|
|
23
29
|
*These single commands will install the package globally and automatically configure it to run as a background service specific to your OS (`systemd` for Linux, `launchd` for macOS, or a detached background process for Windows).*
|
|
30
|
+
The installer now stops older local telepty daemons before starting the new one, so updates do not leave duplicate background processes behind.
|
|
24
31
|
|
|
25
32
|
## Seamless Usage
|
|
26
33
|
|
|
@@ -56,6 +63,12 @@ npm run test:watch
|
|
|
56
63
|
|
|
57
64
|
The automated suite covers config generation, daemon HTTP APIs, WebSocket attach/output flow, bus events, session deletion regressions, and CLI smoke tests against a real daemon process.
|
|
58
65
|
|
|
66
|
+
If you ever need to manually clear stale local daemon processes:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
telepty cleanup-daemons
|
|
70
|
+
```
|
|
71
|
+
|
|
59
72
|
## Skill Installation
|
|
60
73
|
|
|
61
74
|
The package installer opens the telepty skill TUI automatically when you run it in a terminal.
|
package/cli.js
CHANGED
|
@@ -9,7 +9,9 @@ const prompts = require('prompts');
|
|
|
9
9
|
const updateNotifier = require('update-notifier');
|
|
10
10
|
const pkg = require('./package.json');
|
|
11
11
|
const { getConfig } = require('./auth');
|
|
12
|
-
const {
|
|
12
|
+
const { cleanupDaemonProcesses } = require('./daemon-control');
|
|
13
|
+
const { attachInteractiveTerminal, getTerminalSize } = require('./interactive-terminal');
|
|
14
|
+
const { getRuntimeInfo } = require('./runtime-info');
|
|
13
15
|
const { runInteractiveSkillInstaller } = require('./skill-installer');
|
|
14
16
|
const args = process.argv.slice(2);
|
|
15
17
|
|
|
@@ -32,6 +34,28 @@ const fetchWithAuth = (url, options = {}) => {
|
|
|
32
34
|
return fetch(url, { ...options, headers });
|
|
33
35
|
};
|
|
34
36
|
|
|
37
|
+
async function getDaemonMeta(host = REMOTE_HOST) {
|
|
38
|
+
try {
|
|
39
|
+
const res = await fetchWithAuth(`http://${host}:${PORT}/api/meta`, {
|
|
40
|
+
signal: AbortSignal.timeout(1500)
|
|
41
|
+
});
|
|
42
|
+
if (!res.ok) {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
return await res.json();
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function startDetachedDaemon() {
|
|
52
|
+
const cp = spawn(process.argv[0], [process.argv[1], 'daemon'], {
|
|
53
|
+
detached: true,
|
|
54
|
+
stdio: 'ignore'
|
|
55
|
+
});
|
|
56
|
+
cp.unref();
|
|
57
|
+
}
|
|
58
|
+
|
|
35
59
|
async function discoverSessions() {
|
|
36
60
|
await ensureDaemonRunning();
|
|
37
61
|
const hosts = ['127.0.0.1'];
|
|
@@ -71,22 +95,42 @@ async function discoverSessions() {
|
|
|
71
95
|
return allSessions;
|
|
72
96
|
}
|
|
73
97
|
|
|
74
|
-
async function ensureDaemonRunning() {
|
|
98
|
+
async function ensureDaemonRunning(options = {}) {
|
|
75
99
|
if (REMOTE_HOST !== '127.0.0.1') return; // Only auto-start local daemon
|
|
100
|
+
|
|
101
|
+
const requiredCapabilities = options.requiredCapabilities || [];
|
|
102
|
+
|
|
76
103
|
try {
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const cp = spawn(process.argv[0], [process.argv[1], 'daemon'], {
|
|
83
|
-
detached: true,
|
|
84
|
-
stdio: 'ignore'
|
|
104
|
+
const meta = await getDaemonMeta('127.0.0.1');
|
|
105
|
+
const hasCapabilities = meta && requiredCapabilities.every((item) => meta.capabilities.includes(item));
|
|
106
|
+
|
|
107
|
+
const sessionsRes = await fetchWithAuth(`${DAEMON_URL}/api/sessions`, {
|
|
108
|
+
signal: AbortSignal.timeout(1500)
|
|
85
109
|
});
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
110
|
+
|
|
111
|
+
if (sessionsRes.ok && hasCapabilities) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (sessionsRes.ok && !meta) {
|
|
116
|
+
process.stdout.write('\x1b[33m⚙️ Found an older local telepty daemon. Restarting it...\x1b[0m\n');
|
|
117
|
+
cleanupDaemonProcesses();
|
|
118
|
+
} else if (sessionsRes.ok && meta) {
|
|
119
|
+
process.stdout.write('\x1b[33m⚙️ Found a local telepty daemon without the required features. Restarting it...\x1b[0m\n');
|
|
120
|
+
cleanupDaemonProcesses();
|
|
121
|
+
}
|
|
122
|
+
} catch (e) {
|
|
123
|
+
// Continue to auto-start below.
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
process.stdout.write('\x1b[33m⚙️ Auto-starting local telepty daemon...\x1b[0m\n');
|
|
127
|
+
cleanupDaemonProcesses();
|
|
128
|
+
startDetachedDaemon();
|
|
129
|
+
await new Promise(r => setTimeout(r, 1000));
|
|
130
|
+
|
|
131
|
+
const meta = await getDaemonMeta('127.0.0.1');
|
|
132
|
+
if (!meta || !requiredCapabilities.every((item) => meta.capabilities.includes(item))) {
|
|
133
|
+
console.error('❌ Failed to start a compatible local telepty daemon. Try `telepty cleanup-daemons` or rerun the installer.');
|
|
90
134
|
}
|
|
91
135
|
}
|
|
92
136
|
|
|
@@ -101,7 +145,10 @@ async function manageInteractiveAttach(sessionId, targetHost) {
|
|
|
101
145
|
console.log(`\n\x1b[32mEntered room '${sessionId}'.\x1b[0m\n`);
|
|
102
146
|
cleanupTerminal = attachInteractiveTerminal(process.stdin, process.stdout, {
|
|
103
147
|
onData: (d) => ws.send(JSON.stringify({ type: 'input', data: d.toString() })),
|
|
104
|
-
onResize: () =>
|
|
148
|
+
onResize: () => {
|
|
149
|
+
const size = getTerminalSize(process.stdout, { cols: 80, rows: 30 });
|
|
150
|
+
ws.send(JSON.stringify({ type: 'resize', cols: size.cols, rows: size.rows }));
|
|
151
|
+
}
|
|
105
152
|
});
|
|
106
153
|
});
|
|
107
154
|
ws.on('message', m => {
|
|
@@ -135,8 +182,10 @@ async function manageInteractiveAttach(sessionId, targetHost) {
|
|
|
135
182
|
}
|
|
136
183
|
|
|
137
184
|
async function manageInteractive() {
|
|
185
|
+
const runtimeInfo = getRuntimeInfo(__dirname);
|
|
138
186
|
console.clear();
|
|
139
187
|
console.log('\x1b[36m\x1b[1m⚡ Telepty Agent Manager\x1b[0m\n');
|
|
188
|
+
console.log(`\x1b[90mVersion ${runtimeInfo.version} Updated ${runtimeInfo.updatedAtLabel}\x1b[0m\n`);
|
|
140
189
|
|
|
141
190
|
while (true) {
|
|
142
191
|
const response = await prompts({
|
|
@@ -160,11 +209,7 @@ async function manageInteractive() {
|
|
|
160
209
|
try {
|
|
161
210
|
execSync('npm install -g @dmsdc-ai/aigentry-telepty@latest', { stdio: 'inherit' });
|
|
162
211
|
console.log('\n\x1b[32m✅ Update complete! Restarting daemon...\x1b[0m');
|
|
163
|
-
|
|
164
|
-
const os = require('os');
|
|
165
|
-
if (os.platform() === 'win32') execSync('taskkill /IM node.exe /FI "WINDOWTITLE eq telepty daemon*" /F', { stdio: 'ignore' });
|
|
166
|
-
else execSync('pkill -f "telepty daemon"', { stdio: 'ignore' });
|
|
167
|
-
} catch(e) {}
|
|
212
|
+
cleanupDaemonProcesses();
|
|
168
213
|
} catch (e) {
|
|
169
214
|
console.error('\n❌ Update failed.\n');
|
|
170
215
|
}
|
|
@@ -178,11 +223,8 @@ async function manageInteractive() {
|
|
|
178
223
|
|
|
179
224
|
if (response.action === 'daemon') {
|
|
180
225
|
console.log('\n\x1b[33mStarting daemon in background...\x1b[0m');
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
stdio: 'ignore'
|
|
184
|
-
});
|
|
185
|
-
cp.unref();
|
|
226
|
+
cleanupDaemonProcesses();
|
|
227
|
+
startDetachedDaemon();
|
|
186
228
|
console.log('✅ Daemon started.\n');
|
|
187
229
|
continue;
|
|
188
230
|
}
|
|
@@ -313,16 +355,7 @@ async function main() {
|
|
|
313
355
|
try {
|
|
314
356
|
execSync('npm install -g @dmsdc-ai/aigentry-telepty@latest', { stdio: 'inherit' });
|
|
315
357
|
console.log('\n\x1b[32m✅ Update complete! Restarting daemon...\x1b[0m');
|
|
316
|
-
|
|
317
|
-
// Kill local daemon if running, so it auto-restarts on next command
|
|
318
|
-
try {
|
|
319
|
-
if (os.platform() === 'win32') {
|
|
320
|
-
execSync('taskkill /IM node.exe /FI "WINDOWTITLE eq telepty daemon*" /F', { stdio: 'ignore' });
|
|
321
|
-
} else {
|
|
322
|
-
execSync('pkill -f "telepty daemon"', { stdio: 'ignore' });
|
|
323
|
-
}
|
|
324
|
-
} catch (e) {} // Ignore if not running
|
|
325
|
-
|
|
358
|
+
cleanupDaemonProcesses();
|
|
326
359
|
console.log('🎉 You are now using the latest version.');
|
|
327
360
|
} catch (e) {
|
|
328
361
|
console.error('\n❌ Update failed. Please try running: npm install -g @dmsdc-ai/aigentry-telepty@latest');
|
|
@@ -330,6 +363,16 @@ async function main() {
|
|
|
330
363
|
return;
|
|
331
364
|
}
|
|
332
365
|
|
|
366
|
+
if (cmd === 'cleanup-daemons') {
|
|
367
|
+
const results = cleanupDaemonProcesses();
|
|
368
|
+
console.log(`Stopped ${results.stopped.length} telepty daemon(s).`);
|
|
369
|
+
if (results.failed.length > 0) {
|
|
370
|
+
console.log(`Failed to stop ${results.failed.length} daemon(s).`);
|
|
371
|
+
process.exitCode = 1;
|
|
372
|
+
}
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
|
|
333
376
|
if (cmd === 'daemon') {
|
|
334
377
|
console.log('Starting telepty daemon...');
|
|
335
378
|
require('./daemon.js');
|
|
@@ -411,7 +454,7 @@ async function main() {
|
|
|
411
454
|
sessionId = path.basename(command);
|
|
412
455
|
}
|
|
413
456
|
|
|
414
|
-
await ensureDaemonRunning();
|
|
457
|
+
await ensureDaemonRunning({ requiredCapabilities: ['wrapped-sessions'] });
|
|
415
458
|
|
|
416
459
|
// Register session with daemon
|
|
417
460
|
try {
|
|
@@ -481,7 +524,8 @@ async function main() {
|
|
|
481
524
|
child.write(data.toString());
|
|
482
525
|
},
|
|
483
526
|
onResize: () => {
|
|
484
|
-
|
|
527
|
+
const size = getTerminalSize(process.stdout, { cols: 120, rows: 40 });
|
|
528
|
+
child.resize(size.cols, size.rows);
|
|
485
529
|
}
|
|
486
530
|
});
|
|
487
531
|
|
|
@@ -557,10 +601,11 @@ async function main() {
|
|
|
557
601
|
ws.send(JSON.stringify({ type: 'input', data: data.toString() }));
|
|
558
602
|
},
|
|
559
603
|
onResize: () => {
|
|
604
|
+
const size = getTerminalSize(process.stdout, { cols: 80, rows: 30 });
|
|
560
605
|
ws.send(JSON.stringify({
|
|
561
606
|
type: 'resize',
|
|
562
|
-
cols:
|
|
563
|
-
rows:
|
|
607
|
+
cols: size.cols,
|
|
608
|
+
rows: size.rows
|
|
564
609
|
}));
|
|
565
610
|
}
|
|
566
611
|
});
|
|
@@ -739,6 +784,7 @@ Usage:
|
|
|
739
784
|
telepty multicast <id1,id2> "<prompt>" Inject text into multiple specific sessions
|
|
740
785
|
telepty broadcast "<prompt>" Inject text into ALL active sessions
|
|
741
786
|
telepty rename <old_id> <new_id> Rename a session (updates terminal title too)
|
|
787
|
+
telepty cleanup-daemons Stop old local telepty daemon processes
|
|
742
788
|
telepty listen Listen to the event bus and print JSON to stdout
|
|
743
789
|
telepty monitor Human-readable real-time billboard of bus events
|
|
744
790
|
telepty update Update telepty to the latest version
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { execFileSync, execSync } = require('child_process');
|
|
7
|
+
|
|
8
|
+
const TELEPTY_DIR = path.join(os.homedir(), '.telepty');
|
|
9
|
+
const DAEMON_STATE_FILE = path.join(TELEPTY_DIR, 'daemon-state.json');
|
|
10
|
+
|
|
11
|
+
function ensureTeleptyDir() {
|
|
12
|
+
fs.mkdirSync(TELEPTY_DIR, { recursive: true, mode: 0o700 });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function sleepMs(ms) {
|
|
16
|
+
const buffer = new SharedArrayBuffer(4);
|
|
17
|
+
const view = new Int32Array(buffer);
|
|
18
|
+
Atomics.wait(view, 0, 0, ms);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function isProcessRunning(pid) {
|
|
22
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
process.kill(pid, 0);
|
|
28
|
+
return true;
|
|
29
|
+
} catch (error) {
|
|
30
|
+
return error.code === 'EPERM';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function readDaemonState() {
|
|
35
|
+
if (!fs.existsSync(DAEMON_STATE_FILE)) {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(fs.readFileSync(DAEMON_STATE_FILE, 'utf8'));
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function writeDaemonState(state) {
|
|
47
|
+
ensureTeleptyDir();
|
|
48
|
+
fs.writeFileSync(DAEMON_STATE_FILE, JSON.stringify(state, null, 2), { mode: 0o600 });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function clearDaemonState(expectedPid) {
|
|
52
|
+
if (!fs.existsSync(DAEMON_STATE_FILE)) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (expectedPid === undefined) {
|
|
57
|
+
fs.rmSync(DAEMON_STATE_FILE, { force: true });
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const current = readDaemonState();
|
|
62
|
+
if (!current || current.pid === expectedPid) {
|
|
63
|
+
fs.rmSync(DAEMON_STATE_FILE, { force: true });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function claimDaemonState(details) {
|
|
68
|
+
ensureTeleptyDir();
|
|
69
|
+
const current = readDaemonState();
|
|
70
|
+
|
|
71
|
+
if (current && current.pid !== process.pid) {
|
|
72
|
+
if (isProcessRunning(current.pid)) {
|
|
73
|
+
return { claimed: false, current };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
clearDaemonState(current.pid);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const state = {
|
|
80
|
+
pid: process.pid,
|
|
81
|
+
host: details.host,
|
|
82
|
+
port: details.port,
|
|
83
|
+
startedAt: new Date().toISOString(),
|
|
84
|
+
version: details.version
|
|
85
|
+
};
|
|
86
|
+
writeDaemonState(state);
|
|
87
|
+
return { claimed: true, state };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function isLikelyTeleptyDaemon(commandLine) {
|
|
91
|
+
const text = String(commandLine || '').toLowerCase();
|
|
92
|
+
if (!text) {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (text.includes('telepty daemon')) {
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (text.includes('cli.js daemon')) {
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return text.includes('daemon.js') && text.includes('aigentry-telepty');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function listUnixProcesses() {
|
|
108
|
+
const output = execSync('ps -axo pid=,command=', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
|
109
|
+
return output.split('\n')
|
|
110
|
+
.map((line) => line.trim())
|
|
111
|
+
.filter(Boolean)
|
|
112
|
+
.map((line) => {
|
|
113
|
+
const match = line.match(/^(\d+)\s+(.*)$/);
|
|
114
|
+
if (!match) {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
return { pid: Number(match[1]), commandLine: match[2] };
|
|
118
|
+
})
|
|
119
|
+
.filter(Boolean);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function listWindowsProcesses() {
|
|
123
|
+
const script = 'Get-CimInstance Win32_Process | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress';
|
|
124
|
+
const output = execFileSync('powershell.exe', ['-NoProfile', '-Command', script], {
|
|
125
|
+
encoding: 'utf8',
|
|
126
|
+
stdio: ['ignore', 'pipe', 'ignore']
|
|
127
|
+
}).trim();
|
|
128
|
+
|
|
129
|
+
if (!output) {
|
|
130
|
+
return [];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const records = JSON.parse(output);
|
|
134
|
+
const list = Array.isArray(records) ? records : [records];
|
|
135
|
+
return list
|
|
136
|
+
.map((item) => ({
|
|
137
|
+
pid: Number(item.ProcessId),
|
|
138
|
+
commandLine: item.CommandLine || ''
|
|
139
|
+
}))
|
|
140
|
+
.filter((item) => Number.isInteger(item.pid) && item.pid > 0);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function listDaemonProcesses() {
|
|
144
|
+
let processes = [];
|
|
145
|
+
|
|
146
|
+
try {
|
|
147
|
+
processes = process.platform === 'win32' ? listWindowsProcesses() : listUnixProcesses();
|
|
148
|
+
} catch {
|
|
149
|
+
return [];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return processes.filter((item) => item.pid !== process.pid && isLikelyTeleptyDaemon(item.commandLine));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function stopDaemonProcess(pid) {
|
|
156
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
try {
|
|
161
|
+
if (process.platform === 'win32') {
|
|
162
|
+
execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: ['ignore', 'ignore', 'ignore'] });
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
process.kill(pid, 'SIGTERM');
|
|
167
|
+
const deadline = Date.now() + 1500;
|
|
168
|
+
while (Date.now() < deadline) {
|
|
169
|
+
if (!isProcessRunning(pid)) {
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
sleepMs(50);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
process.kill(pid, 'SIGKILL');
|
|
176
|
+
return true;
|
|
177
|
+
} catch {
|
|
178
|
+
return !isProcessRunning(pid);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function cleanupDaemonProcesses() {
|
|
183
|
+
const targets = new Map();
|
|
184
|
+
const state = readDaemonState();
|
|
185
|
+
|
|
186
|
+
if (state && Number.isInteger(state.pid) && state.pid > 0 && state.pid !== process.pid) {
|
|
187
|
+
targets.set(state.pid, { pid: state.pid, source: 'state-file' });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
for (const item of listDaemonProcesses()) {
|
|
191
|
+
if (!targets.has(item.pid)) {
|
|
192
|
+
targets.set(item.pid, { pid: item.pid, source: 'process-scan', commandLine: item.commandLine });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const stopped = [];
|
|
197
|
+
const failed = [];
|
|
198
|
+
|
|
199
|
+
for (const item of targets.values()) {
|
|
200
|
+
if (stopDaemonProcess(item.pid)) {
|
|
201
|
+
stopped.push(item);
|
|
202
|
+
} else {
|
|
203
|
+
failed.push(item);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const nextState = readDaemonState();
|
|
208
|
+
if (nextState && !isProcessRunning(nextState.pid)) {
|
|
209
|
+
clearDaemonState(nextState.pid);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return { stopped, failed };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
module.exports = {
|
|
216
|
+
DAEMON_STATE_FILE,
|
|
217
|
+
claimDaemonState,
|
|
218
|
+
cleanupDaemonProcesses,
|
|
219
|
+
clearDaemonState,
|
|
220
|
+
isProcessRunning,
|
|
221
|
+
listDaemonProcesses,
|
|
222
|
+
readDaemonState
|
|
223
|
+
};
|
package/daemon.js
CHANGED
|
@@ -4,6 +4,8 @@ const pty = require('node-pty');
|
|
|
4
4
|
const os = require('os');
|
|
5
5
|
const { WebSocketServer } = require('ws');
|
|
6
6
|
const { getConfig } = require('./auth');
|
|
7
|
+
const pkg = require('./package.json');
|
|
8
|
+
const { claimDaemonState, clearDaemonState } = require('./daemon-control');
|
|
7
9
|
|
|
8
10
|
const config = getConfig();
|
|
9
11
|
const EXPECTED_TOKEN = config.authToken;
|
|
@@ -33,6 +35,14 @@ app.use((req, res, next) => {
|
|
|
33
35
|
const PORT = process.env.PORT || 3848;
|
|
34
36
|
|
|
35
37
|
const HOST = process.env.HOST || '0.0.0.0';
|
|
38
|
+
process.title = 'telepty-daemon';
|
|
39
|
+
|
|
40
|
+
const daemonClaim = claimDaemonState({ host: HOST, port: Number(PORT), version: pkg.version });
|
|
41
|
+
if (!daemonClaim.claimed) {
|
|
42
|
+
const current = daemonClaim.current;
|
|
43
|
+
console.log(`[DAEMON] telepty daemon already running (pid ${current.pid}, port ${current.port}). Exiting.`);
|
|
44
|
+
process.exit(0);
|
|
45
|
+
}
|
|
36
46
|
|
|
37
47
|
const sessions = {};
|
|
38
48
|
const STRIPPED_SESSION_ENV_KEYS = [
|
|
@@ -197,6 +207,17 @@ app.get('/api/sessions', (req, res) => {
|
|
|
197
207
|
res.json(list);
|
|
198
208
|
});
|
|
199
209
|
|
|
210
|
+
app.get('/api/meta', (req, res) => {
|
|
211
|
+
res.json({
|
|
212
|
+
name: pkg.name,
|
|
213
|
+
version: pkg.version,
|
|
214
|
+
pid: process.pid,
|
|
215
|
+
host: HOST,
|
|
216
|
+
port: Number(PORT),
|
|
217
|
+
capabilities: ['sessions', 'wrapped-sessions', 'skill-installer', 'singleton-daemon']
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
|
|
200
221
|
app.post('/api/sessions/multicast/inject', (req, res) => {
|
|
201
222
|
const { session_ids, prompt } = req.body;
|
|
202
223
|
if (!prompt) return res.status(400).json({ error: 'prompt is required' });
|
|
@@ -396,6 +417,17 @@ const server = app.listen(PORT, HOST, () => {
|
|
|
396
417
|
console.log(`🚀 aigentry-telepty daemon listening on http://${HOST}:${PORT}`);
|
|
397
418
|
});
|
|
398
419
|
|
|
420
|
+
server.on('error', (error) => {
|
|
421
|
+
clearDaemonState(process.pid);
|
|
422
|
+
|
|
423
|
+
if (error && error.code === 'EADDRINUSE') {
|
|
424
|
+
console.error(`[DAEMON] Port ${PORT} is already in use. Another process is blocking telepty.`);
|
|
425
|
+
process.exit(1);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
throw error;
|
|
429
|
+
});
|
|
430
|
+
|
|
399
431
|
|
|
400
432
|
const wss = new WebSocketServer({ noServer: true });
|
|
401
433
|
|
|
@@ -522,3 +554,14 @@ server.on('upgrade', (req, socket, head) => {
|
|
|
522
554
|
socket.destroy();
|
|
523
555
|
}
|
|
524
556
|
});
|
|
557
|
+
|
|
558
|
+
function shutdown(code) {
|
|
559
|
+
clearDaemonState(process.pid);
|
|
560
|
+
process.exit(code);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
process.on('SIGINT', () => shutdown(0));
|
|
564
|
+
process.on('SIGTERM', () => shutdown(0));
|
|
565
|
+
process.on('exit', () => {
|
|
566
|
+
clearDaemonState(process.pid);
|
|
567
|
+
});
|
package/install.js
CHANGED
|
@@ -4,6 +4,7 @@ const { execSync, spawn } = require('child_process');
|
|
|
4
4
|
const os = require('os');
|
|
5
5
|
const fs = require('fs');
|
|
6
6
|
const path = require('path');
|
|
7
|
+
const { cleanupDaemonProcesses } = require('./daemon-control');
|
|
7
8
|
const { runInteractiveSkillInstaller } = require('./skill-installer');
|
|
8
9
|
|
|
9
10
|
console.log("🚀 Installing @dmsdc-ai/aigentry-telepty...");
|
|
@@ -26,6 +27,15 @@ function resolveInstalledPackageRoot() {
|
|
|
26
27
|
}
|
|
27
28
|
}
|
|
28
29
|
|
|
30
|
+
function cleanupLocalDaemons() {
|
|
31
|
+
console.log('🧹 Cleaning up existing telepty daemons...');
|
|
32
|
+
const results = cleanupDaemonProcesses();
|
|
33
|
+
console.log(` Stopped ${results.stopped.length} daemon(s).`);
|
|
34
|
+
if (results.failed.length > 0) {
|
|
35
|
+
console.warn(` Could not stop ${results.failed.length} daemon(s).`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
29
39
|
async function installSkills() {
|
|
30
40
|
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
31
41
|
console.log('⏭️ Skipping interactive skill installation (no TTY).');
|
|
@@ -65,6 +75,7 @@ async function installSkills() {
|
|
|
65
75
|
const platform = os.platform();
|
|
66
76
|
|
|
67
77
|
if (platform === 'win32') {
|
|
78
|
+
cleanupLocalDaemons();
|
|
68
79
|
console.log("⚙️ Setting up Windows background process...");
|
|
69
80
|
const subprocess = spawn(teleptyPath, ['daemon'], {
|
|
70
81
|
detached: true,
|
|
@@ -78,6 +89,8 @@ async function installSkills() {
|
|
|
78
89
|
console.log("⚙️ Setting up macOS launchd service...");
|
|
79
90
|
const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', 'com.aigentry.telepty.plist');
|
|
80
91
|
fs.mkdirSync(path.dirname(plistPath), { recursive: true });
|
|
92
|
+
try { execSync(`launchctl unload "${plistPath}" 2>/dev/null`); } catch(e){}
|
|
93
|
+
cleanupLocalDaemons();
|
|
81
94
|
|
|
82
95
|
const plistContent = `<?xml version="1.0" encoding="UTF-8"?>
|
|
83
96
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
@@ -98,7 +111,6 @@ async function installSkills() {
|
|
|
98
111
|
</plist>`;
|
|
99
112
|
|
|
100
113
|
fs.writeFileSync(plistPath, plistContent);
|
|
101
|
-
try { execSync(`launchctl unload "${plistPath}" 2>/dev/null`); } catch(e){}
|
|
102
114
|
run(`launchctl load "${plistPath}"`);
|
|
103
115
|
console.log("✅ macOS LaunchAgent installed and started.");
|
|
104
116
|
|
|
@@ -108,6 +120,8 @@ async function installSkills() {
|
|
|
108
120
|
execSync('systemctl --version', { stdio: 'ignore' });
|
|
109
121
|
if (process.getuid && process.getuid() === 0) {
|
|
110
122
|
console.log("⚙️ Setting up systemd service for Linux...");
|
|
123
|
+
try { execSync('systemctl stop telepty', { stdio: 'ignore' }); } catch(e) {}
|
|
124
|
+
cleanupLocalDaemons();
|
|
111
125
|
const serviceContent = `[Unit]
|
|
112
126
|
Description=Telepty Daemon
|
|
113
127
|
After=network.target
|
|
@@ -133,6 +147,7 @@ WantedBy=multi-user.target`;
|
|
|
133
147
|
|
|
134
148
|
// Fallback for Linux without systemd or non-root
|
|
135
149
|
console.log("⚠️ Skipping systemd (no root or no systemd). Starting in background...");
|
|
150
|
+
cleanupLocalDaemons();
|
|
136
151
|
const subprocess = spawn(teleptyPath, ['daemon'], {
|
|
137
152
|
detached: true,
|
|
138
153
|
stdio: 'ignore'
|
package/install.ps1
CHANGED
|
@@ -26,7 +26,13 @@ if (!$teleptyCmd) {
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
$teleptyPath = $teleptyCmd.Source
|
|
29
|
-
|
|
29
|
+
try {
|
|
30
|
+
& $teleptyPath cleanup-daemons | Out-Null
|
|
31
|
+
} catch {
|
|
32
|
+
Write-Host "Warning: Could not clean up existing telepty daemons." -ForegroundColor Yellow
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
Start-Process -FilePath $teleptyPath -ArgumentList "daemon" -WindowStyle Hidden
|
|
30
36
|
Write-Host "Success: Windows daemon started in background." -ForegroundColor Green
|
|
31
37
|
|
|
32
38
|
Write-Host "`nInstallation complete! Telepty daemon is running." -ForegroundColor Cyan
|
package/install.sh
CHANGED
|
@@ -56,6 +56,9 @@ if command -v systemctl &> /dev/null && [ -d "/etc/systemd/system" ]; then
|
|
|
56
56
|
SUDO_CMD=""
|
|
57
57
|
fi
|
|
58
58
|
|
|
59
|
+
$SUDO_CMD systemctl stop telepty 2>/dev/null || true
|
|
60
|
+
"$TELEPTY_PATH" cleanup-daemons >/dev/null 2>&1 || true
|
|
61
|
+
|
|
59
62
|
$SUDO_CMD bash -c "cat <<EOF > /etc/systemd/system/telepty.service
|
|
60
63
|
[Unit]
|
|
61
64
|
Description=Telepty Daemon
|
|
@@ -80,6 +83,8 @@ EOF"
|
|
|
80
83
|
elif [[ "$OSTYPE" == "darwin"* ]]; then
|
|
81
84
|
PLIST_PATH="$HOME/Library/LaunchAgents/com.aigentry.telepty.plist"
|
|
82
85
|
mkdir -p "$HOME/Library/LaunchAgents"
|
|
86
|
+
launchctl unload "$PLIST_PATH" 2>/dev/null || true
|
|
87
|
+
"$TELEPTY_PATH" cleanup-daemons >/dev/null 2>&1 || true
|
|
83
88
|
cat <<EOF > "$PLIST_PATH"
|
|
84
89
|
<?xml version="1.0" encoding="UTF-8"?>
|
|
85
90
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
@@ -104,11 +109,11 @@ elif [[ "$OSTYPE" == "darwin"* ]]; then
|
|
|
104
109
|
</dict>
|
|
105
110
|
</plist>
|
|
106
111
|
EOF
|
|
107
|
-
launchctl unload "$PLIST_PATH" 2>/dev/null || true
|
|
108
112
|
launchctl load "$PLIST_PATH"
|
|
109
113
|
echo "✅ macOS LaunchAgent installed and started. (Auto-starts on boot)"
|
|
110
114
|
else
|
|
111
115
|
echo "⚠️ Skipping OS-level service setup (Termux or missing systemd). Starting in background..."
|
|
116
|
+
"$TELEPTY_PATH" cleanup-daemons >/dev/null 2>&1 || true
|
|
112
117
|
nohup $TELEPTY_PATH daemon > /dev/null 2>&1 &
|
|
113
118
|
echo "✅ Daemon started in background. (Note: Will not auto-start on device reboot)"
|
|
114
119
|
fi
|
package/interactive-terminal.js
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
function getTerminalSize(output, fallback = {}) {
|
|
4
|
+
const envCols = Number.parseInt(process.env.COLUMNS || '', 10);
|
|
5
|
+
const envRows = Number.parseInt(process.env.LINES || '', 10);
|
|
6
|
+
const fallbackCols = Number.isInteger(fallback.cols) && fallback.cols > 0 ? fallback.cols : 120;
|
|
7
|
+
const fallbackRows = Number.isInteger(fallback.rows) && fallback.rows > 0 ? fallback.rows : 40;
|
|
8
|
+
|
|
9
|
+
const cols = Number.isInteger(output && output.columns) && output.columns > 0
|
|
10
|
+
? output.columns
|
|
11
|
+
: (Number.isInteger(envCols) && envCols > 0 ? envCols : fallbackCols);
|
|
12
|
+
const rows = Number.isInteger(output && output.rows) && output.rows > 0
|
|
13
|
+
? output.rows
|
|
14
|
+
: (Number.isInteger(envRows) && envRows > 0 ? envRows : fallbackRows);
|
|
15
|
+
|
|
16
|
+
return { cols, rows };
|
|
17
|
+
}
|
|
18
|
+
|
|
3
19
|
function removeListener(stream, eventName, handler) {
|
|
4
20
|
if (!handler || !stream) {
|
|
5
21
|
return;
|
|
@@ -50,5 +66,6 @@ function attachInteractiveTerminal(input, output, handlers = {}) {
|
|
|
50
66
|
}
|
|
51
67
|
|
|
52
68
|
module.exports = {
|
|
53
|
-
attachInteractiveTerminal
|
|
69
|
+
attachInteractiveTerminal,
|
|
70
|
+
getTerminalSize
|
|
54
71
|
};
|
package/package.json
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dmsdc-ai/aigentry-telepty",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.10",
|
|
4
4
|
"main": "daemon.js",
|
|
5
5
|
"bin": {
|
|
6
|
+
"aigentry-telepty": "install.js",
|
|
6
7
|
"telepty": "cli.js",
|
|
7
8
|
"telepty-install": "install.js"
|
|
8
9
|
},
|
|
9
10
|
"scripts": {
|
|
10
|
-
"test": "node --test test/auth.test.js test/daemon.test.js test/cli.test.js test/skill-installer.test.js test/interactive-terminal.test.js",
|
|
11
|
-
"test:watch": "node --test --watch test/auth.test.js test/daemon.test.js test/cli.test.js test/skill-installer.test.js test/interactive-terminal.test.js",
|
|
12
|
-
"test:ci": "node --test --test-reporter=spec test/auth.test.js test/daemon.test.js test/cli.test.js test/skill-installer.test.js test/interactive-terminal.test.js"
|
|
11
|
+
"test": "node --test test/auth.test.js test/daemon.test.js test/daemon-singleton.test.js test/cli.test.js test/skill-installer.test.js test/interactive-terminal.test.js test/runtime-info.test.js",
|
|
12
|
+
"test:watch": "node --test --watch test/auth.test.js test/daemon.test.js test/daemon-singleton.test.js test/cli.test.js test/skill-installer.test.js test/interactive-terminal.test.js test/runtime-info.test.js",
|
|
13
|
+
"test:ci": "node --test --test-reporter=spec test/auth.test.js test/daemon.test.js test/daemon-singleton.test.js test/cli.test.js test/skill-installer.test.js test/interactive-terminal.test.js test/runtime-info.test.js"
|
|
13
14
|
},
|
|
14
15
|
"keywords": [],
|
|
15
16
|
"author": "",
|
package/runtime-info.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
|
|
6
|
+
function pad(value) {
|
|
7
|
+
return String(value).padStart(2, '0');
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function formatTimestamp(date) {
|
|
11
|
+
const year = date.getFullYear();
|
|
12
|
+
const month = pad(date.getMonth() + 1);
|
|
13
|
+
const day = pad(date.getDate());
|
|
14
|
+
const hours = pad(date.getHours());
|
|
15
|
+
const minutes = pad(date.getMinutes());
|
|
16
|
+
const seconds = pad(date.getSeconds());
|
|
17
|
+
const offsetMinutes = -date.getTimezoneOffset();
|
|
18
|
+
const sign = offsetMinutes >= 0 ? '+' : '-';
|
|
19
|
+
const absoluteOffset = Math.abs(offsetMinutes);
|
|
20
|
+
const offsetHours = pad(Math.floor(absoluteOffset / 60));
|
|
21
|
+
const offsetRemainder = pad(absoluteOffset % 60);
|
|
22
|
+
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds} ${sign}${offsetHours}:${offsetRemainder}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function getRuntimeInfo(packageRoot = __dirname) {
|
|
26
|
+
const packageJsonPath = path.join(packageRoot, 'package.json');
|
|
27
|
+
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
|
28
|
+
const packageStat = fs.statSync(packageJsonPath);
|
|
29
|
+
const updatedAt = packageStat.mtime;
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
version: pkg.version || 'unknown',
|
|
33
|
+
updatedAt,
|
|
34
|
+
updatedAtLabel: formatTimestamp(updatedAt)
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = {
|
|
39
|
+
formatTimestamp,
|
|
40
|
+
getRuntimeInfo
|
|
41
|
+
};
|