-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathrun-session.ts
More file actions
409 lines (369 loc) · 13.6 KB
/
run-session.ts
File metadata and controls
409 lines (369 loc) · 13.6 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
import 'server-only';
import { getEnvVariable } from '@/lib/dotenvx';
import { signStreamTicket, type StreamTicketPayload } from '@/lib/cloud-agent/stream-ticket';
import { createWebSocketManager } from './websocket-manager';
import { createEventProcessor, type ProcessedMessage } from './processor';
import type { CloudAgentEvent, StreamError } from './event-types';
import type { CloudAgentNextClient } from './cloud-agent-client';
import type { PrepareSessionInput, InitiateFromPreparedSessionInput } from './cloud-agent-client';
/**
* Server-side helper for running a cloud-agent-next session to completion.
*
* Encapsulates the full lifecycle:
* prepare → initiate → sign ticket → connect WebSocket → stream events → return result
*
* This is the server-side equivalent of the frontend useCloudAgentStream hook,
* designed for headless consumers like the Slack bot and security agent.
*/
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const CLOUD_AGENT_NEXT_WS_URL = getEnvVariable('NEXT_PUBLIC_CLOUD_AGENT_NEXT_WS_URL');
const CLOUD_AGENT_NEXT_API_URL = getEnvVariable('CLOUD_AGENT_NEXT_API_URL');
const DEFAULT_STREAM_TIMEOUT_MS = 15 * 60 * 1000; // 15 minutes
const COMPLETE_GRACE_MS = 1000; // Wait 1s after 'complete' for final events
// ---------------------------------------------------------------------------
// URL resolution
// ---------------------------------------------------------------------------
/**
* Resolve a (possibly relative) stream URL returned by initiateFromPreparedSession
* into an absolute WebSocket URL.
*
* Resolution order for the base URL:
* 1. NEXT_PUBLIC_CLOUD_AGENT_NEXT_WS_URL (preferred, purpose-built for WS)
* 2. CLOUD_AGENT_NEXT_API_URL (fallback, the tRPC API base)
*/
export function resolveStreamUrl(streamUrl: string): string {
if (!streamUrl) {
throw new Error('Cloud Agent stream URL is missing');
}
let url: URL;
if (/^(wss?|https?):\/\//i.test(streamUrl)) {
url = new URL(streamUrl);
} else {
const baseUrl = CLOUD_AGENT_NEXT_WS_URL || CLOUD_AGENT_NEXT_API_URL;
if (!baseUrl) {
throw new Error(
'Neither NEXT_PUBLIC_CLOUD_AGENT_NEXT_WS_URL nor CLOUD_AGENT_NEXT_API_URL is configured'
);
}
url = new URL(streamUrl, baseUrl);
}
// Upgrade HTTP(S) to WS(S)
if (url.protocol === 'http:') url.protocol = 'ws:';
else if (url.protocol === 'https:') url.protocol = 'wss:';
return url.toString();
}
// ---------------------------------------------------------------------------
// Text extraction
// ---------------------------------------------------------------------------
type MessagePart = ProcessedMessage['parts'][number];
type TextMessagePart = Extract<MessagePart, { type: 'text' }>;
function isTextPart(part: MessagePart): part is TextMessagePart {
return part.type === 'text';
}
/**
* Extract concatenated text content from a completed message's parts.
*/
export function extractTextFromMessage(message: ProcessedMessage): string {
return message.parts
.filter(isTextPart)
.map(part => part.text ?? '')
.join('')
.trim();
}
// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------
/** Input for runSessionToCompletion */
export type RunSessionInput = {
/** An already-constructed CloudAgentNextClient (caller owns auth / balance-check config). */
client: CloudAgentNextClient;
/** Fields forwarded to prepareSession. */
prepareInput: PrepareSessionInput;
/** Partial override for initiateFromPreparedSession (e.g. kilocodeOrganizationId). */
initiateInput?: Omit<InitiateFromPreparedSessionInput, 'cloudAgentSessionId'>;
/** Payload fields for signing the WebSocket stream ticket. */
ticketPayload: Pick<StreamTicketPayload, 'userId' | 'organizationId'>;
/** Stream timeout in ms (default: 15 minutes). */
streamTimeoutMs?: number;
/** Optional log prefix for console messages (e.g. '[SlackBot]'). */
logPrefix?: string;
/**
* Called once, right after the session has been prepared and initiated
* (i.e. the cloud agent is running). Useful for posting early user
* feedback such as an ephemeral "View Session" link before the session
* completes. Errors thrown by this callback are logged but do not abort
* the session.
*/
onSessionReady?: (info: { cloudAgentSessionId: string; kiloSessionId: string }) => void;
};
/** Result from runSessionToCompletion */
export type RunSessionResult = {
/** The final text response extracted from the assistant's completed message(s). */
response: string;
/** The cloud-agent session ID (available even on failure). */
sessionId?: string;
/** Whether the session encountered a fatal error (stream/WS/session-level). */
hasError: boolean;
/** Whether stderr output was observed (informational; does NOT imply failure). */
hasStderr: boolean;
/** Collected status/error messages for diagnostics. */
statusMessages: string[];
};
// ---------------------------------------------------------------------------
// Main entry point
// ---------------------------------------------------------------------------
/**
* Run a cloud-agent-next session to completion, returning the final text result.
*
* Steps:
* 1. prepareSession → cloudAgentSessionId + kiloSessionId
* 2. initiateFromPrepared → streamUrl
* 3. resolveStreamUrl → absolute wss:// URL
* 4. signStreamTicket → short-lived JWT for WebSocket auth
* 5. EventProcessor + WebSocketManager → stream events until idle/complete/error
* 6. Return aggregated text result
*/
export async function runSessionToCompletion(input: RunSessionInput): Promise<RunSessionResult> {
const {
client,
prepareInput,
initiateInput,
ticketPayload,
logPrefix = '[CloudAgentNext]',
onSessionReady,
} = input;
const streamTimeoutMs = input.streamTimeoutMs ?? DEFAULT_STREAM_TIMEOUT_MS;
const statusMessages: string[] = [];
let completionResult: string | undefined;
let sessionId: string | undefined;
let kiloSessionId: string | undefined;
let hasError = false;
let hasStderr = false;
let errorMessage: string | undefined;
// 1. Prepare
try {
const prepared = await client.prepareSession(prepareInput);
sessionId = prepared.cloudAgentSessionId;
kiloSessionId = prepared.kiloSessionId;
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
console.error(`${logPrefix} Error preparing session:`, msg, error);
return {
response: `Error preparing Cloud Agent: ${msg}`,
sessionId,
hasError: true,
hasStderr: false,
statusMessages,
};
}
if (!sessionId || !kiloSessionId) {
const msg = 'Session preparation did not return session IDs.';
console.error(`${logPrefix} ${msg}`);
return { response: msg, sessionId, hasError: true, hasStderr: false, statusMessages };
}
// 2. Initiate
let streamUrl: string;
try {
const initiated = await client.initiateFromPreparedSession({
cloudAgentSessionId: sessionId,
...initiateInput,
});
streamUrl = initiated.streamUrl;
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
console.error(`${logPrefix} Error initiating session:`, msg, error);
return {
response: `Error initiating Cloud Agent: ${msg}`,
sessionId,
hasError: true,
hasStderr: false,
statusMessages,
};
}
// Notify caller that the session is live (fire-and-forget)
try {
onSessionReady?.({ cloudAgentSessionId: sessionId, kiloSessionId });
} catch (error) {
console.error(`${logPrefix} onSessionReady callback error:`, error);
}
// 3. Resolve URL
let wsUrl: string;
try {
wsUrl = resolveStreamUrl(streamUrl);
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
console.error(`${logPrefix} Error resolving stream URL:`, msg, error);
return {
response: `Error resolving stream URL: ${msg}`,
sessionId,
hasError: true,
hasStderr: false,
statusMessages,
};
}
// 4. Sign ticket
const ticketFields: StreamTicketPayload = {
userId: ticketPayload.userId,
kiloSessionId,
cloudAgentSessionId: sessionId,
organizationId: ticketPayload.organizationId,
};
const { ticket } = signStreamTicket(ticketFields);
// 5. Wire up EventProcessor + WebSocketManager
let resolveStream: (() => void) | undefined;
let completeGraceTimeoutId: ReturnType<typeof setTimeout> | undefined;
let streamCompleted = false;
const streamTimeoutRef: { id?: ReturnType<typeof setTimeout> } = {};
const resolveOnce = () => {
if (streamCompleted) return;
streamCompleted = true;
if (streamTimeoutRef.id) clearTimeout(streamTimeoutRef.id);
if (completeGraceTimeoutId) clearTimeout(completeGraceTimeoutId);
resolveStream?.();
};
const processor = createEventProcessor({
callbacks: {
onMessageCompleted: (_sid, _mid, message) => {
if (message.info.role !== 'assistant') return;
const text = extractTextFromMessage(message);
if (text) completionResult = text;
if (message.info.error) {
const errData = message.info.error as { data?: { message?: string } };
hasError = true;
errorMessage = errData?.data?.message ?? 'Assistant message failed.';
}
},
onSessionStatusChanged: status => {
if (status.type === 'idle') resolveOnce();
},
onError: error => {
hasError = true;
errorMessage = error;
resolveOnce();
},
},
});
const streamDone = new Promise<void>(resolve => {
resolveStream = resolve;
});
const scheduleCompleteGrace = () => {
if (completeGraceTimeoutId) return;
completeGraceTimeoutId = setTimeout(resolveOnce, COMPLETE_GRACE_MS);
};
const wsManager = createWebSocketManager({
url: wsUrl,
ticket,
onEvent: (event: CloudAgentEvent) => {
processor.processEvent(event);
switch (event.streamEventType) {
case 'complete': {
const data = event.data as { exitCode?: number; metadata?: { executionTimeMs?: number } };
statusMessages.push(
`Session completed${data?.metadata?.executionTimeMs !== undefined ? ` in ${data.metadata.executionTimeMs}ms` : ''} with exit code ${data?.exitCode ?? 'unknown'}`
);
scheduleCompleteGrace();
break;
}
case 'error': {
const data = event.data as { error?: string };
const text = data?.error ?? 'Cloud Agent error';
statusMessages.push(`Error: ${text}`);
hasError = true;
errorMessage = text;
resolveOnce();
break;
}
case 'interrupted': {
const data = event.data as { reason?: string };
const reason = data?.reason ?? 'Session interrupted';
statusMessages.push(`Session interrupted: ${reason}`);
hasError = true;
errorMessage = reason;
resolveOnce();
break;
}
case 'output': {
const data = event.data as { source?: string; content?: string };
if (data?.source === 'stderr') {
statusMessages.push(`[stderr] ${data.content ?? ''}`.trim());
hasStderr = true;
}
break;
}
case 'status': {
const data = event.data as { message?: string };
if (data?.message) statusMessages.push(data.message);
break;
}
}
},
onStateChange: state => {
if (state.status === 'error') {
hasError = true;
errorMessage = state.error;
resolveOnce();
}
if (state.status === 'disconnected') {
resolveOnce();
}
},
onError: (error: StreamError) => {
hasError = true;
errorMessage = `${error.code}: ${error.message}`;
resolveOnce();
},
onRefreshTicket: async () => {
const refreshed = signStreamTicket(ticketFields);
return refreshed.ticket;
},
});
// 6. Stream
console.log(`${logPrefix} Connecting to stream for session ${sessionId}...`);
wsManager.connect();
streamTimeoutRef.id = setTimeout(() => {
hasError = true;
errorMessage = `Stream timed out after ${streamTimeoutMs}ms`;
resolveOnce();
}, streamTimeoutMs);
await streamDone;
wsManager.disconnect();
console.log(
`${logPrefix} Stream completed. statusMessages=${statusMessages.length}, hasResult=${!!completionResult}`
);
// 7. Build result
//
// When the assistant produced a completionResult (e.g. containing a PR/MR
// URL), prefer returning it even if a fatal error also occurred — losing the
// PR link is the worse outcome for users.
if (hasError) {
const details = [errorMessage, ...statusMessages].filter(Boolean).join('\n');
const errorSummary = `Cloud Agent session ${sessionId} encountered errors:\n${details}`;
return {
response: completionResult
? `${errorSummary}\n\nHowever, the agent produced this output:\n\n${completionResult}`
: errorSummary,
sessionId,
hasError: true,
hasStderr,
statusMessages,
};
}
if (completionResult) {
return {
response: `Cloud Agent session ${sessionId} completed:\n\n${completionResult}`,
sessionId,
hasError: false,
hasStderr,
statusMessages,
};
}
return {
response: `Cloud Agent session ${sessionId} completed successfully.\n\nStatus:\n${statusMessages.slice(-5).join('\n')}`,
sessionId,
hasError: false,
hasStderr,
statusMessages,
};
}