feat(kap-server): reclaim idle sessions (#4284)

* feat(kap-server): reclaim idle sessions

* test: trim idle session reclaim test duplication

* test: fix idle reaper fake typing

* fix(kap-server): preserve session state during idle reclaim

* fix(kap-server): resume cold sessions for tool routes

* fix(kap-server): report failed WS session resumes

* refactor(agent-core-v2): let features declare session idle retention

Move the cron, goal, and lifecycle-hook reclaim guards out of SessionManager
into a SessionRetentionContribution collection that each feature contributes,
check retention once under the session lease, and drop the dead optional
task-service branches in the tasks route.

* refactor(agent-core-v2): measure session idle from the activity view

* refactor(agent-core-v2): reclaim idle sessions silently instead of retaining hooked sessions

* fix(kap-server): only resume explicitly requested sessions in tool routes

* refactor(agent-core-v2): inline the cron idle-reclaim guard and stop retaining active goals

* fix(kap-server): reject invalid idle reclaim timeouts

* fix(kap-server): preserve rating evaluation across idle reclaim

* test(kap-server): trim idle reclaim tests

* fix(kap-server): validate idle reclaim config early

* refactor(agent-core-v2): rename the reclaim resume source and derive lifecycle literal unions

* refactor(agent-core-v2): keep the reclaim lifecycle tags off the public lifecycle interface

* fix(agent-core-v2): drop the reclaim marker once a session is archived

* Implement session unload after 30 minutes of idle time

Updated session management to unload sessions after 30 minutes of inactivity for both web and desktop applications.

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* fix(agent-core-v2): reclaim sessions with exited terminals

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
This commit is contained in:
7Sageer 2026-10-21 19:27:25 +08:00 • committed by GitHub
parent 256ce61f0c
commit 366fafbf92
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
32 changed files with 725 additions and 70 deletions

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": minor
---
Sessions in web and desktop now unload from memory after 30 minutes idle and resume transparently on next access.

View file

@ -140,6 +140,7 @@ Switches that control the behavior of subsystems such as telemetry, background t
| --- | --- | --- |
| `KIMI_DISABLE_TELEMETRY` | Disable anonymous telemetry reporting | `1`, `true`, `yes`, `y` (case-insensitive) |
| `KIMI_CODE_PASSWORD` | Parallel auth credential for `kimi web`, recommended when binding beyond loopback (see [Security notes](../guides/web.md#security-notes)) | Any non-empty string; when unset, only the token is valid |
| `KIMI_CODE_SESSION_IDLE_RECLAIM_MS` | How long (ms) a `kimi web` session may stay idle before it is unloaded from memory; the session resumes transparently on next access (default `1800000`; `0` = never unload) | Non-negative integer; invalid values fail fast |
| `KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT` | Keep background tasks when the session closes; higher priority than `config.toml` (default: stop them on exit) | Truthy: `1`/`true`/`yes`/`on`; falsy: `0`/`false`/`no`/`off` |
| `KIMI_CODE_BACKGROUND_MAX_RUNNING_TASKS` | Cap on concurrently running background tasks; higher priority than `[background] max_running_tasks` (unset = no cap) | Positive integer; invalid values are ignored |
| `KIMI_CODE_BACKGROUND_BASH_TASK_TIMEOUT_S` | Default timeout (seconds) for background `Bash` tasks, also used to re-arm foreground commands moved to the background; higher priority than `[task] bash_task_timeout_s` (`0` = no timeout) | Non-negative integer; invalid values are ignored |

View file

@ -117,8 +117,8 @@ Only **blockable events** (`PreToolUse`, `Stop`, `UserPromptSubmit`) have return
| `PermissionRequest` | Tool name | — | Triggered just before waiting for user approval |
| `PermissionResult` | Tool name | — | Triggered after approval completes |
| `SessionStart` | `startup` or `resume` | — | Triggered after a session starts or resumes; payload includes `source`, `model`, `profile` |
| `SessionEnd` | `exit` or `archive` | — | Triggered after a session closes; `archive` means the session was archived rather than exited |
| `SessionHeartbeat` | Empty string | — | Triggered every 60 seconds while the session is alive; the timer runs only when this event is configured; payload includes `uptime_ms` |
| `SessionEnd` | `exit` or `archive` | — | Triggered after a session closes; `archive` means the session was archived rather than exited; not triggered when `kimi web` unloads an idle session from memory, nor when such an unloaded session is later archived or deleted; the transparent reload does not trigger `SessionStart` |
| `SessionHeartbeat` | Empty string | — | Triggered every 60 seconds while the session is alive; the timer runs only when this event is configured; payload includes `uptime_ms`; pauses while `kimi web` has the session unloaded, and `uptime_ms` restarts after reload |
| `SubagentStart` | Sub-agent name | — | Triggered before a sub-agent starts running |
| `SubagentStop` | Sub-agent name | — | Triggered after a sub-agent completes successfully |
| `TaskStarted` | Task kind (`agent`, `process`, or `question`) | — | Triggered when a background task starts; payload includes `task_id`, `description`, `detached` |

View file

@ -140,6 +140,7 @@ kimi
| --- | --- | --- |
| `KIMI_DISABLE_TELEMETRY` | 关闭匿名遥测上报 | `1`、`true`、`yes`、`y`(不区分大小写) |
| `KIMI_CODE_PASSWORD` | 为 `kimi web` 本地服务设置并列鉴权密码;绑到非本机地址时建议设置,见 [安全注意](../guides/web.md#安全注意) | 任意非空字符串;未设置时仅 token 有效 |
| `KIMI_CODE_SESSION_IDLE_RECLAIM_MS` | `kimi web` 会话空闲多久(毫秒)后从内存卸载;之后访问会自动恢复(默认 `1800000`;`0` 表示不卸载) | 非负整数;非法值会立即失败 |
| `KIMI_CODE_BACKGROUND_KEEP_ALIVE_ON_EXIT` | 会话关闭时是否保留后台任务,优先级高于 `config.toml`。默认会在退出时停止后台任务 | 真值:`1`/`true`/`yes`/`on`;假值:`0`/`false`/`no`/`off` |
| `KIMI_CODE_BACKGROUND_MAX_RUNNING_TASKS` | 同时运行的后台任务数上限,优先级高于 `config.toml` 的 `[background] max_running_tasks`;不设置表示无上限 | 正整数;非法值被忽略 |
| `KIMI_CODE_BACKGROUND_BASH_TASK_TIMEOUT_S` | 后台 `Bash` 任务的默认超时(秒),也用于前台命令转入后台后的重新计时,优先级高于 `[task] bash_task_timeout_s`;`0` 表示无超时 | 非负整数;非法值被忽略 |

View file

@ -117,8 +117,8 @@ Hook 命令的工作目录是当前会话的项目目录。
| `PermissionRequest` | 工具名 | — | 即将等待用户审批前触发 |
| `PermissionResult` | 工具名 | — | 审批结束后触发 |
| `SessionStart` | `startup` 或 `resume` | — | 新会话启动或历史会话恢复后触发;payload 含 `source`、`model`、`profile` |
| `SessionEnd` | `exit` 或 `archive` | — | 会话关闭后触发;`archive` 表示会话被归档而非退出 |
| `SessionHeartbeat` | 空字符串 | — | 会话存活期间每 60 秒触发一次,仅配置本事件时计时器才运行;payload 含 `uptime_ms` |
| `SessionEnd` | `exit` 或 `archive` | — | 会话关闭后触发;`archive` 表示会话被归档而非退出;`kimi web` 将空闲会话从内存卸载时不触发,之后归档或删除这个已卸载的会话也不触发;透明恢复不触发 `SessionStart` |
| `SessionHeartbeat` | 空字符串 | — | 会话存活期间每 60 秒触发一次,仅配置本事件时计时器才运行;payload 含 `uptime_ms`;`kimi web` 卸载会话期间暂停,恢复后 `uptime_ms` 重新计时 |
| `SubagentStart` | subagent 名称 | — | subagent 开始运行前触发 |
| `SubagentStop` | subagent 名称 | — | subagent 成功完成后触发 |
| `TaskStarted` | 任务类型(`agent`、`process` 或 `question`) | — | 后台任务启动时触发;payload 含 `task_id`、`description`、`detached` |

View file

@ -45,6 +45,7 @@ export interface ISessionManager {
): Promise<T>;
list(): readonly ISessionScopeHandle[];
close(sessionId: string): Promise<void>;
closeIfIdle(sessionId: string, idleTimeoutMs: number): Promise<boolean>;
archive(sessionId: string): Promise<void>;
restore(sessionId: string, options?: ResumeSessionOptions): Promise<ISessionScopeHandle | undefined>;
delete(sessionId: string): Promise<void>;

View file

@ -3,9 +3,14 @@ import { DisposableStore } from '#/_base/di/lifecycle';
import { Emitter, type Event, type IWaitUntil } from '#/_base/event';
import { ScopeActivation, registerScopedService, type ISessionScopeHandle } from '#/_base/di/scope';
import { LifecycleScope } from '#/app/scopes';
import { Error2, ErrorCodes } from '#/errors';
import { Error2, ErrorCodes, isError2, SessionErrors } from '#/errors';
import { ISessionIndex, type SessionSummary } from '#/app/sessionIndex/sessionIndex';
import { IAgentCronService } from '#/features/cron/cronService';
import type { SessionMeta } from '#/session/sessionMetadata/sessionMetadata';
import { ISessionLockService, type SessionLockLease } from '#/persistence/interface/sessionLock';
import { IAgentLifecycleService } from '#/session/agentLifecycle/agentLifecycle';
import { ISessionActivityView } from '#/session/sessionActivity/sessionActivity';
import { ISessionTerminalService } from '#/session/terminal/terminalService';
import {
type CreateChildSessionOptions,
type ForkSessionOptions,
@ -39,6 +44,7 @@ export class SessionManager implements ISessionManager {
private readonly owners = new Map<string, SessionLifecycleService>();
private readonly pendingResumes = new Map<string, Promise<ISessionScopeHandle | undefined>>();
private readonly resumeFailures = new Map<string, Error>();
private readonly reclaimed = new Set<string>();
private readonly lifecycleChains = new Map<string, Promise<void>>();
private readonly controllers = new Map<string, SessionControllerEntry>();
private readonly controllerEntries = new Set<SessionControllerEntry>();
@ -60,6 +66,7 @@ export class SessionManager implements ISessionManager {
constructor(
@IWorkspaceInstanceManager private readonly workspaces: IWorkspaceInstanceManager,
@ISessionIndex private readonly index: ISessionIndex,
@ISessionLockService private readonly sessionLocks: ISessionLockService,
) {}
async create(options: CreateManagedSessionOptions): Promise<ISessionScopeHandle> {
@ -78,7 +85,11 @@ export class SessionManager implements ISessionManager {
if (inflight !== undefined) return inflight;
this.resumeFailures.delete(sessionId);
const promise = this.serializeLifecycle(sessionId, async () =>
(await this.controllerForSession(sessionId))?.resume(sessionId, options),
(await this.controllerForSession(sessionId))?.resume(
sessionId,
options,
this.reclaimed.has(sessionId) ? 'reclaimed' : 'resume',
),
).finally(() => this.pendingResumes.delete(sessionId));
this.pendingResumes.set(sessionId, promise);
void promise.catch((error: unknown) => {
@ -123,7 +134,7 @@ export class SessionManager implements ISessionManager {
}
private lifecycleKeys(...ids: (string | undefined)[]): string[] {
return [...new Set(ids.filter((id): id is string => id !== undefined))].sort();
return [...new Set(ids.filter((id): id is string => id !== undefined))].toSorted();
}
withLifecycleSerialization<T>(
@ -146,8 +157,45 @@ export class SessionManager implements ISessionManager {
await this.serializeLifecycle(sessionId, async () => this.owners.get(sessionId)?.close(sessionId));
}
async closeIfIdle(sessionId: string, idleTimeoutMs: number): Promise<boolean> {
return this.serializeLifecycle(sessionId, async () => {
const handle = this.sessions.get(sessionId);
const owner = this.owners.get(sessionId);
if (handle === undefined || owner === undefined) return false;
if (Date.now() - handle.accessor.get(ISessionActivityView).lastActiveAt() < idleTimeoutMs) return false;
let lease: SessionLockLease;
try {
lease = this.sessionLocks.lease(sessionId);
} catch (error) {
if (isError2(error) && error.code === SessionErrors.codes.SESSION_OCCUPIED) return false;
throw error;
}
try {
if (await this.retained(handle)) return false;
await owner.close(sessionId, 'reclaim');
this.reclaimed.add(sessionId);
return true;
} finally {
lease.release();
}
});
}
private async retained(handle: ISessionScopeHandle): Promise<boolean> {
const terminals = await handle.accessor.get(ISessionTerminalService).list();
if (terminals.some((terminal) => terminal.status === 'running')) return true;
const agents = handle.accessor.get(IAgentLifecycleService);
const hasCron = agents
.list()
.some((agent) => (agents.handleOf(agent.agentId)?.accessor.get(IAgentCronService).list().length ?? 0) > 0);
if (hasCron) return true;
const activity = handle.accessor.get(ISessionActivityView).state();
return activity.busy || activity.pendingInteraction !== 'none';
}
private async archiveInner(sessionId: string): Promise<void> {
await (await this.controllerForSession(sessionId))?.archive(sessionId);
this.reclaimed.delete(sessionId);
}
async archive(sessionId: string): Promise<void> {
@ -186,6 +234,7 @@ export class SessionManager implements ISessionManager {
const failed = settled.find((result) => result.status === 'rejected');
if (failed?.status === 'rejected') throw failed.reason;
await controller.delete(sessionId);
this.reclaimed.delete(sessionId);
});
}
@ -222,7 +271,7 @@ export class SessionManager implements ISessionManager {
}
dispose(): void {
for (const { controller, subscriptions } of [...this.controllerEntries].reverse()) {
for (const { controller, subscriptions } of [...this.controllerEntries].toReversed()) {
subscriptions.dispose();
controller.dispose();
}
@ -230,6 +279,7 @@ export class SessionManager implements ISessionManager {
this.controllers.clear();
this.sessions.clear();
this.owners.clear();
this.reclaimed.clear();
this.willCreateEmitter.dispose();
this.didCreateEmitter.dispose();
this.willCloseEmitter.dispose();
@ -251,6 +301,7 @@ export class SessionManager implements ISessionManager {
subscriptions.add(controller.onWillCreateSession((event) => this.willCreateEmitter.fire(event)));
subscriptions.add(controller.onDidCreateSession((event) => {
entry.sessionCount += 1;
this.reclaimed.delete(event.sessionId);
this.sessions.set(event.sessionId, event.handle);
this.owners.set(event.sessionId, controller);
this.didCreateEmitter.fire(event);

View file

@ -1,4 +1,5 @@
import type { TowerExitReason } from '#/features/tower/tower';
import type { SessionCloseReason } from '#/workspace/sessionLifecycle/sessionLifecycle';
import type { TelemetryPrimitive } from './telemetry';
@ -594,7 +595,7 @@ export interface AgentCreateFailedEvent {
}
export interface SessionEndedEvent {
reason: 'exit' | 'archive';
reason: SessionCloseReason;
}
export interface WebFetchFallbackEvent {

View file

@ -20,7 +20,8 @@ import {
import { IExternalHooksRunnerService } from '../app/externalHooksRunner';
import { ISessionExternalHooksService } from './sessionExternalHooks';
type SessionStartHookSource = Exclude<SessionCreateSource, 'fork'>;
type SessionStartHookSource = Exclude<SessionCreateSource, 'fork' | 'reclaimed'>;
type SessionEndHookReason = Exclude<SessionCloseReason, 'reclaim'>;
const HEARTBEAT_INTERVAL_MS = 60_000;
@ -65,7 +66,7 @@ export class SessionExternalHooksService
this._register(
onDidCreate((event) => {
if (event.sessionId !== this.context.sessionId) return;
if (event.source !== 'fork') {
if (event.source !== 'fork' && event.source !== 'reclaimed') {
event.waitUntil(this.triggerSessionStart(event.source));
}
}),
@ -75,7 +76,7 @@ export class SessionExternalHooksService
if (onWillClose !== undefined) {
this._register(
onWillClose((event) => {
if (event.sessionId !== this.context.sessionId) return;
if (event.sessionId !== this.context.sessionId || event.reason === 'reclaim') return;
event.waitUntil(this.triggerSessionEnd(event.reason));
}),
);
@ -129,7 +130,7 @@ export class SessionExternalHooksService
}
}
private async triggerSessionEnd(reason: SessionCloseReason): Promise<void> {
private async triggerSessionEnd(reason: SessionEndHookReason): Promise<void> {
await this.runner.trigger('SessionEnd', {
matcherValue: reason,
cwd: this.context.cwd,

View file

@ -29,6 +29,8 @@ export interface ISessionActivityView {
state(): SessionActivityState;
lastActiveAt(): number;
readonly onDidChange: Event<SessionActivityChangedEvent>;
}

View file

@ -64,6 +64,7 @@ export class SessionActivityView extends Disposable implements ISessionActivityV
readonly onDidChange: Event<SessionActivityChangedEvent> = this._onDidChange.event;
private readonly agentSubscriptions = new Map<string, IDisposable>();
private activeAt = Date.now();
constructor(
@ISessionStateService private readonly states: ISessionStateService,
@ -120,6 +121,10 @@ export class SessionActivityView extends Disposable implements ISessionActivityV
return this.current;
}
lastActiveAt(): number {
return this.activeAt;
}
private attachAgent(handle: IAgentScopeHandle): void {
if (this.folds.has(handle.id)) return;
this.folds.set(handle.id, seedFold(handle));
@ -211,6 +216,7 @@ export class SessionActivityView extends Disposable implements ISessionActivityV
const next = this.aggregate();
if (activityEquals(this.current, next)) return;
this.current = next;
this.activeAt = Date.now();
this._onDidChange.fire({ state: next, cause });
}

View file

@ -5,9 +5,9 @@ import type { BindAgentInput } from '#/agent/profile/profile';
import type { McpServerConfig } from '#/mcpCore/config-schema';
import type { SessionMeta } from '#/session/sessionMetadata/sessionMetadata';
export type SessionCreateSource = 'startup' | 'resume' | 'fork';
export type SessionCreateSource = 'startup' | 'resume' | 'reclaimed' | 'fork';
export type SessionCloseReason = 'exit' | 'archive';
export type SessionCloseReason = 'exit' | 'reclaim' | 'archive';
export interface CreateSessionOptions {
readonly sessionId?: string;

View file

@ -33,6 +33,7 @@ import { CHILD_SESSION_KIND,
PARENT_SESSION_ID_KEY,
} from '#/app/sessionIndex/sessionIndex';
import { buildSessionSummary } from '#/app/sessionIndex/sessionIndexSource';
import type { SessionEndedEvent } from '#/app/telemetry/events';
import { ITelemetryService } from '#/app/telemetry/telemetry';
import { bindTelemetryScope } from '#/app/telemetry/telemetryService';
import { ErrorCodes, Error2, isError2 } from '#/errors';
@ -112,7 +113,9 @@ import {
type ResumeSessionOptions,
type SessionArchivedEvent,
type SessionClosedEvent,
type SessionCloseReason,
type SessionCreatedEvent,
type SessionCreateSource,
type SessionForkedEvent,
type SessionWillCloseEvent,
type SessionWillCreateEvent,
@ -342,7 +345,7 @@ export class SessionLifecycleService extends Disposable implements ISessionLifec
private async announceCreated(event: SessionCreatedEvent): Promise<void> {
await this._onDidCreateSession.fireAsync(event, NO_ABORT);
event.handle.accessor.get(ITelemetryService).track2('session_started', {
resumed: event.source === 'resume',
resumed: event.source !== 'startup',
experimental_flags: this.flags.exposedIds().toSorted().join(','),
});
}
@ -352,13 +355,17 @@ export class SessionLifecycleService extends Disposable implements ISessionLifec
return this.sessions.get(sessionId);
}
resume(sessionId: string, opts?: ResumeSessionOptions): Promise<ISessionScopeHandle | undefined> {
resume(
sessionId: string,
opts?: ResumeSessionOptions,
source: Extract<SessionCreateSource, 'resume' | 'reclaimed'> = 'resume',
): Promise<ISessionScopeHandle | undefined> {
const inflight = this.resuming.get(sessionId);
if (inflight !== undefined) return inflight;
const live = this.sessions.get(sessionId);
if (live !== undefined) return Promise.resolve(live);
this.resumeFailures.delete(sessionId);
const promise = this.doResume(sessionId, opts)
const promise = this.doResume(sessionId, source, opts)
.catch((error: unknown) => {
this.telemetry
.withContext({ session_id: sessionId })
@ -381,6 +388,7 @@ export class SessionLifecycleService extends Disposable implements ISessionLifec
private async doResume(
sessionId: string,
source: SessionCreateSource,
opts?: ResumeSessionOptions,
): Promise<ISessionScopeHandle | undefined> {
const live = this.sessions.get(sessionId);
@ -401,7 +409,7 @@ export class SessionLifecycleService extends Disposable implements ISessionLifec
if (agents.get(MAIN_AGENT_ID) === undefined) {
await agents.create({ agentId: MAIN_AGENT_ID });
}
await this.announceCreated({ sessionId, handle, source: 'resume' });
await this.announceCreated({ sessionId, handle, source });
} catch (error) {
this.sessions.delete(sessionId);
void handle.dispose();
@ -418,10 +426,10 @@ export class SessionLifecycleService extends Disposable implements ISessionLifec
return ready;
}
async close(sessionId: string): Promise<void> {
async close(sessionId: string, reason: Exclude<SessionCloseReason, 'archive'> = 'exit'): Promise<void> {
const handle = this.sessions.get(sessionId);
if (handle === undefined) return;
await this.announceWillClose({ sessionId, handle, reason: 'exit' });
await this.announceWillClose({ sessionId, handle, reason });
this.sessions.delete(sessionId);
await this.drainAgents(handle);
await this.appendLogStore.drainRetirements();
@ -430,7 +438,8 @@ export class SessionLifecycleService extends Disposable implements ISessionLifec
void handle.dispose();
await drainLogCloses();
this._onDidCloseSession.fire({ sessionId });
this.telemetry.withContext({ session_id: sessionId }).track2('session_ended', { reason: 'exit' });
const ended: SessionEndedEvent = { reason };
this.telemetry.withContext({ session_id: sessionId }).track2('session_ended', ended);
}
async archive(sessionId: string): Promise<void> {

View file

@ -899,6 +899,7 @@ function registerSessionExportServices(
): Promise<T> => work({ archive: async () => {}, restore: async () => undefined }),
list: () => (options.lifecycleHandle === undefined ? [] : [options.lifecycleHandle]),
close: async () => {},
closeIfIdle: async () => false,
archive: async () => {},
restore: async () => options.lifecycleHandle,
delete: async () => {},

View file

@ -1,4 +1,4 @@
import { describe, expect, it, vi } from 'vitest';
import { describe, expect, it, vi, afterEach, beforeEach } from 'vitest';
import { Emitter, Event } from '#/_base/event';
import type { ISessionScopeHandle } from '#/_base/di/scope';
@ -9,14 +9,21 @@ import { ISessionManager } from '#/app/sessionManager/sessionManager';
import { reloadOnStale } from '#/app/sessionManager/sessionLookup';
import { SessionManager } from '#/app/sessionManager/sessionManagerService';
import { ErrorCodes } from '#/errors';
import { IAgentCronService } from '#/features/cron/cronService';
import { InMemorySessionLockService } from '#/persistence/backends/memory/sessionLockService';
import { Program } from '#/program/program';
import type { ProgramSessionControllerInput } from '#/program/programDependencies';
import { FakeRuntime } from '#/runtime/fakeRuntime';
import { RuntimeRegistry } from '#/runtime/runtimeRegistry';
import { IAgentLifecycleService } from '#/session/agentLifecycle/agentLifecycle';
import { ISessionActivityView } from '#/session/sessionActivity/sessionActivity';
import { ISessionTerminalService } from '#/session/terminal/terminalService';
import type {
SessionArchivedEvent,
SessionCloseReason,
SessionClosedEvent,
SessionCreatedEvent,
SessionCreateSource,
SessionWillCreateEvent,
} from '#/workspace/sessionLifecycle/sessionLifecycle';
import type { SessionLifecycleService } from '#/workspace/sessionLifecycle/sessionLifecycleService';
@ -109,7 +116,7 @@ describe('SessionManager', () => {
const index = {
get: async () => ({ workspaceId: 'workspace-1', cwd: '/workspace' }),
} as unknown as ISessionIndex;
const manager = new SessionManager(workspaces, index);
const manager = new SessionManager(workspaces, index, new InMemorySessionLockService());
const resumePromise = manager.resume('session-1');
const section = manager.withLifecycleSerialization('session-1', async () => {
@ -137,7 +144,7 @@ describe('SessionManager', () => {
const index = {
get: async () => ({ workspaceId: 'workspace-1', cwd: '/workspace' }),
} as unknown as ISessionIndex;
const manager = new SessionManager(workspaces, index);
const manager = new SessionManager(workspaces, index, new InMemorySessionLockService());
let releaseSection!: () => void;
const sectionGate = new Promise<void>((resolve) => {
@ -178,7 +185,7 @@ describe('SessionManager', () => {
const index = {
get: async () => ({ workspaceId: 'workspace-1', cwd: '/workspace' }),
} as unknown as ISessionIndex;
const manager = new SessionManager(workspaces, index);
const manager = new SessionManager(workspaces, index, new InMemorySessionLockService());
let releaseSection!: () => void;
const sectionGate = new Promise<void>((resolve) => {
@ -216,7 +223,7 @@ describe('SessionManager', () => {
const index = {
get: async () => ({ workspaceId: 'workspace-1', cwd: '/workspace' }),
} as unknown as ISessionIndex;
const manager = new SessionManager(workspaces, index);
const manager = new SessionManager(workspaces, index, new InMemorySessionLockService());
let releaseSection!: () => void;
const sectionGate = new Promise<void>((resolve) => {
@ -254,7 +261,7 @@ describe('SessionManager', () => {
const index = {
get: async () => ({ workspaceId: 'workspace-1', cwd: '/workspace' }),
} as unknown as ISessionIndex;
const manager = new SessionManager(workspaces, index);
const manager = new SessionManager(workspaces, index, new InMemorySessionLockService());
let releaseSection!: () => void;
const sectionGate = new Promise<void>((resolve) => {
@ -292,7 +299,7 @@ describe('SessionManager', () => {
const index = {
get: async () => ({ workspaceId: 'workspace-1', cwd: '/workspace' }),
} as unknown as ISessionIndex;
const manager = new SessionManager(workspaces, index);
const manager = new SessionManager(workspaces, index, new InMemorySessionLockService());
let releaseSection!: () => void;
const sectionGate = new Promise<void>((resolve) => {
@ -330,7 +337,7 @@ describe('SessionManager', () => {
const index = {
get: async () => ({ workspaceId: 'workspace-1', cwd: '/workspace' }),
} as unknown as ISessionIndex;
const manager = new SessionManager(workspaces, index);
const manager = new SessionManager(workspaces, index, new InMemorySessionLockService());
let releaseSection!: () => void;
const sectionGate = new Promise<void>((resolve) => {
@ -367,7 +374,7 @@ describe('SessionManager', () => {
const index = {
get: async () => ({ workspaceId: 'workspace-1', cwd: '/workspace' }),
} as unknown as ISessionIndex;
const manager = new SessionManager(workspaces, index);
const manager = new SessionManager(workspaces, index, new InMemorySessionLockService());
let releaseSection!: () => void;
const sectionGate = new Promise<void>((resolve) => {
@ -405,7 +412,7 @@ describe('SessionManager', () => {
const index = {
get: async () => ({ workspaceId: 'workspace-1', cwd: '/workspace' }),
} as unknown as ISessionIndex;
const manager = new SessionManager(workspaces, index);
const manager = new SessionManager(workspaces, index, new InMemorySessionLockService());
await expect(manager.resume('session-1')).rejects.toThrow('boom');
await expect(manager.whenResumeSettled('session-1')).rejects.toThrow('boom');
@ -427,7 +434,7 @@ describe('SessionManager', () => {
get: (workspaceId: string) => workspaceId === workspace.id ? workspace : undefined,
} as unknown as IWorkspaceInstanceManager;
const index = { get: async () => undefined } as unknown as ISessionIndex;
const manager = new SessionManager(workspaces, index);
const manager = new SessionManager(workspaces, index, new InMemorySessionLockService());
const created = await manager.create({ workDir: '/workspace' });
expect(created).toBe(fake.handle);
expect(manager.get('session-1')).toBe(fake.handle);
@ -456,6 +463,7 @@ describe('SessionManager', () => {
const manager = new SessionManager(
workspaces,
{ get: async () => undefined } as unknown as ISessionIndex,
new InMemorySessionLockService(),
);
expect(await manager.create({ workDir: '/workspace' })).toBe(first.handle);
@ -492,6 +500,7 @@ describe('SessionManager', () => {
const manager = new SessionManager(
workspaces,
{ get: async () => undefined } as unknown as ISessionIndex,
new InMemorySessionLockService(),
);
await expect(manager.create({ workDir: '/workspace' })).rejects.toThrow('boom');
@ -505,6 +514,176 @@ describe('SessionManager', () => {
});
});
describe('SessionManager closeIfIdle', () => {
interface Guards {
readonly busy?: boolean;
readonly pending?: 'none' | 'approval' | 'question';
readonly terminal?: 'running' | 'exited';
readonly cronTasks?: number;
}
const managers: SessionManager[] = [];
function setup(guards: Guards = {}) {
const didCreate = new Emitter<SessionCreatedEvent>();
const didClose = new Emitter<SessionClosedEvent>();
const locks = new InMemorySessionLockService();
const state = {
busy: false,
pending: 'none' as const,
cronTasks: 0,
activeAt: Date.now(),
...guards,
};
const agent = {
accessor: {
get: (token: unknown) => token === IAgentCronService
? { list: () => Array.from({ length: state.cronTasks }) }
: undefined,
},
};
const handle = {
id: 'session-1',
accessor: {
get: (token: unknown) => {
if (token === ISessionActivityView) {
return {
state: () => ({ busy: state.busy, mainTurnActive: false, pendingInteraction: state.pending }),
lastActiveAt: () => state.activeAt,
};
}
if (token === ISessionTerminalService) {
return { list: async () => state.terminal === undefined ? [] : [{ status: state.terminal }] };
}
if (token === IAgentLifecycleService) {
return { list: () => [{ agentId: 'main' }], handleOf: () => agent };
}
return undefined;
},
},
} as unknown as ISessionScopeHandle;
let manager: SessionManager;
const resume = vi.fn(async (
sessionId: string,
_options: unknown,
source: SessionCreateSource = 'resume',
) => {
if (manager.get(sessionId) === undefined) didCreate.fire({ sessionId, handle, source });
return handle;
});
const close = vi.fn(async (sessionId: string, _reason: SessionCloseReason = 'exit') => {
didClose.fire({ sessionId });
});
const service = {
onWillCreateSession: Event.None,
onDidCreateSession: didCreate.event,
onWillCloseSession: Event.None,
onDidCloseSession: didClose.event,
onDidArchiveSession: Event.None,
onDidForkSession: Event.None,
create: async () => {
didCreate.fire({ sessionId: 'session-1', handle, source: 'startup' });
return handle;
},
resume,
close,
dispose: () => {},
} as unknown as SessionLifecycleService;
const workspace = {
id: 'workspace-1',
program: { sessionControllerGeneration: 'generation-1', createSessionController: () => service },
} as unknown as WorkspaceInstance;
manager = new SessionManager(
{ getOrCreate: async () => workspace, get: () => workspace } as unknown as IWorkspaceInstanceManager,
{ get: async () => ({ workspaceId: 'workspace-1', cwd: '/workspace' }) } as unknown as ISessionIndex,
locks,
);
managers.push(manager);
return { manager, handle, resume, close, locks };
}
const create = (fake: ReturnType<typeof setup>): Promise<ISessionScopeHandle> =>
fake.manager.create({ sessionId: 'session-1', workDir: '/workspace' } as never);
beforeEach(() => vi.useFakeTimers());
afterEach(() => {
for (const manager of managers) manager.dispose();
managers.length = 0;
vi.useRealTimers();
});
it('reclaims after the activity idle timeout and reloads only once', async () => {
const fake = setup();
expect(await fake.manager.closeIfIdle('session-1', 0)).toBe(false);
await create(fake);
vi.setSystemTime(Date.now() + 999);
expect(await fake.manager.closeIfIdle('session-1', 1000)).toBe(false);
await fake.manager.resume('session-1');
vi.setSystemTime(Date.now() + 1);
expect(await fake.manager.closeIfIdle('session-1', 1000)).toBe(true);
expect(fake.manager.get('session-1')).toBeUndefined();
await fake.manager.resume('session-1');
await fake.manager.close('session-1');
await fake.manager.resume('session-1');
expect(fake.close.mock.calls[0]?.[1]).toBe('reclaim');
expect(fake.resume.mock.calls.map((call) => call[2])).toEqual(['resume', 'reclaimed', 'resume']);
});
const eligibilityCases: Array<[string, Guards]> = [
['a busy turn', { busy: true }],
['a pending approval', { pending: 'approval' }],
['a pending question', { pending: 'question' }],
['a running terminal', { terminal: 'running' }],
['pending cron tasks', { cronTasks: 1 }],
];
it.each(eligibilityCases)('retains sessions with %s', async (_label, guards) => {
const fake = setup(guards);
await create(fake);
expect(await fake.manager.closeIfIdle('session-1', 0)).toBe(false);
expect(fake.manager.get('session-1')).toBeDefined();
});
it('reclaims a session with an exited terminal', async () => {
const fake = setup({ terminal: 'exited' });
await create(fake);
expect(await fake.manager.closeIfIdle('session-1', 0)).toBe(true);
expect(fake.manager.get('session-1')).toBeUndefined();
});
it('releases the lease when the close path fails', async () => {
const fake = setup();
fake.close.mockRejectedValue(new Error('boom'));
await create(fake);
await expect(fake.manager.closeIfIdle('session-1', 0)).rejects.toThrow('boom');
expect(fake.locks.held('session-1')).toBe(false);
expect(fake.manager.get('session-1')).toBeDefined();
});
it('serializes a reclaim with a racing resume', async () => {
const fake = setup();
await create(fake);
let releaseClose!: () => void;
const closeGate = new Promise<void>((resolve) => {
releaseClose = resolve;
});
const close = fake.close.getMockImplementation();
fake.close.mockImplementation(async (id, reason) => {
await closeGate;
await close?.(id, reason);
});
const reclaim = fake.manager.closeIfIdle('session-1', 0);
const resumed = fake.manager.resume('session-1');
await drainMicrotasks();
expect(fake.resume).not.toHaveBeenCalled();
releaseClose();
expect(await reclaim).toBe(true);
expect(await resumed).toBe(fake.handle);
expect(fake.manager.get('session-1')).toBe(fake.handle);
});
});
describe('SessionManager controller retirement', () => {
function runtime(generation: string): FakeRuntime {
return Object.assign(
@ -644,6 +823,7 @@ describe('SessionManager controller retirement', () => {
return new SessionManager(
workspaces,
{ get: async () => undefined } as unknown as ISessionIndex,
new InMemorySessionLockService(),
);
}

View file

@ -891,7 +891,7 @@ describe('IExternalHooksRunnerService integration', () => {
expect(unmatched).toHaveLength(0);
});
it('runs session external hooks from lifecycle callbacks', async () => {
it('runs session external hooks from lifecycle callbacks and skips idle reclaim and reload', async () => {
const disposables = new DisposableStore();
let ix: TestInstantiationService | undefined;
try {
@ -949,7 +949,9 @@ describe('IExternalHooksRunnerService integration', () => {
await lifecycle.fireDidCreate('startup');
await lifecycle.fireDidCreate('resume');
await lifecycle.fireDidCreate('reclaimed');
await lifecycle.fireDidCreate('fork');
await lifecycle.fireWillClose('reclaim');
await lifecycle.fireWillClose('exit');
await lifecycle.fireWillClose('archive');

View file

@ -239,6 +239,7 @@ function sessionManagerResuming(sessionId: string): SessionManager {
return new SessionManager(
{ getOrCreate: async () => workspace, get: () => workspace } as unknown as IWorkspaceInstanceManager,
{ get: async () => summary } as unknown as ISessionIndex,
new InMemorySessionLockService(),
);
}

View file

@ -141,6 +141,7 @@ export async function registerApiV1Routes(
apiV1 as unknown as Parameters<typeof registerSessionRatingRoutes>[0],
opts.sessionRating,
opts.transcriptService,
core,
);
registerRuntimeRoutes(apiV1 as unknown as Parameters<typeof registerRuntimeRoutes>[0], core);
registerSessionExportRoute(

View file

@ -1,3 +1,4 @@
import { resumeSessionById, type Scope } from '@moonshot-ai/agent-core-v2';
import type { SessionRatingHost } from '@moonshot-ai/kimi-code-product/session-rating/node';
import { z } from 'zod';
@ -25,6 +26,7 @@ export function registerSessionRatingRoutes(
app: SessionRatingRouteHost,
sessionRating: SessionRatingHost,
transcripts: TranscriptService,
core: Scope,
): void {
const route = defineRoute(
{
@ -42,15 +44,21 @@ export function registerSessionRatingRoutes(
'Evaluate the latest completed transcript turn, or report a displayed rating and its final answer',
tags: ['sessions'],
},
(req, reply) => {
async (req, reply) => {
const { session_id } = req.params;
const request = req.body;
if (request.op === 'evaluate') {
const latest = transcripts.forSessionLive(session_id)?.getAgent('main')
?.getItems().findLast((item) => item.kind === 'turn');
const offer = latest?.turnId === request.turn_id && latest.state !== 'running'
? sessionRating.evaluate(session_id)
: undefined;
const store = transcripts.forSessionLive(session_id);
const items = store === undefined
? (await transcripts.readColdSnapshot(session_id))?.items
: store.getAgent('main')?.getItems();
const latest = items?.findLast((item) => item.kind === 'turn');
const completed = latest?.turnId === request.turn_id && latest.state !== 'running';
if (completed && store === undefined) {
await resumeSessionById(core.accessor, session_id);
await sessionRating.whenReady(session_id);
}
const offer = completed ? sessionRating.evaluate(session_id) : undefined;
reply.send(okEnvelope({
appearance: offer === undefined
? null

View file

@ -1,7 +1,6 @@
import {
IAgentTaskService,
ISessionIndex,
getLiveSessionById,
resumeSessionById,
type AgentTaskInfo,
type Scope,
} from '@moonshot-ai/agent-core-v2';
@ -78,7 +77,7 @@ export function registerTasksRoutes(app: TasksRouteHost, core: Scope): void {
return;
}
const all = (resolved.tasks?.list(false) ?? []).map((info) =>
const all = resolved.tasks.list(false).map((info) =>
toWireTask(session_id, info),
);
const query = req.query as { status?: TaskStatus };
@ -112,7 +111,7 @@ export function registerTasksRoutes(app: TasksRouteHost, core: Scope): void {
return;
}
const found = resolved.tasks?.getTask(task_id);
const found = resolved.tasks.getTask(task_id);
if (found === undefined) {
reply.send(taskNotFound(session_id, task_id, req.id));
return;
@ -120,7 +119,7 @@ export function registerTasksRoutes(app: TasksRouteHost, core: Scope): void {
const query = req.query as { with_output?: boolean; output_bytes?: number };
let output: { preview: string; bytes: number } | undefined;
if (query.with_output === true && resolved.tasks !== undefined) {
if (query.with_output === true) {
const tailBytes = query.output_bytes ?? DEFAULT_TASK_OUTPUT_PREVIEW_BYTES;
try {
const preview = await resolved.tasks.readOutput(task_id, tailBytes);
@ -186,7 +185,7 @@ export function registerTasksRoutes(app: TasksRouteHost, core: Scope): void {
return;
}
const found = resolved.tasks?.getTask(task_id);
const found = resolved.tasks.getTask(task_id);
if (found === undefined) {
reply.send(taskNotFound(session_id, task_id, req.id));
return;
@ -199,14 +198,14 @@ export function registerTasksRoutes(app: TasksRouteHost, core: Scope): void {
return;
}
await resolved.tasks?.stopByUser(task_id);
await resolved.tasks.stopByUser(task_id);
requestLog(req)?.info({ session_id, task_id }, 'task cancelled');
reply.send(okEnvelope({ cancelled: true as const }, req.id));
return;
}
const detached = found.status === 'running' && found.detached === false;
const info = resolved.tasks?.detach(task_id) ?? found;
const info = resolved.tasks.detach(task_id) ?? found;
if (detached) {
requestLog(req)?.info({ session_id, task_id }, 'task detached');
}
@ -218,14 +217,11 @@ export function registerTasksRoutes(app: TasksRouteHost, core: Scope): void {
type ResolvedTasks =
| { readonly kind: 'not_found' }
| { readonly kind: 'resolved'; readonly tasks: IAgentTaskService | undefined };
| { readonly kind: 'resolved'; readonly tasks: IAgentTaskService };
async function resolveSessionTasks(core: Scope, sid: string): Promise<ResolvedTasks> {
const summary = await core.accessor.get(ISessionIndex).get(sid);
if (summary === undefined) return { kind: 'not_found' };
const session = getLiveSessionById(core.accessor, sid);
if (session === undefined) return { kind: 'resolved', tasks: undefined };
const session = await resumeSessionById(core.accessor, sid);
if (session === undefined) return { kind: 'not_found' };
const agent = await ensureMainAgent(session);
const tasks = agent.accessor.get(IAgentTaskService);
return { kind: 'resolved', tasks };

View file

@ -5,7 +5,9 @@ import {
IAgentToolRegistryService,
IAgentToolPolicyService,
getLiveSessionById,
resumeSessionById,
Error2,
type ISessionScopeHandle,
type Scope,
type ToolInfo,
type ToolSource,
@ -157,9 +159,13 @@ export function registerToolsRoutes(app: ToolsRouteHost, core: Scope): void {
}
async function resolveEffectiveAgent(core: Scope, sessionId: string | undefined) {
const sid = sessionId ?? (await mostRecentSessionId(core));
if (sid === undefined) return undefined;
const session = getLiveSessionById(core.accessor, sid);
let session: ISessionScopeHandle | undefined;
if (sessionId !== undefined) {
session = await resumeSessionById(core.accessor, sessionId);
} else {
const recent = await mostRecentSessionId(core);
session = recent === undefined ? undefined : getLiveSessionById(core.accessor, recent);
}
if (session === undefined) return undefined;
return ensureMainAgent(session);
}

View file

@ -0,0 +1,79 @@
import { Error2, ErrorCodes, type ISessionManager } from '@moonshot-ai/agent-core-v2';
import type { ServerLogger } from './pinoLoggerService';
export const SESSION_IDLE_RECLAIM_ENV = 'KIMI_CODE_SESSION_IDLE_RECLAIM_MS';
export const DEFAULT_SESSION_IDLE_RECLAIM_MS = 30 * 60 * 1000;
const SWEEP_INTERVAL_MS = 60_000;
export function resolveSessionIdleReclaimMs(env: NodeJS.ProcessEnv): number {
const raw = env[SESSION_IDLE_RECLAIM_ENV];
if (raw === undefined || raw.trim().length === 0) return DEFAULT_SESSION_IDLE_RECLAIM_MS;
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed < 0) {
throw new Error2(
ErrorCodes.VALIDATION_FAILED,
`${SESSION_IDLE_RECLAIM_ENV} must be a non-negative integer, got ${JSON.stringify(raw)}.`,
{ details: { value: raw } },
);
}
return parsed;
}
export class SessionIdleReaper {
private timer: ReturnType<typeof setInterval> | undefined;
private inFlight: Promise<void> | undefined;
private closed = false;
constructor(
private readonly sessions: Pick<ISessionManager, 'list' | 'closeIfIdle'>,
private readonly logger: Pick<ServerLogger, 'info' | 'warn'>,
private readonly idleTimeoutMs: number,
private readonly sweepIntervalMs: number = SWEEP_INTERVAL_MS,
) {}
start(): void {
if (this.closed || this.idleTimeoutMs <= 0 || this.timer !== undefined) return;
this.timer = setInterval(() => {
void this.sweep();
}, this.sweepIntervalMs);
this.timer.unref?.();
this.logger.info(
{ idleTimeoutMs: this.idleTimeoutMs, sweepIntervalMs: this.sweepIntervalMs },
'session idle reclaim enabled',
);
}
sweep(): Promise<void> {
if (this.inFlight !== undefined) return this.inFlight;
const run = this.sweepSessions();
this.inFlight = run;
void run.finally(() => {
if (this.inFlight === run) this.inFlight = undefined;
});
return run;
}
async close(): Promise<void> {
this.closed = true;
if (this.timer !== undefined) {
clearInterval(this.timer);
this.timer = undefined;
}
await this.inFlight;
}
private async sweepSessions(): Promise<void> {
for (const handle of this.sessions.list()) {
if (this.closed) return;
try {
await this.sessions.closeIfIdle(handle.id, this.idleTimeoutMs);
} catch (error) {
this.logger.warn(
{ sessionId: handle.id, err: error instanceof Error ? error.message : String(error) },
'session idle reclaim failed',
);
}
}
}
}

View file

@ -14,6 +14,7 @@ import {
IProviderDiscoveryService,
ISessionIndex,
ISessionIndexMirror,
ISessionManager,
ICapabilityService,
IPluginService,
IWorkspaceService,
@ -82,6 +83,7 @@ import {
import { createServerSessionRating } from './services/sessionRating';
import { TranscriptService } from './services/transcript/transcriptService';
import { ModelCatalogRefreshScheduler } from './services/modelCatalog/modelCatalogRefreshScheduler';
import { SessionIdleReaper, resolveSessionIdleReclaimMs } from './services/sessionIdleReaper';
import { startConfigChangedPublisher } from './services/config/configChangedPublisher';
import { createAuthFailureLimiter } from './middleware/rateLimit';
import {
@ -148,6 +150,7 @@ export async function startServer(opts: ServerStartOptions): Promise<RunningServ
const port = opts.port ?? DEFAULT_PORT;
const homeDir = resolveKimiHome(opts.homeDir);
const serverVersion = opts.serverVersion ?? getServerVersion();
const idleReclaimMs = resolveSessionIdleReclaimMs(opts.env ?? process.env);
const registry = createInstanceRegistry({
instancesDir: opts.instancesDir ?? join(homeDir, 'server', 'instances'),
});
@ -272,6 +275,11 @@ export async function startServer(opts: ServerStartOptions): Promise<RunningServ
core.accessor.get(IConfigService),
logger,
);
const sessionIdleReaper = new SessionIdleReaper(
core.accessor.get(ISessionManager),
logger,
idleReclaimMs,
);
try {
await core.accessor.get(IWorkspaceService).list();
@ -337,6 +345,7 @@ export async function startServer(opts: ServerStartOptions): Promise<RunningServ
capabilityInstallSubscription.dispose();
authFailureLimiter?.dispose();
modelCatalogRefreshScheduler.dispose();
await sessionIdleReaper.close();
try {
await shutdownServerTelemetry(telemetry);
} catch (error) {
@ -631,6 +640,7 @@ export async function startServer(opts: ServerStartOptions): Promise<RunningServ
'provider-model catalog auto-refresh failed to start',
);
});
sessionIdleReaper.start();
process.on('unhandledRejection', onUnhandledRejection);
process.on('uncaughtException', onUncaughtException);

View file

@ -24,6 +24,7 @@ import {
MAIN_AGENT_ID,
followSessionLifecycles,
getLiveSessionById,
resumeSessionById,
interactions,
toDisposable,
} from '@moonshot-ai/agent-core-v2';
@ -221,8 +222,17 @@ export class SessionEventBroadcaster {
transcriptGrades?: TranscriptGradeSpec,
opts?: { deferTranscriptReset?: boolean; transcriptSince?: Record<string, number> },
): Promise<boolean> {
try {
await resumeSessionById(this.opts.core.accessor, sessionId);
} catch (error) {
this.opts.logger?.warn(
{ sessionId, err: error instanceof Error ? error.message : String(error) },
'session subscribe resume failed',
);
return false;
}
const state = await this.ensureState(sessionId);
if (state === undefined) return false;
if (state === undefined || this.sessions.get(sessionId) !== state) return false;
const prev = state.targets.get(target);
state.targets.set(target, { agentFilter: filter, transcriptGrades });
if (transcriptGrades !== undefined) {
@ -284,6 +294,7 @@ export class SessionEventBroadcaster {
state.targets.delete(target);
state.transcriptSeeded.delete(target);
state.deferredTranscriptSeeds.delete(target);
this.evictDetachedSession(sessionId);
}
unsubscribeTranscript(
@ -644,6 +655,13 @@ export class SessionEventBroadcaster {
state.transcriptStream = undefined;
this.dropActivityTrackers(sessionId);
this.opts.transcriptService?.dropSession(sessionId);
this.evictDetachedSession(sessionId);
}
private evictDetachedSession(sessionId: string): void {
const state = this.sessions.get(sessionId);
if (state === undefined || state.detached !== true || state.targets.size > 0) return;
this.evictSession(sessionId);
}
private async reattachSession(sessionId: string): Promise<void> {

View file

@ -151,6 +151,21 @@ describe('server-v2 boot', () => {
expect(overridden.headers['User-Agent']).toBe('custom-host/9.9');
});
it('rejects invalid idle reclaim config before registering an instance', async () => {
home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-idle-reclaim-'));
await expect(
startServer({
hostIdentity: TEST_HOST_IDENTITY,
host: '127.0.0.1',
port: 0,
homeDir: home,
logLevel: 'silent',
env: { KIMI_CODE_SESSION_IDLE_RECLAIM_MS: 'nope' },
}),
).rejects.toThrow(/KIMI_CODE_SESSION_IDLE_RECLAIM_MS.*non-negative integer/);
expect(await listLiveServerInstances(home)).toEqual([]);
});
it('seeds explicit skill dirs into the core scope when skillDirs is provided', async () => {
home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-skills-'));
server = await startServer({

View file

@ -462,6 +462,7 @@ function makeCore(
if (token === ISessionManager) {
return {
get: sessionFor,
resume: async (sessionId: string) => sessionFor(sessionId),
list: () => [...sessions.keys()].map((sessionId) => sessionFor(sessionId)),
onWillDeleteSession: managerEvents?.onWillDeleteSession,
onDidCloseSession: managerEvents?.onDidCloseSession,
@ -1271,6 +1272,39 @@ describe('SessionEventBroadcaster', () => {
expect(after.subagents).toEqual([]);
});
it('releases a detached state with no targets and rebuilds from the preserved journal', async () => {
const managerEvents = new FakeManagerEvents();
await bc.close();
bc = new SessionEventBroadcaster({
eventsDir: dir,
core: makeCore(sessions, eventBus, {}, managerEvents),
maxBufferSize: 3,
});
const lc = new FakeLifecycle();
const main = lc.addAgent('main');
sessions.set('s1', lc);
const { target } = collectingTarget();
await bc.subscribe('s1', target);
main.bus.emit(agentEvent('turn.started', { turnId: 1 }));
const before = await bc.getCursor('s1');
expect(before.seq).toBeGreaterThan(0);
bc.unsubscribe('s1', target);
managerEvents.fireDidClose('s1');
await vi.waitFor(() => {
expect((bc as unknown as { sessions: Map<string, unknown> }).sessions.has('s1')).toBe(false);
});
await vi.waitFor(async () => {
const contents = await readFile(join(dir, 's1.jsonl'), 'utf8');
expect(contents).toContain(before.epoch);
expect(contents).toContain(`"seq":${before.seq}`);
});
sessions.set('s1', new FakeLifecycle());
expect(await bc.subscribe('s1', collectingTarget().target)).toBe(true);
expect(await bc.getCursor('s1')).toEqual(before);
});
it('subscribe returns false for an unknown session', async () => {
const { target } = collectingTarget();
expect(await bc.subscribe('nope', target)).toBe(false);

View file

@ -0,0 +1,85 @@
import type { ISessionManager, ISessionScopeHandle } from '@moonshot-ai/agent-core-v2';
import { describe, expect, it, vi } from 'vitest';
import {
DEFAULT_SESSION_IDLE_RECLAIM_MS,
SESSION_IDLE_RECLAIM_ENV,
SessionIdleReaper,
resolveSessionIdleReclaimMs,
} from '../src/services/sessionIdleReaper';
import type { ServerLogger } from '../src/services/pinoLoggerService';
function fakeSessions(ids: readonly string[]) {
const calls: string[] = [];
const fake: {
calls: string[];
impl: (sessionId: string) => Promise<boolean>;
manager: Pick<ISessionManager, 'list' | 'closeIfIdle'>;
} = {
calls,
impl: async (_sessionId: string) => true,
manager: {
list: () => ids.map((id) => ({ id }) as unknown as ISessionScopeHandle),
closeIfIdle: async (sessionId: string) => {
calls.push(sessionId);
return fake.impl(sessionId);
},
} satisfies Pick<ISessionManager, 'list' | 'closeIfIdle'>,
};
return fake;
}
function fakeLogger(): Pick<ServerLogger, 'info' | 'warn'> {
return { info: vi.fn(), warn: vi.fn() } as unknown as Pick<ServerLogger, 'info' | 'warn'>;
}
describe('SessionIdleReaper', () => {
it('resolves the idle timeout from the environment', () => {
expect(resolveSessionIdleReclaimMs({})).toBe(DEFAULT_SESSION_IDLE_RECLAIM_MS);
expect(resolveSessionIdleReclaimMs({ [SESSION_IDLE_RECLAIM_ENV]: '5000' })).toBe(5000);
expect(resolveSessionIdleReclaimMs({ [SESSION_IDLE_RECLAIM_ENV]: '0' })).toBe(0);
});
it('throws for negative, non-integer, or non-numeric values', () => {
for (const raw of ['-1', '0.5', 'nope']) {
expect(() => resolveSessionIdleReclaimMs({ [SESSION_IDLE_RECLAIM_ENV]: raw })).toThrow(
/KIMI_CODE_SESSION_IDLE_RECLAIM_MS.*non-negative integer/,
);
}
});
it('does not re-enter a running sweep, and close waits for it', async () => {
vi.useFakeTimers();
try {
const sessions = fakeSessions(['s1']);
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
sessions.impl = async () => {
await gate;
return true;
};
const reaper = new SessionIdleReaper(sessions.manager, fakeLogger(), 1000);
const first = reaper.sweep();
expect(reaper.sweep()).toBe(first);
reaper.start();
await vi.advanceTimersByTimeAsync(120_000);
expect(sessions.calls).toEqual(['s1']);
let closed = false;
const closing = reaper.close().then(() => {
closed = true;
});
await vi.advanceTimersByTimeAsync(120_000);
expect(sessions.calls).toEqual(['s1']);
expect(closed).toBe(false);
release();
await Promise.all([first, closing]);
expect(closed).toBe(true);
await vi.advanceTimersByTimeAsync(120_000);
expect(sessions.calls).toEqual(['s1']);
} finally {
vi.useRealTimers();
}
});
});

View file

@ -13,6 +13,7 @@ import {
IEventBus,
IAgentProfileService,
IEventDispatcher,
ISessionManager,
ISessionMetadata,
ITelemetryService,
MAIN_AGENT_ID,
@ -21,6 +22,7 @@ import {
type CompactionResult,
type TelemetryAppenderRecord,
} from '@moonshot-ai/agent-core-v2';
import { ContextAppendMessage } from '@moonshot-ai/agent-core-v2/agent/contextMemory/contextEvents';
import { TurnStarted } from '@moonshot-ai/agent-core-v2/agent/loop/turnEvents';
import { TurnEnded, TurnPrompt } from '@moonshot-ai/agent-core-v2/agent/loop/turnOps';
import {
@ -82,17 +84,17 @@ class RatingClient {
return ensureMainAgent(session);
}
async finishUserTurn(sessionId: string, during?: (bus: IEventBus) => void): Promise<void> {
async finishUserTurn(sessionId: string, during?: (bus: IEventBus) => void, turnId = 1): Promise<void> {
const agent = await this.mainAgent(sessionId);
strictEqual((await this.request(`/api/v1/sessions/${sessionId}/transcript?agent_id=main`)).code, 0);
const bus = agent.accessor.get(IEventBus);
const dispatcher = agent.accessor.get(IEventDispatcher);
const origin = { kind: 'user' } as const;
await dispatcher.dispatch(new TurnPrompt({ agentId: MAIN_AGENT_ID, input: [], origin }));
bus.publish(new TurnStarted({ agentId: MAIN_AGENT_ID, turnId: 1, origin }));
bus.publish(new TurnStarted({ agentId: MAIN_AGENT_ID, turnId, origin }));
during?.(bus);
bus.publish(new TurnEnded({
agentId: MAIN_AGENT_ID, turnId: 1, reason: 'completed', traceId: 'trace-1',
agentId: MAIN_AGENT_ID, turnId, reason: 'completed', traceId: 'trace-1',
}));
}
@ -502,6 +504,42 @@ describe('session rating lifecycle', () => {
}
});
it('resumes and evaluates a completed turn for a cold session', async () => {
const id = await client.createSession(home);
await (await client.mainAgent(id)).accessor.get(IAgentProfileService).setModel('kimi-code/k3');
await client.finishUserTurn(id, undefined, 0);
const agent = await client.mainAgent(id);
const dispatcher = agent.accessor.get(IEventDispatcher);
await dispatcher.dispatch(
new ContextAppendMessage({
agentId: MAIN_AGENT_ID,
message: {
role: 'user',
content: [{ type: 'text', text: 'Please review this answer.' }],
toolCalls: [],
origin: { kind: 'user' },
},
}),
);
await dispatcher.dispatch(
new TurnEnded({ agentId: MAIN_AGENT_ID, turnId: 0, reason: 'completed', traceId: 'trace-1' }),
);
const turnId = await client.latestTurnId(id);
expect(await server.core.accessor.get(ISessionManager).closeIfIdle(id, 0)).toBe(true);
const result = await client.evaluate(id, turnId);
expect(result.data.appearance).toMatchObject({ survey: 'session' });
expect(getLiveSessionById(server.core.accessor, id)).not.toBeUndefined();
if (result.data.appearance === null) throw new Error('expected a rating offer');
await client.report(id, result.data.appearance.id, 'shown');
const appeared = records.find(
(record) =>
record.event === 'feedback_survey' &&
record.context['session_id'] === id &&
record.properties['event_type'] === 'appeared',
);
expect(appeared?.properties).toMatchObject({ kfc_trace_id: 'trace-1', user_turn_count: 1 });
});
it('does not load sessions when evaluating or reporting unknown appearances', async () => {
const id = await client.createSession(home);
await closeSessionById(server.core.accessor, id);

View file

@ -6,6 +6,7 @@ import {
type Event2,
IEventBus,
IAgentLifecycleService,
ISessionManager,
getLiveSessionById,
} from '@moonshot-ai/agent-core-v2';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
@ -282,4 +283,25 @@ describe('server-v2 /api/v1/ws resync', () => {
c.ws.close();
await c.closed;
});
it('resumes a reclaimed session on a pure WS reconnect', async () => {
const sid = await createSession();
await ensureMainAgent(sid);
const manager = server!.core.accessor.get(ISessionManager);
expect(await manager.closeIfIdle(sid, 0)).toBe(true);
expect(manager.get(sid)).toBeUndefined();
const c = await openConn(wsUrl, server!.authTokenService.getToken());
await c.next((f) => f.type === 'server_hello');
c.send({
type: 'client_hello',
id: 'h1',
payload: withToken({ client_id: 'cli', subscriptions: [sid] }),
});
const ack = await c.next((f) => f.type === 'ack' && f.id === 'h1');
expect(ack.payload).toMatchObject({ accepted_subscriptions: [sid], resync_required: [] });
expect(manager.get(sid)).toBeDefined();
c.ws.close();
await c.closed;
}, 30_000);
});

View file

@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
import type { PromptOrigin } from '@moonshot-ai/agent-core-v2';
import { isSurveyTurnOrigin } from './survey-turns';
import { isSurveyTurnOrigin, type SurveyTurnRecovery } from './survey-turns';
import type { RatingCooldownStore } from './cooldown-store';
import {
@ -82,6 +82,7 @@ export interface SessionRatingDeps {
export interface SessionRatingMount {
observe(fact: SessionFact): void;
recover(recovery: SurveyTurnRecovery): void;
evaluate(): RatingOffer | undefined;
end(): void;
}
@ -116,13 +117,14 @@ function resumedSubagentCount(
class SessionRatingMountImpl implements SessionRatingMount {
private readonly mountId = Symbol();
private ended = false;
private readonly mountedAt: number;
private mountedAt: number;
private currentTurnUserOrigin: boolean | undefined;
private turnInProgress = false;
private evaluationPending = false;
private pendingTraceId: string | undefined;
private idleSince: number | undefined;
private userTurnsSinceMount = 0;
private recoveredUserTurns = 0;
private lastShownAt: number | undefined;
private userTurnsAtLastShown: number | undefined;
private appearanceCount = 0;
@ -167,6 +169,21 @@ class SessionRatingMountImpl implements SessionRatingMount {
}
}
recover(recovery: SurveyTurnRecovery): void {
if (this.ended || this.turnInProgress || this.evaluationPending || this.userTurnsSinceMount > 0) return;
this.recoveredUserTurns = recovery.userTurnCount;
this.userTurnsSinceMount = recovery.userTurnCount;
if (recovery.firstPromptAt !== undefined) {
this.mountedAt = this.now() - Math.max(0, this.wallNow() - recovery.firstPromptAt);
}
if (isSurveyTurnOrigin(recovery.origin) !== true) return;
this.evaluationPending = true;
this.pendingTraceId = recovery.traceId;
this.idleSince = recovery.endedAt === undefined
? this.now()
: this.now() - Math.max(0, this.wallNow() - recovery.endedAt);
}
evaluate(): RatingOffer | undefined {
if (this.ended || !this.evaluationPending || this.turnInProgress) return undefined;
this.evaluationPending = false;
@ -343,7 +360,7 @@ class SessionRatingMountImpl implements SessionRatingMount {
user_turn_count:
environment.historyUserTurnCount === undefined
? undefined
: environment.historyUserTurnCount + this.userTurnsSinceMount,
: environment.historyUserTurnCount + this.userTurnsSinceMount - this.recoveredUserTurns,
cumulative_tokens: environment.cumulativeTokens,
virtual_context_tokens: environment.contextTokens,
tool_call_count: this.toolCallCount,

View file

@ -109,6 +109,8 @@ export interface SessionRatingHostOptions {
interface MountedSession {
readonly mount: SessionRatingMount;
readonly disposables: IDisposable[];
readonly ready: () => Promise<void>;
recover: boolean;
}
export class SessionRatingHost implements IDisposable {
@ -159,6 +161,8 @@ export class SessionRatingHost implements IDisposable {
});
const created = manager.onDidCreateSession?.((event) => {
this.mountSession(event.sessionId, event.handle);
const session = this.sessions.get(event.sessionId);
if (session !== undefined) session.recover = event.source === 'reclaimed';
});
const closing = manager.onWillCloseSession?.((event) => {
this.unmountSession(event.sessionId);
@ -169,6 +173,10 @@ export class SessionRatingHost implements IDisposable {
for (const handle of manager.list()) this.mountSession(handle.id, handle);
}
async whenReady(sessionId: string): Promise<void> {
await this.sessions.get(sessionId)?.ready();
}
evaluate(sessionId: string): RatingOffer | undefined {
return this.sessions.get(sessionId)?.mount.evaluate();
}
@ -196,7 +204,8 @@ export class SessionRatingHost implements IDisposable {
let mainAgentEvents: IDisposable | undefined;
let userTurnsObserved = 0;
let resumedAgents: Readonly<Record<string, ResumedAgentSeed>> | undefined;
void handle.accessor
let historyReady: Promise<void> = Promise.resolve();
const metadataReady = handle.accessor
.get(ISessionMetadata)
.read()
.then((meta) => {
@ -222,7 +231,8 @@ export class SessionRatingHost implements IDisposable {
mainAgent = agent;
const counter = mountSurveyTurnCounter(agent.accessor.get(IEventDispatcher));
surveyTurns = counter;
void counter.whenAttached.catch((error: unknown) => {
historyReady = counter.whenAttached;
void historyReady.catch((error: unknown) => {
this.options.log?.('session rating history unavailable', { error: String(error) });
});
const bus = agent.accessor.get(IEventBus);
@ -278,7 +288,13 @@ export class SessionRatingHost implements IDisposable {
}),
{ dispose: () => mainAgentEvents?.dispose() },
];
this.sessions.set(sessionId, { mount, disposables });
const ready = async () => {
await Promise.all([metadataReady, historyReady]).catch(() => undefined);
if (this.sessions.get(sessionId)?.recover !== true) return;
const recovery = surveyTurns?.recovery();
if (recovery !== undefined) mount.recover(recovery);
};
this.sessions.set(sessionId, { mount, disposables, ready, recover: false });
}
private unmountSession(sessionId: string): void {

View file

@ -2,13 +2,28 @@ import { randomUUID } from 'node:crypto';
import type { DurableAgentRuntimeParticipant, IEventDispatcher, IDisposable } from '@moonshot-ai/agent-core-v2';
import { ContextAppendMessage } from '@moonshot-ai/agent-core-v2/agent/contextMemory/contextEvents';
import { TurnPrompt } from '@moonshot-ai/agent-core-v2/agent/loop/turnOps';
import { TurnEnded, TurnPrompt } from '@moonshot-ai/agent-core-v2/agent/loop/turnOps';
interface SurveyTurnHistory {
readonly count: number;
readonly reliable: boolean;
readonly firstPrompt: number;
readonly firstUserMessage: number;
readonly firstPromptAt?: number;
readonly currentOrigin?: unknown;
readonly evaluation?: {
readonly origin: unknown;
readonly traceId?: string;
readonly endedAt?: number;
};
}
export interface SurveyTurnRecovery {
readonly userTurnCount: number;
readonly firstPromptAt?: number;
readonly origin: unknown;
readonly traceId?: string;
readonly endedAt?: number;
}
const EMPTY_HISTORY: SurveyTurnHistory = {
@ -31,13 +46,32 @@ function observeHistory(
): SurveyTurnHistory {
if (record === null || typeof record !== 'object') return { ...history, reliable: false };
if (!('type' in record)) return history;
const time = 'time' in record && typeof record.time === 'number' ? record.time : undefined;
if (record.type === 'turn.prompt') {
const counted = isSurveyTurnOrigin('origin' in record ? record.origin : undefined);
const origin = 'origin' in record ? record.origin : undefined;
const counted = isSurveyTurnOrigin(origin);
return {
...history,
count: history.count + (counted === true ? 1 : 0),
reliable: history.reliable && counted !== undefined,
firstPrompt: Math.min(history.firstPrompt, position),
firstPromptAt: history.firstPromptAt ?? time,
currentOrigin: origin,
evaluation: undefined,
};
}
if (record.type === 'turn.ended') {
const origin = history.currentOrigin;
return {
...history,
currentOrigin: undefined,
evaluation: isSurveyTurnOrigin(origin) === true
? {
origin,
traceId: 'traceId' in record && typeof record.traceId === 'string' ? record.traceId : undefined,
endedAt: time,
}
: undefined,
};
}
if (record.type === 'context.append_message' && 'message' in record) {
@ -58,6 +92,7 @@ function observeHistory(
export interface MountedSurveyTurnCounter extends IDisposable {
readonly count: number | undefined;
readonly whenAttached: Promise<void>;
recovery(): SurveyTurnRecovery | undefined;
}
export function mountSurveyTurnCounter(dispatcher: IEventDispatcher): MountedSurveyTurnCounter {
@ -68,7 +103,7 @@ export function mountSurveyTurnCounter(dispatcher: IEventDispatcher): MountedSur
| { phase: 'disposed' } = { phase: 'pending' };
const participant: DurableAgentRuntimeParticipant<typeof state> = {
id: `session-rating.survey-turns:${randomUUID()}`,
events: [TurnPrompt, ContextAppendMessage],
events: [TurnPrompt, TurnEnded, ContextAppendMessage],
undoable: false,
getState: () => state,
commit: (next) => { state = next; },
@ -95,6 +130,19 @@ export function mountSurveyTurnCounter(dispatcher: IEventDispatcher): MountedSur
? undefined
: countOf(state.history);
},
recovery() {
if (attachment.phase !== 'attached' || dispatcher.restorePhase !== 'ready') return undefined;
const userTurnCount = countOf(state.history);
const evaluation = state.history.evaluation;
if (userTurnCount === undefined || evaluation === undefined) return undefined;
return {
userTurnCount,
firstPromptAt: state.history.firstPromptAt,
origin: evaluation.origin,
traceId: evaluation.traceId,
endedAt: evaluation.endedAt,
};
},
dispose() {
if (attachment.phase === 'attached') attachment.registration.dispose();
attachment = { phase: 'disposed' };