-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmanager.ts
More file actions
241 lines (207 loc) · 6.85 KB
/
manager.ts
File metadata and controls
241 lines (207 loc) · 6.85 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
import type { IPty } from "bun-pty";
import type { OpencodeClient } from "@opencode-ai/sdk";
import { RingBuffer } from "./buffer.ts";
import type { PTYSession, PTYSessionInfo, SpawnOptions, ReadResult, SearchResult } from "./types.ts";
import { createLogger } from "../logger.ts";
import { prepareShadowPty } from "./shadow.ts";
const log = createLogger("manager");
let client: OpencodeClient | null = null;
export function initManager(opcClient: OpencodeClient): void {
client = opcClient;
}
function generateId(): string {
const hex = Array.from(crypto.getRandomValues(new Uint8Array(4)))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return `pty_${hex}`;
}
class PTYManager {
private sessions: Map<string, PTYSession> = new Map();
private ptyModule: typeof import("bun-pty") | null = null;
private async ensureLoaded() {
if (this.ptyModule) return this.ptyModule;
await prepareShadowPty();
this.ptyModule = await import("bun-pty");
return this.ptyModule;
}
async spawn(opts: SpawnOptions): Promise<PTYSessionInfo> {
const { spawn } = await this.ensureLoaded();
const id = generateId();
const args = opts.args ?? [];
const workdir = opts.workdir ?? process.cwd();
const env = { ...process.env, ...opts.env } as Record<string, string>;
const title = opts.title ?? (`${opts.command} ${args.join(" ")}`.trim() || `Terminal ${id.slice(-4)}`);
log.info("spawning pty", { id, command: opts.command, args, workdir });
const ptyProcess: IPty = spawn(opts.command, args, {
name: "xterm-256color",
cols: 120,
rows: 40,
cwd: workdir,
env,
});
const buffer = new RingBuffer();
const session: PTYSession = {
id,
title,
description: opts.description,
command: opts.command,
args,
workdir,
env: opts.env,
status: "running",
pid: ptyProcess.pid,
createdAt: new Date(),
parentSessionId: opts.parentSessionId,
notifyOnExit: opts.notifyOnExit ?? false,
buffer,
process: ptyProcess,
};
this.sessions.set(id, session);
ptyProcess.onData((data: string) => {
buffer.append(data);
});
ptyProcess.onExit(async ({ exitCode }: { exitCode: number }) => {
log.info("pty exited", { id, exitCode });
if (session.status === "running") {
session.status = "exited";
session.exitCode = exitCode;
}
if (session.notifyOnExit && client) {
try {
const message = this.buildExitNotification(session, exitCode);
await client.session.promptAsync({
path: { id: session.parentSessionId },
body: {
parts: [{ type: "text", text: message }],
},
});
log.info("sent exit notification", { id, exitCode, parentSessionId: session.parentSessionId });
} catch (err) {
log.error("failed to send exit notification", { id, error: String(err) });
}
}
});
return this.toInfo(session);
}
write(id: string, data: string): boolean {
const session = this.sessions.get(id);
if (!session) {
return false;
}
if (session.status !== "running") {
return false;
}
session.process.write(data);
return true;
}
read(id: string, offset: number = 0, limit?: number): ReadResult | null {
const session = this.sessions.get(id);
if (!session) {
return null;
}
const lines = session.buffer.read(offset, limit);
const totalLines = session.buffer.length;
const hasMore = offset + lines.length < totalLines;
return { lines, totalLines, offset, hasMore };
}
search(id: string, pattern: RegExp, offset: number = 0, limit?: number): SearchResult | null {
const session = this.sessions.get(id);
if (!session) {
return null;
}
const allMatches = session.buffer.search(pattern);
const totalMatches = allMatches.length;
const totalLines = session.buffer.length;
const paginatedMatches = limit !== undefined
? allMatches.slice(offset, offset + limit)
: allMatches.slice(offset);
const hasMore = offset + paginatedMatches.length < totalMatches;
return { matches: paginatedMatches, totalMatches, totalLines, offset, hasMore };
}
list(): PTYSessionInfo[] {
return Array.from(this.sessions.values()).map((s) => this.toInfo(s));
}
get(id: string): PTYSessionInfo | null {
const session = this.sessions.get(id);
return session ? this.toInfo(session) : null;
}
kill(id: string, cleanup: boolean = false): boolean {
const session = this.sessions.get(id);
if (!session) {
return false;
}
log.info("killing pty", { id, cleanup });
if (session.status === "running") {
try {
session.process.kill();
} catch {}
session.status = "killed";
}
if (cleanup) {
session.buffer.clear();
this.sessions.delete(id);
}
return true;
}
cleanupBySession(parentSessionId: string): void {
log.info("cleaning up ptys for session", { parentSessionId });
for (const [id, session] of this.sessions) {
if (session.parentSessionId === parentSessionId) {
this.kill(id, true);
}
}
}
cleanupAll(): void {
log.info("cleaning up all ptys");
for (const id of this.sessions.keys()) {
this.kill(id, true);
}
}
private toInfo(session: PTYSession): PTYSessionInfo {
return {
id: session.id,
title: session.title,
command: session.command,
args: session.args,
workdir: session.workdir,
status: session.status,
exitCode: session.exitCode,
pid: session.pid,
createdAt: session.createdAt,
lineCount: session.buffer.length,
};
}
private buildExitNotification(session: PTYSession, exitCode: number): string {
const lineCount = session.buffer.length;
let lastLine = "";
if (lineCount > 0) {
for (let i = lineCount - 1; i >= 0; i--) {
const bufferLines = session.buffer.read(i, 1);
const line = bufferLines[0];
if (line !== undefined && line.trim() !== "") {
lastLine = line.length > 250 ? line.slice(0, 250) + "..." : line;
break;
}
}
}
const displayTitle = session.description ?? session.title;
const truncatedTitle = displayTitle.length > 64 ? displayTitle.slice(0, 64) + "..." : displayTitle;
const lines = [
"<pty_exited>",
`ID: ${session.id}`,
`Description: ${truncatedTitle}`,
`Exit Code: ${exitCode}`,
`Output Lines: ${lineCount}`,
`Last Line: ${lastLine}`,
"</pty_exited>",
"",
];
if (exitCode === 0) {
lines.push("Use pty_read to check the full output.");
} else {
lines.push("Process failed. Use pty_read with the pattern parameter to search for errors in the output.");
}
return lines.join("\n");
}
}
export const manager = new PTYManager();