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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/dotenv-provider-keys.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"thee": minor
---

`thee` reads provider keys such as `OPENCODE_API_KEY` from the nearest `.env` at or above the current directory, up to the repo root. Variables already set in your shell win over the file. Copy `.env.example` to `.env` to get started.

**Upgrade:** a `.env` line that isn't `KEY=VALUE` (for example `name: value`) now stops every `thee` command with the file and line number. Fix or remove that line.
12 changes: 12 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Copy to .env and fill in the keys you use. .env is gitignored.
# thee reads the nearest .env at or above the current directory, up to the
# repo root. Variables already set in your shell take precedence.

# OpenCode Go (task eval, /providers in the TUI)
OPENCODE_API_KEY=

# DeepInfra (default worker role, weekly CI eval matrix)
DEEPINFRA_API_KEY=

# OpenAI
OPENAI_API_KEY=
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
# Env / secrets
.env
.env.*
!.env.example

# Release tooling (changesets)
node_modules/
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ go test ./...
| `THEE_TRUST` | — | Set to `1` to trust the workspace (same as `--trust`) |
| `DEEPINFRA_API_KEY` (etc.) | — | Provider keys per embedded `models.yaml` / `~/.thee/catalog.json` |

`thee` also reads the nearest `.env` at or above the current directory, stopping at the repo root. Shell variables win over the file. To set it up, copy [`.env.example`](.env.example) to `.env` and fill in your keys.

---

## Install
Expand Down
2 changes: 1 addition & 1 deletion docs/harness-architecture/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ The harness lets users bring their own key. Our own inference is the provider we

### Credential resolution order

1. Per-provider `api_key_env` in `models.yaml` or `catalog.json` (e.g. `DEEPINFRA_API_KEY`).
1. Per-provider `api_key_env` in `models.yaml` or `catalog.json` (e.g. `DEEPINFRA_API_KEY`). At startup `thee` loads the nearest `.env` at or above the current directory (stopping at the directory that holds `.git`). It never overrides variables already set in the environment.
2. Generic fallbacks where documented (e.g. `OPENAI_API_KEY` for OpenAI-compatible base URLs)—explicit in config, not magic.
3. OS keychain entries via `thee auth login <provider>`.
4. **(team)** CI/org secret injection—same env-based contract.
Expand Down
10 changes: 10 additions & 0 deletions harness/cmd/thee/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,22 @@ import (
"os"

"github.com/spf13/cobra"

"github.com/PLACEHOLDER/thee/harness/internal/config"
)

var rootCmd = &cobra.Command{
Use: "thee",
Short: "thee coding agent harness",
SilenceUsage: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
wd, err := os.Getwd()
if err != nil {
return err
}
_, err = config.LoadDotEnv(wd)
return err
},
}

func execute() error {
Expand Down
106 changes: 106 additions & 0 deletions harness/internal/config/dotenv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package config

import (
"bufio"
"bytes"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
)

const dotEnvName = ".env"

var utf8BOM = string([]byte{0xEF, 0xBB, 0xBF})

// FindDotEnv returns the nearest .env file at or above dir, stopping at the
// first directory that holds .git. It returns "" when there is none.
func FindDotEnv(dir string) (string, error) {
dir, err := filepath.Abs(dir)
if err != nil {
return "", err
}
for {
path := filepath.Join(dir, dotEnvName)
info, err := os.Stat(path)
if err == nil && !info.IsDir() {
return path, nil
}
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return "", err
}
if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil {
return "", nil
}
parent := filepath.Dir(dir)
if parent == dir {
return "", nil
}
dir = parent
}
}

// LoadDotEnv sets environment variables from the nearest .env file at or above
// dir. Variables already set in the environment win. It returns the file it
// read, or "" when there was none.
func LoadDotEnv(dir string) (string, error) {
path, err := FindDotEnv(dir)
if err != nil || path == "" {
return "", err
}
b, err := os.ReadFile(path) //nolint:gosec // G304: path is always <dir>/.env from FindDotEnv
if err != nil {
return "", err
}
vars, err := ParseDotEnv(path, bufio.NewScanner(bytes.NewReader(b)))
if err != nil {
return "", err
}
for k, v := range vars {
if _, set := os.LookupEnv(k); set {
continue
}
if err := os.Setenv(k, v); err != nil {
return "", fmt.Errorf("%s: set %s: %w", path, k, err)
}
}
return path, nil
}

// ParseDotEnv reads KEY=VALUE lines. Blank lines, # comments, an optional
// export prefix, and single or double quotes around values are accepted.
func ParseDotEnv(name string, sc *bufio.Scanner) (map[string]string, error) {
vars := map[string]string{}
for n := 1; sc.Scan(); n++ {
line := strings.TrimSpace(sc.Text())
if n == 1 {
line = strings.TrimPrefix(line, utf8BOM)
}
if line == "" || strings.HasPrefix(line, "#") {
continue
}
line = strings.TrimSpace(strings.TrimPrefix(line, "export "))
key, val, ok := strings.Cut(line, "=")
key = strings.TrimSpace(key)
if !ok || key == "" || strings.ContainsAny(key, " \t") {
return nil, fmt.Errorf("%s:%d: want KEY=VALUE", name, n)
}
vars[key] = dotEnvValue(strings.TrimSpace(val))
}
if err := sc.Err(); err != nil {
return nil, fmt.Errorf("%s: %w", name, err)
}
return vars, nil
}

func dotEnvValue(v string) string {
if len(v) >= 2 && (v[0] == '"' || v[0] == '\'') && v[len(v)-1] == v[0] {
return v[1 : len(v)-1]
}
if i := strings.Index(v, " #"); i >= 0 {
v = strings.TrimSpace(v[:i])
}
return v
}
90 changes: 90 additions & 0 deletions harness/internal/config/dotenv_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package config

import (
"bufio"
"os"
"path/filepath"
"strings"
"testing"

"github.com/google/go-cmp/cmp"
)

func TestParseDotEnv(t *testing.T) {
in := utf8BOM + "# keys\n\nexport A=1\nB = \"two words\"\nC='x # y'\nD=plain # note\nE=\n"
got, err := ParseDotEnv("test.env", bufio.NewScanner(strings.NewReader(in)))
if err != nil {
t.Fatal(err)
}
want := map[string]string{"A": "1", "B": "two words", "C": "x # y", "D": "plain", "E": ""}
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("ParseDotEnv (-want +got):\n%s", diff)
}
}

func TestParseDotEnvBadLine(t *testing.T) {
for _, in := range []string{"NOEQUALS", "=v", "BAD KEY=v"} {
if _, err := ParseDotEnv("test.env", bufio.NewScanner(strings.NewReader(in))); err == nil {
t.Errorf("ParseDotEnv(%q): got nil error", in)
}
}
}

func unsetForTest(t *testing.T, keys ...string) {
t.Helper()
for _, k := range keys {
t.Setenv(k, "")
if err := os.Unsetenv(k); err != nil {
t.Fatal(err)
}
}
}

func writeFile(t *testing.T, path, body string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}

func TestLoadDotEnvWalksUpToRepoRoot(t *testing.T) {
unsetForTest(t, "THEE_DOTENV_A", "THEE_DOTENV_B")
root := t.TempDir()
writeFile(t, filepath.Join(root, ".git", "HEAD"), "ref: refs/heads/main\n")
writeFile(t, filepath.Join(root, ".env"), "THEE_DOTENV_A=from-file\nTHEE_DOTENV_B=from-file\n")
t.Setenv("THEE_DOTENV_B", "from-env")
sub := filepath.Join(root, "harness", "cmd")
if err := os.MkdirAll(sub, 0o750); err != nil {
t.Fatal(err)
}
path, err := LoadDotEnv(sub)
if err != nil {
t.Fatal(err)
}
if path != filepath.Join(root, ".env") {
t.Errorf("LoadDotEnv: got path %q", path)
}
if got := os.Getenv("THEE_DOTENV_A"); got != "from-file" {
t.Errorf("THEE_DOTENV_A: got %q, want from-file", got)
}
if got := os.Getenv("THEE_DOTENV_B"); got != "from-env" {
t.Errorf("THEE_DOTENV_B: got %q, want from-env", got)
}
}

func TestFindDotEnvStopsAtRepoRoot(t *testing.T) {
outer := t.TempDir()
writeFile(t, filepath.Join(outer, ".env"), "THEE_DOTENV_OUTER=1\n")
repo := filepath.Join(outer, "repo")
writeFile(t, filepath.Join(repo, ".git"), "gitdir: elsewhere\n")
path, err := FindDotEnv(repo)
if err != nil {
t.Fatal(err)
}
if path != "" {
t.Errorf("FindDotEnv: got %q, want none", path)
}
}
1 change: 1 addition & 0 deletions harness/internal/e2e/m0_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func TestM0RunE2E(t *testing.T) {
}
bin := buildThee(t)
cmd := exec.Command(bin, "run", "-p", "fix the failing test", "--trust", "--directory", fixtureDir)
cmd.Dir = fixtureDir
cmd.Env = append(os.Environ(),
"THEE_HOME="+home,
"THEE_SCRIPTED_PROVIDER_FILE="+scriptPath,
Expand Down
Loading