forked from paperclipai/paperclip
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenvironment-runtime.ts
More file actions
2061 lines (1921 loc) · 79.4 KB
/
Copy pathenvironment-runtime.ts
File metadata and controls
2061 lines (1921 loc) · 79.4 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 { createHash, randomUUID } from "node:crypto";
import { and, eq, inArray } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { companySecrets, companySecretVersions, environmentLeases } from "@paperclipai/db";
import type {
Environment,
EnvironmentLease,
EnvironmentLeaseStatus,
ExecutionWorkspace,
PluginEnvironmentConfig,
SandboxEnvironmentConfig,
} from "@paperclipai/shared";
import type {
PluginEnvironmentExecuteResult,
PluginEnvironmentLease,
PluginEnvironmentRealizeWorkspaceResult,
} from "@paperclipai/plugin-sdk";
import { ensureSshWorkspaceReady } from "@paperclipai/adapter-utils/ssh";
import { environmentService } from "./environments.js";
import {
collectEnvironmentSecretRefs,
parseEnvironmentDriverConfig,
resolveEnvironmentDriverConfigForRuntime,
stripSandboxProviderEnvelope,
} from "./environment-config.js";
import {
createEffectiveRunConfigFingerprints,
type EffectiveRunConfigFingerprint,
type EffectiveRunConfigSecretVersionMetadata,
} from "./effective-run-config-fingerprints.js";
import {
acquireSandboxProviderLease,
destroySandboxProviderLease,
findReusableSandboxProviderLeaseId,
getSandboxProvider as getBuiltinSandboxProvider,
isBuiltinSandboxProvider,
releaseSandboxProviderLease,
sandboxConfigFromLeaseMetadata,
sandboxConfigFromLeaseMetadataLoose,
} from "./sandbox-provider-runtime.js";
import { pluginRegistryService } from "./plugin-registry.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { getProcessPluginWorkerManager } from "./plugin-worker-process-registry.js";
import type { PluginStreamBus } from "./plugin-stream-bus.js";
import {
destroyPluginEnvironmentLease,
executePluginEnvironmentCommand,
realizePluginEnvironmentWorkspace,
resolvePluginSandboxProviderDriverByKey,
resolvePluginExecuteBudget,
resolvePluginExecuteRpcTimeoutMs,
resumePluginEnvironmentLease,
} from "./plugin-environment-driver.js";
import { collectSecretRefPaths } from "./json-schema-secret-refs.js";
import { buildWorkspaceRealizationRecordFromDriverInput } from "./workspace-realization.js";
/** Channel name a plugin worker emits live exec output on for a given run. */
export function envExecOutputChannel(runId: string): string {
return `env-exec-output:${runId}`;
}
/**
* Bridge live stdout/stderr from a plugin worker back to an in-process
* `onOutput` sink across the worker RPC boundary.
*
* The worker cannot be handed a callback (functions don't serialize over
* JSON-RPC), so when the caller provides `onOutput` AND a `runId` AND a stream
* bus is available we subscribe to the worker's output channel
* (`env-exec-output:${runId}`, scoped to `companyId`) BEFORE running the RPC,
* route each emitted `{ stream, text }` chunk to `onOutput`, and unsubscribe on
* EVERY exit path (resolve or throw) so no subscription leaks. The `run`
* callback is told whether streaming is active so it can set the serializable
* `streamOutput` RPC flag; when streaming can't be set up we run with
* `streaming=false` and the provider falls back to buffered-at-end output.
*/
export async function withPluginExecOutputStream<T>(opts: {
streamBus?: PluginStreamBus;
pluginId: string;
companyId: string;
runId?: string | null;
onOutput?: (stream: "stdout" | "stderr", text: string) => void | Promise<void>;
run: (streaming: boolean) => Promise<T>;
}): Promise<T> {
const { streamBus, pluginId, companyId, runId, onOutput, run } = opts;
if (!streamBus || !onOutput || !runId) {
return await run(false);
}
const channel = envExecOutputChannel(runId);
const unsubscribe = streamBus.subscribe(pluginId, channel, companyId, (event) => {
const chunk = event as { stream?: unknown; text?: unknown } | null | undefined;
if (
chunk &&
typeof chunk.text === "string" &&
(chunk.stream === "stdout" || chunk.stream === "stderr")
) {
void onOutput(chunk.stream, chunk.text);
}
});
try {
return await run(true);
} finally {
unsubscribe();
}
}
export function buildEnvironmentLeaseContext(input: {
persistedExecutionWorkspace: Pick<ExecutionWorkspace, "id" | "mode"> | null;
}) {
return {
executionWorkspaceId: input.persistedExecutionWorkspace?.id ?? null,
executionWorkspaceMode: input.persistedExecutionWorkspace?.mode ?? null,
};
}
function stripSecretRefValuesFromPluginLeaseMetadata(input: {
metadata: Record<string, unknown> | null | undefined;
schema: Record<string, unknown> | null | undefined;
}): Record<string, unknown> {
const sanitized = structuredClone(input.metadata ?? {}) as Record<string, unknown>;
for (const path of collectSecretRefPaths(input.schema)) {
const keys = path.split(".");
const parents: Array<{ container: Record<string, unknown>; key: string }> = [];
let cursor: Record<string, unknown> | null = sanitized;
for (let index = 0; index < keys.length - 1; index += 1) {
const key = keys[index]!;
const next = cursor?.[key];
if (!next || typeof next !== "object" || Array.isArray(next)) {
cursor = null;
break;
}
parents.push({ container: cursor, key });
cursor = next as Record<string, unknown>;
}
if (!cursor) continue;
const leafKey = keys[keys.length - 1]!;
if (!Object.prototype.hasOwnProperty.call(cursor, leafKey)) continue;
delete cursor[leafKey];
for (let index = parents.length - 1; index >= 0; index -= 1) {
const { container, key } = parents[index]!;
const value = container[key];
if (
value &&
typeof value === "object" &&
!Array.isArray(value) &&
Object.keys(value as Record<string, unknown>).length === 0
) {
delete container[key];
} else {
break;
}
}
}
return sanitized;
}
export interface EnvironmentDriverAcquireInput {
companyId: string;
environment: Environment;
issueId: string | null;
agentId: string | null;
/**
* UUID of the owning heartbeat run, or null for ad-hoc invocations
* (e.g. operator-initiated `Test` probes) that are not tied to a run.
* Null leases must be released by id via `getDriver(...).releaseRunLease`
* since `releaseRunLeases(heartbeatRunId)` cannot find them.
*/
heartbeatRunId: string | null;
executionWorkspaceId: string | null;
executionWorkspaceMode: ExecutionWorkspace["mode"] | null;
/**
* The harness/adapter type for this run (the agent's adapter). Drivers that
* materialize a per-run sandbox use it to select the runtime image so a single
* environment can serve mixed harnesses; null falls back to the environment's
* configured default adapter.
*/
adapterType: string | null;
/**
* Force applying the active custom-image template even when issueId and
* heartbeatRunId are null. Operator-initiated `Test` probes set this so the
* probe uses the operator-prepared custom image for the runtime lease instead
* of the base image, matching what real agent runs do.
*/
applyCustomImageTemplate?: boolean;
}
export interface EnvironmentDriverReleaseInput {
environment: Environment;
lease: EnvironmentLease;
status: Extract<EnvironmentLeaseStatus, "released" | "expired" | "failed">;
}
function resolvePluginSandboxRpcTimeoutMs(config: Record<string, unknown>): number | undefined {
const timeoutCandidates = [
typeof config.timeoutMs === "number" ? config.timeoutMs : undefined,
typeof config.bridgeRequestTimeoutMs === "number" ? config.bridgeRequestTimeoutMs : undefined,
]
.filter((value): value is number => typeof value === "number" && Number.isFinite(value) && value > 0)
.map((value) => Math.trunc(value));
if (timeoutCandidates.length === 0) {
return undefined;
}
return resolvePluginExecuteRpcTimeoutMs({
requestedTimeoutMs: Math.max(...timeoutCandidates),
config,
});
}
export interface EnvironmentDriverLeaseInput {
environment: Environment;
lease: EnvironmentLease;
failureReason?: string;
}
export interface EnvironmentDriverRealizeWorkspaceInput extends EnvironmentDriverLeaseInput {
workspace: {
localPath?: string;
remotePath?: string;
mode?: string;
metadata?: Record<string, unknown>;
};
}
export interface EnvironmentDriverExecuteInput extends EnvironmentDriverLeaseInput {
command: string;
args?: string[];
cwd?: string;
env?: Record<string, string>;
stdin?: string;
timeoutMs?: number;
// Optional live-output sink. When a driver executes in-process it can forward
// stdout/stderr chunks here as they arrive and set `streamed: true` on its
// result. NOTE: for plugin-backed sandbox providers the actual execute runs
// in a worker behind a JSON-RPC boundary (see the `execute` impl below), and
// a function cannot cross that boundary — so this sink is not delivered to the
// worker today and those providers fall back to buffered-at-end output. The
// last-mile RPC forwarding of chunks (worker -> host) is a separate change.
onOutput?: (stream: "stdout" | "stderr", text: string) => void | Promise<void>;
// Run correlation id. For plugin-backed sandbox providers this is forwarded
// over the worker RPC boundary and used (with `onOutput`) to bridge live
// stdout/stderr from the worker back to `onOutput` via the plugin stream bus
// (see the `execute` impl below). Null/undefined -> no live streaming, the
// provider falls back to buffered-at-end output.
runId?: string | null;
}
export interface EnvironmentRuntimeDriver {
readonly driver: string;
acquireRunLease(input: EnvironmentDriverAcquireInput): Promise<EnvironmentLease>;
releaseRunLease(input: EnvironmentDriverReleaseInput): Promise<EnvironmentLease | null>;
resumeRunLease?(input: EnvironmentDriverLeaseInput): Promise<PluginEnvironmentLease | EnvironmentLease | null>;
destroyRunLease?(input: EnvironmentDriverLeaseInput): Promise<EnvironmentLease | null>;
realizeWorkspace?(input: EnvironmentDriverRealizeWorkspaceInput): Promise<PluginEnvironmentRealizeWorkspaceResult>;
execute?(input: EnvironmentDriverExecuteInput): Promise<PluginEnvironmentExecuteResult>;
}
export interface EnvironmentRuntimeLeaseRecord {
environment: Environment;
lease: EnvironmentLease;
leaseContext: ReturnType<typeof buildEnvironmentLeaseContext>;
}
const DEFAULT_PLUGIN_SANDBOX_WORKER_READY_TIMEOUT_MS = 5_000;
const DEFAULT_PLUGIN_SANDBOX_WORKER_READY_POLL_MS = 100;
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function getLeaseDriverKey(lease: Pick<EnvironmentLease, "metadata">, environment: Pick<Environment, "driver">): string {
const leaseDriver = typeof lease.metadata?.driver === "string" ? lease.metadata.driver : null;
return leaseDriver ?? environment.driver;
}
function toEnvironmentLeaseSnapshot(row: typeof environmentLeases.$inferSelect): EnvironmentLease {
return {
id: row.id,
companyId: row.companyId,
environmentId: row.environmentId,
executionWorkspaceId: row.executionWorkspaceId ?? null,
issueId: row.issueId ?? null,
heartbeatRunId: row.heartbeatRunId ?? null,
status: row.status as EnvironmentLease["status"],
leasePolicy: row.leasePolicy as EnvironmentLease["leasePolicy"],
provider: row.provider ?? null,
providerLeaseId: row.providerLeaseId ?? null,
acquiredAt: row.acquiredAt,
lastUsedAt: row.lastUsedAt,
expiresAt: row.expiresAt ?? null,
releasedAt: row.releasedAt ?? null,
failureReason: row.failureReason ?? null,
cleanupStatus: row.cleanupStatus as EnvironmentLease["cleanupStatus"],
metadata: (row.metadata as Record<string, unknown> | null) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function stableStringify(value: unknown): string {
if (Array.isArray(value)) {
return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
}
if (isRecord(value)) {
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
}
return JSON.stringify(value) ?? "null";
}
function reusableRuntimeFingerprint(input: {
provider: string;
adapterType: string | null;
config: Record<string, unknown>;
}): string {
return createHash("sha256")
.update(stableStringify(input))
.digest("hex");
}
function serializeLeaseFingerprint(
fingerprint: EffectiveRunConfigFingerprint | null | undefined,
): Record<string, unknown> | null {
if (!fingerprint) return null;
return {
version: fingerprint.version,
category: fingerprint.category,
algorithm: fingerprint.algorithm,
fingerprint: fingerprint.fingerprint,
};
}
function readLeaseFingerprint(value: unknown): string | null {
return isRecord(value) ? readString(value.fingerprint) : null;
}
async function buildEnvironmentSecretMetadataForLeaseFingerprint(input: {
db: Db;
companyId: string;
environment: Environment;
}): Promise<EffectiveRunConfigSecretVersionMetadata[]> {
const refs = await collectEnvironmentSecretRefs({
db: input.db,
environment: input.environment,
});
if (refs.length === 0) return [];
const secretIds = [...new Set(refs.map((ref) => ref.secretId))];
const secretRows = await input.db
.select()
.from(companySecrets)
.where(inArray(companySecrets.id, secretIds));
const secretsById = new Map(
secretRows
.filter((secret) => secret.companyId === input.companyId)
.map((secret) => [secret.id, secret]),
);
const versionRequests = refs.flatMap((ref) => {
const secret = secretsById.get(ref.secretId);
if (!secret) return [];
const resolvedVersion = ref.versionSelector === "latest" || ref.versionSelector === undefined
? secret.latestVersion
: ref.versionSelector;
return typeof resolvedVersion === "number"
? [{ secretId: secret.id, version: resolvedVersion }]
: [];
});
const versionSecretIds = [...new Set(versionRequests.map((request) => request.secretId))];
const versions = [...new Set(versionRequests.map((request) => request.version))];
const versionRows = versionSecretIds.length > 0 && versions.length > 0
? await input.db
.select()
.from(companySecretVersions)
.where(
and(
inArray(companySecretVersions.secretId, versionSecretIds),
inArray(companySecretVersions.version, versions),
),
)
: [];
const versionsBySecretAndNumber = new Map(
versionRows.map((row) => [`${row.secretId}:${row.version}`, row]),
);
const metadata: EffectiveRunConfigSecretVersionMetadata[] = [];
for (const ref of refs) {
const secret = secretsById.get(ref.secretId);
if (!secret) {
metadata.push({
configPath: ref.configPath,
envKey: null,
secretId: ref.secretId,
version: typeof ref.versionSelector === "number" ? ref.versionSelector : "unresolved",
outcome: "failure",
});
continue;
}
const resolvedVersion = ref.versionSelector === "latest" || ref.versionSelector === undefined
? secret.latestVersion
: ref.versionSelector;
const versionRow = typeof resolvedVersion === "number"
? versionsBySecretAndNumber.get(`${secret.id}:${resolvedVersion}`) ?? null
: null;
metadata.push({
configPath: ref.configPath,
envKey: null,
secretId: secret.id,
version: resolvedVersion,
provider: secret.provider,
providerVersionRef: versionRow?.providerVersionRef ?? null,
valueFingerprint: versionRow
? versionRow.fingerprintSha256 ?? versionRow.valueSha256
: null,
outcome: versionRow ? "success" : "failure",
});
}
return metadata;
}
async function buildReusableSandboxLeaseFingerprint(input: {
db: Db;
companyId: string;
environment: Environment;
executionWorkspaceId: string | null;
agentId: string | null;
adapterType: string | null;
provider: string;
providerConfig: Record<string, unknown>;
providerPlugin?: {
id: string;
pluginKey: string;
packageName: string;
version: string;
} | null;
}): Promise<EffectiveRunConfigFingerprint> {
const secretMetadata = await buildEnvironmentSecretMetadataForLeaseFingerprint({
db: input.db,
companyId: input.companyId,
environment: input.environment,
});
return createEffectiveRunConfigFingerprints({
lease: {
companyId: input.companyId,
environment: {
id: input.environment.id,
driver: input.environment.driver,
},
executionWorkspaceId: input.executionWorkspaceId,
agentId: input.agentId,
adapterType: input.adapterType,
provider: input.provider,
providerPlugin: input.providerPlugin ?? null,
providerConfig: input.providerConfig,
secrets: secretMetadata,
},
secretManifest: secretMetadata,
}).leaseFingerprint;
}
function buildReusableSandboxLeaseScope(input: {
companyId: string;
environmentId: string;
executionWorkspaceId: string | null;
agentId: string | null;
adapterType: string | null;
provider: string;
config: Record<string, unknown>;
leaseFingerprint?: EffectiveRunConfigFingerprint | null;
providerMetadata?: Record<string, unknown> | null;
// Mirrors the `sandboxProviderPlugin === true` gate that
// reusableSandboxLeaseScopeMatches uses for its strict adapterType-equality
// rule. Only plugin-backed sandbox leases resolve a per-run adapter/image
// through the plugin worker RPC, so only they may fall back to reading
// adapterType/image out of providerMetadata; a built-in provider's
// providerMetadata is not per-run-image-keyed the way the plugin pool is,
// so treating any stray adapterType/image key there as a positive match
// would be unfounded. Built-in callers omit this flag (default false),
// making the fallback inert for them today; it exists so the two functions
// stay symmetric if a built-in provider ever starts publishing those keys.
isPluginBackedLease?: boolean;
}): Record<string, unknown> | null {
if (!input.executionWorkspaceId || !input.agentId) return null;
const providerMetadata = input.providerMetadata ?? {};
// Prefer the server's own per-run hint; fall back to the plugin's actually
// resolved adapter type when the server's hint is absent (e.g. a run whose
// adapterType wasn't threaded through). This is what keeps the persisted
// scope from ever being null for a plugin sandbox lease that DID resolve a
// concrete adapter/image: a null scope has no positive proof of which
// image the pod carries and can be matched by any run's reuse lookup.
const adapterType =
input.adapterType ??
(input.isPluginBackedLease ? readString(providerMetadata.adapterType) : null) ??
null;
const runtimeImage = input.isPluginBackedLease ? readString(providerMetadata.image) : null;
const remoteCwd = readString(providerMetadata.remoteCwd);
const workspaceSentinel = isRecord(providerMetadata.workspaceSentinel)
? { ...providerMetadata.workspaceSentinel }
: null;
return {
version: 1,
companyId: input.companyId,
environmentId: input.environmentId,
executionWorkspaceId: input.executionWorkspaceId,
agentId: input.agentId,
adapterType,
provider: input.provider,
runtimeFingerprint: reusableRuntimeFingerprint({
provider: input.provider,
adapterType,
config: input.config,
}),
...(input.leaseFingerprint
? { leaseFingerprint: serializeLeaseFingerprint(input.leaseFingerprint) }
: {}),
...(runtimeImage ? { runtimeImage } : {}),
...(remoteCwd ? { remoteCwd } : {}),
...(workspaceSentinel ? { workspaceSentinel } : {}),
};
}
function reusableSandboxLeaseScopeMatches(input: {
lease: Pick<EnvironmentLease, "metadata">;
companyId: string;
environmentId: string;
executionWorkspaceId: string | null;
agentId: string | null;
adapterType: string | null;
provider: string;
config: Record<string, unknown>;
leaseFingerprint?: EffectiveRunConfigFingerprint | null;
allowLegacyRuntimeFingerprint?: boolean;
environmentHasSecretRefs?: boolean;
}): boolean {
if (!input.executionWorkspaceId || !input.agentId) return false;
const scope = input.lease.metadata?.reusableSandboxLease;
if (!isRecord(scope)) return false;
const adapterType = input.adapterType ?? null;
const storedAdapterType = typeof scope.adapterType === "string" ? scope.adapterType : null;
// Plugin-backed sandbox leases pick a per-run runtime image keyed on the
// adapter type; a lease published (or resumed from before this fix) with
// adapterType null carries no positive proof of which image its pod is
// running. Treating null as a wildcard let ANY run reuse it, including one
// requesting a different harness (the production adapter_runtime_image_mismatch
// case this closes). Require a POSITIVE match instead: both sides must be
// set and equal, never null-on-either-side.
//
// Built-in (non-plugin) sandbox providers never publish adapterType in the
// scope at all (they are not per-run-image-keyed the way the plugin pool
// is), so their leases legitimately keep the permissive equality check:
// scoping the strict rule to `sandboxProviderPlugin === true` leaves that
// reuse path unaffected.
const isPluginBackedLease = input.lease.metadata?.sandboxProviderPlugin === true;
const adapterTypeMatches = isPluginBackedLease
? storedAdapterType !== null && adapterType !== null && storedAdapterType === adapterType
: scope.adapterType === adapterType;
const baseScopeMatches =
scope.companyId === input.companyId &&
scope.environmentId === input.environmentId &&
scope.executionWorkspaceId === input.executionWorkspaceId &&
scope.agentId === input.agentId &&
adapterTypeMatches &&
scope.provider === input.provider;
if (!baseScopeMatches) return false;
const expectedLeaseFingerprint = input.leaseFingerprint?.fingerprint ?? null;
if (expectedLeaseFingerprint) {
const storedLeaseFingerprint = readLeaseFingerprint(scope.leaseFingerprint);
if (storedLeaseFingerprint) {
return storedLeaseFingerprint === expectedLeaseFingerprint;
}
// Legacy lease (created before value-aware lease fingerprints existed): it
// only carries the secret-blind runtimeFingerprint. For a secret-bearing
// environment we must NEVER fall through to the runtime-only match, or an
// in-place secret value change would be invisible and we'd serve a stale
// credential from the reused sandbox. Force a fresh, value-aware lease.
if (input.environmentHasSecretRefs) return false;
if (!input.allowLegacyRuntimeFingerprint) return false;
}
return scope.runtimeFingerprint === reusableRuntimeFingerprint({
provider: input.provider,
adapterType,
config: input.config,
});
}
function reusableLeaseCanBeResumed(input: {
lease: Pick<EnvironmentLease, "status" | "heartbeatRunId">;
heartbeatRunId: string | null;
}): boolean {
if (input.lease.status === "released" || input.lease.status === "retained") return true;
return input.lease.status === "active" && input.heartbeatRunId !== null && input.lease.heartbeatRunId === input.heartbeatRunId;
}
function reusableLeaseCanBeCleanedUp(lease: Pick<EnvironmentLease, "status">): boolean {
return lease.status === "released" || lease.status === "retained";
}
export function findReusableSandboxLeaseId(input: {
config: SandboxEnvironmentConfig;
leases: Array<Pick<EnvironmentLease, "providerLeaseId" | "metadata">>;
}): string | null {
return findReusableSandboxProviderLeaseId(input);
}
function createLocalEnvironmentDriver(db: Db): EnvironmentRuntimeDriver {
const environmentsSvc = environmentService(db);
return {
driver: "local",
async acquireRunLease(input) {
return await environmentsSvc.acquireLease({
companyId: input.companyId,
environmentId: input.environment.id,
executionWorkspaceId: input.executionWorkspaceId,
issueId: input.issueId,
heartbeatRunId: input.heartbeatRunId,
leasePolicy: "ephemeral",
provider: "local",
metadata: {
...(input.agentId ? { agentId: input.agentId } : {}),
driver: input.environment.driver,
executionWorkspaceMode: input.executionWorkspaceMode,
},
});
},
async releaseRunLease(input) {
return await environmentsSvc.releaseLease(input.lease.id, input.status);
},
async realizeWorkspace(input) {
const record = buildWorkspaceRealizationRecordFromDriverInput({
environment: input.environment,
lease: input.lease,
workspace: input.workspace,
cwd: input.workspace.localPath ?? input.workspace.remotePath ?? null,
});
return {
cwd: input.workspace.localPath ?? input.workspace.remotePath ?? "/",
metadata: {
workspaceRealization: record,
},
};
},
};
}
function createSshEnvironmentDriver(db: Db): EnvironmentRuntimeDriver {
const environmentsSvc = environmentService(db);
return {
driver: "ssh",
async acquireRunLease(input) {
const parsed = await resolveEnvironmentDriverConfigForRuntime(db, input.companyId, input.environment, {
issueId: input.issueId,
heartbeatRunId: input.heartbeatRunId,
applyCustomImageTemplate: input.applyCustomImageTemplate ?? false,
});
if (parsed.driver !== "ssh") {
throw new Error(`Expected SSH environment config for driver "${input.environment.driver}".`);
}
const { remoteCwd } = await ensureSshWorkspaceReady(parsed.config);
return await environmentsSvc.acquireLease({
companyId: input.companyId,
environmentId: input.environment.id,
executionWorkspaceId: input.executionWorkspaceId,
issueId: input.issueId,
heartbeatRunId: input.heartbeatRunId,
leasePolicy: "ephemeral",
provider: "ssh",
providerLeaseId: `ssh://${parsed.config.username}@${parsed.config.host}:${parsed.config.port}${remoteCwd}`,
metadata: {
...(input.agentId ? { agentId: input.agentId } : {}),
driver: input.environment.driver,
executionWorkspaceMode: input.executionWorkspaceMode,
host: parsed.config.host,
port: parsed.config.port,
username: parsed.config.username,
remoteWorkspacePath: parsed.config.remoteWorkspacePath,
remoteCwd,
},
});
},
async releaseRunLease(input) {
return await environmentsSvc.releaseLease(input.lease.id, input.status);
},
async realizeWorkspace(input) {
const record = buildWorkspaceRealizationRecordFromDriverInput({
environment: input.environment,
lease: input.lease,
workspace: input.workspace,
cwd:
typeof input.lease.metadata?.remoteCwd === "string" && input.lease.metadata.remoteCwd.trim().length > 0
? input.lease.metadata.remoteCwd.trim()
: input.workspace.remotePath ?? input.workspace.localPath ?? null,
});
return {
cwd: record.remote.path ?? record.local.path,
metadata: {
workspaceRealization: record,
},
};
},
};
}
function createSandboxEnvironmentDriver(
db: Db,
options: {
pluginWorkerManager?: PluginWorkerManager;
pluginWorkerReadyTimeoutMs?: number;
pluginWorkerReadyPollMs?: number;
} = {},
): EnvironmentRuntimeDriver {
// Fall back to the process-scoped manager when a caller did not pass one.
// Every path that dispatches a run funnels through here, so this single
// fallback covers all of them: the six runtime construction sites, and the
// `heartbeatService(db)` calls that pass no options at all (which is how
// `assignment` and `automation` dispatches used to reach a manager-less
// runtime and fail with "sandbox plugin workers are unavailable in this
// server process"). An explicitly passed manager still wins, so tests can
// inject their own.
const pluginWorkerManager = options.pluginWorkerManager ?? getProcessPluginWorkerManager();
const pluginWorkerReadyTimeoutMs = options.pluginWorkerReadyTimeoutMs ?? DEFAULT_PLUGIN_SANDBOX_WORKER_READY_TIMEOUT_MS;
const pluginWorkerReadyPollMs = options.pluginWorkerReadyPollMs ?? DEFAULT_PLUGIN_SANDBOX_WORKER_READY_POLL_MS;
const environmentsSvc = environmentService(db);
async function resolveSandboxProviderPlugin(input: { provider: string }) {
const running = await resolvePluginSandboxProviderDriverByKey({
db,
driverKey: input.provider,
workerManager: pluginWorkerManager,
requireRunning: true,
});
if (running) {
return { state: "running" as const, resolved: running };
}
const installed = await resolvePluginSandboxProviderDriverByKey({
db,
driverKey: input.provider,
workerManager: pluginWorkerManager,
requireRunning: false,
});
if (!installed) {
return { state: "missing" as const, resolved: null };
}
if (installed.plugin.status !== "ready") {
return { state: "not_ready" as const, resolved: installed };
}
if (!pluginWorkerManager) {
return { state: "worker_unavailable" as const, resolved: installed };
}
const deadline = Date.now() + Math.max(0, pluginWorkerReadyTimeoutMs);
while (Date.now() < deadline) {
const retried = await resolvePluginSandboxProviderDriverByKey({
db,
driverKey: input.provider,
workerManager: pluginWorkerManager,
requireRunning: true,
});
if (retried) {
return { state: "running" as const, resolved: retried };
}
await delay(Math.max(1, pluginWorkerReadyPollMs));
}
return { state: "worker_unavailable" as const, resolved: installed };
}
async function resolvePluginSandboxRuntimeConfig(input: {
environment: Environment;
lease: EnvironmentLease;
provider: string;
}): Promise<Record<string, unknown>> {
const metadataConfig = sandboxConfigFromLeaseMetadataLoose(input.lease);
if (metadataConfig && metadataConfig.provider === input.provider) {
const parsed = await resolveEnvironmentDriverConfigForRuntime(db, input.lease.companyId, {
id: input.environment.id,
driver: "sandbox",
config: sandboxConfigForLeaseMetadata(metadataConfig),
});
if (parsed.driver === "sandbox") {
return parsed.config as unknown as Record<string, unknown>;
}
}
if (input.environment.driver === "sandbox") {
try {
const parsed = await resolveEnvironmentDriverConfigForRuntime(
db,
input.lease.companyId,
input.environment,
);
if (parsed.driver === "sandbox" && parsed.config.provider === input.provider) {
return parsed.config as unknown as Record<string, unknown>;
}
} catch {
// Lease metadata below is intentionally kept sufficient for cleanup
// after the environment config changes or becomes invalid.
}
}
return {
provider: input.provider,
...sanitizePluginSandboxConfigFromLeaseMetadata(input.lease.metadata),
};
}
async function cleanupObsoleteReusableSandboxLeases(input: {
environment: Environment;
leases: EnvironmentLease[];
reusableLeases: EnvironmentLease[];
}) {
const reusableIds = new Set(input.reusableLeases.map((lease) => lease.id));
for (const lease of input.leases) {
if (reusableIds.has(lease.id)) continue;
if (!reusableLeaseCanBeCleanedUp(lease)) continue;
await destroyReusableSandboxLease({
environment: input.environment,
lease,
failureReason: "lease_fingerprint_mismatch",
});
}
}
return {
driver: "sandbox",
async acquireRunLease(input) {
const storedParsed = parseEnvironmentDriverConfig(input.environment);
const parsed = await resolveEnvironmentDriverConfigForRuntime(db, input.companyId, input.environment, {
issueId: input.issueId,
heartbeatRunId: input.heartbeatRunId,
applyCustomImageTemplate: input.applyCustomImageTemplate ?? false,
});
if (parsed.driver !== "sandbox" || storedParsed.driver !== "sandbox") {
throw new Error(`Expected sandbox environment config for driver "${input.environment.driver}".`);
}
// Check if this provider should be handled by a plugin.
if (!isBuiltinSandboxProvider(parsed.config.provider)) {
const pluginProvider = await resolveSandboxProviderPlugin({
provider: parsed.config.provider,
});
if (pluginProvider.state === "missing") {
throw new Error(
`Sandbox provider "${parsed.config.provider}" is not registered as a built-in provider and no matching plugin is available.`,
);
}
if (pluginProvider.state === "not_ready") {
throw new Error(
`Sandbox provider "${parsed.config.provider}" is installed via plugin "${pluginProvider.resolved.plugin.pluginKey}", but that plugin is currently ${pluginProvider.resolved.plugin.status}.`,
);
}
// Check the wiring before the worker state. A server process with no
// plugin worker manager can never see a running worker, so reporting it
// as "worker is not running" sends debugging after a healthy worker
// instead of the missing dependency.
if (!pluginWorkerManager) {
throw new Error(
`Sandbox provider "${parsed.config.provider}" is installed, but sandbox plugin workers are unavailable in this server process.`,
);
}
if (pluginProvider.state === "worker_unavailable") {
throw new Error(
`Sandbox provider "${parsed.config.provider}" is installed via plugin "${pluginProvider.resolved.plugin.pluginKey}", but its worker is not running.`,
);
}
const workerConfig = stripSandboxProviderEnvelope(parsed.config);
const storedConfig = storedParsed.config;
const providerConfigForLease = sandboxConfigForLeaseMetadata(storedConfig);
const supportsReusableLeases = pluginProvider.resolved.driver.supportsReusableLeases === true;
const leaseFingerprint =
supportsReusableLeases &&
parsed.config.reuseLease &&
input.heartbeatRunId !== null &&
input.executionWorkspaceId !== null &&
input.agentId !== null
? await buildReusableSandboxLeaseFingerprint({
db,
companyId: input.companyId,
environment: input.environment,
executionWorkspaceId: input.executionWorkspaceId,
agentId: input.agentId,
adapterType: input.adapterType,
provider: parsed.config.provider,
providerConfig: providerConfigForLease,
providerPlugin: {
id: pluginProvider.resolved.plugin.id,
pluginKey: pluginProvider.resolved.plugin.pluginKey,
packageName: pluginProvider.resolved.plugin.packageName,
version: pluginProvider.resolved.plugin.version,
},
})
: null;
// Ad-hoc tests (heartbeatRunId === null) must never resume an existing
// provider lease. If they did, releasing the test lease at the end of
// the probe would tear down the live heartbeat run that owns it.
// We also filter out leases whose policy is not reuse_by_environment
// and whose status is not reusable so non-reusable, cleanup-pending,
// or terminal rows cannot be matched.
const reusableCandidateLeases =
supportsReusableLeases &&
parsed.config.reuseLease &&
input.heartbeatRunId !== null &&
input.executionWorkspaceId !== null &&
input.agentId !== null
? (await environmentsSvc.listLeases(input.environment.id))
.filter((lease) =>
lease.leasePolicy === "reuse_by_environment" &&
reusableLeaseCanBeResumed({ lease, heartbeatRunId: input.heartbeatRunId }) &&
lease.executionWorkspaceId === input.executionWorkspaceId &&
lease.metadata?.agentId === input.agentId,
)
: [];
// Hoisted out of the filter: whether this environment references any
// secrets gates the secret-blind legacy runtime fallback below. One DB
// read per acquire, never per candidate lease.
const environmentHasSecretRefs =
reusableCandidateLeases.length > 0
? (await collectEnvironmentSecretRefs({ db, environment: input.environment })).length > 0
: false;
const reusableExistingLeases = reusableCandidateLeases.filter((lease) =>
reusableSandboxLeaseScopeMatches({
lease,
companyId: input.companyId,
environmentId: input.environment.id,
executionWorkspaceId: input.executionWorkspaceId,
agentId: input.agentId,
adapterType: input.adapterType,
provider: parsed.config.provider,
config: providerConfigForLease,
leaseFingerprint,
environmentHasSecretRefs,
allowLegacyRuntimeFingerprint:
lease.status === "active" &&
input.heartbeatRunId !== null &&
lease.heartbeatRunId === input.heartbeatRunId,
}),
);
if (reusableCandidateLeases.length > reusableExistingLeases.length) {
await cleanupObsoleteReusableSandboxLeases({
environment: input.environment,
leases: reusableCandidateLeases,
reusableLeases: reusableExistingLeases,
});
}
const reusableProviderLeaseId =
supportsReusableLeases &&
parsed.config.reuseLease &&
input.heartbeatRunId !== null &&
input.executionWorkspaceId !== null &&
input.agentId !== null
? findReusableSandboxLeaseId({ config: storedConfig, leases: reusableExistingLeases })
: null;
const reusableLease = reusableProviderLeaseId
? reusableExistingLeases.find((lease) => lease.providerLeaseId === reusableProviderLeaseId)
: null;
let providerLease: PluginEnvironmentLease | null = null;
if (reusableLease?.providerLeaseId) {
try {
const resumed = await pluginWorkerManager.call(
pluginProvider.resolved.plugin.id,
"environmentResumeLease",
{
driverKey: parsed.config.provider,
companyId: input.companyId,
environmentId: input.environment.id,
issueId: input.issueId,
config: workerConfig,
providerLeaseId: reusableLease.providerLeaseId,
leaseMetadata: reusableLease.metadata ?? undefined,
},
resolvePluginSandboxRpcTimeoutMs(workerConfig),
);