260 lines
10 KiB
TypeScript
260 lines
10 KiB
TypeScript
import { $ } from "bun"
|
|
import { homedir } from "os"
|
|
import { dirname } from "path"
|
|
|
|
const CONTAINER_NAME = "sandlot"
|
|
const USER = "ubuntu"
|
|
const CLAUDE_BIN = `/home/${USER}/.local/bin/claude`
|
|
|
|
/** Translate a host path to its corresponding container path. */
|
|
export function containerPath(hostPath: string): string {
|
|
const home = homedir()
|
|
if (hostPath.startsWith(`${home}/.sandlot`)) {
|
|
return "/sandlot" + hostPath.slice(`${home}/.sandlot`.length)
|
|
}
|
|
if (hostPath.startsWith(`${home}/dev`)) {
|
|
return "/host" + hostPath.slice(`${home}/dev`.length)
|
|
}
|
|
return hostPath
|
|
}
|
|
|
|
function requireContainer(): void {
|
|
if (!Bun.which("container")) {
|
|
console.error('✖ Apple Container is not installed. Install it with: brew install container')
|
|
process.exit(1)
|
|
}
|
|
}
|
|
|
|
/** Run a shell command, logging stderr on failure. */
|
|
async function run(cmd: ReturnType<typeof $>, step: string): Promise<void> {
|
|
const result = await cmd.nothrow().quiet()
|
|
if (result.exitCode !== 0) {
|
|
const stderr = result.stderr.toString().trim()
|
|
const stdout = result.stdout.toString().trim()
|
|
const detail = stderr || stdout || "(no output)"
|
|
throw new Error(`${step} failed (exit ${result.exitCode}):\n${detail}`)
|
|
}
|
|
}
|
|
|
|
/** Create and provision the container from scratch. Fails if it already exists. */
|
|
export async function create(log?: (msg: string) => void): Promise<void> {
|
|
requireContainer()
|
|
|
|
const s = await status()
|
|
if (s !== "missing") {
|
|
throw new Error("Container already exists. Use 'sandlot vm destroy' first to recreate it.")
|
|
}
|
|
|
|
const home = homedir()
|
|
log?.("Pulling image & creating container")
|
|
await run(
|
|
$`container run -d --name ${CONTAINER_NAME} -m 4G --mount type=bind,source=${home}/dev,target=/host,readonly -v ${home}/.sandlot:/sandlot ubuntu:24.04 sleep infinity`,
|
|
"Container creation")
|
|
|
|
// Provision (as root)
|
|
log?.("Installing packages")
|
|
await run(
|
|
$`container exec ${CONTAINER_NAME} bash -c ${"apt update && apt install -y curl git neofetch fish unzip"}`,
|
|
"Package installation")
|
|
|
|
// Create symlinks so git worktree absolute paths from the host resolve inside the container
|
|
await run(
|
|
$`container exec ${CONTAINER_NAME} bash -c ${`mkdir -p '${home}' && ln -s /host '${home}/dev' && ln -s /sandlot '${home}/.sandlot'`}`,
|
|
"Symlink creation")
|
|
|
|
// Install Bun and Claude Code (as ubuntu user)
|
|
log?.("Installing Bun")
|
|
await run(
|
|
$`container exec --user ${USER} ${CONTAINER_NAME} env BUN_INSTALL=/home/${USER}/.local bash -c ${"curl -fsSL https://bun.sh/install | bash"}`,
|
|
"Bun installation")
|
|
|
|
log?.("Installing Claude Code")
|
|
await run(
|
|
$`container exec --user ${USER} ${CONTAINER_NAME} bash -c ${"curl -fsSL https://claude.ai/install.sh | bash"}`,
|
|
"Claude Code installation")
|
|
|
|
log?.("Configuring environment")
|
|
const gitName = (await $`git config user.name`.quiet().text()).trim()
|
|
const gitEmail = (await $`git config user.email`.quiet().text()).trim()
|
|
if (gitName) await $`container exec --user ${USER} ${CONTAINER_NAME} git config --global user.name ${gitName}`.quiet()
|
|
if (gitEmail) await $`container exec --user ${USER} ${CONTAINER_NAME} git config --global user.email ${gitEmail}`.quiet()
|
|
|
|
// Configure claude to use API key from host ~/.env (skip login prompt)
|
|
let apiKey: string | undefined
|
|
const envFile = Bun.file(`${home}/.env`)
|
|
if (await envFile.exists()) {
|
|
const envContent = await envFile.text()
|
|
apiKey = envContent.match(/^(?:export\s+)?ANTHROPIC_API_KEY=["']?([^"'\s]+)["']?/m)?.[1]
|
|
}
|
|
|
|
if (!apiKey) {
|
|
log?.("Warning: ANTHROPIC_API_KEY not found in ~/.env — claude will require manual login")
|
|
}
|
|
|
|
const activityBin = `/home/${USER}/.local/bin/sandlot-activity`
|
|
const hooks = {
|
|
UserPromptSubmit: [{ hooks: [{ type: "command", command: `${activityBin} active` }] }],
|
|
Stop: [{ hooks: [{ type: "command", command: `${activityBin} idle` }] }],
|
|
}
|
|
const settingsJson = JSON.stringify(apiKey
|
|
? { apiKeyHelper: "~/.claude/api-key-helper.sh", skipDangerousModePermissionPrompt: true, hooks }
|
|
: { skipDangerousModePermissionPrompt: true, hooks })
|
|
const claudeJson = JSON.stringify({ hasCompletedOnboarding: true, effortCalloutDismissed: true })
|
|
|
|
// Write the helper script to a temp file and copy it in so the key
|
|
// never appears in a process argument visible in `ps`.
|
|
if (apiKey) {
|
|
const tmp = `${home}/.sandlot/.api-key-helper.tmp`
|
|
await Bun.write(tmp, `#!/bin/sh\necho '${apiKey.replace(/'/g, "'\\''")}'\n`)
|
|
await $`chmod +x ${tmp}`.quiet()
|
|
await $`container exec --user ${USER} ${CONTAINER_NAME} bash -c ${"mkdir -p ~/.claude && cp /sandlot/.api-key-helper.tmp ~/.claude/api-key-helper.sh"}`.quiet()
|
|
await Bun.file(tmp).unlink()
|
|
}
|
|
|
|
// Install activity tracking hook script
|
|
const activityTmp = `${home}/.sandlot/.sandlot-activity.tmp`
|
|
await Bun.write(activityTmp, [
|
|
'#!/bin/bash',
|
|
'P="${CLAUDE_PROJECT_DIR%/}"',
|
|
'echo "$1" > "$(dirname "$P")/.activity-$(basename "$P")"',
|
|
'',
|
|
].join('\n'))
|
|
await $`chmod +x ${activityTmp}`.quiet()
|
|
await $`container exec --user ${USER} ${CONTAINER_NAME} bash -c ${"cp /sandlot/.sandlot-activity.tmp ~/.local/bin/sandlot-activity"}`.quiet()
|
|
await Bun.file(activityTmp).unlink()
|
|
|
|
await $`container exec --user ${USER} ${CONTAINER_NAME} bash -c ${`
|
|
mkdir -p ~/.claude
|
|
echo '${settingsJson}' > ~/.claude/settings.json
|
|
echo '${claudeJson}' > ~/.claude.json
|
|
`}`.quiet()
|
|
}
|
|
|
|
/** Start a stopped container. */
|
|
export async function start(): Promise<void> {
|
|
requireContainer()
|
|
const s = await status()
|
|
if (s === "running") return
|
|
if (s === "missing") throw new Error("Container does not exist. Use 'sandlot vm create' first.")
|
|
await $`container start ${CONTAINER_NAME}`.quiet()
|
|
}
|
|
|
|
/** Ensure the sandlot container exists and is running. Creates and provisions on first use. */
|
|
export async function ensure(log?: (msg: string) => void): Promise<void> {
|
|
requireContainer()
|
|
|
|
// Ensure the container daemon is running
|
|
await $`container system start`.nothrow().quiet()
|
|
|
|
const s = await status()
|
|
if (s === "running") return
|
|
|
|
if (s === "stopped") {
|
|
await start()
|
|
return
|
|
}
|
|
|
|
await create(log)
|
|
}
|
|
|
|
/** Check container status. */
|
|
export async function status(): Promise<"running" | "stopped" | "missing"> {
|
|
const result = await $`container list --format json --all`.nothrow().quiet().text()
|
|
|
|
try {
|
|
const containers = JSON.parse(result.trim())
|
|
const container = containers.find((c: any) => c.configuration?.id === CONTAINER_NAME)
|
|
if (!container) return "missing"
|
|
return container.status?.toLowerCase() === "running" ? "running" : "stopped"
|
|
} catch {
|
|
return "missing"
|
|
}
|
|
}
|
|
|
|
/** Launch claude in the container at the given workdir. */
|
|
export async function claude(workdir: string, opts?: { prompt?: string; print?: string }): Promise<string | void> {
|
|
const cwd = containerPath(workdir)
|
|
const systemPromptLines = [
|
|
"You are running inside a sandlot container (Apple Container, ubuntu:24.04).",
|
|
`Your working directory is ${cwd}, a git worktree managed by sandlot.`,
|
|
"The host's ~/dev is mounted read-only at /host.",
|
|
"The host's ~/.sandlot is mounted at /sandlot.",
|
|
"Bun is installed at ~/.local/bin/bun. Use bun instead of node/npm.",
|
|
]
|
|
if (opts?.print) {
|
|
systemPromptLines.push("IMPORTANT: Do not use plan mode. Do not call the EnterPlanMode tool. Proceed directly with the task.")
|
|
}
|
|
const systemPrompt = systemPromptLines.join("\n")
|
|
|
|
const term = process.env.TERM || "xterm-256color"
|
|
const args = ["container", "exec", "-it", "--user", USER, "--workdir", cwd, CONTAINER_NAME, "env", `TERM=${term}`, CLAUDE_BIN, "--dangerously-skip-permissions", "--model", "claude-opus-4-6", "--append-system-prompt", systemPrompt]
|
|
if (opts?.print) args.push("-p", opts.print)
|
|
else if (opts?.prompt) args.push(opts.prompt)
|
|
|
|
if (opts?.print) {
|
|
const proc = Bun.spawn(args, { stdin: "inherit", stdout: "pipe", stderr: "inherit" })
|
|
const output = await new Response(proc.stdout).text()
|
|
await proc.exited
|
|
return output
|
|
}
|
|
|
|
const proc = Bun.spawn(args, { stdin: "inherit", stdout: "inherit", stderr: "inherit" })
|
|
await proc.exited
|
|
}
|
|
|
|
/** Open an interactive fish shell in the container, optionally in a specific directory. */
|
|
export async function shell(workdir?: string): Promise<void> {
|
|
const args = ["container", "exec", "-it", "--user", USER]
|
|
if (workdir) args.push("--workdir", containerPath(workdir))
|
|
args.push(CONTAINER_NAME, "env", "TERM=xterm-256color", "fish", "--login")
|
|
const proc = Bun.spawn(args, { stdin: "inherit", stdout: "inherit", stderr: "inherit" })
|
|
await proc.exited
|
|
}
|
|
|
|
/** Run neofetch in the container. */
|
|
export async function info(): Promise<void> {
|
|
const proc = Bun.spawn(
|
|
["container", "exec", "--user", USER, CONTAINER_NAME, "neofetch"],
|
|
{ stdin: "inherit", stdout: "inherit", stderr: "inherit" },
|
|
)
|
|
await proc.exited
|
|
}
|
|
|
|
/** Run a bash command in the container at the given workdir, capturing output. */
|
|
export async function exec(workdir: string, command: string): Promise<{ exitCode: number; stdout: string; stderr: string }> {
|
|
const result = await $`container exec --user ${USER} --workdir ${containerPath(workdir)} ${CONTAINER_NAME} bash -c ${"export PATH=$HOME/.local/bin:$PATH; " + command}`.nothrow().quiet()
|
|
return {
|
|
exitCode: result.exitCode,
|
|
stdout: result.stdout.toString().trim(),
|
|
stderr: result.stderr.toString().trim(),
|
|
}
|
|
}
|
|
|
|
/** Check if Claude is actively working in the given worktree (based on activity hook). */
|
|
export async function isClaudeActive(worktree: string, branch: string): Promise<boolean> {
|
|
const file = `${dirname(worktree)}/.activity-${branch}`
|
|
try {
|
|
const content = await Bun.file(file).text()
|
|
return content.trim() === "active"
|
|
} catch {
|
|
return false
|
|
}
|
|
}
|
|
|
|
/** Remove the activity marker file for a worktree. */
|
|
export async function clearActivity(worktree: string, branch: string): Promise<void> {
|
|
const file = `${dirname(worktree)}/.activity-${branch}`
|
|
await Bun.file(file).unlink().catch(() => {})
|
|
}
|
|
|
|
/** Stop the container. */
|
|
export async function stop(): Promise<void> {
|
|
await $`container stop ${CONTAINER_NAME}`.nothrow().quiet()
|
|
}
|
|
|
|
/** Stop and delete the container. */
|
|
export async function destroy(): Promise<void> {
|
|
await stop()
|
|
await $`container delete ${CONTAINER_NAME}`.nothrow().quiet()
|
|
}
|