-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsession-service.ts
More file actions
2301 lines (2097 loc) · 73.3 KB
/
Copy pathsession-service.ts
File metadata and controls
2301 lines (2097 loc) · 73.3 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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { dirname } from 'node:path';
import type {
ExecutionSession,
SandboxInstance,
SandboxId,
SessionContext,
SessionId,
InterruptResult,
} from './types.js';
import type { ExecutionParams as _ExecutionParams } from './schema.js';
import { generateSandboxId } from './sandbox-id.js';
import { normalizeKilocodeModel } from './persistence/model-utils.js';
import {
checkDiskAndCleanBeforeSetup,
cloneGitHubRepo,
cloneGitRepo,
cleanupWorkspace,
getSessionHomePath,
getSessionWorkspacePath,
GIT_COMMAND_TIMEOUT_MS,
manageBranch,
restoreWorkspace,
setupWorkspace,
} from './workspace.js';
import { logger, WithLogTags } from './logger.js';
import { timedExec } from './sandbox-timeout-logging.js';
import type {
PersistenceEnv,
CloudAgentSessionState,
MCPServerConfig,
RuntimeSkill,
RuntimeAgent,
} from './persistence/types.js';
import { MetadataSchema } from './persistence/schemas.js';
import { withDORetry } from './utils/do-retry.js';
import { decryptWithPrivateKey, mergeEnvVarsWithSecrets } from './utils/encryption.js';
import type { MCPSecretValue } from './router/schemas.js';
import type { SessionProfileBundle } from './session-profile.js';
import { readProfileBundle } from './session-profile.js';
import { destroySandboxAfterInternalServerError } from './sandbox-recovery.js';
const SETUP_COMMAND_TIMEOUT_SECONDS = 300; // 5 minutes
const SANDBOX_RETRY_DEFAULTS = {
maxAttempts: 3,
baseBackoffMs: 100,
maxBackoffMs: 5000,
};
const DEFAULT_DENIED_COMMAND_PATTERNS = ['rm -rf', 'sudo rm', 'mkfs', 'dd if='];
// Keep in sync with: cloud-agent/src/workspace.ts, cloudflare-code-review-infra/src/code-review-orchestrator.ts
// mkdir and touch are intentionally allowed for agent scratch space during analysis
const CODE_REVIEW_ALLOWED_COMMANDS = [
'ls',
'cat',
'echo',
'pwd',
'find',
'grep',
'git',
'gh',
'whoami',
'date',
'head',
'tail',
'cd',
'mkdir',
'touch',
];
const CODE_REVIEW_DENIED_COMMAND_PATTERNS = [
'git add',
'git commit',
'git push',
'git merge',
'git rebase',
'git cherry-pick',
'git reset',
'git checkout',
'git switch',
'git stash',
'git tag',
'git am',
'git apply',
'git remote set-url',
'gh pr merge',
'gh pr review',
'gh pr create',
'gh pr close',
'gh pr edit',
'gh issue',
'gh repo create',
'gh repo fork',
'npm test',
'pnpm test',
'bun test',
'yarn test',
'pytest',
'vitest',
];
type CommandGuardPolicy = {
policyName: string;
allowed: string[];
denied: string[];
};
function getCommandGuardPolicy(createdOnPlatform?: string): CommandGuardPolicy | null {
if (createdOnPlatform !== 'code-review') {
return null;
}
return {
policyName: 'code-review-read-only',
allowed: CODE_REVIEW_ALLOWED_COMMANDS,
denied: [...DEFAULT_DENIED_COMMAND_PATTERNS, ...CODE_REVIEW_DENIED_COMMAND_PATTERNS],
};
}
class SessionSnapshotRestoreError extends Error {
constructor(
message: string,
public readonly status?: number
) {
super(message);
this.name = 'SessionSnapshotRestoreError';
}
}
export function determineBranchName(sessionId: string, upstreamBranch?: string): string {
return upstreamBranch ?? `session/${sessionId}`;
}
export function backendUrlForSandbox(workerBackendUrl: string): string {
try {
const url = new URL(workerBackendUrl);
if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {
url.hostname = 'host.docker.internal';
return url.toString().replace(/\/$/, '');
}
} catch {
// Non-URL value: leave untouched.
}
return workerBackendUrl;
}
type SandboxRetryConfig = {
maxAttempts: number;
baseBackoffMs: number;
maxBackoffMs: number;
};
type RetryableSandboxError = Error & { retryable?: boolean; overloaded?: boolean };
function isRetryableSandboxError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const sandboxError = error as RetryableSandboxError;
if (sandboxError.overloaded === true) return false;
return sandboxError.retryable === true;
}
function getSandboxErrorFlags(error: unknown): {
retryable?: boolean;
overloaded?: boolean;
} {
if (!(error instanceof Error)) {
return {};
}
const sandboxError = error as RetryableSandboxError;
return {
retryable: sandboxError.retryable,
overloaded: sandboxError.overloaded,
};
}
function calculateSandboxBackoff(attempt: number, config: SandboxRetryConfig): number {
const exponentialBackoff = config.baseBackoffMs * Math.pow(2, attempt);
const jitteredBackoff = exponentialBackoff * Math.random();
return Math.min(config.maxBackoffMs, jitteredBackoff);
}
async function cleanupSandboxAttempt(
getSandbox: () => Promise<SandboxInstance>,
sessionId: string,
workspacePath: string,
sessionHome: string
): Promise<void> {
try {
const sandbox = await getSandbox();
const session = await sandbox.getSession(sessionId);
await cleanupWorkspace(session, workspacePath, sessionHome);
await sandbox.deleteSession(sessionId);
} catch (error) {
logger
.withFields({ error: error instanceof Error ? error.message : String(error), sessionId })
.warn('Failed to cleanup sandbox after retryable error');
}
}
async function withSandboxRetry<T>(
getSandbox: () => Promise<SandboxInstance>,
operation: (sandbox: SandboxInstance) => Promise<T>,
operationName: string,
cleanup: () => Promise<void>,
config: SandboxRetryConfig = SANDBOX_RETRY_DEFAULTS
): Promise<T> {
let lastError: Error | undefined;
for (let attempt = 0; attempt < config.maxAttempts; attempt++) {
try {
const sandbox = await getSandbox();
return await operation(sandbox);
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
const errorFlags = getSandboxErrorFlags(error);
if (!isRetryableSandboxError(error)) {
logger
.withFields({
operation: operationName,
attempt: attempt + 1,
error: lastError.message,
retryable: false,
retryableFlag: errorFlags.retryable,
overloadedFlag: errorFlags.overloaded,
})
.warn('Sandbox operation failed with non-retryable error');
throw lastError;
}
if (attempt + 1 >= config.maxAttempts) {
logger
.withFields({
operation: operationName,
attempts: attempt + 1,
error: lastError.message,
})
.error('Sandbox operation failed after all retry attempts');
throw lastError;
}
await cleanup();
const backoffMs = calculateSandboxBackoff(attempt, config);
logger
.withFields({
operation: operationName,
attempt: attempt + 1,
backoffMs: Math.round(backoffMs),
error: lastError.message,
retryableFlag: errorFlags.retryable,
overloadedFlag: errorFlags.overloaded,
})
.warn('Sandbox operation failed, retrying');
await scheduler.wait(backoffMs);
}
}
throw lastError ?? new Error('Unexpected sandbox retry loop exit');
}
export class SetupCommandFailedError extends Error {
constructor(
public readonly command: string,
public readonly exitCode: number,
public readonly stderr: string,
public readonly stdout: string = ''
) {
const details = [
`exit code ${exitCode}`,
...(stderr ? [`stderr: ${stderr.trim()}`] : []),
...(stdout ? [`stdout: ${stdout.trim()}`] : []),
].join(': ');
super(`Setup command failed: ${command} (${details})`);
this.name = 'SetupCommandFailedError';
}
}
export class InvalidSessionMetadataError extends Error {
constructor(
public readonly userId: string,
public readonly sessionId: string,
public readonly details?: string
) {
super(`Invalid session metadata for session ${sessionId}`);
this.name = 'InvalidSessionMetadataError';
}
}
/**
* Execute setup commands in the sandbox session.
* Commands run in the workspace directory with access to env vars.
*
* @param session - ExecutionSession to run commands in
* @param context - Session context (paths, IDs)
* @param setupCommands - Array of setup commands to execute
* @param failFast - Whether to stop on first failure (default: false)
*/
export async function runSetupCommands(
session: ExecutionSession,
context: SessionContext,
setupCommands: string[],
failFast: boolean = false
): Promise<void> {
if (!setupCommands || setupCommands.length === 0) {
return;
}
logger.setTags({ setupCommandsCount: setupCommands.length });
logger.info('Running setup commands');
for (const command of setupCommands) {
try {
// Run command in workspace directory
const result = await timedExec(session, command, 'session.runSetupCommand', {
timeoutMs: SETUP_COMMAND_TIMEOUT_SECONDS * 1000,
cwd: context.workspacePath,
});
if (result.exitCode !== 0) {
logger
.withFields({
command,
exitCode: result.exitCode,
stdout: result.stdout,
stderr: result.stderr,
})
.warn('Setup command failed');
if (failFast) {
throw new SetupCommandFailedError(command, result.exitCode, result.stderr, result.stdout);
}
}
} catch (error) {
logger
.withFields({
command,
error: error instanceof Error ? error.message : String(error),
})
.error('Error executing setup command');
if (failFast) {
if (error instanceof SetupCommandFailedError) {
throw error;
}
throw new SetupCommandFailedError(
command,
-1,
error instanceof Error ? error.message : String(error)
);
}
}
}
logger.info('Setup commands completed');
}
// Write Kilo auth file so the CLI's KiloSessions can call session ingest.
// The CLI reads ~/.local/share/kilo/auth.json via Auth.get("kilo") but we
// never run `kilo auth login` — credentials are injected purely via env vars
// for config (KILO_CONFIG_CONTENT). The session ingest code path ignores the
// provider config and only reads the auth file.
export async function writeAuthFile(
sandbox: SandboxInstance,
sessionHome: string,
kilocodeToken: string
): Promise<void> {
const authDir = `${sessionHome}/.local/share/kilo`;
const authPath = `${authDir}/auth.json`;
await timedExec(sandbox, `mkdir -p ${authDir}`, 'session.writeAuthFile.mkdir');
const authContent = JSON.stringify({ kilo: { type: 'api', key: kilocodeToken } }, null, 2);
await sandbox.writeFile(authPath, authContent);
logger.info('Wrote kilo auth file for session ingest');
}
/**
* CLI-native MCP config shape (env/header values as plain strings), ready to
* JSON-encode into KILO_CONFIG_CONTENT.mcp.
*/
type CliMcpServer =
| {
type: 'local';
command: string[];
environment?: Record<string, string>;
enabled?: boolean;
timeout?: number;
}
| {
type: 'remote';
url: string;
headers?: Record<string, string>;
enabled?: boolean;
timeout?: number;
};
/**
* Materialize each MCP env/header value into its plaintext form for the CLI.
* Plain strings pass through verbatim; encrypted envelopes are decrypted
* per key. Throws only if at least one envelope is present and
* AGENT_ENV_VARS_PRIVATE_KEY is missing — records of pure plain strings
* never require the key.
*/
function materializeMcpServers(
mcpServers: Record<string, MCPServerConfig>,
privateKey: string | undefined
): Record<string, CliMcpServer> {
const out: Record<string, CliMcpServer> = {};
for (const [name, server] of Object.entries(mcpServers)) {
if (server.type === 'local') {
const environment = materializeSecretValueRecord(
server.environment,
privateKey,
`MCP server "${name}" environment`
);
out[name] = {
type: 'local',
command: server.command,
...(environment !== undefined && { environment }),
...(server.enabled !== undefined && { enabled: server.enabled }),
...(server.timeout !== undefined && { timeout: server.timeout }),
};
} else {
const headers = materializeSecretValueRecord(
server.headers,
privateKey,
`MCP server "${name}" headers`
);
out[name] = {
type: 'remote',
url: server.url,
...(headers !== undefined && { headers }),
...(server.enabled !== undefined && { enabled: server.enabled }),
...(server.timeout !== undefined && { timeout: server.timeout }),
};
}
}
return out;
}
function materializeSecretValueRecord(
values: Record<string, MCPSecretValue> | undefined,
privateKey: string | undefined,
label: string
): Record<string, string> | undefined {
if (!values || Object.keys(values).length === 0) return undefined;
const out: Record<string, string> = {};
for (const [key, value] of Object.entries(values)) {
if (typeof value === 'string') {
out[key] = value;
continue;
}
if (!privateKey) {
throw new Error(
`${label} contains encrypted values but AGENT_ENV_VARS_PRIVATE_KEY is not configured on the worker`
);
}
out[key] = decryptWithPrivateKey(value, privateKey);
}
return out;
}
// Write global rules file so the CLI injects cloud-agent-specific instructions.
// The CLI's RulesMigrator discovers ~/.kilocode/rules/*.md and appends them
// to the system prompt automatically.
export async function writeGlobalRules(
sandbox: SandboxInstance,
sessionHome: string,
sessionId: string
): Promise<void> {
const rulesDir = `${sessionHome}/.kilocode/rules`;
const rulesPath = `${rulesDir}/cloud-agent.md`;
await timedExec(sandbox, `mkdir -p ${rulesDir}`, 'session.writeGlobalRules.mkdir');
const content = [
'# Cloud Agent Environment',
'',
"You are running inside a sandboxed cloud container, not on the user's local machine.",
'The filesystem is ephemeral and will not persist after the session ends.',
"Do not assume access to the user's local files, browsers, or desktop environment.",
'',
'## Temporary Files',
'',
`When you need to create temporary or scratch files, use \`/tmp/${sessionId}/\` as your scratch directory.`,
'This path is pre-approved for file access and will not trigger permission prompts.',
'',
].join('\n');
await sandbox.writeFile(rulesPath, content);
}
/**
* Simple djb2 hash for logging a short, non-reversible fingerprint of skill
* content without exposing the content itself.
*/
function shortHash(input: string): string {
let hash = 5381;
for (let i = 0; i < input.length; i++) {
hash = ((hash << 5) + hash + input.charCodeAt(i)) | 0;
}
return (hash >>> 0).toString(16);
}
/**
* Write each runtime skill to `${sessionHome}/.kilocode/skills/<name>/SKILL.md`.
* The CLI auto-discovers skills under `~/.kilocode/skills/<name>/SKILL.md`; `HOME`
* is set to `sessionHome` when the execution session is created so the default
* discovery path resolves here.
*
* Logs name, size, and a short content hash — never the raw content.
*/
/**
* Build the `KILO_CONFIG_CONTENT.agent.<slug>` entry for a profile agent.
* The stored `config` already matches the CLI's AgentConfig shape, so this
* is essentially a pass-through with a default `mode: 'primary'` when the
* user didn't specify one.
*/
export function buildAgentEntryFromRuntimeAgent(agent: RuntimeAgent): Record<string, unknown> {
const { config } = agent;
const entry: Record<string, unknown> = {
mode: config.mode ?? 'primary',
};
if (config.prompt !== undefined) entry.prompt = config.prompt;
if (config.description !== undefined) entry.description = config.description;
if (config.model !== undefined) entry.model = normalizeKilocodeModel(config.model);
if (config.variant !== undefined) entry.variant = config.variant;
if (config.temperature !== undefined) entry.temperature = config.temperature;
if (config.top_p !== undefined) entry.top_p = config.top_p;
if (config.steps !== undefined) entry.steps = config.steps;
if (config.hidden !== undefined) entry.hidden = config.hidden;
if (config.disable !== undefined) entry.disable = config.disable;
if (config.color !== undefined) entry.color = config.color;
if (config.permission !== undefined) entry.permission = config.permission;
if (config.options !== undefined) entry.options = config.options;
return entry;
}
/**
* Defensive check on a companion file path before we exec `mkdir -p`/`writeFile`.
* Schema-level validation already enforces these rules, but re-check at the
* sandbox boundary to prevent any stray input from escaping the skill dir.
*/
function isSafeSkillFilePath(relativePath: string): boolean {
if (relativePath.length === 0 || relativePath.length > 200) return false;
if (relativePath.startsWith('/')) return false;
if (relativePath.includes('..')) return false;
if (relativePath.includes('\\') || relativePath.includes('\0')) return false;
if (relativePath.toLowerCase() === 'skill.md') return false;
return /^[a-zA-Z0-9._\-/]+$/.test(relativePath);
}
export async function writeRuntimeSkills(
sandbox: SandboxInstance,
sessionHome: string,
skills: readonly RuntimeSkill[] | undefined
): Promise<void> {
if (!skills || skills.length === 0) return;
const baseDir = `${sessionHome}/.kilocode/skills`;
await timedExec(sandbox, `mkdir -p ${baseDir}`, 'session.writeRuntimeSkills.mkdir');
const summaries: { name: string; bytes: number; hash: string; fileCount: number }[] = [];
for (const skill of skills) {
const skillDir = `${baseDir}/${skill.name}`;
const skillPath = `${skillDir}/SKILL.md`;
await timedExec(sandbox, `mkdir -p ${skillDir}`, 'session.writeRuntimeSkills.mkdir');
await sandbox.writeFile(skillPath, skill.rawMarkdown);
let fileCount = 0;
if (skill.files) {
for (const [relativePath, content] of Object.entries(skill.files)) {
if (!isSafeSkillFilePath(relativePath)) {
logger
.withFields({ skill: skill.name, relativePath })
.warn('Rejected unsafe skill companion file path');
continue;
}
const filePath = `${skillDir}/${relativePath}`;
const parent = filePath.substring(0, filePath.lastIndexOf('/'));
if (parent && parent !== skillDir) {
await timedExec(sandbox, `mkdir -p ${parent}`, 'session.writeRuntimeSkills.mkdir');
}
await sandbox.writeFile(filePath, content);
fileCount += 1;
}
}
summaries.push({
name: skill.name,
bytes: skill.rawMarkdown.length,
hash: shortHash(skill.rawMarkdown),
fileCount,
});
}
logger
.withFields({ skillCount: summaries.length, skills: summaries })
.info('Wrote runtime skills');
}
/**
* Fetch session metadata from Durable Object using RPC with retry logic.
* Creates a fresh stub for each retry attempt as recommended by Cloudflare.
* @returns CloudAgentSessionState if found, null otherwise
*/
export async function fetchSessionMetadata(
env: PersistenceEnv,
userId: string,
sessionId: string
): Promise<CloudAgentSessionState | null> {
const doKey = `${userId}:${sessionId}`;
const metadata = await withDORetry(
() => env.CLOUD_AGENT_SESSION.get(env.CLOUD_AGENT_SESSION.idFromName(doKey)),
stub => stub.getMetadata(),
'getMetadata'
);
if (!metadata) {
return null;
}
const parsed = MetadataSchema.safeParse(metadata);
if (!parsed.success) {
const reason = JSON.stringify(parsed.error.format());
logger
.withFields({
userId,
sessionId,
reason,
})
.error('Invalid session metadata shape');
throw new InvalidSessionMetadataError(userId, sessionId, reason);
}
return parsed.data;
}
/**
* Generate a unique session ID with the agent_ prefix.
*/
export function generateSessionId(): SessionId {
return `agent_${crypto.randomUUID()}`;
}
/**
* Manages Cloudflare sessions within sandboxes.
* Sessions are bash shell execution contexts within a sandbox (like terminal tabs).
*/
export class SessionService {
private _metadata?: CloudAgentSessionState;
/**
* Get the cached metadata (available after getSandboxIdForSession is called)
*/
get metadata(): CloudAgentSessionState | undefined {
return this._metadata;
}
/**
* Get the sandboxId for a session by fetching and caching its metadata.
* This method should be called before resume() to avoid double-fetching metadata.
* @throws TRPCError with code 'NOT_FOUND' if session doesn't exist
*/
async getSandboxIdForSession(
env: PersistenceEnv,
userId: string,
sessionId: SessionId
): Promise<SandboxId> {
// Fetch and store metadata
const fetchedMetadata = await fetchSessionMetadata(env, userId, sessionId);
if (!fetchedMetadata) {
const { TRPCError } = await import('@trpc/server');
throw new TRPCError({
code: 'NOT_FOUND',
message: `Session ${sessionId} not found. Please initiate a new session.`,
});
}
this._metadata = fetchedMetadata;
// Use the stored sandboxId when available (handles per-session sandboxes).
// Fall back to generating from orgId/userId/botId for old sessions that
// predate sandboxId storage.
const sandboxId: SandboxId =
this._metadata.sandboxId ??
(await generateSandboxId(
env.PER_SESSION_SANDBOX_ORG_IDS,
this._metadata.orgId,
userId,
sessionId,
this._metadata.botId
));
return sandboxId;
}
/**
* Derive a SessionContext from the provided metadata.
*/
buildContext(options: {
sandboxId: SessionContext['sandboxId'];
orgId?: string;
userId: string;
sessionId: SessionId;
workspacePath?: string;
sessionHome?: string;
githubRepo?: string;
githubToken?: string;
gitUrl?: string;
gitToken?: string;
upstreamBranch?: string;
botId?: string;
platform?: 'github' | 'gitlab';
}): SessionContext {
const sessionHome = options.sessionHome ?? getSessionHomePath(options.sessionId);
const workspacePath =
options.workspacePath ??
getSessionWorkspacePath(options.orgId, options.userId, options.sessionId);
const branchName = determineBranchName(options.sessionId, options.upstreamBranch);
return {
sandboxId: options.sandboxId,
sessionId: options.sessionId,
sessionHome,
workspacePath,
branchName,
upstreamBranch: options.upstreamBranch,
orgId: options.orgId,
userId: options.userId,
botId: options.botId,
githubRepo: options.githubRepo,
githubToken: options.githubToken,
gitUrl: options.gitUrl,
gitToken: options.gitToken,
platform: options.platform,
};
}
private getSaferEnvVars(opts: GetSaferEnvVarsOptions): Record<string, string> {
const {
sessionHome,
sessionId,
workspacePath,
env,
originalToken,
kilocodeModel,
originalOrgId,
githubToken,
githubRepo,
createdOnPlatform,
appendSystemPrompt,
gitUrl,
gitToken,
platform,
profile,
} = opts;
const userEnvVars = profile?.envVars;
const encryptedSecrets = profile?.encryptedSecrets;
const mcpServers = profile?.mcpServers;
const runtimeAgents = profile?.runtimeAgents;
// Use override if available, otherwise use original values from API
const kilocodeToken = env.KILOCODE_TOKEN_OVERRIDE ?? originalToken;
const kilocodeOrganizationId = env.KILOCODE_ORG_ID_OVERRIDE ?? originalOrgId;
// Start with user env vars
let baseEnvVars = userEnvVars || {};
// Decrypt and merge encrypted secrets if present
if (encryptedSecrets && Object.keys(encryptedSecrets).length > 0) {
const privateKey = env.AGENT_ENV_VARS_PRIVATE_KEY;
if (!privateKey) {
throw new Error(
'Encrypted secrets provided but AGENT_ENV_VARS_PRIVATE_KEY is not configured on the worker'
);
}
baseEnvVars = mergeEnvVarsWithSecrets(baseEnvVars, encryptedSecrets, privateKey);
logger
.withTags({ secretCount: Object.keys(encryptedSecrets).length })
.info('Decrypted and merged encrypted secrets');
}
const envVars: Record<string, string> = {
// Spread user-provided env vars (including decrypted secrets) first
...baseEnvVars,
// Then set reserved variables to ensure they always take precedence
HOME: sessionHome,
SESSION_ID: sessionId,
SESSION_HOME: sessionHome,
// Inject Kilocode credentials (with override support)
KILOCODE_TOKEN: kilocodeToken,
// Platform identifier - defaults to 'cloud-agent' if not specified
KILO_PLATFORM: createdOnPlatform ?? 'cloud-agent',
KILO_DISABLE_AUTOUPDATE: 'true',
// Feature attribution for microdollar usage tracking
KILOCODE_FEATURE: createdOnPlatform ?? 'cloud-agent',
};
const providerOptions: Record<string, string> = {
apiKey: kilocodeToken,
kilocodeToken: kilocodeToken,
};
if (kilocodeOrganizationId) {
providerOptions.kilocodeOrganizationId = kilocodeOrganizationId;
}
if (env.KILO_OPENROUTER_BASE) {
providerOptions.baseURL = backendUrlForSandbox(env.KILO_OPENROUTER_BASE);
}
const isInteractive = createdOnPlatform == 'cloud-agent-web';
const commandGuardPolicy = getCommandGuardPolicy(createdOnPlatform);
const permission: Record<string, unknown> = {
external_directory: {
'*': 'deny',
[`/tmp/${sessionId}/**`]: 'allow',
[`${workspacePath}/**`]: 'allow',
[`${sessionHome}/.kilocode/skills/**`]: 'allow',
},
...(!isInteractive && { question: 'deny' }),
read: 'allow',
edit: 'allow',
glob: 'allow',
grep: 'allow',
list: 'allow',
bash: 'allow',
task: 'allow',
webfetch: 'allow',
websearch: 'allow',
codesearch: 'allow',
lsp: 'allow',
skill: 'allow',
todowrite: 'allow',
todoread: 'allow',
};
if (commandGuardPolicy) {
// Build bash permission rules from guard policy.
// Denied patterns (e.g. "git add *") are more specific than allowed patterns
// (e.g. "git *"); the CLI resolves overlapping globs most-specific-first,
// so denied sub-commands correctly override broader allows.
const bashPermissions: Record<string, string> = {};
for (const cmd of commandGuardPolicy.denied) {
bashPermissions[`${cmd} *`] = 'deny';
}
for (const cmd of commandGuardPolicy.allowed) {
bashPermissions[`${cmd} *`] = 'allow';
}
// Parity with old autoApproval config:
// read: allow (was read.enabled: true)
// edit: deny (was write.enabled: false)
// webfetch/websearch/codesearch: deny (was browser.enabled: false)
// MCP: allowed by default (was mcp.enabled: true)
// question: handled above (line 564) for non-interactive sessions
Object.assign(permission, {
read: 'allow',
edit: 'deny',
bash: bashPermissions,
webfetch: 'deny',
websearch: 'deny',
codesearch: 'deny',
todowrite: 'allow',
todoread: 'allow',
});
logger
.withFields({
createdOnPlatform,
commandPolicy: commandGuardPolicy.policyName,
deniedCommandPatterns: commandGuardPolicy.denied.length,
})
.info('Enabled read-only command guard policy');
}
const configContent: Record<string, unknown> = {
permission,
provider: {
kilo: {
options: providerOptions,
},
},
autoupdate: false,
};
// Decrypt each env/header envelope into its plaintext value and emit the
// CLI-native shape the runtime consumes under `KILO_CONFIG_CONTENT.mcp`.
if (mcpServers && Object.keys(mcpServers).length > 0) {
const materialized = materializeMcpServers(mcpServers, env.AGENT_ENV_VARS_PRIVATE_KEY);
configContent.mcp = materialized;
logger.info('MCP config merged into KILO_CONFIG_CONTENT', {
mcpServerNames: Object.keys(materialized),
mcpServerCount: Object.keys(materialized).length,
});
}
if (kilocodeModel && kilocodeModel.trim()) {
const normalizedModel = kilocodeModel.startsWith('kilo/')
? kilocodeModel
: `kilo/${kilocodeModel}`;
configContent.model = normalizedModel;
}
// Merge custom-prompt (appendSystemPrompt) and profile-provided runtimeAgents
// under a single `agent` map keyed by slug. The CLI looks up the mode by
// slug and applies its prompt + per-tool permission map.
const agentConfig: Record<string, unknown> = {};
if (appendSystemPrompt && appendSystemPrompt.trim()) {
agentConfig.custom = { prompt: appendSystemPrompt };
}
if (runtimeAgents && runtimeAgents.length > 0) {
for (const agent of runtimeAgents) {
agentConfig[agent.slug] = buildAgentEntryFromRuntimeAgent(agent);
}
logger.info('Runtime agents merged into KILO_CONFIG_CONTENT', {
agentSlugs: runtimeAgents.map(a => a.slug),
agentCount: runtimeAgents.length,
});
}
if (Object.keys(agentConfig).length > 0) {
configContent.agent = agentConfig;
}
const configJson = JSON.stringify(configContent);
envVars.OPENCODE_CONFIG_CONTENT = configJson;
envVars.KILO_CONFIG_CONTENT = configJson;
// Set GH_TOKEN for GitHub repos only, respecting user overrides
if (githubToken && githubRepo && !baseEnvVars.GH_TOKEN) {
envVars.GH_TOKEN = githubToken;
}
// Determine effective platform: use explicit platform param, or infer from gitUrl as fallback
const effectivePlatform = platform ?? (gitUrl?.includes('gitlab') ? 'gitlab' : undefined);
// Set GITLAB_TOKEN for GitLab repos, respecting user overrides.
//
// We also set GLAB_IS_OAUTH2=true unconditionally so that `glab` (>=1.82.0)
// sends `Authorization: Bearer $token` instead of `PRIVATE-TOKEN: $token`.
// This is required for OAuth access tokens (which GitLab rejects with 401
// when sent via PRIVATE-TOKEN) and is also valid for PATs — per GitLab
// REST API docs, personal/project/group access tokens accept OAuth-compliant
// headers (https://docs.gitlab.com/api/rest/authentication/). Treating both
// token types uniformly avoids threading the auth type through the session
// request/DO/metadata stack.
if (gitToken && effectivePlatform === 'gitlab' && !baseEnvVars.GITLAB_TOKEN) {
envVars.GITLAB_TOKEN = gitToken;
if (!baseEnvVars.GITLAB_HOST) {
if (gitUrl) {
try {
const url = new URL(gitUrl);
envVars.GITLAB_HOST = url.host;
} catch {
envVars.GITLAB_HOST = 'gitlab.com';
}
} else {
envVars.GITLAB_HOST = 'gitlab.com';
}
}
if (!baseEnvVars.GLAB_IS_OAUTH2) {
envVars.GLAB_IS_OAUTH2 = 'true';
}
logger
.withFields({
gitUrl,
gitlabHost: envVars.GITLAB_HOST,
gitTokenLength: gitToken.length,
})
.info('[GITLAB] Setting GITLAB_TOKEN, GITLAB_HOST, and GLAB_IS_OAUTH2 for GitLab session');
}
// Only add KILOCODE_ORG_ID if we have an org (personal accounts don't have one)
if (kilocodeOrganizationId) {
envVars.KILOCODE_ORGANIZATION_ID = kilocodeOrganizationId;
}
if (env.KILOCODE_BACKEND_BASE_URL) {
const sandboxUrl = backendUrlForSandbox(env.KILOCODE_BACKEND_BASE_URL);
envVars.KILOCODE_BACKEND_BASE_URL = sandboxUrl;
// Used by kilo server to check user auth to send to ingest
envVars.KILO_API_URL = sandboxUrl;
}
if (env.KILO_SESSION_INGEST_URL) {
envVars.KILO_SESSION_INGEST_URL = env.KILO_SESSION_INGEST_URL;
}
return envVars;
}
/**
* Get an existing session or create a new one.
*
* Sessions within a sandbox maintain isolated shell state (environment variables,
* working directory) but share the filesystem.
*
* Profile-derived configuration (envVars, encryptedSecrets, MCP servers,
* runtime skills/agents) comes through as a single `profile` bundle so
* adding a new profile field is one-line change here instead of threading