-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
110 lines (94 loc) · 2.96 KB
/
socket.js
File metadata and controls
110 lines (94 loc) · 2.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const net = require('net');
const fs = require('fs');
const path = require('path');
const { EventEmitter } = require('events');
const SOCKET_PATH = process.platform === 'win32'
? '\\\\.\\pipe\\aby-claude-watcher'
: '/tmp/aby-claude-watcher.sock';
class SocketServer extends EventEmitter {
constructor() {
super();
this.server = null;
}
start() {
// Clean up stale socket file on Unix
if (process.platform !== 'win32' && fs.existsSync(SOCKET_PATH)) {
fs.unlinkSync(SOCKET_PATH);
}
this.server = net.createServer((conn) => {
let buffer = '';
conn.on('data', (data) => {
buffer += data.toString();
const lines = buffer.split('\n');
buffer = lines.pop(); // keep incomplete line in buffer
for (const line of lines) {
if (!line.trim()) continue;
try {
const msg = JSON.parse(line);
this.handleMessage(msg, conn);
} catch (e) {
// skip malformed messages
}
}
});
conn.on('error', () => {});
});
this.server.listen(SOCKET_PATH, () => {
// Make socket accessible
if (process.platform !== 'win32') {
fs.chmodSync(SOCKET_PATH, 0o600);
}
});
this.server.on('error', (err) => {
console.error('Socket server error:', err.message);
});
}
handleMessage(msg, conn) {
switch (msg.action) {
case 'register':
// cc wrapper: new session with terminal info
this.emit('register', {
pid: msg.pid,
terminalApp: msg.terminalApp,
terminalId: msg.terminalId,
cwd: msg.cwd,
});
conn.write(JSON.stringify({ status: 'ok' }) + '\n');
break;
case 'attach':
// cwa: attach terminal to existing session
this.emit('attach', {
sessionId: msg.sessionId,
terminalApp: msg.terminalApp,
terminalId: msg.terminalId,
});
conn.write(JSON.stringify({ status: 'ok' }) + '\n');
break;
case 'permission-pending':
// Claude hook fired (PreToolUse / Notification) — session is waiting
// for the user to answer a permission prompt or a question.
// toolName is set on PreToolUse (Bash, AskUserQuestion, …); empty for Notification.
this.emit('permission-pending', {
sessionId: msg.sessionId,
hookEvent: msg.hookEvent,
toolName: msg.toolName || null,
});
conn.write(JSON.stringify({ status: 'ok' }) + '\n');
break;
case 'ping':
conn.write(JSON.stringify({ status: 'pong' }) + '\n');
break;
default:
conn.write(JSON.stringify({ status: 'error', message: 'unknown action' }) + '\n');
}
}
stop() {
if (this.server) {
this.server.close();
if (process.platform !== 'win32' && fs.existsSync(SOCKET_PATH)) {
fs.unlinkSync(SOCKET_PATH);
}
}
}
}
module.exports = { SocketServer, SOCKET_PATH };