-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathspawn-cloud-agent-session.ts
More file actions
299 lines (266 loc) · 10.7 KB
/
spawn-cloud-agent-session.ts
File metadata and controls
299 lines (266 loc) · 10.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
import {
createCloudAgentNextClient,
type AgentMode,
type PrepareSessionInput,
} from '@/lib/cloud-agent-next/cloud-agent-client';
import type { RunSessionInput } from '@/lib/cloud-agent-next/run-session';
import {
getGitHubTokenForOrganization,
getGitHubTokenForUser,
} from '@/lib/cloud-agent/github-integration-helpers';
import {
getGitLabTokenForOrganization,
getGitLabTokenForUser,
getGitLabInstanceUrlForOrganization,
getGitLabInstanceUrlForUser,
buildGitLabCloneUrl,
} from '@/lib/cloud-agent/gitlab-integration-helpers';
import type { CloudAgentAttachments } from '@/lib/cloud-agent/constants';
import { APP_URL } from '@/lib/constants';
import { CALLBACK_TOKEN_SECRET } from '@/lib/config.server';
import { parseBotCallbackStep } from '@/lib/bot/step-budget';
import { resolveBotSessionProfile } from '@/lib/bot/tools/resolve-bot-session-profile';
import { ownerFromIntegration } from '@/lib/integrations/core/owner';
import type { Owner } from '@/lib/integrations/core/types';
import {
profileMcpServersToClientRecord,
type MergeProfileConfigurationResult,
} from '@kilocode/cloud-agent-profile';
import { createHmac } from 'crypto';
import { captureException } from '@sentry/nextjs';
import type { PlatformIntegration } from '@kilocode/db';
import z from 'zod';
const SEPARATE_PULL_REQUEST_STRATEGY_INSTRUCTION = `
---
**Required GitHub PR strategy:**
The user explicitly requested a separate new PR. You must create a fresh branch from the original PR's base branch, open a separate new GitHub PR targeting that same base branch, and must not push to or modify the current PR's head branch.`;
const CURRENT_PULL_REQUEST_BRANCH_STRATEGY_INSTRUCTION = `
---
**Required GitHub PR strategy:**
Work on the current PR head branch for this task and do not open a separate GitHub PR.`;
/**
* Derive a per-request callback token so the dedicated callback HMAC secret
* is never stored in session metadata (which is visible via getSession).
*/
function deriveBotCallbackToken(botRequestId: string): string {
return createHmac('sha256', CALLBACK_TOKEN_SECRET)
.update(`bot-callback:${botRequestId}`)
.digest('hex');
}
function buildBotCallbackUrl(botRequestId: string, currentStep: number | undefined): string {
const url = new URL(`/api/internal/bot-session-callback/${botRequestId}`, APP_URL);
url.searchParams.set('currentStep', String(parseBotCallbackStep(String(currentStep ?? 0))));
return url.toString();
}
/**
* Result from spawning a Cloud Agent session
*/
type SpawnCloudAgentResult = {
response: string;
cloudAgentSessionId?: string;
kiloSessionId?: string;
};
// Structured as a single object (not z.union) so the JSON schema has a top-level
// "type": "object", which Anthropic's tool API requires.
export const spawnCloudAgentInputSchema = z.object({
githubRepo: z
.string()
.regex(/^[-a-zA-Z0-9_.]+\/[-a-zA-Z0-9_.]+$/)
.describe('The GitHub repository in owner/repo format (e.g., "facebook/react")')
.optional(),
githubPullRequestStrategy: z
.enum(['current_pr_branch', 'separate_pull_request'])
.describe(
'For GitHub PR or review-thread work only. Select "separate_pull_request" when the user asks for a new, fresh, separate, or different PR. Select "current_pr_branch" when the user wants the current PR updated or does not ask for a separate PR.'
)
.optional(),
gitlabProject: z
.string()
.regex(/^[-a-zA-Z0-9_.]+(?:\/[-a-zA-Z0-9_.]+)+$/)
.describe(
'The GitLab project path in group/project format (e.g., "mygroup/myproject"). May include nested groups (e.g., "group/subgroup/project").'
)
.optional(),
prompt: z
.string()
.describe(
'The task description for the Cloud Agent. Be specific about what changes or analysis you want. Cloud Agent does not see bot-only GitHub PR/review-thread context unless you include it here. For GitHub PR or review-thread work, include the PR URL or number, relevant review-thread/comment details, and the chosen current-PR or separate-PR strategy.'
),
mode: z
.enum(['code', 'ask'])
.describe(
'The agent mode: "code" for making changes, "ask" for questions and explanations about existing code. When using "code", decide based on the conversation context whether the agent should create a new PR/MR or push to an existing one, and include that instruction in the prompt.'
),
});
type SpawnCloudAgentInput = z.infer<typeof spawnCloudAgentInputSchema>;
/**
* Spawn a Cloud Agent session and collect the results.
* Supports both GitHub (githubRepo) and GitLab (gitlabProject) repositories.
* Delegates to the shared runSessionToCompletion helper.
*/
export default async function spawnCloudAgentSession(
args: SpawnCloudAgentInput,
model: string,
platformIntegration: PlatformIntegration,
authToken: string,
ticketUserId: string,
botRequestId: string,
onSessionReady?: RunSessionInput['onSessionReady'],
options?: {
prSignature?: string;
chatPlatform?: string;
currentStep?: number;
attachments?: CloudAgentAttachments;
}
): Promise<SpawnCloudAgentResult> {
console.log('[KiloBot] spawnCloudAgentSession called with args:', JSON.stringify(args, null, 2));
if (!CALLBACK_TOKEN_SECRET) {
const error = new Error(
'CALLBACK_TOKEN_SECRET missing - bot callbacks would be silently dropped'
);
captureException(error, {
tags: { component: 'kilo-bot', op: 'spawn-cloud-agent-session' },
extra: { botRequestId },
});
throw error;
}
// Build platform-specific prepare input
let prepareInput: PrepareSessionInput;
const mode: AgentMode = args.mode;
const chatPlatform = options?.chatPlatform ?? 'slack';
const callbackTarget = {
url: buildBotCallbackUrl(botRequestId, options?.currentStep),
headers: { 'X-Bot-Callback-Token': deriveBotCallbackToken(botRequestId) },
};
if (!args.githubRepo && !args.gitlabProject) {
return { response: 'Error: You must specify either a githubRepo or a gitlabProject.' };
}
let prompt = args.prompt;
if (args.githubPullRequestStrategy === 'separate_pull_request' && args.githubRepo) {
prompt += SEPARATE_PULL_REQUEST_STRATEGY_INSTRUCTION;
} else if (args.githubPullRequestStrategy === 'current_pr_branch' && args.githubRepo) {
prompt += CURRENT_PULL_REQUEST_BRANCH_STRATEGY_INSTRUCTION;
}
// Append PR/MR signature to the prompt if available
if (options?.prSignature) {
prompt += options.prSignature;
}
const owner: Owner = ownerFromIntegration(platformIntegration);
let profileConfig: MergeProfileConfigurationResult;
try {
profileConfig = await resolveBotSessionProfile(owner, ticketUserId, args);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { response: `Error resolving profile for Cloud Agent: ${message}` };
}
const kilocodeOrganizationId = owner.type === 'org' ? owner.id : undefined;
if (args.gitlabProject) {
// GitLab path: get token + instance URL, build clone URL, use gitUrl/gitToken
const gitlabToken =
owner.type === 'org'
? await getGitLabTokenForOrganization(owner.id)
: await getGitLabTokenForUser(owner.id);
if (!gitlabToken) {
return {
response:
'Error: No GitLab token available. Please ensure a GitLab integration is connected in your Kilo Code settings.',
};
}
const instanceUrl =
owner.type === 'org'
? await getGitLabInstanceUrlForOrganization(owner.id)
: await getGitLabInstanceUrlForUser(owner.id);
const gitUrl = buildGitLabCloneUrl(args.gitlabProject, instanceUrl);
const isSelfHosted = !/^https?:\/\/(www\.)?gitlab\.com(\/|$)/i.test(instanceUrl);
console.log(
'[KiloBot] GitLab session - project:',
args.gitlabProject,
'instance:',
isSelfHosted ? 'self-hosted' : 'gitlab.com'
);
prepareInput = {
prompt,
mode,
model,
gitUrl,
gitToken: gitlabToken,
platform: 'gitlab',
kilocodeOrganizationId,
createdOnPlatform: chatPlatform,
callbackTarget,
attachments: options?.attachments,
envVars: profileConfig.envVars,
encryptedSecrets: profileConfig.encryptedSecrets,
setupCommands: profileConfig.setupCommands,
mcpServers: profileMcpServersToClientRecord(profileConfig.mcpServers),
runtimeSkills: profileConfig.skills,
runtimeAgents: profileConfig.agents,
};
} else {
// GitHub path: get token, use githubRepo/githubToken
const githubToken =
owner.type === 'org'
? await getGitHubTokenForOrganization(owner.id)
: await getGitHubTokenForUser(owner.id);
if (!githubToken) {
return {
response:
'Error: No GitHub token available. Please ensure a GitHub integration is connected in your Kilo Code settings.',
};
}
prepareInput = {
githubRepo: args.githubRepo,
prompt,
mode,
model,
githubToken,
kilocodeOrganizationId,
createdOnPlatform: chatPlatform,
callbackTarget,
attachments: options?.attachments,
envVars: profileConfig.envVars,
encryptedSecrets: profileConfig.encryptedSecrets,
setupCommands: profileConfig.setupCommands,
mcpServers: profileMcpServersToClientRecord(profileConfig.mcpServers),
runtimeSkills: profileConfig.skills,
runtimeAgents: profileConfig.agents,
};
}
const client = createCloudAgentNextClient(authToken, { skipBalanceCheck: true });
let cloudAgentSessionId: string;
let kiloSessionId: string;
try {
const prepared = await client.prepareSession(prepareInput);
cloudAgentSessionId = prepared.cloudAgentSessionId;
kiloSessionId = prepared.kiloSessionId;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { response: `Error preparing Cloud Agent: ${message}` };
}
try {
await client.initiateFromPreparedSession({
cloudAgentSessionId,
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
response: `Error initiating Cloud Agent: ${message}`,
cloudAgentSessionId,
kiloSessionId,
};
}
try {
onSessionReady?.({ cloudAgentSessionId, kiloSessionId });
} catch (error) {
console.error('[KiloBot] onSessionReady callback error:', error);
captureException(error, {
tags: { component: 'kilo-bot', op: 'onSessionReady' },
extra: { cloudAgentSessionId, kiloSessionId },
});
}
const response =
mode === 'code'
? 'Cloud Agent session started. I will post the final result back in this thread when it completes.'
: 'Cloud Agent session started. I will post the final response back in this thread when it completes.';
return { response, cloudAgentSessionId, kiloSessionId };
}