@myrialabs/clopen 0.4.6 → 0.4.7

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.
@@ -1,300 +0,0 @@
1
- /**
2
- * Terminal Stream Manager
3
- * Manages background terminal streams and their state
4
- * Uses @xterm/headless to maintain accurate terminal state in-memory
5
- */
6
-
7
- import type { IPty } from 'bun-pty';
8
- import { Terminal } from '@xterm/headless';
9
- import { SerializeAddon } from '@xterm/addon-serialize';
10
-
11
- interface TerminalStream {
12
- streamId: string;
13
- sessionId: string;
14
- command: string;
15
- pty: IPty;
16
- status: 'active' | 'completed' | 'error' | 'cancelled';
17
- startedAt: Date;
18
- workingDirectory?: string;
19
- projectPath?: string;
20
- projectId?: string;
21
- processId?: number;
22
- headlessTerminal: Terminal;
23
- serializeAddon: SerializeAddon;
24
- }
25
-
26
- class TerminalStreamManager {
27
- private streams: Map<string, TerminalStream> = new Map();
28
- private sessionToStream: Map<string, string> = new Map();
29
-
30
- /**
31
- * Create a headless terminal instance with serialize addon
32
- */
33
- private createHeadlessTerminal(cols: number, rows: number): { terminal: Terminal; serializeAddon: SerializeAddon } {
34
- const terminal = new Terminal({
35
- scrollback: 5000,
36
- cols,
37
- rows,
38
- allowProposedApi: true
39
- });
40
- const serializeAddon = new SerializeAddon();
41
- terminal.loadAddon(serializeAddon);
42
- return { terminal, serializeAddon };
43
- }
44
-
45
- /**
46
- * Create a new terminal stream
47
- */
48
- createStream(
49
- sessionId: string,
50
- command: string,
51
- pty: IPty,
52
- workingDirectory?: string,
53
- projectPath?: string,
54
- projectId?: string,
55
- predefinedStreamId?: string,
56
- terminalSize?: { cols: number; rows: number }
57
- ): string {
58
- const cols = terminalSize?.cols || 80;
59
- const rows = terminalSize?.rows || 24;
60
-
61
- // Check if there's already a stream for this session
62
- const existingStreamId = this.sessionToStream.get(sessionId);
63
- if (existingStreamId) {
64
- const existingStream = this.streams.get(existingStreamId);
65
- if (existingStream) {
66
- if (existingStream.pty === pty) {
67
- // Same PTY (reconnection) - reuse existing headless terminal as-is
68
- // The headless terminal already has all accumulated output
69
- const newStreamId = predefinedStreamId || existingStreamId;
70
-
71
- // Resize headless terminal if dimensions changed
72
- existingStream.headlessTerminal.resize(cols, rows);
73
-
74
- // Update stream ID if changed
75
- if (newStreamId !== existingStreamId) {
76
- this.streams.delete(existingStreamId);
77
- existingStream.streamId = newStreamId;
78
- this.streams.set(newStreamId, existingStream);
79
- this.sessionToStream.set(sessionId, newStreamId);
80
- }
81
-
82
- return newStreamId;
83
- }
84
-
85
- // Different PTY, kill the old one and dispose headless terminal
86
- if (existingStream.pty) {
87
- try {
88
- existingStream.pty.kill();
89
- } catch {
90
- // Ignore error if PTY already killed
91
- }
92
- }
93
- existingStream.serializeAddon.dispose();
94
- existingStream.headlessTerminal.dispose();
95
- this.streams.delete(existingStreamId);
96
- }
97
- }
98
-
99
- // Use provided streamId or generate a new one
100
- const streamId = predefinedStreamId || `terminal-stream-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
101
-
102
- // Create headless terminal
103
- const { terminal: headlessTerminal, serializeAddon } = this.createHeadlessTerminal(cols, rows);
104
-
105
- const stream: TerminalStream = {
106
- streamId,
107
- sessionId,
108
- command,
109
- pty,
110
- status: 'active',
111
- startedAt: new Date(),
112
- workingDirectory,
113
- projectPath,
114
- projectId,
115
- processId: pty.pid,
116
- headlessTerminal,
117
- serializeAddon
118
- };
119
-
120
- this.streams.set(streamId, stream);
121
- this.sessionToStream.set(sessionId, streamId);
122
-
123
- return streamId;
124
- }
125
-
126
- /**
127
- * Get stream by ID
128
- */
129
- getStream(streamId: string): TerminalStream | undefined {
130
- return this.streams.get(streamId);
131
- }
132
-
133
- /**
134
- * Get stream by session ID
135
- */
136
- getStreamBySession(sessionId: string): TerminalStream | undefined {
137
- const streamId = this.sessionToStream.get(sessionId);
138
- if (streamId) {
139
- return this.streams.get(streamId);
140
- }
141
- return undefined;
142
- }
143
-
144
- /**
145
- * Add output to stream (writes to headless terminal)
146
- */
147
- addOutput(streamId: string, output: string): void {
148
- const stream = this.streams.get(streamId);
149
- if (stream) {
150
- stream.headlessTerminal.write(output);
151
- }
152
- }
153
-
154
- /**
155
- * Get serialized terminal output for a stream
156
- */
157
- getSerializedOutput(streamId: string): string {
158
- const stream = this.streams.get(streamId);
159
- if (stream) {
160
- return stream.serializeAddon.serialize();
161
- }
162
- return '';
163
- }
164
-
165
- /**
166
- * Get serialized terminal output by session ID
167
- */
168
- getSerializedOutputBySession(sessionId: string): string {
169
- const streamId = this.sessionToStream.get(sessionId);
170
- if (streamId) {
171
- return this.getSerializedOutput(streamId);
172
- }
173
- return '';
174
- }
175
-
176
- /**
177
- * Clear headless terminal buffer (sync with frontend clear)
178
- */
179
- clearHeadlessTerminal(sessionId: string): void {
180
- const streamId = this.sessionToStream.get(sessionId);
181
- if (streamId) {
182
- const stream = this.streams.get(streamId);
183
- if (stream) {
184
- stream.headlessTerminal.clear();
185
- }
186
- }
187
- }
188
-
189
- /**
190
- * Resize headless terminal to match PTY dimensions
191
- */
192
- resizeHeadlessTerminal(sessionId: string, cols: number, rows: number): void {
193
- const streamId = this.sessionToStream.get(sessionId);
194
- if (streamId) {
195
- const stream = this.streams.get(streamId);
196
- if (stream) {
197
- stream.headlessTerminal.resize(cols, rows);
198
- }
199
- }
200
- }
201
-
202
- /**
203
- * Update stream status
204
- */
205
- updateStatus(streamId: string, status: TerminalStream['status']): void {
206
- const stream = this.streams.get(streamId);
207
- if (stream) {
208
- stream.status = status;
209
-
210
- // Clean up completed/cancelled streams after a delay
211
- if (status === 'completed' || status === 'cancelled' || status === 'error') {
212
- // Keep stream for 5 minutes for reconnection attempts
213
- setTimeout(() => {
214
- this.removeStream(streamId);
215
- }, 5 * 60 * 1000);
216
- }
217
- }
218
- }
219
-
220
- /**
221
- * Remove stream and dispose headless terminal
222
- */
223
- removeStream(streamId: string): void {
224
- const stream = this.streams.get(streamId);
225
- if (stream) {
226
- // Kill PTY if still active
227
- if (stream.status === 'active' && stream.pty) {
228
- try {
229
- stream.pty.kill();
230
- } catch {
231
- // Silently handle error
232
- }
233
- }
234
-
235
- // Dispose headless terminal
236
- stream.serializeAddon.dispose();
237
- stream.headlessTerminal.dispose();
238
-
239
- // Remove from maps
240
- this.streams.delete(streamId);
241
- this.sessionToStream.delete(stream.sessionId);
242
- }
243
- }
244
-
245
- /**
246
- * Get stream status info
247
- */
248
- getStreamStatus(streamId: string): {
249
- status: string;
250
- bufferLength: number;
251
- startedAt: Date;
252
- processId?: number;
253
- } | null {
254
- const stream = this.streams.get(streamId);
255
- if (!stream) {
256
- return null;
257
- }
258
-
259
- return {
260
- status: stream.status,
261
- bufferLength: stream.headlessTerminal.buffer.active.length,
262
- startedAt: stream.startedAt,
263
- processId: stream.processId
264
- };
265
- }
266
-
267
- /**
268
- * Clean up terminal streams for a specific project
269
- */
270
- cleanupProjectStreams(projectId: string): number {
271
- let cleaned = 0;
272
-
273
- for (const [streamId, stream] of this.streams) {
274
- if (stream.projectId === projectId) {
275
- if (stream.status === 'active' && stream.pty) {
276
- try { stream.pty.kill(); } catch {}
277
- }
278
- stream.serializeAddon.dispose();
279
- stream.headlessTerminal.dispose();
280
- this.streams.delete(streamId);
281
- this.sessionToStream.delete(stream.sessionId);
282
- cleaned++;
283
- }
284
- }
285
-
286
- return cleaned;
287
- }
288
-
289
- /**
290
- * Clean up all streams
291
- */
292
- cleanup(): void {
293
- for (const streamId of this.streams.keys()) {
294
- this.removeStream(streamId);
295
- }
296
- }
297
- }
298
-
299
- // Export singleton instance
300
- export const terminalStreamManager = new TerminalStreamManager();
@@ -1,56 +0,0 @@
1
- /**
2
- * Terminal access guards.
3
- *
4
- * Resolves terminal-owned resources (PTY sessions, headless streams) to their
5
- * owning project, then defers to the global `requireProjectAccess` helper.
6
- * Centralising the lookup keeps every handler from re-implementing the
7
- * "manager.getSession → null check → project guard" boilerplate.
8
- */
9
-
10
- import type { WSConnection } from '$shared/utils/ws-server';
11
- import { requireProjectAccess } from '../access';
12
- import { ptySessionManager, type PtySession } from '../../terminal/pty-session-manager';
13
- import { terminalStreamManager } from '../../terminal/stream-manager';
14
-
15
- type TerminalStream = NonNullable<ReturnType<typeof terminalStreamManager.getStream>>;
16
-
17
- export function requirePtySessionAccess(conn: WSConnection, sessionId: string): PtySession {
18
- const session = ptySessionManager.getSession(sessionId);
19
- if (!session || !session.projectId) {
20
- throw new Error('Access denied');
21
- }
22
- requireProjectAccess(conn, session.projectId);
23
- return session;
24
- }
25
-
26
- export function requireTerminalStreamAccess(conn: WSConnection, streamId: string): TerminalStream {
27
- const stream = terminalStreamManager.getStream(streamId);
28
- if (!stream || !stream.projectId) {
29
- throw new Error('Access denied');
30
- }
31
- requireProjectAccess(conn, stream.projectId);
32
- return stream;
33
- }
34
-
35
- /**
36
- * Resolve a (sessionId, optional streamId) pair to its owning project.
37
- * Used by `terminal:missed-output` which accepts either or both ids.
38
- * Throws if neither resolves to an accessible project.
39
- */
40
- export function requireTerminalLookupAccess(
41
- conn: WSConnection,
42
- sessionId: string,
43
- streamId?: string
44
- ): { projectId: string; stream: TerminalStream | null; session: PtySession | null } {
45
- const session = ptySessionManager.getSession(sessionId) ?? null;
46
- const stream = streamId
47
- ? terminalStreamManager.getStream(streamId) ?? null
48
- : terminalStreamManager.getStreamBySession(sessionId) ?? null;
49
-
50
- const projectId = session?.projectId || stream?.projectId;
51
- if (!projectId) {
52
- throw new Error('Access denied');
53
- }
54
- requireProjectAccess(conn, projectId);
55
- return { projectId, stream, session };
56
- }
@@ -1,145 +0,0 @@
1
- /**
2
- * Terminal Stream Persistence
3
- *
4
- * Handles terminal stream persistence and reconnection:
5
- * - Get stream status
6
- * - Retrieve missed output
7
- * - Reconnect to existing streams
8
- */
9
-
10
- import { t } from 'elysia';
11
- import { createRouter } from '$shared/utils/ws-server';
12
- import { terminalStreamManager } from '../../terminal/stream-manager';
13
- import { debug } from '$shared/utils/logger';
14
- import { ws } from '$backend/utils/ws';
15
- import { ptySessionManager } from '../../terminal/pty-session-manager';
16
- import { requireTerminalStreamAccess, requireTerminalLookupAccess } from './access';
17
-
18
- export const persistenceHandler = createRouter()
19
- // Get stream status
20
- .http('terminal:stream-status', {
21
- data: t.Object({
22
- streamId: t.String()
23
- }),
24
- response: t.Any()
25
- }, async ({ data, conn }) => {
26
- const { streamId } = data;
27
-
28
- requireTerminalStreamAccess(conn, streamId);
29
-
30
- const status = terminalStreamManager.getStreamStatus(streamId);
31
-
32
- if (!status) {
33
- throw new Error('Stream not found');
34
- }
35
-
36
- return status;
37
- })
38
-
39
- // Get missed output (serialized terminal state)
40
- .http('terminal:missed-output', {
41
- data: t.Object({
42
- sessionId: t.String(),
43
- streamId: t.Optional(t.String())
44
- }),
45
- response: t.Object({
46
- sessionId: t.String(),
47
- streamId: t.Union([t.String(), t.Null()]),
48
- output: t.String(),
49
- status: t.String(),
50
- timestamp: t.String()
51
- })
52
- }, async ({ data, conn }) => {
53
- const { sessionId, streamId } = data;
54
-
55
- requireTerminalLookupAccess(conn, sessionId, streamId);
56
-
57
- // Get serialized terminal state from headless xterm
58
- let output = '';
59
-
60
- if (streamId) {
61
- output = terminalStreamManager.getSerializedOutput(streamId);
62
- } else {
63
- output = terminalStreamManager.getSerializedOutputBySession(sessionId);
64
- }
65
-
66
- const streamStatus = streamId ? terminalStreamManager.getStreamStatus(streamId) : null;
67
-
68
- return {
69
- sessionId,
70
- streamId: streamId || null,
71
- output,
72
- status: streamStatus?.status || 'unknown',
73
- timestamp: new Date().toISOString()
74
- };
75
- })
76
-
77
- // Reconnect to stream
78
- .on('terminal:reconnect', {
79
- data: t.Object({
80
- streamId: t.String(),
81
- sessionId: t.String()
82
- })
83
- }, async ({ data, conn }) => {
84
- const { streamId, sessionId } = data;
85
-
86
- const stream = terminalStreamManager.getStream(streamId);
87
- if (!stream || !stream.projectId) {
88
- const fallbackProjectId = ws.getProjectId(conn);
89
- ws.emit.project(fallbackProjectId, 'terminal:error', {
90
- sessionId,
91
- error: 'Access denied'
92
- });
93
- return;
94
- }
95
- requireTerminalStreamAccess(conn, streamId);
96
- const projectId = stream.projectId;
97
-
98
- try {
99
- // Send serialized terminal state (frontend writes it to xterm to restore)
100
- const serializedOutput = terminalStreamManager.getSerializedOutput(streamId);
101
-
102
- if (serializedOutput) {
103
- ws.emit.project(projectId, 'terminal:output', {
104
- sessionId,
105
- content: serializedOutput,
106
- timestamp: new Date().toISOString()
107
- });
108
- }
109
-
110
- if (stream.status === 'active') {
111
- // If no dataListeners exist yet (create-session hasn't been called),
112
- // set up a project-broadcast listener so ongoing output reaches all clients.
113
- // This listener will be replaced when terminal:create-session is called later.
114
- const ptySession = ptySessionManager.getSession(sessionId);
115
- if (ptySession && ptySession.dataListeners.size === 0) {
116
- debug.log('terminal', `📡 Reconnect: No dataListeners, setting up broadcast listener for session: ${sessionId}`);
117
-
118
- const broadcastListener = (output: string) => {
119
- const currentSeq = ptySessionManager.getSession(sessionId)?.outputSeq || 0;
120
- ws.emit.project(projectId, 'terminal:output', {
121
- sessionId,
122
- content: output,
123
- seq: currentSeq,
124
- projectId,
125
- timestamp: new Date().toISOString()
126
- });
127
- };
128
- ptySession.dataListeners.add(broadcastListener);
129
- }
130
- // No polling needed - dataListener handles ongoing output via ws.emit.project()
131
- } else {
132
- // Stream is not active, broadcast exit event (frontend filters by sessionId)
133
- ws.emit.project(projectId, 'terminal:exit', {
134
- sessionId,
135
- exitCode: 0
136
- });
137
- }
138
- } catch (error) {
139
- debug.error('terminal', 'Error in stream reconnect:', error);
140
- ws.emit.project(projectId, 'terminal:error', {
141
- sessionId,
142
- error: error instanceof Error ? error.message : 'Unknown error'
143
- });
144
- }
145
- })