Repository navigation
Expand file tree
/
Copy pathconfig.rs
More file actions
744 lines (670 loc) · 26.8 KB
/
Copy pathconfig.rs
File metadata and controls
744 lines (670 loc) · 26.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
//! Credential storage, XDG paths, and the default API URL.
//!
//! Credentials live at
//! `$XDG_CONFIG_HOME/openresearch/credentials.json` (falling back to
//! `~/.config/openresearch/credentials.json`), written owner-only (mode 0600).
use std::path::PathBuf;
#[cfg(not(test))]
use dirs::home_dir;
use serde::{Deserialize, Serialize};
use tokio::fs;
use crate::error::Result;
/// Base URL of the API. Defaults to prod (`https://api.openresearch.sh`), so a
/// plain `orx login` just works. Override per-invocation with `--api-url` (handled
/// in the `login` command) or set the `OPENRESEARCH_API_URL` env var to point at
/// local dev, e.g. `OPENRESEARCH_API_URL=http://localhost:4000 orx login`.
pub fn default_api_url() -> String {
std::env::var("OPENRESEARCH_API_URL")
.unwrap_or_else(|_| "https://api.openresearch.sh".to_string())
}
/// Base URL for the alphaXiv JSON API (full-text literature search). Unlike the
/// OpenResearch API these endpoints are public — no token — and live on a
/// different host. Override with `ALPHAXIV_API_URL`.
pub fn alphaxiv_api_url() -> String {
std::env::var("ALPHAXIV_API_URL").unwrap_or_else(|_| "https://api.alphaxiv.org".to_string())
}
/// Base URL for the alphaXiv web app, which serves the per-paper `.md` routes
/// (`/overview/<id>.md` report, `/abs/<id>.md` full text). Default is the `www.`
/// host so we skip the apex→www 301. Override with `ALPHAXIV_WEB_URL`.
pub fn alphaxiv_web_url() -> String {
std::env::var("ALPHAXIV_WEB_URL").unwrap_or_else(|_| "https://www.alphaxiv.org".to_string())
}
/// Base URL for the OpenAlex REST API (scholarly works search). Public, no
/// token. Backs OpenAlex and bioRxiv discovery. Override with `OPENALEX_API_URL`.
pub fn openalex_api_url() -> String {
std::env::var("OPENALEX_API_URL").unwrap_or_else(|_| "https://api.openalex.org".to_string())
}
/// Base URL for the bioRxiv API (per-DOI preprint details). Public, no token.
/// Backs `orx paper <biorxiv-doi>`. Override with `BIORXIV_API_URL`.
pub fn biorxiv_api_url() -> String {
std::env::var("BIORXIV_API_URL").unwrap_or_else(|_| "https://api.biorxiv.org".to_string())
}
/// Base URL for NCBI E-utilities (PubMed search and records). Public, no
/// token. Backs PubMed discovery and `orx paper <pmid>`. Override with
/// `PUBMED_API_URL`.
pub fn pubmed_api_url() -> String {
std::env::var("PUBMED_API_URL")
.unwrap_or_else(|_| "https://eutils.ncbi.nlm.nih.gov/entrez/eutils".to_string())
}
/// Contact address sent to NCBI as `email=` alongside `tool=orx`, which NCBI
/// asks E-utilities clients to include. Override with `NCBI_EMAIL`.
pub fn ncbi_email() -> String {
std::env::var("NCBI_EMAIL").unwrap_or_else(|_| "orx@alphaxiv.org".to_string())
}
/// No default: OpenAlex has pooled keyless requests by `mailto`, so a shared
/// address would put every orx install on one daily budget.
pub fn openalex_mailto() -> Option<String> {
std::env::var("OPENALEX_MAILTO")
.ok()
.filter(|v| !v.trim().is_empty())
}
/// Without a key, OpenAlex shares one daily budget among everyone on the network's IP.
pub fn openalex_api_key() -> Option<String> {
std::env::var("OPENALEX_API_KEY")
.ok()
.filter(|v| !v.trim().is_empty())
}
/// Stored credentials: the API base URL and the bearer token.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Credentials {
#[serde(rename = "apiUrl")]
pub api_url: String,
pub token: String,
}
pub(crate) fn config_dir() -> PathBuf {
#[cfg(test)]
let base = test_home().join(".config");
#[cfg(not(test))]
let base = crate::local::shell_env::var("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| {
home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(".config")
});
base.join("openresearch")
}
#[cfg(test)]
fn home_dir() -> Option<PathBuf> {
Some(test_home())
}
/// Debug builds divide background timers (run supervision, turn leases) by `ORX_TEST_SPEEDUP`,
/// read once, so end-to-end tests finish in seconds.
pub(crate) fn paced(wait: std::time::Duration) -> std::time::Duration {
if !cfg!(debug_assertions) {
return wait;
}
static SPEEDUP: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
let speedup = SPEEDUP.get_or_init(|| {
std::env::var("ORX_TEST_SPEEDUP")
.ok()
.and_then(|value| value.parse().ok())
.unwrap_or(1)
});
wait / (*speedup).max(1)
}
/// Stands in for `$HOME` and the XDG dirs under test: one fresh directory per
/// process, so no test reads or writes the user's config or data.
#[cfg(test)]
pub(crate) fn test_home() -> PathBuf {
static HOME: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
HOME.get_or_init(|| {
std::env::temp_dir().join(format!("orx-test-home-{}", uuid::Uuid::new_v4()))
})
.clone()
}
/// Runs the calling test again, alone, in a child process with its own
/// [`test_home`] and without `cleared` vars, so its body may change
/// process-wide env. True in that child; in the parent, asserts the child passed.
#[cfg(test)]
pub(crate) fn in_test_child(cleared: &[&str]) -> bool {
const CHILD: &str = "ORX_TEST_CHILD";
let thread = std::thread::current();
let test = thread.name().expect("libtest names each test's thread");
if std::env::var_os(CHILD).is_some_and(|child| child == test) {
return true;
}
let temp = std::env::temp_dir().join(format!("orx-test-child-{}", uuid::Uuid::new_v4()));
std::fs::create_dir(&temp).unwrap();
let mut command = crate::process::command(std::env::current_exe().unwrap());
command
.args(["--exact", test])
.env(CHILD, test)
.env_remove("ORX_DATA_DIR");
// The child's temp dir, home included, goes away with it.
for var in ["TMPDIR", "TMP", "TEMP"] {
command.env(var, &temp);
}
for var in cleared {
command.env_remove(var);
}
let output = command.output().unwrap();
let _ = std::fs::remove_dir_all(&temp);
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains(" 1 passed"),
"{test} in its child process:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr)
);
false
}
/// Skips a test whose external tool this machine lacks; in CI the missing
/// tool is the failure.
#[cfg(test)]
pub(crate) fn skip_without_tool(missing: &str) {
assert!(
std::env::var_os("CI").is_none(),
"{missing}: CI must provide it"
);
eprintln!("skipped: {missing}");
}
fn credentials_path() -> PathBuf {
config_dir().join("credentials.json")
}
/// Whether `orx login` credentials exist on disk. A cheap sync fs probe for
/// summary views — whether the token still *works* is a network question
/// (`load_credentials` + an API call).
pub fn credentials_present() -> bool {
credentials_path().exists()
}
/// Reads stored credentials. Returns `Ok(None)` when the file is missing,
/// unreadable, malformed, or missing required fields — matching the TS
/// `loadCredentials`, which swallows all errors and returns `null`.
pub async fn load_credentials() -> Result<Option<Credentials>> {
let path = credentials_path();
let raw = match fs::read_to_string(&path).await {
Ok(raw) => raw,
Err(_) => return Ok(None),
};
match serde_json::from_str::<Credentials>(&raw) {
Ok(creds) if !creds.api_url.is_empty() && !creds.token.is_empty() => Ok(Some(creds)),
_ => Ok(None),
}
}
/// The signed-in API, else the default: where public endpoints such as project links resolve.
pub async fn openresearch_api_url() -> String {
match load_credentials().await {
Ok(Some(creds)) => creds.api_url,
_ => default_api_url(),
}
}
/// Persists credentials as pretty JSON with a trailing newline, mode 0600.
pub async fn save_credentials(creds: &Credentials) -> Result<()> {
let path = credentials_path();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).await?;
}
let body = format!("{}\n", serde_json::to_string_pretty(creds)?);
fs::write(&path, body).await?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = std::fs::Permissions::from_mode(0o600);
fs::set_permissions(&path, perms).await?;
}
Ok(())
}
/// Removes the credentials file. Succeeds even if it does not exist (`force`).
pub async fn clear_credentials() -> Result<()> {
match fs::remove_file(credentials_path()).await {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.into()),
}
}
/// Where the Overleaf Git authentication token and session cookie live. Deliberately *not*
/// `~/.openresearch/env`: `list_synced_env` fans that file out to every compute
/// backend and into the agent's environment, and nothing off this machine
/// pushes to Overleaf.
fn overleaf_credentials_path() -> PathBuf {
config_dir().join("overleaf.json")
}
#[derive(Default, Serialize, Deserialize)]
struct OverleafCredentials {
#[serde(default)]
token: String,
/// The browser session cookie the live editor channel authenticates with,
/// as `name=value`. Separate from the token: the git bridge is a paid
/// feature and the cookie is not, so either can be present alone.
#[serde(default)]
session: String,
/// The Overleaf host the cookie belongs to; it is sent nowhere else.
#[serde(default)]
session_host: String,
}
fn overleaf_credentials() -> OverleafCredentials {
std::fs::read_to_string(overleaf_credentials_path())
.ok()
.and_then(|raw| serde_json::from_str(&raw).ok())
.unwrap_or_default()
}
/// Writes owner-only, like `save_credentials` beside it. An empty file goes
/// away rather than lingering with nothing in it.
fn save_overleaf_credentials(credentials: &OverleafCredentials) -> Result<()> {
let path = overleaf_credentials_path();
if credentials.token.is_empty() && credentials.session.is_empty() {
return match std::fs::remove_file(&path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.into()),
};
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let body = serde_json::to_string_pretty(credentials)?;
std::fs::write(&path, format!("{body}\n"))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
fn non_empty(value: String) -> Option<String> {
let value = value.trim().to_string();
(!value.is_empty()).then_some(value)
}
pub fn overleaf_token() -> Option<String> {
non_empty(overleaf_credentials().token)
}
pub fn set_overleaf_token(token: &str) -> Result<()> {
let mut credentials = overleaf_credentials();
credentials.token = token.to_string();
save_overleaf_credentials(&credentials)
}
pub fn clear_overleaf_token() -> Result<()> {
let mut credentials = overleaf_credentials();
credentials.token.clear();
save_overleaf_credentials(&credentials)
}
/// The session cookie and the host it was issued by.
pub fn overleaf_session() -> Option<(String, String)> {
let credentials = overleaf_credentials();
let session = non_empty(credentials.session)?;
let host = non_empty(credentials.session_host)?;
Some((host, session))
}
pub fn set_overleaf_session(host: &str, session: &str) -> Result<()> {
let mut credentials = overleaf_credentials();
credentials.session = session.to_string();
credentials.session_host = host.to_string();
save_overleaf_credentials(&credentials)
}
pub fn clear_overleaf_session() -> Result<()> {
let mut credentials = overleaf_credentials();
credentials.session.clear();
credentials.session_host.clear();
save_overleaf_credentials(&credentials)
}
/// The user-chosen data dir, if one is persisted and non-empty. Consumed by
/// `store::data_dir()` between the `$ORX_DATA_DIR` override and the XDG default.
///
/// `settings.json` (in `config_dir()`, deliberately *outside* the data dir so it
/// can point *at* it without a chicken-and-egg) is owned by `crate::telemetry`,
/// which already guards it with an in-process mutex + cross-process flock +
/// atomic temp-and-rename RMW. We delegate rather than add a second writer — a
/// naive whole-object write here would clobber `installId`/`telemetryDisabled`
/// (and vice-versa). Sync because `store::data_dir()` calls it on every open.
pub fn settings_data_dir() -> Option<PathBuf> {
crate::telemetry::persisted_data_dir().map(PathBuf::from)
}
#[cfg(desktop_app)]
pub fn desktop_zoom_percent() -> i32 {
crate::telemetry::load_settings()
.and_then(|settings| settings.desktop_zoom_percent)
.filter(|percent| (50..=200).contains(percent))
.unwrap_or(100)
}
#[cfg(desktop_app)]
pub fn set_desktop_zoom_percent(percent: i32) -> Result<()> {
crate::telemetry::mutate_settings(|settings| settings.desktop_zoom_percent = Some(percent))?;
Ok(())
}
pub fn settings_cache_dir() -> Option<PathBuf> {
crate::telemetry::persisted_cache_dir().map(PathBuf::from)
}
/// Set or clear the persisted data dir, preserving every other settings field.
/// Delegates to `telemetry::set_persisted_data_dir` (the locked, atomic RMW).
/// `None` clears it (revert to the env/XDG/default chain).
pub fn set_settings_data_dir(data_dir: Option<String>) -> Result<()> {
crate::telemetry::set_persisted_data_dir(data_dir)?;
Ok(())
}
pub fn run_engine_settings() -> Result<(bool, Option<&'static str>)> {
let channel = crate::updates::current_release_channel();
let override_value = std::env::var_os("ORX_RUN_ENGINE");
let saved = crate::telemetry::load_settings().and_then(|settings| settings.run_engine);
run_engine_settings_for(channel, override_value.as_deref(), saved)
}
fn run_engine_settings_for(
channel: crate::updates::ReleaseChannel,
override_value: Option<&std::ffi::OsStr>,
saved: Option<bool>,
) -> Result<(bool, Option<&'static str>)> {
if channel == crate::updates::ReleaseChannel::Canary {
return Ok((true, Some("canary")));
}
match override_value {
Some(value) if value == "1" => Ok((true, Some("environment"))),
Some(value) if value == "0" => Ok((false, Some("environment"))),
None => Ok((saved.unwrap_or(false), None)),
Some(_) => Err(crate::error::anyhow!("ORX_RUN_ENGINE must be 1 or 0.")),
}
}
pub fn set_run_engine_enabled(enabled: bool) -> Result<()> {
crate::telemetry::mutate_settings(|settings| settings.run_engine = Some(enabled))?;
Ok(())
}
/// The persisted default compute target for local-mode launches, if any:
/// `(backend, flavor)`. Lives in the telemetry-owned `settings.json` for the
/// same single-writer reason as the data dir above.
pub fn compute_default() -> Option<(String, Option<String>)> {
crate::telemetry::compute_default()
}
/// Set or clear the default compute target, preserving every other settings
/// field. Delegates to `telemetry::set_compute_default` (the locked, atomic
/// RMW). `None` backend clears both backend and flavor.
pub fn set_compute_default(backend: Option<String>, flavor: Option<String>) -> Result<()> {
crate::telemetry::set_compute_default(backend, flavor)?;
Ok(())
}
/// Literature sources the user disabled in Settings (their `LitSource::as_str()`
/// names). Lives in the telemetry-owned `settings.json`; enforced by discovery,
/// `orx discover`, and `orx paper`. Empty = all enabled.
pub fn disabled_lit_sources() -> Vec<String> {
crate::telemetry::disabled_lit_sources()
}
pub fn github_for_new_projects() -> bool {
crate::telemetry::github_for_new_projects()
}
pub fn set_github_for_new_projects(enabled: bool) -> Result<()> {
crate::telemetry::set_github_for_new_projects(enabled)?;
Ok(())
}
/// Whether orx may install updates on its own (Settings → Updates). Lives in
/// the telemetry-owned `settings.json` for the same single-writer reason as the
/// data dir above. Read by `updates::auto_update_eligible`.
pub fn auto_update_enabled() -> bool {
crate::telemetry::auto_update_enabled()
}
pub fn set_auto_update_enabled(enabled: bool) -> Result<()> {
crate::telemetry::set_auto_update_enabled(enabled)?;
Ok(())
}
pub fn github_default_prompt_seen() -> bool {
crate::telemetry::github_default_prompt_seen()
}
pub fn set_github_default_prompt_seen(seen: bool) -> Result<()> {
crate::telemetry::set_github_default_prompt_seen(seen)?;
Ok(())
}
/// Look up a var from the box's synced env file (`~/.openresearch/env`, written
/// by the api's env sync). Needed because non-interactive shells never source
/// it via .bashrc (Ubuntu's interactive guard returns first), so an agent's
/// `orx` can't rely on the process environment alone. Parses only the exact
/// format the api writes: `export KEY='value'` with `\` doubled and `'`
/// written as `'\''`.
pub fn synced_env_var(key: &str) -> Option<String> {
let path = home_dir()?.join(".openresearch").join("env");
let content = std::fs::read_to_string(path).ok()?;
let prefix = format!("export {key}='");
for line in content.lines() {
let Some(rest) = line.strip_prefix(&prefix) else {
continue;
};
let Some(escaped) = rest.strip_suffix('\'') else {
continue;
};
// Invert buildEnvFile's escaping (quotes first, then backslashes).
let value = escaped.replace(r"'\''", "'").replace(r"\\", r"\");
if !value.is_empty() {
return Some(value);
}
}
None
}
/// All vars in the synced env file, in file order (same format as
/// `synced_env_var`). Malformed lines are skipped.
pub fn list_synced_env() -> Vec<(String, String)> {
let Some(path) = home_dir().map(|h| h.join(".openresearch").join("env")) else {
return Vec::new();
};
let Ok(content) = std::fs::read_to_string(path) else {
return Vec::new();
};
let mut out = Vec::new();
for line in content.lines() {
let Some(rest) = line.strip_prefix("export ") else {
continue;
};
let Some((key, quoted)) = rest.split_once('=') else {
continue;
};
let Some(escaped) = quoted.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) else {
continue;
};
let value = escaped.replace(r"'\''", "'").replace(r"\\", r"\");
if !key.is_empty() && !value.is_empty() {
out.push((key.to_string(), value));
}
}
out
}
/// Names the run inside its job, e.g. as a metric tracker's run name.
pub const RUN_ID_ENV: &str = "ORX_RUN_ID";
/// A run's environment: the synced env file plus what the run knows about itself.
pub fn run_env(run_id: &str) -> std::collections::HashMap<String, String> {
let mut env: std::collections::HashMap<String, String> =
list_synced_env().into_iter().collect();
env.extend(run_context_env(run_id));
env
}
/// What a launched job sees: [`run_env`] plus a configured Hugging Face token. Resolved at
/// launch, so secrets never enter a stored launch intent.
pub fn launch_env(run_id: &str) -> std::collections::HashMap<String, String> {
let mut env = run_env(run_id);
if let Ok(token) = crate::jobs::huggingface::resolve_token() {
env.entry("HF_TOKEN".to_string()).or_insert(token);
}
env
}
const EXPERIMENT_ENV: &str = "ORX_EXPERIMENT";
const EXPERIMENT_TITLE_ENV: &str = "ORX_EXPERIMENT_TITLE";
const PARENT_EXPERIMENT_ENV: &str = "ORX_PARENT_EXPERIMENT";
const COMMIT_ENV: &str = "ORX_COMMIT";
/// The run's id, experiment, parent, commit and Trackio project, read from its reserved row.
pub fn run_context_env(run_id: &str) -> Vec<(String, String)> {
let mut env = vec![(RUN_ID_ENV.to_string(), run_id.to_string())];
match stored_run_context(run_id) {
Ok(context) => env.extend(context),
Err(error) => {
eprintln!(
"warning: could not read run {run_id}'s experiment for its environment: {error}"
)
}
}
env
}
fn stored_run_context(run_id: &str) -> Result<Vec<(String, String)>> {
let store = crate::store::Store::open()?;
let Some(run) = store.get_run(run_id)? else {
return Ok(Vec::new());
};
let mut env = Vec::new();
if let Some(experiment) = store.get_local_experiment(&run.experiment_id)? {
let parent = match &experiment.parent_experiment_id {
Some(id) => store.get_local_experiment(id)?,
None => None,
};
if let Some(parent) = parent {
env.push((PARENT_EXPERIMENT_ENV.to_string(), parent.slug));
}
if let Some(title) = experiment.title.filter(|title| !title.trim().is_empty()) {
env.push((EXPERIMENT_TITLE_ENV.to_string(), title));
}
env.push((EXPERIMENT_ENV.to_string(), experiment.slug));
}
if let Some(commit) = run.commit_sha.filter(|sha| !sha.is_empty()) {
env.push((COMMIT_ENV.to_string(), commit));
}
if let Some(project) = store.get_local_project(&run.project_id)? {
env.push((
crate::local::trackio::PROJECT.to_string(),
crate::local::trackio::project_for(&project.slug),
));
}
Ok(env)
}
/// Drop `key`'s line from the synced env file. Missing file/key is a no-op.
pub fn remove_synced_env_var(key: &str) -> Result<()> {
let Some(path) = home_dir().map(|h| h.join(".openresearch").join("env")) else {
return Ok(());
};
let Ok(existing) = std::fs::read_to_string(&path) else {
return Ok(());
};
let prefix = format!("export {key}=");
let lines: Vec<&str> = existing
.lines()
.filter(|l| !l.starts_with(&prefix))
.collect();
let body = if lines.is_empty() {
String::new()
} else {
format!("{}\n", lines.join("\n"))
};
std::fs::write(&path, body)?;
Ok(())
}
/// Write `export KEY='value'` into `~/.openresearch/env` (the exact format
/// `synced_env_var` parses), replacing an existing line for `key` and keeping
/// every other line. File is owner-only (0600) on create and rewrite.
pub fn write_synced_env_var(key: &str, value: &str) -> Result<()> {
write_synced_env_vars(&[(key, value)])
}
pub fn write_synced_env_vars(values: &[(&str, &str)]) -> Result<()> {
use anyhow::anyhow;
let dir = home_dir()
.ok_or_else(|| anyhow!("no home directory"))?
.join(".openresearch");
std::fs::create_dir_all(&dir)?;
let path = dir.join("env");
let existing = std::fs::read_to_string(&path).unwrap_or_default();
let mut lines: Vec<String> = existing.lines().map(str::to_string).collect();
for (key, value) in values {
// Inverse of synced_env_var's unescaping: backslashes first, then quotes.
let escaped = value.replace('\\', r"\\").replace('\'', r"'\''");
let new_line = format!("export {key}='{escaped}'");
let prefix = format!("export {key}=");
let mut replaced = false;
lines.retain_mut(|line| {
if !line.starts_with(&prefix) {
return true;
}
if replaced {
return false;
}
*line = new_line.clone();
replaced = true;
true
});
if !replaced {
lines.push(new_line);
}
}
let body = format!("{}\n", lines.join("\n"));
{
use std::io::Write;
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600); // applies on create only
}
opts.open(&path)?.write_all(body.as_bytes())?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SshHostSettings {
pub container: Option<String>,
/// Absolute storage root for runs and the source cache; `None` is `~/.orx`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remote_root: Option<String>,
/// Keep every finished run's remote dir, not just each project's newest few.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub keep_remote_runs: bool,
/// Fields from a newer orx, kept across this version's saves.
#[serde(flatten)]
pub unknown: serde_json::Map<String, serde_json::Value>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SshSettings {
pub default_host: Option<String>,
#[serde(default)]
pub hosts: std::collections::BTreeMap<String, SshHostSettings>,
/// Fields from a newer orx, kept across this version's saves.
#[serde(flatten)]
pub unknown: serde_json::Map<String, serde_json::Value>,
}
pub fn ssh_settings() -> Result<SshSettings> {
crate::telemetry::ssh_settings()
}
pub fn set_ssh_host(host: String, options: SshHostSettings) -> Result<()> {
crate::jobs::ssh::validate_host_options(&options)?;
crate::telemetry::set_ssh_host(host, options)?;
Ok(())
}
pub fn set_ssh_default(host: Option<String>) -> Result<()> {
crate::telemetry::set_ssh_default(host)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::updates::ReleaseChannel;
use std::ffi::OsStr;
#[test]
fn canary_forces_the_engine_while_stable_and_dev_allow_opt_in() {
for saved in [None, Some(false), Some(true)] {
for value in [None, Some("0"), Some("1"), Some("invalid")] {
let value = value.map(OsStr::new);
assert_eq!(
run_engine_settings_for(ReleaseChannel::Canary, value, saved).unwrap(),
(true, Some("canary"))
);
let stable = run_engine_settings_for(ReleaseChannel::Stable, value, saved);
match value {
None => assert_eq!(stable.unwrap(), (saved.unwrap_or(false), None)),
Some(value) if value == "0" => {
assert_eq!(stable.unwrap(), (false, Some("environment")))
}
Some(value) if value == "1" => {
assert_eq!(stable.unwrap(), (true, Some("environment")))
}
Some(_) => assert!(stable.is_err()),
}
}
}
}
#[cfg(unix)]
#[test]
fn canary_ignores_even_a_non_unicode_environment_override() {
use std::os::unix::ffi::OsStrExt;
let value = Some(OsStr::from_bytes(&[0xff]));
assert_eq!(
run_engine_settings_for(ReleaseChannel::Canary, value, None).unwrap(),
(true, Some("canary"))
);
assert!(run_engine_settings_for(ReleaseChannel::Stable, value, None).is_err());
}
}