feat: add support for Kimi Code CLI and fixed some bugs (#659)

* Add Kimi agent support via ACP protocol

Add full integration for the Kimi Code CLI agent using the standard
Agent Client Protocol (ACP). Includes:

- kimi command and CLI registry wiring
- Local launcher spawning kimi directly
- Remote launcher with ACP stdio transport via AcpSdkBackend
- Session management with resume support
- Permission handler supporting all Kimi permission modes
- Terminal UI display component
- Runtime config resolving model from env and ~/.kimi/config.toml

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* Fix Kimi ACP tool call input decoding on web

Kimi streams tool arguments as JSON text inside the content array
(e.g. {\"command\": \"df -h\"}) instead of rawInput/kind. The handler
now extracts input from three sources in priority order:

1. rawInput (Claude/Codex path)
2. kind + title fallback (Gemini path)
3. content JSON text (Kimi path)

Also handles:
- rawInput: null no longer blocks the kind+title fallback
- Title prefixes like \"Shell: free -h\" are stripped to extract args
- Stale placeholder inputs are re-derived when the title updates
- Normalized kind aliases (shell, run, read_file, write, etc.)

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* Add kimi support to web UI

* Fix some bugs

* fix(kimi): dedupe repeated tool_call display in terminal UI

* fix(web): keep tool block immutable so React detects input/state changes

* fix(web): recognise Kimi subagent titles like 'Agent: ...' as subagent tools

* fix(web): allow-for-session for ACP agents (kimi, cursor)

PermissionFooter treated all non-codex sessions as Claude, sending
Claude-specific acceptEdits/allowTools to ACP agents that don't
support them. Hub rejected acceptEdits for kimi, and the ACP
PermissionAdapter ignored allowTools.

- Only show 'allow all edits' for Claude sessions
- Send decision: approved_for_session for non-Claude ACP agents
- Update status display to check decision field

* fix(web): lookup subagent sidechains by tool-call id instead of msg id

* fix(web): don't trim newest messages when loading older history

fetchOlderMessages was using trimVisible(merged, 'prepend') which kept
the oldest 400 messages and dropped the newest ones. This caused:
1. Latest messages to disappear when user loaded older history
2. User to see no visible change when new old messages were drowned
   in the 400-message window.

Remove the incorrect trim so all fetched older messages are retained
alongside the current window. Subsequent ingestIncomingMessages
(append mode) will naturally keep the window bounded when new agent
messages arrive.

* fix(cli): route Kimi session resume to runKimi instead of runCursor

Kimi was present in AGENT_FLAVORS but dispatchLocalResume had no branch
for it, so resuming a Kimi session fell through to the Cursor launcher.

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* fix(cli): pass selected model to Kimi ACP backend via KIMI_MODEL env

createKimiBackend was ignoring opts.model and only setting KIMI_PROJECT_DIR.
Use buildKimiEnv so the selected model reaches the subprocess as KIMI_MODEL.

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* fix(web): bound message window on older loads with dedicated larger cap

fetchOlderMessages was keeping all messages unbounded, causing
sessionStorage bloat on repeated pagination. Reintroduce trimming
with OLDER_LOAD_WINDOW_SIZE (800) so growth is capped while the
newest messages are still preserved for far longer than before.

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* fix(web): revert sidechain lookup to message id, matching tracer/grouping pipeline

tracer.ts sets sidechainId to the parent message id, and reducer.ts groups
by sidechainId. A prior commit changed reducerTimeline.ts to look up by
tool-call id (c.id), which broke sidechain attachment. Revert to msg.id
so the lookup matches the actual grouping key end-to-end.

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* fix(cli): gate ACP title prefix stripping to known tool-kind labels

extractTitleArgument stripped at the first colon unconditionally,
corrupting commands/paths like curl http://localhost:3000 or
Windows paths. Now it only strips when the prefix normalizes to
the same tool kind as the event, verified via regex.

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

* fix(shared): include kimi in isCodexFamilyFlavor for ACP permission UI

Kimi is an ACP-style agent that supports the abort decision, but
isCodexFamilyFlavor excluded it, so PermissionFooter rendered the
non-Codex Allow/Deny UI without the Abort button.

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>

---------

Co-authored-by: HAPI <noreply@hapi.run>
This commit is contained in:
凌
2026-05-22 10:08:14 +08:00
committed by GitHub
co-authored by HAPI
parent 6aa7274851
commit 763f45acdd
35 changed files with 1697 additions and 54 deletions
+187
View File
@@ -0,0 +1,187 @@
import React, { useEffect, useState } from 'react';
import { Box, Text, useStdout } from 'ink';
import { MessageBuffer, type BufferedMessage } from './messageBuffer';
import { useSwitchControls } from './useSwitchControls';
interface KimiDisplayProps {
messageBuffer: MessageBuffer;
logPath?: string;
onExit?: () => void;
onSwitchToLocal?: () => void;
}
function extractTag(messages: BufferedMessage[], tag: 'MODEL' | 'MODE'): string | null {
const prefix = `[${tag}:`;
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (message.type !== 'system') {
continue;
}
if (!message.content.startsWith(prefix)) {
continue;
}
const match = message.content.match(/\[\w+:(.+?)\]/);
if (match && match[1]) {
return match[1];
}
}
return null;
}
export const KimiDisplay: React.FC<KimiDisplayProps> = ({
messageBuffer,
logPath,
onExit,
onSwitchToLocal
}) => {
const [messages, setMessages] = useState<BufferedMessage[]>([]);
const [model, setModel] = useState<string | null>(null);
const [permissionMode, setPermissionMode] = useState<string | null>(null);
const { confirmationMode, actionInProgress } = useSwitchControls({
onExit,
onSwitch: onSwitchToLocal
});
const { stdout } = useStdout();
const terminalWidth = stdout.columns || 80;
const terminalHeight = stdout.rows || 24;
useEffect(() => {
setMessages(messageBuffer.getMessages());
const unsubscribe = messageBuffer.onUpdate((newMessages) => {
setMessages(newMessages);
const nextModel = extractTag(newMessages, 'MODEL');
if (nextModel) {
setModel(nextModel);
}
const nextMode = extractTag(newMessages, 'MODE');
if (nextMode) {
setPermissionMode(nextMode);
}
});
return () => {
unsubscribe();
};
}, [messageBuffer]);
const getMessageColor = (type: BufferedMessage['type']): string => {
switch (type) {
case 'user': return 'magenta';
case 'assistant': return 'cyan';
case 'system': return 'blue';
case 'tool': return 'yellow';
case 'result': return 'green';
case 'status': return 'gray';
default: return 'white';
}
};
const formatMessage = (msg: BufferedMessage): string => {
const lines = msg.content.split('\n');
const maxLineLength = Math.max(1, terminalWidth - 10);
return lines.map(line => {
if (line.length <= maxLineLength) return line;
const chunks: string[] = [];
for (let i = 0; i < line.length; i += maxLineLength) {
chunks.push(line.slice(i, i + maxLineLength));
}
return chunks.join('\n');
}).join('\n');
};
const visibleMessages = messages.filter((msg) => {
if (msg.type === 'system' && msg.content.startsWith('[MODEL:')) {
return false;
}
if (msg.type === 'system' && msg.content.startsWith('[MODE:')) {
return false;
}
return true;
});
return (
<Box flexDirection="column" width={terminalWidth} height={terminalHeight}>
<Box
flexDirection="column"
width={terminalWidth}
height={terminalHeight - 4}
borderStyle="round"
borderColor="gray"
paddingX={1}
overflow="hidden"
>
<Box flexDirection="column" marginBottom={1}>
<Text color="gray" bold>Kimi Agent Messages</Text>
<Text color="gray" dimColor>{'-'.repeat(Math.min(terminalWidth - 4, 60))}</Text>
</Box>
<Box flexDirection="column" height={terminalHeight - 10} overflow="hidden">
{visibleMessages.length === 0 ? (
<Text color="gray" dimColor>Waiting for messages...</Text>
) : (
visibleMessages
.slice(-Math.max(1, terminalHeight - 10))
.map((msg) => (
<Box key={msg.id} flexDirection="column" marginBottom={1}>
<Text color={getMessageColor(msg.type)} dimColor>
{formatMessage(msg)}
</Text>
</Box>
))
)}
</Box>
</Box>
<Box
width={terminalWidth}
borderStyle="round"
borderColor={
actionInProgress ? 'gray' :
confirmationMode === 'exit' ? 'red' :
confirmationMode === 'switch' ? 'yellow' :
'green'
}
paddingX={2}
justifyContent="center"
alignItems="center"
flexDirection="column"
>
<Box flexDirection="column" alignItems="center">
{actionInProgress === 'exiting' ? (
<Text color="gray" bold>
Exiting agent...
</Text>
) : actionInProgress === 'switching' ? (
<Text color="gray" bold>
Switching to local mode...
</Text>
) : confirmationMode === 'exit' ? (
<Text color="red" bold>
Press Ctrl-C again to exit the agent
</Text>
) : confirmationMode === 'switch' ? (
<Text color="yellow" bold>
Press space again to switch to local mode
</Text>
) : (
<Text color="green" bold>
Kimi running {onSwitchToLocal ? '(Space to switch to local, Ctrl-C to exit)' : '(Ctrl-C to exit)'}
</Text>
)}
{(model || permissionMode) && (
<Text color="gray" dimColor>
{model ? `Model: ${model}` : 'Model: default'}
{permissionMode ? ` | Permission: ${permissionMode}` : ''}
</Text>
)}
{process.env.DEBUG && logPath && (
<Text color="gray" dimColor>
Debug logs: {logPath}
</Text>
)}
</Box>
</Box>
</Box>
);
};