tacticremote 1.7.0 → 1.8.1
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/LICENSE +28 -0
- package/README.md +33 -41
- package/bin/tacticremote.js +41 -101
- package/package.json +30 -42
- package/bin/tactic-remote-server.js +0 -636
- package/lib/authChallengeManager.js +0 -1
- package/lib/bonjourPublisher.js +0 -68
- package/lib/claudeSessionManager.js +0 -1
- package/lib/claudeTransport.js +0 -1
- package/lib/errorCodes.js +0 -1
- package/lib/execSafe.js +0 -1
- package/lib/fileService.js +0 -1
- package/lib/hookInstaller.js +0 -253
- package/lib/outputParser.js +0 -1
- package/lib/pushClient.js +0 -1
- package/lib/rateLimiter.js +0 -1
- package/lib/serverIdentity.js +0 -1
- package/lib/streamJsonParser.js +0 -1
- package/lib/tmuxManager.js +0 -1
- package/lib/uploadService.js +0 -1
- package/lib/validators.js +0 -1
- package/middleware/authMiddleware.js +0 -152
- package/routes/httpHandler.js +0 -111
- package/routes/wsHandler.js +0 -1094
- package/server.js +0 -236
- package/shared/server-core/authChallengeManager.js +0 -108
- package/shared/server-core/claudeSessionManager.js +0 -222
- package/shared/server-core/claudeTransport.js +0 -176
- package/shared/server-core/errorCodes.js +0 -91
- package/shared/server-core/execSafe.js +0 -185
- package/shared/server-core/fileService.js +0 -155
- package/shared/server-core/outputParser.js +0 -174
- package/shared/server-core/protocol-manifest.json +0 -59
- package/shared/server-core/protocol-manifest.schema.json +0 -90
- package/shared/server-core/protocolManifest.js +0 -42
- package/shared/server-core/pushClient.js +0 -198
- package/shared/server-core/rateLimiter.js +0 -98
- package/shared/server-core/serverConnectionLifecycle.js +0 -118
- package/shared/server-core/serverHandshake.js +0 -72
- package/shared/server-core/serverIdentity.js +0 -102
- package/shared/server-core/streamJsonParser.js +0 -321
- package/shared/server-core/tmuxManager.js +0 -596
- package/shared/server-core/unixProcessLifecycle.js +0 -96
- package/shared/server-core/unixServerHooks.js +0 -148
- package/shared/server-core/unixWsRuntime.js +0 -412
- package/shared/server-core/uploadService.js +0 -321
- package/shared/server-core/validators.js +0 -274
- package/shared/server-core/windowsServerHooks.js +0 -174
- package/shared/server-core/windowsWsRuntime.js +0 -413
|
@@ -1,148 +0,0 @@
|
|
|
1
|
-
// Warn-once-per-process flags to avoid log spam when hooks are stale.
|
|
2
|
-
// Cleared only when the server process restarts.
|
|
3
|
-
const warnedOnce = new Set();
|
|
4
|
-
function warnOnce(key, message) {
|
|
5
|
-
if (warnedOnce.has(key)) return;
|
|
6
|
-
warnedOnce.add(key);
|
|
7
|
-
console.warn(message);
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
function getForegroundMatchingClients(server, sessionName) {
|
|
11
|
-
if (!sessionName) return [];
|
|
12
|
-
const matches = [];
|
|
13
|
-
for (const [clientId] of server.externalClients) {
|
|
14
|
-
const state = server.clientState.get(clientId);
|
|
15
|
-
if (!state || state.foreground !== true) continue;
|
|
16
|
-
if (state.currentSession === sessionName) {
|
|
17
|
-
matches.push(clientId);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return matches;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function getLegacyExternalClients(server) {
|
|
24
|
-
const legacyClients = [];
|
|
25
|
-
for (const [clientId] of server.externalClients) {
|
|
26
|
-
const state = server.clientState.get(clientId);
|
|
27
|
-
if (!state || state.supportsClientState !== true) {
|
|
28
|
-
legacyClients.push(clientId);
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
return legacyClients;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
async function handleUnixHookEvent(server, hookData, { extractToolDetail }) {
|
|
35
|
-
const projectName = hookData.project || 'unknown project';
|
|
36
|
-
|
|
37
|
-
if (hookData.tactic_session) {
|
|
38
|
-
hookData.tmux_session = hookData.tactic_session;
|
|
39
|
-
} else if (hookData.tmux_session) {
|
|
40
|
-
warnOnce('legacy-tmux-session', `[notify][hook] legacy tmux_session field — hooks need reinstall`);
|
|
41
|
-
} else {
|
|
42
|
-
warnOnce('no-session-identity', `[notify][hook] no session identity in hook payload — hooks may be stale or claude launched outside TacticRemote`);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
console.log(`[notify][hook] event=${hookData.event} project=${projectName} session=${hookData.tmux_session || '-'} externalClients=${server.externalClients.size} pushEnabled=${server.pushEnabled}`);
|
|
46
|
-
|
|
47
|
-
server.lastHookEvent = hookData;
|
|
48
|
-
|
|
49
|
-
server.wsHandler.broadcast({
|
|
50
|
-
type: 'hook_event',
|
|
51
|
-
event: hookData.event,
|
|
52
|
-
project: hookData.project,
|
|
53
|
-
session: hookData.tmux_session,
|
|
54
|
-
timestamp: hookData.timestamp
|
|
55
|
-
});
|
|
56
|
-
server.wsHandler.broadcastEvent('hook_event', {
|
|
57
|
-
event: hookData.event,
|
|
58
|
-
project: hookData.project,
|
|
59
|
-
session: hookData.tmux_session,
|
|
60
|
-
timestamp: hookData.timestamp
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
if (hookData.event === 'Stop') {
|
|
64
|
-
console.log(`✅ Claude task completed in ${hookData.project}`);
|
|
65
|
-
if (hookData.tmux_session) {
|
|
66
|
-
server.wsHandler.captureAndBroadcast(hookData.tmux_session, 'completed');
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
const hookEventName = hookData.hook_event_name || hookData.event;
|
|
71
|
-
if (hookEventName === 'PreToolUse' || hookEventName === 'PostToolUse') {
|
|
72
|
-
const toolEvent = {
|
|
73
|
-
event: hookEventName,
|
|
74
|
-
tool_name: hookData.tool_name,
|
|
75
|
-
tool_use_id: hookData.tool_use_id,
|
|
76
|
-
tool_detail: extractToolDetail(hookData.tool_name, hookData.tool_input),
|
|
77
|
-
project: hookData.project,
|
|
78
|
-
session: hookData.tmux_session,
|
|
79
|
-
timestamp: hookData.timestamp || Date.now()
|
|
80
|
-
};
|
|
81
|
-
server.wsHandler.broadcastEvent('tool_use', toolEvent);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
if (hookData.event === 'Notification' && hookData.data?.message) {
|
|
85
|
-
console.log(`[notify][ws] event=notification project=${projectName} body="${hookData.data.message}"`);
|
|
86
|
-
server.wsHandler.broadcastEvent('notification', {
|
|
87
|
-
title: 'Claude',
|
|
88
|
-
body: hookData.data.message,
|
|
89
|
-
project: hookData.project,
|
|
90
|
-
session: hookData.tmux_session,
|
|
91
|
-
event: 'notification',
|
|
92
|
-
timestamp: hookData.timestamp
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
const pushEvents = ['Stop', 'Notification', 'Error'];
|
|
97
|
-
const legacyExternalClients = getLegacyExternalClients(server);
|
|
98
|
-
const matchingForegroundClients = legacyExternalClients.length === 0
|
|
99
|
-
? getForegroundMatchingClients(server, hookData.tmux_session)
|
|
100
|
-
: [];
|
|
101
|
-
if (pushEvents.includes(hookData.event) && !server.pushEnabled) {
|
|
102
|
-
console.log(`[notify][push] skipped event=${hookData.event} project=${projectName} reason=push_disabled`);
|
|
103
|
-
} else if (pushEvents.includes(hookData.event) && legacyExternalClients.length !== 0) {
|
|
104
|
-
console.log(`[notify][push] skipped event=${hookData.event} project=${projectName} reason=legacy_client_without_client_state clients=${legacyExternalClients.join(',')}`);
|
|
105
|
-
} else if (pushEvents.includes(hookData.event) && matchingForegroundClients.length !== 0) {
|
|
106
|
-
console.log(`[notify][push] skipped event=${hookData.event} project=${projectName} session=${hookData.tmux_session || '-'} reason=foreground_client_viewing_session clients=${matchingForegroundClients.join(',')}`);
|
|
107
|
-
} else if (pushEvents.includes(hookData.event)) {
|
|
108
|
-
const { serverId, serverSecret } = server.serverIdentity || {};
|
|
109
|
-
if (serverId && serverSecret) {
|
|
110
|
-
const projectLabel = hookData.project || 'unknown project';
|
|
111
|
-
let title = `${projectLabel} — Claude`;
|
|
112
|
-
let body = `Task ${hookData.event.toLowerCase()} in ${projectLabel}`;
|
|
113
|
-
if (hookData.event === 'Stop') {
|
|
114
|
-
title = `${projectLabel} — Task Completed`;
|
|
115
|
-
body = 'Claude finished';
|
|
116
|
-
} else if (hookData.event === 'Notification' && hookData.data?.message) {
|
|
117
|
-
title = `${projectLabel} — Claude`;
|
|
118
|
-
body = hookData.data.message;
|
|
119
|
-
} else if (hookData.event === 'Error') {
|
|
120
|
-
title = `${projectLabel} — Error`;
|
|
121
|
-
body = 'An error occurred';
|
|
122
|
-
}
|
|
123
|
-
console.log(`[notify][push] dispatch event=${hookData.event} project=${projectName} title="${title}" body="${body}"`);
|
|
124
|
-
const pushClient = require('./pushClient');
|
|
125
|
-
pushClient.notifyCompletion(serverId, serverSecret, title, body, hookData.project || '', hookData.event, hookData.tmux_session || '')
|
|
126
|
-
.then((result) => {
|
|
127
|
-
const sent = result?.data?.sent ?? result?.sent ?? 'n/a';
|
|
128
|
-
if (result && result.ok) {
|
|
129
|
-
console.log(`[notify][push] dispatched event=${hookData.event} project=${projectName} sent=${sent} status=${result.status || '-'}`);
|
|
130
|
-
} else {
|
|
131
|
-
console.warn(`[notify][push] rejected event=${hookData.event} project=${projectName} sent=${sent} error=${result?.data?.error || result?.error || 'unknown'} status=${result?.status || '-'}`);
|
|
132
|
-
}
|
|
133
|
-
})
|
|
134
|
-
.catch((err) => {
|
|
135
|
-
console.error(`[push] notifyCompletion error: ${err.message}`);
|
|
136
|
-
});
|
|
137
|
-
} else {
|
|
138
|
-
console.warn(`[notify][push] skipped event=${hookData.event} project=${projectName} reason=missing_server_identity`);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
module.exports = {
|
|
144
|
-
getForegroundMatchingClients,
|
|
145
|
-
getLegacyExternalClients,
|
|
146
|
-
handleUnixHookEvent,
|
|
147
|
-
_resetWarnedForTests: () => warnedOnce.clear()
|
|
148
|
-
};
|
|
@@ -1,412 +0,0 @@
|
|
|
1
|
-
const { stabilitySignature } = require('./outputParser');
|
|
2
|
-
|
|
3
|
-
function createUnixWsRuntime({
|
|
4
|
-
server,
|
|
5
|
-
tmux,
|
|
6
|
-
fileService,
|
|
7
|
-
authChallengeManager,
|
|
8
|
-
parseClaudeOutput,
|
|
9
|
-
tmuxCapture,
|
|
10
|
-
execSafe,
|
|
11
|
-
validatePath,
|
|
12
|
-
getStructuredSessionManager
|
|
13
|
-
}) {
|
|
14
|
-
const outputMonitors = new Map();
|
|
15
|
-
const clientMonitors = new Map();
|
|
16
|
-
|
|
17
|
-
function getClientPath(ws) {
|
|
18
|
-
const state = server.clientState.get(ws._clientId);
|
|
19
|
-
return state ? state.currentPath : server.currentPath;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function updateClientState(ws, patch) {
|
|
23
|
-
const state = server.clientState.get(ws._clientId);
|
|
24
|
-
if (!state) return null;
|
|
25
|
-
Object.assign(state, patch);
|
|
26
|
-
return state;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function setClientPath(ws, path) {
|
|
30
|
-
updateClientState(ws, { currentPath: path });
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function normalizeClientSession(session) {
|
|
34
|
-
return typeof session === 'string' && session.trim() !== ''
|
|
35
|
-
? session.trim()
|
|
36
|
-
: null;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function sendToClient(ws, message) {
|
|
40
|
-
if (ws.readyState === 1) {
|
|
41
|
-
ws.send(JSON.stringify(message));
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function sendOutputToClient(ws, message) {
|
|
46
|
-
if (ws.readyState === 1 && ws.bufferedAmount < 256 * 1024) {
|
|
47
|
-
ws.send(JSON.stringify(message));
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function sendResponse(ws, requestId, payload) {
|
|
52
|
-
sendToClient(ws, {
|
|
53
|
-
type: 'res',
|
|
54
|
-
id: requestId,
|
|
55
|
-
ok: true,
|
|
56
|
-
payload
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function sendErrorResponse(ws, requestId, error) {
|
|
61
|
-
sendToClient(ws, {
|
|
62
|
-
type: 'res',
|
|
63
|
-
id: requestId,
|
|
64
|
-
ok: false,
|
|
65
|
-
error
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function sendEvent(ws, eventName, payload) {
|
|
70
|
-
sendToClient(ws, {
|
|
71
|
-
type: 'event',
|
|
72
|
-
event: eventName,
|
|
73
|
-
payload
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function broadcastEvent(eventName, payload) {
|
|
78
|
-
server.clients.forEach((ws) => {
|
|
79
|
-
sendEvent(ws, eventName, payload);
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function broadcast(message) {
|
|
84
|
-
server.clients.forEach((ws) => {
|
|
85
|
-
sendToClient(ws, message);
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
async function withSensitivePathAuth(ws, userPath, method, validateOptions, operation) {
|
|
90
|
-
const validation = validatePath(userPath, validateOptions);
|
|
91
|
-
console.log(`[DEBUG withSensitivePathAuth] method=${method}, userPath=${userPath}, valid=${validation.valid}, requiresAuth=${validation.requiresAuth}, error=${validation.error}`);
|
|
92
|
-
|
|
93
|
-
if (!validation.valid && validation.requiresAuth) {
|
|
94
|
-
const sensitiveDir = validation.sensitiveDir;
|
|
95
|
-
|
|
96
|
-
if (authChallengeManager.isGranted(ws, sensitiveDir)) {
|
|
97
|
-
return await operation();
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
const { challengeId, expiresAt, promise } = authChallengeManager.createChallenge(
|
|
101
|
-
ws, userPath, sensitiveDir, method
|
|
102
|
-
);
|
|
103
|
-
|
|
104
|
-
sendEvent(ws, 'auth_challenge', {
|
|
105
|
-
challengeId,
|
|
106
|
-
path: userPath,
|
|
107
|
-
sensitiveDir,
|
|
108
|
-
method,
|
|
109
|
-
expiresAt
|
|
110
|
-
});
|
|
111
|
-
|
|
112
|
-
const granted = await promise;
|
|
113
|
-
if (granted) {
|
|
114
|
-
return await operation();
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
return {
|
|
118
|
-
success: false,
|
|
119
|
-
error: {
|
|
120
|
-
type: 'error',
|
|
121
|
-
code: 'AUTH_DENIED',
|
|
122
|
-
error: `Access to ${sensitiveDir} was denied`,
|
|
123
|
-
retryable: false
|
|
124
|
-
}
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
return await operation();
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
async function collectGitInfo(cwd) {
|
|
132
|
-
try {
|
|
133
|
-
const [branch, gitStatus, diffStat, branchList, worktreePath] = await Promise.all([
|
|
134
|
-
execSafe('git', ['-C', cwd, 'branch', '--show-current'], { timeout: 5000 }).catch(() => ''),
|
|
135
|
-
execSafe('git', ['-C', cwd, 'status', '--short'], { timeout: 5000 }).catch(() => ''),
|
|
136
|
-
execSafe('git', ['-C', cwd, 'diff', '--stat', 'HEAD'], { timeout: 10000 }).catch(() => ''),
|
|
137
|
-
execSafe('git', ['-C', cwd, 'branch', '--format=%(refname:short)'], { timeout: 5000 }).catch(() => ''),
|
|
138
|
-
execSafe('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], { timeout: 5000 }).catch(() => '')
|
|
139
|
-
]);
|
|
140
|
-
const resolvedWorktree = worktreePath.trim();
|
|
141
|
-
return {
|
|
142
|
-
cwd,
|
|
143
|
-
branch: branch.trim(),
|
|
144
|
-
branches: branchList.trim().split('\n').filter(Boolean),
|
|
145
|
-
git_status: gitStatus.trim(),
|
|
146
|
-
diff_stat: diffStat.trim(),
|
|
147
|
-
is_git_repo: true,
|
|
148
|
-
worktree_path: resolvedWorktree || undefined,
|
|
149
|
-
is_worktree: Boolean(resolvedWorktree) && resolvedWorktree !== cwd
|
|
150
|
-
};
|
|
151
|
-
} catch {
|
|
152
|
-
return { cwd, is_git_repo: false };
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/// Parse `git worktree list --porcelain` output into a structured array.
|
|
157
|
-
/// Each worktree stanza is separated by a blank line and starts with
|
|
158
|
-
/// `worktree <path>`; branches begin with `branch refs/heads/<name>`; a
|
|
159
|
-
/// worktree is `detached` or `locked` when those keywords appear on their
|
|
160
|
-
/// own line.
|
|
161
|
-
async function collectWorktrees(cwd) {
|
|
162
|
-
try {
|
|
163
|
-
const raw = await execSafe(
|
|
164
|
-
'git',
|
|
165
|
-
['-C', cwd, 'worktree', 'list', '--porcelain'],
|
|
166
|
-
{ timeout: 5000 }
|
|
167
|
-
);
|
|
168
|
-
const worktrees = [];
|
|
169
|
-
let current = null;
|
|
170
|
-
for (const line of raw.split('\n')) {
|
|
171
|
-
if (line.startsWith('worktree ')) {
|
|
172
|
-
if (current) worktrees.push(current);
|
|
173
|
-
current = {
|
|
174
|
-
path: line.slice('worktree '.length).trim(),
|
|
175
|
-
branch: null,
|
|
176
|
-
is_main: worktrees.length === 0, // first entry is the main working tree
|
|
177
|
-
is_detached: false,
|
|
178
|
-
is_locked: false
|
|
179
|
-
};
|
|
180
|
-
} else if (!current) {
|
|
181
|
-
continue;
|
|
182
|
-
} else if (line.startsWith('branch refs/heads/')) {
|
|
183
|
-
current.branch = line.slice('branch refs/heads/'.length).trim();
|
|
184
|
-
} else if (line.trim() === 'detached') {
|
|
185
|
-
current.is_detached = true;
|
|
186
|
-
} else if (line.trim() === 'locked' || line.startsWith('locked ')) {
|
|
187
|
-
current.is_locked = true;
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
if (current) worktrees.push(current);
|
|
191
|
-
return worktrees;
|
|
192
|
-
} catch {
|
|
193
|
-
return [];
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function startOutputMonitor(ws, sessionName) {
|
|
198
|
-
if (!clientMonitors.has(ws)) clientMonitors.set(ws, new Set());
|
|
199
|
-
clientMonitors.get(ws).add(sessionName);
|
|
200
|
-
|
|
201
|
-
if (outputMonitors.has(sessionName)) {
|
|
202
|
-
const monitor = outputMonitors.get(sessionName);
|
|
203
|
-
monitor.subscribers.set(ws, true);
|
|
204
|
-
monitor.checkCount = 0;
|
|
205
|
-
monitor.stableCount = 0;
|
|
206
|
-
monitor.lastOutput = '';
|
|
207
|
-
monitor.lastSignature = '';
|
|
208
|
-
return;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
const maxChecks = 120;
|
|
212
|
-
const subscribers = new Map();
|
|
213
|
-
subscribers.set(ws, true);
|
|
214
|
-
|
|
215
|
-
const monitorState = {
|
|
216
|
-
subscribers,
|
|
217
|
-
intervalId: null,
|
|
218
|
-
checkCount: 0,
|
|
219
|
-
stableCount: 0,
|
|
220
|
-
lastOutput: '',
|
|
221
|
-
lastSignature: ''
|
|
222
|
-
};
|
|
223
|
-
|
|
224
|
-
function emitFinalAndTeardown(reason) {
|
|
225
|
-
try {
|
|
226
|
-
if (reason === 'stable') {
|
|
227
|
-
const parsed = parseClaudeOutput(monitorState.lastOutput || '');
|
|
228
|
-
const isWaiting = tmux.isWaitingForInput(monitorState.lastOutput || '');
|
|
229
|
-
for (const [subWs] of subscribers) {
|
|
230
|
-
if (subWs.readyState !== 1) continue;
|
|
231
|
-
if (isWaiting) {
|
|
232
|
-
sendToClient(subWs, { type: 'status', status: 'waiting' });
|
|
233
|
-
}
|
|
234
|
-
sendToClient(subWs, {
|
|
235
|
-
type: 'claude_output',
|
|
236
|
-
content: parsed.display,
|
|
237
|
-
userQuestion: parsed.userQuestion,
|
|
238
|
-
claudeResponse: parsed.claudeResponse,
|
|
239
|
-
session: sessionName,
|
|
240
|
-
final: true,
|
|
241
|
-
finalReason: reason,
|
|
242
|
-
waiting: isWaiting
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
} finally {
|
|
247
|
-
if (monitorState.intervalId) clearInterval(monitorState.intervalId);
|
|
248
|
-
outputMonitors.delete(sessionName);
|
|
249
|
-
for (const [subWs] of subscribers) {
|
|
250
|
-
const sessions = clientMonitors.get(subWs);
|
|
251
|
-
if (sessions) sessions.delete(sessionName);
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
const intervalId = setInterval(async () => {
|
|
257
|
-
monitorState.checkCount++;
|
|
258
|
-
|
|
259
|
-
for (const [subWs] of subscribers) {
|
|
260
|
-
if (subWs.readyState !== 1) {
|
|
261
|
-
subscribers.delete(subWs);
|
|
262
|
-
const sessions = clientMonitors.get(subWs);
|
|
263
|
-
if (sessions) sessions.delete(sessionName);
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
if (subscribers.size === 0) {
|
|
268
|
-
emitFinalAndTeardown('no_subscribers');
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
if (monitorState.checkCount > maxChecks) {
|
|
272
|
-
emitFinalAndTeardown('max_checks');
|
|
273
|
-
return;
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
try {
|
|
277
|
-
const output = await tmuxCapture(sessionName, 2000);
|
|
278
|
-
|
|
279
|
-
// Push display on any raw change so the client sees live
|
|
280
|
-
// output (logo animation, spinner tick, token streaming).
|
|
281
|
-
if (output !== monitorState.lastOutput) {
|
|
282
|
-
monitorState.lastOutput = output;
|
|
283
|
-
|
|
284
|
-
const parsed = parseClaudeOutput(output);
|
|
285
|
-
for (const [subWs] of subscribers) {
|
|
286
|
-
sendOutputToClient(subWs, {
|
|
287
|
-
type: 'claude_output',
|
|
288
|
-
content: parsed.display,
|
|
289
|
-
session: sessionName
|
|
290
|
-
});
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
// Stability is measured on a normalized signature of the
|
|
295
|
-
// input-box region only. This ignores the startup logo
|
|
296
|
-
// animation Amp draws higher up on the screen and the
|
|
297
|
-
// spinner tick that would otherwise reset the counter on
|
|
298
|
-
// every poll.
|
|
299
|
-
const signature = stabilitySignature(output);
|
|
300
|
-
if (signature !== monitorState.lastSignature) {
|
|
301
|
-
monitorState.lastSignature = signature;
|
|
302
|
-
monitorState.stableCount = 0;
|
|
303
|
-
monitorState.checkCount = 0;
|
|
304
|
-
} else {
|
|
305
|
-
monitorState.stableCount++;
|
|
306
|
-
|
|
307
|
-
if (monitorState.stableCount >= 5) {
|
|
308
|
-
emitFinalAndTeardown('stable');
|
|
309
|
-
return;
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
} catch (error) {
|
|
313
|
-
console.error('Monitor error:', error.message);
|
|
314
|
-
}
|
|
315
|
-
}, 1000);
|
|
316
|
-
|
|
317
|
-
monitorState.intervalId = intervalId;
|
|
318
|
-
outputMonitors.set(sessionName, monitorState);
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
function stopMonitor(sessionName) {
|
|
322
|
-
if (outputMonitors.has(sessionName)) {
|
|
323
|
-
const entry = outputMonitors.get(sessionName);
|
|
324
|
-
clearInterval(entry.intervalId);
|
|
325
|
-
for (const [subWs] of entry.subscribers) {
|
|
326
|
-
const sessions = clientMonitors.get(subWs);
|
|
327
|
-
if (sessions) sessions.delete(sessionName);
|
|
328
|
-
}
|
|
329
|
-
outputMonitors.delete(sessionName);
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
function removeClientFromMonitor(ws, sessionName) {
|
|
334
|
-
if (outputMonitors.has(sessionName)) {
|
|
335
|
-
const entry = outputMonitors.get(sessionName);
|
|
336
|
-
entry.subscribers.delete(ws);
|
|
337
|
-
const sessions = clientMonitors.get(ws);
|
|
338
|
-
if (sessions) sessions.delete(sessionName);
|
|
339
|
-
if (entry.subscribers.size === 0) {
|
|
340
|
-
clearInterval(entry.intervalId);
|
|
341
|
-
outputMonitors.delete(sessionName);
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
function cleanupClient(ws) {
|
|
347
|
-
const sessions = clientMonitors.get(ws);
|
|
348
|
-
if (sessions) {
|
|
349
|
-
for (const sessionName of sessions) {
|
|
350
|
-
if (outputMonitors.has(sessionName)) {
|
|
351
|
-
const entry = outputMonitors.get(sessionName);
|
|
352
|
-
entry.subscribers.delete(ws);
|
|
353
|
-
if (entry.subscribers.size === 0) {
|
|
354
|
-
clearInterval(entry.intervalId);
|
|
355
|
-
outputMonitors.delete(sessionName);
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
clientMonitors.delete(ws);
|
|
360
|
-
}
|
|
361
|
-
authChallengeManager.cleanupClient(ws);
|
|
362
|
-
getStructuredSessionManager?.()?.removeSubscriberFromAll(ws);
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
async function captureAndBroadcast(sessionName, reason = 'update', originWs = null) {
|
|
366
|
-
const result = await tmux.captureOutput(sessionName, 2000);
|
|
367
|
-
if (result.success) {
|
|
368
|
-
const message = {
|
|
369
|
-
type: 'claude_output',
|
|
370
|
-
content: result.content,
|
|
371
|
-
userQuestion: result.userQuestion,
|
|
372
|
-
claudeResponse: result.claudeResponse,
|
|
373
|
-
session: sessionName,
|
|
374
|
-
reason
|
|
375
|
-
};
|
|
376
|
-
const monitor = outputMonitors.get(sessionName);
|
|
377
|
-
if (monitor) {
|
|
378
|
-
for (const [subWs] of monitor.subscribers) {
|
|
379
|
-
sendOutputToClient(subWs, message);
|
|
380
|
-
}
|
|
381
|
-
} else if (originWs) {
|
|
382
|
-
sendOutputToClient(originWs, message);
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
return {
|
|
388
|
-
outputMonitors,
|
|
389
|
-
clientMonitors,
|
|
390
|
-
getClientPath,
|
|
391
|
-
updateClientState,
|
|
392
|
-
setClientPath,
|
|
393
|
-
normalizeClientSession,
|
|
394
|
-
sendToClient,
|
|
395
|
-
sendOutputToClient,
|
|
396
|
-
sendResponse,
|
|
397
|
-
sendErrorResponse,
|
|
398
|
-
sendEvent,
|
|
399
|
-
broadcastEvent,
|
|
400
|
-
broadcast,
|
|
401
|
-
withSensitivePathAuth,
|
|
402
|
-
collectGitInfo,
|
|
403
|
-
collectWorktrees,
|
|
404
|
-
startOutputMonitor,
|
|
405
|
-
stopMonitor,
|
|
406
|
-
removeClientFromMonitor,
|
|
407
|
-
cleanupClient,
|
|
408
|
-
captureAndBroadcast
|
|
409
|
-
};
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
module.exports = { createUnixWsRuntime };
|