fix(agents): opencode 2 VMs get the store's changed logins and keys at each launch

opencode 2 keeps its logins in its database, so a VM whose database
existed kept the logins it had: a key saved from another VM, or a ChatGPT
login for another account, never reached it.

Every launch's setup now sends the store's opencode logins as opencode
auth import reads them (agentlogin.OpencodeImport: each API key the proxy
puts in and OpenAI's Codex login, placeholders alone, IDs
cred_devvm_<provider>; methodID chatgpt-browser and a whole-number
expires, as opencode 2.2.5's credential schema needs). The new guest
script assets/guest/opencode.sh reads them on its input, never argv, and,
once opencode has a database, imports them when they differ from its
record (~/.local/state/devvm/opencode-import.json) or when the database
no longer holds one of devvm's IDs (deleted, or replaced by a history
import; checked with opencode auth export, only the IDs kept). It logs
out of devvm's earlier entries (opencode auth import skips an ID it has),
imports each entry on its own and switches its provider to devvm's entry;
the user's own credentials stay in the database. devvm agent login
opencode --api-key runs the same script at once, in place of the old
one-key import. The record lives in the VM because only the VM knows its
database and what it holds.

No partial success: a provider whose import opencode refuses is printed
as devvm-opencode-failed PROVIDER, the script exits 1 and records
nothing, so the next launch tries again, and devvm agent login names the
providers in the new message opencode_import_failed.

Three faults found on real opencode 2.2.5 VMs and fixed: bash -lc runs
~/.bash_logout (Debian's clear_console, failing without a terminal),
which under set -e became the script's status after a good import, so
the work runs in a subshell; opencode 2.2.5 made its database without
importing auth.json while the script had recorded the entries anyway, so
nothing is recorded until the database exists; and a missing expires
becomes 0.

Every VM also sets OPENCODE_DISABLE_AUTOUPDATE=1, beside Claude Code's
DISABLE_AUTOUPDATER in base's /etc/profile.d/devvm-tools.sh: the agents
are read-only shared tools whose versions mise pins.

Tests: TestOpencodeImport; TestOpencodeScript (the script against a fake
opencode: no database, an import, the same input again, a database made
again, a refused entry); TestOpencodeRefused; TestToolsEnvironment;
agent_login.txtar (the script at a key's save, opencode-import.json in
the setup, a refused provider named through the guest stub's new
opencode-refuses switch). e2e's network section: OPENCODE_DISABLE_AUTOUPDATE in an
opencode VM's login shell; a second opencode VM with a database and a
credential of its own gets a key saved from the first at its next
launch, its own credential kept; and gets it again once its database is
deleted and made again. Failures print opencode.sh's stderr, the run
logs' opencode lines and the VM's credential IDs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
w3cjandClaude Opus 5.5 committed 2026-11-06 01:02:42 -07:00
1 parent 3f2d3658ed
commit b6b60d5cf3
20 files changed
+517 -64

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
package assets
import (
"io/fs"
"strings"
"testing"
)
// Every VM's shells get the tools' environment from base's
// /etc/profile.d/devvm-tools.sh, which turns off the agents'
// self-updates: their installs are read-only shared tools, and mise pins
// their versions.
func TestToolsEnvironment(t *testing.T) {
b, err := fs.ReadFile(FS, "layers/base.sh")
if err != nil {
t.Fatal(err)
}
_, rest, ok := strings.Cut(string(b), "/etc/profile.d/devvm-tools.sh >/dev/null <<'SH'\n")
block, _, closed := strings.Cut(rest, "\nSH\n")
if !ok || !closed {
t.Fatal("base.sh writes no /etc/profile.d/devvm-tools.sh")
}
for _, line := range []string{"export DISABLE_AUTOUPDATER=1", "export OPENCODE_DISABLE_AUTOUPDATE=1"} {
if !strings.Contains("\n"+block+"\n", "\n"+line+"\n") {
t.Errorf("devvm-tools.sh lacks %q", line)
}
}
}
+57
View File
@@ -0,0 +1,57 @@
#!/bin/bash
# Brings opencode 2's logins in this VM in line with devvm's store, run in a login shell (opencode on
# PATH) by sync.sh on every launch and by devvm agent login --api-key. Its input is the store's
# opencode logins as opencode auth export prints them, with placeholders alone, under devvm's IDs
# (cred_devvm_PROVIDER). opencode 2 keeps its logins in its database, so once it has made one, an
# input that differs from the last this VM's database got, or one whose IDs the database no longer
# holds, is imported: devvm's entries of the last
# are logged out first, then each new one is imported on its own and made its provider's active
# credential, and the user's own credentials stay in the database. Until opencode has made its
# database there is nothing to import into, and nothing is recorded, so the first launch after it
# imports them all. Each provider whose import fails is printed as a line "devvm-opencode-failed
# PROVIDER", and then the script exits non-zero, recording nothing, so the next launch tries again;
# any other failure prints the command that failed to stderr.
#
# It runs in a login shell, whose ~/.bash_logout (Debian's clear_console, which fails without a
# terminal) would end it with its own status under set -e, so the work runs in a subshell and the
# shell itself exits with the subshell's status.
(
set -euo pipefail
trap 'echo "opencode.sh: line $LINENO: $BASH_COMMAND failed" >&2' ERR
new=$(cat)
last=~/.local/state/devvm/opencode-import.json
command -v opencode >/dev/null || exit 0
set -- ~/.local/share/opencode/opencode*.db
[[ -e $1 ]] || exit 0
# The record alone isn't enough: a database made again (deleted, or replaced by a history import)
# no longer holds devvm's entries, so every ID of the input must still be there. Only the IDs leave
# opencode auth export's output.
have=$(opencode auth export </dev/null 2>/dev/null | jq -r '.[].id' 2>/dev/null) || have=
missing=0
while read -r id; do
grep -qxF -- "$id" <<<"$have" || missing=1
done < <(jq -r '.[].id' <<<"$new")
[[ "$new" != "$(cat "$last" 2>/dev/null)" || $missing == 1 ]] || exit 0
if [[ -f $last ]]; then
{ jq -r '.[] | "\(.integrationID) \(.id)"' "$last" 2>/dev/null || true; } | while read -r provider id; do
opencode auth logout "$provider" "$id" </dev/null >/dev/null 2>&1 || true
done
fi
# One entry at a time, so a refused one names its provider and the others still go in. The store's
# login is the one made last, so each provider then uses devvm's entry, as every VM does.
failed=0
while read -r entry; do
provider=$(jq -r .integrationID <<<"$entry")
if ! opencode auth import <<<"[$entry]" >&2; then
echo "devvm-opencode-failed $provider"
failed=1
continue
fi
opencode auth switch "$provider" "$(jq -r .id <<<"$entry")" </dev/null >/dev/null 2>&1 || true
done < <(jq -c '.[]' <<<"$new")
[[ $failed == 0 ]] || exit 1
mkdir -p "${last%/*}"
printf '%s\n' "$new" > "$last.devvm"
mv -f "$last.devvm" "$last"
)
exit $?
+9
View File
@@ -17,6 +17,8 @@
# and DEVVM_LOCAL_PROXY (ADDRESS:PORT on the VM's loopback, where devvm-local-proxy
# listens; empty without a proxy)
# tools the VM's shared tool images, "FILE TOOL VERSION" lines; tools.sh mounts them
# opencode-import.json the store's opencode logins as opencode auth import reads them, with
# placeholders (none: no opencode login in the store); opencode.sh imports them
# hosts the VM's links (devvm checked them): a line per target, "ADDRESS NAME
# NAME.devvm.internal...", for /etc/hosts
# guide.md devvm's guide for the agents in the VM, installed as /usr/share/doc/devvm/README.md
@@ -210,6 +212,13 @@ if command -v codex >/dev/null; then
mv ~/.codex/config.toml.devvm ~/.codex/config.toml
fi
# opencode 2's database gets the store's opencode logins that changed (opencode.sh); none in the store
# is an empty list, so devvm's entries go. A failed import is tried again at the next launch.
oc_import=$s/opencode-import.json
[[ -f $oc_import ]] || echo '[]' > "$oc_import"
bash -l "$s/opencode.sh" < "$oc_import" >/dev/null ||
echo "devvm: opencode in this VM didn't get the logins devvm keeps for it; the next launch tries again" >&2
# The VM's proxy (DEVVM_PROXY set): Lima's env: already puts the proxy variables in /etc/environment;
# point the tools that ignore them at the proxy too. When the guest has none, undo all of it.
proxy_block() { # proxy_block FILE [CONTENT]: replace (or remove) devvm's block in FILE
+3 -1
View File
@@ -82,13 +82,15 @@ rm /tmp/mise
# Every shell finds the tools: login shells through profile.d, interactive ones through mise activate
# (it follows `cd` into projects with other versions), and the rest (`bash -c` from agents, editors
# over SSH) through BASH_ENV and mise's shims. Read-only installs can't take global packages or update
# themselves: npm installs globals into ~/.npm-global, and Claude Code's auto-update is off.
# themselves: npm installs globals into ~/.npm-global, and Claude Code's and opencode's auto-updates
# are off.
sudo tee /etc/profile.d/devvm-tools.sh >/dev/null <<'SH'
case ":$PATH:" in *":$HOME/.local/share/mise/shims:"*) ;; *)
export PATH="$HOME/.npm-global/bin:$HOME/go/bin:$HOME/.cargo/bin:$HOME/.local/bin:$HOME/.local/share/mise/shims:$PATH" ;;
esac
export NPM_CONFIG_PREFIX="$HOME/.npm-global"
export DISABLE_AUTOUPDATER=1
export OPENCODE_DISABLE_AUTOUPDATE=1
SH
grep -qs devvm-tools /etc/environment || echo 'BASH_ENV=/etc/profile.d/devvm-tools.sh' | sudo tee -a /etc/environment >/dev/null
echo 'eval "$(mise activate bash)"' > ~/.bashrc.d/mise.sh
+112
View File
@@ -0,0 +1,112 @@
package assets
import (
"bytes"
"errors"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// fakeOpencode stands in for opencode 2 in guest/opencode.sh's test: its
// credentials are $HOME/creds.json, auth export prints them, auth import
// adds the entries whose IDs it lacks (refusing one for the provider
// "refused"), auth logout removes one, and each call is logged to
// $HOME/calls.
const fakeOpencode = `#!/bin/bash
set -eu
c=$HOME/creds.json
[ -f "$c" ] || echo '[]' > "$c"
echo "$*" >> "$HOME/calls"
case "$1 $2" in
"auth export") cat "$c" ;;
"auth import")
in=$(cat)
if jq -e 'any(.[]; .integrationID == "refused")' <<<"$in" >/dev/null; then echo "Missing key" >&2; exit 1; fi
jq --argjson in "$in" '. as $have | . + [$in[] | select(.id as $i | all($have[]; .id != $i))]' "$c" > "$c.new" && mv "$c.new" "$c" ;;
"auth logout")
jq --arg id "$4" '[.[] | select(.id != $id)]' "$c" > "$c.new" && mv "$c.new" "$c" ;;
"auth switch") ;;
*) exit 1 ;;
esac
`
// opencode.sh imports devvm's entries once opencode has a database, and
// again whenever the input changed or the database lost one of devvm's
// IDs (made again, or replaced); with no database it records nothing; a
// refused entry names its provider, fails, and records nothing.
func TestOpencodeScript(t *testing.T) {
for _, c := range []string{"bash", "jq"} {
if _, err := exec.LookPath(c); err != nil {
t.Skipf("no %s: %v", c, err)
}
}
script, err := fs.ReadFile(FS, "guest/opencode.sh")
if err != nil {
t.Fatal(err)
}
home := t.TempDir()
bin := filepath.Join(home, "bin")
must(t, os.MkdirAll(bin, 0o700))
must(t, os.WriteFile(filepath.Join(bin, "opencode"), []byte(fakeOpencode), 0o700)) //nolint:gosec // the fake runs: its owner's alone
db := filepath.Join(home, ".local", "share", "opencode", "opencode.db")
const record = ".local/state/devvm/opencode-import.json"
files := os.DirFS(home)
read := func(name string) string { b, _ := fs.ReadFile(files, name); return string(b) }
exists := func(name string) bool { _, err := fs.Stat(files, name); return err == nil }
run := func(input string) (string, int) {
cmd := exec.CommandContext(t.Context(), "bash", "-c", string(script), "opencode.sh") //nolint:gosec // devvm's own embedded script
cmd.Env = []string{"HOME=" + home, "PATH=" + bin + ":" + os.Getenv("PATH")}
cmd.Stdin = strings.NewReader(input)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
code := 0
var e *exec.ExitError
if errors.As(err, &e) {
code = e.ExitCode()
} else if err != nil {
t.Fatal(err)
}
return out.String(), code
}
imports := func() int { return strings.Count(read("calls"), "auth import") }
creds := func() string { return read("creds.json") }
in := `[{"active":true,"id":"cred_devvm_openrouter","integrationID":"openrouter","label":"devvm","value":{"key":"PH","type":"key"}}]`
if _, code := run(in); code != 0 || imports() != 0 || exists(record) {
t.Fatalf("no database: code %d, %d imports, record %v", code, imports(), exists(record))
}
must(t, os.MkdirAll(filepath.Dir(db), 0o700))
must(t, os.WriteFile(db, nil, 0o600))
if _, code := run(in); code != 0 || imports() != 1 || !strings.Contains(creds(), "cred_devvm_openrouter") || !exists(record) {
t.Fatalf("a database: code %d, %d imports, creds %s", code, imports(), creds())
}
if _, code := run(in); code != 0 || imports() != 1 {
t.Fatalf("the same input again: code %d, %d imports", code, imports())
}
// The database made again: devvm's entry is gone, so it's imported again.
must(t, os.Remove(filepath.Join(home, "creds.json")))
if _, code := run(in); code != 0 || imports() != 2 || !strings.Contains(creds(), "cred_devvm_openrouter") {
t.Fatalf("a new database: code %d, %d imports, creds %s", code, imports(), creds())
}
refused := `[{"active":true,"id":"cred_devvm_refused","integrationID":"refused","label":"devvm","value":{"key":"PH","type":"key"}}]`
before := read(record)
if out, code := run(refused); code != 1 || out != "devvm-opencode-failed refused\n" {
t.Fatalf("a refused entry: code %d, output %q", code, out)
}
if read(record) != before {
t.Error("a refused entry changed the record")
}
}
func must(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
+1 -1
View File
@@ -382,7 +382,7 @@ The sections so far:
- `project`: devvm in a new project folder (under `/tmp/devvm-go-e2e/p`) makes a VM from base and opens a shell there, which reads its commands from devvm's input. The folder and the shared tools are mounted and nothing else is, there's no SSH agent, no Docker (no docker layer) and the hostname is the folder's. The ssh config lists it as `devvm-web` with its host keys pinned; through an `~/.ssh/config` of the run's own that includes it under a `Host *` forwarding the agent, `ssh devvm-web` works, forwards no agent (a throwaway one), and refuses a changed host key. `.git` is locked (macOS) and git in the VM can still commit. `devvm stop` stops it and drops its entry, and on macOS reports and locks a submodule git folder the VM added. `TestE2EExecQuoting` in `internal/backend/registry`, which runs only there (`DEVVM_E2E_VM` names the VM), checks that arguments with spaces, quotes, `$`, newlines and globs, a folder and input reach the guest as given, through the `Exec` of the backend the VM's state records, so one test covers every backend. Then a VM from a `devcontainer.json`, with no ports by default: its `forwardPorts` said and not forwarded, none reaching this machine, its `containerEnv` in the shell and its commands, its `postCreateCommand` run once in the folder, its `postStartCommand` at each start (again after `devvm restart`), nothing written to the folder, and a changed file warned about without changing the VM. Then a claude VM with a fake agent config, history, git identity and token in a home of its own: `devvm agent import` copies the agent's settings into the sandbox's agent store without the history or the links out of its folder, the store's folder is mounted read-only and linked into the VM's home, and the home folder's isn't mounted, its settings are copied and its history isn't, the VM gets the git identity, the timezone and its hostname, and, open as it is, the token's placeholder and never the token. `devvm agent save` without a terminal shows the VM's changed `settings.json` as a diff and its new `commands` folder's file, then refuses and saves nothing, and after a yes it saves both into the store, but neither the VM's fake login beside them nor the folder's link out of it. Then SSH agents, with a home of their own and throwaway keys: a `--ssh-agent` VM uses a throwaway agent standing for yours; after `devvm ssh-agent add` and `devvm ssh-agent devvm` it keeps yours, in its shell and by name, until a restart, then uses only devvm's own agent's key, in its shells and by name; after `devvm ssh-agent off`, none.
- `gc`: a VM from a folder named `img-keep`, which is named like an image, and a fixture layer edited after its build: `devvm gc` deletes the stale image and its record and an old tool image no VM lists (once there's a tools lock), and keeps base and the VM.
- `tools`: first, the shared tools resolve to upstream's newest versions, with devvm's pinned mise (downloaded once), each download with its checksum. This section is the only one that uses the newest versions, and no other step checks for them (`DEVVM_NO_TOOL_CHECK`). At the section's end, e2e puts the pinned lock back. Then a node project's VM: node, npm, pnpm, bun and yarn at the locked versions, each a read-only EROFS image, the share read-only even for root, `npm i -g` into the VM's home, a non-login shell over SSH, an `.nvmrc`'s own version, the tools mounted at boot without devvm, and a second node VM that builds nothing.
- `network`: a VM with Claude Code, Codex and opencode and `--network allowlist`, a fake token in devvm's environment and a fake `~/.claude.json` and Codex login in a home of its own, which `devvm agent import` copies into the sandbox's agent store, only yours to read. Its proxy runs and the self-check passed; its password was in no host process's arguments while devvm launched it (`ps`, sampled), and the guest has it; `ssh devvm-net` reaches it; direct connections fail, even as root, to an address and to other ports; an allowed host works and others, or other ports, are blocked; a line in the VM's policy file that reads as a deny but isn't a rule makes the running proxy refuse an allowed host, with no allow command in `devvm network log --blocked`, `devvm network rm` warns of it, and the host works again once it's gone; DNS fails at once; the host's loopback services are out of reach, directly or through the proxy; the proxy refuses requests without the VM's password; the token is nowhere in the VM, which has its own CA and the next one, its own placeholder and logins' copies with placeholders only; the proxy puts the token in for its host (for the VM's own placeholder only), an MCP server's header and Codex's key for theirs, over TLS the VM verifies; a second allowlist VM has CAs of its own, each VM trusts only its own and has no key, each proxy serves and presents only its own VM's CAs, and `devvm rm` deletes one VM's CAs and leaves the other's; the home folder's and the store's login files are unchanged. `devvm agent save` saves the VM's changed `~/.claude.json` with the store's MCP header in place of its placeholder, and once the VM changes that server's URL it leaves the file out, so the store keeps the server as it was. `devvm secret set github --stdin` saves a fake token (in the Keychain on macOS, under the run's service, found through a link to `~/Library/Keychains` in the VM's home), read from a file so it's in no process's arguments, and `devvm secret` lists it saved, while asking `devvm secret` for a `get` subcommand is refused without printing it; `secret use github` binds it to the running proxy at once, and on the next launch the VM has its own placeholder in `GH_TOKEN`, never the token, which the proxy puts in for `api.github.com`; `secret unuse` and `rm` take the binding and the token away. `TestE2ESelfCheck` in `internal/netpolicy` runs the self-check on the VM: it passes, then, once the VM is started outside devvm, it fails and stops the VM. `devvm stop` stops the VM and its proxy at once. `devvm network open` makes its next start direct, its proxy set in the guest and answering, and the open VM holds no real secret either: the token is nowhere in it, its environment and Codex's login hold only its placeholders, its proxy puts the token in over TLS the VM verifies with its own CA, and a request that goes around the proxy carries only the placeholder and gets a 401 from the token's host. Then `devvm network internet` and `devvm network none` change its tier at once, the VM running on. Restarted behind the run's company proxy on this machine's loopback, named in the shell's `HTTPS_PROXY` with a fake password that the check reads from a file, the guest has the proxy and reaches GitHub through it, while devvm's run logs hold the password only as `<password>` and Lima's `ha.stderr.log` only as stars. `devvm network allowlist` while it runs open shows it `unenforced` until `devvm restart` starts it confined; `devvm network open` while it runs confined keeps it on its proxy until it next starts. Behind a company proxy of the run's own that fakes OpenAI's token endpoint with a certificate from the run's CA, a login made in the VM is captured: the store gets the fake tokens and API key, and the VM gets placeholders. Then `devvm agent login codex` runs the real Codex's login in the VM, curl on this machine opens its callback with the state Codex's address names, through the forward of `localhost:1455`, devvm names the account the store saved, the VM's Codex holds only placeholders, and the forward is gone once the login ends, and gone too after an interrupted login. `devvm agent login opencode --device-code` runs the real opencode 2's Codex device code login in the VM, which the fake endpoint answers too, devvm says the store saved the login, and `opencode auth export` in the VM shows only placeholders. The same company proxy fakes Claude's token endpoint and Anthropic's API, which logs the token each request brings: `claude setup-token`'s request, as curl, makes the fake token the `claude` secret and gives the VM its placeholder, and the API gets the token for it. Then `devvm agent login claude` runs the real Claude Code's `claude auth login` in the VM, its code pasted on devvm's input with the state its address names, the store keeps the fake login and the `claude` secret is gone, the VM's `~/.claude/.credentials.json` holds only placeholders and its environment no token, and once the store's acLine truncated
- `network`: a VM with Claude Code, Codex and opencode and `--network allowlist`, a fake token in devvm's environment and a fake `~/.claude.json` and Codex login in a home of its own, which `devvm agent import` copies into the sandbox's agent store, only yours to read. Its proxy runs and the self-check passed; its password was in no host process's arguments while devvm launched it (`ps`, sampled), and the guest has it; `ssh devvm-net` reaches it; direct connections fail, even as root, to an address and to other ports; an allowed host works and others, or other ports, are blocked; a line in the VM's policy file that reads as a deny but isn't a rule makes the running proxy refuse an allowed host, with no allow command in `devvm network log --blocked`, `devvm network rm` warns of it, and the host works again once it's gone; DNS fails at once; the host's loopback services are out of reach, directly or through the proxy; the proxy refuses requests without the VM's password; the token is nowhere in the VM, which has its own CA and the next one, its own placeholder and logins' copies with placeholders only; the proxy puts the token in for its host (for the VM's own placeholder only), an MCP server's header and Codex's key for theirs, over TLS the VM verifies; a second allowlist VM has CAs of its own, each VM trusts only its own and has no key, each proxy serves and presents only its own VM's CAs, and `devvm rm` deletes one VM's CAs and leaves the other's; the home folder's and the store's login files are unchanged. `devvm agent save` saves the VM's changed `~/.claude.json` with the store's MCP header in place of its placeholder, and once the VM changes that server's URL it leaves the file out, so the store keeps the server as it was. `devvm secret set github --stdin` saves a fake token (in the Keychain on macOS, under the run's service, found through a link to `~/Library/Keychains` in the VM's home), read from a file so it's in no process's arguments, and `devvm secret` lists it saved, while asking `devvm secret` for a `get` subcommand is refused without printing it; `secret use github` binds it to the running proxy at once, and on the next launch the VM has its own placeholder in `GH_TOKEN`, never the token, which the proxy puts in for `api.github.com`; `secret unuse` and `rm` take the binding and the token away. `TestE2ESelfCheck` in `internal/netpolicy` runs the self-check on the VM: it passes, then, once the VM is started outside devvm, it fails and stops the VM. `devvm stop` stops the VM and its proxy at once. `devvm network open` makes its next start direct, its proxy set in the guest and answering, and the open VM holds no real secret either: the token is nowhere in it, its environment and Codex's login hold only its placeholders, its proxy puts the token in over TLS the VM verifies with its own CA, and a request that goes around the proxy carries only the placeholder and gets a 401 from the token's host. Then `devvm network internet` and `devvm network none` change its tier at once, the VM running on. Restarted behind the run's company proxy on this machine's loopback, named in the shell's `HTTPS_PROXY` with a fake password that the check reads from a file, the guest has the proxy and reaches GitHub through it, while devvm's run logs hold the password only as `<password>` and Lima's `ha.stderr.log` only as stars. `devvm network allowlist` while it runs open shows it `unenforced` until `devvm restart` starts it confined; `devvm network open` while it runs confined keeps it on its proxy until it next starts. Behind a company proxy of the run's own that fakes OpenAI's token endpoint with a certificate from the run's CA, a login made in the VM is captured: the store gets the fake tokens and API key, and the VM gets placeholders. Then `devvm agent login codex` runs the real Codex's login in the VM, curl on this machine opens its callback with the state Codex's address names, through the forward of `localhost:1455`, devvm names the account the store saved, the VM's Codex holds only placeholders, and the forward is gone once the login ends, and gone too after an interrupted login. `devvm agent login opencode --device-code` runs the real opencode 2's Codex device code login in the VM, which the fake endpoint answers too, devvm says the store saved the login, and `opencode auth export` in the VM shows only placeholders. A second VM with opencode has `OPENCODE_DISABLE_AUTOUPDATE=1` in its login shell, makes its database and imports a credential of its own, then `devvm agent login opencode --api-key --provider openrouter --stdin` saves a fake key from the first VM, and at the second VM's next launch its opencode has devvm's entry with the key's placeholder, never the key, beside its own credential, and once its database is deleted and made again, the next launch gives it the key's placeholder again. The same company proxy fakes Claude's token endpoint and Anthropic's API, which logs the token each request brings: `cLine truncated
- `nix`: the nix layer. A copy of `assets/layers/nix.sh` as a layer of the run's own, built behind a company proxy of the run's own, reaches Nix's releases through it and leaves no proxy settings for `nix-daemon` (and not the company proxy's password) anywhere on its image's disk. Then a folder with `package.json`, `flake.nix` and `.envrc` gets a VM with node on the nix layer (`--layers nix`) on the allowlist tier: Nix and direnv at their pins, a store that's root's, `sandbox` on with no fallback, `trusted-users` root alone and an untrusted user's `--option substituters` ignored, `nix-daemon` with the VM's own proxy in devvm's drop-in alone, `nix run nixpkgs#hello` from Nix's cache, a build in Nix's sandbox, `sudo nix` and `nix` over ssh, the flake's dev shell (nixpkgs at a pinned revision) loaded by direnv in an interactive shell, its `node` ahead of the shared node prompt after prompt and gone outside the folder, nix-direnv's cache in the VM's home with no `.direnv` in the folder, a fixed-output download from a host that isn't allowed refused with `403` and named by `devvm-why`, and after `devvm network open` and `devvm restart`, no drop-in and no proxy for the daemon.
- `from`: run with a `docker` that isn't running, so nothing comes from Docker. Its container images go by their pinned digests, as `node:24@sha256:…`, so devvm looks them up nowhere, except the company proxy's `alpine:3.21`, which keeps its tag so that devvm's registry lookup is checked too. A VM from `node:24` with node, python and Claude Code on the docker and nix layers (Debian 12, in a home of its own) boots, with its base keyed by the pinned digest, its node, python and claude at the locked versions, GNU `tar` as its commands find it, its tool images built in a clone of devvm's own Ubuntu base when the run builds them, the docker layer's Docker from Docker's Debian repository, and the nix layer's Nix under systemd running `nix run nixpkgs#hello` and a build in Nix's sandbox; a VM from `alpine:3` with node on the docker, nix and desktop layers runs node and pnpm from musl tool images, built in its own base and keyed and recorded by its digest, the docker layer's Docker on OpenRC, the desktop layer's programs from Alpine's packages, with no crashed services, and the nix layer's Nix as an OpenRC service, with `nix run nixpkgs#hello` and a sandboxed build, then after `devvm network allowlist` and `devvm restart` a download only its daemon makes from a host that isn't allowed refused with the proxy's `403`, and with GNU `tar` as its commands find it, `devvm history import` puts an export into it, while an export with a path outside the agents' history imports nothing there; base builds from `ubuntu:26.04`; and the build VM and its temporary folders are gone.
+1 -1
View File
@@ -220,7 +220,7 @@ Codex's login is `~/.local/share/devvm/logins/codex/.codex/auth.json` and openco
- For Codex, those are OpenAI's hosts, `api.openai.com`, and `chatgpt.com` for a ChatGPT login.
- For opencode, they're the hosts of Anthropic, OpenAI and OpenRouter keys, and of OpenAI and GitHub Copilot logins, but not Copilot Enterprise.
The store keeps opencode's login in the `auth.json` format of opencode 1: one entry per provider, `{"type":"api","key"}` or `{"type":"oauth","access","refresh","expires"}` with its expiry in milliseconds. opencode 2 keeps its logins in the `credential` table of its SQLite database, `~/.local/share/opencode/opencode.db`, and imports `auth.json` into it once, in the migration that makes the table, so a VM's opencode gets the VM's copy when it first runs there. A VM's placeholders don't change when the host refreshes a login, so the database's copies keep working. An API key that `devvm agent login opencode --api-key --provider PROVIDER` saves after that reaches the database through `opencode auth import`, as an `auth export` entry with the ID `cred_devvm_<provider>` and the key's placeholder (`agentlogin.OpencodeKeyImport`), which opencode skips when it has that ID already.
The store keeps opencode's login in the `auth.json` format of opencode 1: one entry per provider, `{"type":"api","key"}` or `{"type":"oauth","access","refresh","expires"}` with its expiry in milliseconds. opencode 2 keeps its logins in the `credential` table of its SQLite database, `~/.local/share/opencode/opencode.db`, and imports `auth.json` into it once, in the migration that makes the table, so a VM's opencode gets the VM's copy when it first runs there. A VM's placeholders don't change when the host refreshes a login, so the database's copies keep working. After that, the store's opencode logins reach the database through `opencode auth import`, as `auth export` entries with the IDs `cred_devvm_<provider>` and the logins' placeholders (`agentlogin.OpencodeImport`): each API key that the proxy puts in, and the OpenAI login from one of opencode's Codex logins. The VM's setup sends these entries on every launch, and `devvm agent login opencode --api-key --provider PROVIDER` sends them at once, both on the input of devvm's guest script `opencode.sh`, never in a command's arguments. The script keeps the last entries it got in `~/.local/state/devvm/opencode-import.json` in the VM. When opencode has made its database and the new entries differ from the record, or the database no longer holds one of their IDs because it was made again, such as after you delete it or a history import replaces it, it logs out of devvm's entries from the last ones with `opencode auth logout`, because `opencode auth import` skips an ID it already has, and then imports the new ones and makes each of them its provider's active credential with `opencode auth switch`, so a ChatGPT login for another account or a key saved from another VM reaches every VM at its next launch. Credentials that you added in the VM yourself have other IDs, so they stay in the database, and `opencode auth switch` makes one of them active again. Before opencode has made its database, the script does nothing and records nothing, because opencode 2.2.5 doesn't always import `auth.json` as it makes the database, so the first launch after opencode has run imports every entry. The script imports each entry on its own, so an entry that opencode refuses doesn't keep the others out, and `devvm agent login` names the providers that opencode refused. A failed import leaves the record as it was, so the next launch tries again. The script and its record live in the VM rather than in the VM's state on the host, because only the VM knows whether its database exists and what it last imported, and a VM that is set up again or has its home copied keeps both together.
Each VM's placeholders end in its own random value, so no other VM's placeholder gets its secrets. devvm reads a login file only when it's a regular file, so a FIFO or a device in its place can't hold devvm. devvm refreshes OAuth logins on the host, one lookup at a time, and writes them back to the store's file, so a VM never holds a refresh token. A refresh that has started finishes and is written back even when the request that needed it ends, because OpenAI may already have replaced the refresh token. When a refresh fails, or the store's login no longer has what a binding names, the proxy puts nothing in, and its own log says to log in again with the agent and import the login again (`codex_refresh_failed`, `opencode_refresh_failed`, `codex_no_key`, `codex_no_chatgpt`), or names the login file it couldn't read (`login_read_failed`). devvm copies logins it doesn't know as they are, and warns you (`codex_login_kept`, `opencode_login_kept`). An opencode OAuth login that devvm doesn't bind, such as Copilot Enterprise's or one for a provider devvm doesn't know, is the exception: its access and refresh tokens become `devvm-redacted` in the VM's copy, so opencode in the VM can't use that login, and devvm warns you (`opencode_login_withheld`). If devvm can't make the VM's copy of a login, it stops the VM's setup (`login_copy_failed`).
+3 -3
View File
@@ -38,7 +38,7 @@ In the VM, you run the agent as `claude`, `codex` or `opencode`.
| `codex` | Codex | the newest release, with its analytics and metrics off unless your config sets them | the OpenAI API and the ChatGPT login: `api.openai.com`, `chatgpt.com` and `auth.openai.com` |
| `opencode` | opencode | the newest 2.x release, because opencode marks its 1.x releases as its latest on GitHub | opencode's own service and its model catalog: `opencode.ai` and `models.opencode.ai` |
Claude Code's telemetry hosts aren't on its allowlist, because blocking them costs nothing. opencode talks to the model provider you choose, so on the allowlist tier you allow that provider's API host yourself, such as `devvm network allow api.anthropic.com` ([changing rules](../safety/network.md#changing-rules)).
Claude Code's telemetry hosts aren't on its allowlist, because blocking them costs nothing. opencode talks to the model provider you choose, so on the allowlist tier you allow that provider's API host yourself, such as `devvm network allow api.anthropic.com` ([changing rules](../safety/network.md#changing-rules)). Every VM sets `OPENCODE_DISABLE_AUTOUPDATE=1`, as it sets `DISABLE_AUTOUPDATER=1` for Claude Code, because the agents are read-only shared tools that can't update themselves, and devvm keeps their versions.
Agents are [shared tools](images.md#shared-tools), like the toolchains, so you can combine them with any layers and with each other, as in `devvm --tools node --agents claude,codex`. devvm follows each agent's newest release, because agents release several times a week, and `devvm update` or `devvm tools update` moves a VM to newer versions ([adding and removing tools](toolchains.md#adding-and-removing-tools)).
@@ -175,13 +175,13 @@ With `--device-code`, the agent shows a code instead, which you type into a brow
When the agent logs in, the VM's proxy saves the login in the store, and the agent in the VM gets placeholders, as [the next section](#logins-made-in-a-vm) describes. devvm then says what the store saved and the account's email, and the VM uses the login at once. When the login ends without a new login in the store, for example because you chose another way to log in, devvm says so and fails, and `devvm network log` shows each login the proxy saved. Codex in a VM keeps its login in `~/.codex/auth.json`, never in a keyring, because devvm sets `cli_auth_credentials_store = "file"` in the VM's `~/.codex/config.toml` on every launch.
With `--api-key`, devvm asks for the API key without showing it, or reads it from a line of input with `--stdin`, and saves it in the store itself, so the key never goes into the VM. Codex's key is an OpenAI key, and it replaces Codex's ChatGPT login in the store, as `codex login --with-api-key` does. opencode's key is for the provider that `--provider` names, `anthropic`, `openai` or `openrouter`, the providers whose keys the proxy puts in, and the store keeps opencode's other providers beside it. devvm then gives the running VM its copy of the login, with a placeholder in place of the key, and the VM's proxy puts the key in at once. opencode keeps its logins in its own database in the VM, and it reads its `auth.json` only when it first makes that database, so when opencode has already run in the VM, devvm also gives it the key's placeholder with `opencode auth import`.
With `--api-key`, devvm asks for the API key without showing it, or reads it from a line of input with `--stdin`, and saves it in the store itself, so the key never goes into the VM. Codex's key is an OpenAI key, and it replaces Codex's ChatGPT login in the store, as `codex login --with-api-key` does. opencode's key is for the provider that `--provider` names, `anthropic`, `openai` or `openrouter`, the providers whose keys the proxy puts in, and the store keeps opencode's other providers beside it. devvm then gives the running VM its copy of the login, with a placeholder in place of the key, and the VM's proxy puts the key in at once. opencode keeps its logins in its own database in the VM, and it reads its `auth.json` only when it first makes that database, so when opencode has already run in the VM, devvm also gives it the key's placeholder with `opencode auth import`. Every other VM with opencode gets the key's placeholder at its next launch, the same way, and any credentials that you added to opencode in a VM yourself stay in its database.
opencode's Anthropic login is an API key, because opencode itself has no other way to log in to Anthropic. opencode's Claude Agent provider uses Claude Code's own login instead, so it works in a VM that has Claude Code too, with the login that `devvm agent login claude` saves.
#### Logins made in a VM
When Codex or opencode in a VM logs in to OpenAI, whether `devvm agent login` runs it or you run it yourself, the VM's proxy saves the login in devvm's store, in the agent's own `auth.json`, and the agent in the VM gets only placeholders, so the VM never holds the login's tokens. The VM you logged in from uses the login at once, and every VM with that agent gets it from its next launch. opencode is the exception, because it reads its `auth.json` only when it first makes its database: a VM where opencode has already run keeps the logins it has, so log in there with `devvm agent login opencode` too. A login that shows a code to type into a browser on any machine works in a VM as it is, such as `codex login --device-auth` and opencode's Codex device code login. opencode's Sign in with ChatGPT doesn't work in a VM, because it gets its tokens from another endpoint, whose replies the VM's proxy refuses so that they never reach the VM, so choose one of opencode's Codex logins instead, as `devvm agent login opencode` does. A new login replaces the one in the store, together with Codex's API key, so every VM with the agent uses the account you logged in to last. In a VM with both Codex and opencode, devvm tells their logins apart by the program that sends them. `devvm network log` shows a `login` line for each login it saved. On the open tier, a program that goes around the VM's proxy gets the login's tokens itself, and devvm saves nothing ([logins made in a VM](../internals/network.md#logins-made-in-a-vm)). Claude Code's logins in a VM are saved in the same way ([Claude Code login](#claude-code-login)).
When Codex or opencode in a VM logs in to OpenAI, whether `devvm agent login` runs it or you run it yourself, the VM's proxy saves the login in devvm's store, in the agent's own `auth.json`, and the agent in the VM gets only placeholders, so the VM never holds the login's tokens. The VM you logged in from uses the login at once, and every VM with that agent gets it from its next launch. opencode reads its `auth.json` only when it first makes its database, so in a VM where opencode has already run, devvm adds the store's logins to opencode's database at each launch when they changed since the VM last got them, and makes them the ones opencode uses. Credentials that you added to opencode in the VM yourself stay in its database, labeled with your names rather than devvm, and `opencode auth switch` changes back to one of them. A login that shows a code to type into a browser on any machine works in a VM as it is, such as `codex login --device-auth` and opencode's Codex device code login. opencode's Sign in with ChatGPT doesn't work in a VM, because it gets its tokens from another endpoint, whose replies the VM's proxy refuses so that they never reach the VM, so choose one of opencode's Codex logins instead, as `devvm agent login opencode` does. A new login replaces the one in the store, together with Codex's API key, so every VM with the agent uses the account you logged in to last. In a VM with both Codex and opencode, devvm tells their logins apart by the program that sends them. `devvm network log` shows a `login` line for each login it saved. On the open tier, a program that goes around the VM's proxy gets the login's tokens itself, and devvm saves nothing ([logins made in a VM](../internals/network.md#logins-made-in-a-vm)). Claude Code's logins in a VM are saved in the same way ([Claude Code login](#claude-code-login)).
## History
+40 -12
View File
@@ -1,6 +1,7 @@
package agentlogin
import (
"bytes"
"cmp"
"encoding/json"
"errors"
@@ -23,19 +24,46 @@ func KeyProviders(kind string) []string {
// errKeyProvider: an API key for a provider devvm doesn't put in.
var errKeyProvider = errors.New("no API key devvm puts in for that provider")
// OpencodeKeyImport is what opencode's auth import reads to add provider's API key, of
// KeyProviders, to a VM whose opencode has made its database: opencode 2 keeps its logins there
// and reads auth.json only as it makes it. It's the key's credential as opencode's auth export
// prints it, the key's placeholder ending in salt, under an ID of devvm's, which opencode skips
// when it has it, so a second import adds nothing.
func OpencodeKeyImport(provider, salt string) ([]byte, error) {
if !slices.Contains(KeyProviders(Opencode), provider) {
return nil, errKeyProvider
// OpencodeImport is what opencode's auth import reads to give a VM whose opencode has made its
// database the logins of vmCopy, the VM's copy of the store's opencode login (File.VMCopy, which
// holds placeholders alone): opencode 2 keeps its logins there and reads auth.json only as it
// makes it. It's each API key devvm puts in (KeyProviders) and OpenAI's Codex login as opencode's
// auth export prints them, sorted by provider, under IDs of devvm's (cred_devvm_<provider>), which
// the VM's setup logs out of before it imports a new set, so the user's own credentials stay.
func OpencodeImport(vmCopy []byte) ([]byte, error) {
d := json.NewDecoder(bytes.NewReader(vmCopy))
d.UseNumber()
var m map[string]any
if err := d.Decode(&m); err != nil {
return nil, err
}
return json.Marshal([]map[string]any{{
"id": "cred_devvm_" + provider, "integrationID": provider, "label": "devvm", "active": true,
"value": map[string]any{"type": "key", "key": opencodePlaceholder(provider, salt)},
}})
out := []map[string]any{}
for _, id := range slices.Sorted(maps.Keys(m)) {
e := obj(m, id)
var v map[string]any
switch {
case str(e, "type") == "api" && slices.Contains(KeyProviders(Opencode), id) && str(e, "key") != "":
v = map[string]any{"type": "key", "key": str(e, "key")}
case str(e, "type") == "oauth" && id == "openai" && str(e, "access") != "":
// opencode 2 (checked at v2.2.5) needs a method, Codex's in a browser, whose tokens
// come from the endpoint the store refreshes at, and a whole number for expires.
expires, _ := e["expires"].(json.Number)
if _, err := expires.Int64(); err != nil {
expires = "0"
}
v = map[string]any{
"type": "oauth", "methodID": "chatgpt-browser", "access": str(e, "access"),
"refresh": str(e, "refresh"), "expires": expires,
}
if a := str(e, "accountId"); a != "" {
v["metadata"] = map[string]any{"accountID": a}
}
default:
continue
}
out = append(out, map[string]any{"id": "cred_devvm_" + id, "integrationID": id, "label": "devvm", "active": true, "value": v})
}
return json.Marshal(out)
}
// SetKey saves key as the agent's API key in f, the store's login file,
+49 -23
View File
@@ -54,41 +54,67 @@ func TestSetKey(t *testing.T) {
}
}
// opencode's import of a key is opencode 2's auth export entry: devvm's
// ID, the key's placeholder, which is the one the VM's copy of auth.json
// holds and the proxy binds, never the key; a provider devvm doesn't put
// keys in for is refused.
func TestOpencodeKeyImport(t *testing.T) {
// opencode's import is opencode 2's auth export entries for the VM's copy
// of the store's login: devvm's IDs, sorted, each API key devvm puts in and
// OpenAI's Codex login with the placeholders the copy holds and the proxy
// binds, never a key or token; a key devvm doesn't put in is left out, and
// an empty login is an empty list.
func TestOpencodeImport(t *testing.T) {
o := storeFile(t, Opencode, "auth.json")
must(t, o.lockStoreWrite(map[string]any{}))
access := jwtWith(time.Now().Add(time.Hour), map[string]any{"email": "[email protected]"})
must(t, o.lockStoreWrite(map[string]any{
"groq": map[string]any{"type": "api", "key": "gsk-kept"},
"openai": map[string]any{"type": "oauth", "access": access, "refresh": "rt-secret", "expires": 1, "accountId": "acct-1"},
}))
must(t, o.SetKey("anthropic", "sk-ant-secret"))
o.Salt = "s4lt"
c, err := o.VMCopy()
must(t, err)
bs, err := o.Bindings()
if err != nil || len(bs) != 1 {
t.Fatalf("bindings: %v %v", bs, err)
must(t, err)
ph := map[string]string{}
for _, b := range bs {
ph[b.Name] = b.Placeholder
}
data, err := OpencodeKeyImport("anthropic", "s4lt")
if err != nil {
t.Fatal(err)
data, err := OpencodeImport(c.Data)
must(t, err)
type value struct {
Type, MethodID, Key, Access, Refresh string
Metadata struct{ AccountID string }
}
var got []struct {
ID, IntegrationID, Label string
Active bool
Value struct{ Type, Key string }
Value value
}
if err := json.Unmarshal(data, &got); err != nil {
t.Fatal(err)
must(t, json.Unmarshal(data, &got))
if len(got) != 2 {
t.Fatalf("OpencodeImport = %s", data)
}
want := []struct {
ID, IntegrationID, Label string
Active bool
Value struct{ Type, Key string }
}{{"cred_devvm_anthropic", "anthropic", "devvm", true, struct{ Type, Key string }{"key", bs[0].Placeholder}}}
if !slices.Equal(got, want) || strings.Contains(string(data), "sk-ant-secret") {
t.Errorf("OpencodeKeyImport = %s, want the placeholder %s", data, bs[0].Placeholder)
a, oa := got[0], got[1]
if a.ID != "cred_devvm_anthropic" || a.IntegrationID != "anthropic" || a.Label != "devvm" || !a.Active ||
a.Value != (value{Type: "key", Key: ph["opencode-anthropic"]}) {
t.Errorf("anthropic: %+v", a)
}
if _, err := OpencodeKeyImport("groq", "s4lt"); err == nil {
t.Error("OpencodeKeyImport(groq) took it")
want := value{Type: "oauth", MethodID: "chatgpt-browser", Access: ph["opencode-openai"], Refresh: ph["opencode-openai"]}
want.Metadata.AccountID = "acct-1"
if oa.ID != "cred_devvm_openai" || oa.IntegrationID != "openai" || oa.Value != want {
t.Errorf("openai: %+v", oa)
}
for _, secret := range []string{"sk-ant-secret", "rt-secret", access, "gsk-kept"} {
if strings.Contains(string(data), secret) {
t.Errorf("OpencodeImport holds %q: %s", secret, data)
}
}
// opencode 2 needs a whole number for expires.
if data, err := OpencodeImport([]byte(`{"openai":{"type":"oauth","access":"a","refresh":"r"}}`)); err != nil || !strings.Contains(string(data), `"expires":0,`) {
t.Errorf("OpencodeImport without expires = %s, %v", data, err)
}
if data, err := OpencodeImport([]byte(`{}`)); err != nil || string(data) != "[]" {
t.Errorf("OpencodeImport({}) = %s, %v", data, err)
}
if _, err := OpencodeImport([]byte(`[`)); err == nil {
t.Error("OpencodeImport took a broken copy")
}
}
+2 -1
View File
@@ -18,7 +18,8 @@
// entry per provider: {"type":"api","key"} or {"type":"oauth","access","refresh","expires" (ms)}.
// opencode 2 (checked at v2.2.5) keeps its logins in its SQLite database instead, and imports
// auth.json, in that format, once, as it makes its credential table; devvm's store keeps the
// file, which a VM's opencode reads as it first runs (OpencodeKeyImport for a key saved later).
// file, which a VM's opencode reads as it first runs, and each setup after that imports what changed
// (OpencodeImport).
package agentlogin
import (
+1
View File
@@ -291,6 +291,7 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede
"agent_login_exited": "using/coding-agents#logging-in-with-devvm-agent-login",
"agent_login_not_saved": "using/coding-agents#logging-in-with-devvm-agent-login",
"agent_key_copy_failed": "using/coding-agents#logging-in-with-devvm-agent-login",
"opencode_import_failed": "using/coding-agents#logging-in-with-devvm-agent-login",
"agent_login_failed": "using/coding-agents#logging-in-with-devvm-agent-login",
"agent_login_provider_needed": "using/coding-agents#logging-in-with-devvm-agent-login",
"agent_login_provider_alone": "using/coding-agents#logging-in-with-devvm-agent-login",
+6
View File
@@ -2544,6 +2544,11 @@ func OCIWaiting() M {
return M{id: "oci_waiting"}
}
// OpencodeImportFailed is [opencode_import_failed]: "opencode in {{.vm}} refused devvm's login for {{.providers}}, though devvm saved the API key. Run devvm in the VM's folder to try again."
func OpencodeImportFailed(providers string, vm string) M {
return M{id: "opencode_import_failed", vals: []val{{"providers", providers}, {"vm", vm}}}
}
// OpencodeLoginKept is [opencode_login_kept]: "The VM gets opencode's {{.providers}} login unchanged."
func OpencodeLoginKept(providers string) M {
return M{id: "opencode_login_kept", vals: []val{{"providers", providers}}}
@@ -4444,6 +4449,7 @@ var specs = map[string]spec{
"nothing_saved": {},
"nothing_to_clean": {},
"oci_waiting": {},
"opencode_import_failed": {fields: []string{"providers", "vm"}},
"opencode_login_kept": {fields: []string{"providers"}},
"opencode_login_withheld": {fields: []string{"providers"}},
"opencode_refresh_failed": {fields: []string{"provider", "reason"}},
+4
View File
@@ -33,6 +33,7 @@ import (
// an empty one
// net-direct a direct connection (curl --noproxy, past the VM's proxy) works,
// which fails as a confined VM's does without it
// opencode-refuses devvm's opencode.sh says opencode refused the provider this file names
// hostkeys-fails the VM doesn't show its ssh host keys, which are otherwise one
// made-up ed25519 key per VM, its name the key
// guest-ports what listens in the VM, as /proc/net/tcp has it, for a port
@@ -211,6 +212,9 @@ func (g *guest) answer() int {
return 0
case strings.Contains(all, "'curl' '--noproxy'") && !g.on("net-direct"):
return 7
case strings.HasSuffix(all, "'opencode.sh'") && g.on("opencode-refuses"):
g.print("devvm-opencode-failed " + strings.TrimSpace(string(g.raw("opencode-refuses", ""))) + "\n")
return 1
case strings.Contains(all, "/etc/ssh/ssh_host_"):
if g.on("hostkeys-fails") {
return 1
+43 -18
View File
@@ -4,9 +4,12 @@ import (
"bytes"
"context"
"errors"
"io"
"io/fs"
"os"
"slices"
"strconv"
"strings"
"time"
"github.com/w3cj/devvm/internal/agentlogin"
@@ -269,7 +272,7 @@ func (e AgentLogin) saveKey(ctx context.Context, t *target, store *secrets.Store
return backend.Logged(msg.AgentKeyCopyFailed(o.Agent, vm))
}
if o.Agent == agentlogin.Opencode {
if err := e.importKey(ctx, t, o.Provider, salt); err != nil {
if err := e.importLogins(ctx, t, data); err != nil {
return err
}
}
@@ -277,26 +280,48 @@ func (e AgentLogin) saveKey(ctx context.Context, t *target, store *secrets.Store
return nil
}
// opencodeImportScript gives opencode in the VM the credential on its
// input with opencode auth import, in a login shell (opencode on PATH),
// once opencode has made its database: until then, opencode reads the
// login file as it makes it.
const opencodeImportScript = `set -- "$HOME"/.local/share/opencode/opencode*.db; [ -e "$1" ] || exit 0; exec opencode auth import`
// opencodeScript is devvm's guest script that gives opencode 2 in the VM
// the store's opencode logins that changed, run by every launch's setup
// too (guest/sync.sh).
const opencodeScript = "opencode.sh"
// importKey adds provider's API key, as its placeholder ending in salt,
// to the VM's opencode, which keeps its logins in its database
// (agentlogin.OpencodeKeyImport).
func (e AgentLogin) importKey(ctx context.Context, t *target, provider, salt string) error {
data, err := agentlogin.OpencodeKeyImport(provider, salt)
// importLogins gives the VM's opencode, which keeps its logins in its
// database, the logins of vmCopy, the VM's copy of the store's
// (agentlogin.OpencodeImport), with opencodeScript in a login shell
// (opencode on PATH), the logins on its input.
func (e AgentLogin) importLogins(ctx context.Context, t *target, vmCopy []byte) error {
data, err := agentlogin.OpencodeImport(vmCopy)
if err != nil {
return msg.LoginCopyFailed(agentlogin.Opencode, err.Error(), t.f.Name).Because(err)
}
log := e.LogWriter()
if err := t.exec(ctx, []string{"bash", "-lc", opencodeImportScript}, backend.ExecOpts{Stdin: bytes.NewReader(data), Stdout: log, Stderr: log}); err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return backend.Logged(msg.AgentKeyCopyFailed(agentlogin.Opencode, t.f.Name))
script, err := fs.ReadFile(e.Assets, "guest/"+opencodeScript)
if err != nil {
return err
}
return nil
log := e.LogWriter()
var out bytes.Buffer
argv := []string{"bash", "-lc", string(script), opencodeScript}
err = t.exec(ctx, argv, backend.ExecOpts{Stdin: bytes.NewReader(data), Stdout: io.MultiWriter(&out, log), Stderr: log})
switch {
case err == nil:
return nil
case ctx.Err() != nil:
return ctx.Err()
}
if failed := opencodeRefused(out.String()); len(failed) > 0 {
return backend.Logged(msg.OpencodeImportFailed(strings.Join(failed, ", "), t.f.Name))
}
return backend.Logged(msg.AgentKeyCopyFailed(agentlogin.Opencode, t.f.Name))
}
// opencodeRefused is the providers opencodeScript's output names as
// refused by opencode's import, its "devvm-opencode-failed PROVIDER" lines.
func opencodeRefused(out string) []string {
var failed []string
for line := range strings.Lines(out) {
if p, ok := strings.CutPrefix(strings.TrimSpace(line), "devvm-opencode-failed "); ok && p != "" {
failed = append(failed, msg.Printable(p))
}
}
return failed
}
+19
View File
@@ -13,6 +13,25 @@ import (
"github.com/w3cj/devvm/internal/secrets"
)
// The providers opencode's import refused are the script's
// devvm-opencode-failed lines alone, in order, made printable.
func TestOpencodeRefused(t *testing.T) {
for _, c := range []struct {
out string
want []string
}{
{"", nil},
{"Imported 1 credential\n", nil},
{"devvm-opencode-failed openai\nnoise\ndevvm-opencode-failed openrouter\r\n", []string{"openai", "openrouter"}},
{"devvm-opencode-failed \n", nil},
{"devvm-opencode-failed a\x1bb\n", []string{msg.Printable("a\x1bb")}},
} {
if got := opencodeRefused(c.out); !slices.Equal(got, c.want) {
t.Errorf("opencodeRefused(%q) = %q, want %q", c.out, got, c.want)
}
}
}
// What devvm agent login says the store saved: a new ChatGPT login, with
// the account's email when its tokens name one; an API key, the same
// login as before, or none at all, fails.
+8 -1
View File
@@ -252,7 +252,7 @@ func (e syncer) stage(ctx context.Context, st *state.VM, in setupInputs) (*stage
if m := claudeMoved(in.moved, st.Dir); m != nil {
s.put("moved", 0o644, m)
}
for _, name := range []string{"sync.sh", "tools.sh", "ca.sh", "claude.sh", "guide.md"} {
for _, name := range []string{"sync.sh", "tools.sh", "ca.sh", "claude.sh", "guide.md", opencodeScript} {
data, err := fs.ReadFile(e.Assets, "guest/"+name)
if err != nil {
return nil, err
@@ -421,6 +421,13 @@ func (e syncer) stageSecrets(ctx context.Context, s *stage, store *secrets.Store
name = "home/" + secrets.LoginRel(kind)
}
s.put(name, 0o600, data)
if kind == agentlogin.Opencode {
imp, err := agentlogin.OpencodeImport(data)
if err != nil {
return msg.LoginCopyFailed(kind, err.Error(), vm).Because(err)
}
s.put("opencode-import.json", 0o600, imp)
}
}
for _, f := range slices.Clone(s.files) {
rel, ok := strings.CutPrefix(f.name, "home/")
+4
View File
@@ -2339,6 +2339,10 @@ other = "devvm saved {{.agent}}'s {{.provider}} API key in its agent store, and
[agent_key_copy_failed]
other = "Giving {{.vm}} its copy of {{.agent}}'s login failed, though devvm saved the API key. Run devvm in the VM's folder to give it the copy."
[opencode_import_failed]
description = "providers is a comma-separated list of opencode's provider names"
other = "opencode in {{.vm}} refused devvm's login for {{.providers}}, though devvm saved the API key. Run devvm in the VM's folder to try again."
[agent_key_howto]
description = "provider is the API key's provider, as opencode names it: openai, anthropic or openrouter"
other = "Paste the {{.provider}} API key for {{.agent}}. devvm keeps it on this machine, and VMs get a placeholder."
+23 -3
View File
@@ -92,8 +92,9 @@ stdout '''sh'' ''-c'' ''f="\$HOME/\$1".*'' ''sh'' ''.codex/auth.json''$'
! stdout 'sk-testfake'
# opencode's key for a provider: the store keeps it beside the others,
# and the VM's opencode, once it has its database, imports the key's
# placeholder.
# and the VM's opencode, once it has its database, imports the store's
# opencode logins with devvm's guest script (opencode.sh), their
# placeholders on its input.
stub_reset
stdin $WORK/key2
exec devvm agent login opencode --api-key --provider anthropic --stdin
@@ -102,9 +103,28 @@ grep '"key": "sk-ant-testfake"' $DATA/logins/opencode/.local/share/opencode/auth
grep '"name":"opencode-anthropic"' $AG_dir/run/secrets.json
stub_calls
stdout '''sh'' ''-c'' ''f="\$HOME/\$1".*'' ''sh'' ''.local/share/opencode/auth.json''$'
stdout '''bash'' ''-lc'' ''[^'']*opencode\*\.db; [^'']*exec opencode auth import''$'
stdout '''bash'' ''-lc'' ''#!/bin/bash$'
stdout 'if ! opencode auth import <<<"\[\$entry\]" >&2; then$'
stdout '^'' ''opencode\.sh''$'
! stdout 'sk-ant-testfake'
# Every launch sends the store's opencode logins as opencode 2's import
# reads them, devvm's IDs and placeholders alone, beside the script.
stub_reset
exec devvm host
exec tar -tf $STUB_DIR/sync.tar
stdout '^opencode\.sh$'
exec tar -xOf $STUB_DIR/sync.tar opencode-import.json
stdout '\{"active":true,"id":"cred_devvm_anthropic","integrationID":"anthropic","label":"devvm","value":\{"key":"devvm-proxy-managed-opencode-anthropic[^"]*","type":"key"\}'
! stdout 'sk-ant-testfake'
# opencode refuses a provider's entry: devvm names the provider.
exec sh -c 'echo openrouter > "$STUB_DIR/opencode-refuses"'
stdin $WORK/key2
! exec devvm agent login opencode --api-key --provider anthropic --stdin
stderr '^devvm: opencode_import_failed providers=openrouter vm=devvm-agents-[0-9a-f]{14}$'
rm $STUB_DIR/opencode-refuses
# The import fails: the key is saved, and devvm says the VM's copy failed.
exec sh -c 'echo "opencode auth import" > "$STUB_DIR/shell-fails-on"'
stdin $WORK/key2
+104
View File
@@ -14,6 +14,7 @@ import (
"path/filepath"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
"syscall"
@@ -70,6 +71,7 @@ func networkSection(s *S) {
netCodexLogin(n)
netOpencodeLogin(n)
netOpencodeHistory(n)
netOpencodeKeys(n)
netClaudeLogins(n)
netSave(n)
netGithub(n)
@@ -911,6 +913,108 @@ func netOpencodeLogin(n *netRun) {
}, Tail(60))
}
// devvm agent login opencode --api-key saves a key from the network VM;
// a second opencode 2 VM, whose database was made before, gets the key's
// placeholder at its next launch, beside a credential of its own that
// stays.
func netOpencodeKeys(n *netRun) {
s := n.s
oc, _ := s.NewProject("net-oc")
vm, _, _ := launchWith(s, oc, n.home(), "--network", "allowlist", "--no-git-protect", "--agents", "opencode", "--cpus", "2", "--memory", "2", "--ports", "none")
s.Check("opencode's self-update is off in an opencode VM's login shell", func() error {
if got := vmOut(s, vm, "printenv OPENCODE_DISABLE_AUTOUPDATE"); vm == "" || got != "1" {
return fmt.Errorf("OPENCODE_DISABLE_AUTOUPDATE is %q", got)
}
return nil
})
own := `[{"id":"cred_e2e_own","integrationID":"anthropic","label":"mine","active":true,"value":{"type":"key","key":"sk-ant-e2e-own"}}]`
s.Check("an opencode 2 VM whose database exists gets a key saved from another VM at its next launch", func() error {
switch {
case vm == "":
return errors.New("no second VM")
case inVM(s, vm, "opencode auth list >/dev/null && ls ~/.local/share/opencode/opencode*.db >/dev/null") != nil:
return errors.New("the second VM's opencode made no database")
case inVM(s, vm, "echo "+shell.Quote(own)+" | opencode auth import") != nil:
return errors.New("the second VM's opencode didn't import a credential of its own")
}
// The company proxy's environment, as the logins before: the save brings the VM up as it was.
if r, err := n.dv("sk-or-e2efake-saved\n", n.tokenEnv("DEVVM_MESSAGES=names"), "agent", "login", "opencode", "--api-key", "--provider", "openrouter", "--stdin"); err != nil {
// The run log's end holds opencode.sh's stderr: the import's own, or the command that failed.
return failed("devvm agent login opencode --api-key failed:\n"+r.Out+"\n"+n.runLogEnd(r.Out), err)
}
if has, err := vmHas(s, vm, true, "opencode auth export", "devvm-proxy-managed-opencode-openrouter"); err != nil || has {
return errors.New("the second VM had the key before its launch")
}
if _, _, err := launchWith(s, oc, n.home()); err != nil {
return err
}
export := "opencode auth export openrouter"
if has, err := vmHas(s, vm, true, export, `"id": "cred_devvm_openrouter"`); err != nil || !has {
return errors.New("the second VM's opencode has no devvm entry for the key\n" + n.opencodeWhy(vm))
}
if has, err := vmHas(s, vm, true, export, "devvm-proxy-managed-opencode-openrouter"); err != nil || !has {
return errors.New("the second VM's opencode has no placeholder of the key")
}
if has, err := vmHas(s, vm, true, "opencode auth export", "e2efake"); err != nil || has {
return errors.New("the second VM's opencode holds the key itself")
}
if has, err := vmHas(s, vm, true, "opencode auth export anthropic", "sk-ant-e2e-own"); err != nil || !has {
return errors.New("the second VM's own credential is gone")
}
return nil
}, Tail(40))
s.Check("... and gets it again at its next launch once its database is made again", func() error {
// opencode's service keeps the old database open: it goes first.
remake := "pkill -x opencode; sleep 1; rm -f ~/.local/share/opencode/opencode.db* && opencode auth list >/dev/null"
if vm == "" || inVM(s, vm, remake) != nil {
return errors.New("the second VM's opencode didn't make its database again")
}
if has, err := vmHas(s, vm, true, "opencode auth export", "cred_devvm_openrouter"); err != nil || has {
return errors.New("the new database already holds devvm's entry")
}
if _, _, err := launchWith(s, oc, n.home()); err != nil {
return err
}
if has, err := vmHas(s, vm, true, "opencode auth export openrouter", "devvm-proxy-managed-opencode-openrouter"); err != nil || !has {
return errors.New("the new database has no placeholder of the key after the launch\n" + n.opencodeWhy(vm))
}
return nil
}, Tail(40))
if vm != "" {
_, _ = s.Run(devvmCmd(s, oc, "", n.home(), "rm", "--force", "--no-export"))
}
}
// opencodeWhy is what the VM's opencode got: the IDs of opencode.sh's
// record and of opencode's credentials (never their values), and the
// lines of the newest run log that name opencode.
func (n *netRun) opencodeWhy(vm string) string {
s := n.s
ids := vmOut(s, vm, `jq -c '[.[].id]' ~/.local/state/devvm/opencode-import.json; ls ~/.local/share/opencode; opencode auth export 2>&1 | jq -c '[.[] | [.id, .integrationID, .active]]'`)
runs, _ := filepath.Glob(filepath.Join(s.Paths.Devvm, "logs", "runs", "*.log"))
slices.Sort(runs)
var lines []string
for _, f := range runs[max(0, len(runs)-4):] {
lines = append(lines, "== "+filepath.Base(f))
for l := range strings.Lines(readText(f)) {
if strings.Contains(l, "opencode") || strings.Contains(l, "Imported") || strings.Contains(l, "sync") {
lines = append(lines, strings.TrimRight(l, "\n"))
}
}
}
return "in the VM: " + ids + "\nthe last run logs' opencode lines:\n" + tailLines(strings.Join(lines, "\n"), 60)
}
// runLogEnd is the last lines of the run log that out's log_end line
// names, nothing when it names none.
func (n *netRun) runLogEnd(out string) string {
m := regexp.MustCompile(`log_end file=(\S+)`).FindStringSubmatch(out)
if m == nil {
return ""
}
return "the run log ends:\n" + tailLines(readText(m[1]), 40)
}
// opencodeLoggedIn is the opencode login's first step that failed,
// nothing when none.
func (n *netRun) opencodeLoggedIn(p *Proc) string {