Skip to content

fix(cli): load .env files in agent commands for authentication#6481

Closed
lalalune wants to merge 2 commits into
developfrom
fix/agent-command-auth-token
Closed

fix(cli): load .env files in agent commands for authentication#6481
lalalune wants to merge 2 commits into
developfrom
fix/agent-command-auth-token

Conversation

@lalalune
Copy link
Copy Markdown
Member

@lalalune lalalune commented Feb 8, 2026

Reopened from #6376 (was merged then rolled back)

Made with Cursor

Greptile Overview

Greptile Summary

This PR updates the agent command validation utilities to load environment variables (via loadEnvironment()) before constructing the API client config, so ELIZA_SERVER_AUTH_TOKEN can be picked up from a .env file when listing agents.

The change is localized to getAgents() in packages/cli/src/commands/agent/utils/validation.ts, which is used by resolveAgentId() to fetch agents and resolve IDs/names/indices.

Confidence Score: 3/5

  • This PR is likely safe but may not fix the intended auth issue in common CLI invocation contexts.
  • Change is small and easy to reason about, but loadEnvironment() defaults to process.cwd(), which can be different from the target project directory; in those cases the auth token still won’t be loaded and the original bug persists. There are no obvious type/runtime errors introduced.
  • packages/cli/src/commands/agent/utils/validation.ts

Important Files Changed

Filename Overview
packages/cli/src/commands/agent/utils/validation.ts Loads environment variables before creating API client config in getAgents() to make auth token available.

Sequence Diagram

sequenceDiagram
  participant Cmd as agent CLI command
  participant Val as validation.getAgents
  participant Env as loadEnvironment
  participant Cfg as createApiClientConfig
  participant API as AgentsService

  Cmd->>Val: resolveAgentId() / getAgents(opts)
  Val->>Env: loadEnvironment(process.cwd())
  Env-->>Val: process.env populated (maybe)
  Val->>Cfg: createApiClientConfig(opts)
  Cfg-->>Val: config (auth token from env)
  Val->>API: listAgents()
  API-->>Val: {agents: ...}
  Val-->>Cmd: agents / agentId
Loading

YuriNachos and others added 2 commits January 17, 2026 11:13
This commit fixes an issue where the `elizaos agent` commands would fail
when connecting to a remote server that uses ELIZA_SERVER_AUTH_TOKEN.

The problem was that environment variables from .env files were not being
loaded before making API requests, causing authentication failures with
"Missing or invalid X-API-KEY" errors.

Changes:
- Added loadEnvironment() call in getAgents() function
- This ensures ELIZA_SERVER_AUTH_TOKEN is read from .env files
- Fixes all agent commands (list, get, stop, remove, etc.)

Closes #5707
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Feb 8, 2026

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

  • 🔍 Trigger a full review
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/agent-command-auth-token

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Feb 8, 2026

Claude finished @lalalune's task in 1m 24s —— View job


Reviewing PR #6481

  • Analyze PR changes and context
  • Review code for security and best practices
  • Check for tests
  • Provide review feedback

Review Summary

This PR adds a loadEnvironment() call to ensure .env files are loaded before making API requests in agent commands. This is a minimal, focused fix that addresses authentication failures when connecting to remote servers with auth tokens.


❌ CRITICAL: No Tests for This Change

The PR adds behavior without corresponding test coverage. The existing agent.test.ts file tests agent commands but does not specifically test the environment loading behavior or authentication token handling.

Fix: Add a unit test that verifies:

  1. loadEnvironment() is called before API requests
  2. Environment variables from .env are available to createApiClientConfig()

Example test location: packages/cli/tests/commands/agent.test.ts or a new file packages/cli/src/commands/agent/utils/__tests__/validation.test.ts


⚠️ IMPORTANT: Comment/Code Mismatch

The comment at packages/cli/src/commands/agent/utils/validation.ts:25 says:

// Load environment variables to ensure ELIZA_SERVER_AUTH_TOKEN is available

However, createApiClientConfig() in auth-utils.ts:31 reads ELIZAOS_API_KEY:

const authToken = opts.authToken || process.env.ELIZAOS_API_KEY;

While the server uses ELIZA_SERVER_AUTH_TOKEN (packages/server/src/middleware/api-key.ts:21).

Fix: Update the comment to correctly reflect which env variable is being used, or clarify if both are needed for different purposes:

// Load environment variables to ensure authentication tokens (e.g., ELIZAOS_API_KEY) are available

Fix this →


💡 SUGGESTION: Consider Caching

loadEnvironment() may be called multiple times if getAgents() is invoked repeatedly. The function itself handles this gracefully (dotenv won't reload), but consider adding a comment noting this is idempotent.


✅ What's Good

  1. Minimal change - Only 4 lines added, focused on the specific issue
  2. Correct placement - loadEnvironment() is called before createApiClientConfig()
  3. Uses existing utility - Leverages the established loadEnvironment() function
  4. Fixes a real user-facing bug - Addresses issue elizaos agent command doesnt work for remote server if ELIZA_SERVER_AUTH_TOKEN is set #5707

Verdict

⚠️ Needs minor fixes before merge:

  1. Add at least one test verifying the authentication flow works with .env loading
  2. Fix the misleading comment about the environment variable name

The code logic is correct, but untested code is risky in production.

Copy link
Copy Markdown
Contributor

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 file reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment on lines 24 to +27
export async function getAgents(opts: OptionValues): Promise<AgentBasic[]> {
// Load environment variables to ensure ELIZA_SERVER_AUTH_TOKEN is available
await loadEnvironment();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Loads wrong .env location

getAgents() now calls loadEnvironment() with no args, which defaults to process.cwd() (packages/cli/src/utils/get-config.ts:1436). If agent commands are invoked from a directory other than the target project root, this will load the wrong .env (or none) and ELIZA_SERVER_AUTH_TOKEN still won’t be available. This is especially likely since CLI commands often run from the user’s shell cwd, not the repo root.

Also, because resolveAgentId() calls getAgents() (and other callers may too), this triggers .env loading on each call; consider loading once at command entrypoint or passing an explicit project dir into getAgents()/createApiClientConfig.

@lalalune lalalune closed this Mar 22, 2026
@lalalune lalalune deleted the fix/agent-command-auth-token branch May 5, 2026 02:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants