fix(agent-core-v2): assemble flag-gated features after config ready (#3471)

FeatureAssemblyService ran during the eager bootstrap batch, while
ConfigService was still loading config.toml asynchronously, so
flags.enabled() always read false for config-sourced flags and gated
features (e.g. tower via [experimental] tower = true) never assembled.

registerFeature now accepts a { flag } option; gated registrations are
assembled in a deferred pass once IConfigService.ready resolves, and
IFeatureAssemblyService.ready exposes that pass. WorkspaceInstanceManager
.materialize also awaits config.ready so session creation cannot race
the deferred assembly.
This commit is contained in:
7Sageer 2026-09-02 21:09:35 +08:00 • committed by GitHub
parent 9f866cb7f4
commit eb4cd4b38e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 224 additions and 31 deletions

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
Fix tower mode not turning on when enabled through the [experimental] section in config.toml.

View file

@ -2,6 +2,7 @@ import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiatio
export interface IFeatureAssemblyService {
readonly _serviceBrand: undefined;
readonly ready: Promise<void>;
}
export const IFeatureAssemblyService: ServiceIdentifier<IFeatureAssemblyService> =

View file

@ -1,19 +1,41 @@
import type { ServiceClassRecipe } from '#/_base/di/fiber';
import { IConfigService } from '#/app/config/config';
import { IFeatureManager } from '#/app/feature/featureManager';
import { IFlagService } from '#/app/flag/flag';
import type { FlagId } from '#/app/flag/flagRegistry';
import { LifecycleScope } from '#/app/scopes';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { Service } from '#/_base/di/service';
import { IFeatureAssemblyService } from './featureAssembly';
import { getFeatureRecipes } from './featureRegistry';
import { getFeatureRegistrations } from './featureRegistry';
export class FeatureAssemblyService extends Service implements IFeatureAssemblyService {
declare readonly _serviceBrand: undefined;
readonly ready: Promise<void>;
constructor(@IFeatureManager featureManager: IFeatureManager) {
constructor(
@IFeatureManager featureManager: IFeatureManager,
@IConfigService config: IConfigService,
@IFlagService flags: IFlagService,
) {
super();
for (const recipe of getFeatureRecipes()) {
featureManager.provideUnit(recipe);
const gated: { recipe: ServiceClassRecipe; flag: FlagId }[] = [];
for (const { recipe, flag } of getFeatureRegistrations()) {
if (flag === undefined) {
featureManager.provideUnit(recipe);
} else {
gated.push({ recipe, flag });
}
}
this.ready = config.ready.then(() => {
for (const { recipe, flag } of gated) {
if (flags.enabled(flag)) {
featureManager.provideUnit(recipe);
}
}
});
void this.ready.catch(() => {});
}
}

View file

@ -1,15 +1,24 @@
import type { ServiceClassRecipe } from '#/_base/di/fiber';
import type { FlagId } from '#/app/flag/flagRegistry';
const _featureRecipes: ServiceClassRecipe[] = [];
export function registerFeature(recipe: ServiceClassRecipe): void {
_featureRecipes.push(recipe);
export interface FeatureRegistration {
readonly recipe: ServiceClassRecipe;
readonly flag?: FlagId;
}
export function getFeatureRecipes(): readonly ServiceClassRecipe[] {
return _featureRecipes;
const _featureRegistrations: FeatureRegistration[] = [];
export function registerFeature(
recipe: ServiceClassRecipe,
options: { readonly flag?: FlagId } = {},
): void {
_featureRegistrations.push({ recipe, flag: options.flag });
}
export function getFeatureRegistrations(): readonly FeatureRegistration[] {
return _featureRegistrations;
}
export function _clearFeatureRecipesForTests(): void {
_featureRecipes.length = 0;
_featureRegistrations.length = 0;
}

View file

@ -90,4 +90,4 @@ export function _setTowerFeatureAssembledForTests(value: boolean | undefined): v
assembledOverrideForTests = value;
}
registerFeature(TowerFeature);
registerFeature(TowerFeature, { flag: TOWER_FLAG_ID });

View file

@ -186,6 +186,7 @@ export class WorkspaceInstanceManager implements IWorkspaceInstanceManager {
private async materialize(workspace: Workspace): Promise<WorkspaceInstance> {
await this.environment.ready;
await this.config.ready;
const runtimes = new RuntimeRegistry(workspace.id);
const unitHost = this.unitHostFactory.create(this.instantiation, runtimes);
const instance = new WorkspaceInstance(

View file

@ -7,8 +7,10 @@ import {
registerScopedService,
} from '#/_base/di/scope';
import { createScopedTestHost } from '#/_base/di/test';
import { IConfigService } from '#/app/config/config';
import { IFeatureManager } from '#/app/feature/featureManager';
import { FeatureManagerService } from '#/app/feature/featureManagerService';
import { IFlagService } from '#/app/flag/flag';
import { LifecycleScope } from '#/app/scopes';
import { IFeatureAssemblyService } from '#/features/featureAssembly';
import { FeatureAssemblyService } from '#/features/featureAssemblyService';
@ -18,8 +20,14 @@ import {
} from '#/features/featureRegistry';
import { IDebugEventsService } from '#/features/debugEvents/debugEvents';
import { stubFlag } from '../../app/flag/stubs';
import { DebugEventsFeature } from '#/features/debugEvents/debugEventsFeature';
const featureAssemblySeeds = [
[IConfigService, { ready: Promise.resolve() }],
[IFlagService, stubFlag(false)],
] as const;
describe('DebugEventsFeature — App-scope introspection service', () => {
beforeEach(() => {
_clearScopedRegistryForTests();
@ -48,7 +56,7 @@ describe('DebugEventsFeature — App-scope introspection service', () => {
),
).toBe(false);
const host = createScopedTestHost();
const host = createScopedTestHost(featureAssemblySeeds);
const manager = host.app.accessor.get(IFeatureManager);
expect(manager.units().map((unit) => unit.name)).toContain('debugEvents');
expect(

View file

@ -11,6 +11,7 @@ import { IBootstrapService } from '#/app/bootstrap/bootstrap';
import { IConfigService } from '#/app/config/config';
import { IFeatureManager } from '#/app/feature/featureManager';
import { FeatureManagerService } from '#/app/feature/featureManagerService';
import { IFlagService } from '#/app/flag/flag';
import { IPluginService } from '#/app/plugin/plugin';
import { LifecycleScope } from '#/app/scopes';
import { IFeatureAssemblyService } from '#/features/featureAssembly';
@ -23,6 +24,7 @@ import { ISessionExternalHooksService } from '#/features/externalHooks/session/s
import { IHostProcessService } from '#/os/interface/hostProcess';
import { stubBootstrap } from '../../app/bootstrap/stubs';
import { stubFlag } from '../../app/flag/stubs';
function collectionViewOf<T>(scope: Scope, token: CollectionToken<T>): CollectionView<T> {
return (scope.instantiation as InstantiationService).fiberHost.collectionView(token);
@ -59,6 +61,7 @@ describe('ExternalHooksFeature — assembly (src/features/externalHooks)', () =>
{ _serviceBrand: undefined, enabledHooks: async () => [], onDidReload: Event.None },
],
[IHostProcessService, { _serviceBrand: undefined }],
[IFlagService, stubFlag(false)],
]);
const manager = host.app.accessor.get(IFeatureManager);
expect(manager.units().map((unit) => unit.name)).toContain('externalHooks');

View file

@ -17,9 +17,11 @@ import {
import { Service } from '#/_base/di/service';
import { createScopedTestHost } from '#/_base/di/test';
import { AgentProfileContribution } from '#/app/agentProfileCatalog/agentProfileContribution';
import { IConfigService } from '#/app/config/config';
import { ConfigSectionContribution } from '#/app/config/configSectionContributions';
import { IFeatureManager } from '#/app/feature/featureManager';
import { FeatureManagerService } from '#/app/feature/featureManagerService';
import { IFlagService } from '#/app/flag/flag';
import { LifecycleScope } from '#/app/scopes';
import { AgentToolContribution } from '#/agent/toolRegistry/toolContribution';
import { Feature } from '#/features/feature';
@ -38,6 +40,13 @@ import {
} from '#/features/featureRegistry';
import type { AgentTool, ToolExecution } from '#/tool/toolContract';
import { stubFlag } from '../app/flag/stubs';
const featureAssemblySeeds = [
[IConfigService, { ready: Promise.resolve() }],
[IFlagService, stubFlag(false)],
] as const;
interface IGreeter {
readonly _serviceBrand: undefined;
greet(): string;
@ -115,7 +124,7 @@ describe('Feature — built-in capability assembly (src/features)', () => {
}
registerFeature(TestFeature);
const host = createScopedTestHost();
const host = createScopedTestHost(featureAssemblySeeds);
const manager = host.app.accessor.get(IFeatureManager);
expect(manager.units()).toHaveLength(1);
expect(manager.units()[0]!.name).toBe('test-feature');
@ -185,7 +194,7 @@ describe('Feature — built-in capability assembly (src/features)', () => {
}
registerFeature(DomainFeature);
const host = createScopedTestHost();
const host = createScopedTestHost(featureAssemblySeeds);
const manager = host.app.accessor.get(IFeatureManager);
const views = [
collectionViewOf(host.app, SessionModelContribution),
@ -225,7 +234,7 @@ describe('Feature — built-in capability assembly (src/features)', () => {
}
registerFeature(FirstFeature);
const host = createScopedTestHost();
const host = createScopedTestHost(featureAssemblySeeds);
const manager = host.app.accessor.get(IFeatureManager);
const agent = host.child(LifecycleScope.Agent, 'agent-1');
const original = agent.accessor.get(IGreeter);
@ -261,8 +270,8 @@ describe('Feature — built-in capability assembly (src/features)', () => {
}
registerFeature(SharedFeature);
const first = createScopedTestHost();
const second = createScopedTestHost();
const first = createScopedTestHost(featureAssemblySeeds);
const second = createScopedTestHost(featureAssemblySeeds);
const firstManager = first.app.accessor.get(IFeatureManager);
const secondManager = second.app.accessor.get(IFeatureManager);
const firstAgent = first.child(LifecycleScope.Agent, 'agent-1');
@ -301,7 +310,7 @@ describe('Feature — built-in capability assembly (src/features)', () => {
}
registerFeature(SoloFeature);
const host = createScopedTestHost();
const host = createScopedTestHost(featureAssemblySeeds);
const agent = host.child(LifecycleScope.Agent, 'agent-1');
expect(agent.accessor.get(IGreeter).greet()).toBe('hi');
host.dispose();

View file

@ -31,6 +31,13 @@ import { GoalFeature } from '#/features/goal/goalFeature';
import { ISessionUsageService } from '#/session/usage/sessionUsage';
import { IEventDispatcher } from '#/state/eventDispatcher';
import { stubFlag } from '../../app/flag/stubs';
const featureAssemblySeeds = [
[IConfigService, { ready: Promise.resolve() }],
[IFlagService, stubFlag(false)],
] as const;
describe('GoalFeature', () => {
beforeEach(() => {
_clearScopedRegistryForTests();
@ -53,14 +60,14 @@ describe('GoalFeature', () => {
});
it('assembles a named, introspectable goal unit', () => {
const host = createScopedTestHost();
const host = createScopedTestHost(featureAssemblySeeds);
const manager = host.app.accessor.get(IFeatureManager);
expect(manager.units().map((unit) => unit.name)).toContain('goal');
host.dispose();
});
it('retracts the goal runtime contribution with the Feature', async () => {
const host = createScopedTestHost();
const host = createScopedTestHost(featureAssemblySeeds);
const manager = host.app.accessor.get(IFeatureManager);
await manager.unprovideUnit('goal');

View file

@ -7,8 +7,10 @@ import {
} from '#/_base/di/scope';
import { createScopedTestHost, stubPair } from '#/_base/di/test';
import { IBootstrapService } from '#/app/bootstrap/bootstrap';
import { IConfigService } from '#/app/config/config';
import { IFeatureManager } from '#/app/feature/featureManager';
import { FeatureManagerService } from '#/app/feature/featureManagerService';
import { IFlagService } from '#/app/flag/flag';
import { LifecycleScope } from '#/app/scopes';
import { SessionInitFeature } from '#/features/sessionInit/sessionInitFeature';
import { ISessionInitService } from '#/features/sessionInit/sessionInit';
@ -24,6 +26,13 @@ import { IAgentLifecycleService } from '#/session/agentLifecycle/agentLifecycle'
import { ISessionContext } from '#/session/sessionContext/sessionContext';
import { ISessionSubagentService } from '#/session/subagent/subagent';
import { stubFlag } from '../../app/flag/stubs';
const featureAssemblySeeds = [
[IConfigService, { ready: Promise.resolve() }],
[IFlagService, stubFlag(false)],
] as const;
describe('SessionInitFeature', () => {
beforeEach(() => {
_clearScopedRegistryForTests();
@ -46,7 +55,7 @@ describe('SessionInitFeature', () => {
});
it('withdraws and restores the Session service with the Feature', async () => {
const host = createScopedTestHost();
const host = createScopedTestHost(featureAssemblySeeds);
const session = host.child(LifecycleScope.Session, 'session-1', [
stubPair(IAgentLifecycleService, {} as IAgentLifecycleService),
stubPair(ISessionSubagentService, {} as ISessionSubagentService),

View file

@ -50,6 +50,10 @@ function collectionViewOf<T>(scope: Scope, token: CollectionToken<T>): Collectio
return (scope.instantiation as InstantiationService).fiberHost.collectionView(token);
}
function flushMicrotasks(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}
describe('TowerFeature — experimental flag gating', () => {
beforeEach(() => {
_clearScopedRegistryForTests();
@ -68,13 +72,17 @@ describe('TowerFeature — experimental flag gating', () => {
ScopeActivation.OnScopeCreated,
'features',
);
registerFeature(TowerFeature);
registerFeature(TowerFeature, { flag: TOWER_FLAG_ID });
});
it('assembles an empty unit when the tower flag is off', () => {
const host = createScopedTestHost([[IFlagService, stubFlag(false)]]);
it('does not assemble when the tower flag is off', async () => {
const host = createScopedTestHost([
[IFlagService, stubFlag(false)],
[IConfigService, { ready: Promise.resolve() }],
]);
await host.app.accessor.get(IFeatureAssemblyService).ready;
const manager = host.app.accessor.get(IFeatureManager);
expect(manager.units().map((unit) => unit.name)).toEqual(['tower']);
expect(manager.units()).toHaveLength(0);
expect(manager.contributedServices()).toHaveLength(0);
expect(collectionViewOf(host.app, AgentProfileContribution).items).toHaveLength(0);
const agent = host.child(LifecycleScope.Agent, 'agent-1');
@ -82,10 +90,12 @@ describe('TowerFeature — experimental flag gating', () => {
host.dispose();
});
it('contributes tools, profile, and rate-limit service when the tower flag is on', () => {
it('contributes tools, profile, and rate-limit service when the tower flag is on', async () => {
const host = createScopedTestHost([
[IFlagService, stubFlag((id) => id === TOWER_FLAG_ID)],
[IConfigService, { ready: Promise.resolve() }],
]);
await host.app.accessor.get(IFeatureAssemblyService).ready;
const manager = host.app.accessor.get(IFeatureManager);
expect(
manager
@ -121,7 +131,11 @@ describe('TowerFeature — experimental flag gating', () => {
it('clears the assembly marker when the feature unit unloads', async () => {
const flags = stubFlag((id) => id === TOWER_FLAG_ID);
const host = createScopedTestHost([[IFlagService, flags]]);
const host = createScopedTestHost([
[IFlagService, flags],
[IConfigService, { ready: Promise.resolve() }],
]);
await host.app.accessor.get(IFeatureAssemblyService).ready;
const manager = host.app.accessor.get(IFeatureManager);
expect(isTowerFeatureAssembled(flags)).toBe(true);
@ -130,6 +144,79 @@ describe('TowerFeature — experimental flag gating', () => {
expect(isTowerFeatureAssembled(flags)).toBe(false);
host.dispose();
});
it('defers gated assembly until config ready resolves', async () => {
let resolveConfigReady!: () => void;
const configReady = new Promise<void>((resolve) => {
resolveConfigReady = resolve;
});
const host = createScopedTestHost([
[IFlagService, stubFlag((id) => id === TOWER_FLAG_ID)],
[IConfigService, { ready: configReady }],
]);
const assembly = host.app.accessor.get(IFeatureAssemblyService);
const manager = host.app.accessor.get(IFeatureManager);
await flushMicrotasks();
expect(manager.units()).toHaveLength(0);
expect(manager.contributedServices()).toHaveLength(0);
expect(collectionViewOf(host.app, AgentProfileContribution).items).toHaveLength(0);
const pendingAgent = host.child(LifecycleScope.Agent, 'agent-pending');
expect(collectionViewOf(pendingAgent, AgentToolContribution).items).toHaveLength(0);
resolveConfigReady();
await assembly.ready;
expect(manager.units().map((unit) => unit.name)).toContain('tower');
expect(
manager
.contributedServices()
.filter(
(entry) => entry.scope === LifecycleScope.App && entry.id === ITowerRateLimitService,
),
).toHaveLength(1);
const profiles = collectionViewOf(host.app, AgentProfileContribution).items;
expect(profiles).toHaveLength(1);
expect(profiles[0]!.sourceId).toBe('feature:tower');
const agent = host.child(LifecycleScope.Agent, 'agent-1');
expect(collectionViewOf(agent, AgentToolContribution).items).toHaveLength(11);
host.dispose();
});
it('does not assemble when the flag turns on after ready', async () => {
let towerEnabled = false;
const host = createScopedTestHost([
[IFlagService, stubFlag((id) => id === TOWER_FLAG_ID && towerEnabled)],
[IConfigService, { ready: Promise.resolve() }],
]);
await host.app.accessor.get(IFeatureAssemblyService).ready;
const manager = host.app.accessor.get(IFeatureManager);
expect(manager.units()).toHaveLength(0);
towerEnabled = true;
await flushMicrotasks();
expect(manager.units()).toHaveLength(0);
expect(collectionViewOf(host.app, AgentProfileContribution).items).toHaveLength(0);
host.dispose();
});
it('does not unload when the flag turns off after ready', async () => {
let towerEnabled = true;
const host = createScopedTestHost([
[IFlagService, stubFlag((id) => id === TOWER_FLAG_ID && towerEnabled)],
[IConfigService, { ready: Promise.resolve() }],
]);
await host.app.accessor.get(IFeatureAssemblyService).ready;
const manager = host.app.accessor.get(IFeatureManager);
expect(manager.units()).toHaveLength(1);
towerEnabled = false;
await flushMicrotasks();
expect(manager.units()).toHaveLength(1);
expect(collectionViewOf(host.app, AgentProfileContribution).items).toHaveLength(1);
host.dispose();
});
});
describe('tower flag — resolution', () => {

View file

@ -142,6 +142,7 @@ function manager(
...Array.from({ length: 22 }, () => undefined),
new TestRuntimeUnitHostFactory(),
];
args[5] = { ready: Promise.resolve() };
args[18] = { entries: () => [] };
const value = Reflect.construct(WorkspaceInstanceManager, args) as WorkspaceInstanceManager;
const providers = (value as unknown as { providers: Map<string, RuntimeProviderFactory> }).providers;

View file

@ -3,7 +3,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { IFeatureManager } from '@moonshot-ai/agent-core-v2/app/feature/featureManager';
import { getFeatureRecipes } from '@moonshot-ai/agent-core-v2/features/featureRegistry';
import { getFeatureRegistrations } from '@moonshot-ai/agent-core-v2/features/featureRegistry';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { type RunningServer, startServer } from '../src/start';
@ -164,7 +164,13 @@ describe('/api/v1/meta features', () => {
meta: Record<string, unknown>;
}
beforeEach(() => {
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_FLAG', '0');
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_TOWER', '0');
});
afterEach(async () => {
vi.unstubAllEnvs();
if (server !== undefined) {
await server.close();
server = undefined;
@ -199,8 +205,9 @@ describe('/api/v1/meta features', () => {
it('lists every registered built-in feature as Active with an empty meta', async () => {
const base = await boot();
const features = await getMetaFeatures(base);
const expected = getFeatureRecipes()
.map((recipe) => recipe.name)
const expected = getFeatureRegistrations()
.filter((registration) => registration.flag === undefined)
.map((registration) => registration.recipe.name)
.sort();
expect(features.map((feature) => feature.name).sort()).toEqual(expected);
for (const feature of features) {

View file

@ -1135,6 +1135,30 @@ key = "${titleOAuthRef.key}"
}
});
it('enables tower mode from config.toml [experimental] without env vars', async () => {
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_FLAG', '0');
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_TOWER', undefined);
const homeDir = await mkdtemp(join(tmpdir(), 'kimi-sdk-v2-'));
tempDirs.push(homeDir);
await writeFile(join(homeDir, 'config.toml'), '[experimental]\ntower = true\n', 'utf-8');
const workDir = await mkdtemp(join(tmpdir(), 'kimi-sdk-v2-work-'));
tempDirs.push(workDir);
const client = new SDKRpcClientV2({ homeDir, identity: TEST_IDENTITY });
try {
await client.createSession({ id: 'ses_tower_config', workDir });
await expect(client.setTowerMode({ sessionId: 'ses_tower_config', enabled: true }))
.resolves.toBeUndefined();
expect((await client.getStatus({ sessionId: 'ses_tower_config' })).towerMode).toBe(true);
await client.setTowerMode({ sessionId: 'ses_tower_config', enabled: false });
expect((await client.getStatus({ sessionId: 'ses_tower_config' })).towerMode).toBe(false);
} finally {
vi.unstubAllEnvs();
await client.close();
}
});
it('exposes Session.setTowerMode and getStatus().towerMode on the v2 harness', async () => {
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_TOWER', '1');
const { harness } = await makeHarness();