gent-link 0.1.0

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
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
//! Per-user service lifecycle. No account/model credentials enter service files.
mod command;
mod display;
mod files;
pub use command::GatewayCommand;
use command::{Action, Install};
pub use display::print;
mod manager;
mod startup;
use crate::{DaemonCommand, managed_file, owner};
use anyhow::{Context, Result, ensure};
use files::{Kind, Platform, Spec};
use fs2::FileExt;
use gent_daemon::config;
use gent_protocol::OwnerOp;
use manager::{Manager, State};
use serde_json::{Value, json};
use std::{
    fs,
    io::{Read, Seek, SeekFrom},
    os::unix::fs::OpenOptionsExt,
    path::{Path, PathBuf},
    time::Duration,
};

struct Service {
    home: PathBuf,
    path: PathBuf,
    manager: Manager,
    kind: Kind,
}
impl Service {
    async fn new(home: &Path) -> Result<Self> {
        Self::with_kind(home, Kind::Daemon).await
    }
    async fn with_kind(home: &Path, kind: Kind) -> Result<Self> {
        let platform = Platform::native()?;
        let home = files::normalize(home)?;
        let user_home = PathBuf::from(
            std::env::var_os("HOME").context("HOME is required to locate user services")?,
        );
        let xdg = std::env::var_os("XDG_CONFIG_HOME")
            .filter(|v| !v.is_empty())
            .map(PathBuf::from);
        let path = files::location(platform, &home, &user_home, xdg.as_deref(), kind)?;
        let manager = Manager {
            platform,
            uid: manager::uid().await?,
            label: kind.label(platform, &home),
        };
        Ok(Self {
            home,
            path,
            manager,
            kind,
        })
    }
    fn installed(&self) -> Result<Option<Spec>> {
        files::read(
            &self.path,
            self.manager.platform,
            &self.home,
            self.manager.uid,
            self.kind,
        )
    }
    /// A daemon that execs an update retains its manager PID. Stage its policy
    /// without starting, enabling or stopping any job. Only systemd can apply
    /// the definition to the live PID; launchd reads it on the next bootstrap.
    fn upgrade_running_policy(&self, binary: &Path, state: &State) -> Result<bool> {
        if !state.running || state.pid != Some(std::process::id()) {
            return Ok(false);
        }
        let candidate = || -> Result<Option<Spec>> {
            Ok(self.installed()?.filter(|s| {
                s.kind() == Kind::Daemon
                    && s.binary == binary
                    && (s.legacy_daemon() || state.need_reload)
            }))
        };
        if candidate()?.is_none() {
            return Ok(false);
        }
        let _lock = self.lock()?;
        let Some(spec) = candidate()? else {
            return Ok(false);
        };
        if spec.legacy_daemon() {
            spec.upgrade_daemon(&self.path)?;
        }
        Ok(self.manager.platform == Platform::Systemd)
    }
    fn lock(&self) -> Result<fs::File> {
        ensure!(
            self.home.is_dir(),
            "Gent state directory is unavailable; restore it before changing its service"
        );
        config::private_dir(&self.home)?;
        let path = self.home.join(self.kind.lock());
        match fs::symlink_metadata(&path) {
            Ok(_) => files::owned_regular(&path, self.manager.uid)?,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => return Err(e.into()),
        }
        let lock = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .mode(0o600)
            .open(path)?;
        lock.try_lock_exclusive()
            .context("another Gent service operation is running; retry when it finishes")?;
        Ok(lock)
    }
    async fn probe(&self) -> Result<Value> {
        tokio::time::timeout(Duration::from_secs(1), async {
            match self.kind {
                Kind::Daemon => owner(&self.home, OwnerOp::Status).await,
                Kind::Gateway => crate::gateway::control::probe(&self.home).await,
            }
        })
        .await
        .context("Gent process did not respond")?
    }
    async fn status(&self) -> Value {
        let installed = self.installed();
        let mut state = self.manager.inspect().await;
        state.enabled &= matches!(&installed, Ok(Some(_)));
        let probe = self.probe().await;
        let running = probe.is_ok();
        let pid = probe.as_ref().ok().and_then(|v| v["process_id"].as_u64());
        let managed = running && pid == state.pid.map(u64::from);
        let mut value = probe.as_ref().ok().cloned().unwrap_or_else(|| json!({}));
        value[self.kind.name()] = json!({"running":running,"managed":managed,"pid":pid,"error":probe.err().map(|e|e.to_string())});
        value["service"] = serde_json::to_value(&state).expect("service status serializes");
        value["service"]["kind"] = json!(self.kind.name());
        value["service"]["backend"] = json!(self.manager.platform);
        value["service"]["installed"] = json!(matches!(&installed, Ok(Some(_))));
        value["service"]["label"] = self.manager.label.clone().into();
        value["service"]["file"] = json!(self.path);
        value["service"]["home"] = json!(self.home);
        let enabled = if matches!(&installed, Ok(None)) {
            Some(false)
        } else {
            (installed.is_ok() && state.available).then_some(state.enabled)
        };
        value["service"]["startup"] =
            json!(startup::inspect(self.manager.platform, self.manager.uid, enabled).await);
        if let Err(error) = installed {
            value["service"]["file_error"] = error.to_string().into();
        }
        value
    }
    async fn no_foreground(&self, state: &State) -> Result<()> {
        if let Ok(value) = self.probe().await {
            ensure!(
                value["process_id"].as_u64() == state.pid.map(u64::from),
                "a foreground or externally managed {} is using this state directory; stop it before controlling its service",
                self.kind.name()
            );
        }
        Ok(())
    }
    async fn wait(&self, running: bool) -> Result<()> {
        // A fresh database can still be initializing at ten seconds on slow
        // storage. Keep waiting for authenticated readiness from the same
        // managed process; a live PID alone is never sufficient.
        let timeout = Duration::from_secs(if running { 30 } else { 10 });
        let until = tokio::time::Instant::now() + timeout;
        loop {
            if let Ok(value) = self.probe().await {
                if running {
                    let state = self.manager.inspect().await;
                    if state.running && value["process_id"].as_u64() == state.pid.map(u64::from) {
                        return Ok(());
                    }
                }
            } else if !running {
                let state = self.manager.inspect().await;
                if state.available && !state.running && state.pid.is_none() {
                    return Ok(());
                }
            }
            ensure!(
                tokio::time::Instant::now() < until,
                "{} did not reach the requested state within {} seconds; inspect its service status and logs",
                self.kind.name(),
                timeout.as_secs()
            );
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    }
    fn prepare_log(&self) -> Result<()> {
        if self.manager.platform == Platform::Launchd {
            let path = self.home.join(format!("{}.log", self.kind.name()));
            match fs::symlink_metadata(&path) {
                Ok(_) => files::owned_regular(&path, self.manager.uid)?,
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => return Err(e.into()),
            }
            fs::OpenOptions::new()
                .append(true)
                .create(true)
                .mode(0o600)
                .open(path)?;
        }
        Ok(())
    }
    async fn logs(&self, lines: u32) -> Result<Value> {
        self.installed()?; // Never inspect an unrelated service under this label.
        let text = match self.manager.platform {
            Platform::Systemd => self.manager.journal(lines).await?,
            Platform::Launchd => {
                let path = self.home.join(format!("{}.log", self.kind.name()));
                if !path.exists() {
                    String::new()
                } else {
                    files::owned_regular(&path, self.manager.uid)?;
                    let mut file = fs::File::open(path)?;
                    let start = file.metadata()?.len().saturating_sub(2 * 1024 * 1024);
                    file.seek(SeekFrom::Start(start))?;
                    let mut bytes = Vec::new();
                    file.take(2 * 1024 * 1024).read_to_end(&mut bytes)?;
                    let text = String::from_utf8_lossy(&bytes);
                    let mut rows: Vec<_> = text.lines().collect();
                    if start > 0 && !rows.is_empty() {
                        rows.remove(0);
                    }
                    rows[rows.len().saturating_sub(lines as usize)..].join("\n")
                }
            }
        };
        Ok(
            json!({"backend":self.manager.platform,"label":self.manager.label,"lines":text.lines().collect::<Vec<_>>() }),
        )
    }
}

/// Fail before guided login/enrollment when this machine cannot install a service.
pub async fn preflight(home: &Path) -> Result<()> {
    let service = Service::new(home).await?;
    let state = service.manager.inspect().await;
    ensure!(
        state.available,
        "{}",
        state
            .error
            .as_deref()
            .unwrap_or("user service manager is unavailable; use gent daemon run")
    );
    ensure!(
        service.installed()?.is_some() || !state.loaded,
        "a service with this label is loaded without Gent's managed file; inspect {}",
        service.path.display()
    );
    service.no_foreground(&state).await
}

/// Inspect only the manager and registration. Doctor uses its own read-only
/// daemon operation instead of the ordinary status/projection path.
pub(crate) async fn diagnose(home: &Path) -> Result<Value> {
    let service = Service::new(home).await?;
    let installed = service.installed()?;
    let state = service.manager.inspect().await;
    Ok(
        json!({"installed":installed.is_some(),"available":state.available,
        "binary_available":installed.as_ref().is_some_and(|s| s.binary.is_file()),
        "loaded":state.loaded,"running":state.running,"enabled":state.enabled,
        "pid":state.pid,"last_exit":state.last_exit}),
    )
}

/// Upgrade older managed installations when their new daemon first starts.
pub(crate) async fn migrate_installation(home: &Path) -> Result<()> {
    let service = Service::new(home).await?;
    let binary = std::env::current_exe()?;
    let still_installed = || {
        Ok(service
            .installed()?
            .is_some_and(|spec| spec.binary == binary))
    };
    if still_installed()? {
        if let Err(error) = crate::desktop::migrate(&service.home, still_installed) {
            eprintln!("Gent Desktop login setup: {error:#}. Retry with gent desktop enable.");
        }
        let state = service.manager.inspect().await;
        if service.upgrade_running_policy(&binary, &state)? {
            service.manager.reload().await?;
        }
    }
    Ok(())
}

pub async fn execute(home: &Path, action: DaemonCommand) -> Result<Value> {
    let _progress = crate::ui::Progress::start("Checking daemon service");
    control(home, Kind::Daemon, action.into()).await
}

pub(crate) fn validate_linger(requested: bool) -> Result<()> {
    ensure!(
        !requested || Platform::native()? == Platform::Systemd,
        "--linger is only supported on Linux; macOS uses a login LaunchAgent"
    );
    Ok(())
}

pub(crate) async fn enable_linger() -> Result<()> {
    validate_linger(true)?;
    startup::enable(manager::uid().await?).await
}

pub(crate) async fn gateway(home: &Path, action: GatewayCommand) -> Result<Value> {
    control(home, Kind::Gateway, action.into()).await
}

async fn control(home: &Path, kind: Kind, mut action: Action) -> Result<Value> {
    let service = Service::with_kind(home, kind).await?;
    match action {
        Action::Status => return Ok(service.status().await),
        Action::Logs { lines } => return service.logs(lines).await,
        _ => {}
    }
    let before = service.manager.inspect().await;
    ensure!(
        before.available,
        "{}",
        before
            .error
            .as_deref()
            .unwrap_or("user service manager is unavailable; use gent daemon run")
    );
    let previous = service.installed()?;
    if previous.is_none() {
        ensure!(
            !before.loaded,
            "a service with this label is already loaded without Gent's managed file; inspect {}",
            service.path.display()
        );
    }
    match &action {
        Action::Install(Install::Daemon { local }) => {
            if !config::path(&service.home).exists() {
                local.as_deref().context("no Gent configuration; run gent auth login and gent cluster new NAME, or use gent daemon install --local NAME for a development cluster")?;
                config::private_dir(&service.home)?;
            }
        }
        Action::Uninstall
            if previous.is_none()
                && (!matches!(kind, Kind::Daemon)
                    || !crate::desktop::previously_configured(&service.home)?) =>
        {
            return Ok(service.status().await);
        }
        Action::Install(Install::Gateway(_)) => {
            config::load(&service.home)?;
        }
        Action::Uninstall => {}
        _ => ensure!(
            previous.is_some(),
            "service is not installed; install it first"
        ),
    }
    let _lock = service.lock()?;
    // Recheck ownership after acquiring the per-state mutation lock.
    let previous = service.installed()?;
    let before = service.manager.inspect().await;
    ensure!(
        before.available,
        "user service manager became unavailable; retry the command"
    );
    ensure!(
        previous.is_some() || !before.loaded,
        "loaded service has no Gent-managed file; inspect {}",
        service.path.display()
    );
    if matches!(action, Action::Uninstall) && previous.is_none() {
        if matches!(kind, Kind::Daemon) {
            crate::desktop::removed(&service.home)?;
        }
        return Ok(service.status().await);
    }
    if let Action::Install(Install::Daemon { local }) = &action {
        if !config::path(&service.home).exists() {
            let _daemon = managed_file::lock(&service.home.join("daemon.lock"))?;
            let name = local
                .as_deref()
                .context("Gent configuration disappeared; restore it before installing")?;
            ensure!(
                fs::read_dir(&service.home)?.all(|entry| entry.is_ok_and(|e| matches!(
                    e.file_name().to_str(),
                    Some("service.lock" | "daemon.lock" | "auth")
                ))),
                "state exists without config.toml; restore the configuration before installing"
            );
            config::initialize(&service.home, name)?;
        }
        config::load(&service.home)?;
        config::read_private(&service.home.join("owner.key"))?;
    }
    service.no_foreground(&before).await?;
    if let Action::Install(Install::Gateway(options)) = &mut action {
        *options = options.for_service(&service.home).await?;
    }
    if matches!(action, Action::Start | Action::Restart)
        && let Some(options) = previous.as_ref().and_then(|spec| spec.gateway.as_ref())
    {
        options.for_service(&service.home).await?;
    }
    match action {
        Action::Install(installation) => {
            let binary = fs::canonicalize(std::env::current_exe()?)
                .context("cannot locate the running Gent binary; reinstall it first")?;
            let desired = match installation {
                Install::Daemon { .. } => {
                    Spec::new(service.manager.platform, service.home.clone(), binary)?
                }
                Install::Gateway(options) => Spec::gateway(
                    service.manager.platform,
                    service.home.clone(),
                    binary,
                    options,
                )?,
            };
            let changed =
                previous.as_ref().map(|spec| spec.render()).transpose()? != Some(desired.render()?);
            service.prepare_log()?;
            let policy_only = previous
                .as_ref()
                .filter(|spec| spec.legacy_daemon() && spec.binary == desired.binary);
            if let Some(legacy) = policy_only {
                legacy.upgrade_daemon(&service.path)?;
            } else if changed {
                files::write(&service.path, &desired)?;
            }
            let reconfigure = if policy_only.is_some() {
                before.stopped_launch_agent(&service.path)
            } else {
                changed
            };
            service
                .manager
                .install(&service.path, reconfigure, &before)
                .await
                .context("service installation failed; inspect its service status and logs")?;
            service.wait(true).await?;
            if matches!(kind, Kind::Daemon)
                && let Err(error) = crate::desktop::installed(&service.home)
            {
                eprintln!("Gent Desktop login setup: {error:#}. Retry with gent desktop enable.");
            }
        }
        Action::Start | Action::Restart => {
            let spec = previous.context("service was uninstalled; install it again")?;
            if spec.legacy_daemon() && spec.binary == std::env::current_exe()? {
                spec.upgrade_daemon(&service.path)?;
            }
            service.prepare_log()?;
            // A loaded, stopped LaunchAgent can still have its old KeepAlive
            // policy in memory. Bootstrap the on-disk daemon definition.
            let rebootstrap = kind == Kind::Daemon
                && service.manager.platform == Platform::Launchd
                && before.stopped_launch_agent(&service.path);
            service
                .manager
                .start(
                    &service.path,
                    &before,
                    matches!(action, Action::Restart) || rebootstrap,
                )
                .await?;
            service.wait(true).await?;
        }
        Action::Stop => {
            service.manager.stop(&before).await?;
            service.wait(false).await?;
        }
        Action::Uninstall => {
            service.manager.uninstall(&before).await?;
            service.wait(false).await?;
            service
                .installed()?
                .context("service file disappeared during uninstall")?;
            fs::remove_file(&service.path)?;
            fs::File::open(service.path.parent().unwrap())?.sync_all()?;
            service.manager.reload().await?;
            if matches!(kind, Kind::Daemon) {
                crate::desktop::removed(&service.home)?;
            }
        }
        _ => unreachable!(),
    }
    Ok(service.status().await)
}

/// Stop both Gent-owned processes before their state is archived. An absent
/// service needs no manager; an installed service must be removed normally.
pub(crate) async fn retire(home: &Path) -> Result<()> {
    for kind in [Kind::Gateway, Kind::Daemon] {
        let service = Service::with_kind(home, kind).await?;
        if service.installed()?.is_some() {
            control(home, kind, Action::Uninstall).await?;
        } else {
            let state = service.manager.inspect().await;
            ensure!(
                !state.loaded,
                "a Gent service is loaded without its registration; inspect service status before resetting"
            );
            service.no_foreground(&state).await?;
            if matches!(kind, Kind::Daemon) && crate::desktop::previously_configured(&service.home)?
            {
                crate::desktop::removed(&service.home)?;
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests;