Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/btw-side-agent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@moonshot-ai/agent-core": minor
"@moonshot-ai/kimi-code-sdk": minor
"@moonshot-ai/kimi-code": minor
---

Add `/btw` for side-channel conversations without steering the active main turn.
25 changes: 25 additions & 0 deletions apps/kimi-code/src/tui/commands/btw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { LLM_NOT_SET_MESSAGE } from '../constant/kimi-tui';
import { formatErrorMessage } from '../utils/event-payload';
import type { SlashCommandHost } from './dispatch';

export async function handleBtwCommand(host: SlashCommandHost, args: string): Promise<void> {
const prompt = args.trim();
if (prompt.length === 0) {
host.showError('Usage: /btw <question>');
return;
}

const session = host.session;
if (host.state.appState.model.trim().length === 0 || session === undefined) {
host.showError(LLM_NOT_SET_MESSAGE);
return;
}
host.btwPanelController.closeOrCancel();

try {
const agentId = await session.startBtw();
host.btwPanelController.open(agentId, prompt);
Comment thread
kermanx marked this conversation as resolved.
} catch (error) {
host.showError(`Failed to start /btw: ${formatErrorMessage(error)}`);
}
}
7 changes: 7 additions & 0 deletions apps/kimi-code/src/tui/commands/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ import {
} from './resolve';
import type { BuiltinSlashCommandName } from './registry';
import type { AuthFlowController } from '../controllers/auth-flow';
import type { BtwPanelController } from '../controllers/btw-panel';
import type { StreamingUIController } from '../controllers/streaming-ui';
import type { TasksBrowserController } from '../controllers/tasks-browser';
import type { AppState, LoginProgressSpinnerHandle, QueuedMessage } from '../types';
import type { TUIState } from '../tui-state';

import { handleLoginCommand, handleLogoutCommand } from './auth';
import { handleBtwCommand } from './btw';
import { tryHandleDanceCommand } from '../easter-eggs/dance';
import {
handleAutoCommand,
Expand Down Expand Up @@ -55,6 +57,7 @@ export {
handleLoginCommand,
handleLogoutCommand,
} from './auth';
export { handleBtwCommand } from './btw';
export {
handleAutoCommand,
handleCompactCommand,
Expand Down Expand Up @@ -132,6 +135,7 @@ export interface SlashCommandHost {

// Controller refs
readonly streamingUI: StreamingUIController;
readonly btwPanelController: BtwPanelController;
readonly tasksBrowserController: TasksBrowserController;
readonly authFlow: AuthFlowController;
}
Expand Down Expand Up @@ -258,6 +262,9 @@ async function handleBuiltInSlashCommand(
case 'feedback':
await handleFeedbackCommand(host);
return;
case 'btw':
await handleBtwCommand(host, args);
return;
case 'title':
await handleTitleCommand(host, args);
return;
Expand Down
1 change: 1 addition & 0 deletions apps/kimi-code/src/tui/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export {
handleLoginCommand,
handleLogoutCommand,
} from './auth';
export { handleBtwCommand } from './btw';
export {
handleCompactCommand,
handleEditorCommand,
Expand Down
7 changes: 7 additions & 0 deletions apps/kimi-code/src/tui/commands/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ export const BUILTIN_SLASH_COMMANDS = [
priority: 95,
availability: 'always',
},
{
name: 'btw',
aliases: [],
description: 'Ask a forked side agent a question',
priority: 90,
availability: 'always',
},
{
name: 'help',
aliases: ['h', '?'],
Expand Down
18 changes: 15 additions & 3 deletions apps/kimi-code/src/tui/components/editor/custom-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,10 @@ export class CustomEditor extends Editor {
* through so pi-tui's built-in history navigation runs.
*/
public onUpArrowEmpty?: () => boolean;
public onDownArrowEmpty?: () => boolean;
public onShiftTab?: () => void;
public connectedAbove = false;
public borderHighlighted = false;
/**
* Called when the user triggers "paste image" (Ctrl-V on Unix,
* Alt-V on Windows — Ctrl-V is terminal-reserved there). Return
Expand Down Expand Up @@ -213,7 +216,9 @@ export class CustomEditor extends Editor {
// overwrite it (e.g. plan-mode / slash-context highlight via
// `editor.borderColor = chalk.hex(primary)`), so we route corners and
// side bars through the same hook to stay in sync.
return wrapWithSideBorders(lines, (s) => this.borderColor(s));
return wrapWithSideBorders(lines, (s) => this.borderColor(s), {
connectedAbove: this.connectedAbove && !this.borderHighlighted,
});
}

override handleInput(data: string): void {
Expand Down Expand Up @@ -320,6 +325,12 @@ export class CustomEditor extends Editor {
}
}

if (matchesKey(normalized, Key.down)) {
if (this.getText().length === 0 && this.onDownArrowEmpty) {
if (this.onDownArrowEmpty()) return;
}
}

if (matchesKey(normalized, Key.escape)) {
if (this.hasAutocompleteActivity()) {
this.cancelAutocompleteActivity();
Expand Down Expand Up @@ -398,13 +409,14 @@ export function injectPromptSymbol(line: string): string | undefined {
export function wrapWithSideBorders(
lines: string[],
paint: (s: string) => string,
options: { readonly connectedAbove?: boolean } = {},
): string[] {
let seenTop = false;
return lines.map((line) => {
const plain = stripSgr(line);
if (plain.length > 0 && plain[0] === '─') {
const leftCorner = seenTop ? '╰' : '╭';
const rightCorner = seenTop ? '╯' : '╮';
const leftCorner = seenTop ? '╰' : options.connectedAbove === true ? '├' : '╭';
const rightCorner = seenTop ? '╯' : options.connectedAbove === true ? '┤' : '╮';
seenTop = true;
if (plain.length === 1) return paint(leftCorner);
const middle = plain.slice(1, -1);
Expand Down
247 changes: 247 additions & 0 deletions apps/kimi-code/src/tui/components/panes/btw-panel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
import type { Component, MarkdownTheme } from '@earendil-works/pi-tui';
import {
Markdown,
Text,
truncateToWidth,
visibleWidth,
} from '@earendil-works/pi-tui';
import chalk from 'chalk';

import { THINKING_PREVIEW_LINES } from '../../constant/rendering';
import type { ColorPalette } from '../../theme/colors';

type BtwPanelPhase = 'running' | 'done' | 'failed';

const MIN_COLLAPSED_PANEL_LINES = 3;

interface BtwTurn {
readonly prompt: string;
answer: string;
thinking: string;
error?: string | undefined;
phase: BtwPanelPhase;
}

interface BtwBodyRender {
readonly lines: string[];
readonly truncated: boolean;
}

export interface BtwPanelOptions {
readonly colors: ColorPalette;
readonly markdownTheme: MarkdownTheme;
readonly canUseScrollKeys: () => boolean;
readonly onPrompt: (prompt: string) => void;
readonly terminalRows: () => number;
}

export class BtwPanelComponent implements Component {
private readonly turns: BtwTurn[] = [];
private readonly transientNotices: string[] = [];
private minBodyLines = 0;
private followTail = true;
private scrollTop = 0;
private maxScrollTop = 0;

constructor(private readonly options: BtwPanelOptions) {}

submit(prompt: string): void {
const normalized = prompt.trim();
if (normalized.length === 0 || this.isRunning()) return;
this.followTail = true;
this.scrollTop = 0;
this.transientNotices.length = 0;
this.turns.push({
prompt: normalized,
answer: '',
thinking: '',
phase: 'running',
});
this.options.onPrompt(normalized);
}

addTransientNotice(message: string): void {
this.transientNotices.push(message);
this.followTail = true;
}

appendAnswer(delta: string): void {
const turn = this.currentTurn();
if (turn === undefined) return;
turn.answer += delta;
}

appendThinking(delta: string): void {
const turn = this.currentTurn();
if (turn === undefined) return;
turn.thinking += delta;
}

markDone(resultSummary?: string | undefined): void {
const turn = this.currentTurn();
if (turn === undefined) return;
if (turn.answer.trim().length === 0 && resultSummary !== undefined) {
turn.answer = resultSummary;
}
this.transientNotices.length = 0;
turn.phase = 'done';
}

markFailed(error: string): void {
const turn = this.currentTurn();
if (turn === undefined || turn.phase !== 'running') {
this.turns.push({
prompt: '',
answer: '',
thinking: '',
error,
phase: 'failed',
});
this.transientNotices.length = 0;
return;
}
turn.error = error;
this.transientNotices.length = 0;
turn.phase = 'failed';
}

invalidate(): void {}

render(width: number): string[] {
const safeWidth = Math.max(4, width);
const contentWidth = Math.max(1, safeWidth - 4);
const body = this.renderBody(contentWidth);
const lines = [this.renderTopBorder(safeWidth, body.truncated)];
for (const line of body.lines) {
lines.push(this.renderBodyLine(line, safeWidth));
}
return lines;
}

private renderTopBorder(width: number, truncated: boolean): string {
const paint = (s: string): string => chalk.hex(this.options.colors.border)(s);
const hint = truncated && this.options.canUseScrollKeys()
? 'Esc close · ↑↓ scroll '
: 'Esc close ';
const title =
chalk.hex(this.options.colors.accent).bold(' BTW ') +
paint('─ ') +
chalk.hex(this.options.colors.textMuted)(hint);
const innerWidth = Math.max(1, width - 2);
const clippedTitle =
visibleWidth(title) > innerWidth ? truncateToWidth(title, innerWidth, '') : title;
const dashCount = Math.max(0, innerWidth - visibleWidth(clippedTitle));
return paint('╭') + clippedTitle + paint('─'.repeat(dashCount)) + paint('╮');
}

private renderBody(width: number): BtwBodyRender {
const lines: string[] = [];
for (const [index, turn] of this.turns.entries()) {
if (index > 0) lines.push('');
lines.push(...this.renderTurn(turn, width));
}
if (this.turns.length === 0) {
lines.push(chalk.hex(this.options.colors.textDim)('Ready for a side question...'));
}
lines.push(...this.renderTransientNotices(width));
return this.fitBodyLines(lines);
}

private renderTransientNotices(width: number): string[] {
const lines: string[] = [];
for (const notice of this.transientNotices) {
lines.push(...new Text(chalk.hex(this.options.colors.textDim)(notice), 0, 0).render(width));
}
return lines;
}

private fitBodyLines(lines: string[]): BtwBodyRender {
const bodyLimit = this.collapsedBodyLimit();
const targetUncapped = Math.max(this.minBodyLines, lines.length);
const target =
bodyLimit === undefined ? targetUncapped : Math.min(bodyLimit, targetUncapped);
this.minBodyLines = Math.max(this.minBodyLines, target);

if (lines.length > target) {
this.maxScrollTop = lines.length - target;
if (this.followTail) {
this.scrollTop = this.maxScrollTop;
} else {
this.scrollTop = Math.min(this.scrollTop, this.maxScrollTop);
}
const start = this.scrollTop;
return { lines: lines.slice(start, start + target), truncated: true };
}

this.followTail = true;
this.scrollTop = 0;
this.maxScrollTop = 0;
const padded = [...lines];
while (padded.length < target) {
padded.push('');
}
return { lines: padded, truncated: false };
}

private collapsedBodyLimit(): number | undefined {
const terminalRows = this.options.terminalRows();
if (!Number.isFinite(terminalRows) || terminalRows <= 0) return undefined;
const maxPanelLines = Math.max(MIN_COLLAPSED_PANEL_LINES, Math.floor(terminalRows / 2));
return Math.max(1, maxPanelLines - 1);
}

private renderTurn(turn: BtwTurn, width: number): string[] {
const prompt = chalk.hex(this.options.colors.accent)(`Q: ${turn.prompt}`);
const lines = [...new Text(prompt, 0, 0).render(width)];
const answer = turn.answer.trim();
const thinking = turn.thinking.trim();
if (answer.length > 0) {
lines.push(...new Markdown(answer, 0, 0, this.options.markdownTheme).render(width));
} else if (thinking.length > 0) {
const thinkingLines = new Text(chalk.hex(this.options.colors.textDim)(thinking), 0, 0).render(
width,
);
const visibleThinking =
thinkingLines.length > THINKING_PREVIEW_LINES
? thinkingLines.slice(thinkingLines.length - THINKING_PREVIEW_LINES)
: thinkingLines;
lines.push(...visibleThinking);
} else if (turn.error === undefined) {
lines.push(chalk.hex(this.options.colors.textDim)('Waiting for answer...'));
}
if (turn.error !== undefined) {
const error = chalk.hex(this.options.colors.error)(turn.error);
lines.push(...new Text(error, 0, 0).render(width));
}
return lines;
}

private renderBodyLine(line: string, width: number): string {
const paint = (s: string): string => chalk.hex(this.options.colors.border)(s);
const contentWidth = Math.max(1, width - 4);
const clipped =
visibleWidth(line) > contentWidth ? truncateToWidth(line, contentWidth, '…') : line;
const padding = Math.max(0, contentWidth - visibleWidth(clipped));
return paint('│') + ' ' + clipped + ' '.repeat(padding) + ' ' + paint('│');
}

private currentTurn(): BtwTurn | undefined {
return this.turns.at(-1);
}

isRunning(): boolean {
return this.currentTurn()?.phase === 'running';
}

scroll(direction: 'up' | 'down'): boolean {
if (this.maxScrollTop <= 0) return false;
const current = this.followTail ? this.maxScrollTop : this.scrollTop;
const next =
direction === 'up'
? Math.max(0, current - 1)
: Math.min(this.maxScrollTop, current + 1);
this.scrollTop = next;
this.followTail = next === this.maxScrollTop;
return true;
}
}
Loading
Loading