harnessd 0.1.0

The harness daemon: API server (axum WS + REST), agent runtime host, and CLI (init/pair/doctor).
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
//! The `harnessd` command-line surface (design doc §2 table, §9 operability).
//!
//! `serve` is the daemon; the rest are the operator commands that keep it alive
//! without babysitting — the "checklist as a command, not a README" principle.

use crate::paths;
use crate::server::{self, AppState};
use anyhow::Context;
use clap::{Parser, Subcommand};
use harness_core::{Config, Runtime, Store};
use std::path::PathBuf;
use tracing::info;

#[derive(Parser)]
#[command(
    name = "harnessd",
    version,
    about = "Self-hosted agentic harness daemon"
)]
pub struct Cli {
    /// Path to the config file. Defaults to the platform config dir.
    #[arg(long, global = true)]
    config: Option<PathBuf>,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// Run the daemon (default if no subcommand is given).
    Serve,
    /// Interactive first-run setup: pick providers, write a config, pair a device.
    Init,
    /// Environment/permissions/network checklist as a command.
    Doctor,
    /// Mint a one-time pairing code + QR for a new client (§8).
    Pair {
        /// Endpoint URL to embed in the QR (what the phone connects to). Defaults to
        /// the configured bind, resolving `0.0.0.0`/loopback to the Tailscale IP.
        #[arg(long)]
        endpoint: Option<String>,
    },
    /// List or revoke paired devices (§8).
    #[command(subcommand)]
    Devices(DevicesCmd),
    /// Inspect or revoke progressive-trust grants (§7.3).
    #[command(subcommand)]
    Trust(TrustCmd),
    /// Report version and how to update (signed self-update is future; §9).
    Update,
    /// Print version and protocol info.
    Version,
}

/// `harnessd trust list | revoke <tool> <scope>`.
#[derive(Subcommand)]
enum TrustCmd {
    /// List all "always allow" grants.
    List,
    /// Revoke the grant for a tool on a scope.
    Revoke { tool: String, scope: String },
}

/// `harnessd devices list | revoke <name>`.
#[derive(Subcommand)]
enum DevicesCmd {
    /// List paired devices.
    List,
    /// Revoke a paired device by name.
    Revoke { name: String },
}

impl Cli {
    pub async fn run(self) -> anyhow::Result<()> {
        let config_path = self
            .config
            .clone()
            .unwrap_or_else(paths::default_config_path);
        match self.command.unwrap_or(Command::Serve) {
            Command::Serve => serve(config_path).await,
            Command::Init => init(config_path),
            Command::Doctor => doctor(config_path),
            Command::Pair { endpoint } => pair(config_path, endpoint),
            Command::Devices(cmd) => devices(config_path, cmd),
            Command::Trust(cmd) => trust(config_path, cmd),
            Command::Update => update(),
            Command::Version => {
                println!(
                    "harnessd/{}  protocol {}",
                    env!("CARGO_PKG_VERSION"),
                    harness_proto::PROTOCOL_VERSION
                );
                Ok(())
            }
        }
    }
}

/// Load config + open the store + build the runtime.
fn build_runtime(config_path: &std::path::Path) -> anyhow::Result<(Config, Runtime)> {
    let config = Config::load(config_path).context("loading config")?;
    let db = paths::resolve_db_path(&config.server.db_path, config_path);
    if let Some(parent) = db.parent() {
        std::fs::create_dir_all(parent).ok();
    }
    let store = Store::open(&db).with_context(|| format!("opening db at {}", db.display()))?;
    // Persist secrets (auth.json) + the provider overlay (providers.json) next to the db.
    let state_dir = db
        .parent()
        .map(std::path::Path::to_path_buf)
        .unwrap_or_else(|| std::path::PathBuf::from("."));
    let runtime = Runtime::with_state_dir(store, config.clone(), &state_dir);
    Ok((config, runtime))
}

async fn serve(config_path: PathBuf) -> anyhow::Result<()> {
    // serve() connects MCP services (async), unlike the sync CLI helpers.
    let config = Config::load(&config_path).context("loading config")?;
    let db = paths::resolve_db_path(&config.server.db_path, &config_path);
    if let Some(parent) = db.parent() {
        std::fs::create_dir_all(parent).ok();
    }
    let store = Store::open(&db).with_context(|| format!("opening db at {}", db.display()))?;
    let state_dir = db
        .parent()
        .map(std::path::Path::to_path_buf)
        .unwrap_or_else(|| std::path::PathBuf::from("."));
    let runtime = Runtime::with_state_dir_and_services(store, config.clone(), &state_dir).await;
    let bind = config.server.bind.clone();

    let state = AppState::new(runtime);
    let app = server::router(state);

    let listener = tokio::net::TcpListener::bind(&bind)
        .await
        .with_context(|| format!("binding {bind}"))?;
    info!(%bind, "harnessd listening (bind only the Tailscale/loopback iface in production)");
    axum::serve(listener, app).await.context("server error")?;
    Ok(())
}

fn init(config_path: PathBuf) -> anyhow::Result<()> {
    if config_path.exists() {
        println!(
            "Config already exists at {}. Edit it or delete to re-init.",
            config_path.display()
        );
        return Ok(());
    }
    if let Some(parent) = config_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    // Write a documented starter config. M4 turns this into an interactive wizard.
    std::fs::write(&config_path, STARTER_CONFIG)?;
    println!("Wrote a starter config to {}", config_path.display());
    println!("It ships with a zero-key `mock` provider so you can try the stack immediately.");
    println!("To use Anthropic: set ANTHROPIC_API_KEY and enable the [providers] entry.");
    println!("Then: harnessd serve");
    Ok(())
}

fn doctor(config_path: PathBuf) -> anyhow::Result<()> {
    println!("harnessd doctor\n");
    // Config
    match Config::load(&config_path) {
        Ok(cfg) => {
            println!("[ok]  config loaded ({} provider(s))", cfg.providers.len());
            // Provider build check (key present, kind supported).
            let (_c, rt) = build_runtime(&config_path)?;
            for (id, res) in rt.validate_providers() {
                match res {
                    Ok(()) => println!("[ok]  provider '{id}' ready"),
                    Err(e) => println!("[!!]  provider '{id}': {e}"),
                }
            }
            println!(
                "[ok]  {} tool(s), {} preset(s) loaded",
                rt.tool_count(),
                rt.preset_count()
            );
            // Delegated CLI backends need their vendor CLI on PATH + a prior login.
            for p in &cfg.providers {
                use harness_core::config::ProviderKind;
                let cmd = match p.kind {
                    ProviderKind::ClaudeCli => p.command.clone().unwrap_or_else(|| "claude".into()),
                    ProviderKind::CodexCli => p.command.clone().unwrap_or_else(|| "codex".into()),
                    _ => continue,
                };
                if harness_core::provider::cli::is_on_path(&cmd) {
                    println!(
                        "[ok]  CLI backend '{}' found: `{cmd}` on PATH (ensure you've logged in)",
                        p.id
                    );
                } else {
                    println!("[!!]  CLI backend '{}' missing: `{cmd}` not on PATH", p.id);
                }
            }
            if rt.workspace_writable() {
                println!("[ok]  workspace writable: {}", cfg.workspace.display());
            } else {
                println!("[!!]  workspace NOT writable: {}", cfg.workspace.display());
            }
            // Port availability: can we bind the configured address right now?
            match std::net::TcpListener::bind(&cfg.server.bind) {
                Ok(l) => {
                    drop(l);
                    println!("[ok]  bind address free: {}", cfg.server.bind);
                }
                Err(e) => println!("[!!]  bind {} unavailable: {e}", cfg.server.bind),
            }
        }
        Err(e) => println!("[!!]  config: {e}"),
    }
    // A full doctor also checks Tailscale up + TCC/permissions (macOS); those are
    // environment probes tracked in the operability issue.
    println!("\n(Tailscale + macOS TCC/permission probes are tracked in issue #8.)");
    Ok(())
}

/// `harnessd update` — report the running version and how to update. A signed,
/// automatic self-update lands with the release-signing work (issue #8 / #15); until
/// then this stays honest and offline rather than pretending to swap binaries.
fn update() -> anyhow::Result<()> {
    println!("harnessd {}", env!("CARGO_PKG_VERSION"));
    println!("Self-update (signature-verified binary swap) ships with signed releases.");
    println!("For now, update in place with:");
    println!("  curl -fsSL http://100.113.110.34:3001/Muk/harness/raw/branch/main/scripts/install.sh | sh");
    println!("or, from a clone: git pull && cargo build --release");
    Ok(())
}

/// `harnessd pair` — mint a one-time pairing code (5-min TTL) into the shared DB and
/// render a QR the iOS app scans. The QR encodes a [`harness_proto::PairingPayload`]
/// (`endpoint` + `code`); the client `POST`s the code to `/v1/pair/complete`.
fn pair(config_path: PathBuf, endpoint: Option<String>) -> anyhow::Result<()> {
    use time::format_description::well_known::Rfc3339;
    let (config, runtime) = build_runtime(&config_path)?;
    let code = crate::auth::generate_code();
    let expires = (time::OffsetDateTime::now_utc() + time::Duration::minutes(5))
        .format(&Rfc3339)
        .unwrap_or_default();
    runtime
        .store()
        .add_pairing_code(&crate::auth::hash(&code), &expires)?;

    let endpoint = endpoint.unwrap_or_else(|| resolve_endpoint(&config.server.bind));
    let payload = harness_proto::PairingPayload {
        endpoint: endpoint.clone(),
        code: code.clone(),
    };
    let json = serde_json::to_string(&payload)?;

    // Render the QR to the terminal. Dense1x2 packs two vertical modules per glyph so
    // the code stays roughly square and scannable from a phone camera.
    match qrcode::QrCode::new(json.as_bytes()) {
        Ok(qr) => {
            let art = qr
                .render::<qrcode::render::unicode::Dense1x2>()
                .quiet_zone(true)
                .build();
            println!("\nScan this with the HarnessApp pairing screen:\n\n{art}\n");
        }
        Err(e) => println!("(could not render QR: {e})"),
    }

    println!("Endpoint: {endpoint}");
    println!("Pairing code: {code}   (valid 5 minutes)");
    println!("\nManual fallback (no camera):");
    println!(
        "  curl -X POST {}/v1/pair/complete -H 'content-type: application/json' \\",
        endpoint
    );
    println!("       -d '{{\"code\":\"{code}\",\"device_name\":\"my-phone\"}}'");
    println!("The response contains a device_token to store on the client.");
    if !config.server.require_pairing {
        println!("\nNote: require_pairing is false, so clients connect without a token today.");
        println!("Set `require_pairing = true` under [server] to enforce device tokens.");
    }
    Ok(())
}

/// Turn a bind address into a client-reachable `http://host:port` URL. When the bind
/// is loopback or `0.0.0.0` (not reachable from a phone), try to substitute the host's
/// Tailscale IP so the QR points somewhere the device can actually reach.
fn resolve_endpoint(bind: &str) -> String {
    let (host, port) = bind.rsplit_once(':').unwrap_or((bind, "8787"));
    let unreachable = matches!(host, "0.0.0.0" | "127.0.0.1" | "localhost" | "::" | "[::]");
    if unreachable {
        if let Some(ip) = tailscale_ip() {
            return format!("http://{ip}:{port}");
        }
        eprintln!(
            "warning: bind is {bind} (not reachable from another device) and no Tailscale IP \
             was found. Pass --endpoint http://<reachable-ip>:{port}, or set `bind` to the \
             Tailscale interface."
        );
    }
    format!("http://{bind}")
}

/// Best-effort `tailscale ip -4` → first IPv4 address, if the CLI is present.
fn tailscale_ip() -> Option<String> {
    let out = std::process::Command::new("tailscale")
        .args(["ip", "-4"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    String::from_utf8(out.stdout)
        .ok()?
        .lines()
        .next()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// `harnessd devices list | revoke <name>`.
fn devices(config_path: PathBuf, cmd: DevicesCmd) -> anyhow::Result<()> {
    let (_config, runtime) = build_runtime(&config_path)?;
    match cmd {
        DevicesCmd::List => {
            let devs = runtime.store().list_devices()?;
            if devs.is_empty() {
                println!("No paired devices. Run `harnessd pair` to add one.");
            } else {
                println!("{:<24} paired_at", "NAME");
                for (name, at) in devs {
                    println!("{name:<24} {at}");
                }
            }
            Ok(())
        }
        DevicesCmd::Revoke { name } => {
            let n = runtime.store().revoke_device(&name)?;
            println!("revoked {n} device(s) named '{name}'");
            Ok(())
        }
    }
}

/// `harnessd trust list | revoke` — review/revoke progressive-trust grants (§7.3).
fn trust(config_path: PathBuf, cmd: TrustCmd) -> anyhow::Result<()> {
    let (_config, runtime) = build_runtime(&config_path)?;
    match cmd {
        TrustCmd::List => {
            let grants = runtime.list_trust()?;
            if grants.is_empty() {
                println!("No trust grants. Approve a tool with \"always allow\" to add one.");
            } else {
                println!("{:<28} {:<24} {:<8} granted_by", "TOOL", "SCOPE", "CLASS");
                for g in grants {
                    println!(
                        "{:<28} {:<24} {:<8} {}",
                        g.tool, g.scope, g.class, g.granted_by
                    );
                }
            }
            Ok(())
        }
        TrustCmd::Revoke { tool, scope } => {
            if runtime.revoke_trust(&tool, &scope)? {
                println!("revoked trust: {tool} on {scope}");
            } else {
                println!("no grant found for {tool} on {scope}");
            }
            Ok(())
        }
    }
}

const STARTER_CONFIG: &str = r#"# harnessd configuration
# Secrets (API keys) are read from environment variables named below, never stored
# here. Production moves these into the OS keyring / an age file (design doc §8).

user_name = "you"

[server]
# Bind loopback by default. In production bind only the Tailscale interface.
bind = "127.0.0.1:8787"
db_path = "harness.db"

[roles]
main = "mock"
fast = "mock"

# Zero-key deterministic provider — great for trying the stack end to end.
[[providers]]
id = "mock"
kind = "mock"
model = "mock-1"
enabled = true

# Anthropic (native API-key backend). Set ANTHROPIC_API_KEY and flip enabled = true,
# then point roles.main = "anthropic".
[[providers]]
id = "anthropic"
kind = "anthropic"
model = "claude-opus-4-8"
api_key_env = "ANTHROPIC_API_KEY"
enabled = false
"#;