-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathserver.mjs
More file actions
2392 lines (2114 loc) · 92.2 KB
/
Copy pathserver.mjs
File metadata and controls
2392 lines (2114 loc) · 92.2 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createServer } from 'http'
import { parse } from 'url'
import { execSync, execFileSync, execFile } from 'child_process'
import { WebSocketServer } from 'ws'
import WebSocket from 'ws'
import pty from 'node-pty'
import os from 'os'
import fs from 'fs'
import path from 'path'
import crypto from 'crypto'
import { getHostById, isSelf } from './lib/hosts-config-server.mjs'
import { hostHints } from './lib/host-hints-server.mjs'
import { getOrCreateBuffer, removeBuffer } from './lib/cerebellum/session-bridge.mjs'
import {
sessionActivity,
terminalSessions,
statusSubscribers,
companionClients,
callSessions,
broadcastStatusUpdate,
broadcastChatEvent
} from './services/shared-state-bridge.mjs'
// =============================================================================
// GLOBAL ERROR HANDLERS - Must be first to catch all errors
// =============================================================================
// These handlers prevent the server from crashing on unhandled errors.
// On Ubuntu 24.04 and other Linux systems, native modules (node-pty, cozo-node)
// can occasionally throw errors that would otherwise crash the process.
process.on('uncaughtException', (error, origin) => {
console.error(`[CRASH-GUARD] Uncaught exception from ${origin}:`)
console.error(error)
// Log to file for debugging
const crashLogPath = path.join(process.cwd(), 'logs', 'crash.log')
const timestamp = new Date().toISOString()
const logEntry = `[${timestamp}] Uncaught exception (${origin}):\n${error.stack || error}\n\n`
try {
fs.appendFileSync(crashLogPath, logEntry)
} catch (fsError) {
// Ignore file write errors
}
// Don't exit - allow the server to continue running
// Only exit for truly fatal errors
if (error.code === 'EADDRINUSE' || error.code === 'EACCES') {
console.error('[CRASH-GUARD] Fatal error, exiting...')
process.exit(1)
}
})
process.on('unhandledRejection', (reason, promise) => {
console.error('[CRASH-GUARD] Unhandled promise rejection:')
console.error('Reason:', reason)
// Log to file for debugging
const crashLogPath = path.join(process.cwd(), 'logs', 'crash.log')
const timestamp = new Date().toISOString()
const logEntry = `[${timestamp}] Unhandled rejection:\n${reason?.stack || reason}\n\n`
try {
fs.appendFileSync(crashLogPath, logEntry)
} catch (fsError) {
// Ignore file write errors
}
// Don't exit - allow the server to continue running
})
// Catch SIGPIPE errors (common on Linux when clients disconnect abruptly)
process.on('SIGPIPE', () => {
console.log('[CRASH-GUARD] SIGPIPE received (client disconnected), ignoring')
})
// =============================================================================
const dev = process.env.NODE_ENV !== 'production'
const hostname = process.env.HOSTNAME || '0.0.0.0' // 0.0.0.0 allows network access
const port = parseInt(process.env.PORT || '23000', 10)
// Server mode: 'full' (default) = Next.js + UI, 'headless' = API-only (no Next.js)
const MAESTRO_MODE = process.env.MAESTRO_MODE || 'full'
// Global logging master switch - set ENABLE_LOGGING=true to enable all logging
const globalLoggingEnabled = process.env.ENABLE_LOGGING === 'true'
// Session state management
// sessionActivity, terminalSessions, statusSubscribers, companionClients, broadcastStatusUpdate
// are imported from shared-state-bridge.mjs (backed by globalThis._sharedState)
const idleTimers = new Map() // sessionName -> { timer, wasActive }
// Idle threshold in milliseconds (30 seconds)
const IDLE_THRESHOLD_MS = 30 * 1000
// PTY cleanup grace period (30 seconds)
const PTY_CLEANUP_GRACE_MS = 30 * 1000
// Periodic orphaned PTY cleanup interval (5 minutes)
const ORPHAN_CLEANUP_INTERVAL_MS = 5 * 60 * 1000
/**
* Safely kill a PTY process
* Based on node-pty best practices from GitHub issues #333, #382
*
* Key learnings:
* - Use ptyProcess.kill() first (not process.kill)
* - Wrap in try-catch because killing already-dead process throws
* - Use SIGKILL as fallback after timeout
* - Process group kill (-pid) is unreliable with node-pty
*
* @returns true if kill was attempted, false if process was already dead
*/
function killPtyProcess(ptyProcess, sessionName, alreadyExited = false) {
if (!ptyProcess) {
return false
}
// If process already exited via onExit, don't try to kill again
if (alreadyExited) {
console.log(`[PTY] Skipping kill for ${sessionName} - already exited`)
return true
}
const pid = ptyProcess.pid
if (!pid) {
return false
}
console.log(`[PTY] Killing PTY for ${sessionName} (pid: ${pid})`)
// Method 1: Use node-pty's kill() - recommended approach
// This properly handles the underlying PTY cleanup
try {
ptyProcess.kill()
console.log(`[PTY] Sent SIGTERM to ${sessionName} via ptyProcess.kill()`)
} catch (e) {
// Process might already be dead - this is expected
console.log(`[PTY] ptyProcess.kill() failed for ${sessionName}: ${e.message}`)
}
// Schedule a SIGKILL as a fallback if SIGTERM didn't work
// This ensures we don't leave zombie processes
setTimeout(() => {
try {
// Check if process still exists (signal 0 just checks existence)
process.kill(pid, 0)
// Still alive after 3 seconds, force kill
console.log(`[PTY] Force killing ${sessionName} (pid: ${pid}) - SIGTERM didn't work`)
try {
ptyProcess.kill('SIGKILL')
} catch (e) {
// Fallback to process.kill if ptyProcess.kill fails
try { process.kill(pid, 'SIGKILL') } catch (e2) {}
}
} catch (e) {
// Process doesn't exist anymore - good!
}
}, 3000)
return true
}
// =============================================================================
// CHAT PROTOCOL HELPERS — getChatHistory, JSONL watcher, broadcast updates
// =============================================================================
/**
* Resolve the JSONL conversation file path for an agent.
* Returns null if not found.
*/
function resolveJsonlPath(agent) {
const workingDir = agent?.workingDirectory ||
agent?.sessions?.[0]?.workingDirectory ||
agent?.preferences?.defaultWorkingDirectory
if (!workingDir) return null
const claudeProjectsDir = path.join(os.homedir(), '.claude', 'projects')
const projectDirName = workingDir.replace(/[/_]/g, '-')
const conversationDir = path.join(claudeProjectsDir, projectDirName)
if (!fs.existsSync(conversationDir)) return null
const files = fs.readdirSync(conversationDir)
.filter(f => f.endsWith('.jsonl'))
.map(f => ({
name: f,
path: path.join(conversationDir, f),
mtime: fs.statSync(path.join(conversationDir, f)).mtime
}))
.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())
return files.length > 0 ? files[0] : null
}
/**
* Read hook state file for an agent's working directory.
*/
function readHookState(workingDir) {
if (!workingDir) return null
const stateDir = path.join(os.homedir(), '.aimaestro', 'chat-state')
const cwdHash = crypto.createHash('md5').update(workingDir || '').digest('hex').substring(0, 16)
const stateFile = path.join(stateDir, `${cwdHash}.json`)
try {
if (fs.existsSync(stateFile)) {
const content = fs.readFileSync(stateFile, 'utf-8')
const state = JSON.parse(content)
const isWaitingState = state.status === 'waiting_for_input' || state.status === 'permission_request'
if (!isWaitingState) {
const stateAge = Date.now() - new Date(state.updatedAt).getTime()
if (stateAge > 60000) return null
}
return state
}
} catch { /* ignore */ }
return null
}
/**
* Parse JSONL lines into message objects (same logic as agents-chat-service).
*/
function parseJsonlLines(lines, limit = 100) {
const messages = []
for (const line of lines) {
if (!line.trim()) continue
try {
const message = JSON.parse(line)
// Skip tool-result user messages (invisible in chat, waste message budget)
if (message.type === 'user' && message.toolUseResult) continue
// Convert compact_boundary system messages to summary type
if (message.type === 'system' &&
(message.subtype === 'compact_boundary' || message.subtype === 'microcompact_boundary')) {
messages.push({
type: 'summary',
summary: message.content || 'Conversation compacted',
timestamp: message.timestamp,
uuid: message.uuid,
})
continue
}
// Extract thinking blocks from assistant messages
if (message.type === 'assistant' && message.message?.content) {
const content = message.message.content
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === 'thinking' && block.thinking) {
messages.push({
type: 'thinking',
thinking: block.thinking,
timestamp: message.timestamp,
uuid: message.uuid
})
}
}
}
}
messages.push(message)
} catch { /* skip malformed */ }
}
return messages.slice(-limit)
}
/**
* Get chat history for a session (messages + hookState).
* Called on chat:requestHistory.
*/
async function getChatHistory(sessionName, agentId) {
const { getAgent, getAgentByName } = await import('./lib/agent-registry.ts')
// Try agentId first, fall back to sessionName (remote hosts won't have the local agentId)
const agent = (agentId && getAgent(agentId)) || getAgentByName(sessionName)
if (!agent) {
return { messages: [], hookState: null }
}
const file = resolveJsonlPath(agent)
if (!file) {
return { messages: [], hookState: null }
}
const fileContent = fs.readFileSync(file.path, 'utf-8')
const lines = fileContent.split('\n')
const messages = parseJsonlLines(lines, 200)
const workingDir = agent.workingDirectory ||
agent.sessions?.[0]?.workingDirectory ||
agent.preferences?.defaultWorkingDirectory
let hookState = readHookState(workingDir)
// If the file no longer has permission_request but the server remembers one
// from this session (agent is still waiting for approval), use the stored state.
// This handles tab-switching: component unmounts/remounts while permission is pending.
if (hookState?.status !== 'permission_request') {
const sessionState = terminalSessions.get(sessionName)
if (sessionState?._lastPermission) {
hookState = sessionState._lastPermission
}
}
return {
messages,
hookState,
conversationFile: file.path,
lastModified: file.mtime.toISOString()
}
}
/**
* Start watching the JSONL file for a session.
* Uses fs.watchFile (polling-based, reliable on macOS) to detect changes.
*/
function startJsonlWatcher(sessionName, sessionState, agentId) {
// Already watching
if (sessionState.jsonlWatcher) return
import('./lib/agent-registry.ts').then(({ getAgent, getAgentByName }) => {
// Try agentId first, fall back to sessionName (remote hosts won't have the local agentId)
const agent = (agentId && getAgent(agentId)) || getAgentByName(sessionName)
if (!agent) return
const file = resolveJsonlPath(agent)
if (!file) return
sessionState.jsonlFilePath = file.path
try {
const stat = fs.statSync(file.path)
sessionState.jsonlFileSize = stat.size
} catch {
sessionState.jsonlFileSize = 0
}
// Poll every 1s — low overhead, reliable on macOS where fs.watch is flaky
fs.watchFile(file.path, { interval: 1000 }, (curr, prev) => {
if (curr.size > sessionState.jsonlFileSize) {
console.log(`[Chat] JSONL change detected for ${sessionName}: ${sessionState.jsonlFileSize} → ${curr.size} (${sessionState.chatClients?.size || 0} clients)`)
broadcastJsonlUpdates(sessionName, sessionState)
}
// Handle file truncation (new conversation started)
if (curr.size < sessionState.jsonlFileSize) {
sessionState.jsonlFileSize = 0
broadcastJsonlUpdates(sessionName, sessionState)
}
})
sessionState.jsonlWatcher = true
console.log(`[Chat] Started JSONL watcher for ${sessionName}: ${file.path}`)
// Watch hook state file for real-time permission/status updates
const workingDir = agent.workingDirectory ||
agent.sessions?.[0]?.workingDirectory ||
agent.preferences?.defaultWorkingDirectory
if (workingDir) {
sessionState._hookStateWorkingDir = workingDir
const cwdHash = crypto.createHash('md5').update(workingDir).digest('hex').substring(0, 16)
const hookStateFile = path.join(os.homedir(), '.aimaestro', 'chat-state', `${cwdHash}.json`)
sessionState._hookStateFile = hookStateFile
// Use fs.watchFile (1s poll) instead of setInterval — same reliability as JSONL watcher
fs.watchFile(hookStateFile, { interval: 1000 }, () => {
broadcastHookState(sessionName, sessionState)
})
sessionState._hookStateWatcher = true
console.log(`[Chat] Started hookState watcher for ${sessionName}: ${hookStateFile}`)
}
}).catch(err => {
console.error(`[Chat] Failed to start JSONL watcher for ${sessionName}:`, err.message)
})
}
/**
* Read hookState and broadcast to chat clients if changed.
* Extracted so it can be called from the file watcher AND from broadcastJsonlUpdates
* (on tool_use messages that precede permission prompts).
*/
function broadcastHookState(sessionName, sessionState) {
if (!sessionState.chatClients || sessionState.chatClients.size === 0) return
const workingDir = sessionState._hookStateWorkingDir
if (!workingDir) return
const state = readHookState(workingDir)
// Remember permission_request states so we can serve them on history re-requests
if (state?.status === 'permission_request') {
sessionState._lastPermission = state
}
const stateJson = JSON.stringify(state)
if (stateJson !== sessionState._lastHookState) {
sessionState._lastHookState = stateJson
const msg = JSON.stringify({ type: 'chat:hookState', data: state })
sessionState.chatClients.forEach(ws => {
if (ws.readyState === 1) ws.send(msg)
})
if (state?.status) {
console.log(`[Chat] hookState broadcast for ${sessionName}: ${state.status}`)
}
}
}
/**
* Read new JSONL lines since last read and broadcast to chat clients.
*/
function broadcastJsonlUpdates(sessionName, sessionState) {
if (!sessionState.chatClients || sessionState.chatClients.size === 0) {
return
}
if (!sessionState.jsonlFilePath) {
console.log(`[Chat] No JSONL path for ${sessionName}, skipping broadcast`)
return
}
try {
const stat = fs.statSync(sessionState.jsonlFilePath)
const currentSize = stat.size
const prevSize = sessionState.jsonlFileSize || 0
if (currentSize <= prevSize && prevSize > 0) return
// Read only new bytes (or full file if truncated)
const readStart = currentSize < prevSize ? 0 : prevSize
const fd = fs.openSync(sessionState.jsonlFilePath, 'r')
const buffer = Buffer.alloc(currentSize - readStart)
fs.readSync(fd, buffer, 0, buffer.length, readStart)
fs.closeSync(fd)
const newContent = buffer.toString('utf-8')
// Handle partial lines: if content doesn't end with \n, the last line
// is incomplete (Claude is still writing). Save it for the next read.
const allLines = newContent.split('\n')
let partial = ''
if (!newContent.endsWith('\n') && allLines.length > 0) {
partial = allLines.pop()
}
// Prepend any partial line saved from the previous read
if (sessionState.jsonlPartialLine && allLines.length > 0) {
allLines[0] = sessionState.jsonlPartialLine + allLines[0]
}
sessionState.jsonlPartialLine = partial
// Advance file position, but don't count the partial bytes we deferred
sessionState.jsonlFileSize = currentSize - Buffer.byteLength(partial, 'utf-8')
const lines = allLines.filter(l => l.trim())
if (lines.length === 0) return
const messages = parseJsonlLines(lines, 50)
if (messages.length === 0) return
// Clear stored permission when assistant responds (permission cycle is over)
if (messages.some(m => m.type === 'assistant') && sessionState._lastPermission) {
sessionState._lastPermission = null
}
// Clear activity indicator when new messages arrive (tool completed, response started)
if (messages.length > 0 && sessionState._lastActivityLabel) {
sessionState._lastActivityLabel = null
const clearMsg = JSON.stringify({ type: 'chat:activity', data: null })
sessionState.chatClients.forEach(ws => {
if (ws.readyState === 1) try { ws.send(clearMsg) } catch {}
})
}
const msg = JSON.stringify({ type: 'chat:messages', data: messages })
let sentCount = 0
sessionState.chatClients.forEach(ws => {
if (ws.readyState === 1) {
ws.send(msg)
sentCount++
}
})
console.log(`[Chat] Broadcast ${messages.length} messages to ${sentCount}/${sessionState.chatClients.size} clients for ${sessionName}`)
// When tool_use messages appear, permission prompts follow shortly after.
// Schedule rapid hookState reads to catch them before the file watcher's next poll.
const hasToolUse = lines.some(l => l.includes('"tool_use"'))
if (hasToolUse && sessionState._hookStateWorkingDir) {
for (const delay of [200, 600, 1200, 2000, 3500]) {
setTimeout(() => broadcastHookState(sessionName, sessionState), delay)
}
}
} catch (err) {
console.error(`[Chat] Error reading JSONL updates for ${sessionName}:`, err.message)
}
}
/**
* Clean up a session's PTY and resources
* Called when last client disconnects, on error, or when PTY exits
*
* @param sessionName - Name of the session
* @param sessionState - Session state object (optional, will lookup if null)
* @param reason - Reason for cleanup (for logging)
* @param ptyAlreadyExited - If true, PTY has already exited (don't try to kill)
*/
function cleanupSession(sessionName, sessionState, reason = 'unknown', ptyAlreadyExited = false) {
if (!sessionState) {
sessionState = terminalSessions.get(sessionName)
}
if (!sessionState) {
return
}
// Prevent double cleanup
if (sessionState.cleanedUp) {
console.log(`[PTY] Session ${sessionName} already cleaned up, skipping`)
return
}
sessionState.cleanedUp = true
console.log(`[PTY] Cleaning up session ${sessionName} (reason: ${reason}, ptyExited: ${ptyAlreadyExited})`)
// Clear any pending cleanup timer
if (sessionState.cleanupTimer) {
clearTimeout(sessionState.cleanupTimer)
sessionState.cleanupTimer = null
}
// Close log stream
if (sessionState.logStream) {
try {
sessionState.logStream.end()
} catch (e) {
// Ignore
}
}
// Kill the PTY process (skip if it already exited)
if (sessionState.ptyProcess) {
killPtyProcess(sessionState.ptyProcess, sessionName, ptyAlreadyExited)
}
// Stop JSONL file watcher
if (sessionState.jsonlWatcher) {
try {
fs.unwatchFile(sessionState.jsonlFilePath)
} catch { /* ignore */ }
sessionState.jsonlWatcher = null
}
// Stop hook state file watcher
if (sessionState._hookStateWatcher && sessionState._hookStateFile) {
try {
fs.unwatchFile(sessionState._hookStateFile)
} catch { /* ignore */ }
sessionState._hookStateWatcher = null
}
// Close all remaining client connections
if (sessionState.clients) {
sessionState.clients.forEach((client) => {
try {
if (client.readyState === 1) { // WebSocket.OPEN
client.close(1000, 'Session cleaned up')
}
} catch (e) {
// Ignore close errors
}
})
sessionState.clients.clear()
}
// Clear chat clients
if (sessionState.chatClients) {
sessionState.chatClients.clear()
}
// Remove from terminal sessions map
terminalSessions.delete(sessionName)
// Clean up activity tracking
sessionActivity.delete(sessionName)
const idleTimer = idleTimers.get(sessionName)
if (idleTimer?.timer) {
clearTimeout(idleTimer.timer)
}
idleTimers.delete(sessionName)
console.log(`[PTY] Session ${sessionName} cleaned up. Active sessions: ${terminalSessions.size}`)
}
/**
* Handle client removal from a session
* Schedules cleanup if no clients remain
*/
function handleClientDisconnect(ws, sessionName, sessionState, reason = 'close') {
if (!sessionState) return
// Remove this client from both regular and chat client sets
sessionState.clients.delete(ws)
sessionState.chatClients?.delete(ws)
console.log(`[PTY] Client disconnected from ${sessionName} (${reason}). Remaining clients: ${sessionState.clients.size}`)
// If no clients remain, schedule cleanup
if (sessionState.clients.size === 0) {
console.log(`[PTY] Last client disconnected from ${sessionName}, scheduling cleanup in ${PTY_CLEANUP_GRACE_MS / 1000}s`)
// Clear any existing cleanup timer
if (sessionState.cleanupTimer) {
clearTimeout(sessionState.cleanupTimer)
}
// Schedule cleanup after grace period
sessionState.cleanupTimer = setTimeout(() => {
// Double-check no clients reconnected
if (sessionState.clients.size === 0) {
cleanupSession(sessionName, sessionState, 'no_clients_after_grace_period')
}
}, PTY_CLEANUP_GRACE_MS)
}
}
/**
* Periodic cleanup of orphaned sessions
* Runs every ORPHAN_CLEANUP_INTERVAL_MS to catch any leaked PTYs
*/
function startOrphanedPtyCleanup() {
setInterval(() => {
let orphanedCount = 0
terminalSessions.forEach((sessionState, sessionName) => {
// Skip if already cleaned up or being cleaned up
if (sessionState.cleanedUp) {
return
}
// Check for sessions with no clients and no pending cleanup timer
// These are orphaned - they have a PTY but no way to clean it up
if (sessionState.clients.size === 0 && !sessionState.cleanupTimer) {
console.log(`[PTY] Found orphaned session: ${sessionName}`)
cleanupSession(sessionName, sessionState, 'orphan_cleanup', false)
orphanedCount++
}
})
if (orphanedCount > 0) {
console.log(`[PTY] Cleaned up ${orphanedCount} orphaned session(s). Active: ${terminalSessions.size}`)
}
}, ORPHAN_CLEANUP_INTERVAL_MS)
console.log(`[PTY] Orphaned PTY cleanup scheduled every ${ORPHAN_CLEANUP_INTERVAL_MS / 1000}s`)
}
/**
* Get agentId for a session
*
* Session names follow the pattern: agentId@hostId (like email)
* - For local sessions: the session name IS the agentId (e.g., "my-agent")
* - For structured sessions: "my-agent@local" or "my-agent@remote1"
*
* We verify the agent exists by checking if its database directory exists.
*/
function getAgentIdForSession(sessionName) {
try {
// Parse session name to extract agentId
// Format: agentId@hostId or just agentId for legacy
const atIndex = sessionName.indexOf('@')
const agentId = atIndex > 0 ? sessionName.substring(0, atIndex) : sessionName
// Verify the agent database directory exists
const agentDbPath = path.join(os.homedir(), '.aimaestro', 'agents', agentId)
if (fs.existsSync(agentDbPath) && fs.statSync(agentDbPath).isDirectory()) {
return agentId
}
} catch {
// Agent directory doesn't exist or error accessing it
}
return null
}
/**
* Send a chat message to a tmux session with verification.
*
* 1. Check if the agent is at a permission prompt — refuse if so.
* 2. Capture pane baseline.
* 3. Write text to a temp file, load into tmux buffer, paste into pane.
* 4. Poll until the tail of the text appears in the pane (paste-probe).
* 5. Send Enter only after verification (or after timeout).
*
* Returns { ok, error? }
*/
const PASTE_PROBE_TIMEOUT_MS = 1200
const PASTE_PROBE_INTERVAL_MS = 50
const PASTE_PROBE_MIN_CHARS = 8
function capturePaneCompact(sessionName, lines = 100) {
try {
const res = execSync(
`tmux capture-pane -p -J -t "${sessionName}" -S -${lines}`,
{ timeout: 2000, encoding: 'utf-8' }
)
return res.replace(/\s+/g, ' ').trim()
} catch { return '' }
}
function pasteTailProbe(text) {
const compacted = text.replace(/\s+/g, ' ').trim()
if (compacted.length <= PASTE_PROBE_MIN_CHARS) return compacted
return compacted.slice(-Math.min(80, compacted.length))
}
function isAgentAtPermissionPrompt(sessionName) {
try {
const raw = execSync(
`tmux capture-pane -p -t "${sessionName}" -S -15`,
{ timeout: 2000, encoding: 'utf-8' }
)
const lines = raw.split('\n').map(l => l.trim()).filter(Boolean)
const lastLines = lines.slice(-12).join('\n').toLowerCase()
return lastLines.includes('esc to cancel') &&
(lastLines.includes('do you want to proceed') ||
lastLines.includes('yes, and don\'t ask') ||
/❯\s*1\.\s*yes/i.test(lastLines))
} catch { return false }
}
async function sendChatMessage(sessionName, message) {
// 1. Check hookState first (fast path)
const sessionState = terminalSessions.get(sessionName)
if (sessionState?._lastPermission?.status === 'permission_request') {
return { ok: false, error: 'Agent is waiting for permission approval. Approve or deny the pending action first.' }
}
// 2. Check pane for permission prompt (catches cases hookState missed)
if (isAgentAtPermissionPrompt(sessionName)) {
return { ok: false, error: 'Agent is waiting for permission approval. Approve or deny the pending action first.' }
}
// 3. Capture baseline for paste-probe verification
const baseline = capturePaneCompact(sessionName)
// 4. Write text to temp file, load into tmux buffer, paste into pane
const tmpFile = path.join(os.tmpdir(), `aimaestro-send-${Date.now()}.txt`)
const bufferName = `aimaestro-${Date.now()}`
try {
fs.writeFileSync(tmpFile, message, 'utf-8')
execSync(`tmux load-buffer -b "${bufferName}" "${tmpFile}"`, { timeout: 3000 })
execSync(`tmux paste-buffer -d -r -b "${bufferName}" -t "${sessionName}"`, { timeout: 3000 })
} catch (err) {
try { fs.unlinkSync(tmpFile) } catch {}
try { execSync(`tmux delete-buffer -b "${bufferName}"`, { timeout: 1000 }) } catch {}
return { ok: false, error: 'Failed to paste text: ' + err.message }
}
try { fs.unlinkSync(tmpFile) } catch {}
// 5. Paste-probe: poll until text tail appears in pane
const probe = pasteTailProbe(message)
if (probe) {
const baselineCount = (baseline.match(new RegExp(probe.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) || []).length
const deadline = Date.now() + PASTE_PROBE_TIMEOUT_MS
while (Date.now() < deadline) {
const captured = capturePaneCompact(sessionName)
const currentCount = (captured.match(new RegExp(probe.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) || []).length
if (currentCount > baselineCount) break
await new Promise(r => setTimeout(r, PASTE_PROBE_INTERVAL_MS))
}
}
// 6. Send Enter (C-m is more reliable than Enter through tmux)
try {
execSync(`tmux send-keys -t "${sessionName}" C-m`, { timeout: 3000 })
} catch (err) {
return { ok: false, error: 'Text pasted but Enter failed: ' + err.message }
}
return { ok: true }
}
/**
* Extract structured activity signals from raw PTY output.
* Returns { label, detail? } or null if no recognizable signal.
*/
function extractPtyActivity(cleanedData) {
const trimmed = cleanedData.replace(/[\r\n]/g, ' ').trim()
if (!trimmed || trimmed.length < 2) return null
// Thinking step progress: [1/418], [2/418], etc.
const stepMatch = trimmed.match(/\[(\d+)\/(\d+)\]/)
if (stepMatch) {
return { label: 'Thinking', detail: `step ${stepMatch[1]}/${stepMatch[2]}` }
}
// Spinner status: "✳ Forming...", "· Thinking…", "· Reading..."
const spinnerMatch = trimmed.match(/[✳·⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]\s*(\w+ing)[\.\…]*/i)
if (spinnerMatch) {
return { label: spinnerMatch[1] }
}
// Tool execution patterns from Claude Code TUI
const toolPatterns = [
{ re: /(?:Running|Executing)\s+`([^`]{1,60})`/i, label: 'Running', detail: (m) => m[1] },
{ re: /(?:Reading|Read)\s+([^\s]{1,80})/i, label: 'Reading', detail: (m) => m[1] },
{ re: /(?:Writing|Wrote)\s+([^\s]{1,80})/i, label: 'Writing', detail: (m) => m[1] },
{ re: /(?:Editing|Edited)\s+([^\s]{1,80})/i, label: 'Editing', detail: (m) => m[1] },
{ re: /(?:Searching|Searched|Grep)\s+(.{1,60})/i, label: 'Searching', detail: (m) => m[1] },
{ re: /Compacting conversation/i, label: 'Compacting' },
]
for (const { re, label, detail } of toolPatterns) {
const m = trimmed.match(re)
if (m) return { label, detail: detail ? detail(m) : undefined }
}
return null
}
/**
* Track session activity and detect idle transitions
* Sends host hints to agents when session goes idle
*/
function trackSessionActivity(sessionName) {
const now = Date.now()
const previousActivity = sessionActivity.get(sessionName)
const previousState = idleTimers.get(sessionName)
// Update activity timestamp
sessionActivity.set(sessionName, now)
// Clear existing idle timer
if (previousState?.timer) {
clearTimeout(previousState.timer)
}
// Schedule idle transition check
const timer = setTimeout(() => {
// Check if still idle (no new activity since timer was set)
const currentActivity = sessionActivity.get(sessionName)
if (currentActivity && now === currentActivity) {
// Session went idle - notify agent via host hints
const agentId = getAgentIdForSession(sessionName)
if (agentId) {
console.log(`[IdleDetect] Session ${sessionName} went idle, notifying agent ${agentId.substring(0, 8)}`)
hostHints.notifyIdleTransition(agentId)
}
}
// Update state to reflect idle
idleTimers.set(sessionName, { timer: null, wasActive: false })
}, IDLE_THRESHOLD_MS)
// Update idle timer state
idleTimers.set(sessionName, { timer, wasActive: true })
}
// Create logs directory if it doesn't exist
const logsDir = path.join(process.cwd(), 'logs')
if (!fs.existsSync(logsDir)) {
fs.mkdirSync(logsDir, { recursive: true })
}
// statusSubscribers, broadcastStatusUpdate imported from shared-state-bridge.mjs
/**
* Start the HTTP server with the given request handler.
* All WebSocket servers, PTY handling, startup tasks, and graceful shutdown
* are shared between full and headless modes.
*/
async function startServer(handleRequest) {
const server = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url, true)
// Internal endpoint for PTY debug info - served directly from server.mjs
// This allows access to the in-memory sessions map
if (parsedUrl.pathname === '/api/internal/pty-sessions') {
res.setHeader('Content-Type', 'application/json')
const sessionInfo = []
terminalSessions.forEach((state, name) => {
sessionInfo.push({
name,
clients: state.clients?.size || 0,
hasPty: !!state.ptyProcess,
pid: state.ptyProcess?.pid || null,
hasCleanupTimer: !!state.cleanupTimer,
lastActivity: sessionActivity.get(name) || null
})
})
res.end(JSON.stringify({
activeSessions: terminalSessions.size,
sessions: sessionInfo,
timestamp: new Date().toISOString()
}))
return
}
await handleRequest(req, res, parsedUrl)
} catch (err) {
console.error('Error handling request:', err)
res.statusCode = 500
res.end('Internal server error')
}
})
// WebSocket server for terminal connections
const wss = new WebSocketServer({ noServer: true })
// Handle remote worker connections (proxy WebSocket to remote host)
// With retry logic for flaky networks
function handleRemoteWorker(clientWs, sessionName, workerUrl, extraParams = '') {
const MAX_RETRIES = 5
const RETRY_DELAYS = [500, 1000, 2000, 3000, 5000] // Exponential backoff
let retryCount = 0
let workerWs = null
let clientClosed = false
const messageQueue = [] // Buffer client messages until remote connects
// Build WebSocket URL for remote worker
const workerWsUrl = `${workerUrl}/term?name=${encodeURIComponent(sessionName)}${extraParams}`
.replace(/^http:/, 'ws:')
.replace(/^https:/, 'wss:')
// Send status message to client
function sendStatus(message, type = 'info') {
if (clientWs.readyState === 1) {
try {
clientWs.send(JSON.stringify({ type: 'status', message, statusType: type }))
} catch (e) {
// Ignore send errors
}
}
}
// Register client message handler IMMEDIATELY so early messages
// (e.g. chat:requestHistory sent on connect) are not lost
clientWs.on('message', (data) => {
if (workerWs && workerWs.readyState === WebSocket.OPEN) {
workerWs.send(data)
} else {
// Remote not connected yet — queue for later
messageQueue.push(data)
}
})
clientWs.on('close', () => {
clientClosed = true
console.log(`🌐 [REMOTE] Client disconnected from ${sessionName}`)
if (workerWs && workerWs.readyState === WebSocket.OPEN) {
workerWs.close()
}
})
clientWs.on('error', (error) => {
clientClosed = true
console.error(`🌐 [REMOTE] Client error for ${sessionName}:`, error.message)
if (workerWs && workerWs.readyState === WebSocket.OPEN) {
workerWs.close()
}
})
// Attempt connection with retry
function attemptConnection() {
if (clientClosed) {
console.log(`🌐 [REMOTE] Client closed, aborting connection to ${sessionName}`)
return
}
if (retryCount > 0) {
console.log(`🌐 [REMOTE] Retry ${retryCount}/${MAX_RETRIES} connecting to ${workerUrl}`)
sendStatus(`Retrying connection (${retryCount}/${MAX_RETRIES})...`, 'warning')
} else {
console.log(`🌐 [REMOTE] Connecting to remote worker: ${workerUrl}`)
sendStatus('Connecting to remote host...', 'info')
}
workerWs = new WebSocket(workerWsUrl)
// Set connection timeout
const connectionTimeout = setTimeout(() => {
if (workerWs.readyState === WebSocket.CONNECTING) {
console.log(`🌐 [REMOTE] Connection timeout for ${sessionName}`)
workerWs.terminate()
}
}, 10000) // 10 second timeout
workerWs.on('open', () => {
clearTimeout(connectionTimeout)
console.log(`🌐 [REMOTE] Connected to ${sessionName} at ${workerUrl}`)
sendStatus('Connected to remote host', 'success')
// Reset retry count on successful connection
retryCount = 0
// Track activity for remote sessions
sessionActivity.set(sessionName, Date.now())
// Flush queued messages (e.g. chat:requestHistory sent before remote connected)
while (messageQueue.length > 0) {
const queued = messageQueue.shift()
if (workerWs.readyState === WebSocket.OPEN) {
workerWs.send(queued)
}
}
// Proxy messages: remote worker → browser
workerWs.on('message', (data) => {
// Convert Buffer to string if needed
const dataStr = typeof data === 'string' ? data : data.toString('utf8')
if (clientWs.readyState === 1) { // WebSocket.OPEN
// Send as string (browser expects string)
clientWs.send(dataStr)