supercode-harness 0.4.23

The optional native Supercode agent and tool harness
Documentation
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
//! Where supercode-teams lives on this box, and the service unit that keeps
//! its node up (`docs/architecture/teams.md`).
//!
//! supercode does not implement teams; the `sdk/teams` package does. This
//! module holds the two facts the Rust CLI needs about it:
//!
//! * **where its Node entry is** — [`teams_entry`], resolved exactly the way
//!   [`crate::orchestrator::daemon_entry`] resolves the orchestrator's:
//!   `SUPERCODE_TEAMS_ENTRY` first, then the checkout the running binary sits
//!   in, then the current directory, then the globally installed
//!   `@volter-ai-dev/supercode-teams` package (`npm root -g`).
//! * **what a service unit for its node would say** — [`service_unit`] renders
//!   the launchd plist / systemd unit that runs `node <entry> node start
//!   --listen 127.0.0.1:0`, written under `<home>/service/`;
//!   [`install_service`] and [`uninstall_service`] drive `launchctl` /
//!   `systemctl --user` over it.
//!
//! Everything else about teams — its keys, grants, log, machines — is the Node
//! package's own state, written by its own CLI. There is no second writer of
//! that home in this binary.

use std::path::{Path, PathBuf};

use crate::orchestrator::{absolute_program, ServiceState, ServiceUnit};

/// The teams CLI entry inside the `sdk/teams` package.
pub const TEAMS_ENTRY: &str = "bin/teams.mjs";

/// The npm name the `sdk/teams` package is published under.
pub const TEAMS_PACKAGE: &str = "@volter-ai-dev/supercode-teams";

/// Directory the rendered service unit is written into, relative to the home.
pub const SERVICE_DIR: &str = "service";

/// launchd label / systemd unit name for this Machine's teams node.
pub const SERVICE_NAME: &str = "dev.volter.supercode-teams-node";

/// Why a teams verb could not do its work.
#[derive(Debug, thiserror::Error)]
pub enum TeamsError {
    /// The Node teams entry could not be located.
    #[error("no teams entry found (looked for `sdk/teams/{TEAMS_ENTRY}` under: {searched}); install it with `npm install -g {TEAMS_PACKAGE}`")]
    NoEntry {
        /// The candidate paths that were searched, joined.
        searched: String,
    },
    /// A service manager refused, or there is none on this platform.
    #[error("teams service: {action} failed: {detail}")]
    Service {
        /// What was attempted (`install`, `uninstall`).
        action: &'static str,
        /// What the service manager (or this module) said about it.
        detail: String,
    },
    /// A file under the teams home could not be written or removed.
    #[error("teams file `{}`: {source}", path.display())]
    File {
        /// The path involved.
        path: PathBuf,
        /// The underlying I/O failure.
        source: std::io::Error,
    },
}

/// The teams home: `SUPERCODE_TEAMS_HOME`, else `<SUPERCODE_HOME>/teams`.
///
/// The same precedence `sdk/teams/home.mjs` uses, so a unit installed from
/// here serves the home the Node CLI reads.
pub fn teams_home() -> PathBuf {
    if let Ok(home) = std::env::var("SUPERCODE_TEAMS_HOME") {
        if !home.is_empty() {
            return PathBuf::from(home);
        }
    }
    crate::agent::global_instructions_dir().join("teams")
}

/// Locate the Node teams entry (`sdk/teams/bin/teams.mjs`).
///
/// Candidates, in order: `SUPERCODE_TEAMS_ENTRY` (an explicit override, which
/// is also how a test points at a fake), the repo checkout the running binary
/// sits in, the current directory, the workspace this crate was built from,
/// and the globally installed npm package — an installed binary has no
/// checkout, so `npm install -g @volter-ai-dev/supercode-teams` is how a
/// Machine gets its node.
pub fn teams_entry() -> Result<PathBuf, TeamsError> {
    let mut searched = Vec::new();
    if let Some(explicit) = std::env::var_os("SUPERCODE_TEAMS_ENTRY") {
        let path = PathBuf::from(explicit);
        if path.is_file() {
            return Ok(path);
        }
        searched.push(path.display().to_string());
    }
    let mut roots: Vec<PathBuf> = Vec::new();
    if let Ok(exe) = std::env::current_exe() {
        // target/<profile>/supercode → the workspace root is two levels up.
        roots.extend(exe.ancestors().skip(1).take(4).map(Path::to_path_buf));
    }
    if let Ok(cwd) = std::env::current_dir() {
        roots.push(cwd);
    }
    // A locally built binary's target directory can live anywhere (a shared
    // cargo build dir, another volume), so the checkout it was built from is
    // the last candidate. On an installed binary this path simply does not
    // exist and is skipped like any other miss.
    if let Some(workspace) = Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2) {
        roots.push(workspace.to_path_buf());
    }
    for root in roots {
        let candidate = root.join("sdk/teams").join(TEAMS_ENTRY);
        if candidate.is_file() {
            return Ok(candidate);
        }
        searched.push(candidate.display().to_string());
    }
    if let Some(global) = global_npm_root() {
        let candidate = global.join(TEAMS_PACKAGE).join(TEAMS_ENTRY);
        if candidate.is_file() {
            return Ok(candidate);
        }
        searched.push(candidate.display().to_string());
    }
    Err(TeamsError::NoEntry {
        searched: searched.join(", "),
    })
}

/// Where npm installs global packages (`npm root -g`), when npm is present.
fn global_npm_root() -> Option<PathBuf> {
    let output = std::process::Command::new("npm")
        .args(["root", "-g"])
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let root = text.trim();
    if root.is_empty() {
        return None;
    }
    Some(PathBuf::from(root))
}

/// Render the per-platform service unit for this Machine's teams node.
///
/// The node takes no `--root`: it serves the home its own environment
/// resolves (`SUPERCODE_TEAMS_HOME`, else `<SUPERCODE_HOME>/teams`), so the
/// unit names the listen address and nothing else. A port of `0` means the
/// node picks one and publishes it in `<home>/node.json`.
pub fn service_unit(home: &Path, entry: &Path, node: &str) -> ServiceUnit {
    let home_display = home.display().to_string();
    let entry_display = entry.display().to_string();
    if cfg!(target_os = "macos") {
        let path = home.join(SERVICE_DIR).join(format!("{SERVICE_NAME}.plist"));
        let text = format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>{SERVICE_NAME}</string>
  <key>ProgramArguments</key>
  <array>
    <string>{node}</string>
    <string>{entry_display}</string>
    <string>node</string>
    <string>start</string>
    <string>--listen</string>
    <string>127.0.0.1:0</string>
  </array>
  <key>EnvironmentVariables</key>
  <dict>
    <key>SUPERCODE_TEAMS_HOME</key><string>{home_display}</string>
  </dict>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>{home_display}/service/teams-node.out.log</string>
  <key>StandardErrorPath</key><string>{home_display}/service/teams-node.err.log</string>
</dict>
</plist>
"#
        );
        let install = format!("launchctl bootstrap gui/$(id -u) {}", path.display());
        ServiceUnit {
            kind: "launchd",
            path,
            text,
            install_command: install,
        }
    } else {
        let path = home
            .join(SERVICE_DIR)
            .join(format!("{SERVICE_NAME}.service"));
        let text = format!(
            "[Unit]\n\
             Description=supercode teams node ({home_display})\n\
             After=network.target\n\
             \n\
             [Service]\n\
             Environment=SUPERCODE_TEAMS_HOME={home_display}\n\
             ExecStart={node} {entry_display} node start --listen 127.0.0.1:0\n\
             Restart=on-failure\n\
             KillSignal=SIGTERM\n\
             \n\
             [Install]\n\
             WantedBy=default.target\n"
        );
        let install = format!(
            "systemctl --user link {} && systemctl --user enable --now {SERVICE_NAME}",
            path.display()
        );
        ServiceUnit {
            kind: "systemd",
            path,
            text,
            install_command: install,
        }
    }
}

/// Write a rendered unit under `<home>/service/`.
pub fn write_unit(unit: &ServiceUnit) -> Result<(), TeamsError> {
    if let Some(parent) = unit.path.parent() {
        std::fs::create_dir_all(parent).map_err(|source| TeamsError::File {
            path: unit.path.clone(),
            source,
        })?;
    }
    std::fs::write(&unit.path, &unit.text).map_err(|source| TeamsError::File {
        path: unit.path.clone(),
        source,
    })
}

/// Run a service-manager command and return (success, stdout+stderr).
fn run_tool(program: &str, args: &[&str]) -> Result<(bool, String), std::io::Error> {
    let output = std::process::Command::new(program).args(args).output()?;
    let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
    text.push_str(&String::from_utf8_lossy(&output.stderr));
    Ok((output.status.success(), text.trim().to_string()))
}

#[cfg(target_os = "macos")]
fn gui_domain() -> String {
    // SAFETY: `getuid` reads this process's own real user id and cannot fail.
    format!("gui/{}", unsafe { libc::getuid() })
}

/// What the platform's service manager says about the teams node unit.
///
/// Never starts or installs anything.
pub fn service_status() -> ServiceState {
    platform_status()
}

#[cfg(target_os = "macos")]
fn platform_status() -> ServiceState {
    let label = SERVICE_NAME.to_string();
    let target = format!("{}/{SERVICE_NAME}", gui_domain());
    match run_tool("launchctl", &["print", &target]) {
        Ok((true, text)) => ServiceState {
            kind: "launchd",
            label,
            installed: true,
            pid: field_of(&text, "pid = ").and_then(|value| value.parse().ok()),
            detail: field_of(&text, "state = ").unwrap_or_else(|| "loaded".into()),
        },
        Ok((false, _)) => ServiceState {
            kind: "launchd",
            label,
            installed: false,
            pid: None,
            detail: format!("not bootstrapped in {}", gui_domain()),
        },
        Err(error) => ServiceState {
            kind: "launchd",
            label,
            installed: false,
            pid: None,
            detail: format!("launchctl unavailable: {error}"),
        },
    }
}

#[cfg(all(unix, not(target_os = "macos")))]
fn platform_status() -> ServiceState {
    let label = SERVICE_NAME.to_string();
    match run_tool("systemctl", &["--user", "is-active", SERVICE_NAME]) {
        Ok((active, text)) => {
            let known = run_tool("systemctl", &["--user", "is-enabled", SERVICE_NAME])
                .map(|(ok, _)| ok)
                .unwrap_or(false);
            ServiceState {
                kind: "systemd",
                label,
                installed: active || known,
                pid: None,
                detail: if text.is_empty() {
                    "unknown".into()
                } else {
                    text
                },
            }
        }
        Err(error) => ServiceState {
            kind: "systemd",
            label,
            installed: false,
            pid: None,
            detail: format!("systemctl unavailable: {error}"),
        },
    }
}

#[cfg(not(unix))]
fn platform_status() -> ServiceState {
    ServiceState {
        kind: "none",
        label: SERVICE_NAME.to_string(),
        installed: false,
        pid: None,
        detail: "no service manager on this platform".into(),
    }
}

/// `key = value` out of a service manager's block output.
#[cfg(target_os = "macos")]
fn field_of(text: &str, key: &str) -> Option<String> {
    text.lines()
        .find_map(|line| line.trim().strip_prefix(key))
        .map(|value| value.trim().to_string())
}

/// The file name the unit takes on this platform.
fn unit_file_name() -> String {
    if cfg!(target_os = "macos") {
        format!("{SERVICE_NAME}.plist")
    } else {
        format!("{SERVICE_NAME}.service")
    }
}

/// Render the unit, hand it to the platform's service manager, and start it.
///
/// Refuses a label the manager already holds rather than replacing it: two
/// homes share one label, so an install that silently took it over would point
/// a running node at a different folder.
pub fn install_service(
    home: &Path,
    entry: &Path,
    node: &str,
) -> Result<(ServiceUnit, ServiceState), TeamsError> {
    let existing = service_status();
    if existing.installed {
        return Err(TeamsError::Service {
            action: "install",
            detail: format!(
                "`{}` is already installed ({}); `supercode teams node uninstall` first",
                existing.label, existing.detail
            ),
        });
    }
    let unit = service_unit(home, entry, &absolute_program(node));
    write_unit(&unit)?;
    platform_install(&unit)?;
    Ok((unit, service_status()))
}

#[cfg(target_os = "macos")]
fn platform_install(unit: &ServiceUnit) -> Result<(), TeamsError> {
    let path = unit.path.display().to_string();
    let (ok, text) =
        run_tool("launchctl", &["bootstrap", &gui_domain(), &path]).map_err(|error| {
            TeamsError::Service {
                action: "install",
                detail: format!("launchctl: {error}"),
            }
        })?;
    if !ok {
        return Err(TeamsError::Service {
            action: "install",
            detail: format!("launchctl bootstrap {}: {text}", gui_domain()),
        });
    }
    Ok(())
}

/// Untested on this box (the receipt is macOS); these are the commands
/// `service_unit` prints as its `install_command`.
#[cfg(all(unix, not(target_os = "macos")))]
fn platform_install(unit: &ServiceUnit) -> Result<(), TeamsError> {
    let path = unit.path.display().to_string();
    for args in [
        vec!["--user", "link", path.as_str()],
        vec!["--user", "enable", "--now", SERVICE_NAME],
    ] {
        let (ok, text) = run_tool("systemctl", &args).map_err(|error| TeamsError::Service {
            action: "install",
            detail: format!("systemctl: {error}"),
        })?;
        if !ok {
            return Err(TeamsError::Service {
                action: "install",
                detail: format!("systemctl {}: {text}", args.join(" ")),
            });
        }
    }
    Ok(())
}

#[cfg(not(unix))]
fn platform_install(_unit: &ServiceUnit) -> Result<(), TeamsError> {
    Err(TeamsError::Service {
        action: "install",
        detail: "no service manager on this platform".into(),
    })
}

/// Stop and unregister the unit, and remove the rendered file.
///
/// Idempotent: a unit the manager does not hold is not an error, because the
/// state the operator asked for is the state they get.
pub fn uninstall_service(home: &Path) -> Result<ServiceState, TeamsError> {
    platform_uninstall()?;
    let unit_path = home.join(SERVICE_DIR).join(unit_file_name());
    match std::fs::remove_file(&unit_path) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(source) => {
            return Err(TeamsError::File {
                path: unit_path,
                source,
            })
        }
    }
    // `launchctl bootout` returns before the job is torn down, so the state
    // this reports is the settled one, not the manager mid-teardown.
    let mut state = service_status();
    for _ in 0..40 {
        if !state.installed {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
        state = service_status();
    }
    Ok(state)
}

#[cfg(target_os = "macos")]
fn platform_uninstall() -> Result<(), TeamsError> {
    let target = format!("{}/{SERVICE_NAME}", gui_domain());
    let (ok, text) =
        run_tool("launchctl", &["bootout", &target]).map_err(|error| TeamsError::Service {
            action: "uninstall",
            detail: format!("launchctl: {error}"),
        })?;
    // `bootout` on a label nobody holds says so and exits non-zero.
    if !ok && !text.contains("No such process") && !text.contains("not find") {
        return Err(TeamsError::Service {
            action: "uninstall",
            detail: format!("launchctl bootout {target}: {text}"),
        });
    }
    Ok(())
}

#[cfg(all(unix, not(target_os = "macos")))]
fn platform_uninstall() -> Result<(), TeamsError> {
    let _ = run_tool("systemctl", &["--user", "disable", "--now", SERVICE_NAME]);
    Ok(())
}

#[cfg(not(unix))]
fn platform_uninstall() -> Result<(), TeamsError> {
    Ok(())
}