Repository navigation
Expand file tree
/
Copy pathproject_entry.rs
More file actions
1179 lines (1122 loc) · 39.8 KB
/
Copy pathproject_entry.rs
File metadata and controls
1179 lines (1122 loc) · 39.8 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
//! Canonical project onboarding and readiness application service.
//!
//! Configuration lives outside the Git checkout. CLI readiness is derived from
//! canonical Runtime/Runner/Project observations; it never parses
//! human-formatted output to decide whether coding is ready.
#[path = "project_entry_client_handoff.rs"]
mod client_handoff_service;
#[path = "project_entry_cloudflared.rs"]
mod cloudflared_service;
#[path = "project_entry_openai_tunnel.rs"]
mod openai_tunnel_service;
#[path = "project_entry_regular_tunnel.rs"]
mod regular_tunnel_service;
#[path = "project_entry_setup.rs"]
mod setup_service;
#[path = "project_entry_share.rs"]
mod share_service;
#[cfg(windows)]
#[path = "project_entry_windows.rs"]
mod windows_private_state;
pub(crate) use regular_tunnel_service::{run_regular_server_tunnel, RegularServerTunnelOptions};
pub(crate) use setup_service::setup;
use setup_service::{
create_private_dir, local_readiness, prepare_runtime_private_state, read_private_value,
read_project_agent_token, read_project_credential, read_toml_optional,
validate_agent_authentication, validate_existing_registration, validate_existing_runner,
validate_product_config, validate_profile, ProjectConfig,
};
#[cfg(test)]
pub(crate) use share_service::TunnelProvider;
pub(crate) use share_service::{parse_share_options, share, ShareCommandOptions};
use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::{Duration, Instant};
use tokio::process::{Child, Command};
const DEFAULT_PROFILE: &str = "personal";
const START_TIMEOUT: Duration = Duration::from_secs(30);
const NPM_WRAPPER_NETWORK_ENV_KEYS: [&str; 8] = [
"npm_config_https_proxy",
"npm_config_proxy",
"npm_config_noproxy",
"npm_config_no_proxy",
"npm_config_cafile",
"npm_config_ca",
"npm_config_strict_ssl",
"WEBCODEX_NPM_WRAPPER",
];
fn remove_npm_wrapper_network_environment(command: &mut Command) {
for key in NPM_WRAPPER_NETWORK_ENV_KEYS {
command.env_remove(key);
}
}
fn remove_runner_parent_credentials(command: &mut Command) {
for key in ["WEBCODEX_TOKEN", "WEBCODEX_PAT", "WEBCODEX_AGENT_TOKEN"] {
command.env_remove(key);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProjectCommandOptions {
pub root: PathBuf,
pub profile: String,
pub state_dir: Option<PathBuf>,
pub json: bool,
pub console_assets_dir: Option<PathBuf>,
}
impl ProjectCommandOptions {
pub(crate) fn current() -> Result<Self, String> {
Ok(Self {
root: std::env::current_dir().map_err(|error| format!("cannot read cwd: {error}"))?,
profile: DEFAULT_PROFILE.to_string(),
state_dir: None,
json: false,
console_assets_dir: None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct ProductError {
pub code: String,
pub message: String,
pub retryable: bool,
pub user_action_required: bool,
pub next_action: Option<String>,
}
impl ProductError {
fn new(code: &str, message: impl Into<String>, next_action: Option<&str>) -> Self {
Self {
code: code.to_string(),
message: message.into(),
retryable: matches!(code, "server_unreachable" | "agent_offline"),
user_action_required: true,
next_action: next_action.map(str::to_string),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct SetupReport {
pub project: String,
pub connection_url: String,
pub status: String,
pub changed: Vec<String>,
pub next_action: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ReadinessStatus {
Pass,
Warn,
Fail,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ReadinessFact {
pub name: String,
pub status: ReadinessStatus,
pub code: String,
pub summary: String,
pub next_action: Option<String>,
}
impl ReadinessFact {
fn pass(name: &str, code: &str, summary: impl Into<String>) -> Self {
Self {
name: name.to_string(),
status: ReadinessStatus::Pass,
code: code.to_string(),
summary: summary.into(),
next_action: None,
}
}
fn warn(name: &str, code: &str, summary: impl Into<String>, action: &str) -> Self {
Self {
name: name.to_string(),
status: ReadinessStatus::Warn,
code: code.to_string(),
summary: summary.into(),
next_action: Some(action.to_string()),
}
}
fn fail(name: &str, code: &str, summary: impl Into<String>, action: &str) -> Self {
Self {
name: name.to_string(),
status: ReadinessStatus::Fail,
code: code.to_string(),
summary: summary.into(),
next_action: Some(action.to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ProjectReadiness {
pub project: Option<String>,
pub connection: String,
pub agent: String,
pub capabilities: String,
pub ready: bool,
pub next_action: Option<String>,
pub findings: Vec<ReadinessFact>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RemoteProbe {
Unreachable,
CredentialRejected,
Ready,
RunnerOffline,
ProjectMissing,
}
pub(crate) fn parse_options(
args: &[String],
command: &str,
) -> Result<ProjectCommandOptions, String> {
let mut options = ProjectCommandOptions::current()?;
let mut index = 0;
while index < args.len() {
let flag = args[index].as_str();
let value = |index: &mut usize| -> Result<String, String> {
*index += 1;
args.get(*index)
.cloned()
.ok_or_else(|| format!("{flag} requires a value"))
};
match flag {
"--root" => options.root = PathBuf::from(value(&mut index)?),
"--profile" => options.profile = value(&mut index)?,
"--state-dir" => options.state_dir = Some(PathBuf::from(value(&mut index)?)),
"--json" if command != "run" => options.json = true,
"--console-assets-dir" if command == "run" => {
let directory = PathBuf::from(value(&mut index)?);
if !directory.is_absolute() {
return Err(
"--console-assets-dir requires an absolute directory path".to_string()
);
}
options.console_assets_dir = Some(directory);
}
"--help" | "-h" => return Err("help requested".to_string()),
_ => return Err(format!("unknown {command} option '{flag}'")),
}
index += 1;
}
validate_profile(&options.profile).map_err(|error| error.message)?;
Ok(options)
}
pub(crate) fn usage() -> &'static str {
"Usage: webcodex share [--root PATH] [--profile NAME] [--state-dir PATH] [--json]\n\
[--tunnel cloudflare|openai|none] [--auth bearer|query-token|oauth]\n\
[--oauth-redirect-uri URL] [--public-url URL] [--no-copy-url]\n\
[--stop-on-stdin-eof]\n\
webcodex status [--root PATH] [--profile NAME] [--state-dir PATH] [--json]\n\
webcodex doctor [--root PATH] [--profile NAME] [--state-dir PATH] [--json]\n\
webcodex setup [--root PATH] [--profile NAME] [--state-dir PATH] [--json]\n\
webcodex run [--root PATH] [--profile NAME] [--state-dir PATH]\n\
[--console-assets-dir ABSOLUTE_PATH]\n\n\
`share` is the Quick Trial path: it temporarily shares this one project for ChatGPT/remote MCP,\n\
starts a local Server + Runner for the foreground lifetime, and ends when the command exits.\n\
For full daily use, configure the regular WebCodex Server + Runner flow instead. The default\n\
Cloudflare Quick Tunnel reuses or auto-manages a verified `cloudflared`. The opt-in\n\
OpenAI Secure MCP Tunnel provider uses a pinned verified `tunnel-client` and keeps\n\
the temporary WebCodex Bearer credential local. Public URL sharing best-effort\n\
copies only the MCP URL by default; `--auth query-token` explicitly opts into a\n\
single sensitive URL carrying the temporary share credential. Use `--no-copy-url`\n\
to disable clipboard access. `--stop-on-stdin-eof` is a `--json` machine-integration\n\
lifecycle hook: the foreground share exits cleanly when its supervising parent closes stdin.\n\
`setup`, `doctor`, and `run` remain the local/manual workflow; setup writes private state without\n\
starting services. `run` is the explicit foreground local runtime step. Its optional\n\
`--console-assets-dir` enables loopback-only development assets for that run.\n\
`--auth query-token` is a temporary share-only convenience for MCP clients that\n\
cannot configure a Bearer header; `--auth oauth` adds project-bound OAuth.\n\
On Windows, explicit `webcodex share` is supported. Managed Cloudflare acquisition is available on Windows x64; Windows ARM64 requires a trusted explicit/PATH cloudflared because the pinned upstream release has no official ARM64 artifact. Managed OpenAI tunnel-client supports Windows x64/arm64.\n"
}
pub(crate) fn readiness_with_probe(
options: &ProjectCommandOptions,
remote: RemoteProbe,
) -> ProjectReadiness {
let local = local_readiness(options);
let config = local.config;
let paths = local.paths;
let setup_present = local.setup_present;
let can_probe_remote = local.can_probe_remote;
let mut findings = local.findings;
let project = config.as_ref().map(|config| config.project_name.clone());
let mut connection = if can_probe_remote {
"configured".to_string()
} else if setup_present {
"invalid".to_string()
} else {
"not configured".to_string()
};
let mut runner_status = "unknown".to_string();
let mut capabilities = "not_ready".to_string();
let local_complete = can_probe_remote
&& paths.as_ref().is_some_and(|paths| {
paths
.resolved_runner_config()
.is_ok_and(|config| config.is_file())
&& paths.project_credential.is_file()
&& paths.agent_token.is_file()
&& paths.bootstrap_key.is_file()
})
&& !findings
.iter()
.any(|finding| finding.status == ReadinessStatus::Fail);
if can_probe_remote {
let runtime = runtime_readiness(project.clone(), remote);
connection = runtime.connection;
runner_status = runtime.agent;
capabilities = runtime.capabilities;
findings.extend(runtime.findings);
}
if local_complete {
findings.push(ReadinessFact::pass(
"Setup",
"setup_complete",
"Project setup is complete.",
));
}
findings.push(gitignore_hygiene_fact(&options.root));
let ready = local_complete
&& connection == "connected"
&& runner_status == "online"
&& capabilities == "ready";
if ready {
findings.push(ReadinessFact::pass(
"Coding access",
"ready",
"Coding access is ready.",
));
}
let next_action = if ready {
None
} else {
findings
.iter()
.find(|finding| finding.status == ReadinessStatus::Fail)
.and_then(|finding| finding.next_action.clone())
.or_else(|| Some("webcodex run".to_string()))
};
ProjectReadiness {
project,
connection,
agent: runner_status,
capabilities,
ready,
next_action,
findings,
}
}
pub(crate) fn runtime_readiness(project: Option<String>, probe: RemoteProbe) -> ProjectReadiness {
let mut findings = vec![ReadinessFact::pass(
"Connection",
"server_reachable",
"WebCodex is reachable.",
)];
let (connection, runner_status, capabilities) = match probe {
RemoteProbe::Unreachable => {
findings[0] = ReadinessFact::fail(
"Connection",
"server_unreachable",
"WebCodex is not reachable.",
"Run webcodex run, then retry.",
);
("unreachable", "unknown", "not_ready")
}
RemoteProbe::CredentialRejected => {
findings.push(ReadinessFact::fail(
"Authentication",
"project_credential_rejected",
"WebCodex rejected the configured project credential.",
"Restore the matching private credential or explicitly rotate the project setup.",
));
("connected", "unknown", "not_ready")
}
RemoteProbe::RunnerOffline => {
findings.push(ReadinessFact::fail(
"Runner",
"agent_offline",
"The local Runner is offline.",
"Run webcodex run.",
));
("connected", "offline", "not_ready")
}
RemoteProbe::ProjectMissing => {
findings.push(ReadinessFact::fail(
"Project",
"project_registration_invalid",
"The Runner registration does not contain this project.",
"Stop the Runner, run webcodex setup, then start it again.",
));
("connected", "online", "not_ready")
}
RemoteProbe::Ready => {
findings.push(ReadinessFact::pass(
"Runner",
"agent_online",
"The local Runner is online.",
));
findings.push(ReadinessFact::pass(
"Project",
"project_registered",
"The current project is registered.",
));
findings.push(ReadinessFact::pass(
"Capabilities",
"required_capabilities_available",
"Required coding capabilities are available.",
));
("connected", "online", "ready")
}
};
ProjectReadiness {
project,
connection: connection.to_string(),
agent: runner_status.to_string(),
capabilities: capabilities.to_string(),
ready: probe == RemoteProbe::Ready,
next_action: (probe != RemoteProbe::Ready).then(|| "webcodex doctor".to_string()),
findings,
}
}
/// Untracked build artifacts poison the workspace provenance fingerprint and
/// used to wedge check validation irrecoverably; catch the setup before the
/// first task does.
const IGNORE_HYGIENE_DIRS: &[&str] = &[
"target/",
"node_modules/",
"__pycache__/",
".venv/",
"venv/",
"dist/",
"build/",
"coverage/",
".pytest_cache/",
];
fn gitignore_hygiene_fact(root: &Path) -> ReadinessFact {
let untracked_artifacts: Vec<String> = std::process::Command::new("git")
.args(["status", "--porcelain"])
.current_dir(root)
.output()
.ok()
.filter(|output| output.status.success())
.map(|output| {
String::from_utf8_lossy(&output.stdout)
.lines()
.filter_map(|line| line.strip_prefix("?? ").map(str::to_string))
.filter(|path| {
IGNORE_HYGIENE_DIRS
.iter()
.any(|dir| path == dir || path.starts_with(dir))
})
.take(3)
.collect()
})
.unwrap_or_default();
let has_gitignore = root.join(".gitignore").exists();
if !untracked_artifacts.is_empty() {
ReadinessFact::warn(
"Ignore hygiene",
"untracked_build_artifacts",
format!(
"Untracked build artifacts present ({}); checks that touch them will fail \
workspace provenance validation.",
untracked_artifacts.join(", ")
),
"Add a .gitignore covering build artifacts (target/, __pycache__/, ...), then rerun webcodex doctor.",
)
} else if !has_gitignore {
ReadinessFact::warn(
"Ignore hygiene",
"gitignore_missing",
"The project has no .gitignore; checks that generate build artifacts will fail \
workspace provenance validation.",
"Add a .gitignore covering build artifacts before running checks.",
)
} else {
ReadinessFact::pass(
"Ignore hygiene",
"gitignore_present",
"No untracked build artifacts detected.",
)
}
}
pub(crate) async fn collect_readiness(options: &ProjectCommandOptions) -> ProjectReadiness {
let local = local_readiness(options);
if !local.can_probe_remote {
return readiness_with_probe(options, RemoteProbe::Unreachable);
}
let (Some(config), Some(paths)) = (local.config, local.paths) else {
return readiness_with_probe(options, RemoteProbe::Unreachable);
};
let key = match read_project_credential(&paths.project_credential) {
Ok(key) => key,
Err(_) => return readiness_with_probe(options, RemoteProbe::Unreachable),
};
collect_readiness_from_remote(options, &config, &key).await
}
async fn collect_readiness_from_remote(
options: &ProjectCommandOptions,
config: &ProjectConfig,
credential: &str,
) -> ProjectReadiness {
let client = match reqwest::Client::builder()
.no_proxy()
.connect_timeout(Duration::from_secs(1))
.timeout(Duration::from_secs(3))
.build()
{
Ok(client) => client,
Err(_) => return readiness_with_probe(options, RemoteProbe::Unreachable),
};
let status = match client
.post(format!("{}/api/runtime/status", config.server_url()))
.bearer_auth(credential)
.json(&serde_json::json!({"client_id": config.executor_client_id}))
.send()
.await
{
Ok(response)
if matches!(
response.status(),
reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN
) =>
{
return readiness_with_probe(options, RemoteProbe::CredentialRejected)
}
Ok(response) if response.status().is_success() => {
response.json::<serde_json::Value>().await.ok()
}
Ok(response) if response.status() == reqwest::StatusCode::BAD_REQUEST => None,
_ => return readiness_with_probe(options, RemoteProbe::Unreachable),
};
let Some(status) = status else {
return readiness_with_probe(options, RemoteProbe::RunnerOffline);
};
if status.get("success").and_then(serde_json::Value::as_bool) != Some(true)
|| status
.pointer("/output/focus/client_id")
.and_then(serde_json::Value::as_str)
!= Some(config.executor_client_id.as_str())
|| status
.pointer("/output/focus/connected")
.and_then(serde_json::Value::as_bool)
!= Some(true)
{
return readiness_with_probe(options, RemoteProbe::RunnerOffline);
}
let runtime_project_id = config.runtime_project_id();
let projects = match client
.post(format!("{}/api/projects/list", config.server_url()))
.bearer_auth(credential)
.json(&serde_json::json!({
"client_id": config.executor_client_id,
"project": runtime_project_id,
"limit": 1,
"summary_only": true,
}))
.send()
.await
{
Ok(response)
if matches!(
response.status(),
reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN
) =>
{
return readiness_with_probe(options, RemoteProbe::CredentialRejected)
}
Ok(response) if response.status().is_success() => {
response.json::<serde_json::Value>().await.ok()
}
_ => None,
};
let visible = projects
.as_ref()
.and_then(|value| value.pointer("/output/projects"))
.and_then(serde_json::Value::as_array)
.is_some_and(|projects| {
projects.iter().any(|project| {
project.get("id").and_then(serde_json::Value::as_str)
== Some(runtime_project_id.as_str())
&& project.get("client_id").and_then(serde_json::Value::as_str)
== Some(config.executor_client_id.as_str())
&& project
.get("connected")
.and_then(serde_json::Value::as_bool)
== Some(true)
})
});
readiness_with_probe(
options,
if visible {
RemoteProbe::Ready
} else {
RemoteProbe::ProjectMissing
},
)
}
pub(crate) fn render_setup_text(report: &SetupReport) -> String {
let state = if report.status == "already_configured" {
"already configured"
} else {
"configured"
};
format!(
"Project: {}\nConnection: {state} at {}\nAgent: configured, not running\nCapabilities: ready after Agent starts\n\nNext:\n {}\n",
report.project, report.connection_url, report.next_action
)
}
pub(crate) fn render_doctor_text(readiness: &ProjectReadiness) -> String {
let mut output = format!(
"WebCodex doctor — {}\n",
readiness.project.as_deref().unwrap_or("current project")
);
for finding in &readiness.findings {
let status = match finding.status {
ReadinessStatus::Pass => "pass",
ReadinessStatus::Warn => "warn",
ReadinessStatus::Fail => "fail",
};
output.push_str(&format!(
"[{status}] {}: {}\n",
finding.name, finding.summary
));
}
output.push_str(if readiness.ready {
"\nVerdict: Ready\n"
} else {
"\nVerdict: Needs action\n"
});
if let Some(action) = &readiness.next_action {
output.push_str(&format!("Next:\n {action}\n"));
}
output
}
pub(crate) fn render_status_text(readiness: &ProjectReadiness) -> String {
let mut output = format!(
"Project: {}\nConnection: {}\nAgent: {}\nCapabilities: {}\nCoding access: {}\n",
readiness.project.as_deref().unwrap_or("not configured"),
readiness.connection,
readiness.agent,
readiness.capabilities,
if readiness.ready {
"ready"
} else {
"not ready"
}
);
if let Some(action) = &readiness.next_action {
output.push_str(&format!("\nNext:\n {action}\n"));
}
output
}
pub(crate) fn render_error(error: &ProductError, json: bool) -> String {
if json {
serde_json::to_string_pretty(&serde_json::json!({
"ok": false,
"error": error
}))
.unwrap_or_else(|_| format!("{{\"ok\":false,\"error\":{{\"code\":\"{}\"}}}}", error.code))
} else {
let mut output = format!("{}: {}", error.code, error.message);
if let Some(action) = &error.next_action {
output.push_str(&format!("\nNext:\n {action}"));
}
output
}
}
#[derive(Debug, Clone)]
pub(super) struct ProjectShareOAuthRuntimeOptions {
pub(super) project_grant_id: String,
pub(super) session_id: String,
}
#[derive(Debug, Clone)]
pub(super) struct LocalRuntimeOptions {
pub(super) public_url: Option<String>,
pub(super) project_credential_file: Option<PathBuf>,
pub(super) mcp_query_token_auth: bool,
pub(super) project_share_oauth: Option<ProjectShareOAuthRuntimeOptions>,
pub(super) child_environment_remove: Vec<&'static str>,
pub(super) port_conflict_action: &'static str,
pub(super) readiness_deadline: Option<Instant>,
}
impl Default for LocalRuntimeOptions {
fn default() -> Self {
Self {
public_url: None,
project_credential_file: None,
mcp_query_token_auth: false,
project_share_oauth: None,
child_environment_remove: Vec::new(),
port_conflict_action: "Stop the conflicting process, then run webcodex run.",
readiness_deadline: None,
}
}
}
pub(super) struct LocalRuntimeHandle {
pub(super) project_name: String,
pub(super) local_url: String,
pub(super) public_url: String,
pub(super) console_assets_dir: Option<PathBuf>,
server: Child,
runner: Child,
}
impl LocalRuntimeHandle {
pub(super) async fn wait_for_exit(&mut self) -> Result<(), ProductError> {
tokio::select! {
status = self.server.wait() => Err(ProductError::new(
"server_unreachable",
format!("WebCodex stopped unexpectedly ({:?})", status.ok()),
Some("Run webcodex doctor."),
)),
status = self.runner.wait() => Err(ProductError::new(
"agent_offline",
format!("the local Runner stopped unexpectedly ({:?})", status.ok()),
Some("Run webcodex doctor."),
)),
}
}
pub(super) async fn stop(&mut self) {
let _ = self.runner.start_kill();
let _ = self.server.start_kill();
let _ = self.runner.wait().await;
let _ = self.server.wait().await;
}
}
fn configured_project(
options: &ProjectCommandOptions,
) -> Result<(ProjectConfig, setup_service::ProjectPaths), ProductError> {
let (expected, paths) = ProjectConfig::resolve(options)?;
let config = read_toml_optional::<ProjectConfig>(&paths.config)?.ok_or_else(|| {
ProductError::new(
"project_not_configured",
"the current project has not been set up",
Some("Run webcodex setup."),
)
})?;
validate_product_config(&expected, &config)?;
validate_existing_runner(&config, &paths)?;
validate_existing_registration(&config, &paths)?;
Ok((config, paths))
}
pub(super) fn ensure_local_runtime_port_available(
port: u16,
port_conflict_action: &'static str,
) -> Result<(), ProductError> {
if TcpListener::bind(("127.0.0.1", port)).is_err() {
return Err(ProductError::new(
"server_unreachable",
"the configured loopback port is already in use",
Some(port_conflict_action),
));
}
Ok(())
}
pub(super) async fn start_local_runtime(
options: &ProjectCommandOptions,
runtime_options: LocalRuntimeOptions,
) -> Result<LocalRuntimeHandle, ProductError> {
let console_assets_dir = resolve_console_assets_directory(options)?;
let (config, paths) = configured_project(options)?;
prepare_runtime_private_state(&paths)?;
ensure_local_runtime_port_available(config.port, runtime_options.port_conflict_action)?;
let readiness_deadline = runtime_options
.readiness_deadline
.unwrap_or_else(|| Instant::now() + START_TIMEOUT);
let project_share_oauth = runtime_options.project_share_oauth.clone();
let mcp_query_token_auth = runtime_options.mcp_query_token_auth;
let runner_binary = locate_runner_binary().ok_or_else(|| {
ProductError::new(
"required_capability_unavailable",
"the WebCodex Runner executable is unavailable",
Some("Install all WebCodex binaries, then run webcodex doctor."),
)
})?;
let bootstrap = read_private_value(&paths.bootstrap_key)?;
let credential_file = runtime_options
.project_credential_file
.unwrap_or_else(|| paths.project_credential.clone());
let project_credential = read_project_credential(&credential_file)?;
let _agent_token = read_project_agent_token(&paths.agent_token)?;
validate_agent_authentication(&config, &paths)?;
let server_binary = locate_companion_binary("webcodex-server").ok_or_else(|| {
ProductError::new(
"required_capability_unavailable",
"the WebCodex Server executable is unavailable",
Some("Install all WebCodex binaries, then run webcodex doctor."),
)
})?;
let local_url = config.server_url();
let public_url = runtime_options
.public_url
.unwrap_or_else(|| local_url.clone());
let server_log = open_log(&paths.logs.join("server.log"))?;
let server_error = server_log.try_clone().map_err(io_error)?;
let mut server_command = Command::new(server_binary);
remove_npm_wrapper_network_environment(&mut server_command);
for name in &runtime_options.child_environment_remove {
server_command.env_remove(name);
}
server_command
.current_dir(&paths.state)
.env_remove("WEBCODEX_ENV_FILE")
.env("WEBCODEX_ADDR", format!("127.0.0.1:{}", config.port))
.env("WEBCODEX_DATA", &paths.data)
.env("WEBCODEX_TOKEN", bootstrap)
.env("WEBCODEX_SHARED_KEY_ENABLED", "false")
.env("WEBCODEX_ALLOW_ANONYMOUS", "false")
.env("WEBCODEX_PUBLIC_URL", &public_url)
.env("WEBCODEX_OAUTH2_SHARED_KEY_BRIDGE", "false")
.env("WEBCODEX_OAUTH2_REQUIRE_PKCE", "true")
.env("WEBCODEX_OAUTH2_ACCESS_TOKEN_TTL_SECS", "3600")
.env("WEBCODEX_OAUTH2_REFRESH_TOKEN_TTL_SECS", "2592000")
.env("WEBCODEX_OAUTH2_AUTH_CODE_TTL_SECS", "300")
.env("WEBCODEX_OAUTH2_TRUSTED_MCP_FILE_CLIENT_IDS", "")
.env("WEBCODEX_QUIC_ENABLED", "false")
.env(
crate::auth::PROJECT_GRANT_ID_ENV,
config.project_grant_id(&paths),
)
.env(crate::auth::PROJECT_CREDENTIAL_FILE_ENV, &credential_file)
.env(
"WEBCODEX_PROJECT_SHARE_MCP_QUERY_TOKEN_ENABLED",
if mcp_query_token_auth {
"true"
} else {
"false"
},
)
.env(
crate::auth::PROJECT_AGENT_TOKEN_FILE_ENV,
&paths.agent_token,
)
.env(
crate::auth::PROJECT_RUNNER_CLIENT_ID_ENV,
&config.executor_client_id,
)
.stdout(Stdio::from(server_log))
.stderr(Stdio::from(server_error))
.kill_on_drop(true);
if let Some(oauth) = project_share_oauth {
server_command
.env("WEBCODEX_OAUTH2_ENABLED", "true")
.env("WEBCODEX_OAUTH2_ISSUER", &public_url)
.env(
"WEBCODEX_OAUTH2_PROJECT_SHARE_GRANT_ID",
oauth.project_grant_id,
)
.env("WEBCODEX_OAUTH2_PROJECT_SHARE_SESSION_ID", oauth.session_id);
} else {
server_command
.env("WEBCODEX_OAUTH2_ENABLED", "false")
.env_remove("WEBCODEX_OAUTH2_ISSUER")
.env_remove("WEBCODEX_OAUTH2_PROJECT_SHARE_GRANT_ID")
.env_remove("WEBCODEX_OAUTH2_PROJECT_SHARE_SESSION_ID");
}
configure_console_assets_environment(&mut server_command, console_assets_dir.as_deref());
let mut server = server_command.spawn().map_err(|_| {
ProductError::new(
"server_unreachable",
"WebCodex could not start",
Some("Run webcodex doctor."),
)
})?;
if let Err(error) = wait_for_server(
&mut server,
&local_url,
&project_credential,
readiness_deadline,
)
.await
{
stop_child(&mut server).await;
return Err(error);
}
let runner_log = open_log(&paths.logs.join("agent.log"))?;
let runner_error = runner_log.try_clone().map_err(io_error)?;
let runner_config = paths.resolved_runner_config()?;
let mut runner_command = Command::new(runner_binary);
remove_npm_wrapper_network_environment(&mut runner_command);
for name in &runtime_options.child_environment_remove {
runner_command.env_remove(name);
}
remove_runner_parent_credentials(&mut runner_command);
runner_command
.arg("--config")
.arg(&runner_config)
.current_dir(&paths.state)
.stdout(Stdio::from(runner_log))
.stderr(Stdio::from(runner_error))
.kill_on_drop(true);
let mut runner = match runner_command.spawn() {
Ok(runner) => runner,
Err(_) => {
stop_child(&mut server).await;
return Err(ProductError::new(
"agent_offline",
"the local Runner could not start",
Some("Run webcodex doctor."),
));
}
};
if let Err(error) = wait_for_ready(
&mut server,
&mut runner,
options,
&config,
&project_credential,
readiness_deadline,
)
.await
{
stop_child(&mut runner).await;
stop_child(&mut server).await;
return Err(error);
}
Ok(LocalRuntimeHandle {
project_name: config.project_name,
local_url,
public_url,
console_assets_dir,
server,
runner,
})
}
pub(crate) async fn start_runner(options: &ProjectCommandOptions) -> Result<(), ProductError> {
let mut runtime = start_local_runtime(options, LocalRuntimeOptions::default()).await?;
let mut started = format!(
"Project: {}\nConnection: connected at {}\nConsole: {}/runtime\nConsole assets: {}",
runtime.project_name,
runtime.local_url,
runtime.local_url,
if runtime.console_assets_dir.is_some() {
"local development"
} else {
"embedded"
}
);
if let Some(directory) = &runtime.console_assets_dir {
started.push_str(&format!("\nAssets directory: {}", directory.display()));
}
started.push_str("\nRunner: online\nCoding access: ready\n\nPress Ctrl-C to stop.");
println!("{started}");
let outcome = tokio::select! {
_ = wait_for_local_runtime_stop_signal() => Ok(()),
result = runtime.wait_for_exit() => result,
};
runtime.stop().await;
outcome
}
#[cfg(not(windows))]
async fn wait_for_local_runtime_stop_signal() {
let _ = tokio::signal::ctrl_c().await;
}
#[cfg(windows)]
async fn wait_for_local_runtime_stop_signal() {
let mut ctrl_break = match tokio::signal::windows::ctrl_break() {
Ok(signal) => signal,
Err(_) => {
let _ = tokio::signal::ctrl_c().await;
return;
}
};
tokio::select! {
_ = tokio::signal::ctrl_c() => {},
_ = ctrl_break.recv() => {},
}
}
fn resolve_console_assets_directory(
options: &ProjectCommandOptions,
) -> Result<Option<PathBuf>, ProductError> {
let Some(directory) = options.console_assets_dir.as_deref() else {
return Ok(None);
};
let source =
crate::console_web::ConsoleAssetSource::from_directory(directory).map_err(|error| {
ProductError::new(
"console_assets_invalid",
error.to_string(),
Some("Fix the development build directory, then retry."),
)
})?;
Ok(source.directory().map(Path::to_path_buf))
}
fn configure_console_assets_environment(command: &mut Command, directory: Option<&Path>) {
command.env_remove(crate::console_web::CONSOLE_ASSETS_DIR_ENV);
if let Some(directory) = directory {
command.env(crate::console_web::CONSOLE_ASSETS_DIR_ENV, directory);
}
}
fn locate_runner_binary() -> Option<PathBuf> {
if let Some(path) = std::env::var_os("WEBCODEX_AGENT_BIN").map(PathBuf::from) {
if path.is_file() {
return Some(path);