-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy patheliza-sandbox.ts
More file actions
3162 lines (2889 loc) · 102 KB
/
eliza-sandbox.ts
File metadata and controls
3162 lines (2889 loc) · 102 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
/**
* Agent Sandbox Service — orchestrates cloud agent lifecycle:
* Neon DB provisioning, Docker sandbox creation, bridge proxy, backups, heartbeat.
*/
import crypto from "node:crypto";
import { isIP } from "node:net";
import { sql } from "drizzle-orm";
import { type Database, dbWrite } from "../../db/helpers";
import {
type AgentBackupSnapshotType,
type AgentSandbox,
type AgentSandboxBackup,
agentSandboxesRepository,
prepareAgentBackupInsertData,
} from "../../db/repositories/agent-sandboxes";
import { userCharactersRepository } from "../../db/repositories/characters";
import { dockerNodesRepository } from "../../db/repositories/docker-nodes";
import {
type AgentBackupStateData,
agentSandboxBackups,
agentSandboxes,
} from "../../db/schemas/agent-sandboxes";
import { jobs } from "../../db/schemas/jobs";
import { getElizaAgentPublicWebUiUrl } from "../eliza-agent-web-ui";
import { getCloudAwareEnv } from "../runtime/cloud-bindings";
import { assertSafeOutboundUrl } from "../security/outbound-url";
import { logger } from "../utils/logger";
import { apiKeysService } from "./api-keys";
import type { DockerSandboxMetadata } from "./docker-sandbox-provider";
import {
reusesExistingElizaCharacter,
stripReservedElizaConfigKeys,
withReusedElizaCharacterOwnership,
} from "./eliza-agent-config";
import { elizaProvisionAdvisoryLockSql } from "./eliza-provision-lock";
import { prepareManagedElizaEnvironment } from "./managed-eliza-env";
import { getNeonClient, NeonClientError } from "./neon-client";
import { JOB_TYPES } from "./provisioning-job-types";
import { createSandboxProvider, type SandboxProvider } from "./sandbox-provider";
/** Shared Neon project used as branch parent for per-agent databases. */
const NEON_PARENT_PROJECT_ID: string = process.env.NEON_PARENT_PROJECT_ID ?? "";
export interface CreateAgentParams {
organizationId: string;
userId: string;
agentName: string;
agentConfig?: Record<string, unknown>;
environmentVars?: Record<string, string>;
/** Link to a user_characters record (canonical character with token linkage). */
characterId?: string;
/** Override the default Docker image (e.g. for different agent flavors). */
dockerImage?: string;
}
export type ProvisionResult =
| {
success: true;
sandboxRecord: AgentSandbox;
bridgeUrl: string;
healthUrl: string;
}
| { success: false; sandboxRecord?: AgentSandbox; error: string };
export type DeleteAgentResult =
| { success: true; deletedSandbox: AgentSandbox }
| { success: false; error: string };
export interface BridgeRequest {
jsonrpc: "2.0";
id?: string | number;
method: string;
params?: Record<string, unknown>;
}
export interface BridgeResponse {
jsonrpc: "2.0";
id?: string | number;
result?: Record<string, unknown>;
error?: { code: number; message: string };
}
export interface SnapshotResult {
success: boolean;
backup?: AgentSandboxBackup;
error?: string;
}
const MAX_BACKUPS = 10;
type LifecycleTx = Parameters<Parameters<Database["transaction"]>[0]>[0];
function isDockerSandboxMetadata(value: unknown): value is DockerSandboxMetadata {
return (
typeof value === "object" &&
value !== null &&
(value as { provider?: unknown }).provider === "docker" &&
typeof (value as { nodeId?: unknown }).nodeId === "string" &&
typeof (value as { hostname?: unknown }).hostname === "string" &&
typeof (value as { containerName?: unknown }).containerName === "string"
);
}
type RuntimeAgentSummary = {
id?: string;
name?: string;
status?: string;
};
type RuntimeAgentListResult = {
supported: boolean;
agents: RuntimeAgentSummary[];
};
const DEFAULT_CENTRAL_SERVER_ID = "00000000-0000-0000-0000-000000000000";
const RUNTIME_AGENT_SECRET_KEYS = [
"OPENAI_API_KEY",
"OPENAI_BASE_URL",
"OPENAI_SMALL_MODEL",
"OPENAI_LARGE_MODEL",
"OPENAI_EMBEDDING_MODEL",
"OPENAI_EMBEDDING_API_KEY",
"OPENAI_EMBEDDING_URL",
"OPENAI_EMBEDDING_DIMENSIONS",
"SMALL_MODEL",
"LARGE_MODEL",
"ANTHROPIC_API_KEY",
"ANTHROPIC_BASE_URL",
"AI_GATEWAY_API_KEY",
"VERCEL_AI_GATEWAY_API_KEY",
] as const;
class BridgeRouteUnavailableError extends Error {
constructor(
message: string,
readonly status: number,
) {
super(message);
this.name = "BridgeRouteUnavailableError";
}
}
export class ElizaSandboxService {
private _provider?: SandboxProvider;
private _providerPromise?: Promise<SandboxProvider>;
constructor(provider?: SandboxProvider) {
if (provider) {
this._provider = provider;
}
}
private async getProvider(): Promise<SandboxProvider> {
if (this._provider) return this._provider;
if (!this._providerPromise) {
this._providerPromise = createSandboxProvider().then((p) => {
this._provider = p;
return p;
});
}
return this._providerPromise;
}
private getAgentApiToken(rec: Pick<AgentSandbox, "id" | "environment_vars">): string | undefined {
const envVars = rec.environment_vars as Record<string, string> | null;
const apiToken =
envVars?.ELIZA_API_TOKEN?.trim() ||
envVars?.ELIZAOS_API_KEY?.trim() ||
envVars?.ELIZAOS_CLOUD_API_KEY?.trim();
if (!apiToken) {
logger.warn("[agent-sandbox] No API token for agent proxy", {
agentId: rec.id,
});
return undefined;
}
return apiToken;
}
private getAgentJsonHeaders(rec: Pick<AgentSandbox, "id" | "environment_vars">) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
const apiToken = this.getAgentApiToken(rec);
if (apiToken) {
headers.Authorization = `Bearer ${apiToken}`;
headers["X-Api-Key"] = apiToken;
headers["X-Eliza-Token"] = apiToken;
}
return headers;
}
private getRuntimeAgentsFromBody(body: unknown): RuntimeAgentSummary[] {
const root = body && typeof body === "object" ? (body as Record<string, unknown>) : {};
const data =
root.data && typeof root.data === "object" ? (root.data as Record<string, unknown>) : {};
const rawAgents = Array.isArray(root.agents)
? root.agents
: Array.isArray(data.agents)
? data.agents
: [];
return rawAgents
.map((item): RuntimeAgentSummary | null => {
if (!item || typeof item !== "object") return null;
const agent = item as Record<string, unknown>;
return {
id: typeof agent.id === "string" ? agent.id : undefined,
name:
typeof agent.name === "string"
? agent.name
: typeof agent.characterName === "string"
? agent.characterName
: undefined,
status: typeof agent.status === "string" ? agent.status : undefined,
};
})
.filter((agent): agent is RuntimeAgentSummary => Boolean(agent?.id || agent?.name));
}
private isRuntimeAgentReady(agent: RuntimeAgentSummary | undefined): boolean {
if (!agent) return false;
const status = agent.status?.toLowerCase();
return status === "active" || status === "running" || status === "ready";
}
private selectRuntimeAgent(agents: RuntimeAgentSummary[]): RuntimeAgentSummary | undefined {
return agents.find((agent) => this.isRuntimeAgentReady(agent)) ?? agents[0];
}
private async listRuntimeAgents(
rec: Pick<
AgentSandbox,
| "id"
| "environment_vars"
| "bridge_url"
| "health_url"
| "node_id"
| "bridge_port"
| "web_ui_port"
| "headscale_ip"
| "sandbox_id"
>,
): Promise<RuntimeAgentListResult> {
const agentsEndpoint = await this.getAgentApiEndpoint(rec, "/api/agents");
const agentsRes = await fetch(agentsEndpoint, {
method: "GET",
headers: this.getAgentJsonHeaders(rec),
signal: AbortSignal.timeout(10_000),
});
if (agentsRes.status === 404) {
return { supported: false, agents: [] };
}
if (!agentsRes.ok) {
throw new Error(`Runtime agent list returned HTTP ${agentsRes.status}`);
}
return {
supported: true,
agents: this.getRuntimeAgentsFromBody(await agentsRes.json().catch(() => ({}))),
};
}
private buildRuntimeBootstrapAgent(
rec: Pick<AgentSandbox, "id" | "agent_name" | "agent_config" | "environment_vars">,
) {
const rawConfig =
rec.agent_config && typeof rec.agent_config === "object" && !Array.isArray(rec.agent_config)
? ({ ...(rec.agent_config as Record<string, unknown>) } as Record<string, unknown>)
: {};
const rawName =
typeof rawConfig.name === "string" && rawConfig.name.trim()
? rawConfig.name.trim()
: rec.agent_name?.trim() || `Cloud Agent ${rec.id.slice(0, 8)}`;
const plugins =
Array.isArray(rawConfig.plugins) && rawConfig.plugins.length > 0
? rawConfig.plugins
: ["@elizaos/plugin-sql", "@elizaos/plugin-elizacloud"];
const rawSettings =
rawConfig.settings &&
typeof rawConfig.settings === "object" &&
!Array.isArray(rawConfig.settings)
? ({ ...(rawConfig.settings as Record<string, unknown>) } as Record<string, unknown>)
: {};
const rawSecrets =
rawSettings.secrets &&
typeof rawSettings.secrets === "object" &&
!Array.isArray(rawSettings.secrets)
? ({ ...(rawSettings.secrets as Record<string, unknown>) } as Record<string, unknown>)
: {};
const environmentVars =
rec.environment_vars && typeof rec.environment_vars === "object"
? (rec.environment_vars as Record<string, string>)
: {};
const secrets: Record<string, unknown> = { ...rawSecrets };
for (const key of RUNTIME_AGENT_SECRET_KEYS) {
const current = typeof secrets[key] === "string" ? secrets[key].trim() : "";
const next = environmentVars[key]?.trim();
if (!current && next) {
secrets[key] = next;
}
}
const settings = {
...rawSettings,
secrets,
};
return {
...rawConfig,
name: rawName,
username:
typeof rawConfig.username === "string" && rawConfig.username.trim()
? rawConfig.username.trim()
: rawName
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "") || "cloud-agent",
system:
typeof rawConfig.system === "string" && rawConfig.system.trim()
? rawConfig.system
: "Concise cloud agent.",
bio:
Array.isArray(rawConfig.bio) && rawConfig.bio.length > 0
? rawConfig.bio
: ["Managed Eliza Cloud agent"],
topics:
Array.isArray(rawConfig.topics) && rawConfig.topics.length > 0
? rawConfig.topics
: ["cloud assistance"],
adjectives:
Array.isArray(rawConfig.adjectives) && rawConfig.adjectives.length > 0
? rawConfig.adjectives
: ["helpful", "concise"],
plugins,
settings,
};
}
private async startRuntimeAgent(
rec: Pick<
AgentSandbox,
| "id"
| "environment_vars"
| "bridge_url"
| "health_url"
| "node_id"
| "bridge_port"
| "web_ui_port"
| "headscale_ip"
| "sandbox_id"
>,
runtimeAgentId: string,
): Promise<void> {
const startEndpoint = await this.getAgentApiEndpoint(
rec,
`/api/agents/${encodeURIComponent(runtimeAgentId)}/start`,
);
const startRes = await fetch(startEndpoint, {
method: "POST",
headers: this.getAgentJsonHeaders(rec),
signal: AbortSignal.timeout(60_000),
});
if (!startRes.ok) {
throw new Error(`Runtime agent start returned HTTP ${startRes.status}`);
}
}
private async createRuntimeAgent(
rec: Pick<
AgentSandbox,
| "id"
| "agent_name"
| "agent_config"
| "environment_vars"
| "bridge_url"
| "health_url"
| "node_id"
| "bridge_port"
| "web_ui_port"
| "headscale_ip"
| "sandbox_id"
>,
): Promise<string> {
const createEndpoint = await this.getAgentApiEndpoint(rec, "/api/agents");
const createRes = await fetch(createEndpoint, {
method: "POST",
headers: this.getAgentJsonHeaders(rec),
body: JSON.stringify({ agent: this.buildRuntimeBootstrapAgent(rec) }),
signal: AbortSignal.timeout(60_000),
});
if (!createRes.ok) {
throw new Error(`Runtime agent create returned HTTP ${createRes.status}`);
}
const body = (await createRes.json().catch(() => ({}))) as Record<string, unknown>;
const data =
body.data && typeof body.data === "object" ? (body.data as Record<string, unknown>) : {};
const runtimeAgentId = typeof data.id === "string" ? data.id : undefined;
if (!runtimeAgentId) {
throw new Error("Runtime agent create response was missing data.id");
}
return runtimeAgentId;
}
private async ensureRuntimeAgentStarted(
rec: Pick<
AgentSandbox,
| "id"
| "agent_name"
| "agent_config"
| "environment_vars"
| "bridge_url"
| "health_url"
| "node_id"
| "bridge_port"
| "web_ui_port"
| "headscale_ip"
| "sandbox_id"
>,
): Promise<RuntimeAgentSummary | null> {
const initial = await this.listRuntimeAgents(rec);
if (!initial.supported) return null;
const existing = this.selectRuntimeAgent(initial.agents);
if (this.isRuntimeAgentReady(existing)) return existing ?? null;
const runtimeAgentId = existing?.id ?? (await this.createRuntimeAgent(rec));
await this.startRuntimeAgent(rec, runtimeAgentId);
const afterStart = await this.listRuntimeAgents(rec);
const started =
afterStart.agents.find((agent) => agent.id === runtimeAgentId) ?? afterStart.agents[0];
if (!this.isRuntimeAgentReady(started)) {
throw new Error("Runtime agent did not become active after start");
}
return started;
}
private stableBridgeUuid(raw: string): string {
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(raw)) {
return raw;
}
const hash = crypto.createHash("sha256").update(raw).digest("hex");
return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-4${hash.slice(13, 16)}-a${hash.slice(
17,
20,
)}-${hash.slice(20, 32)}`;
}
private stableBridgeUserId(params: Record<string, unknown>): string {
const raw =
typeof params.userId === "string" && params.userId.trim()
? params.userId.trim()
: typeof params.roomId === "string" && params.roomId.trim()
? params.roomId.trim()
: "cloud-user";
return this.stableBridgeUuid(raw);
}
private stableBridgeChannelId(agentId: string, params: Record<string, unknown>): string {
const raw =
typeof params.roomId === "string" && params.roomId.trim()
? params.roomId.trim()
: typeof params.userId === "string" && params.userId.trim()
? params.userId.trim()
: "default";
return this.stableBridgeUuid(`cloud-bridge-channel:${agentId}:${raw}`);
}
// Agent CRUD
async createAgent(params: CreateAgentParams): Promise<AgentSandbox> {
logger.info("[agent-sandbox] Creating agent", {
orgId: params.organizationId,
name: params.agentName,
});
const sanitizedConfig = stripReservedElizaConfigKeys(params.agentConfig);
const agentConfig = params.characterId
? withReusedElizaCharacterOwnership(sanitizedConfig)
: sanitizedConfig;
return agentSandboxesRepository.create({
organization_id: params.organizationId,
user_id: params.userId,
agent_name: params.agentName,
agent_config: agentConfig,
environment_vars: params.environmentVars ?? {},
status: "pending",
database_status: "none",
...(params.characterId && { character_id: params.characterId }),
...(params.dockerImage && { docker_image: params.dockerImage }),
});
}
async getAgent(agentId: string, orgId: string) {
return agentSandboxesRepository.findByIdAndOrg(agentId, orgId);
}
async updateAgentEnvironment(
agentId: string,
orgId: string,
environmentVars: Record<string, string>,
): Promise<AgentSandbox | undefined> {
const rec = await agentSandboxesRepository.findByIdAndOrg(agentId, orgId);
if (!rec) return undefined;
return agentSandboxesRepository.update(rec.id, {
environment_vars: environmentVars,
});
}
async getAgentForWrite(agentId: string, orgId: string) {
return agentSandboxesRepository.findByIdAndOrgForWrite(agentId, orgId);
}
async listAgents(orgId: string) {
return agentSandboxesRepository.listByOrganization(orgId);
}
async deleteAgent(agentId: string, orgId: string): Promise<DeleteAgentResult> {
const result = await dbWrite.transaction(async (tx) => {
await this.lockLifecycle(tx, agentId, orgId);
const rec = await this.getAgentForLifecycleMutation(tx, agentId, orgId);
if (!rec) return { success: false, error: "Agent not found" } as const;
const hasActiveProvisionJob = await this.hasActiveProvisionJobTx(tx, agentId, orgId);
if (rec.status === "provisioning" || hasActiveProvisionJob) {
return {
success: false,
error: "Agent provisioning is in progress",
} as const;
}
logger.info("[agent-sandbox] Deleting agent", {
agentId,
neon: rec.neon_project_id,
sandbox: rec.sandbox_id,
});
if (rec.sandbox_id) {
try {
await (await this.getProvider()).stop(rec.sandbox_id);
} catch (e) {
const errorMessage = e instanceof Error ? e.message : String(e);
if (!this.isIgnorableSandboxStopError(e)) {
logger.warn("[agent-sandbox] Stop failed during delete", {
sandboxId: rec.sandbox_id,
status: rec.status,
error: errorMessage,
});
return {
success: false,
error: "Failed to delete sandbox",
} as const;
}
logger.info("[agent-sandbox] Sandbox already absent during delete cleanup", {
sandboxId: rec.sandbox_id,
status: rec.status,
error: errorMessage,
});
}
}
if (rec.neon_project_id) {
try {
await this.cleanupNeon(rec.neon_project_id, rec.neon_branch_id);
} catch (e) {
logger.warn("[agent-sandbox] Neon cleanup failed during delete", {
projectId: rec.neon_project_id,
branchId: rec.neon_branch_id,
error: e instanceof Error ? e.message : String(e),
});
return {
success: false,
error: "Failed to delete database project",
} as const;
}
}
const result = await tx.execute<AgentSandbox>(sql`
DELETE FROM ${agentSandboxes}
WHERE id = ${agentId}
AND organization_id = ${orgId}
RETURNING *
`);
const deletedSandbox = result.rows[0];
return deletedSandbox
? ({ success: true, deletedSandbox } as const)
: ({ success: false, error: "Agent not found" } as const);
});
if (result.success) {
// Best-effort: revoke the per-agent API key after the row delete commits.
// A failure here does not un-delete the sandbox; the key just lingers as
// inactive data and can be cleaned by ops.
try {
await apiKeysService.revokeForAgent(agentId);
} catch (err) {
logger.warn("[agent-sandbox] Failed to revoke per-agent API key", {
agentId,
error: err instanceof Error ? err.message : String(err),
});
}
}
return result;
}
/**
* Async-path counterpart to `deleteAgent`, invoked by the provisioning
* worker daemon when it picks up an `agent_delete` job. Returns a
* structured outcome the daemon stores in the job result so observers can
* tell apart "container survived stop" (ops needed) from "row delete
* failed" (probably retried by next attempt).
*
* Wraps `deleteAgent` so the SSH/Neon/DB sequence stays in one place,
* but maps the return shape to what the queue handler expects and
* tracks whether the container actually went down before the row was
* removed. The row delete happens iff `stop` either succeeded or the
* container was already gone — both are observable in the `deleteAgent`
* success path (`isIgnorableSandboxStopError` swallows "no such
* container" specifically).
*/
async executeDeletion(
agentId: string,
orgId: string,
): Promise<{
success: boolean;
containerStopped: boolean;
error?: string;
}> {
const result = await this.deleteAgent(agentId, orgId);
if (!result.success) {
// If the row is already gone, treat as success. This covers the retry
// case where a prior attempt deleted the row but failed before updating
// the job status to "completed", causing the runner to retry.
if (result.error === "Agent not found") {
return { success: true, containerStopped: true };
}
return {
success: false,
containerStopped: false,
error: result.error,
};
}
// Character cleanup used to live in the HTTP DELETE handler. Now that
// delete is async via the queue, the daemon owns this step so orphan
// characters do not pile up when the deletion completes outside of an
// HTTP request context. Best-effort: a failure here leaves an orphan
// row but does not un-delete the (already gone) sandbox.
const characterId = result.deletedSandbox.character_id;
if (characterId && !reusesExistingElizaCharacter(result.deletedSandbox.agent_config)) {
try {
await userCharactersRepository.delete(characterId);
logger.info("[agent-sandbox] Cleaned up linked character after delete", {
agentId,
characterId,
});
} catch (charErr) {
logger.warn("[agent-sandbox] Linked character cleanup failed after delete", {
agentId,
characterId,
error: charErr instanceof Error ? charErr.message : String(charErr),
});
}
}
return {
success: true,
// If we got past the stop step at all, by the time we returned success
// the container was either stopped or was never there. Either way it
// is no longer running, which is what the daemon needs to know to
// mark the job complete.
containerStopped: true,
};
}
// Provision
async provision(agentId: string, orgId: string): Promise<ProvisionResult> {
let rec = await agentSandboxesRepository.findByIdAndOrg(agentId, orgId);
if (!rec) return { success: false, error: "Agent not found" } as ProvisionResult;
const lock = await agentSandboxesRepository.trySetProvisioning(rec.id);
if (!lock) {
if (rec.status === "running" && rec.bridge_url && rec.health_url)
return {
success: true,
sandboxRecord: rec,
bridgeUrl: rec.bridge_url,
healthUrl: rec.health_url,
};
return {
success: false,
sandboxRecord: rec,
error: "Agent is already being provisioned",
};
}
// 1. Database
let dbUri = rec.database_uri;
if (rec.database_status !== "ready" || !dbUri) {
const db = await this.provisionNeon(rec);
if (!db.success) {
await this.markError(rec, `Database provisioning failed: ${db.error}`);
return {
success: false,
sandboxRecord: await agentSandboxesRepository.findById(rec.id),
error: db.error ?? "Unknown database error",
};
}
dbUri = db.connectionUri!;
// Neon provision updates DB but doesn't return the full record; re-fetch to avoid stale data
const refreshed = await agentSandboxesRepository.findByIdAndOrg(agentId, orgId);
if (refreshed) {
rec = refreshed;
}
}
const managedEnvironment = await prepareManagedElizaEnvironment({
existingEnv: (rec.environment_vars as Record<string, string>) ?? {},
organizationId: rec.organization_id,
userId: rec.user_id,
sandboxId: agentId,
});
if (managedEnvironment.changed) {
const updatedEnvRecord = await agentSandboxesRepository.update(rec.id, {
environment_vars: managedEnvironment.environmentVars,
});
if (updatedEnvRecord) {
rec = updatedEnvRecord;
} else {
rec = {
...rec,
environment_vars: managedEnvironment.environmentVars,
};
}
}
// 2-5. Sandbox creation + DB persistence with retry for port collision
// TOCTOU race: Port allocation happens in-memory (provider allocates next available port),
// but persistence to DB (unique constraint on node_id + bridge_port) happens later.
// If two concurrent provisions pick the same port, one will fail with PG 23505.
// Solution: Retry loop catches unique constraint errors, cleans up ghost container, and retries.
const MAX_PROVISION_ATTEMPTS = 3;
let lastError: string = "Unknown error";
for (let attempt = 1; attempt <= MAX_PROVISION_ATTEMPTS; attempt++) {
let handle;
try {
// 2. Sandbox (via provider)
handle = await (await this.getProvider()).create({
agentId: rec.id,
agentName: rec.agent_name ?? "CloudAgent",
organizationId: rec.organization_id,
environmentVars: {
...((rec.environment_vars as Record<string, string>) ?? {}),
DATABASE_URL: dbUri,
},
snapshotId: rec.snapshot_id ?? undefined,
dockerImage: rec.docker_image ?? undefined,
});
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
await this.markError(rec, `Sandbox creation failed: ${msg}`);
return {
success: false,
sandboxRecord: await agentSandboxesRepository.findById(rec.id),
error: msg,
};
}
try {
// 3. Health check (via provider)
if (!(await (await this.getProvider()).checkHealth(handle))) {
throw new Error("Sandbox health check timed out");
}
const dockerMeta = isDockerSandboxMetadata(handle.metadata) ? handle.metadata : undefined;
const runtimeRec = {
...rec,
sandbox_id: handle.sandboxId,
bridge_url: handle.bridgeUrl,
health_url: handle.healthUrl,
node_id: dockerMeta?.nodeId ?? rec.node_id,
container_name: dockerMeta?.containerName ?? rec.container_name,
bridge_port: dockerMeta?.bridgePort ?? rec.bridge_port,
web_ui_port: dockerMeta?.webUiPort ?? rec.web_ui_port,
headscale_ip: dockerMeta?.headscaleIp ?? rec.headscale_ip,
};
await this.ensureRuntimeAgentStarted(runtimeRec);
// 4. Restore from backup
const backup = await agentSandboxesRepository.getLatestBackup(rec.id);
if (backup)
await this.pushState(handle.bridgeUrl, backup.state_data as AgentBackupStateData, {
trusted: true,
});
// 5. Mark running + persist provider-specific metadata
const updateData: Parameters<typeof agentSandboxesRepository.update>[1] = {
status: "running",
sandbox_id: handle.sandboxId,
bridge_url: handle.bridgeUrl,
health_url: handle.healthUrl,
last_heartbeat_at: new Date(),
error_message: null,
};
if (dockerMeta) {
if (dockerMeta.nodeId) updateData.node_id = dockerMeta.nodeId;
if (dockerMeta.containerName) updateData.container_name = dockerMeta.containerName;
if (dockerMeta.bridgePort) updateData.bridge_port = dockerMeta.bridgePort;
if (dockerMeta.webUiPort) updateData.web_ui_port = dockerMeta.webUiPort;
if (dockerMeta.headscaleIp) updateData.headscale_ip = dockerMeta.headscaleIp;
if (dockerMeta.dockerImage) updateData.docker_image = dockerMeta.dockerImage;
}
const updated = await agentSandboxesRepository.update(rec.id, updateData);
logger.info("[agent-sandbox] Provisioned", {
agentId: rec.id,
sandboxId: handle.sandboxId,
attempt,
});
return {
success: true,
sandboxRecord: updated!,
bridgeUrl: handle.bridgeUrl,
healthUrl: handle.healthUrl,
};
} catch (err) {
// Ghost container cleanup: provider.create() succeeded but DB update or health check failed
const msg = err instanceof Error ? err.message : String(err);
lastError = msg;
logger.warn("[agent-sandbox] Post-create failure, cleaning up container", {
agentId: rec.id,
sandboxId: handle.sandboxId,
attempt,
error: msg,
});
await (await this.getProvider()).stop(handle.sandboxId).catch((stopErr) => {
logger.error("[agent-sandbox] Ghost container cleanup failed", {
sandboxId: handle.sandboxId,
error: stopErr instanceof Error ? stopErr.message : String(stopErr),
});
});
// Check if it's a unique constraint error (port collision) -> retry
const isUniqueConstraintError =
msg.includes("23505") ||
msg.toLowerCase().includes("unique") ||
msg.toLowerCase().includes("duplicate");
if (isUniqueConstraintError && attempt < MAX_PROVISION_ATTEMPTS) {
logger.info("[agent-sandbox] Port collision detected, retrying", {
attempt,
nextAttempt: attempt + 1,
});
continue; // Retry
}
// Non-retryable error or max attempts reached -> fail
break;
}
}
// All attempts exhausted
await this.markError(
rec,
`Provisioning failed after ${MAX_PROVISION_ATTEMPTS} attempts: ${lastError}`,
);
return {
success: false,
sandboxRecord: await agentSandboxesRepository.findById(rec.id),
error: lastError,
};
}
private async getSafeBridgeEndpoint(
sandboxOrBridgeUrl:
| Pick<AgentSandbox, "bridge_url" | "node_id" | "bridge_port" | "headscale_ip" | "sandbox_id">
| string,
path: string,
options?: { trusted?: boolean },
): Promise<string> {
if (typeof sandboxOrBridgeUrl === "string") {
if (options?.trusted) {
return new URL(path, sandboxOrBridgeUrl).toString();
}
return (await assertSafeOutboundUrl(new URL(path, sandboxOrBridgeUrl).toString())).toString();
}
const dockerBridgeBaseUrl = await this.getTrustedDockerBridgeBaseUrl(sandboxOrBridgeUrl);
if (
dockerBridgeBaseUrl &&
sandboxOrBridgeUrl.bridge_url &&
this.matchesTrustedDockerBridge(sandboxOrBridgeUrl.bridge_url, dockerBridgeBaseUrl)
) {
return new URL(path, dockerBridgeBaseUrl).toString();
}
if (!sandboxOrBridgeUrl.bridge_url) {
throw new Error("Sandbox bridge is missing");
}
if (this.isTrustedLegacyPrivateBridgeUrl(sandboxOrBridgeUrl)) {
return new URL(path, sandboxOrBridgeUrl.bridge_url).toString();
}
return (
await assertSafeOutboundUrl(new URL(path, sandboxOrBridgeUrl.bridge_url).toString())
).toString();
}
private getConfiguredAgentBaseDomain(): string | null {
const configured = getCloudAwareEnv().ELIZA_CLOUD_AGENT_BASE_DOMAIN?.trim();
if (!configured) return null;
const normalized = configured
.replace(/^https?:\/\//, "")
.replace(/\/.*$/, "")
.replace(/\.+$/, "");
return normalized || null;
}
private async getAgentApiEndpoint(
rec: Pick<
AgentSandbox,
| "id"
| "bridge_url"
| "health_url"
| "node_id"
| "bridge_port"
| "web_ui_port"
| "headscale_ip"
| "sandbox_id"
>,
path: string,
): Promise<string> {
const isWorkerRuntime = this.isCloudflareWorkerRuntime();
const baseDomain = this.getConfiguredAgentBaseDomain();
if (isWorkerRuntime) {
const publicEndpoint = getElizaAgentPublicWebUiUrl(
rec,
baseDomain ? { baseDomain, path } : { path },
);
if (publicEndpoint) return publicEndpoint;
}
const trustedWebBaseUrl = await this.getTrustedDockerWebBaseUrl(rec);
if (trustedWebBaseUrl) {
return new URL(path, trustedWebBaseUrl).toString();
}
if (baseDomain) {
const publicEndpoint = getElizaAgentPublicWebUiUrl(rec, {
baseDomain,
path,
});
if (publicEndpoint) return publicEndpoint;
}
return this.getSafeBridgeEndpoint(rec, path);
}
private async getTrustedDockerWebBaseUrl(
sandbox: Pick<
AgentSandbox,
"node_id" | "web_ui_port" | "headscale_ip" | "health_url" | "bridge_url"
>,
): Promise<string | null> {
if (sandbox.health_url) {
try {
return new URL(sandbox.health_url).origin;
} catch {
// Fall through to metadata-based resolution.
}
}
if (!sandbox.node_id || !sandbox.web_ui_port) {
return null;
}
const host =
sandbox.headscale_ip || (await dockerNodesRepository.findByNodeId(sandbox.node_id))?.hostname;
if (!host) {
return null;
}
return `http://${host}:${sandbox.web_ui_port}`;
}
private async getTrustedDockerBridgeBaseUrl(