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
34 changes: 17 additions & 17 deletions apps/cli/src/ui/interactive-mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ import { wireInteractiveRuntime, wireStartupInput } from "./runtime/index.ts";
import {
clipboardPaste,
handleStartupSubmit,
isExtensionCommand,
rightClickPaste,
wireKeyHandlers,
wireSubmitHandler,
Expand Down Expand Up @@ -4126,9 +4125,9 @@ export class InteractiveMode {
const text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();
if (!text) return;

// Queue input during compaction (extension commands execute immediately)
// Queue input during compaction (commands execute immediately)
if (this.session.isCompacting) {
if (this.isExtensionCommand(text)) {
if (this.isCommandInput(text)) {
this.editor.addToHistory?.(text);
this.editor.setText("");
await this.session.prompt(text);
Expand All @@ -4142,15 +4141,15 @@ export class InteractiveMode {
}

// Alt+Enter queues a follow-up message (waits until agent finishes)
// This handles extension commands (execute immediately), prompt template expansion, and queueing
// This handles commands (execute immediately), prompt template expansion, and queueing
if (this.session.isStreaming) {
this.editor.addToHistory?.(text);
this.editor.setText("");
const { text: message, images } = await resolvePastedImages(this.pastedImages, text, {
autoResizeImages: this.settingsManager.getImageAutoResize(),
});
await this.session.prompt(message, {
streamingBehavior: "followUp",
await this.session.submit(message, {
duringRun: "followUp",
images: images.length ? images : undefined,
});
this.updatePendingMessagesDisplay();
Expand Down Expand Up @@ -4431,7 +4430,7 @@ export class InteractiveMode {
if (this.session.isAutoClmCompacting) {
this.editor.addToHistory?.(text);
this.editor.setText("");
void this.session.prompt(text, { streamingBehavior: mode, images }).catch((error) => {
void this.session.submit(text, { duringRun: mode, images }).catch((error) => {
this.editor.setText(text);
this.showError(error instanceof Error ? error.message : String(error));
});
Expand Down Expand Up @@ -4465,8 +4464,9 @@ export class InteractiveMode {
return name;
}

isExtensionCommand(text: string): boolean {
return isExtensionCommand(this.session.extensionRunner, text);
/** Would `text` run as a command now, rather than become a message or wait in a queue? */
isCommandInput(text: string): boolean {
return this.session.isCommandInput(text);
}

async flushCompactionQueue(options?: { willRetry?: boolean }): Promise<void> {
Expand All @@ -4493,7 +4493,7 @@ export class InteractiveMode {
if (options?.willRetry) {
// When retry is pending, queue messages for the retry turn
for (const message of queuedMessages) {
if (this.isExtensionCommand(message.text)) {
if (this.isCommandInput(message.text)) {
await this.session.prompt(message.text);
} else if (message.mode === "followUp") {
await this.session.followUp(message.text, message.images);
Expand All @@ -4505,17 +4505,17 @@ export class InteractiveMode {
return;
}

// Find first non-extension-command message to use as prompt
const firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text));
// Find first non-command message to use as prompt
const firstPromptIndex = queuedMessages.findIndex((message) => !this.isCommandInput(message.text));
if (firstPromptIndex === -1) {
// All extension commands - execute them all
// All commands - execute them all
for (const message of queuedMessages) {
await this.session.prompt(message.text);
}
return;
}

// Execute any extension commands before the first prompt
// Execute any commands before the first prompt
const preCommands = queuedMessages.slice(0, firstPromptIndex);
const firstPrompt = queuedMessages[firstPromptIndex];
const rest = queuedMessages.slice(firstPromptIndex + 1);
Expand All @@ -4526,8 +4526,8 @@ export class InteractiveMode {

// Start a prompt when idle, or queue it into a run still finishing compaction.
const promptPromise = this.session
.prompt(firstPrompt.text, {
streamingBehavior: firstPrompt.mode,
.submit(firstPrompt.text, {
duringRun: firstPrompt.mode,
images: firstPrompt.images?.length ? firstPrompt.images : undefined,
})
.catch((error) => {
Expand All @@ -4536,7 +4536,7 @@ export class InteractiveMode {

// Queue remaining messages
for (const message of rest) {
if (this.isExtensionCommand(message.text)) {
if (this.isCommandInput(message.text)) {
await this.session.prompt(message.text);
} else if (message.mode === "followUp") {
await this.session.followUp(message.text, message.images);
Expand Down
2 changes: 1 addition & 1 deletion apps/cli/src/ui/runtime/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ export interface RuntimeContext {
handleShareCommand(): Promise<void>;
handleStepLogoutCommand(): Promise<void>;
handleThinkingCommand(searchTerm?: string): void;
isExtensionCommand(text: string): boolean;
isCommandInput(text: string): boolean;
queueCompactionMessage(text: string, mode: "steer" | "followUp", images?: ImageContent[]): void;
showModelSelector(initialSearchInput?: string): void;
addCommandInputToChat(text: string): void;
Expand Down
14 changes: 2 additions & 12 deletions apps/cli/src/ui/runtime/input-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import {
type AgentSession,
APP_NAME,
cleanPastedPath,
extensionForImageMimeType,
Expand All @@ -40,15 +39,6 @@ import type { RuntimeContext } from "./context.ts";
import { handleEscape } from "./interrupt.ts";
import { resolvePastedImages } from "./pasted-images.ts";

/** Pure recognizer: is `text` a slash command provided by a loaded extension? */
export function isExtensionCommand(extensionRunner: AgentSession["extensionRunner"], text: string): boolean {
if (!text.startsWith("/")) return false;

const spaceIndex = text.indexOf(" ");
const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
return !!extensionRunner.getCommand(commandName);
}

export async function rightClickPaste(ctx: RuntimeContext): Promise<void> {
const target = ctx.renderer.getFocusedComponent();
const handleInput = target?.handleInput;
Expand Down Expand Up @@ -431,7 +421,7 @@ export function wireSubmitHandler(ctx: RuntimeContext): void {

// Queue input during compaction (extension commands execute immediately)
if (ctx.session.isCompacting) {
if (ctx.isExtensionCommand(text)) {
if (ctx.isCommandInput(text)) {
ctx.editor.addToHistory?.(text);
ctx.editor.setText("");
await ctx.session.prompt(text);
Expand All @@ -452,7 +442,7 @@ export function wireSubmitHandler(ctx: RuntimeContext): void {
const { text: message, images } = await resolvePastedImages(ctx.pastedImages, text, {
autoResizeImages: ctx.settingsManager.getImageAutoResize(),
});
await ctx.session.prompt(message, { streamingBehavior: "steer", images: images.length ? images : undefined });
await ctx.session.submit(message, { duringRun: "steer", images: images.length ? images : undefined });
ctx.updatePendingMessagesDisplay();
ctx.redraw.requestRender();
return;
Expand Down
9 changes: 5 additions & 4 deletions apps/cli/test/interactive-mode-compaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ describe("InteractiveMode compaction events", () => {
test("forwards terminal input to the active automatic CLM queue so maintenance is interrupted", async () => {
const fakeThis = {
compactionQueuedMessages: [],
session: { isAutoClmCompacting: true, prompt: vi.fn().mockResolvedValue(undefined) },
session: { isAutoClmCompacting: true, submit: vi.fn().mockResolvedValue(undefined) },
editor: { addToHistory: vi.fn(), setText: vi.fn() },
updatePendingMessagesDisplay: vi.fn(), showStatus: vi.fn(), showError: vi.fn(),
};
const queue = Reflect.get(InteractiveMode.prototype, "queueCompactionMessage") as (this: typeof fakeThis, text: string, mode: "steer" | "followUp") => void;
queue.call(fakeThis, "Preserve output order", "steer");
expect(fakeThis.session.prompt).toHaveBeenCalledWith("Preserve output order", { streamingBehavior: "steer", images: undefined });
expect(fakeThis.session.submit).toHaveBeenCalledWith("Preserve output order", { duringRun: "steer", images: undefined });
expect(fakeThis.compactionQueuedMessages).toEqual([]);
});
test("uses the cache miss notice setting for compaction and branch summary costs", () => {
Expand Down Expand Up @@ -279,10 +279,11 @@ describe("InteractiveMode compaction events", () => {
session: {
clearQueue: vi.fn(),
prompt: vi.fn().mockResolvedValue(undefined),
submit: vi.fn().mockResolvedValue(undefined),
steer: vi.fn().mockResolvedValue(undefined),
followUp: vi.fn().mockResolvedValue(undefined),
},
isExtensionCommand: vi.fn().mockReturnValue(false),
isCommandInput: vi.fn().mockReturnValue(false),
updatePendingMessagesDisplay: vi.fn(),
showError: vi.fn(),
};
Expand All @@ -294,7 +295,7 @@ describe("InteractiveMode compaction events", () => {

await flushCompactionQueue.call(fakeThis, { willRetry: false });

expect(fakeThis.session.prompt).toHaveBeenCalledWith("change direction", { streamingBehavior: "steer" });
expect(fakeThis.session.submit).toHaveBeenCalledWith("change direction", { duringRun: "steer" });
expect(fakeThis.compactionQueuedMessages).toEqual([]);
expect(fakeThis.showError).not.toHaveBeenCalled();
});
Expand Down
1 change: 1 addition & 0 deletions packages/coding-agent/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

### Fixed

- `steer()` and `followUp()` now refuse the session's own `/clm` family as well as registered extension commands; queued as text, `/clm status` used to reach the model as a literal line. The session also exposes the decision the two methods depend on: `isCommandInput()` and `submit()`, the entry that runs a command immediately and otherwise starts a turn or joins the running one.
- Summary requests now use the provider's model output limit and remaining-context sizing instead of fixed compaction/branch caps or reserve-derived budgets. Existing reserve arguments remain accepted for call compatibility; automatic trigger and branch source-selection settings are unchanged.
- Compaction and branch-summary inputs omit provider thinking blocks while retaining visible replies, tool calls, diagnostic output, and existing skill-retention rules. Original session history is unchanged. These changes adapt Pi commits `15e7bdc` and `6fcb486` (upstream PR #11036).
- Recognize `search_files`, `find_files`, and `list_directory` when selecting default system-prompt file-exploration guidance.
4 changes: 2 additions & 2 deletions packages/coding-agent/docs/rpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ The `images` field is optional. Each image uses `ImageContent` format: `{"type":

#### steer

Queue a steering message while the agent is running. It is delivered after the current assistant turn finishes executing its tool calls, before the next LLM call. Skill commands and prompt templates are expanded. Extension commands are not allowed (use `prompt` instead).
Queue a steering message while the agent is running. It is delivered after the current assistant turn finishes executing its tool calls, before the next LLM call. Skill commands and prompt templates are expanded. Commands are refused, both registered extension commands and the session's own `/clm` family: they run on the spot, so send them with `prompt`.

```json
{"type": "steer", "message": "Stop and do this instead"}
Expand All @@ -101,7 +101,7 @@ See [set_steering_mode](#set_steering_mode) for controlling how steering message

#### follow_up

Queue a follow-up message to be processed after the agent finishes. Delivered only when agent has no more tool calls or steering messages. Skill commands and prompt templates are expanded. Extension commands are not allowed (use `prompt` instead).
Queue a follow-up message to be processed after the agent finishes. Delivered only when agent has no more tool calls or steering messages. Skill commands and prompt templates are expanded. Commands are refused, as for `steer`: use `prompt`.

```json
{"type": "follow_up", "message": "After you're done, also do this"}
Expand Down
26 changes: 24 additions & 2 deletions packages/coding-agent/docs/sdk.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,12 @@ interface AgentSession {
// Send a prompt and wait for completion
prompt(text: string, options?: PromptOptions): Promise<void>;

// Queue messages during streaming
// Submit what the user typed: commands run now, messages run or join the run
submit(text: string, options?: SubmitOptions): Promise<void>;
// Whether `text` is a command the kernel runs instead of sending to the model
isCommandInput(text: string): boolean;

// Queue messages during streaming (they refuse commands; prefer submit)
steer(text: string): Promise<void>;
followUp(text: string): Promise<void>;

Expand Down Expand Up @@ -235,6 +240,11 @@ interface PromptOptions {
source?: InputSource;
preflightResult?: (success: boolean) => void;
}

// submit() takes the same options, minus the queueing choice it decides itself
interface SubmitOptions extends Omit<PromptOptions, "streamingBehavior"> {
duringRun?: "steer" | "followUp";
}
```

`preflightResult` is called once per `prompt()` invocation:
Expand Down Expand Up @@ -269,6 +279,18 @@ await session.prompt("After you're done, also check X", { streamingBehavior: "fo
- **`preflightResult(true)`**: Means the prompt was accepted, queued, or handled immediately.
- **`preflightResult(false)`**: Means preflight rejected before acceptance.

**Prefer `submit()` from a host.** It is `prompt()` with the queueing choice made from the state at the call, so a host never has to look at `isStreaming` first:

```typescript
// A command runs immediately; text runs as a turn or joins the running one.
await session.submit(input, { duringRun: "steer" }); // default
await session.submit(input, { duringRun: "followUp" });
```

The distinction that matters: a command is not a message. `prompt()` and `submit()` dispatch it before they look at the run, so it executes during streaming and during compaction. `steer()` and `followUp()` are for a host that has already decided a line is a message — they throw for commands, and a host that queues one itself sends the literal line to the model. `isCommandInput(text)` answers the same question without side effects, for a host that keeps its own editable queue and must not park a command there.

One case stays with the host: compaction refuses new prompts outright, commands aside, so text submitted while the context is being compacted throws. A host that queues during compaction (both the CLI and the Web host do) keeps that queue and calls `submit()` when compaction ends.

For explicit queueing during streaming:

```typescript
Expand All @@ -279,7 +301,7 @@ await session.steer("New instruction");
await session.followUp("After you're done, also do this");
```

Both `steer()` and `followUp()` expand file-based prompt templates but error on extension commands (extension commands cannot be queued).
Both `steer()` and `followUp()` expand file-based prompt templates but refuse commands (registered extension commands and the session's own `/clm` family).

### Agent and AgentState

Expand Down
Loading