Skip to content
Open
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
43 changes: 28 additions & 15 deletions cmd/lk/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ func createAgent(ctx context.Context, cmd *cli.Command) error {
return err
}

if configExists && lkConfig.Agent != nil {
if configExists && lkConfig.HasAgent() {
out.Statusf("Using agent configuration [%s]", util.Accented(tomlFilename))
} else {
lkConfig = config.NewLiveKitTOML(subdomainMatches[1]).WithDefaultAgent()
Expand Down Expand Up @@ -727,15 +727,18 @@ func createAgent(ctx context.Context, cmd *cli.Command) error {
buildContext, cancel := context.WithTimeout(ctx, buildTimeout)
defer cancel()
regions := []string{region}
agentID, err := agentsClient.RegisterAgent(buildContext, secrets, regions)
created, err := agentsClient.AgentClient.CreateAgent(buildContext, &lkproto.CreateAgentRequest{
Secrets: secrets,
Regions: regions,
})
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
return fmt.Errorf("unable to create agent: %s", twerr.Msg())
}
return fmt.Errorf("unable to create agent: %w", err)
}
lkConfig.Agent.ID = agentID
if err := lkConfig.SaveTOMLFile(workingDir, tomlFilename); err != nil {
agentID := created.AgentId
if err := recordCreatedAgent(agentID, created.AgentName); err != nil {
return err
}
out.Statusf("Created agent with ID [%s]", util.Accented(agentID))
Expand Down Expand Up @@ -788,8 +791,7 @@ func createAgent(ctx context.Context, cmd *cli.Command) error {
return fmt.Errorf("unable to create agent: %w", err)
}

lkConfig.Agent.ID = resp.AgentId
if err := lkConfig.SaveTOMLFile(workingDir, tomlFilename); err != nil {
if err := recordCreatedAgent(resp.AgentId, resp.AgentName); err != nil {
return err
}

Expand All @@ -811,7 +813,7 @@ func createAgent(ctx context.Context, cmd *cli.Command) error {
return err
} else if viewLogs {
out.Status("Tailing runtime logs...safe to exit at any time")
return agentsClient.StreamLogs(ctx, "deploy", lkConfig.Agent.ID, "", os.Stdout, resp.ServerRegions[0])
return agentsClient.StreamLogs(ctx, "deploy", resp.AgentId, "", os.Stdout, resp.ServerRegions[0])
}
}
return nil
Expand Down Expand Up @@ -852,7 +854,7 @@ func createAgentConfig(ctx context.Context, cmd *cli.Command) error {
}

if configExists && lkConfig.HasAgent() {
agentID = lkConfig.Agent.ID
agentID = lkConfig.AgentID()
} else {
agentID, err = selectAgent(ctx, cmd, false)
if err != nil {
Expand Down Expand Up @@ -882,16 +884,26 @@ func createAgentConfig(ctx context.Context, cmd *cli.Command) error {

agent := response.Agents[0]
lkConfig := config.NewLiveKitTOML(matches[1])
lkConfig.Agent = &config.LiveKitTOMLAgentConfig{
ID: agent.AgentId,
}
lkConfig.Agent = &config.LiveKitTOMLAgentConfig{Name: agent.AgentName}
lkConfig.Cloud = &config.LiveKitTOMLCloudConfig{ID: agent.AgentId}

if err := lkConfig.SaveTOMLFile(workingDir, tomlFilename); err != nil {
return err
}
return nil
}

// recordCreatedAgent saves the new agent's id and Cloud-assigned name to
// livekit.toml, replacing any agent already there.
func recordCreatedAgent(agentID, agentName string) error {
if lkConfig.Agent == nil {
lkConfig.WithDefaultAgent()
}
lkConfig.Agent.Name = agentName
lkConfig.Cloud = &config.LiveKitTOMLCloudConfig{ID: agentID}
return lkConfig.SaveTOMLFile(workingDir, tomlFilename)
}

func deployAgent(ctx context.Context, cmd *cli.Command) error {
agentId, err := getAgentID(ctx, cmd, workingDir, tomlFilename, false)
if err != nil {
Expand Down Expand Up @@ -1233,9 +1245,10 @@ func updateAgent(ctx context.Context, cmd *cli.Command) error {
if !lkConfig.HasAgent() {
return fmt.Errorf("no agent config found in [%s]", tomlFilename)
}
agentID := lkConfig.AgentID()

req := &lkproto.UpdateAgentRequest{
AgentId: lkConfig.Agent.ID,
AgentId: agentID,
}

secrets, err := requireSecrets(ctx, cmd, false, true)
Expand All @@ -1247,7 +1260,7 @@ func updateAgent(ctx context.Context, cmd *cli.Command) error {
}

var resp *lkproto.UpdateAgentResponse
err = out.Await("Updating agent ["+util.Accented(lkConfig.Agent.ID)+"]", ctx, func(ctx context.Context) error {
err = out.Await("Updating agent ["+util.Accented(agentID)+"]", ctx, func(ctx context.Context) error {
var clientErr error
resp, clientErr = agentsClient.UpdateAgent(ctx, req)
return clientErr
Expand All @@ -1260,7 +1273,7 @@ func updateAgent(ctx context.Context, cmd *cli.Command) error {
}

if resp.Success {
out.Statusf("Updated agent [%s]", util.Accented(lkConfig.Agent.ID))
out.Statusf("Updated agent [%s]", util.Accented(agentID))
err = lkConfig.SaveTOMLFile("", tomlFilename)
return err
}
Expand Down Expand Up @@ -1786,7 +1799,7 @@ func getAgentID(ctx context.Context, cmd *cli.Command, agentDir string, tomlFile
if !lkConfig.HasAgent() {
return "", fmt.Errorf("no agent config found in [%s]", tomlFilename)
}
agentID = lkConfig.Agent.ID
agentID = lkConfig.AgentID()
} else {
agentID, err = selectAgent(ctx, cmd, excludeEmptyVersion)
if err != nil {
Expand Down
71 changes: 45 additions & 26 deletions pkg/config/livekit.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,23 @@ type AgentTOML struct {
type LiveKitTOML struct {
Project *LiveKitTOMLProjectConfig `toml:"project"` // Required
Agent *LiveKitTOMLAgentConfig `toml:"agent"`
Cloud *LiveKitTOMLCloudConfig `toml:"cloud,omitempty"`
}

type LiveKitTOMLProjectConfig struct {
Subdomain string `toml:"subdomain"`
}

type LiveKitTOMLAgentConfig struct {
// Deprecated: the id lives in [cloud]; a legacy value is moved there on load.
ID string `toml:"id,omitempty"`
// Identity of the agent under test in simulation runs; self-hosted agents
// set it by hand.
Name string `toml:"name"`
}

// LiveKitTOMLCloudConfig identifies the agent on LiveKit Cloud.
type LiveKitTOMLCloudConfig struct {
ID string `toml:"id"`
}

Expand All @@ -68,7 +78,15 @@ func (c *LiveKitTOML) WithDefaultAgent() *LiveKitTOML {
}

func (c *LiveKitTOML) HasAgent() bool {
return c.Agent != nil
return c.Agent != nil || c.Cloud != nil
}

// AgentID returns the Cloud Agents id, or "" for an agent not on Cloud.
func (c *LiveKitTOML) AgentID() string {
if c.Cloud == nil {
return ""
}
return c.Cloud.ID
}

func (c *LiveKitTOML) SaveTOMLFile(dir string, tomlFileName string) error {
Expand All @@ -87,31 +105,32 @@ func (c *LiveKitTOML) SaveTOMLFile(dir string, tomlFileName string) error {

func LoadTOMLFile(dir string, tomlFileName string) (*LiveKitTOML, bool, error) {
logger.Debugw(fmt.Sprintf("loading %s file", tomlFileName))
var config *LiveKitTOML = nil
var err error
configExists := false

tomlFile := filepath.Join(dir, tomlFileName)

if _, err = os.Stat(tomlFile); err == nil {
configExists = true

_, err = toml.DecodeFile(tomlFile, &config)
if config.Project == nil {
// Attempt to decode old agent config
var oldConfig AgentTOML
_, err = toml.DecodeFile(tomlFile, &oldConfig)
if err != nil {
return nil, configExists, err
}
config.Project = &LiveKitTOMLProjectConfig{
Subdomain: oldConfig.ProjectSubdomain,
}
config.Agent = &LiveKitTOMLAgentConfig{}
}
} else {
configExists = !errors.Is(err, fs.ErrNotExist)
path := filepath.Join(dir, tomlFileName)

if _, err := os.Stat(path); err != nil {
return nil, !errors.Is(err, fs.ErrNotExist), err
}

return config, configExists, err
var config LiveKitTOML
if _, err := toml.DecodeFile(path, &config); err != nil {
return nil, true, err
}
if config.Project == nil {
// Attempt to decode old agent config
var oldConfig AgentTOML
if _, err := toml.DecodeFile(path, &oldConfig); err != nil {
return nil, true, err
}
config.Project = &LiveKitTOMLProjectConfig{
Subdomain: oldConfig.ProjectSubdomain,
}
config.Agent = &LiveKitTOMLAgentConfig{}
}
if config.Agent != nil && config.Agent.ID != "" {
if config.Cloud == nil {
config.Cloud = &LiveKitTOMLCloudConfig{ID: config.Agent.ID}
}
config.Agent.ID = ""
}
return &config, true, nil
}
87 changes: 87 additions & 0 deletions pkg/config/livekit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright 2025 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package config

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

"github.com/stretchr/testify/require"
)

func writeTOML(t *testing.T, body string) string {
t.Helper()
dir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(dir, LiveKitTOMLFile), []byte(body), 0o644))
return dir
}

func TestLoadTOMLFile_LegacyAgentIDMovesToCloud(t *testing.T) {
dir := writeTOML(t, `
[project]
subdomain = "proj"

[agent]
id = "CA_legacy"
name = "my-agent"
`)
cfg, exists, err := LoadTOMLFile(dir, LiveKitTOMLFile)
require.True(t, exists)
require.NoError(t, err)
require.Equal(t, "my-agent", cfg.Agent.Name)
require.Empty(t, cfg.Agent.ID)
require.Equal(t, "CA_legacy", cfg.AgentID())
}

func TestLoadTOMLFile_CloudID(t *testing.T) {
dir := writeTOML(t, `
[project]
subdomain = "proj"

[agent]
name = "my-agent"

[cloud]
id = "CA_a"
`)
cfg, _, err := LoadTOMLFile(dir, LiveKitTOMLFile)
require.NoError(t, err)
require.Equal(t, "CA_a", cfg.AgentID())
}

func TestSaveTOMLFile_RoundTrip(t *testing.T) {
dir := t.TempDir()
cfg := NewLiveKitTOML("proj").WithDefaultAgent()
cfg.Agent.Name = "my-agent"
cfg.Cloud = &LiveKitTOMLCloudConfig{ID: "CA_a"}
require.NoError(t, cfg.SaveTOMLFile(dir, LiveKitTOMLFile))
raw, err := os.ReadFile(filepath.Join(dir, LiveKitTOMLFile))
require.NoError(t, err)
require.Equal(t, `[project]
subdomain = "proj"

[agent]
name = "my-agent"

[cloud]
id = "CA_a"
`, string(raw))

loaded, _, err := LoadTOMLFile(dir, LiveKitTOMLFile)
require.NoError(t, err)
require.Equal(t, cfg.Agent.Name, loaded.Agent.Name)
require.Equal(t, cfg.AgentID(), loaded.AgentID())
}
Loading