-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathsession-lifecycle.ts
More file actions
168 lines (147 loc) · 4.51 KB
/
Copy pathsession-lifecycle.ts
File metadata and controls
168 lines (147 loc) · 4.51 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
import { spawn, type IPty } from 'bun-pty'
import { RingBuffer } from './buffer.ts'
import { TerminalSnapshot } from './snapshot.ts'
import type { PTYSession, PTYSessionInfo, SpawnOptions } from './types.ts'
import { DEFAULT_TERMINAL_COLS, DEFAULT_TERMINAL_ROWS } from '../constants.ts'
import moment from 'moment'
const SESSION_ID_BYTE_LENGTH = 4
function generateId(): string {
const hex = Array.from(crypto.getRandomValues(new Uint8Array(SESSION_ID_BYTE_LENGTH)))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
return `pty_${hex}`
}
export class SessionLifecycleManager {
private sessions: Map<string, PTYSession> = new Map()
private createSessionObject(opts: SpawnOptions): PTYSession {
const id = generateId()
const args = opts.args ?? []
const workdir = opts.workdir ?? process.cwd()
const title =
opts.title ?? (`${opts.command} ${args.join(' ')}`.trim() || `Terminal ${id.slice(-4)}`)
const buffer = new RingBuffer()
const snapshot = new TerminalSnapshot(DEFAULT_TERMINAL_COLS, DEFAULT_TERMINAL_ROWS)
return {
id,
title,
description: opts.description,
command: opts.command,
args,
workdir,
env: opts.env,
status: 'running',
pid: 0, // will be set after spawn
createdAt: moment(),
parentSessionId: opts.parentSessionId,
parentAgent: opts.parentAgent,
notifyOnExit: opts.notifyOnExit ?? false,
buffer,
snapshot,
process: null, // will be set
}
}
private spawnProcess(session: PTYSession): void {
const env = { ...process.env, ...session.env } as Record<string, string>
const ptyProcess: IPty = spawn(session.command, session.args, {
name: 'xterm-256color',
cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS,
cwd: session.workdir,
env,
})
session.process = ptyProcess
session.pid = ptyProcess.pid
}
private setupEventHandlers(
session: PTYSession,
onData: (session: PTYSession, data: string) => void,
onExit: (session: PTYSession, exitCode: number | null) => void
): void {
session.process?.onData((data: string) => {
session.buffer.append(data)
session.snapshot.write(data)
onData(session, data)
})
session.process?.onExit(({ exitCode, signal }) => {
// Flush any remaining incomplete line in the buffer
session.buffer.flush()
if (session.status === 'killing') {
session.status = 'killed'
} else {
session.status = 'exited'
}
session.exitCode = exitCode
session.exitSignal = signal
onExit(session, exitCode)
})
}
spawn(
opts: SpawnOptions,
onData: (session: PTYSession, data: string) => void,
onExit: (session: PTYSession, exitCode: number | null) => void
): PTYSessionInfo {
const session = this.createSessionObject(opts)
this.spawnProcess(session)
this.setupEventHandlers(session, onData, onExit)
this.sessions.set(session.id, session)
return this.toInfo(session)
}
kill(id: string, cleanup: boolean = false): boolean {
const session = this.sessions.get(id)
if (!session) {
return false
}
if (session.status === 'running') {
session.status = 'killing'
try {
session.process?.kill()
} catch {
// Ignore kill errors
}
}
if (cleanup) {
session.buffer.clear()
this.sessions.delete(id)
}
return true
}
private clearAllSessionsInternal(): void {
for (const id of [...this.sessions.keys()]) {
this.kill(id, true)
}
}
clearAllSessions(): void {
this.clearAllSessionsInternal()
}
cleanupBySession(parentSessionId: string): void {
for (const [id, session] of this.sessions) {
if (session.parentSessionId === parentSessionId) {
this.kill(id, true)
}
}
}
getSession(id: string): PTYSession | null {
return this.sessions.get(id) || null
}
listSessions(): PTYSession[] {
return Array.from(this.sessions.values())
}
toInfo(session: PTYSession): PTYSessionInfo {
const snapshot = session.snapshot.getState()
return {
id: session.id,
title: session.title,
description: session.description,
command: session.command,
args: session.args,
workdir: session.workdir,
status: session.status,
exitCode: session.exitCode,
exitSignal: session.exitSignal,
pid: session.pid,
createdAt: session.createdAt.toISOString(true),
lineCount: session.buffer.length,
size: snapshot.size,
}
}
}