Files
w3cjandClaude Opus 5.5 376f1c2ad7 fix(agents): opencode's save, plugin approvals and the history scripts' framing
devvm agent save refused a VM whose ~/.config/opencode held a bun.lock (which opencode's plugins' installs write), a package-lock.json, a .gitignore or a .DS_Store: the save's script sent every entry of that folder but node_modules and FolderOwn, while the host's listedPath refuses those files (fileSetting), so it saved nothing. notSettings is now their one list, as patterns path.Match and the shell's case read alike: fileSetting leaves them out and the script sends a file of those names no more, only a folder that isn't a link, which is a setting. TestAgentSaveScriptRuns plants them and a folder named old.lock, and failed with agent_save_unsafe before the fix.

opencode's HistoryOwn names its native client's plugin approvals, in its state folder (cli-rs's plugin/src/loader/approval.rs and tui/src/plugins/host.rs, opencode v2.4.1): plugin-approvals.json, its .lock and the .plugin-approvals.json.<pid>.<n>.tmp it's written through, and plugin-staged, the approved trees' copies, which it reuses by their hash's name without hashing them again, so a hostile VM's export could approve a project plugin for the VM that imports it. That client doesn't ship in 2.4.1. TestHistoryExportRuns and TestHistoryImportRuns plant them, with plugin-notes.json as the control, and failed on fedora without the entries.

The history scripts' framing (onInputCmd) now says why on its stderr, which goes to the VM's log, when its input was cut short: TestOnInputCutShort checks it for every cut, an empty input included, and none for a whole one, and failed before. TestHistoryScriptsOnInput holds each script under 128 KiB, Linux's limit on one argument, which bash -c "$s" passes it as. The CLI scripts match the framing's new start.

Docs: the save's and the store's table say which files stay in the VM; the import's and How it works' lists name the plugin approvals; the release page gets opencode's lock files in a save and the approvals; the changelog's opencode block gets the save's fix, and the hardening line names approved plugins. The review's optional wording: the design note's `*` matches every resource, and the plain-password steps set this machine's password first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:03:05 -07:00

734 lines
34 KiB
Go

package vm
import (
"context"
"errors"
"io/fs"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"unicode"
"unicode/utf16"
"github.com/devvmhq/devvm/internal/agents"
"github.com/devvmhq/devvm/internal/backend"
"github.com/devvmhq/devvm/internal/image"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/paths"
"github.com/devvmhq/devvm/internal/shell"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/tools"
)
// Each agent's settings (agents.Def's Dirs, Files and Folder) are paths
// relative to the home folder, which devvm's store of the agent's
// settings (agentStore) keeps at the same paths below it. Folders are
// mounted read-only at their path in the store and linked into the VM's
// home; files are copied in on every launch. An agent's logins are in the
// store of its logins (secrets.LoginFile). History (transcripts,
// sessions, databases) is in neither.
// agentStore is devvm's store of an agent's settings, laid out as they
// are in the home folder: the one place devvm reads them from for VMs,
// never the home folder.
func agentStore(d paths.Dirs, agent string) string { return d.AgentSettings(agent) }
// opencodeData is opencode's data folder. opencode 2 keeps its sessions
// and its logins in one SQLite database there, opencode.db (or
// opencode-<channel>.db for another channel's build), in WAL mode, so
// the database's -wal file holds the pages it changed last, its logins'
// among them, until opencode checkpoints it.
const opencodeData = agents.OpencodeData
// opencodeDBs are the names of opencode's databases and their WAL,
// shared-memory and rollback journal files in opencodeData, as globs.
// An export and an import never take them as they are: only the
// database's copy that opencodeClean makes.
var opencodeDBs = []string{"opencode*.db", "opencode*.db-wal", "opencode*.db-shm", "opencode*.db-journal"}
// opencodeLogins is the SQL condition that picks the tables of
// opencode's database that hold logins: opencode 2.2's credential
// (logins and API keys), account and control_account (its console's
// access and refresh tokens) and account_state, an earlier opencode's
// session_share (each share's secret), opencode 2.4's machine (the public
// key each machine it paired logs in to its home with, the VM's own as
// a machine, as its home key is: agents.Def's HistoryOwn), and any other
// table whose name or a column's says it holds one, so a table a later
// opencode adds for its logins is picked too. testdata/opencode-2.4.1.sql
// is opencode's own schema, which TestOpencodeCleanSchema checks it
// against.
const opencodeLogins = `type = 'table' AND name NOT LIKE 'sqlite\_%' ESCAPE '\' AND (name = 'machine' OR ` +
`name LIKE '%credential%' OR name LIKE '%account%' OR name LIKE '%auth%' OR name LIKE '%secret%' ` +
`OR name LIKE '%token%' OR name LIKE '%share%' OR name IN (SELECT m.name FROM sqlite_master m ` +
`JOIN pragma_table_info(m.name) c WHERE m.type = 'table' AND lower(c.name) IN ('secret', 'access_token', ` +
`'refresh_token', 'id_token', 'api_key', 'apikey', 'password', 'token', 'credential', 'credentials')))`
// opencodeUnattended is the SQL condition that picks the tables of
// opencode's database whose rows let something run in the VM without
// asking, which an exported database brings from another VM, from
// opencode v2.4.1's source: automation, each automation's trigger and the
// shell command it runs on it, which opencode approved once, as it was
// made, and never asks about again (core/src/automation/shell.ts);
// permission, the requests you said always to allow in a project; job,
// the subagents' jobs, which its service starts again when it starts
// (core/src/session/execution/restart.ts); and session_inbox, the
// messages queued for a session's next turn. Any table whose name starts
// as theirs is picked too, so one a later opencode adds for them is.
// What else runs without asking is a column (opencodeNulled,
// opencodeAllowRules).
const opencodeUnattended = `type = 'table' AND (name LIKE 'automation%' OR name LIKE 'permission%' OR name LIKE 'job%' ` +
`OR name LIKE 'session_inbox%')`
// opencodeNulled is the SQL condition that picks the columns, of every
// table (c, of m), that opencodeClean sets to NULL: time_suspended, which
// marks a session whose turn opencode's service resumes on its own when it
// starts (session_v2), and commands, a project's commands, whose start
// command opencode runs with bash -lc for each worktree it makes
// (core/src/worktree.ts). Names are compared in lower case, as SQLite
// reads them.
const opencodeNulled = `FROM sqlite_master m JOIN pragma_table_info(m.name) c WHERE m.type = 'table' ` +
`AND lower(c.name) IN ('time_suspended', 'commands')`
// opencodeAllowRules is the SQL that keeps only the deny and ask rules of
// the permission column of a table, a printf format that names the table
// (%w) twice: opencode 2.4's session_v2 keeps each session's rules there,
// a JSON array of {action, resource, effect}, and a session imported with
// an allow rule would run what it allows without asking. A value that
// isn't such an array becomes NULL, no rules, and so does a rule that
// isn't an object with a text action. Each rule kept is written again
// from the values sqlite3 read, so a key written twice, which sqlite3
// reads first and opencode's JSON.parse last, can't keep an allow
// effect behind a deny; a resource that isn't text becomes "*", every
// resource, as opencode's Permission.Rule needs one. opencodeAllowLeft
// counts the rows whose value is still anything else, a rule that isn't
// in the form written again included. Each reads JSON only where CASE
// has found it valid, as sqlite3's AND and OR may read both sides and
// fail on what isn't JSON.
const (
opencodeAllowRules = `UPDATE "%w" SET permission = NULL WHERE permission IS NOT NULL AND ` +
`CASE WHEN json_valid(permission) THEN json_type(permission) IS NOT 'array' ELSE 1 END; ` +
`UPDATE "%w" SET permission = (SELECT json_group_array(json_object('action', json_extract(r.value, '$.action'), ` +
`'resource', CASE WHEN json_type(r.value, '$.resource') = 'text' THEN json_extract(r.value, '$.resource') ELSE '*' END, ` +
`'effect', json_extract(r.value, '$.effect'))) FROM json_each(permission) AS r ` +
`WHERE CASE WHEN r.type = 'object' THEN json_type(r.value, '$.action') = 'text' ` +
`AND json_extract(r.value, '$.effect') IN ('deny', 'ask') ELSE 0 END) WHERE permission IS NOT NULL;`
opencodeAllowLeft = `SELECT count(*) FROM "%w" WHERE permission IS NOT NULL AND CASE WHEN NOT json_valid(permission) THEN 1 ` +
`WHEN json_type(permission) IS NOT 'array' THEN 1 ELSE EXISTS (SELECT 1 FROM json_each(permission) AS r WHERE ` +
`CASE WHEN r.type = 'object' THEN coalesce(json_extract(r.value, '$.effect') IN ('deny', 'ask'), 0) = 0 ` +
`OR json_type(r.value, '$.action') IS NOT 'text' OR r.value IS NOT json_object('action', json_extract(r.value, '$.action'), ` +
`'resource', CASE WHEN json_type(r.value, '$.resource') = 'text' THEN json_extract(r.value, '$.resource') ELSE '*' END, ` +
`'effect', json_extract(r.value, '$.effect')) ELSE 1 END) END;`
// opencodeRuleTables picks the tables with a permission column, its
// name in any case, as SQLite reads it.
opencodeRuleTables = `FROM sqlite_master m JOIN pragma_table_info(m.name) c WHERE m.type = 'table' AND lower(c.name) = 'permission'`
)
// opencodeHidden is the SQL that counts the columns of the database's
// tables that pragma_table_info doesn't list, a generated column's or a
// virtual table's, which opencodeClean's steps would miss, so a copy with
// any fails its check. opencode's own tables have none.
const opencodeHidden = `SELECT count(*) FROM sqlite_master m JOIN pragma_table_xinfo(m.name) c WHERE m.type = 'table' AND c.hidden != 0;`
// opencodeAuthImport is opencode 2's migration that imports auth.json
// into its credential table, once. opencodeClean takes its record out,
// so the opencode that next opens the copy imports the logins devvm's
// setup wrote in that VM's auth.json, as it does when it makes its
// database.
const opencodeAuthImport = "20260805200742_import_legacy_credentials"
// opencodeWellknown is the SQL condition that picks the rows of
// opencode's kv table that hold an organization's remote config, which
// opencode fetched with its well-known login's headers, one row for each
// organization; opencode fetches it again after that login.
const opencodeWellknown = `key LIKE 'wellknown:config:%'`
// opencodeClean is the shell function devvm_opencode_clean DB, which
// makes clean.db in the current folder: a copy of opencode's database
// DB without its logins, nor anything that would run without asking in
// the VM that gets it. sqlite3 copies it with VACUUM INTO, which reads
// the database with what its -wal file holds, as one snapshot; in the
// copy it drops every trigger and view, empties the tables opencodeLogins
// and opencodeUnattended pick, sets the columns opencodeNulled picks to
// NULL, keeps only the deny and ask rules of each permission column
// (opencodeAllowRules), deletes the kv rows opencodeWellknown picks and
// takes opencodeAuthImport's record out, then turns WAL off and rebuilds
// the file (secure_delete and VACUUM), so no page of it keeps a deleted
// row. It fails when the VM has no sqlite3, or one without JSON, when any
// step fails, when the copy has fewer tables than DB or none, or unless
// each count left (the triggers and views, the generated columns
// (opencodeHidden), each table it emptied, each column it set to NULL,
// each permission column's rules that aren't deny or ask, kv's rows it
// deleted) prints 0, so a sqlite3 that runs nothing and prints nothing
// fails too;
// the caller then leaves the database out. The schema's own functions stay off
// (trusted_schema), as an imported database is the export's: each
// sqlite3 gets that pragma first in its own input, never in -cmd, as
// sqlite3 3.54 with -bail stops after an SQL -cmd and runs nothing
// else, exiting 0.
func opencodeClean() string {
// opencodeWellknown in an SQL string literal, its quotes doubled.
wellknown := strings.ReplaceAll(opencodeWellknown, "'", "''")
allowRules, allowLeft := strings.ReplaceAll(opencodeAllowRules, "'", "''"), strings.ReplaceAll(opencodeAllowLeft, "'", "''")
gen := `SELECT printf('DROP TRIGGER IF EXISTS "%w";', name) FROM sqlite_master WHERE type = 'trigger';` + "\n" +
`SELECT printf('DROP VIEW IF EXISTS "%w";', name) FROM sqlite_master WHERE type = 'view';` + "\n" +
`SELECT printf('DELETE FROM "%w";', name) FROM sqlite_master WHERE ` + opencodeLogins + ";\n" +
`SELECT printf('DELETE FROM "%w";', name) FROM sqlite_master WHERE ` + opencodeUnattended + ";\n" +
`SELECT printf('UPDATE "%w" SET "%w" = NULL;', m.name, c.name) ` + opencodeNulled + ";\n" +
`SELECT printf('` + allowRules + `', m.name, m.name) ` + opencodeRuleTables + ";\n" +
`SELECT 'DELETE FROM migration WHERE id = ''` + opencodeAuthImport + `'';' FROM sqlite_master ` +
`WHERE type = 'table' AND name = 'migration';` + "\n" +
`SELECT 'DELETE FROM kv WHERE ` + wellknown + `;' FROM sqlite_master WHERE type = 'table' AND name = 'kv';`
check := `SELECT 'SELECT count(*) FROM sqlite_master WHERE type IN (''trigger'', ''view'');';` + "\n" +
`SELECT '` + strings.ReplaceAll(opencodeHidden, "'", "''") + `';` + "\n" +
`SELECT printf('SELECT count(*) FROM "%w";', name) FROM sqlite_master WHERE ` + opencodeLogins + ";\n" +
`SELECT printf('SELECT count(*) FROM "%w";', name) FROM sqlite_master WHERE ` + opencodeUnattended + ";\n" +
`SELECT printf('SELECT count(*) FROM "%w" WHERE "%w" IS NOT NULL;', m.name, c.name) ` + opencodeNulled + ";\n" +
`SELECT printf('` + allowLeft + `', m.name) ` + opencodeRuleTables + ";\n" +
`SELECT 'SELECT count(*) FROM kv WHERE ` + wellknown + `;' FROM sqlite_master WHERE type = 'table' AND name = 'kv';`
const untrusted = "PRAGMA trusted_schema = OFF;"
tables := shell.Quote("SELECT count(*) FROM sqlite_master WHERE type = 'table';")
// sql runs sqlite3 on clean.db with untrusted first, then its
// arguments, or its stdin when it has none.
sql := "sqlite3 -bail clean.db '" + untrusted + "'"
return strings.Join([]string{
"devvm_opencode_clean() {",
" local t s c left",
" rm -f clean.db clean.db-journal clean.db-wal clean.db-shm &&",
// The copy, then the original's count of tables, which the copy
// must have too: a copy that isn't made, or is empty, fails.
` t=$(sqlite3 -bail "$1" '.timeout 10000' '` + untrusted + `' "VACUUM INTO 'clean.db'" ` + tables + `) || return 1`,
` case $t in '' | 0 | *[!0-9]*) return 1 ;; esac`,
` [ "$(` + sql + " " + tables + `)" = "$t" ] &&`,
" s=$(" + sql + " " + shell.Quote(gen) + ") &&",
` printf '` + untrusted + `\nPRAGMA journal_mode = DELETE;\nPRAGMA secure_delete = ON;\n%s\nVACUUM;\n' "$s" | sqlite3 -bail clean.db >/dev/null &&`,
// check's first statement, the triggers' count, is always there,
// and each of its statements must print one 0: no output, or
// less, fails too.
" c=$(" + sql + " " + shell.Quote(check) + ") && [ -n \"$c\" ] &&",
` left=$(printf '` + untrusted + `\n%s\n' "$c" | sqlite3 -bail clean.db) && [ -n "$left" ] &&`,
` [ "$(printf '%s\n' "$left" | grep -cx 0)" = "$(printf '%s\n' "$c" | grep -c '')" ] &&`,
` ! printf '%s\n' "$left" | grep -qvx 0 || return 1`,
" [ ! -e clean.db-wal ] && [ ! -e clean.db-journal ]",
"}",
}, "\n")
}
// opencodeCleanAll is the shell loop that runs devvm_opencode_clean on
// each of opencode's databases in the folder dir (shell-quoted), from the
// current folder, then runs then with $db, the database, for the copy it
// made. When there's no copy, or then fails, it says so and runs
// otherwise. A database that's a symbolic link is never read.
func opencodeCleanAll(dir, then, otherwise string) string {
return strings.Join([]string{
"for db in " + dir + "/" + opencodeDBs[0] + "; do",
` [ -f "$db" ] && [ ! -L "$db" ] || continue`,
` if ! command -v sqlite3 >/dev/null; then echo "devvm: left out $db: the VM has no sqlite3" >&2`,
` elif devvm_opencode_clean "$db" && ` + then + "; then continue",
` else echo "devvm: left out $db: its copy without opencode's logins failed" >&2`,
" fi",
" " + otherwise,
"done",
}, "\n")
}
// historyExport is the script that writes an export of the VM's agents'
// history to its stdout, a gzipped tar of what there is of their History,
// run in the VM as its user: without their HistoryExcludes or the VM's own
// folders of their seeds (agents.Seed), which are settings, never history:
// they hold what the VM installed, which reaches another VM only through
// devvm agent save, and what each plugin keeps, such as its own logins and
// caches. With each
// of opencode's databases as its copy without its logins (opencodeClean),
// made in a folder of its own and put at the database's path
// (--transform, which leaves links' targets as they are), never the
// database or its WAL and journal files as they are (opencodeDBs, each
// matched within its folder).
func historyExport() string {
historyExcludes := agents.HistoryExcludes()
excludes := make([]string, 0, len(historyExcludes)+len(opencodeDBs)+1)
for _, p := range historyExcludes {
excludes = append(excludes, "--exclude="+p)
}
for _, sd := range agents.Seeds() {
excludes = append(excludes, "--exclude="+sd.Rel)
}
excludes = append(excludes, "--no-wildcards-match-slash")
for _, p := range opencodeDBs {
excludes = append(excludes, "--exclude="+opencodeData+"/"+p)
}
// No pipefail: ls fails on the paths there aren't, and only tar's
// status counts.
return strings.Join([]string{
opencodeClean(),
`mkdir -p ~/.cache && t=$(mktemp -d ~/.cache/devvm-export.XXXXXX) || exit 1`,
`trap 'rm -rf "$t"' EXIT`,
`mkdir "$t/devvm-clean" && cd "$t" || exit 1`,
"add=()",
opencodeCleanAll(`"$HOME"/`+shell.Quote(opencodeData),
`mv clean.db "devvm-clean/${db##*/}" && add=(${add[@]+"${add[@]}"} "devvm-clean/${db##*/}")`, ":"),
`[ "${#add[@]}" -eq 0 ] || add=(-C "$t" "${add[@]}")`,
"cd ~ && ls -d " + strings.Join(agents.History(), " ") + " 2>/dev/null | tar -czf - " + shell.QuoteJoin(excludes) +
" " + shell.Quote("--transform=flags=r;s,^devvm-clean/,"+opencodeData+"/,") + ` -T - ${add[@]+"${add[@]}"}`,
}, "\n")
}
// historyUnsafe is what historyImport prints when it imports nothing
// because a path in the export is outside the agents' history.
const historyUnsafe = "devvm-history-unsafe"
// importSkips are the paths in an export of agents' history, relative to
// the home folder, that an import leaves out, because devvm's setup
// writes them: what an export leaves out (HistoryExcludes), every login
// file in the agents' history, such as ~/.claude.json, whose copy holds
// the old VM's placeholders, every agent's folders linked to their
// mounts, the seeds' links among them, and the VM's own folders of the
// seeds, which an export leaves out, and files copied from the host.
// Sorted.
func importSkips() []string {
skips := agents.HistoryExcludes()
for _, d := range agents.Defs {
for _, l := range d.Logins {
if slices.ContainsFunc(d.History, func(h string) bool { return l.Rel == h || strings.HasPrefix(l.Rel, h+"/") }) {
skips = append(skips, l.Rel)
}
}
skips = append(skips, d.Dirs...)
for _, sd := range d.Seeds {
skips = append(skips, sd.Link)
}
for _, f := range d.Files {
skips = append(skips, f.Rel)
}
}
slices.Sort(skips)
return slices.Compact(skips)
}
// appleDouble matches an export's name whose last part is an AppleDouble
// file's, ._ then anything (historyImport).
const appleDouble = `(^|/)\._[^/]*$`
// historyImport is the script that puts an export of agents' history,
// on its stdin, into the VM's home, run there as the VM's user, so the
// host never reads the export. It saves the export in a folder of its
// own and lists its paths as they are in it (--absolute-names, which
// only the listing takes: tar would list them with their leading / and
// .. parts taken off), each on one line (GNU tar's escape quoting). It
// imports nothing when one is outside the agents' History, absolute or has a
// ., .. or empty part (such as .claude/./plugins or .claude//plugins, which
// an exclude, matched against the name as written, would miss), printing
// historyUnsafe instead. An AppleDouble file (a name
// whose last part starts with ._), which macOS's tar puts beside each file
// with extended attributes, such as com.apple.provenance, isn't checked
// and is never unpacked (appleDouble), so an export made on a Mac imports;
// what's below a folder named so is checked. Every tar here is GNU tar,
// which Debian and Ubuntu have and base's Alpine branch installs over
// busybox's (TestHistoryImportHasGNUTarOnAlpine). GNU tar unpacks it
// in a folder of its own, without its owners or modes (the user's umask
// applies) and without importSkips (anchored, each with what's below
// it); the symlinks there that point outside it (absolute, or with a ..
// part) are taken out, so an agent's write never follows one out of its
// history, and only then is each of importSkips taken out again by its
// path, whatever name got it there, so that never follows one either.
// opencode's databases' WAL and journal files, and any of its
// databases that isn't a regular file, are taken out, and each database
// becomes its copy without its logins (opencodeClean), or is taken out
// when there's none, so an export made without it, which holds them,
// never gives them to a VM; then what's left of their History goes into the home folder,
// without replacing a file or folder the VM has (--skip-old-files,
// which implies --no-overwrite-dir).
func historyImport() string {
historyPaths := agents.History()
allowed := make([]string, len(historyPaths))
for i, p := range historyPaths {
allowed[i] = regexp.QuoteMeta(p)
}
own := []string{"--no-same-owner", "--no-same-permissions"}
unpack := append(slices.Clone(own), "--anchored")
for _, p := range importSkips() {
unpack = append(unpack, "--exclude="+p)
}
unpack = append(unpack, "--exclude=._*", "--exclude=*/._*")
return strings.Join([]string{
"set -o pipefail",
`mkdir -p ~/.cache && t=$(mktemp -d ~/.cache/devvm-import.XXXXXX) || exit 1`,
`trap 'rm -rf "$t"' EXIT`,
`cat > "$t/export" && tar -tzf "$t/export" --absolute-names --quoting-style=escape > "$t/names" || exit 1`,
"if grep -vE " + shell.Quote(appleDouble) + ` "$t/names" | grep -vqE ` + shell.Quote("^("+strings.Join(allowed, "|")+")(/|$)") + ` || ` +
"grep -qE " + shell.Quote(`(^|/)(\.\.?)?/|(^|/)\.\.?$`) + ` "$t/names"; then echo ` + historyUnsafe + "; exit 1; fi",
`mkdir "$t/x" && tar -xzf "$t/export" -C "$t/x" ` + shell.QuoteJoin(unpack) + " || exit 1",
`find "$t/x" -type l -print0 | while IFS= read -r -d '' l; do`,
` case $(readlink "$l") in /* | .. | ../* | */.. | */../*) echo "devvm: left out the link $l" >&2; rm -f "$l" ;; esac`,
"done",
"# shellcheck disable=SC2231 # each is a path or a pattern (agents.Def's HistoryOwn), which the loop expands",
`for p in ` + shell.QuoteJoin(importSkips()) + `; do for f in "$t/x/"$p; do rm -rf "$f"; done; done`,
opencodeClean(),
`o="$t/x/"` + shell.Quote(opencodeData),
`for f in "$o"/` + strings.Join(opencodeDBs[1:], ` "$o"/`) + `; do rm -rf "$f"; done`,
`for f in "$o"/` + opencodeDBs[0] + `; do if [ -L "$f" ] || { [ -e "$f" ] && [ ! -f "$f" ]; }; then rm -rf "$f"; fi; done`,
`cd "$t" || exit 1`,
opencodeCleanAll(`"$o"`, `mv clean.db "$db"`, `rm -f "$db"`),
`cd "$t/x" && set -- && for p in ` + shell.QuoteJoin(historyPaths) + `; do if [ -e "$p" ] || [ -L "$p" ]; then set -- "$@" "$p"; fi; done`,
`[ "$#" -eq 0 ] || tar -cf - "$@" | tar --extract --file=- --directory ~ --skip-old-files ` + shell.QuoteJoin(own),
}, "\n")
}
// agentDirs returns an agent's settings folders, relative to home, a home
// folder or the agent's store (agentStore): its Dirs, and for a
// WholeFolder agent (opencode) its folder's subfolders there as they are
// now, but node_modules and what's each machine's own (folderSetting).
func agentDirs(home, agent string) []string {
d := agents.Of(agent)
dirs := slices.Clone(d.Dirs)
if !d.WholeFolder {
return dirs
}
for _, e := range readDir(filepath.Join(home, d.Folder)) {
if e.IsDir() && folderSetting(d, e.Name()) {
dirs = append(dirs, d.Folder+"/"+e.Name())
}
}
return dirs
}
// agentLink is where the VM's home links an agent's settings folder rel,
// mounted from the store: a seed's Link, as the folder at rel is the
// VM's own (agents.Seed), or rel.
func agentLink(rel string) string {
if sd, ok := agents.SeedOf(rel); ok {
return sd.Link
}
return rel
}
// folderSetting reports whether a folder of a WholeFolder agent's folder,
// by its name, is among its settings: all but node_modules and those
// that are each machine's own (agents.MachineOwn).
func folderSetting(d agents.Def, name string) bool {
return name != "node_modules" && !agents.MachineOwn(d.Folder+"/"+name)
}
// fileSetting reports whether a file of a WholeFolder agent's folder, by
// its name, is among its settings: all but lock files and the like
// (notSettings), and those that are each machine's own
// (agents.MachineOwn), such as opencode's service.json.
func fileSetting(d agents.Def, name string) bool {
return !slices.ContainsFunc(notSettings(), func(p string) bool { ok, _ := path.Match(p, name); return ok }) &&
!agents.MachineOwn(d.Folder+"/"+name)
}
// notSettings are the names of a WholeFolder agent's files that are never
// its settings, as patterns that path.Match and a shell's case read
// alike: lock files and what else a package manager or a Mac leaves
// there. fileSetting leaves them out, and the save's script doesn't send
// them (agentSaveScript).
func notSettings() []string {
return []string{"*.lock", "package-lock.json", ".gitignore", ".DS_Store"}
}
// agentFiles returns an agent's settings files, relative to home, a home
// folder or the agent's store (agentStore): its Files, and for a
// WholeFolder agent (opencode) its folder's files there, but lock files
// and what's each machine's own, such as opencode's service.json
// (fileSetting), which no store keeps and no VM gets, even from a store
// that an earlier devvm agent import filled.
func agentFiles(home, agent string) []string {
d := agents.Of(agent)
var files []string
for _, f := range d.Files {
files = append(files, f.Rel)
}
if !d.WholeFolder {
return files
}
for _, e := range readDir(filepath.Join(home, d.Folder)) {
if e.Type().IsRegular() && fileSetting(d, e.Name()) {
files = append(files, d.Folder+"/"+e.Name())
}
}
return files
}
// agentLinks returns the links in a WholeFolder agent's (opencode's)
// folder in home, relative to home, but those named as no file or folder
// of its settings could be (folderSetting, fileSetting): agentDirs and
// agentFiles leave links out, so devvm agent import reads these as it
// reads a link among another agent's settings, which it copies or leaves
// out with a warning, never without one.
func agentLinks(home, agent string) []string {
d := agents.Of(agent)
if !d.WholeFolder {
return nil
}
var links []string
for _, e := range readDir(filepath.Join(home, d.Folder)) {
if e.Type()&fs.ModeSymlink != 0 && folderSetting(d, e.Name()) && fileSetting(d, e.Name()) {
links = append(links, d.Folder+"/"+e.Name())
}
}
return links
}
// readDir returns a folder's entries, but those whose names have a
// control character: the VM's setup takes paths one per line.
func readDir(dir string) []os.DirEntry {
es, _ := os.ReadDir(dir)
return slices.DeleteFunc(es, func(e os.DirEntry) bool { return strings.IndexFunc(e.Name(), unicode.IsControl) >= 0 }) //nolint:forbidigo // the setup's one path per line, not the terminal
}
// AgentMounts returns the host folders a VM with these shared tools
// mounts: its agents' settings folders that exist in devvm's store. One
// with a comma in its path is left out on every backend, with a warning:
// Lima splits mount options on commas.
func (e Launch) AgentMounts(tools []string) []string {
dirs, comma := agentMounts(e.Dirs, tools)
for _, p := range comma {
e.Warn(msg.AgentDirComma(p))
}
return dirs
}
// agentMounts returns the folders of devvm's store a VM with these shared
// tools mounts (AgentMounts), and those it leaves out for a comma.
func agentMounts(d paths.Dirs, tools []string) (dirs, comma []string) {
for _, a := range image.AgentsOf(tools) {
store := agentStore(d, a)
for _, rel := range agentDirs(store, a) {
p := filepath.Join(store, rel)
if fi, err := os.Stat(p); err != nil || !fi.IsDir() {
continue
}
if strings.Contains(p, ",") {
comma = append(comma, p)
continue
}
dirs = append(dirs, p)
}
}
return dirs, comma
}
// cleanStore takes out of devvm's agent store what is each machine's own
// (agents.MachineOwn) and warns of what it took out of each folder. That's
// each entry of a seed's folder that isn't one of its Entries, such as
// Claude Code's plugins' data and installed_plugins.json
// (agent_seed_cleaned), which only devvm agent import of devvm 0.1.0 put
// there, as it copied the whole plugins folder, and every VM with the
// agent mounts the seed's folder whole, so a VM could read them. It's also
// the entries of a WholeFolder agent's folder that its FolderOwn names,
// such as opencode's service.json, with this machine's service password
// (cleanFolderOwn). Today's import and save copy neither, so this finds
// them once, at the first start after an upgrade. A seed's folder itself
// stays, so no VM's mounts change. Every start takes this step before the
// VM runs (starter.bringUp). A seed's folder it can't clean fails the
// start of a VM with that agent (has, the agents the VM has), which would
// read the entries, and is a warning for any other VM
// (agent_seed_clean_failed). It takes them out holding the store's lock
// (lockStore), once it has found any, so a start with nothing to clean
// never waits for an import or a save.
func (e *Env) cleanStore(ctx context.Context, has []string) error {
var unlock func()
defer func() {
if unlock != nil {
unlock()
}
}()
lock := func() error {
if unlock != nil {
return nil
}
var err error
unlock, err = lockStore(ctx, e.Dirs, e.Reporter)
return err
}
for _, d := range agents.Defs {
store := agentStore(e.Dirs, d.Name)
cleanFolderOwn(e.Dirs, e.Reporter, d, lock)
for _, sd := range d.Seeds {
dir := filepath.Join(store, filepath.FromSlash(sd.Rel))
temp := func(en fs.DirEntry) bool { return en.Type().IsRegular() && seedTemp(sd, en.Name()) }
gone, err := cleanOwn(e.Dirs.Config, store, sd.Rel, temp, lock)
if len(gone) > 0 {
e.Warn(msg.AgentSeedCleaned(d.Display, dir, shownList(gone)))
}
if err == nil {
continue
}
m := msg.AgentSeedCleanFailed(d.Display, dir, shownList(sd.Entries), err.Error()).Because(err)
if l, ok := errors.AsType[storeLink](err); ok {
m = msg.AgentSeedLink(d.Display, dir, shownList(sd.Entries), l.path).Because(err)
}
if slices.Contains(has, d.Name) {
return m
}
e.Warn(m)
}
}
return nil
}
// cleanFolderOwn takes out of a WholeFolder agent's folder in devvm's
// agent store, d's, the entries its FolderOwn names, such as opencode's
// service.json, and warns r of what it took out (agent_store_own_cleaned).
// No VM gets them from the store (agentFiles), so a folder it can't clean
// is a warning (agent_store_own_clean_failed), whichever agents the VM
// has.
func cleanFolderOwn(dirs paths.Dirs, r msg.Reporter, d agents.Def, lock func() error) {
if !d.WholeFolder || len(d.FolderOwn) == 0 {
return
}
store := agentStore(dirs, d.Name)
dir := filepath.Join(store, filepath.FromSlash(d.Folder))
gone, err := cleanOwn(dirs.Config, store, d.Folder, nil, lock)
if len(gone) > 0 {
r.Warn(msg.AgentStoreOwnCleaned(d.Display, dir, shownList(gone)))
}
if err != nil {
r.Warn(msg.AgentStoreOwnCleanFailed(dir, shownList(d.FolderOwn), err.Error()).Because(err))
}
}
// cleanOwn takes out what of the folder rel in an agent's store, below
// devvm's config folder config, is each machine's own (cleanStore), but
// the entries keep reports, and returns the names it took out. It opens
// the folder through config (openStoreDir), so a link on its path, which
// could lead to this machine's own plugins folder, is an error, as the
// VM's mount follows it, and no folder there means nothing to clean. A
// link among the folder's entries is taken out, never followed. A seed's
// keep is the temporary files that devvm agent import and save write its
// entries through (seedTemp), regular files. Once it finds any to take
// out, it calls lock, which holds the store's lock, and looks again under
// it.
func cleanOwn(config, store, rel string, keep func(fs.DirEntry) bool, lock func() error) ([]string, error) {
if found, err := storeOwn(config, store, rel, keep, false); err != nil || len(found) == 0 {
return nil, err
}
if err := lock(); err != nil {
return nil, err
}
return storeOwn(config, store, rel, keep, true)
}
// storeOwn returns what of the folder rel in an agent's store is each
// machine's own, as cleanOwn says, taking each out when take.
func storeOwn(config, store, rel string, keep func(fs.DirEntry) bool, take bool) ([]string, error) {
dir, err := openStoreDir(config, filepath.Join(store, filepath.FromSlash(rel)))
if err != nil || dir == nil {
return nil, err
}
defer func() { _ = dir.Close() }()
es, err := fs.ReadDir(dir.FS(), ".")
if err != nil {
return nil, err
}
var gone []string
for _, en := range es {
if !agents.MachineOwn(rel+"/"+en.Name()) || keep != nil && keep(en) {
continue
}
if take {
if err := dir.RemoveAll(en.Name()); err != nil {
return gone, err
}
}
gone = append(gone, en.Name())
}
return gone, nil
}
// seedTemp reports whether name, in sd's folder, is a temporary file that
// one of its entries is written through (state.WriteFileIn's), which a
// devvm agent import or save running at the same time renames into place.
func seedTemp(sd agents.Seed, name string) bool {
for _, e := range sd.Entries {
if strings.HasPrefix(name, "."+e+".tmp-") {
return true
}
}
return false
}
// updateAgentDirs says how an existing VM's agent folder mounts change to
// match the store's folders, which can appear or go after it's made, from
// in, its instance. Each start of a stopped VM mounts the store's
// (starter.start): a stopped VM's change as its launch starts it, a
// running one's at its next start (later), which bringUp offers to make
// now, with whatever else waits for it, in its one question
// (restartForNextStart).
func (e Launch) updateAgentDirs(st *state.VM, in backend.Instance) (later bool) {
vm := st.Name()
want := e.AgentMounts(tools.Names(st))
added := missing(want, in.AgentDirs)
removed := missing(in.AgentDirs, want)
if len(added) == 0 && len(removed) == 0 {
return false
}
if len(added) > 0 {
e.Warn(msg.AgentDirsAdded(shownList(added), vm))
}
if len(removed) > 0 {
e.Warn(msg.AgentDirsRemoved(shownList(removed), vm))
}
if in.Status == backend.StatusRunning {
return true
}
e.Info(msg.MountsUpdated(vm))
return false
}
func shownList(paths []string) string { return strings.Join(paths, ", ") }
// claudeSlugMax is how long a slug of Claude Code's is before it's cut.
const claudeSlugMax = 200
// claudeSlug is the name of the folder Claude Code keeps a project
// folder's sessions in, under ~/.claude/projects, from the folder's path,
// as Claude Code computes it: each UTF-16 unit of the path that isn't an
// ASCII letter or digit becomes a dash, and a name longer than 200 is cut
// there and ends with a dash and its path's hash (claudeHash) in base 36.
func claudeSlug(path string) string {
units := utf16.Encode([]rune(path))
b := make([]byte, len(units))
for i, u := range units {
switch {
case u >= 'a' && u <= 'z', u >= 'A' && u <= 'Z', u >= '0' && u <= '9':
b[i] = byte(u)
default:
b[i] = '-'
}
}
if len(b) <= claudeSlugMax {
return string(b)
}
h := int64(claudeHash(units))
if h < 0 {
h = -h
}
return string(b[:claudeSlugMax]) + "-" + strconv.FormatInt(h, 36)
}
// claudeHash is the hash Claude Code ends a long slug with: h*31 + u over
// the path's UTF-16 units, in 32 bits.
func claudeHash(units []uint16) int32 {
var h int32
for _, u := range units {
h = h*31 + int32(u)
}
return h
}
// missing returns what of a isn't in b.
func missing(a, b []string) []string {
var out []string
for _, s := range a {
if !slices.Contains(b, s) {
out = append(out, s)
}
}
return out
}