whetstone-cli 3.19.0

Installer and CLI for Claude Code token optimization (Headroom + RTK + Memory)
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
//! A Headroom proxy on another machine, reached over SSH.
//!
//! Every ssh invocation whetstone makes lives here. The proxy stays bound to
//! the remote's `127.0.0.1`; a local `ssh -L` tunnel makes it look like a
//! local port, so the proxy registry and everything downstream of "which
//! local port?" work unchanged.
//!
//! Calls run with `BatchMode=yes`: key/agent auth only, never a password
//! prompt in the middle of a launch. Host-key checking is left at ssh's
//! default on purpose — a destination the user has never connected to fails
//! instead of being trusted silently, which matters because a project
//! manifest can name the host.

use anyhow::{bail, Context, Result};
use std::io::Write;
use std::process::{Command, Stdio};

use crate::proxy_registry::{proxy_fingerprint, ProxySpec};

const SSH_OPTS: [&str; 4] = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=10"];

// Non-interactive ssh skips the login profile, so uv's tool dir is not on
// PATH unless we put it there.
//
// `ours` guards every kill: pid files outlive a reboot of the remote, and by
// then the pid may belong to something else. If `ps` can't tell, we don't
// kill.
const PREAMBLE: &str = r#"PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"; export PATH
ours() { ps -p "$1" -o args= 2>/dev/null | grep -q 'headroom'; }
"#;

/// Remote state dir, one `<fingerprint>.{port,pid,log}` triple per proxy.
const STATE_DIR: &str = "$HOME/.whetstone/proxies";

/// Single-quote a value for the remote POSIX shell.
pub fn sh_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

/// Reject destinations ssh would read as an option (`-oProxyCommand=...`) or
/// that carry shell/whitespace surprises. The value can come from a project
/// file, so this is a trust boundary.
pub fn validate_dest(dest: &str) -> Result<()> {
    let ok = !dest.is_empty()
        && !dest.starts_with('-')
        && dest
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "@.:_-/[]%".contains(c));
    if !ok {
        bail!("`{dest}` is not a valid ssh destination (user@host, an ssh-config alias, or ssh://user@host:port)");
    }
    Ok(())
}

/// The remote Headroom host configured for the current directory, if any.
pub fn configured() -> Option<String> {
    crate::wrapper::resolved_settings().headroom_remote
}

fn ssh(dest: &str) -> Command {
    let mut cmd = Command::new("ssh");
    cmd.args(SSH_OPTS).arg("--").arg(dest);
    cmd
}

/// Run `script` on the remote under `sh`, returning its stdout. On failure
/// the error is the remote's (or ssh's) last line of stderr.
pub fn run_script(dest: &str, script: &str) -> Result<String> {
    validate_dest(dest)?;
    let mut child = ssh(dest)
        .arg("sh -s")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .context("could not run ssh")?;
    child
        .stdin
        .take()
        .context("ssh stdin")?
        .write_all(format!("{PREAMBLE}{script}").as_bytes())?;
    let output = child.wait_with_output()?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let detail = stderr
            .lines()
            .map(str::trim)
            .rfind(|l| !l.is_empty())
            .unwrap_or("ssh failed with no output");
        bail!("{dest}: {detail}");
    }
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Like [`run_script`] but with the remote's output shown live — for
/// installs, which are slow and worth watching.
fn run_script_streaming(dest: &str, script: &str) -> Result<()> {
    validate_dest(dest)?;
    let mut child = ssh(dest)
        .arg("sh -s")
        .stdin(Stdio::piped())
        .spawn()
        .context("could not run ssh")?;
    child
        .stdin
        .take()
        .context("ssh stdin")?
        .write_all(format!("{PREAMBLE}{script}").as_bytes())?;
    if !child.wait()?.success() {
        bail!("remote command failed on {dest}");
    }
    Ok(())
}

/// Can we log in without a prompt?
pub fn reachable(dest: &str) -> Result<()> {
    run_script(dest, "true").map(|_| ())
}

/// Interactive `ssh-copy-id`, for when key auth is not set up yet.
pub fn copy_id(dest: &str) -> Result<()> {
    validate_dest(dest)?;
    let status = Command::new("ssh-copy-id")
        .arg("--")
        .arg(dest)
        .status()
        .context("could not run ssh-copy-id")?;
    if !status.success() {
        bail!("ssh-copy-id failed for {dest}");
    }
    Ok(())
}

/// What a remote host looks like from here.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RemoteStatus {
    /// `headroom --version` on the remote, if it runs.
    pub headroom: Option<String>,
    /// `headroom proxy` exists (the `proxy` extra is installed).
    pub proxy_ok: bool,
    /// curl is needed for health checks and for installing uv.
    pub curl: bool,
    /// Live whetstone-spawned proxies.
    pub proxies: usize,
}

impl RemoteStatus {
    /// The reason this host can't serve a proxy, if any.
    pub fn problem(&self) -> Option<String> {
        if self.headroom.is_none() {
            Some("headroom is not installed".into())
        } else if !self.proxy_ok {
            Some("headroom is installed without the proxy extra".into())
        } else if !self.curl {
            Some("curl is missing (needed for proxy health checks)".into())
        } else {
            None
        }
    }
}

const STATUS_SCRIPT: &str = r#"
echo "headroom=$(headroom --version 2>/dev/null | grep -i version | head -n1)"
headroom proxy --help >/dev/null 2>&1 && echo proxy=1
command -v curl >/dev/null 2>&1 && echo curl=1
n=0
for p in "$HOME"/.whetstone/proxies/*.pid; do
  [ -f "$p" ] && ours "$(cat "$p")" && n=$((n+1))
done
echo "proxies=$n"
"#;

pub fn status(dest: &str) -> Result<RemoteStatus> {
    run_script(dest, STATUS_SCRIPT).map(|out| parse_status(&out))
}

fn parse_status(out: &str) -> RemoteStatus {
    let mut status = RemoteStatus::default();
    for line in out.lines() {
        match line.trim().split_once('=') {
            Some(("headroom", v)) => {
                status.headroom =
                    v.split_whitespace().last().map(str::to_string)
            }
            Some(("proxy", _)) => status.proxy_ok = true,
            Some(("curl", _)) => status.curl = true,
            Some(("proxies", n)) => status.proxies = n.parse().unwrap_or(0),
            _ => {}
        }
    }
    status
}

/// Install (or bring current) headroom on the remote. Needs no sudo: uv and
/// its tools live in the remote user's home.
pub fn install(dest: &str, extras: &str) -> Result<()> {
    let spec = sh_quote(&crate::headroom::package_spec(extras));
    let script = format!(
        r#"set -e
if ! command -v uv >/dev/null 2>&1; then
  command -v curl >/dev/null 2>&1 || {{ echo "curl is required on the remote to install uv" >&2; exit 1; }}
  curl -LsSf https://astral.sh/uv/install.sh | sh
fi
PYO3_USE_ABI3_FORWARD_COMPATIBILITY=1 uv tool install --upgrade {spec}
headroom --version
"#
    );
    run_script_streaming(dest, &script)
}

/// Remove headroom from the remote.
pub fn uninstall(dest: &str) -> Result<()> {
    run_script(dest, "uv tool uninstall headroom-ai").map(|_| ())
}

/// Kill every whetstone-spawned proxy on the remote; returns how many died.
pub fn stop_proxies(dest: &str) -> Result<usize> {
    let script = format!(
        r#"d="{STATE_DIR}"; n=0
for p in "$d"/*.pid; do
  [ -f "$p" ] && ours "$(cat "$p")" && kill "$(cat "$p")" 2>/dev/null && n=$((n+1))
done
rm -f "$d"/*.pid "$d"/*.port
echo "$n"
"#
    );
    let out = run_script(dest, &script)?;
    Ok(out.trim().parse().unwrap_or(0))
}

/// The environment a remote proxy for `spec` must run with — the same set a
/// local spawn gets from `wrapper::spawn_proxy_detached_pid`.
// shortcut: externally exported HEADROOM_* vars reach a local proxy by env
// inheritance but are not forwarded here; forward them (and add them to the
// fingerprint) if someone needs per-shell overrides on a remote.
fn proxy_env(spec: &ProxySpec) -> Vec<(String, String)> {
    let mut env: Vec<(String, String)> = spec
        .env
        .iter()
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    env.push((
        "HEADROOM_SAVINGS_PROFILE".into(),
        spec.savings_profile.clone(),
    ));
    if !spec.telemetry {
        env.push(("HEADROOM_TELEMETRY".into(), "off".into()));
    }
    if let Some(url) = &spec.anthropic_api_url {
        env.push(("ANTHROPIC_TARGET_API_URL".into(), url.clone()));
    }
    // A key is spliced into `export KEY=...` unquoted, so only plain names.
    env.retain(|(k, _)| {
        !k.is_empty()
            && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
            && !k.starts_with(|c: char| c.is_ascii_digit())
    });
    env
}

/// First remote port to try for a fingerprint. Derived, not random, so no
/// interpreter is needed on the remote to find a free one.
fn base_port(id: &str) -> u16 {
    let hash = id
        .bytes()
        .fold(0u32, |h, b| h.wrapping_mul(31).wrapping_add(u32::from(b)));
    20_000 + (hash % 20_000) as u16
}

// shortcut: remote proxies are not idle-reaped the way local ones are (the
// local registry can't see other clients' sessions); they stop on
// `install-tools --force`, `global uninstall`, or a remote reboot. Track
// sessions in the remote state dir if they pile up.
/// Reuse-or-spawn script: prints the remote port of a healthy proxy for
/// `id`, starting one if needed.
// shortcut: serialized per client by the local registry lock only; two
// machines racing the same fingerprint can each spawn a proxy (wasteful, not
// incorrect). Add a remote mkdir-lock if shared hosts become common.
fn ensure_script(id: &str, spec: &ProxySpec) -> String {
    let mut exports = String::new();
    for (key, value) in proxy_env(spec) {
        exports.push_str(&format!("export {key}={}\n", sh_quote(&value)));
    }
    let telemetry = if spec.telemetry {
        ""
    } else {
        "set -- \"$@\" --no-telemetry\n"
    };
    let memory = if spec.memory {
        "set -- \"$@\" --memory\n"
    } else {
        ""
    };
    let base = base_port(id);
    let id = sh_quote(id);
    format!(
        r#"d="{STATE_DIR}"; mkdir -p "$d"; f="$d"/{id}
healthy() {{ curl -sf -m 2 "http://127.0.0.1:$1/health" >/dev/null 2>&1; }}
if [ -f "$f.port" ] && healthy "$(cat "$f.port")"; then cat "$f.port"; exit 0; fi
command -v curl >/dev/null 2>&1 || {{ echo "curl is not installed on this host" >&2; exit 3; }}
command -v headroom >/dev/null 2>&1 || {{ echo "headroom is not installed on this host (run: whetstone install-tools)" >&2; exit 3; }}
[ -f "$f.pid" ] && ours "$(cat "$f.pid")" && kill "$(cat "$f.pid")" 2>/dev/null
port={base}; i=0
while [ $i -lt 50 ]; do
  curl -s -m 1 -o /dev/null "http://127.0.0.1:$port/"; [ $? -eq 7 ] && break
  port=$((port+1)); i=$((i+1))
done
help=$(headroom proxy --help 2>&1)
set -- proxy --port "$port"
case "$help" in *--savings-profile*) set -- "$@" --savings-profile;; esac
{telemetry}{memory}case "$help" in *--no-rate-limit*) set -- "$@" --no-rate-limit;; esac
{exports}export HEADROOM_MEMORY_DB_PATH="$HOME/.headroom/memory.db"
nohup headroom "$@" >"$f.log" 2>&1 </dev/null &
echo $! >"$f.pid"; echo "$port" >"$f.port"
i=0
while [ $i -lt 60 ]; do
  healthy "$port" && {{ echo "$port"; exit 0; }}
  kill -0 "$(cat "$f.pid")" 2>/dev/null || break
  sleep 0.25; i=$((i+1))
done
grep -v transformers "$f.log" | tail -n 3 >&2
exit 5
"#
    )
}

/// Make sure a proxy for `spec` is running on the remote; returns its remote
/// port.
pub fn ensure_proxy(dest: &str, spec: &ProxySpec) -> Result<u16> {
    ensure_proxy_as(dest, &proxy_fingerprint(spec), spec)
}

fn ensure_proxy_as(dest: &str, id: &str, spec: &ProxySpec) -> Result<u16> {
    let out = run_script(dest, &ensure_script(id, spec))?;
    out.trim().parse().with_context(|| {
        format!("{dest}: unexpected proxy port `{}`", out.trim())
    })
}

/// Doctor's start check: bring up a throwaway proxy with this spec on the
/// remote, then take it down. The error is headroom's own complaint.
pub fn check_proxy_starts(dest: &str, spec: &ProxySpec) -> Result<()> {
    const ID: &str = "doctor";
    let started = ensure_proxy_as(dest, ID, spec).map(|_| ());
    let cleanup = format!(
        "f=\"{STATE_DIR}\"/{ID}; [ -f \"$f.pid\" ] && ours \"$(cat \"$f.pid\")\" && kill \"$(cat \"$f.pid\")\" 2>/dev/null; rm -f \"$f\".*\n"
    );
    let _ = run_script(dest, &cleanup);
    started
}

/// Open a detached `ssh -L` tunnel from a local port to a remote proxy port;
/// returns the ssh pid. The caller polls the local port for readiness.
pub fn open_tunnel(dest: &str, local: u16, remote: u16) -> Option<u32> {
    validate_dest(dest).ok()?;
    let mut cmd = Command::new("ssh");
    cmd.args(SSH_OPTS)
        .args([
            "-o",
            "ExitOnForwardFailure=yes",
            "-o",
            "ServerAliveInterval=30",
            "-o",
            "ServerAliveCountMax=3",
            "-N",
            "-L",
            &format!("127.0.0.1:{local}:127.0.0.1:{remote}"),
            "--",
            dest,
        ])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    // Own process group: closing the launching terminal must not SIGHUP a
    // tunnel other sessions share.
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    cmd.spawn().ok().map(|child| child.id())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    fn spec() -> ProxySpec {
        ProxySpec {
            savings_profile: "agent-90".into(),
            telemetry: false,
            memory: true,
            anthropic_api_url: Some("https://up.test".into()),
            env: BTreeMap::from([
                ("HEADROOM_BUDGET".to_string(), "it's; rm -rf ~".to_string()),
                ("BAD KEY;x".to_string(), "1".to_string()),
            ]),
            remote: Some("me@box".into()),
        }
    }

    #[test]
    fn sh_quote_neutralizes_quotes_and_metacharacters() {
        assert_eq!(sh_quote("plain"), "'plain'");
        assert_eq!(sh_quote("it's $(x)"), "'it'\\''s $(x)'");
    }

    #[test]
    fn validate_dest_accepts_normal_destinations() {
        for dest in ["box", "me@box.example", "ssh://me@box:2222", "[::1]"] {
            assert!(validate_dest(dest).is_ok(), "{dest}");
        }
    }

    #[test]
    fn validate_dest_rejects_option_injection_and_shell() {
        for dest in ["", "-oProxyCommand=evil", "box; rm -rf ~", "a b", "$(x)"]
        {
            assert!(validate_dest(dest).is_err(), "{dest}");
        }
    }

    #[test]
    fn ensure_script_quotes_values_and_drops_bad_keys() {
        let script = ensure_script("abc", &spec());
        assert!(script.contains("export HEADROOM_BUDGET='it'\\''s; rm -rf ~'"));
        assert!(!script.contains("BAD KEY"));
        assert!(script.contains("export HEADROOM_SAVINGS_PROFILE='agent-90'"));
        assert!(script.contains("export HEADROOM_TELEMETRY='off'"));
        assert!(script
            .contains("export ANTHROPIC_TARGET_API_URL='https://up.test'"));
        assert!(script.contains("--no-telemetry"));
        assert!(script.contains("--memory\n"));
        assert!(script.contains("f=\"$d\"/'abc'"));
    }

    #[test]
    fn ensure_script_omits_flags_the_spec_does_not_ask_for() {
        let spec = ProxySpec {
            telemetry: true,
            memory: false,
            ..spec()
        };
        let script = ensure_script("abc", &spec);
        assert!(!script.contains("--no-telemetry"));
        assert!(!script.contains("--memory\n"));
        assert!(!script.contains("HEADROOM_TELEMETRY"));
    }

    #[test]
    fn base_port_is_stable_and_unprivileged() {
        let port = base_port("0123456789abcdef");
        assert_eq!(port, base_port("0123456789abcdef"));
        assert!((20_000..40_000).contains(&port));
    }

    #[test]
    fn parse_status_reads_every_field() {
        let status = parse_status(
            "headroom=headroom, version 0.45.0\nproxy=1\ncurl=1\nproxies=2\n",
        );
        assert_eq!(status.headroom.as_deref(), Some("0.45.0"));
        assert!(status.proxy_ok && status.curl);
        assert_eq!(status.proxies, 2);
        assert_eq!(status.problem(), None);
    }

    #[test]
    fn parse_status_reports_a_missing_headroom() {
        let status = parse_status("headroom=\ncurl=1\nproxies=0\n");
        assert_eq!(status.headroom, None);
        assert!(status.problem().unwrap().contains("not installed"));
    }
}