Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(agent): read Kimi session logs from the task home (#11081)

Danila Katalshovee8c77979767
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index c7d6d58eaa..8420941eaf 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -983,14 +983,14 @@ func ClaudeConfigDir(extraEnv map[string]string, cwd string) (string, error) {
}
func claudeConfigDir(env []string, cwd string) (string, error) {
- if value, ok := lastClaudeEnvValue(env, "CLAUDE_CONFIG_DIR"); ok && value != "" {
+ if value, ok := lastAgentEnvValue(env, "CLAUDE_CONFIG_DIR"); ok && value != "" {
return resolveClaudeConfigPath(value, cwd)
}
if runtime.GOOS == "windows" {
- if value, ok := lastClaudeEnvValue(env, "USERPROFILE"); ok && value != "" {
+ if value, ok := lastAgentEnvValue(env, "USERPROFILE"); ok && value != "" {
return resolveClaudeConfigPath(filepath.Join(value, ".claude"), cwd)
}
- } else if value, ok := lastClaudeEnvValue(env, "HOME"); ok && value != "" {
+ } else if value, ok := lastAgentEnvValue(env, "HOME"); ok && value != "" {
return resolveClaudeConfigPath(filepath.Join(value, ".claude"), cwd)
}
home, err := os.UserHomeDir()
@@ -1021,7 +1021,7 @@ func resolveClaudeConfigPath(path, cwd string) (string, error) {
return absolutePath, nil
}
-func lastClaudeEnvValue(env []string, key string) (string, bool) {
+func lastAgentEnvValue(env []string, key string) (string, bool) {
for i := len(env) - 1; i >= 0; i-- {
name, value, ok := strings.Cut(env[i], "=")
matches := name == key
diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.go
index a04f3a4714..c6b10170b6 100644
--- a/server/pkg/agent/kimi.go
+++ b/server/pkg/agent/kimi.go
@@ -11,6 +11,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "runtime"
"strings"
"sync/atomic"
"time"
@@ -74,6 +75,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
cmd.Dir = opts.Cwd
}
cmd.Env = buildEnv(b.cfg.Env)
+ kimiHome := kimiChildHome(cmd.Env, cmd.Dir)
stdout, err := cmd.StdoutPipe()
if err != nil {
@@ -495,6 +497,13 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
fallbackModel = "unknown"
}
+ wireScan := kimiUsageScan{
+ startTime: startTime,
+ kimiHome: kimiHome,
+ sessionID: sessionID,
+ resumed: opts.ResumeSessionID != "",
+ fallbackModel: fallbackModel,
+ }
var usageMap map[string]TokenUsage
if acpTokenUsagePresent(u) {
usageMap = map[string]TokenUsage{fallbackModel: u}
@@ -502,13 +511,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
// Keyed per model by the scan itself: a task whose subagent
// or compaction step ran on a different model must not have
// that model's tokens priced at the main model's rate.
- usageMap = scanKimiSessionUsage(kimiUsageScan{
- startTime: startTime,
- kimiHome: b.cfg.Env["KIMI_CODE_HOME"],
- sessionID: sessionID,
- resumed: opts.ResumeSessionID != "",
- fallbackModel: fallbackModel,
- })
+ usageMap = scanKimiSessionUsage(wireScan)
// A future Kimi build may expose provider cost before it exposes
// token buckets over ACP. Preserve that cost alongside the current
// wire-log fallback instead of dropping either source.
@@ -532,13 +535,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
// completed run is promoted: timeout/abort/already-failed keep
// their own terminal semantics.
if finalStatus == "completed" {
- if turnErr, failed := scanKimiMainTurnFailure(kimiUsageScan{
- startTime: startTime,
- kimiHome: b.cfg.Env["KIMI_CODE_HOME"],
- sessionID: sessionID,
- resumed: opts.ResumeSessionID != "",
- fallbackModel: fallbackModel,
- }); failed {
+ if turnErr, failed := scanKimiMainTurnFailure(wireScan); failed {
finalStatus = "failed"
finalError = "kimi turn failed: runtime did not record error details (error category unknown)"
if turnErr != "" {
@@ -902,34 +899,32 @@ func kimiWireTurnFailure(path string, scan kimiUsageScan) (string, bool) {
return detail, found
}
-// kimiSessionRoot resolves kimi's session directory: an explicitly configured
-// home first, then the ambient KIMI_CODE_HOME, then ~/.kimi-code. Mirrors
-// codexSessionRoot.
-//
-// The env lookup is not redundant with cfg.Env: the kimi subprocess inherits
-// os.Environ() via buildEnv, so a KIMI_CODE_HOME exported to the daemon
-// relocates kimi's sessions without ever appearing in cfg.Env. Reading only
-// cfg.Env would leave the scan looking in ~/.kimi-code while kimi wrote
-// somewhere else. The stat check keeps a home without a sessions directory
-// from disabling the scan.
-func kimiSessionRoot(kimiHome string) string {
- if kimiHome = strings.TrimSpace(kimiHome); kimiHome == "" {
- kimiHome = strings.TrimSpace(os.Getenv("KIMI_CODE_HOME"))
- }
- if kimiHome != "" {
- dir := filepath.Join(kimiHome, "sessions")
- if info, err := os.Stat(dir); err == nil && info.IsDir() {
- return dir
+// kimiChildHome follows the data directory selected by the launched CLI.
+func kimiChildHome(env []string, cwd string) string {
+ home, _ := lastAgentEnvValue(env, "KIMI_CODE_HOME")
+ if home == "" {
+ homeKey := "HOME"
+ if runtime.GOOS == "windows" {
+ homeKey = "USERPROFILE"
+ }
+ userHome, _ := lastAgentEnvValue(env, homeKey)
+ if userHome == "" {
+ userHome, _ = os.UserHomeDir()
}
+ if userHome == "" {
+ return ""
+ }
+ home = filepath.Join(userHome, ".kimi-code")
+ }
+ if cwd != "" && !filepath.IsAbs(home) {
+ home = filepath.Join(cwd, home)
}
+ return home
+}
- home, err := os.UserHomeDir()
- if err != nil {
+func kimiSessionRoot(kimiHome string) string {
+ if kimiHome == "" {
return ""
}
- dir := filepath.Join(home, ".kimi-code", "sessions")
- if info, err := os.Stat(dir); err == nil && info.IsDir() {
- return dir
- }
- return ""
+ return filepath.Join(kimiHome, "sessions")
}
diff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.go
index c4472f1ef8..8a03f7eb63 100644
--- a/server/pkg/agent/kimi_test.go
+++ b/server/pkg/agent/kimi_test.go
@@ -1328,7 +1328,7 @@ while IFS= read -r line; do
printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"session_e2e"}}\n' "$id"
;;
*'"method":"session/prompt"'*)
- dir="$KIMI_CODE_HOME/sessions/wd_test_abc123/session_e2e/agents/main"
+ dir="${KIMI_CODE_HOME:-$HOME/.kimi-code}/sessions/wd_test_abc123/session_e2e/agents/main"
mkdir -p "$dir"
# The scan drops records stamped before the turn began, so the test
# injects the timestamp. ` + "`date +%s`" + ` would truncate to the start of
@@ -1398,20 +1398,31 @@ func TestKimiBackendPropagatesACPPromptUsage(t *testing.T) {
// with its real token split, keyed by the model the wire log names.
func TestKimiBackendReportsUsageFromWireLog(t *testing.T) {
t.Parallel()
+ assertKimiBackendReportsWireUsage(t, map[string]string{"KIMI_CODE_HOME": t.TempDir()}, "")
+}
+
+func TestKimiBackendReportsWireUsageFromRelativeHome(t *testing.T) {
+ t.Parallel()
+ assertKimiBackendReportsWireUsage(t, map[string]string{"KIMI_CODE_HOME": "runtime-data"}, t.TempDir())
+}
- kimiHome := t.TempDir()
+func TestKimiBackendReportsWireUsageFromTaskHome(t *testing.T) {
+ // Exercise the backend's HOME fallback. The daemon rejects HOME in custom agent environments.
+ t.Setenv("KIMI_CODE_HOME", "")
+ assertKimiBackendReportsWireUsage(t, map[string]string{"HOME": t.TempDir()}, "")
+}
+
+func assertKimiBackendReportsWireUsage(t *testing.T, env map[string]string, cwd string) {
+ t.Helper()
fakePath := filepath.Join(t.TempDir(), "kimi")
writeTestExecutable(t, fakePath, []byte(fakeKimiACPNoUsageScript()))
+ // Timestamp the record comfortably after the turn starts.
+ env["KIMI_TEST_RECORD_TIME"] = strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)
backend, err := New("kimi", Config{
ExecutablePath: fakePath,
Logger: slog.Default(),
- Env: map[string]string{
- "KIMI_CODE_HOME": kimiHome,
- // Comfortably after the turn's startTime, so the assertion
- // tests the scan rather than clock granularity.
- "KIMI_TEST_RECORD_TIME": strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10),
- },
+ Env: env,
})
if err != nil {
t.Fatalf("new kimi backend: %v", err)
@@ -1420,7 +1431,7 @@ func TestKimiBackendReportsUsageFromWireLog(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
- session, err := backend.Execute(ctx, "task", ExecOptions{Timeout: 20 * time.Second})
+ session, err := backend.Execute(ctx, "task", ExecOptions{Cwd: cwd, Timeout: 20 * time.Second})
if err != nil {
t.Fatalf("execute: %v", err)
}
@@ -1553,25 +1564,18 @@ func TestScanKimiSessionUsageFallbackModel(t *testing.T) {
}
}
-// TestKimiSessionRootPrefersConfiguredThenEnv pins the discovery order.
-// The kimi subprocess inherits os.Environ() via buildEnv, so a KIMI_CODE_HOME
-// exported to the daemon relocates kimi's sessions without ever reaching
-// cfg.Env — reading only cfg.Env would scan the wrong directory.
-func TestKimiSessionRootPrefersConfiguredThenEnv(t *testing.T) {
- configured := t.TempDir()
- fromEnv := t.TempDir()
- for _, dir := range []string{configured, fromEnv} {
- if err := os.MkdirAll(filepath.Join(dir, "sessions"), 0o755); err != nil {
- t.Fatalf("mkdir: %v", err)
- }
+func TestKimiChildHomeUsesEffectiveEnvironment(t *testing.T) {
+ inherited := t.TempDir()
+ override := t.TempDir()
+ t.Setenv("KIMI_CODE_HOME", inherited)
+ if got := kimiChildHome(buildEnv(nil), ""); got != inherited {
+ t.Errorf("inherited KIMI_CODE_HOME = %q, want %q", got, inherited)
}
- t.Setenv("KIMI_CODE_HOME", fromEnv)
-
- if got, want := kimiSessionRoot(configured), filepath.Join(configured, "sessions"); got != want {
- t.Errorf("explicit config should win: got %q, want %q", got, want)
+ if got := kimiChildHome(buildEnv(map[string]string{"KIMI_CODE_HOME": override}), ""); got != override {
+ t.Errorf("overridden KIMI_CODE_HOME = %q, want %q", got, override)
}
- if got, want := kimiSessionRoot(""), filepath.Join(fromEnv, "sessions"); got != want {
- t.Errorf("ambient KIMI_CODE_HOME should be used: got %q, want %q", got, want)
+ if got, want := kimiChildHome(buildEnv(map[string]string{"KIMI_CODE_HOME": "kimi-data"}), override), filepath.Join(override, "kimi-data"); got != want {
+ t.Errorf("relative KIMI_CODE_HOME = %q, want %q", got, want)
}
}
@@ -1812,14 +1816,13 @@ done
func TestKimiBackendWireTurnFailureFailsCompletedRun(t *testing.T) {
t.Parallel()
- home := t.TempDir()
fakePath := filepath.Join(t.TempDir(), "kimi")
writeTestExecutable(t, fakePath, []byte(fakeKimiWireTurnFailureScript("ses_wirefail")))
backend, err := New("kimi", Config{
ExecutablePath: fakePath,
Logger: slog.Default(),
- Env: map[string]string{"KIMI_CODE_HOME": home},
+ Env: map[string]string{"KIMI_CODE_HOME": "runtime-data"},
})
if err != nil {
t.Fatalf("new kimi backend: %v", err)
@@ -1828,7 +1831,7 @@ func TestKimiBackendWireTurnFailureFailsCompletedRun(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
- session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second})
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Cwd: t.TempDir(), Timeout: 5 * time.Second})
if err != nil {
t.Fatalf("execute: %v", err)
}