-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpcoder.cjs
More file actions
executable file
·1180 lines (1042 loc) · 34.7 KB
/
pcoder.cjs
File metadata and controls
executable file
·1180 lines (1042 loc) · 34.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
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
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const cp = require('child_process');
const crypto = require('crypto');
const repoRoot = path.resolve(__dirname, '..');
const stateDir = path.join(repoRoot, 'state');
const settingsPath = path.join(stateDir, 'settings.json');
const authStateRoot = path.join(stateDir, 'auth');
const vmManifestPath = path.join(repoRoot, 'runtime', 'linux', 'vm-manifest.json');
const vmStateDir = path.join(repoRoot, 'state', 'vm');
const vmSshPortPath = path.join(vmStateDir, 'ssh-port.txt');
const runModeValues = new Set(['linux-portable', 'host-native', 'linux-wsl']);
const windowsDefaultModeValues = new Set(['linux-portable', 'host-native']);
const authModeValues = new Set(['oauth', 'api']);
function main(argv) {
const [command, ...rest] = argv;
switch (command) {
case 'doctor':
commandDoctor();
return;
case 'setup':
commandSetup(rest);
return;
case 'auth':
commandAuth(rest);
return;
case 'runtime':
commandRuntime(rest);
return;
case 'run':
commandRun(rest);
return;
case 'help':
case '--help':
case '-h':
printHelp();
return;
case undefined:
// No args: launch Claude in current directory (host-native)
commandRun([]);
return;
default:
// Pass unrecognized first argument (and remaining args) directly to claude.
// This allows patterns like `pcoder --resume` or `pcoder --print "hello"`.
// If you mistyped a command (e.g. 'pcoder doctro'), claude will receive it as an arg.
commandRun([command, ...rest]);
}
}
function printHelp() {
console.log('Portable Claude Code Launcher');
console.log('');
console.log('Usage:');
console.log(' pcoder Launch Claude Code in current directory');
console.log(' pcoder [-- <claude args...>] Launch Claude Code with extra args');
console.log(' pcoder doctor Check environment health');
console.log(' pcoder setup [--init] Initialize or show settings');
console.log(' [--claude-auth <oauth|api>]');
console.log(' [--windows-mode <linux-portable|host-native>]');
console.log(' [--sync-back <true|false>]');
console.log(' [--show]');
console.log(' pcoder auth status Show auth status');
console.log(' pcoder auth login Log in via OAuth');
console.log(' pcoder auth logout Log out');
console.log(' pcoder runtime probe Probe available runtimes');
console.log(' pcoder runtime bootstrap Download/install Windows VM runtime');
console.log(' pcoder run [--mode <linux-portable|host-native>]');
console.log(' [--project <path>] [--no-sync-back] [-- <claude args...>]');
console.log('');
console.log('Auth modes:');
console.log(' oauth - use Claude OAuth login (default, credentials stored portably)');
console.log(' api - inject ANTHROPIC_API_KEY environment variable at launch time');
console.log('');
console.log('Windows run modes:');
console.log(' linux-portable - run Claude inside bundled QEMU Linux VM (default on Windows)');
console.log(' host-native - run Claude directly on Windows (requires claude in PATH)');
}
function commandDoctor() {
const checks = [];
const requiredDirs = ['runtime', 'state', 'scripts', 'profiles'];
for (const rel of requiredDirs) {
const abs = path.join(repoRoot, rel);
checks.push({
label: `dir:${rel}`,
ok: fs.existsSync(abs) && fs.statSync(abs).isDirectory(),
detail: abs
});
}
const settings = loadSettings();
checks.push({
label: 'settings:file',
ok: settingsFileExists(),
detail: settingsFileExists()
? path.relative(repoRoot, settingsPath)
: "missing (run 'pcoder setup --init')"
});
const authMode = settings.auth.claude;
if (process.platform === 'win32') {
checks.push({
label: 'tool:claude:runner',
ok: true,
detail: `vm guest runner 'claude' (auth=${authMode}, host binary optional)`
});
} else {
const runner = commandExists('claude') ? 'claude' : (process.env.PCODER_CLAUDE_CMD || null);
checks.push({
label: 'tool:claude:runner',
ok: Boolean(runner),
detail: runner ? `${runner} (auth=${authMode})` : 'not found (claude not in PATH)'
});
}
if (authMode === 'api') {
const hasKey = Boolean(process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN);
checks.push({
label: 'claude:api-key',
ok: hasKey,
detail: hasKey ? 'ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN set' : 'missing ANTHROPIC_API_KEY (api auth mode)'
});
} else {
const authPaths = getPortableHostAuthPaths();
const claudeConfigDir = path.join(authPaths.home, '.claude');
checks.push({
label: 'claude:oauth',
ok: true,
detail: `oauth home: ${path.relative(repoRoot, authPaths.home)}`
});
checks.push({
label: 'claude:oauth:config-dir',
ok: true,
detail: claudeConfigDir
});
}
let failed = 0;
for (const check of checks) {
if (check.ok) {
console.log(`[ok] ${check.label} -> ${check.detail}`);
} else {
failed += 1;
console.log(`[fail] ${check.label} -> ${check.detail}`);
}
}
if (failed > 0) {
process.exitCode = 2;
console.log(`\nDoctor completed with ${failed} failed check(s).`);
console.log("Run 'pcoder setup --init' for first-time setup.");
return;
}
console.log('\nDoctor completed: all checks passed.');
}
function commandSetup(args) {
const parsed = parseSetupArgs(args);
const hadSettings = settingsFileExists();
const settings = parsed.init ? defaultSettings() : loadSettings();
let changed = parsed.init;
if (parsed.claudeAuth) {
changed = changed || settings.auth.claude !== parsed.claudeAuth;
settings.auth.claude = parsed.claudeAuth;
}
if (parsed.windowsMode) {
changed = changed || settings.runtime.windows_default_mode !== parsed.windowsMode;
settings.runtime.windows_default_mode = parsed.windowsMode;
}
if (typeof parsed.syncBack === 'boolean') {
changed = changed || settings.runtime.sync_back_default !== parsed.syncBack;
settings.runtime.sync_back_default = parsed.syncBack;
}
const shouldSave = changed || parsed.persist;
if (shouldSave) {
saveSettings(settings);
}
if (shouldSave) {
console.log('Setup saved to state/settings.json');
console.log('');
} else if (!hadSettings) {
console.log("Settings not initialized yet. Run 'pcoder setup --init' to create state/settings.json.");
console.log('');
}
printSettings(settings, hadSettings || shouldSave);
}
function commandAuth(args) {
const action = args[0];
const hasSettings = settingsFileExists();
const settings = hasSettings ? loadSettings() : defaultSettings();
if (!action || action === 'status') {
printAuthStatus(settings, hasSettings);
return;
}
if (action !== 'login' && action !== 'logout') {
fail('Usage: pcoder auth <status|login|logout> [--mode <linux-portable|host-native>]');
}
if (!hasSettings) {
fail("Settings not initialized. Run 'pcoder setup --init' before auth login/logout.");
}
const parsed = parseAuthArgs(args.slice(1));
const mode = resolveRunMode(parsed.mode, settings);
const authMode = settings.auth.claude;
if (action === 'login' && authMode === 'api') {
console.log('[warn] claude auth mode is api; OAuth login is optional.');
}
const authCommandSettings = authMode === 'oauth'
? settings
: { ...settings, auth: { ...settings.auth, claude: 'oauth' } };
if (mode === 'linux-portable') {
runInLinuxPortableVm({
projectPath: repoRoot,
mergedEnv: applyPortableHostAuthEnv({ ...process.env }, authCommandSettings),
toolArgs: [action],
noSyncBack: true,
skipProjectSync: true,
authMode: 'oauth',
settings
});
return;
}
if (mode === 'linux-wsl') {
fail('linux-wsl mode is not implemented yet. Use --mode linux-portable or --mode host-native.');
}
if (mode !== 'host-native') {
fail(`Unsupported auth mode target '${mode}'.`);
}
const env = applyPortableHostAuthEnv({ ...process.env }, authCommandSettings);
const runner = resolveRunner(env);
if (!runner) {
fail('No claude executable found. Install claude or set PCODER_CLAUDE_CMD.');
}
const result = cp.spawnSync(runner, [action], {
cwd: repoRoot,
stdio: 'inherit',
env
});
if (result.error) {
fail(`Failed to run claude ${action}: ${result.error.message}`);
}
process.exitCode = typeof result.status === 'number' ? result.status : 1;
}
function commandRuntime(args) {
const action = args[0];
if (!action || action === 'probe') {
commandRuntimeProbe();
return;
}
if (action === 'bootstrap' || action === 'install') {
commandRuntimeBootstrap(args.slice(1));
return;
}
fail('Usage: pcoder runtime <probe|bootstrap>');
}
function commandRuntimeProbe() {
const probes = [
{ key: 'bundled-qemu', cmd: path.join(repoRoot, 'runtime', 'qemu', 'qemu-system-x86_64.exe') },
{ key: 'wsl', cmd: 'wsl' },
{ key: 'proot', cmd: 'proot' },
{ key: 'docker', cmd: 'docker' },
{ key: 'podman', cmd: 'podman' },
{ key: 'limactl', cmd: 'limactl' },
{ key: 'qemu-system-x86_64', cmd: 'qemu-system-x86_64' }
];
console.log(`host_platform=${process.platform}`);
for (const probe of probes) {
console.log(`${probe.key}=${commandOrPathExists(probe.cmd) ? 'yes' : 'no'}`);
}
const recommendation = recommendRuntimeBackend(process.platform, probes);
console.log(`recommended_backend=${recommendation}`);
if (process.platform === 'win32') {
console.log('vm_accel_policy=try_whpx_then_fallback_tcg');
}
}
function commandRuntimeBootstrap(args) {
if (process.platform !== 'win32') {
fail('runtime bootstrap is currently implemented for Windows hosts only.');
}
const supported = new Set(['--force']);
for (const arg of args) {
if (!supported.has(arg)) {
fail(`Unknown runtime bootstrap flag: ${arg}`);
}
}
const bootstrapScript = path.join(repoRoot, 'scripts', 'runtime', 'windows', 'bootstrap-runtime.cmd');
if (!fs.existsSync(bootstrapScript)) {
fail(`Missing runtime bootstrap script: ${bootstrapScript}`);
}
const cmdArgs = ['/c', bootstrapScript];
if (args.includes('--force')) {
cmdArgs.push('--force');
}
const result = cp.spawnSync('cmd.exe', cmdArgs, {
cwd: repoRoot,
stdio: 'inherit'
});
if (result.error) {
fail(`Failed to execute runtime bootstrap script: ${result.error.message}`);
}
process.exitCode = typeof result.status === 'number' ? result.status : 1;
}
function recommendRuntimeBackend(platform, probes) {
const available = new Set(probes.filter((p) => commandOrPathExists(p.cmd)).map((p) => p.key));
if (platform === 'win32') {
if (available.has('bundled-qemu') || available.has('qemu-system-x86_64')) {
return 'bundled-vm-qemu-auto-accel-fallback';
}
if (available.has('wsl')) {
return 'wsl-optional-no-bundled-engine';
}
return 'bundled-vm-qemu-missing';
}
if (platform === 'darwin') {
if (available.has('limactl')) {
return 'lima-vm';
}
if (available.has('docker')) {
return 'docker-vm';
}
return 'host-native-fallback';
}
if (platform === 'linux') {
if (available.has('proot')) {
return 'proot-userspace';
}
if (available.has('podman')) {
return 'podman-container';
}
if (available.has('docker')) {
return 'docker-container';
}
return 'host-native-fallback';
}
return 'host-native-fallback';
}
function commandRun(args) {
const parsed = parseRunArgs(args);
const settings = loadSettings();
const mergedEnv = { ...process.env };
const authMode = settings.auth.claude;
applyPortableHostAuthEnv(mergedEnv, settings);
applyClaudeCompatibilityEnv(mergedEnv);
if (authMode === 'api') {
const hasKey = Boolean(mergedEnv.ANTHROPIC_API_KEY || mergedEnv.ANTHROPIC_AUTH_TOKEN);
if (!hasKey) {
fail("Claude auth mode is 'api' but ANTHROPIC_API_KEY is not set. Set the env var or switch to oauth with 'pcoder setup --claude-auth oauth'.");
}
}
const projectPath = parsed.project ? path.resolve(parsed.project) : process.cwd();
if (!fs.existsSync(projectPath) || !fs.statSync(projectPath).isDirectory()) {
fail(`Project path does not exist or is not a directory: ${projectPath}`);
}
const mode = resolveRunMode(parsed.mode, settings);
const noSyncBack = parsed.noSyncBack === true
? true
: !Boolean(settings.runtime.sync_back_default);
if (mode === 'linux-portable') {
runInLinuxPortableVm({
projectPath,
mergedEnv,
toolArgs: parsed.toolArgs,
noSyncBack,
skipProjectSync: false,
authMode,
settings
});
return;
}
if (mode === 'linux-wsl') {
fail('linux-wsl mode is not implemented yet. Use --mode linux-portable or --mode host-native.');
}
if (mode !== 'host-native') {
fail(`Unsupported run mode '${mode}'. Supported modes: linux-portable, host-native`);
}
const runner = resolveRunner(mergedEnv);
if (!runner) {
if (process.platform === 'win32') {
fail("No claude executable found in host-native mode. Either install claude on Windows (npm install -g @anthropic-ai/claude-code), set PCODER_CLAUDE_CMD, or switch to VM mode: pcoder setup --windows-mode linux-portable");
}
fail("No claude executable found. Install claude (npm install -g @anthropic-ai/claude-code) or set PCODER_CLAUDE_CMD.");
}
const result = cp.spawnSync(runner, parsed.toolArgs, {
cwd: projectPath,
stdio: 'inherit',
env: mergedEnv
});
if (result.error) {
fail(`Failed to launch '${runner}': ${result.error.message}`);
}
process.exitCode = typeof result.status === 'number' ? result.status : 1;
}
function parseRunArgs(args) {
const parsed = { project: null, mode: null, noSyncBack: false, toolArgs: [] };
for (let i = 0; i < args.length; i += 1) {
const arg = args[i];
if (arg === '--') {
parsed.toolArgs = args.slice(i + 1);
return parsed;
}
if (arg === '--project') {
parsed.project = args[i + 1] || null;
i += 1;
continue;
}
if (arg === '--mode') {
parsed.mode = args[i + 1] || null;
i += 1;
continue;
}
if (arg === '--no-sync-back') {
parsed.noSyncBack = true;
continue;
}
parsed.toolArgs.push(arg);
}
return parsed;
}
function parseSetupArgs(args) {
const parsed = {
init: false,
claudeAuth: null,
windowsMode: null,
syncBack: undefined,
persist: false
};
for (let i = 0; i < args.length; i += 1) {
const arg = args[i];
if (arg === '--init') {
parsed.init = true;
parsed.persist = true;
continue;
}
if (arg === '--show') {
continue;
}
if (arg === '--claude-auth') {
parsed.claudeAuth = normalizeAuthModeValue(args[i + 1], '--claude-auth');
parsed.persist = true;
i += 1;
continue;
}
if (arg === '--windows-mode') {
parsed.windowsMode = normalizeWindowsModeValue(args[i + 1], '--windows-mode');
parsed.persist = true;
i += 1;
continue;
}
if (arg === '--sync-back') {
parsed.syncBack = parseBooleanFlagValue(args[i + 1], '--sync-back');
parsed.persist = true;
i += 1;
continue;
}
fail(`Unknown setup flag: ${arg}`);
}
return parsed;
}
function parseAuthArgs(args) {
const parsed = { mode: null };
for (let i = 0; i < args.length; i += 1) {
const arg = args[i];
if (arg === '--mode') {
parsed.mode = args[i + 1] || null;
i += 1;
continue;
}
fail(`Unknown auth flag: ${arg}`);
}
return parsed;
}
function parseBooleanFlagValue(rawValue, flagName) {
const normalized = String(rawValue || '').trim().toLowerCase();
if (normalized === 'true') {
return true;
}
if (normalized === 'false') {
return false;
}
fail(`Flag ${flagName} expects true or false.`);
}
function normalizeAuthModeValue(rawValue, context) {
const value = String(rawValue || '').trim().toLowerCase();
if (!authModeValues.has(value)) {
fail(`${context} must be one of: oauth, api`);
}
return value;
}
function normalizeRunModeValue(rawValue, context) {
const value = String(rawValue || '').trim();
if (!runModeValues.has(value)) {
fail(`${context} must be one of: linux-portable, host-native, linux-wsl`);
}
return value;
}
function normalizeWindowsModeValue(rawValue, context) {
const value = normalizeRunModeValue(rawValue, context);
if (!windowsDefaultModeValues.has(value)) {
fail(`${context} must be one of: linux-portable, host-native`);
}
return value;
}
function defaultSettings() {
return {
version: 1,
auth: {
claude: 'oauth'
},
runtime: {
windows_default_mode: 'linux-portable',
sync_back_default: true
}
};
}
function settingsFileExists() {
return fs.existsSync(settingsPath);
}
function loadSettings() {
if (!settingsFileExists()) {
return defaultSettings();
}
let raw = null;
try {
raw = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
} catch (error) {
fail(`Invalid JSON in ${path.relative(repoRoot, settingsPath)}: ${error.message}`);
}
return normalizeSettings(raw);
}
function normalizeSettings(raw) {
const defaults = defaultSettings();
const settings = {
version: defaults.version,
auth: {
claude: defaults.auth.claude
},
runtime: {
windows_default_mode: defaults.runtime.windows_default_mode,
sync_back_default: defaults.runtime.sync_back_default
}
};
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
fail(`Settings file ${path.relative(repoRoot, settingsPath)} must contain a JSON object.`);
}
if (raw.auth !== undefined) {
if (!raw.auth || typeof raw.auth !== 'object' || Array.isArray(raw.auth)) {
fail('settings.auth must be an object when present.');
}
if (raw.auth.claude !== undefined) {
settings.auth.claude = normalizeAuthModeValue(raw.auth.claude, 'settings.auth.claude');
}
}
if (raw.runtime !== undefined) {
if (!raw.runtime || typeof raw.runtime !== 'object' || Array.isArray(raw.runtime)) {
fail('settings.runtime must be an object when present.');
}
if (raw.runtime.windows_default_mode !== undefined) {
settings.runtime.windows_default_mode = normalizeWindowsModeValue(
raw.runtime.windows_default_mode,
'settings.runtime.windows_default_mode'
);
}
if (raw.runtime.sync_back_default !== undefined) {
if (typeof raw.runtime.sync_back_default !== 'boolean') {
fail('settings.runtime.sync_back_default must be true or false.');
}
settings.runtime.sync_back_default = raw.runtime.sync_back_default;
}
}
return settings;
}
function saveSettings(settings) {
ensureDir(stateDir);
fs.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`, 'utf8');
}
function printSettings(settings, initialized) {
console.log('Settings');
console.log(` initialized: ${initialized ? 'yes' : 'no'}`);
console.log(` claude auth: ${settings.auth.claude}`);
console.log(` windows default mode: ${settings.runtime.windows_default_mode}`);
console.log(` sync back default: ${settings.runtime.sync_back_default ? 'true' : 'false'}`);
console.log(` settings file: ${path.relative(repoRoot, settingsPath)}`);
}
function printAuthStatus(settings, initialized) {
console.log('Auth status');
console.log(` settings initialized: ${initialized ? 'yes' : 'no'}`);
const mode = settings.auth.claude;
const hostPaths = getPortableHostAuthPaths();
console.log(` claude: ${mode}`);
if (mode === 'oauth') {
console.log(` claude host oauth home: ${path.relative(repoRoot, hostPaths.home)}`);
console.log(` claude vm oauth home: /home/portable/.pcoder-auth/claude`);
} else {
console.log(` claude api mode: inject ANTHROPIC_API_KEY at launch time`);
}
}
function getPortableHostAuthPaths() {
const root = path.join(authStateRoot, 'claude', 'host');
const home = path.join(root, 'home');
const config = path.join(home, '.config');
const cache = path.join(home, '.cache');
const data = path.join(home, '.local', 'share');
const state = path.join(home, '.local', 'state');
return { root, home, config, cache, data, state };
}
function applyPortableHostAuthEnv(env, settings) {
const authMode = settings.auth.claude;
env.PCODER_AUTH_MODE = authMode;
if (authMode !== 'oauth') {
return env;
}
const authPaths = getPortableHostAuthPaths();
ensureDir(authPaths.root);
ensureDir(authPaths.home);
ensureDir(authPaths.config);
ensureDir(authPaths.cache);
ensureDir(authPaths.data);
ensureDir(authPaths.state);
env.HOME = authPaths.home;
env.XDG_CONFIG_HOME = authPaths.config;
env.XDG_CACHE_HOME = authPaths.cache;
env.XDG_DATA_HOME = authPaths.data;
env.XDG_STATE_HOME = authPaths.state;
env.PCODER_AUTH_HOME = authPaths.home;
if (process.platform === 'win32') {
const appData = path.join(authPaths.home, 'AppData', 'Roaming');
const localAppData = path.join(authPaths.home, 'AppData', 'Local');
ensureDir(appData);
ensureDir(localAppData);
env.USERPROFILE = authPaths.home;
env.APPDATA = appData;
env.LOCALAPPDATA = localAppData;
}
const claudeConfigDir = path.join(authPaths.home, '.claude');
ensureDir(claudeConfigDir);
env.CLAUDE_CONFIG_DIR = claudeConfigDir;
return env;
}
function applyClaudeCompatibilityEnv(env) {
if (!env.ANTHROPIC_AUTH_TOKEN && env.ANTHROPIC_API_KEY) {
env.ANTHROPIC_AUTH_TOKEN = env.ANTHROPIC_API_KEY;
}
}
function resolveRunMode(explicitMode, settings) {
if (explicitMode) {
return normalizeRunModeValue(explicitMode, '--mode');
}
if (process.platform === 'win32') {
return settings.runtime.windows_default_mode || 'linux-portable';
}
return 'host-native';
}
function resolveRunner(env) {
const override = env.PCODER_CLAUDE_CMD;
if (override) {
return override;
}
if (commandExists('claude')) {
return 'claude';
}
return null;
}
function runInLinuxPortableVm(options) {
const {
projectPath,
mergedEnv,
toolArgs,
noSyncBack,
skipProjectSync,
authMode,
settings
} = options;
// On non-Windows hosts, linux-portable mode uses portable host-native execution
// with isolated auth state instead of a VM. This provides portability without
// requiring Docker/Podman.
if (process.platform !== 'win32') {
return runPortableHostNative(options);
}
loadJsonSafe(vmManifestPath, 'vm manifest');
startWindowsVm();
const sshPort = readVmSshPort();
const sshHost = mergedEnv.PCODER_VM_HOST || '127.0.0.1';
const sshUser = mergedEnv.PCODER_VM_USER || 'portable';
const sshKeyPath = mergedEnv.PCODER_VM_SSH_KEY || path.join(repoRoot, 'runtime', 'linux', 'ssh', 'id_ed25519');
if (!fs.existsSync(sshKeyPath)) {
fail(`Missing VM SSH key: ${sshKeyPath}. Set PCODER_VM_SSH_KEY or provide runtime/linux/ssh/id_ed25519.`);
}
const sshCmd = resolveSshCommand(mergedEnv);
const scpCmd = resolveScpCommand(mergedEnv, sshCmd);
waitForVmSshReady({
sshCmd,
sshHost,
sshPort,
sshUser,
sshKeyPath,
timeoutSeconds: resolveVmSshTimeoutSeconds(mergedEnv)
});
const remoteRoot = mergedEnv.PCODER_VM_PROJECTS_ROOT || '/home/portable/projects';
const remoteProjectPath = skipProjectSync
? (mergedEnv.PCODER_VM_AUTH_WORKDIR || '/home/portable')
: buildRemoteProjectPath(remoteRoot, projectPath);
const prepLines = ['set -e'];
if (skipProjectSync) {
prepLines.push(`mkdir -p ${shellEscape(remoteProjectPath)}`);
} else {
prepLines.push(`mkdir -p ${shellEscape(remoteRoot)}`);
prepLines.push(`rm -rf ${shellEscape(remoteProjectPath)}`);
prepLines.push(`mkdir -p ${shellEscape(remoteProjectPath)}`);
}
const prepScript = prepLines.join('\n');
const prepResult = runSshScript({
sshCmd,
sshHost,
sshPort,
sshUser,
sshKeyPath,
script: prepScript,
inheritOutput: true
});
if (prepResult.status !== 0) {
fail('Failed to prepare remote project directory in VM.');
}
if (!skipProjectSync) {
syncProjectToVm({
scpCmd,
sshHost,
sshPort,
sshUser,
sshKeyPath,
projectPath,
remoteProjectPath
});
}
const remoteScript = buildRemoteRunScript({
authMode,
remoteProjectPath,
toolArgs,
mergedEnv
});
const runResult = runSshScript({
sshCmd,
sshHost,
sshPort,
sshUser,
sshKeyPath,
script: remoteScript,
inheritOutput: true
});
if (!skipProjectSync && !noSyncBack) {
syncProjectFromVm({
scpCmd,
sshHost,
sshPort,
sshUser,
sshKeyPath,
projectPath,
remoteProjectPath
});
}
process.exitCode = typeof runResult.status === 'number' ? runResult.status : 1;
}
/**
* Run tool in portable host-native mode (non-Windows hosts).
* Uses isolated auth state in state/auth/<tool>/host/ but runs the tool
* directly on the host without a VM. This provides portability on Linux/macOS
* where a VM isn't needed for Linux tools.
*/
function runPortableHostNative(options) {
const {
tool,
adapter,
projectPath,
mergedEnv,
toolArgs,
authMode,
settings
} = options;
// Resolve the runner
const runner = resolveRunner(adapter, mergedEnv);
if (!runner) {
fail(`No executable found for tool '${tool}'. Set ${adapter.command_env} or install one of: ${adapter.candidate_commands.join(', ')}`);
}
// Apply portable auth environment (isolates auth state to state/auth/<tool>/host/)
const env = applyPortableHostAuthEnv(tool, { ...mergedEnv }, settings);
console.log(`[portable-native] Running ${tool} with isolated auth state...`);
const result = cp.spawnSync(runner, toolArgs, {
cwd: projectPath,
stdio: 'inherit',
env
});
if (result.error) {
fail(`Failed to launch '${runner}': ${result.error.message}`);
}
process.exitCode = typeof result.status === 'number' ? result.status : 1;
}
function startWindowsVm() {
const startScript = path.join(repoRoot, 'scripts', 'runtime', 'windows', 'start-vm.cmd');
if (!fs.existsSync(startScript)) {
fail(`Missing VM start script: ${startScript}`);
}
const result = cp.spawnSync('cmd.exe', ['/c', startScript], {
cwd: repoRoot,
stdio: 'inherit'
});
if (result.error) {
fail(`Failed to execute VM start script: ${result.error.message}`);
}
if (result.status !== 0) {
fail(`VM start script failed with exit code ${result.status}.`);
}
}
function readVmSshPort() {
if (!fs.existsSync(vmSshPortPath)) {
fail(`Missing VM SSH port file: ${vmSshPortPath}. VM may not be initialized correctly.`);
}
const raw = fs.readFileSync(vmSshPortPath, 'utf8').trim();
const port = Number.parseInt(raw, 10);
if (!Number.isFinite(port) || port < 1 || port > 65535) {
fail(`Invalid VM SSH port value in ${vmSshPortPath}: ${raw}`);
}
return String(port);
}
function resolveSshCommand(env) {
const override = env.PCODER_SSH_CMD;
if (override) {
if (!commandOrPathExists(override)) {
fail(`PCODER_SSH_CMD is set but not found: ${override}`);
}
return override;
}
const bundled = path.join(repoRoot, 'runtime', 'ssh', 'ssh.exe');
if (fs.existsSync(bundled)) {
return bundled;
}
if (commandExists('ssh')) {
return 'ssh';
}
fail('No SSH client found. Bundle runtime/ssh/ssh.exe or ensure ssh is available in PATH.');
}
function resolveScpCommand(env, sshCmd) {
const override = env.PCODER_SCP_CMD;
if (override) {
if (!commandOrPathExists(override)) {
fail(`PCODER_SCP_CMD is set but not found: ${override}`);
}
return override;
}
if (sshCmd.includes('/') || sshCmd.includes('\\')) {
const sshDir = path.dirname(sshCmd);
const siblingScp = path.join(sshDir, 'scp.exe');
if (fs.existsSync(siblingScp)) {
return siblingScp;
}
}
const bundled = path.join(repoRoot, 'runtime', 'ssh', 'scp.exe');
if (fs.existsSync(bundled)) {
return bundled;
}
if (commandExists('scp')) {
return 'scp';
}
fail('No SCP client found. Bundle runtime/ssh/scp.exe or ensure scp is available in PATH.');
}
function waitForVmSshReady(options) {
const { sshCmd, sshHost, sshPort, sshUser, sshKeyPath, timeoutSeconds } = options;
const startedAt = Date.now();
const timeoutMs = timeoutSeconds * 1000;
while ((Date.now() - startedAt) < timeoutMs) {
const probe = runSshScript({
sshCmd, sshHost, sshPort, sshUser, sshKeyPath,
script: 'echo vm-ready',
inheritOutput: false
});
if (probe.status === 0) {
return;
}
sleepMs(2000);
}
fail(`Timed out waiting for VM SSH readiness after ${timeoutSeconds}s.`);
}
function resolveVmSshTimeoutSeconds(env) {
const raw = env.PCODER_VM_SSH_TIMEOUT_SECONDS;
if (!raw) {
return 300;
}
const parsed = Number.parseInt(String(raw), 10);
if (!Number.isFinite(parsed) || parsed < 10 || parsed > 3600) {
fail('PCODER_VM_SSH_TIMEOUT_SECONDS must be an integer between 10 and 3600.');
}