mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-26 05:27:06 +00:00
feat(kimi): thinking level selection for remote sessions (#2349)
* feat(kimi): thinking level selection for remote sessions Kimi Code's ACP session advertises the active model's thinking levels as a thought_level config option (`thinking`: off/on or off plus declared efforts). Expose it like Grok's effort: a session RPC + hub route for the options, the composer effort picker, and per-turn session/set_config_option in the remote launcher. The runner forwards --effort so resumed sessions keep the selection. * fix(kimi): keep thinking options in step with model switches Kimi Code answers session/set_model with no config options and pushes the new model's thought_level via config_option_update; capture it (opt-in in the ACP backend, same hunk as #2348), re-baseline the launcher's level after a switch, report 'switch pending' until the next turn applies it, and have the web poll until discovery succeeds. * fix(kimi): gate thinking discovery on the model the backend applied Compare the model the next queued turn carries with the backend's model instead of session state, so an older queued batch or a failed switch keeps discovery pending; forward the saved effort on terminal resume.
This commit is contained in:
@@ -2594,3 +2594,20 @@ describe('AcpSdkBackend OpenCode child session updates', () => {
|
||||
expect(texts(messages)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AcpSdkBackend config_option_update', () => {
|
||||
it('refreshes cached thought_level only when the flavor opts in', () => {
|
||||
const update = {
|
||||
sessionId: 's1',
|
||||
update: {
|
||||
sessionUpdate: 'config_option_update',
|
||||
configOptions: [{ id: 'effort', category: 'thought_level', currentValue: 'low', options: [{ value: 'low', name: 'low' }] }]
|
||||
}
|
||||
};
|
||||
for (const configOptionUpdates of [true, false]) {
|
||||
const backend = new AcpSdkBackend({ command: 'acp-agent', configOptionUpdates });
|
||||
(backend as unknown as { handleNotification: (m: string, p: unknown) => void }).handleNotification('session/update', update);
|
||||
expect(backend.getThoughtLevelConfigOption('s1')?.currentValue).toBe(configOptionUpdates ? 'low' : undefined);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -207,6 +207,13 @@ export class AcpSdkBackend implements AgentBackend {
|
||||
* would wait on a request nobody answers.
|
||||
*/
|
||||
elicitationForm?: boolean;
|
||||
/**
|
||||
* Refresh cached config options (model, thought_level, ...) from ACP
|
||||
* `config_option_update` notifications. Opt-in for agents whose
|
||||
* `session/set_model` response carries no options and which push the
|
||||
* new model's options this way instead.
|
||||
*/
|
||||
configOptionUpdates?: boolean;
|
||||
textChunkMode?: AcpTextChunkMode;
|
||||
flavor?: AgentFlavor;
|
||||
}) {}
|
||||
@@ -1315,6 +1322,9 @@ export class AcpSdkBackend implements AgentBackend {
|
||||
// work is queued so async image registration preserves event order.
|
||||
if (sessionId) {
|
||||
this.captureAvailableCommands(sessionId, update);
|
||||
if (this.options.configOptionUpdates && isObject(update) && update.sessionUpdate === 'config_option_update') {
|
||||
this.captureSessionConfigOptions(sessionId, update);
|
||||
}
|
||||
}
|
||||
this.forwardSessionInfoUpdate(sessionId, update);
|
||||
this.captureUsageUpdate(update);
|
||||
|
||||
@@ -16,6 +16,7 @@ export const kimiCommand: CommandDefinition = {
|
||||
startingMode?: 'local' | 'remote'
|
||||
permissionMode?: KimiPermissionMode
|
||||
model?: string
|
||||
effort?: string
|
||||
resumeSessionId?: string
|
||||
existingSessionId?: string
|
||||
reservedSessionId?: string
|
||||
@@ -68,6 +69,12 @@ export const kimiCommand: CommandDefinition = {
|
||||
throw new Error('Missing --model value')
|
||||
}
|
||||
options.model = model
|
||||
} else if (arg === '--effort') {
|
||||
const effort = commandArgs[++i]
|
||||
if (!effort) {
|
||||
throw new Error('Missing --effort value')
|
||||
}
|
||||
options.effort = effort
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -157,7 +157,8 @@ async function dispatchLocalResume(target: LocalResumeTarget): Promise<void> {
|
||||
startedBy: base.startedBy,
|
||||
permissionMode: base.permissionMode as KimiPermissionMode | undefined,
|
||||
startingMode: 'local',
|
||||
model: target.model ?? undefined
|
||||
model: target.model ?? undefined,
|
||||
effort: target.effort ?? undefined
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@ import { MessageQueue2 } from '@/utils/MessageQueue2'
|
||||
import type { KimiMode } from './types'
|
||||
|
||||
const harness = vi.hoisted(() => ({
|
||||
prompts: [] as unknown[][]
|
||||
prompts: [] as unknown[][],
|
||||
configCalls: [] as unknown[][],
|
||||
thinking: 'on'
|
||||
}))
|
||||
|
||||
vi.mock('./utils/kimiBackend', () => ({
|
||||
@@ -11,7 +13,15 @@ vi.mock('./utils/kimiBackend', () => ({
|
||||
initialize: vi.fn(async () => {}),
|
||||
newSession: vi.fn(async () => 'kimi-session-1'),
|
||||
loadSession: vi.fn(async () => 'kimi-session-1'),
|
||||
setModel: vi.fn(async () => {}),
|
||||
// Mimics config_option_update: a new model reports its own level.
|
||||
setModel: vi.fn(async (_sessionId: string, model: string) => {
|
||||
if (model === 'kimi-k3') harness.thinking = 'medium'
|
||||
}),
|
||||
getThoughtLevelConfigOption: vi.fn(() => ({ id: 'thinking', currentValue: harness.thinking, options: [] })),
|
||||
setConfigOption: vi.fn(async (...args: unknown[]) => {
|
||||
harness.configCalls.push(args)
|
||||
harness.thinking = args[2] as string
|
||||
}),
|
||||
prompt: vi.fn(async (_sessionId: string, content: unknown[]) => {
|
||||
harness.prompts.push(content)
|
||||
}),
|
||||
@@ -45,10 +55,13 @@ vi.mock('@/ui/logger', () => ({
|
||||
|
||||
import { kimiRemoteLauncher } from './kimiRemoteLauncher'
|
||||
|
||||
function createSession() {
|
||||
function createSession(modes: KimiMode[] = [
|
||||
{ permissionMode: 'default', model: 'kimi-k2' },
|
||||
{ permissionMode: 'default', model: 'kimi-k2' }
|
||||
]) {
|
||||
const queue = new MessageQueue2<KimiMode>((mode) => JSON.stringify(mode))
|
||||
queue.pushIsolateAndClear('first', { permissionMode: 'default', model: 'kimi-k2' })
|
||||
queue.push('second', { permissionMode: 'default', model: 'kimi-k2' })
|
||||
queue.pushIsolateAndClear('first', modes[0])
|
||||
queue.push('second', modes[1])
|
||||
queue.close()
|
||||
|
||||
const session = {
|
||||
@@ -67,7 +80,9 @@ function createSession() {
|
||||
onSessionFound(id: string) { session.sessionId = id },
|
||||
onThinkingChange: vi.fn(),
|
||||
sendAgentMessage: vi.fn(),
|
||||
sendSessionEvent: vi.fn()
|
||||
sendSessionEvent: vi.fn(),
|
||||
setEffort: vi.fn(),
|
||||
pushKeepAlive: vi.fn()
|
||||
}
|
||||
return session
|
||||
}
|
||||
@@ -75,6 +90,8 @@ function createSession() {
|
||||
describe('kimiRemoteLauncher skill lookup instruction', () => {
|
||||
afterEach(() => {
|
||||
harness.prompts = []
|
||||
harness.configCalls = []
|
||||
harness.thinking = 'on'
|
||||
})
|
||||
|
||||
it('does not prepend skill_lookup instructions onto user turns', async () => {
|
||||
@@ -86,4 +103,28 @@ describe('kimiRemoteLauncher skill lookup instruction', () => {
|
||||
expect(JSON.stringify(harness.prompts[0])).not.toContain('$name')
|
||||
expect(JSON.stringify(harness.prompts[1])).not.toContain('skill_lookup')
|
||||
})
|
||||
|
||||
it('applies the queued effort and resets to the agent default', async () => {
|
||||
await kimiRemoteLauncher(createSession([
|
||||
{ permissionMode: 'default', model: 'kimi-k2', effort: 'high' },
|
||||
{ permissionMode: 'default', model: 'kimi-k2', effort: null }
|
||||
]) as never, { model: 'kimi-k2' })
|
||||
|
||||
expect(harness.configCalls).toEqual([
|
||||
['kimi-session-1', 'thinking', 'high'],
|
||||
['kimi-session-1', 'thinking', 'on']
|
||||
])
|
||||
})
|
||||
|
||||
it('re-applies the selected effort after a model switch changes the agent level', async () => {
|
||||
await kimiRemoteLauncher(createSession([
|
||||
{ permissionMode: 'default', model: 'kimi-k2', effort: 'high' },
|
||||
{ permissionMode: 'default', model: 'kimi-k3', effort: 'high' }
|
||||
]) as never, { model: 'kimi-k2' })
|
||||
|
||||
expect(harness.configCalls).toEqual([
|
||||
['kimi-session-1', 'thinking', 'high'],
|
||||
['kimi-session-1', 'thinking', 'high']
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -11,9 +11,12 @@ import type { PermissionMode } from './types';
|
||||
import { createKimiBackend } from './utils/kimiBackend';
|
||||
import { KimiPermissionHandler } from './utils/permissionHandler';
|
||||
import { resolveKimiRuntimeConfig } from './utils/config';
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
|
||||
class KimiRemoteLauncher extends RemoteLauncherBase {
|
||||
private readonly session: KimiSession;
|
||||
private readonly model?: string;
|
||||
private readonly onEffortRollback?: (effort: string | null) => void;
|
||||
private readonly getQueuedModel?: () => string | null;
|
||||
private backend: ReturnType<typeof createKimiBackend> | null = null;
|
||||
private permissionHandler: KimiPermissionHandler | null = null;
|
||||
private happyServer: { stop: () => void } | null = null;
|
||||
@@ -21,12 +24,21 @@ class KimiRemoteLauncher extends RemoteLauncherBase {
|
||||
private displayModel: string | null = null;
|
||||
private displayPermissionMode: PermissionMode | null = null;
|
||||
private currentBackendModel: string | null = null;
|
||||
private currentBackendEffort: string | null = null;
|
||||
private defaultBackendEffort: string | null = null;
|
||||
private setModelSupported: boolean | undefined = undefined;
|
||||
private lastDisplayedToolCall = new Map<string, string>();
|
||||
constructor(session: KimiSession, opts: { model?: string }) {
|
||||
constructor(session: KimiSession, opts: {
|
||||
model?: string;
|
||||
onEffortRollback?: (effort: string | null) => void;
|
||||
/** Model the next queued turn will carry; differs from the backend's while a switch is pending. */
|
||||
getQueuedModel?: () => string | null;
|
||||
}) {
|
||||
super(process.env.DEBUG ? session.logPath : undefined);
|
||||
this.session = session;
|
||||
this.model = opts.model;
|
||||
this.onEffortRollback = opts.onEffortRollback;
|
||||
this.getQueuedModel = opts.getQueuedModel;
|
||||
}
|
||||
|
||||
public async launch(): Promise<RemoteLauncherExitReason> {
|
||||
@@ -118,6 +130,17 @@ class KimiRemoteLauncher extends RemoteLauncherBase {
|
||||
messageBuffer.addMessage(`[MODEL:${effectiveModel}]`, 'system');
|
||||
}
|
||||
this.applyDisplayMode(session.getPermissionMode() as PermissionMode, effectiveModel ?? undefined);
|
||||
this.captureEffortBaseline(acpSessionId);
|
||||
session.client.rpcHandlerManager.registerHandler(RPC_METHODS.ListKimiReasoningEffortOptions, async () => {
|
||||
// A model change is applied with the turn that carries it; until
|
||||
// then (or after it failed) the cached levels belong to another model.
|
||||
const queuedModel = this.getQueuedModel?.() ?? null;
|
||||
if (queuedModel !== null && queuedModel !== this.currentBackendModel) {
|
||||
return { success: false, error: 'Kimi model switch pending' };
|
||||
}
|
||||
const option = backend.getThoughtLevelConfigOption(acpSessionId);
|
||||
return { success: true, options: option?.options ?? [], currentValue: option?.currentValue ?? null };
|
||||
});
|
||||
|
||||
this.setupAbortHandlers(session.client.rpcHandlerManager, {
|
||||
onAbort: () => this.handleAbort(),
|
||||
@@ -137,6 +160,7 @@ class KimiRemoteLauncher extends RemoteLauncherBase {
|
||||
break;
|
||||
}
|
||||
|
||||
const modelBeforeBatch = this.currentBackendModel;
|
||||
if (batch.mode.model && batch.mode.model !== this.currentBackendModel) {
|
||||
if (!backend.setModel || this.setModelSupported === false) {
|
||||
batch.mode.model = this.currentBackendModel ?? undefined;
|
||||
@@ -168,6 +192,11 @@ class KimiRemoteLauncher extends RemoteLauncherBase {
|
||||
}
|
||||
}
|
||||
|
||||
if (this.currentBackendModel !== modelBeforeBatch) {
|
||||
this.captureEffortBaseline(acpSessionId);
|
||||
}
|
||||
await this.applyQueuedEffort(acpSessionId, batch.mode);
|
||||
|
||||
this.applyDisplayMode(batch.mode.permissionMode, batch.mode.model);
|
||||
messageBuffer.addMessage(batch.message, 'user');
|
||||
|
||||
@@ -203,6 +232,35 @@ class KimiRemoteLauncher extends RemoteLauncherBase {
|
||||
}
|
||||
}
|
||||
|
||||
/** The agent's level for the active model; "Default" resets to it. */
|
||||
private captureEffortBaseline(sessionId: string): void {
|
||||
this.currentBackendEffort = this.backend?.getThoughtLevelConfigOption(sessionId)?.currentValue ?? null;
|
||||
this.defaultBackendEffort = this.currentBackendEffort;
|
||||
}
|
||||
|
||||
private async applyQueuedEffort(sessionId: string, mode: { effort?: string | null }): Promise<void> {
|
||||
const backend = this.backend;
|
||||
const requested = mode.effort ?? this.defaultBackendEffort;
|
||||
if (!backend || !requested || requested === this.currentBackendEffort) return;
|
||||
const option = backend.getThoughtLevelConfigOption(sessionId);
|
||||
try {
|
||||
if (!option) throw new Error('no thinking option');
|
||||
await backend.setConfigOption(sessionId, option.id, requested);
|
||||
this.currentBackendEffort = requested;
|
||||
} catch (error) {
|
||||
logger.warn('[kimi-remote] Inline effort switch failed', error);
|
||||
const effort = this.currentBackendEffort === this.defaultBackendEffort ? null : this.currentBackendEffort;
|
||||
mode.effort = effort;
|
||||
this.session.setEffort(effort);
|
||||
this.session.pushKeepAlive();
|
||||
this.onEffortRollback?.(effort);
|
||||
this.session.sendSessionEvent({
|
||||
type: 'message',
|
||||
message: `Failed to switch Kimi effort to ${requested}.`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
protected async cleanup(): Promise<void> {
|
||||
this.clearAbortHandlers(this.session.client.rpcHandlerManager);
|
||||
|
||||
@@ -359,7 +417,7 @@ function toAcpMcpServers(config: Record<string, { command: string; args: string[
|
||||
|
||||
export async function kimiRemoteLauncher(
|
||||
session: KimiSession,
|
||||
opts: { model?: string }
|
||||
opts: ConstructorParameters<typeof KimiRemoteLauncher>[1]
|
||||
): Promise<'switch' | 'exit'> {
|
||||
const launcher = new KimiRemoteLauncher(session, opts);
|
||||
return launcher.launch();
|
||||
|
||||
@@ -19,6 +19,8 @@ interface KimiLoopOptions {
|
||||
model?: string;
|
||||
resumeSessionId?: string;
|
||||
onSessionReady?: (session: KimiSession) => void;
|
||||
onEffortRollback?: (effort: string | null) => void;
|
||||
getQueuedModel?: () => string | null;
|
||||
}
|
||||
|
||||
export async function kimiLoop(opts: KimiLoopOptions): Promise<void> {
|
||||
@@ -57,7 +59,9 @@ export async function kimiLoop(opts: KimiLoopOptions): Promise<void> {
|
||||
model: getCurrentModel()
|
||||
}),
|
||||
runRemote: (instance) => kimiRemoteLauncher(instance, {
|
||||
model: getCurrentModel()
|
||||
model: getCurrentModel(),
|
||||
onEffortRollback: opts.onEffortRollback,
|
||||
getQueuedModel: opts.getQueuedModel
|
||||
}),
|
||||
onSessionReady: opts.onSessionReady
|
||||
});
|
||||
|
||||
+20
-6
@@ -21,6 +21,7 @@ export async function runKimi(opts: {
|
||||
startingMode?: 'local' | 'remote';
|
||||
permissionMode?: PermissionMode;
|
||||
model?: string;
|
||||
effort?: string;
|
||||
resumeSessionId?: string;
|
||||
existingSessionId?: string;
|
||||
/** Fresh-spawn reserved hub id from `--hapi-session-id` (create/getOrCreate). */
|
||||
@@ -71,13 +72,15 @@ export async function runKimi(opts: {
|
||||
|
||||
const messageQueue = new MessageQueue2<KimiMode>((mode) => hashObject({
|
||||
permissionMode: mode.permissionMode,
|
||||
model: mode.model
|
||||
model: mode.model,
|
||||
effort: mode.effort
|
||||
}));
|
||||
|
||||
const sessionWrapperRef: { current: KimiSession | null } = { current: null };
|
||||
let currentPermissionMode: PermissionMode = opts.permissionMode ?? 'default';
|
||||
let sessionModel: string | null = persistedModel ?? null;
|
||||
let resolvedModel = sessionModel ?? machineDefault;
|
||||
let sessionEffort: string | null = opts.effort ?? null;
|
||||
|
||||
const lifecycle = createRunnerLifecycle({
|
||||
session,
|
||||
@@ -100,6 +103,7 @@ export async function runKimi(opts: {
|
||||
}
|
||||
sessionInstance.setPermissionMode(currentPermissionMode);
|
||||
sessionInstance.setModel(sessionModel);
|
||||
sessionInstance.setEffort(sessionEffort);
|
||||
sessionInstance.pushKeepAlive();
|
||||
|
||||
logger.debug(`[kimi] Synced session config for keepalive: permissionMode=${currentPermissionMode}, model=${resolvedModel}`);
|
||||
@@ -109,7 +113,8 @@ export async function runKimi(opts: {
|
||||
const formattedText = formatMessageWithAttachments(message.content.text, message.content.attachments);
|
||||
const mode: KimiMode = {
|
||||
permissionMode: currentPermissionMode,
|
||||
model: resolvedModel
|
||||
model: resolvedModel,
|
||||
effort: sessionEffort
|
||||
};
|
||||
messageQueue.push(formattedText, mode, localId);
|
||||
});
|
||||
@@ -128,12 +133,12 @@ export async function runKimi(opts: {
|
||||
return parsed.data as PermissionMode;
|
||||
};
|
||||
|
||||
const resolveModel = (value: unknown): string | null => {
|
||||
const resolveModel = (value: unknown, label = 'model'): string | null => {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value !== 'string' || value.trim().length === 0) {
|
||||
throw new Error('Invalid model');
|
||||
throw new Error(`Invalid ${label}`);
|
||||
}
|
||||
return value.trim();
|
||||
};
|
||||
@@ -142,7 +147,7 @@ export async function runKimi(opts: {
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
throw new Error('Invalid session config payload');
|
||||
}
|
||||
const config = payload as { permissionMode?: unknown; model?: unknown };
|
||||
const config = payload as { permissionMode?: unknown; model?: unknown; effort?: unknown };
|
||||
const applied: Record<string, unknown> = {};
|
||||
|
||||
if (config.permissionMode !== undefined) {
|
||||
@@ -156,6 +161,11 @@ export async function runKimi(opts: {
|
||||
applied.model = sessionModel;
|
||||
}
|
||||
|
||||
if (config.effort !== undefined) {
|
||||
sessionEffort = resolveModel(config.effort, 'effort');
|
||||
applied.effort = sessionEffort;
|
||||
}
|
||||
|
||||
syncSessionMode();
|
||||
return { applied };
|
||||
});
|
||||
@@ -177,7 +187,11 @@ export async function runKimi(opts: {
|
||||
onSessionReady: (instance) => {
|
||||
sessionWrapperRef.current = instance;
|
||||
syncSessionMode();
|
||||
}
|
||||
},
|
||||
onEffortRollback: (effort) => {
|
||||
sessionEffort = effort;
|
||||
},
|
||||
getQueuedModel: () => resolvedModel ?? null
|
||||
});
|
||||
} catch (error) {
|
||||
crashed = true;
|
||||
|
||||
@@ -58,6 +58,10 @@ export class KimiSession extends AgentSessionBase<KimiMode> {
|
||||
this.model = model;
|
||||
};
|
||||
|
||||
setEffort = (effort: string | null): void => {
|
||||
this.effort = effort;
|
||||
};
|
||||
|
||||
recordLocalLaunchFailure = (message: string, exitReason: LocalLaunchExitReason): void => {
|
||||
this.localLaunchFailure = { message, exitReason };
|
||||
};
|
||||
|
||||
@@ -5,4 +5,5 @@ export type PermissionMode = KimiPermissionMode;
|
||||
export interface KimiMode {
|
||||
permissionMode: PermissionMode;
|
||||
model?: string;
|
||||
effort?: string | null;
|
||||
}
|
||||
|
||||
@@ -24,5 +24,6 @@ export function createKimiBackend(): AcpSdkBackend {
|
||||
args: ['acp'],
|
||||
env: filterEnv(process.env),
|
||||
flavor: 'kimi',
|
||||
configOptionUpdates: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2128,7 +2128,7 @@ export function buildCliArgs(
|
||||
if (options.model) {
|
||||
args.push('--model', options.model);
|
||||
}
|
||||
if (options.effort && (agent === 'claude' || agent === 'grok' || agent === 'pi' || agent === 'agy')) {
|
||||
if (options.effort && (agent === 'claude' || agent === 'grok' || agent === 'pi' || agent === 'agy' || agent === 'kimi')) {
|
||||
args.push('--effort', options.effort);
|
||||
}
|
||||
if (options.modelReasoningEffort && (agent === 'codex' || agent === 'opencode')) {
|
||||
|
||||
Reference in New Issue
Block a user