-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathws-server.ts
More file actions
810 lines (721 loc) · 26.7 KB
/
ws-server.ts
File metadata and controls
810 lines (721 loc) · 26.7 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
/**
* Copyright 2025 GoodRx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import 'module-alias/register';
import { join } from 'path';
import moduleAlias from 'module-alias';
// Register path aliases
moduleAlias.addAliases({
shared: join(__dirname, 'src/shared'),
server: join(__dirname, 'src/server'),
root: join(__dirname, '.'),
src: join(__dirname, 'src'),
scripts: join(__dirname, 'scripts'),
});
import { createServer, IncomingMessage, ServerResponse, request as httpRequest } from 'http';
import type { Socket } from 'net';
import { parse, URL } from 'url';
import next from 'next';
import { WebSocketServer, WebSocket } from 'ws';
import { rootLogger } from './src/server/lib/logger';
import { streamK8sLogs, AbortHandle } from './src/server/lib/k8sStreamer';
import {
buildWorkspaceEditorProxyHeaders,
serializeSocketHttpResponse,
} from './src/server/lib/agentSession/workspaceEditorProxy';
const dev = process.env.NODE_ENV !== 'production';
const hostname = process.env.HOSTNAME || 'localhost';
const port = parseInt(process.env.PORT || '3000', 10);
// --- Initialize Next.js App ---
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
const LOG_STREAM_PATH = '/api/logs/stream'; // Path for WebSocket connections
const SESSION_WORKSPACE_EDITOR_PATH_PREFIX = '/api/agent-session/workspace-editor/';
const SESSION_WORKSPACE_EDITOR_COOKIE_NAME = 'lfc_session_workspace_editor_auth';
const SESSION_WORKSPACE_EDITOR_PORT = parseInt(process.env.AGENT_SESSION_WORKSPACE_EDITOR_PORT || '13337', 10);
const logger = rootLogger.child({ filename: __filename });
const HOP_BY_HOP_HEADERS = new Set([
'connection',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'te',
'trailer',
'transfer-encoding',
'upgrade',
]);
function parseCookieHeader(cookieHeader: string | string[] | undefined): Record<string, string> {
if (!cookieHeader) {
return {};
}
const raw = Array.isArray(cookieHeader) ? cookieHeader.join(';') : cookieHeader;
return raw.split(';').reduce<Record<string, string>>((cookies, entry) => {
const separatorIndex = entry.indexOf('=');
if (separatorIndex < 0) {
return cookies;
}
const key = entry.slice(0, separatorIndex).trim();
const value = entry.slice(separatorIndex + 1).trim();
if (!key) {
return cookies;
}
cookies[key] = decodeURIComponent(value);
return cookies;
}, {});
}
type SessionWorkspaceEditorPathMatch = { sessionId: string; forwardPath: string };
function parseSessionWorkspaceEditorPath(pathname: string | null | undefined): SessionWorkspaceEditorPathMatch | null {
const safePathname = pathname || '';
if (safePathname.startsWith(SESSION_WORKSPACE_EDITOR_PATH_PREFIX)) {
const remainder = safePathname.slice(SESSION_WORKSPACE_EDITOR_PATH_PREFIX.length);
const slashIndex = remainder.indexOf('/');
const sessionId = slashIndex >= 0 ? remainder.slice(0, slashIndex) : remainder;
if (!sessionId) {
return null;
}
const forwardPath = slashIndex >= 0 ? remainder.slice(slashIndex) : '/';
return {
sessionId: decodeURIComponent(sessionId),
forwardPath: forwardPath || '/',
};
}
return null;
}
function getSessionWorkspaceEditorCookiePath(sessionId: string): string {
return `${SESSION_WORKSPACE_EDITOR_PATH_PREFIX}${encodeURIComponent(sessionId)}`;
}
function isSendableCloseCode(code?: number): code is number {
if (typeof code !== 'number') {
return false;
}
if (code < 1000 || code >= 5000) {
return false;
}
return ![1004, 1005, 1006, 1015].includes(code);
}
function buildSessionWorkspaceEditorCookie(request: IncomingMessage, sessionId: string, token: string): string {
const isSecure =
request.headers['x-forwarded-proto'] === 'https' || (request.socket as { encrypted?: boolean }).encrypted === true;
const cookieParts = [
`${SESSION_WORKSPACE_EDITOR_COOKIE_NAME}=${encodeURIComponent(token)}`,
`Path=${getSessionWorkspaceEditorCookiePath(sessionId)}`,
'HttpOnly',
'SameSite=Lax',
];
if (isSecure) {
cookieParts.push('Secure');
}
return cookieParts.join('; ');
}
function appendSetCookie(res: ServerResponse, value: string) {
const existing = res.getHeader('Set-Cookie');
if (!existing) {
res.setHeader('Set-Cookie', value);
return;
}
if (Array.isArray(existing)) {
res.setHeader('Set-Cookie', [...existing, value]);
return;
}
res.setHeader('Set-Cookie', [existing.toString(), value]);
}
function buildSessionWorkspaceEditorServiceUrl(
session: { id: string; podName: string; namespace: string },
forwardPath: string,
query: Record<string, string | string[] | undefined>,
isWebSocket = false
) {
const protocol = isWebSocket ? 'ws' : 'http';
const target = new URL(
`${protocol}://${session.podName}.${session.namespace}.svc.cluster.local:${SESSION_WORKSPACE_EDITOR_PORT}${forwardPath}`
);
for (const [key, value] of Object.entries(query)) {
if (key === 'token' || value == null) {
continue;
}
if (Array.isArray(value)) {
value.forEach((item) => target.searchParams.append(key, item));
continue;
}
target.searchParams.set(key, value);
}
return target;
}
function buildProxyHeaders(request: IncomingMessage, target: URL, forwardedPrefix: string): Record<string, string> {
return buildWorkspaceEditorProxyHeaders({
requestHeaders: request.headers,
targetHost: target.host,
forwardedHost: request.headers.host || target.host,
forwardedProto:
(typeof request.headers['x-forwarded-proto'] === 'string' && request.headers['x-forwarded-proto']) ||
((request.socket as { encrypted?: boolean }).encrypted ? 'https' : 'http'),
forwardedPrefix,
remoteAddress: request.socket.remoteAddress,
});
}
function resolveSessionWorkspaceEditorErrorStatus(error: unknown): number {
const message = error instanceof Error ? error.message : String(error);
if (message === 'Authentication token is required') {
return 401;
}
if (message === 'Forbidden: you do not own this session') {
return 403;
}
if (message === 'Session not found or not active') {
return 404;
}
return 502;
}
async function handleSessionWorkspaceEditorUpgrade(request: IncomingMessage, socket: Socket, head: Buffer) {
const parsedUrl = parse(request.url || '', true);
const match = parseSessionWorkspaceEditorPath(parsedUrl.pathname);
const editorLogCtx: Record<string, unknown> = {
remoteAddress: request.socket.remoteAddress,
path: parsedUrl.pathname,
};
if (!match) {
socket.end(
serializeSocketHttpResponse({ statusCode: 400, statusMessage: 'Bad Request', body: 'Invalid editor path' })
);
return;
}
let upstreamSocket: Socket | null = null;
let proxyReq: ReturnType<typeof httpRequest> | null = null;
try {
const queryToken = typeof parsedUrl.query.token === 'string' ? parsedUrl.query.token : null;
const session = await resolveOwnedAgentSession(request, match.sessionId, queryToken);
const forwardedPrefix = getSessionWorkspaceEditorCookiePath(match.sessionId);
const targetUrl = buildSessionWorkspaceEditorServiceUrl(
session,
match.forwardPath,
parsedUrl.query as Record<string, string | string[] | undefined>
);
const proxyHeaders = buildWorkspaceEditorProxyHeaders({
requestHeaders: request.headers,
targetHost: targetUrl.host,
forwardedHost: request.headers.host || targetUrl.host,
forwardedProto:
(typeof request.headers['x-forwarded-proto'] === 'string' && request.headers['x-forwarded-proto']) ||
((request.socket as { encrypted?: boolean }).encrypted ? 'https' : 'http'),
forwardedPrefix,
remoteAddress: request.socket.remoteAddress,
includeUpgradeHeaders: true,
});
await new Promise<void>((resolve, reject) => {
proxyReq = httpRequest(targetUrl, {
method: request.method || 'GET',
headers: proxyHeaders,
});
proxyReq.on('upgrade', (upstreamRes, proxiedSocket, upstreamHead) => {
upstreamSocket = proxiedSocket as Socket;
socket.write(
serializeSocketHttpResponse({
statusCode: upstreamRes.statusCode || 101,
statusMessage: upstreamRes.statusMessage,
headers: upstreamRes.headers,
})
);
if (upstreamHead.length > 0) {
socket.write(upstreamHead);
}
if (head.length > 0) {
upstreamSocket.write(head);
}
socket.on('error', (error) => {
logger.warn(
{ ...editorLogCtx, error },
`SessionEditor: socket error source=client sessionId=${match.sessionId}`
);
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.destroy(error as Error);
}
});
upstreamSocket.on('error', (error) => {
logger.warn(
{ ...editorLogCtx, error },
`SessionEditor: socket error source=upstream sessionId=${match.sessionId}`
);
if (!socket.destroyed) {
socket.destroy(error as Error);
}
});
socket.on('close', () => {
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.end();
}
});
upstreamSocket.on('close', () => {
if (!socket.destroyed) {
socket.end();
}
});
socket.pipe(upstreamSocket);
upstreamSocket.pipe(socket);
socket.resume();
upstreamSocket.resume();
resolve();
});
proxyReq.on('response', (upstreamRes) => {
const chunks: Buffer[] = [];
upstreamRes.on('data', (chunk) => {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
});
upstreamRes.on('end', () => {
if (!socket.destroyed) {
socket.end(
serializeSocketHttpResponse({
statusCode: upstreamRes.statusCode || 502,
statusMessage: upstreamRes.statusMessage,
headers: upstreamRes.headers,
body: Buffer.concat(chunks),
})
);
}
reject(new Error(`Editor upgrade rejected with status ${upstreamRes.statusCode || 502}`));
});
});
proxyReq.on('error', reject);
proxyReq.end();
});
} catch (error: any) {
logger.error(
{ ...editorLogCtx, error, sessionId: match.sessionId },
`SessionEditor: websocket setup failed sessionId=${match.sessionId}`
);
if (proxyReq) {
proxyReq.destroy();
}
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.destroy();
}
if (!socket.destroyed) {
socket.end(
serializeSocketHttpResponse({
statusCode: resolveSessionWorkspaceEditorErrorStatus(error),
statusMessage: 'Bad Gateway',
body: error instanceof Error ? error.message : String(error),
})
);
}
}
}
async function resolveOwnedAgentSession(
request: IncomingMessage,
sessionId: string,
queryToken?: string | null
): Promise<any> {
const AgentSessionService = (await import('./src/server/services/agentSession')).default;
const session = await AgentSessionService.getSession(sessionId);
if (!session || session.status !== 'active') {
throw new Error('Session not found or not active');
}
if (process.env.ENABLE_AUTH === 'true') {
const headerToken = request.headers.authorization?.split(' ')[1];
const cookieToken = parseCookieHeader(request.headers.cookie)[SESSION_WORKSPACE_EDITOR_COOKIE_NAME];
const rawToken = headerToken || cookieToken || queryToken;
if (!rawToken) {
throw new Error('Authentication token is required');
}
const { verifyBearerToken } = await import('./src/server/lib/auth');
const authResult = await verifyBearerToken(rawToken);
if (!authResult.success || authResult.payload?.sub !== session.userId) {
throw new Error('Forbidden: you do not own this session');
}
}
return session;
}
function closeSocket(ws: WebSocket, code: number, reason: string) {
if (ws.readyState !== WebSocket.OPEN && ws.readyState !== WebSocket.CONNECTING) {
return;
}
const safeReason = Buffer.byteLength(reason, 'utf8') > 123 ? 'Connection error' : reason;
if (isSendableCloseCode(code)) {
ws.close(code, safeReason);
return;
}
ws.close(1000, safeReason);
}
async function handleSessionWorkspaceEditorHttp(
req: IncomingMessage,
res: ServerResponse,
pathname: string,
query: Record<string, string | string[] | undefined>
) {
const match = parseSessionWorkspaceEditorPath(pathname);
if (!match) {
return false;
}
try {
const queryToken = typeof query.token === 'string' ? query.token : null;
const session = await resolveOwnedAgentSession(req, match.sessionId, queryToken);
const forwardedPrefix = getSessionWorkspaceEditorCookiePath(match.sessionId);
const targetUrl = buildSessionWorkspaceEditorServiceUrl(session, match.forwardPath, query);
const proxyHeaders = buildProxyHeaders(req, targetUrl, forwardedPrefix);
await new Promise<void>((resolve, reject) => {
const proxyReq = httpRequest(
targetUrl,
{
method: req.method,
headers: proxyHeaders,
},
(proxyRes) => {
res.statusCode = proxyRes.statusCode || 502;
Object.entries(proxyRes.headers).forEach(([key, value]) => {
const normalizedKey = key.toLowerCase();
if (HOP_BY_HOP_HEADERS.has(normalizedKey) || value == null || normalizedKey === 'set-cookie') {
return;
}
res.setHeader(key, Array.isArray(value) ? value : value.toString());
});
const upstreamSetCookies = proxyRes.headers['set-cookie'] || [];
(Array.isArray(upstreamSetCookies) ? upstreamSetCookies : [upstreamSetCookies]).forEach((cookie) => {
if (cookie) {
appendSetCookie(res, cookie);
}
});
if (process.env.ENABLE_AUTH === 'true' && queryToken) {
appendSetCookie(res, buildSessionWorkspaceEditorCookie(req, match.sessionId, queryToken));
}
proxyRes.on('error', reject);
proxyRes.on('end', () => resolve());
proxyRes.pipe(res);
}
);
proxyReq.on('error', reject);
if (req.method && !['GET', 'HEAD'].includes(req.method.toUpperCase())) {
req.pipe(proxyReq);
} else {
proxyReq.end();
}
});
return true;
} catch (error: any) {
logger.error(
{ error, path: pathname, sessionId: match.sessionId },
`SessionEditor: proxy failed sessionId=${match.sessionId} path=${pathname}`
);
res.statusCode =
error?.message?.includes('Forbidden') || error?.message?.includes('Authentication')
? 401
: error?.message?.includes('Session not found')
? 404
: 502;
res.end(error?.message || 'Editor proxy failed');
return true;
}
}
app.prepare().then(() => {
const httpServer = createServer(async (req: IncomingMessage, res: ServerResponse) => {
try {
const parsedUrl = parse(req.url!, true);
if (
parsedUrl.pathname &&
(await handleSessionWorkspaceEditorHttp(
req,
res,
parsedUrl.pathname,
parsedUrl.query as Record<string, string | string[] | undefined>
))
) {
return;
}
await handle(req, res, parsedUrl);
} catch (err) {
logger.error({ err }, 'Error handling HTTP request');
res.statusCode = 500;
res.end('internal server error');
}
});
const wss = new WebSocketServer({ noServer: true });
httpServer.on('upgrade', (request: IncomingMessage, socket, head) => {
const { pathname } = parse(request.url!, true);
const connectionLogCtx = { path: pathname, remoteAddress: request.socket.remoteAddress };
if (pathname === LOG_STREAM_PATH) {
logger.debug(connectionLogCtx, 'Handling upgrade request for log stream');
wss.handleUpgrade(request, socket, head, (ws: WebSocket) => {
wss.emit('connection', ws, request);
});
} else if (parseSessionWorkspaceEditorPath(pathname)) {
logger.debug(connectionLogCtx, 'WebSocket: upgrade path=session_workspace_editor');
void handleSessionWorkspaceEditorUpgrade(request, socket as Socket, head);
} else {
socket.destroy();
}
});
wss.on('connection', (ws: WebSocket, request: IncomingMessage) => {
let k8sStreamAbort: AbortHandle | null = null;
let logCtx: Record<string, any> = {
remoteAddress: request.socket.remoteAddress,
};
try {
const { query } = parse(request.url || '', true);
const {
podName,
namespace,
containerName,
follow: followStr,
tailLines: tailLinesStr,
timestamps: timestampsStr,
} = query;
logCtx = { ...logCtx, podName, namespace, containerName };
logger.debug(logCtx, 'WebSocket connection established');
if (
!podName ||
!namespace ||
!containerName ||
typeof podName !== 'string' ||
typeof namespace !== 'string' ||
typeof containerName !== 'string'
) {
throw new Error('Missing or invalid required parameters: podName, namespace, containerName');
}
const follow = followStr === 'true';
const tailLines = tailLinesStr ? parseInt(tailLinesStr as string, 10) : undefined;
const timestamps = timestampsStr === 'true';
if (tailLines !== undefined && isNaN(tailLines)) throw new Error('Invalid tailLines parameter.');
logger.debug(logCtx, 'Initiating K8s log stream');
k8sStreamAbort = streamK8sLogs(
{ podName, namespace, containerName, follow, tailLines, timestamps },
{
onData: (logLine: string) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'log', payload: logLine }));
}
},
onError: (error: Error) => {
logger.error({ ...logCtx, err: error }, 'K8s stream error');
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'error', message: `Kubernetes stream error: ${error.message}` }));
}
ws.close(1011, 'Kubernetes stream error');
},
onEnd: () => {
logger.debug(logCtx, 'K8s stream ended');
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'end', reason: 'ContainerTerminated' }));
}
ws.close(1000, 'Stream ended');
},
}
);
} catch (error: any) {
logger.error({ ...logCtx, err: error }, 'WebSocket connection setup error');
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
ws.send(JSON.stringify({ type: 'error', message: `Connection error: ${error.message}` }));
closeSocket(ws, 1008, `Connection error: ${error.message}`);
}
return;
}
ws.on('close', (code, reason) => {
const reasonString = reason instanceof Buffer ? reason.toString() : String(reason);
logger.debug({ ...logCtx, code, reason: reasonString }, 'WebSocket connection closed by client');
if (k8sStreamAbort && typeof k8sStreamAbort.abort === 'function') {
logger.debug(logCtx, 'Aborting log stream due to client close');
k8sStreamAbort.abort();
k8sStreamAbort = null;
}
});
ws.on('error', (error) => {
logger.warn({ ...logCtx, err: error }, 'WebSocket error');
if (k8sStreamAbort && typeof k8sStreamAbort.abort === 'function') {
logger.debug(logCtx, 'Aborting log stream due to WebSocket error');
k8sStreamAbort.abort();
k8sStreamAbort = null;
}
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
ws.close(1011, 'WebSocket error');
}
});
});
httpServer.listen(port);
httpServer.on('error', (error) => {
logger.error({ err: error }, 'HTTP Server Error');
process.exit(1);
});
});
/**
* @openapi
* /api/logs/stream:
* get:
* summary: Stream Kubernetes pod logs via WebSocket
* description: |
* Establishes a WebSocket connection to stream real-time logs from a
* specified Kubernetes pod container. The client must provide query
* parameters identifying the pod, namespace, and container.
*
* The endpoint returns log messages as JSON objects with a type field
* indicating the message type (log, error, or end), and additional
* fields depending on the message type.
*
* Note: This endpoint requires WebSocket protocol support.
* tags:
* - Logs
* parameters:
* - in: query
* name: podName
* required: true
* schema:
* type: string
* description: The name of the Kubernetes pod
* - in: query
* name: namespace
* required: true
* schema:
* type: string
* description: The Kubernetes namespace where the pod is located
* - in: query
* name: containerName
* required: true
* schema:
* type: string
* description: The name of the container within the pod
* - in: query
* name: follow
* required: false
* schema:
* type: boolean
* default: true
* description: Whether to follow the log stream as new logs are generated
* - in: query
* name: tailLines
* required: false
* schema:
* type: integer
* default: 200
* description: Number of lines to retrieve from the end of the logs
* - in: query
* name: timestamps
* required: false
* schema:
* type: boolean
* default: false
* description: Whether to include timestamps with each log line
* responses:
* 101:
* description: WebSocket connection established
* content:
* application/json:
* schema:
* oneOf:
* - type: object
* required:
* - type
* - payload
* properties:
* type:
* type: string
* enum: [log]
* description: Indicates this is a log message
* payload:
* type: string
* description: The content of the log line
* - type: object
* required:
* - type
* - message
* properties:
* type:
* type: string
* enum: [error]
* description: Indicates this is an error message
* message:
* type: string
* description: Error message describing what went wrong
* - type: object
* required:
* - type
* properties:
* type:
* type: string
* enum: [end]
* description: Indicates the log stream has ended
* reason:
* type: string
* description: Reason why the stream ended (e.g., 'ContainerTerminated')
* examples:
* logMessage:
* value:
* type: "log"
* payload: "2024-04-14T12:34:56.789Z INFO Starting application..."
* errorMessage:
* value:
* type: "error"
* message: "Kubernetes stream error: Connection refused"
* endMessage:
* value:
* type: "end"
* reason: "ContainerTerminated"
* 400:
* description: Bad request - missing or invalid parameters
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* example: "Missing or invalid required parameters: podName, namespace, containerName"
*/
// Usage example:
// Connect to WebSocket using wscat (substitute your host with the appropriate environment):
// wscat -c "wss://<your-host>/api/logs/stream?podName=<pod-name>&namespace=<namespace>&follow=true&tailLines=200×tamps=true&containerName=<container-name>"
//
// Example messages received from the WebSocket:
// {"type":"log","payload":"2024-04-14T12:34:56.789Z INFO Starting application..."}
// {"type":"error","message":"Kubernetes stream error: Connection refused"}
// {"type":"end","reason":"ContainerTerminated"}
/**
* @openapi
* /api/agent-session/workspace-editor/{sessionId}:
* get:
* summary: Open the workspace editor attached to an active agent session
* description: |
* Proxies a browser-based VS Code session (code-server) running inside the
* session workspace pod. The editor uses the same workspace PVC as the
* session workspace.
*
* Authentication follows the agent session ownership rules. The first
* request may include a bearer token via the
* `Authorization` header or `token` query parameter; the proxy then sets a
* session-scoped HTTP-only cookie for follow-up asset and WebSocket
* requests under the same path prefix.
*
* All nested paths under this prefix are also proxied to the editor
* runtime, including asset requests and WebSocket upgrades required by the
* web IDE.
* tags:
* - Agent Sessions
* parameters:
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* - in: query
* name: token
* required: false
* schema:
* type: string
* description: Optional bearer token used to seed the editor auth cookie.
* responses:
* '200':
* description: Browser editor HTML or proxied editor assets.
* '401':
* description: Unauthorized
* '404':
* description: Session not found
* '502':
* description: Editor runtime unavailable
*/