Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions crates/agent/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -794,8 +794,12 @@ pub struct LaunchEnv {
pub env: Vec<(String, String)>,
/// Home-directory override. Provider-specific: Claude gets `HOME`, Codex
/// gets `CODEX_HOME`, pi gets `PI_CODING_AGENT_DIR`, Cursor gets
/// `CURSOR_CONFIG_DIR` and Grok gets `GROK_HOME`. OpenCode has no
/// supported single-directory override, so its value is ignored.
/// `CURSOR_CONFIG_DIR` and `CURSOR_DATA_DIR` and Grok gets `GROK_HOME`.
/// OpenCode has no supported single-directory override, so its value is
/// ignored. Cursor reads its login from `$XDG_CONFIG_HOME/cursor` or
/// `~/.config/cursor` whatever these say; moving either would also move
/// the configuration of every tool the agent runs (`gh`, git), so Cursor
/// profiles share one login.
pub home: Option<PathBuf>,
}

Expand All @@ -806,19 +810,19 @@ impl LaunchEnv {
pub fn pairs(&self, provider: ProviderKind) -> Vec<(String, String)> {
let mut pairs = self.env.clone();
if let Some(home) = &self.home {
let key = match provider {
ProviderKind::ClaudeCode => Some("HOME"),
ProviderKind::Codex => Some("CODEX_HOME"),
ProviderKind::Pi => Some("PI_CODING_AGENT_DIR"),
ProviderKind::Cursor => Some("CURSOR_CONFIG_DIR"),
ProviderKind::Grok => Some("GROK_HOME"),
ProviderKind::OpenCode => None,
let keys: &[&str] = match provider {
ProviderKind::ClaudeCode => &["HOME"],
ProviderKind::Codex => &["CODEX_HOME"],
ProviderKind::Pi => &["PI_CODING_AGENT_DIR"],
ProviderKind::Cursor => &["CURSOR_CONFIG_DIR", "CURSOR_DATA_DIR"],
ProviderKind::Grok => &["GROK_HOME"],
ProviderKind::OpenCode => &[],
// ACP agents carry their own env in the launch recipe; there is
// no protocol-level home concept to override.
ProviderKind::Acp => None,
ProviderKind::Acp => &[],
};
if let Some(key) = key {
pairs.push((key.to_string(), home.to_string_lossy().into_owned()));
for key in keys {
pairs.push(((*key).to_string(), home.to_string_lossy().into_owned()));
}
}
pairs
Expand Down
11 changes: 7 additions & 4 deletions crates/headless/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,18 @@ RUN apt-get update \
&& groupmod --new-name tcode node \
&& usermod --login tcode --home /data/home --shell /bin/bash node
COPY crates/headless/container/agents.json crates/headless/container/install-agents.mjs /opt/tcode/
# Agent commands are on PATH only through /data/agents/bin, which holds the
# selected ones; Cursor's installer also writes $HOME/.local/bin.
# One global npm prefix per CPU architecture holds the selected npm CLIs and
# every other global install. /data/agents/bin links the CLIs kept elsewhere
# (Cursor's, Grok's current build); $HOME/.local/bin stays off PATH, so an
# unselected Cursor is not on it.
ARG TARGETARCH
ENV HOME=/data/home \
TCODE_DATA_DIR=/data/tcode \
SHELL=/bin/bash \
LANG=C.UTF-8 \
NPM_CONFIG_PREFIX=/data/agents/custom \
NPM_CONFIG_PREFIX=/data/agents/${TARGETARCH}/npm \
NPM_CONFIG_CACHE=/data/agents/npm-cache \
PATH=/data/agents/bin:/data/bin:/data/agents/custom/bin:$PATH
PATH=/data/agents/bin:/data/bin:/data/agents/${TARGETARCH}/npm/bin:$PATH
LABEL org.opencontainers.image.title="tcode-headless" \
org.opencontainers.image.description="Tcode headless machine with the browser app, for NAS and homelab hosts" \
org.opencontainers.image.licenses="MIT"
Expand Down
2 changes: 1 addition & 1 deletion crates/headless/container/agents.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
"pi": { "package": "@earendil-works/pi-coding-agent", "commands": ["pi"] },
"opencode": { "package": "opencode-ai", "commands": ["opencode"] },
"cursor": { "installer": "https://cursor.com/install", "commands": ["cursor-agent", "agent"] },
"grok": { "package": "@xai-official/grok", "commands": ["grok"] }
"grok": { "package": "@xai-official/grok", "commands": ["grok"], "current": ".grok/bin/grok" }
}
2 changes: 1 addition & 1 deletion crates/headless/container/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ if [ "${1:-serve}" = serve ]; then
TCODE_AGENTS=$(node -e 'console.log(Object.keys(require("/opt/tcode/agents.json")).join(","))')
export TCODE_AGENTS
fi
node /opt/tcode/install-agents.mjs /data/agents
node /opt/tcode/install-agents.mjs /data/agents/bin
fi

exec tcode-headless "$@"
106 changes: 47 additions & 59 deletions crates/headless/container/install-agents.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Installs the agent CLIs TCODE_AGENTS selects into the data volume: each
// one's current release, the first time it is selected. From then on it is
// reused offline and updates itself with its own updater.
// reused offline and updated by its own updater or Tcode's provider update.
import { spawnSync } from 'node:child_process';
import { constants as fsConstants } from 'node:fs';
import { access, chmod, mkdir, mkdtemp, readFile, readdir, rename, rm, symlink, writeFile } from 'node:fs/promises';
import { access, mkdir, readFile, rm, symlink } from 'node:fs/promises';
import path from 'node:path';

const agents = JSON.parse(await readFile(new URL('./agents.json', import.meta.url)));
Expand All @@ -16,10 +16,14 @@ for (const name of selected) {
}
}

const [store] = process.argv.slice(2);
// npm packages go to the image's global npm prefix, which is on PATH: a CLI
// or Tcode updating it with `npm install --global` updates the copy that
// runs, and an agent's own global installs run and persist beside it.
const prefix = process.env.NPM_CONFIG_PREFIX;
const home = process.env.HOME;
if (!store || !path.isAbsolute(store) || !home) {
throw new Error('Usage: HOME=... install-agents.mjs ABSOLUTE_STORE');
const [links] = process.argv.slice(2);
if (!links || !path.isAbsolute(links) || !prefix || !path.isAbsolute(prefix) || !home) {
throw new Error('Usage: HOME=... NPM_CONFIG_PREFIX=... install-agents.mjs ABSOLUTE_LINK_DIR');
}

function run(program, args) {
Expand All @@ -38,75 +42,59 @@ async function executable(file) {
}
}

/// An npm package in a prefix of its own, which its commands name to npm: a
/// CLI that updates itself with `npm install --global` updates this copy. A
/// volume can move between hosts of different architectures.
async function installPackage(name, spec) {
const prefix = path.join(store, process.arch, name);
if (!await executable(path.join(prefix, 'bin', spec.commands[0]))) {
const parent = path.dirname(prefix);
await mkdir(parent, { recursive: true });
// A killed first-start installation must not accumulate partial downloads.
for (const entry of await readdir(parent)) {
if (entry.startsWith('.install-')) await rm(path.join(parent, entry), { recursive: true, force: true });
}
const staging = await mkdtemp(path.join(parent, '.install-'));
try {
run('npm', ['install', '--global', '--prefix', staging, '--no-audit', '--no-fund',
`--allow-scripts=${spec.package}`, '--', `${spec.package}@latest`]);
await rm(prefix, { recursive: true, force: true });
await rename(staging, prefix);
} finally {
await rm(staging, { recursive: true, force: true });
}
}
return command => [
'#!/bin/sh',
`NPM_CONFIG_PREFIX='${prefix}'`,
'export NPM_CONFIG_PREFIX',
`exec '${path.join(prefix, 'bin', command)}' "$@"`,
'',
].join('\n');
}

/// Cursor's own installer, which puts the CLI under HOME where its updater
/// keeps it current.
async function installCursor(spec) {
const installed = path.join(home, '.local', 'bin', spec.commands[0]);
if (!await executable(installed)) {
run('bash', ['-c', `set -o pipefail; curl --fail --silent --show-error --location '${spec.installer}' | bash`]);
async function exists(file) {
try {
await access(file);
return true;
} catch {
return false;
}
return command => path.join(home, '.local', 'bin', command);
}

const bin = path.join(store, 'bin');
await mkdir(bin, { recursive: true });
// Only this directory is managed: user-installed ACP commands have their own PATH entries.
await mkdir(links, { recursive: true });
// The link directory leads PATH and holds only links this script makes.
for (const { commands } of Object.values(agents)) {
for (const command of commands) await rm(path.join(bin, command), { force: true });
for (const command of commands) await rm(path.join(links, command), { force: true });
}

const available = [];
for (const name of selected) {
const spec = agents[name];
for (const [name, spec] of Object.entries(agents)) {
const wanted = selected.includes(name);
try {
console.log(`Preparing ${name}`);
if (spec.package) {
const wrapper = await installPackage(name, spec);
for (const command of spec.commands) {
const file = path.join(bin, command);
await writeFile(file, wrapper(command));
await chmod(file, 0o755);
const installed = await exists(path.join(prefix, 'lib', 'node_modules', spec.package));
if (!wanted) {
// Off PATH means uninstalled: the prefix's bin is on PATH. Logins
// and configuration stay under HOME for a later reinstall.
if (installed) run('npm', ['uninstall', '--global', '--no-audit', '--no-fund', spec.package]);
continue;
}
console.log(`Preparing ${name}`);
if (!await executable(path.join(prefix, 'bin', spec.commands[0]))) {
run('npm', ['install', '--global', '--no-audit', '--no-fund',
`--allow-scripts=${spec.package}`, '--', `${spec.package}@latest`]);
}
// A binary the CLI's own updater moves forward outside the package
// (Grok's ~/.grok/bin/grok) runs instead of the package's copy.
if (spec.current && await executable(path.join(home, spec.current))) {
for (const command of spec.commands) await symlink(path.join(home, spec.current), path.join(links, command));
}
} else {
const target = await installCursor(spec);
for (const command of spec.commands) await symlink(target(command), path.join(bin, command));
if (!wanted) continue;
console.log(`Preparing ${name}`);
// Cursor's own installer, whose updater keeps HOME's copy current.
if (!await executable(path.join(home, '.local', 'bin', spec.commands[0]))) {
run('bash', ['-c', `set -o pipefail; curl --fail --silent --show-error --location '${spec.installer}' | bash`]);
}
for (const command of spec.commands) {
await symlink(path.join(home, '.local', 'bin', command), path.join(links, command));
}
}
available.push(name);
if (wanted) available.push(name);
} catch (error) {
// The machine starts without it, so it stays reachable; the next start
// tries again.
console.error(`Could not install ${name}: ${error.message}`);
console.error(`Could not ${wanted ? 'install' : 'remove'} ${name}: ${error.message}`);
}
}
console.log(`Available agents: ${available.join(',') || '(none)'}`);
4 changes: 2 additions & 2 deletions crates/headless/container/profile.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# shellcheck shell=sh
# Login shells in Tcode terminal panes also need the selected and custom commands.
export PATH="/data/agents/bin:/data/bin:/data/agents/custom/bin:$PATH"
# Login shells in Tcode terminal panes also need the agents and global npm commands.
export PATH="/data/agents/bin:/data/bin:$NPM_CONFIG_PREFIX/bin:$PATH"
6 changes: 4 additions & 2 deletions crates/headless/container/smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,9 @@ try {
console.log('First start: every CLI installed, browser password, LAN pairing, project ownership and terminal PATH');
let base = await start(undefined);
for (const name of commands) exec(`${name} --version`);
assert.equal(exec('bash -lc "id -u; command -v codex"'), '1234\n/data/agents/bin/codex');
// The npm CLI runs from the global prefix, where npm's own updates land.
const [uid, codex, globalCodex] = exec('bash -lc "id -u; command -v codex; echo $(npm prefix --global)/bin/codex"').split('\n');
assert.deepEqual([uid, codex], ['1234', globalCodex]);
assert.equal(exec('bash -lc "locale charmap; date +%Z"'), 'UTF-8\nCST', 'Terminal panes get UTF-8 and TZ');
await waitForHealthy();
exec('echo owned > /projects/owned');
Expand Down Expand Up @@ -171,7 +173,7 @@ try {
console.log('Installed CLIs are reused with networking disabled');
docker('run', '--rm', '--network', 'none', '--entrypoint', 'sh', '--env', 'TCODE_AGENTS=codex',
'--volume', `${data}:/data`, image, '-ec',
'node /opt/tcode/install-agents.mjs /data/agents; codex --version');
'node /opt/tcode/install-agents.mjs /data/agents/bin; codex --version');

console.log('Empty selection, custom ACP command, changed UID/GID, same identity');
base = await start('', '1235', '2346', '0');
Expand Down
Loading
Loading