-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathisolation-manager.js
More file actions
2046 lines (1804 loc) · 66 KB
/
Copy pathisolation-manager.js
File metadata and controls
2046 lines (1804 loc) · 66 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
/**
* IsolationManager - Docker container lifecycle for isolated cluster execution
*
* Handles:
* - Container creation with workspace mounts
* - Credential injection for provider CLIs
* - Command execution inside containers
* - Container cleanup on stop/kill
*/
const { spawn, spawnSync } = require('child_process');
const { Worker } = require('worker_threads');
const crypto = require('crypto');
const path = require('path');
const os = require('os');
const fs = require('fs');
const { loadSettings } = require('../lib/settings');
const { CLAUDE_AUTH_ENV_VARS, resolveClaudeAuth } = require('../lib/settings/claude-auth');
const { normalizeProviderName, getProviderMetadata } = require('../lib/provider-names');
const {
MOUNT_PRESETS,
resolveMounts,
resolveEnvs,
expandEnvPatterns,
} = require('../lib/docker-config');
const { getProvider } = require('./providers');
const { readRepoSettings } = require('../lib/repo-settings');
const { provisionClaudeCredentials } = require('./claude-credentials');
const DEFAULT_WORKTREE_SETUP_TIMEOUT_MS = 15 * 60 * 1000;
const FRESH_BASE_REF_PREFIX = 'refs/zeroshot/base-fetch';
function runSync(command, args, options = {}) {
const timeout = options.timeout ?? 30000;
const result = spawnSync(command, args, { ...options, timeout });
if (result.status !== 0 || result.error) {
const detail = result.error?.message || result.stderr?.toString() || 'no stderr';
const error = new Error(
`Command ${command} failed with status ${result.status ?? 'null'}: ${detail}`
);
error.status = result.status;
error.stderr = result.stderr?.toString();
throw error;
}
return result.stdout?.toString() || '';
}
function runShellSync(command, options = {}) {
return runSync('/bin/bash', ['-lc', command], options);
}
function resolveCommit(repoRoot, ref) {
return runSync('git', ['rev-parse', '--verify', `${ref}^{commit}`], {
cwd: repoRoot,
encoding: 'utf8',
stdio: 'pipe',
}).trim();
}
function deleteTemporaryBaseRef(repoRoot, temporaryRef) {
try {
runSync('git', ['update-ref', '-d', temporaryRef], {
cwd: repoRoot,
encoding: 'utf8',
stdio: 'pipe',
});
} catch (err) {
console.warn(
`[IsolationManager] Warning: failed to remove temporary base ref ${temporaryRef}: ${err.message}`
);
}
}
function fetchFreshRemoteBase(repoRoot, remoteName, branch) {
const temporaryRef = `${FRESH_BASE_REF_PREFIX}/${crypto.randomBytes(16).toString('hex')}`;
try {
runSync(
'git',
[
'fetch',
'--atomic',
'--no-tags',
'--no-write-fetch-head',
'--refmap=',
'--',
remoteName,
`+refs/heads/${branch}:${temporaryRef}`,
],
{
cwd: repoRoot,
encoding: 'utf8',
stdio: 'pipe',
}
);
return {
baseSha: resolveCommit(repoRoot, temporaryRef),
temporaryRef,
};
} catch (err) {
deleteTemporaryBaseRef(repoRoot, temporaryRef);
throw err;
}
}
function expandHomePath(value) {
if (!value) return value;
if (value === '~') return os.homedir();
return value.replace(/^~(?=\/|$)/, os.homedir());
}
function pathContains(base, target) {
const resolvedBase = path.resolve(base);
const resolvedTarget = path.resolve(target);
if (resolvedBase === resolvedTarget) return true;
return resolvedTarget.startsWith(resolvedBase + path.sep);
}
function parsePositiveInteger(value, fieldName) {
if (value === undefined || value === null || value === '') {
return null;
}
if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) {
return value;
}
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
const parsed = Number.parseInt(value.trim(), 10);
if (Number.isSafeInteger(parsed) && parsed > 0) {
return parsed;
}
}
throw new Error(`${fieldName} must be a positive integer number of milliseconds`);
}
function resolveWorktreeSetupTimeoutMs(repoSettings = {}, options = {}) {
const candidates = [
{ value: options.worktreeSetupTimeoutMs, field: 'options.worktreeSetupTimeoutMs' },
{ value: options.setupTimeoutMs, field: 'options.setupTimeoutMs' },
{
value: process.env.ZEROSHOT_WORKTREE_SETUP_TIMEOUT_MS,
field: 'ZEROSHOT_WORKTREE_SETUP_TIMEOUT_MS',
},
{ value: repoSettings.worktree?.setupTimeoutMs, field: 'worktree.setupTimeoutMs' },
];
for (const candidate of candidates) {
const parsed = parsePositiveInteger(candidate.value, candidate.field);
if (parsed !== null) {
return parsed;
}
}
return DEFAULT_WORKTREE_SETUP_TIMEOUT_MS;
}
const DEFAULT_IMAGE = 'zeroshot-cluster-base';
/**
* Shell command that installs a provider's CLI inside the cluster image, or null when the
* provider is baked into the base image (e.g. Claude) or has no single-command installer.
* Sourced from the provider registry (docker.install) so nothing here is provider-specific.
* @param {string} providerName
* @returns {string|null}
*/
function providerDockerInstall(providerName) {
if (!providerName) return null;
try {
const metadata = getProviderMetadata(providerName);
const install = metadata && metadata.docker && metadata.docker.install;
return typeof install === 'string' && install.trim() ? install.trim() : null;
} catch {
return null;
}
}
/**
* Subpaths (relative to the provider's mount container path) that must stay writable at runtime
* even though the credential mount itself is read-only. Sourced from the provider registry
* (docker.writableState) so nothing here is provider-specific.
* @param {string} providerName
* @returns {string[]}
*/
function providerWritableState(providerName) {
if (!providerName) return [];
try {
const metadata = getProviderMetadata(providerName);
const writableState = metadata && metadata.docker && metadata.docker.writableState;
return Array.isArray(writableState) ? writableState : [];
} catch {
return [];
}
}
class IsolationManager {
constructor(options = {}) {
this.image = options.image || DEFAULT_IMAGE;
this.containers = new Map(); // clusterId -> containerId
this.isolatedDirs = new Map(); // clusterId -> { path, originalDir }
this.clusterConfigDirs = new Map(); // clusterId -> configDirPath
this.worktrees = new Map(); // clusterId -> { path, branch, repoRoot, baseRef, baseSha }
this._exitWatchers = new Map(); // clusterId -> ChildProcess
}
/**
* Get GitHub token from gh CLI config (hosts.yml)
* Works with older gh CLI versions that don't have `gh auth token` command
* @returns {string|null}
* @private
*/
_getGhToken() {
try {
const hostsPath = path.join(os.homedir(), '.config', 'gh', 'hosts.yml');
if (!fs.existsSync(hostsPath)) return null;
const content = fs.readFileSync(hostsPath, 'utf8');
// Match oauth_token: <token> in YAML
const match = content.match(/oauth_token:\s*(\S+)/);
return match ? match[1] : null;
} catch {
return null;
}
}
/**
* Create and start a container for a cluster
* @param {string} clusterId - Cluster ID
* @param {object} config - Container config
* @param {string} config.workDir - Working directory to mount
* @param {string} [config.image] - Docker image (default: zeroshot-cluster-base)
* @param {boolean} [config.reuseExistingWorkspace=false] - If true, reuse existing isolated workspace (for resume)
* @param {Array<string|object>} [config.mounts] - Override default mounts (preset names or {host, container, readonly})
* @param {boolean} [config.noMounts=false] - Disable all credential mounts
* @param {string} [config.provider] - Provider name for credential warnings
* @returns {Promise<string>} Container ID
*/
async createContainer(clusterId, config) {
const image = config.image || this.image;
let workDir = config.workDir || process.cwd();
const containerName = `zeroshot-cluster-${clusterId}`;
const reuseExisting = config.reuseExistingWorkspace || false;
const runningContainerId = this._getRunningContainerId(clusterId);
if (runningContainerId) {
return runningContainerId;
}
this._removeContainerByName(containerName);
workDir = await this._prepareIsolatedWorkspace(clusterId, workDir, reuseExisting);
const settings = loadSettings();
const providerName = normalizeProviderName(
config.provider || settings.defaultProvider || 'claude'
);
const containerHome = config.containerHome || settings.dockerContainerHome || '/root';
const clusterConfigDir = this._createClusterConfigDir(clusterId, containerHome);
console.log(`[IsolationManager] Created cluster config dir at ${clusterConfigDir}`);
const args = this._buildBaseDockerArgs({
containerName,
workDir,
containerHome,
clusterConfigDir,
});
const mountedHosts = this._applyCredentialMounts(
args,
config,
settings,
containerHome,
providerName
);
this._applyProviderStateMounts(args, config, clusterId, containerHome, providerName);
this._warnMissingProviderCredentials(providerName, mountedHosts, config, containerHome);
args.push('-w', '/workspace', image, 'tail', '-f', '/dev/null');
const containerId = await this._spawnContainer(clusterId, args, workDir);
this._watchContainerExit(clusterId, containerId, config.onExit);
return containerId;
}
_watchContainerExit(clusterId, containerId, onExit) {
if (typeof onExit !== 'function') {
return;
}
const existing = this._exitWatchers.get(clusterId);
if (existing) {
try {
existing.kill('SIGKILL');
} catch {
// Ignore
}
this._exitWatchers.delete(clusterId);
}
const proc = spawn('docker', ['wait', containerId], { stdio: ['ignore', 'pipe', 'ignore'] });
this._exitWatchers.set(clusterId, proc);
let stdout = '';
proc.stdout.on('data', (data) => {
stdout += data.toString();
});
const finalize = () => {
if (this._exitWatchers.get(clusterId) === proc) {
this._exitWatchers.delete(clusterId);
}
const code = parseInt(stdout.trim(), 10);
onExit({ clusterId, containerId, exitCode: Number.isFinite(code) ? code : null });
};
proc.on('close', finalize);
proc.on('error', finalize);
}
_getRunningContainerId(clusterId) {
const existingId = this.containers.get(clusterId);
if (!existingId) {
return null;
}
return this._isContainerRunning(existingId) ? existingId : null;
}
async _prepareIsolatedWorkspace(clusterId, workDir, reuseExisting) {
if (!this._isGitRepo(workDir)) {
return workDir;
}
this.isolatedDirs = this.isolatedDirs || new Map();
const isolatedPath = path.join(os.tmpdir(), 'zeroshot-isolated', clusterId);
if (reuseExisting && fs.existsSync(isolatedPath)) {
console.log(`[IsolationManager] Reusing existing isolated workspace at ${isolatedPath}`);
this.isolatedDirs.set(clusterId, {
path: isolatedPath,
originalDir: workDir,
});
return isolatedPath;
}
const isolatedDir = await this._createIsolatedCopy(clusterId, workDir);
this.isolatedDirs.set(clusterId, {
path: isolatedDir,
originalDir: workDir,
});
console.log(`[IsolationManager] Created isolated copy at ${isolatedDir}`);
return isolatedDir;
}
_buildBaseDockerArgs({ containerName, workDir, containerHome, clusterConfigDir }) {
return [
'run',
'-d',
'--name',
containerName,
'-v',
`${workDir}:/workspace`,
'-v',
'/var/run/docker.sock:/var/run/docker.sock',
'--group-add',
this._getDockerGid(),
'-v',
`${clusterConfigDir}:${containerHome}/.claude`,
];
}
_resolveMountConfig(config, settings) {
if (config.mounts) {
return config.mounts;
}
if (process.env.ZEROSHOT_DOCKER_MOUNTS) {
try {
return JSON.parse(process.env.ZEROSHOT_DOCKER_MOUNTS);
} catch {
console.warn('[IsolationManager] Invalid ZEROSHOT_DOCKER_MOUNTS JSON, using settings');
return settings.dockerMounts;
}
}
return settings.dockerMounts;
}
// Auto-activate the running provider's own credential preset (mount + env) so `--docker` works
// without listing it in dockerMounts. Claude is mounted separately, so skip it.
_withActiveProviderPreset(mountConfig, providerName) {
if (!providerName || providerName === 'claude') return mountConfig;
if (!MOUNT_PRESETS[providerName]) return mountConfig;
if (mountConfig.some((item) => item === providerName)) return mountConfig;
return [...mountConfig, providerName];
}
_applyCredentialMounts(args, config, settings, containerHome, providerName) {
const mountedHosts = [];
if (config.noMounts) {
return mountedHosts;
}
const mountConfig = this._withActiveProviderPreset(
this._resolveMountConfig(config, settings),
providerName
);
const mounts = resolveMounts(mountConfig, { containerHome });
const claudeContainerPath = path.posix.join(containerHome, '.claude');
for (const mount of mounts) {
if (mount.container === claudeContainerPath) {
console.warn(
`[IsolationManager] Skipping mount for ${mount.host} -> ${mount.container} ` +
'(Claude config is managed by zeroshot).'
);
continue;
}
const hostPath = expandHomePath(mount.host);
try {
const stat = fs.statSync(hostPath);
if (hostPath.endsWith('config') && !stat.isFile()) {
continue;
}
} catch {
continue;
}
const mountSpec = mount.readonly
? `${hostPath}:${mount.container}:ro`
: `${hostPath}:${mount.container}`;
args.push('-v', mountSpec);
mountedHosts.push(hostPath);
}
const envToPass = this._collectDockerEnvVars(mountConfig, settings);
for (const [key, value] of Object.entries(envToPass)) {
args.push('-e', `${key}=${value}`);
}
return mountedHosts;
}
_collectDockerEnvVars(mountConfig, settings) {
const envToPass = {};
const envSpecs = expandEnvPatterns(resolveEnvs(mountConfig, settings.dockerEnvPassthrough));
for (const spec of envSpecs) {
if (spec.forced) {
envToPass[spec.name] = spec.value;
} else if (process.env[spec.name]) {
envToPass[spec.name] = process.env[spec.name];
}
}
for (const envVar of CLAUDE_AUTH_ENV_VARS) {
if (process.env[envVar]) {
envToPass[envVar] = process.env[envVar];
}
}
const authEnv = resolveClaudeAuth(settings);
for (const [key, value] of Object.entries(authEnv)) {
if (!(key in envToPass)) {
envToPass[key] = value;
}
}
return envToPass;
}
/**
* Mount writable state dirs (sessions, native addon caches, logs, ...) nested inside a
* provider's otherwise read-only credential mount. Docker sorts bind mounts by destination
* depth, so these apply on top of the read-only `mount` from `_applyCredentialMounts`.
* @private
* @param {string[]} args - Docker argv being built (mutated in place)
* @param {object} config - Container config (respects config.noMounts)
* @param {string} clusterId - Cluster ID (host state dir is scoped per cluster+provider)
* @param {string} containerHome - Container home directory for $HOME expansion
* @param {string} providerName - Active provider name
* @returns {string[]} Host directories created for writable state
*/
_applyProviderStateMounts(args, config, clusterId, containerHome, providerName) {
if (config.noMounts) return [];
const writableState = providerWritableState(providerName);
if (writableState.length === 0) return [];
const preset = MOUNT_PRESETS[providerName];
if (!preset) return [];
const containerRoot = resolveMounts([providerName], { containerHome })[0].container;
const hostRoot = path.join(os.tmpdir(), 'zeroshot-provider-state', clusterId, providerName);
fs.rmSync(hostRoot, { recursive: true, force: true });
// Ancestor path components (the shared `zeroshot-provider-state` root, the per-cluster and
// per-provider dirs) get ordinary default permissions — they hold no data themselves, only
// need to stay traversable so a different host user's own clusterId subtree isn't blocked.
fs.mkdirSync(hostRoot, { recursive: true });
const hostDirs = [];
for (const sub of writableState) {
const hostSub = path.join(hostRoot, sub);
// os.tmpdir() (e.g. /tmp) is shared by every local user on the host, and these leaf dirs are
// bind-mounted writable into the container — so, unlike their ancestors, they must stay
// owner-only (0o700), never widened to group/other access. Widening would let any local
// user plant a file the container's provider process (e.g. a native addon OMP loads on
// startup) then executes, alongside its forwarded credential env vars. Mode is passed
// explicitly (not left to the process umask) so it's deterministically owner-only
// regardless of host umask configuration.
fs.mkdirSync(hostSub, { mode: 0o700 });
hostDirs.push(hostSub);
args.push('-v', `${hostSub}:${path.posix.join(containerRoot, sub)}`);
}
return hostDirs;
}
_warnMissingProviderCredentials(providerName, mountedHosts, config, containerHome) {
if (providerName === 'claude') {
return;
}
const metadata = getProviderMetadata(providerName);
const provider = getProvider(providerName);
// An env token (e.g. COPILOT_GITHUB_TOKEN) is a complete credential on its own.
const credentialEnvKeys = metadata.credentialEnvKeys || [];
if (credentialEnvKeys.some((key) => process.env[key])) {
return;
}
// A mount only counts if it carries the secret (credentialInMount !== false).
const credentialInMount = metadata.docker && metadata.docker.credentialInMount === false;
const credentialPaths = provider.getCredentialPaths ? provider.getCredentialPaths() : [];
const expandedCreds = credentialPaths.map((cred) => expandHomePath(cred));
const hasCredentialMount =
!credentialInMount &&
mountedHosts.some((hostPath) =>
expandedCreds.some(
(credPath) => pathContains(hostPath, credPath) || pathContains(credPath, hostPath)
)
);
if (hasCredentialMount) {
return;
}
if (credentialInMount && credentialEnvKeys.length > 0) {
console.warn(
`[IsolationManager] ⚠️ ${provider.displayName} could not find credentials for Docker. ` +
`Its login token is not stored in a mountable file — export one of ` +
`${credentialEnvKeys.join(', ')} before running with --docker.`
);
return;
}
if (expandedCreds.length > 0) {
const exampleHost = credentialPaths[0];
const exampleContainer = exampleHost.replace(/^~(?=\/|$)/, containerHome);
const mountNote = config.noMounts ? 'Credential mounts are disabled. ' : '';
console.warn(
`[IsolationManager] ⚠️ ${mountNote}No credential mounts found for ${provider.displayName}. ` +
`Add one with --mount ${exampleHost}:${exampleContainer}:ro`
);
}
}
_spawnContainer(clusterId, args, workDir) {
return new Promise((resolve, reject) => {
const proc = spawn('docker', args, { stdio: ['pipe', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
proc.stdout.on('data', (data) => {
stdout += data;
});
proc.stderr.on('data', (data) => {
stderr += data;
});
proc.on('close', async (code) => {
if (code !== 0) {
reject(new Error(`Failed to create container: ${stderr}`));
return;
}
const containerId = stdout.trim().substring(0, 12);
this.containers.set(clusterId, containerId);
try {
console.log(`[IsolationManager] Checking for package.json in ${workDir}...`);
if (fs.existsSync(path.join(workDir, 'package.json'))) {
await this._installDependenciesWithRetry(clusterId);
}
} catch (err) {
console.warn(
`[IsolationManager] ⚠️ Failed to install dependencies (non-fatal): ${err.message}`
);
}
resolve(containerId);
});
proc.on('error', (err) => {
reject(new Error(`Docker spawn error: ${err.message}`));
});
});
}
async _installDependenciesWithRetry(clusterId) {
console.log(`[IsolationManager] Installing npm dependencies in container...`);
const maxRetries = 3;
const baseDelay = 2000; // 2 seconds
const installCommand = [
'sh',
'-c',
[
'if [ -d node_modules ] && [ -f node_modules/.package-lock.json ]; then',
'echo "__deps_present__";',
'exit 0;',
'fi;',
'if ! command -v npm >/dev/null 2>&1; then',
'echo "__npm_missing__";',
'exit 127;',
'fi;',
'if [ -d /pre-baked-deps/node_modules ]; then',
'cp -rn /pre-baked-deps/node_modules . 2>/dev/null || true;',
'npm_config_engine_strict=false npm install --no-audit --no-fund --prefer-offline;',
'install_code=$?;',
'if [ $install_code -ne 0 ]; then',
'rm -rf node_modules;',
'npm_config_engine_strict=false npm install --no-audit --no-fund;',
'fi;',
'else',
'npm_config_engine_strict=false npm install --no-audit --no-fund;',
'fi',
].join(' '),
];
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const installResult = await this.execInContainer(clusterId, installCommand, {});
const stdout = installResult.stdout || '';
if (installResult.code === 0) {
if (stdout.includes('__deps_present__')) {
console.log(
`[IsolationManager] ✓ Dependencies already installed (skipping npm install)`
);
} else {
console.log(`[IsolationManager] ✓ Dependencies installed`);
}
return;
}
const errorOutput = (installResult.stderr || installResult.stdout || '').slice(0, 500);
if (attempt < maxRetries) {
const delay = baseDelay * Math.pow(2, attempt - 1);
console.warn(
`[IsolationManager] ⚠️ npm install failed (attempt ${attempt}/${maxRetries}), retrying in ${delay}ms...`
);
console.warn(`[IsolationManager] Error: ${errorOutput}`);
await new Promise((resolve) => setTimeout(resolve, delay));
} else {
console.warn(
`[IsolationManager] ⚠️ npm install failed after ${maxRetries} attempts (non-fatal): ${errorOutput}`
);
}
} catch (execErr) {
if (attempt < maxRetries) {
const delay = baseDelay * Math.pow(2, attempt - 1);
console.warn(
`[IsolationManager] ⚠️ npm install execution error (attempt ${attempt}/${maxRetries}), retrying in ${delay}ms...`
);
console.warn(`[IsolationManager] Error: ${execErr.message}`);
await new Promise((resolve) => setTimeout(resolve, delay));
} else {
throw execErr;
}
}
}
}
/**
* Execute a command inside the container
* @param {string} clusterId - Cluster ID
* @param {string[]} command - Command and arguments
* @param {object} [options] - Exec options
* @param {boolean} [options.interactive] - Use -it flags
* @param {object} [options.env] - Environment variables
* @param {number} [options.timeout=30000] - Timeout in ms (0 = no timeout). Prevents infinite hangs.
* @returns {Promise<{stdout: string, stderr: string, code: number}>}
*/
execInContainer(clusterId, command, options = {}) {
const containerId = this.containers.get(clusterId);
if (!containerId) {
throw new Error(`No container found for cluster ${clusterId}`);
}
const args = ['exec'];
if (options.interactive) {
args.push('-it');
}
// Add environment variables
if (options.env) {
for (const [key, value] of Object.entries(options.env)) {
args.push('-e', `${key}=${value}`);
}
}
args.push(containerId, ...command);
// Default timeout: 30 seconds (prevents infinite hangs)
const timeout = options.timeout ?? 30000;
return new Promise((resolve, reject) => {
const proc = spawn('docker', args, {
stdio: options.interactive ? 'inherit' : ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
let timedOut = false;
let timeoutId = null;
// Set up timeout if specified (0 = no timeout)
if (timeout > 0) {
timeoutId = setTimeout(() => {
timedOut = true;
proc.kill('SIGKILL');
}, timeout);
}
if (!options.interactive) {
proc.stdout.on('data', (data) => {
stdout += data;
});
proc.stderr.on('data', (data) => {
stderr += data;
});
}
proc.on('close', (code) => {
if (timeoutId) clearTimeout(timeoutId);
if (timedOut) {
reject(new Error(`Docker exec timed out after ${timeout}ms`));
} else {
resolve({ stdout, stderr, code });
}
});
proc.on('error', (err) => {
if (timeoutId) clearTimeout(timeoutId);
reject(new Error(`Docker exec error: ${err.message}`));
});
});
}
async getContainerEnvironmentValue(clusterId, name) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
throw new Error(`Invalid container environment variable name: ${name}`);
}
const result = await this.execInContainer(clusterId, ['printenv', name]);
if (result.code === 1) return null;
if (result.code !== 0) {
throw new Error(
`Failed to read container environment variable ${name}: ${
result.stderr || `exit ${result.code}`
}`
);
}
return result.stdout.replace(/\r?\n$/, '');
}
/**
* Spawn a PTY-like process inside the container
* Returns a child process that can be used like a PTY
* @param {string} clusterId - Cluster ID
* @param {string[]} command - Command and arguments
* @param {object} [options] - Spawn options
* @returns {ChildProcess}
*/
spawnInContainer(clusterId, command, options = {}) {
const containerId = this.containers.get(clusterId);
if (!containerId) {
throw new Error(`No container found for cluster ${clusterId}`);
}
// IMPORTANT: Must use -i flag for interactive stdin/stdout communication with commands like 'cat'
// If omitted, docker exec will not properly connect stdin, causing piped input to be ignored
// This is required for PTY-like behavior where child process stdin/stdout are used
const args = ['exec', '-i'];
// Add environment variables
if (options.env) {
for (const [key, value] of Object.entries(options.env)) {
args.push('-e', `${key}=${value}`);
}
}
args.push(containerId, ...command);
// spawn() throws on null bytes in argv; strip them before they get there.
const safeArgs = args.map((arg) => (typeof arg === 'string' ? arg.replace(/\0/g, '') : arg));
return spawn('docker', safeArgs, {
stdio: ['pipe', 'pipe', 'pipe'],
...options.spawnOptions,
});
}
/**
* Stop a container
* @param {string} clusterId - Cluster ID
* @param {number} [timeout=10] - Timeout in seconds before SIGKILL
* @returns {Promise<void>}
*/
stopContainer(clusterId, timeout = 10, explicitContainerId = null) {
// Use explicit containerId (from restored state) or in-memory Map
const containerId = explicitContainerId || this.containers.get(clusterId);
if (!containerId) {
return; // Already stopped or never started
}
return new Promise((resolve) => {
const proc = spawn('docker', ['stop', '-t', String(timeout), containerId], {
stdio: ['pipe', 'pipe', 'pipe'],
});
proc.on('close', () => {
resolve();
});
proc.on('error', () => {
resolve(); // Ignore errors on stop
});
});
}
/**
* Remove a container
* @param {string} clusterId - Cluster ID
* @param {boolean} [force=false] - Force remove running container
* @returns {Promise<void>}
*/
removeContainer(clusterId, force = false, explicitContainerId = null) {
// Use explicit containerId (from restored state) or in-memory Map
const containerId = explicitContainerId || this.containers.get(clusterId);
if (!containerId) {
return;
}
const args = ['rm'];
if (force) {
args.push('-f');
}
args.push(containerId);
return new Promise((resolve) => {
const proc = spawn('docker', args, {
stdio: ['pipe', 'pipe', 'pipe'],
});
proc.on('close', () => {
this.containers.delete(clusterId);
resolve();
});
proc.on('error', () => {
this.containers.delete(clusterId);
resolve();
});
});
}
/**
* Stop and remove a container, and optionally clean up isolated dir/config
* @param {string} clusterId - Cluster ID
* @param {object} [options] - Cleanup options
* @param {boolean} [options.preserveWorkspace=false] - If true, keep the isolated workspace (for resume capability)
* @returns {Promise<void>}
*/
async cleanup(clusterId, options = {}) {
const preserveWorkspace = options.preserveWorkspace || false;
await this.stopContainer(clusterId);
await this.removeContainer(clusterId);
// Clean up isolated directory if one was created (unless preserveWorkspace is set)
if (this.isolatedDirs?.has(clusterId)) {
const isolatedInfo = this.isolatedDirs.get(clusterId);
if (preserveWorkspace) {
console.log(
`[IsolationManager] Preserving isolated workspace at ${isolatedInfo.path} for resume`
);
// Don't delete - but DON'T remove from Map either, resume() needs it
} else {
console.log(`[IsolationManager] Cleaning up isolated dir at ${isolatedInfo.path}`);
// Preserve Terraform state before deleting isolated directory
this._preserveTerraformState(clusterId, isolatedInfo.path);
// Remove the isolated directory
try {
fs.rmSync(isolatedInfo.path, { recursive: true, force: true });
} catch {
// Ignore
}
this.isolatedDirs.delete(clusterId);
}
}
// Clean up cluster config dir (always - it's recreated on resume)
this._cleanupClusterConfigDir(clusterId);
// Clean up provider writable-state dirs (always - the container that mounted them is gone,
// and _applyProviderStateMounts recreates them fresh on the next createContainer call).
this._cleanupProviderStateDirs(clusterId);
}
/**
* Remove the writable-state host directories a provider's Docker mounts created for this
* cluster (see `_applyProviderStateMounts`). Without this, every `--docker` run with a
* provider that declares `docker.writableState` (e.g. OMP) leaks a directory under
* `os.tmpdir()` per cluster, since each clusterId is unique and nothing else ever removes it.
* @private
* @param {string} clusterId - Cluster ID
*/
_cleanupProviderStateDirs(clusterId) {
const root = path.join(os.tmpdir(), 'zeroshot-provider-state', clusterId);
try {
fs.rmSync(root, { recursive: true, force: true });
} catch {
// Ignore
}
}
/**
* Create an isolated copy of a directory with fresh git repo
* @private
* @param {string} clusterId - Cluster ID
* @param {string} sourceDir - Source directory to copy
* @returns {Promise<string>} Path to isolated directory
*/
async _createIsolatedCopy(clusterId, sourceDir) {
const isolatedPath = path.join(os.tmpdir(), 'zeroshot-isolated', clusterId);
// Clean up existing dir
if (fs.existsSync(isolatedPath)) {
fs.rmSync(isolatedPath, { recursive: true, force: true });
}
// Create directory
fs.mkdirSync(isolatedPath, { recursive: true });
// Copy files (excluding .git and common build artifacts)
await this._copyDirExcluding(sourceDir, isolatedPath, [
'.git',
'node_modules',
'.next',
'dist',
'build',
'__pycache__',
'.pytest_cache',
'.mypy_cache',
'.ruff_cache',
'.venv',
'venv',
'.tox',
'.eggs',
'*.egg-info',
'coverage',
'.coverage',
'.nyc_output',
'.DS_Store',
'Thumbs.db',
]);
// Get remote URL from original repo (for PR creation)
let remoteUrl = null;
try {
remoteUrl = runSync('git', ['remote', 'get-url', 'origin'], {
cwd: sourceDir,
encoding: 'utf8',
stdio: 'pipe',
}).trim();
} catch {
// No remote configured in source
}
// Initialize fresh git repo with all setup in a single batched command