Skip to content
Open
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ A [Visual Studio Code extension](https://marketplace.visualstudio.com/items?item

## Features

- **Code Block Actions**: Copy code to clipboard or paste directly into the integrated terminal (without auto-executing) from any rendered code block.
- **Default & Remembered Mode**: Configure a preferred execution mode (`acp.defaultMode`, defaulting to `auto`) and remember per-agent mode selections (`acp.rememberMode`).
- **Unblocked Input & Prompt Queue**: Continue typing and queue follow-up prompts while an agent turn or compaction is running.
- **Image & File Attachments**: Paste screenshots (`Ctrl+V`), drag-and-drop, or attach files/images via ACP `ContentBlock` (`image`, `resource`, `resource_link`).

- **Multi-Agent Support**: Connect to 11 pre-configured ACP agents or add your own
- **Single-Agent Focus**: One agent active at a time — seamlessly switch between agents
- **Per-Agent Session List**: Each agent in the Agents view is expandable into its previous sessions. Click a session to restore its history in the chat. Backed by `session/list` when the agent supports it, or by a local per-workspace cache otherwise.
Expand Down Expand Up @@ -63,6 +68,8 @@ You can add custom agent configurations in settings.
| `acp.agents` | *(11 agents)* | Agent configurations. Each key is the agent name, value has `command`, `args`, and `env`. |
| `acp.autoApprovePermissions` | `ask` | How agent permission requests are handled: `ask` or `allowAll`. |
| `acp.defaultWorkingDirectory` | `""` | Default working directory for agent sessions. Empty uses current workspace. |
| `acp.defaultMode` | `"auto"` | Preferred agent execution mode ID or name applied to new sessions when supported. |
| `acp.rememberMode` | `true` | Remember the last selected mode per agent and restore it for new sessions. |
| `acp.logTraffic` | `true` | Log all ACP protocol traffic to the ACP Traffic output channel. |

## Commands
Expand Down
10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,16 @@
"default": "",
"description": "Default working directory for agent sessions. Leave empty to use the current workspace folder."
},
"acp.defaultMode": {
"type": "string",
"default": "auto",
"description": "Preferred agent execution mode ID or name (e.g., auto, plan, accept-edits) applied to new sessions when supported by the agent. Leave empty to use each agent's default."
},
"acp.rememberMode": {
"type": "boolean",
"default": true,
"description": "Remember the last selected mode per agent and restore it for new sessions."
},
"acp.logTraffic": {
"type": "boolean",
"default": true,
Expand Down
86 changes: 86 additions & 0 deletions src/config/ModeResolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import type {
SessionConfigOption,
SessionConfigSelectGroup,
SessionConfigSelectOption,
SessionModeState,
} from '@agentclientprotocol/sdk';

function isSelectGroup(
item: SessionConfigSelectOption | SessionConfigSelectGroup,
): item is SessionConfigSelectGroup {
return 'options' in item && Array.isArray((item as SessionConfigSelectGroup).options);
}

function flattenSelectOptions(
options: Array<SessionConfigSelectOption | SessionConfigSelectGroup>,
): SessionConfigSelectOption[] {
const flat: SessionConfigSelectOption[] = [];
for (const item of options) {
if (isSelectGroup(item)) {
flat.push(...item.options);
} else {
flat.push(item);
}
}
return flat;
}

/**
* Return the currently active mode ID from `configOptions` (category === 'mode')
* or legacy `modes.currentModeId`.
*/
export function getCurrentModeId(
modes: SessionModeState | null,
configOptions: SessionConfigOption[] | null,
): string | null {
if (Array.isArray(configOptions) && configOptions.length > 0) {
const modeOpt = configOptions.find((o) => o.category === 'mode' && o.type === 'select');
return modeOpt && modeOpt.type === 'select' ? (modeOpt.currentValue ?? null) : null;
}
return modes?.currentModeId ?? null;
}

/**
* Resolve a preferred mode ID or name against the session's advertised modes.
* Matches exact ID/value first, then case-insensitive ID/value or name.
*/
export function resolvePreferredModeId(
preferred: string,
modes: SessionModeState | null,
configOptions: SessionConfigOption[] | null,
): string | null {
const target = preferred.trim();
if (!target) {
return null;
}
const targetLower = target.toLowerCase();

if (Array.isArray(configOptions) && configOptions.length > 0) {
const modeOpt = configOptions.find((o) => o.category === 'mode' && o.type === 'select');
if (!modeOpt || modeOpt.type !== 'select') {
return null;
}
const flat = flattenSelectOptions(modeOpt.options);
const exact = flat.find((o) => o.value === target);
if (exact) {
return exact.value;
}
const ci = flat.find(
(o) => o.value.toLowerCase() === targetLower || o.name.toLowerCase() === targetLower,
);
return ci ? ci.value : null;
}

const available = modes?.availableModes;
if (!available || available.length === 0) {
return null;
}
const exact = available.find((m) => m.id === target);
if (exact) {
return exact.id;
}
const ci = available.find(
(m) => m.id.toLowerCase() === targetLower || m.name.toLowerCase() === targetLower,
);
return ci ? ci.id : null;
}
110 changes: 110 additions & 0 deletions src/core/PromptBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import * as path from 'path';
import type { ContentBlock } from '@agentclientprotocol/sdk';

export interface PromptCapabilityFlags {
image: boolean;
embeddedContext: boolean;
audio: boolean;
}

export interface PromptAttachment {
id: string;
kind: 'image' | 'file';
name: string;
mimeType: string;
/** Base64 payload (without data: prefix) for image attachments */
data?: string;
/** Workspace/local file URI string */
uri?: string;
/** UTF-8 text content when preloaded for embeddedContext */
text?: string;
}

const IMAGE_MIME_MAP: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
};

const TEXT_MIME_MAP: Record<string, string> = {
'.json': 'application/json',
'.md': 'text/markdown',
'.ts': 'text/typescript',
'.tsx': 'text/typescript',
'.js': 'text/javascript',
'.jsx': 'text/javascript',
'.html': 'text/html',
'.css': 'text/css',
'.xml': 'application/xml',
'.yaml': 'text/yaml',
'.yml': 'text/yaml',
'.csv': 'text/csv',
};

export function getImageMimeType(filePath: string): string | null {
const ext = path.extname(filePath).toLowerCase();
return IMAGE_MIME_MAP[ext] ?? null;
}

export function guessMimeType(filePath: string): string {
const img = getImageMimeType(filePath);
if (img) {
return img;
}
const ext = path.extname(filePath).toLowerCase();
return TEXT_MIME_MAP[ext] ?? 'text/plain';
}

/**
* Build ACP ContentBlock[] from user text and attachments, respecting agent promptCapabilities.
*/
export function buildPromptContentBlocks(
text: string,
attachments: PromptAttachment[],
caps: PromptCapabilityFlags,
): ContentBlock[] {
const blocks: ContentBlock[] = [];

for (const att of attachments) {
if (att.kind === 'image') {
if (!caps.image) {
throw new Error(`The active agent does not support image attachments ("${att.name}").`);
}
if (!att.data) {
throw new Error(`Image attachment "${att.name}" is missing base64 data.`);
}
blocks.push({
type: 'image',
mimeType: att.mimeType,
data: att.data,
...(att.uri ? { uri: att.uri } : {}),
});
} else if (att.kind === 'file') {
if (caps.embeddedContext && att.uri && att.text !== undefined) {
blocks.push({
type: 'resource',
resource: {
uri: att.uri,
mimeType: att.mimeType,
text: att.text,
},
});
} else if (att.uri) {
blocks.push({
type: 'resource_link',
uri: att.uri,
name: att.name,
mimeType: att.mimeType,
});
}
}
}

if (text.trim().length > 0 || blocks.length === 0) {
blocks.push({ type: 'text', text });
}

return blocks;
}
83 changes: 75 additions & 8 deletions src/core/SessionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ import { AgentManager } from './AgentManager';
import { ConnectionManager, ConnectionInfo } from './ConnectionManager';
import { SessionUpdateHandler } from '../handlers/SessionUpdateHandler';
import { SessionHistoryStore } from './SessionHistoryStore';
import { getCurrentModeId, resolvePreferredModeId } from '../config/ModeResolver';
import {
buildPromptContentBlocks,
PromptAttachment,
PromptCapabilityFlags,
} from './PromptBuilder';
import { getAgentConfigs } from '../config/AgentConfig';
import { log, logError } from '../utils/Logger';
import { sendEvent, sendError } from '../utils/TelemetryManager';
Expand Down Expand Up @@ -106,11 +112,27 @@ export class SessionManager extends EventEmitter {
super();
}

private stateStore: vscode.Memento | null = null;

/** Wire in the persistent session-history store (called once at startup). */
setHistoryStore(store: SessionHistoryStore): void {
this.historyStore = store;
}

/** Wire in extension globalState memento for persisting per-agent preferences. */
setStateStore(store: vscode.Memento): void {
this.stateStore = store;
}

private savePreferredMode(agentName: string, modeId: string): void {
if (!this.stateStore) { return; }
const remember = vscode.workspace.getConfiguration('acp').get<boolean>('rememberMode', true);
if (!remember) { return; }
const saved = { ...this.stateStore.get<Record<string, string>>('acp.savedModes', {}) };
saved[agentName] = modeId;
void this.stateStore.update('acp.savedModes', saved);
}

/** Public accessor for downstream UI. */
getHistoryStore(): SessionHistoryStore | null {
return this.historyStore;
Expand Down Expand Up @@ -338,6 +360,24 @@ export class SessionManager extends EventEmitter {
this.sessions.set(sessionInfo.sessionId, sessionInfo);
this.drainPending(sessionInfo);

// Apply remembered or default mode on new sessions when supported
const config = vscode.workspace.getConfiguration('acp');
const rememberMode = config.get<boolean>('rememberMode', true);
const savedModes = this.stateStore?.get<Record<string, string>>('acp.savedModes', {}) ?? {};
const remembered = rememberMode ? savedModes[agentName] : undefined;
const desired = remembered || config.get<string>('defaultMode', 'auto').trim();
if (desired) {
const targetModeId = resolvePreferredModeId(desired, sessionInfo.modes, sessionInfo.configOptions);
const currentModeId = getCurrentModeId(sessionInfo.modes, sessionInfo.configOptions);
if (targetModeId && targetModeId !== currentModeId) {
try {
await this.setMode(sessionInfo.sessionId, targetModeId, false);
} catch (err) {
console.warn(`[ACP] Failed to apply preferred mode "${targetModeId}" for ${agentName}:`, err);
}
}
}

// Capture in the local history store so it appears in the tree.
this.historyStore?.upsertNew(agentName, cwd, sessionInfo.sessionId);

Expand Down Expand Up @@ -435,10 +475,26 @@ export class SessionManager extends EventEmitter {
}
}

/**
* Read prompt capabilities advertised by the agent during initialize.
*/
getPromptCapabilities(session?: SessionInfo | null): PromptCapabilityFlags {
const pc = session?.initResponse?.agentCapabilities?.promptCapabilities;
return {
image: !!pc?.image,
embeddedContext: !!pc?.embeddedContext,
audio: !!pc?.audio,
};
}

/**
* Send a prompt to the active session.
*/
async sendPrompt(sessionId: string, text: string): Promise<PromptResponse> {
async sendPrompt(
sessionId: string,
text: string,
attachments: PromptAttachment[] = [],
): Promise<PromptResponse> {
const session = this.sessions.get(sessionId);
if (!session) {
throw new Error(`Session not found: ${sessionId}`);
Expand All @@ -449,11 +505,13 @@ export class SessionManager extends EventEmitter {
throw new Error(`No connection for agent: ${session.agentId}`);
}

log(`sendPrompt: session=${sessionId}, text="${text.substring(0, 50)}..."`);
log(`sendPrompt: session=${sessionId}, text="${text.substring(0, 50)}...", attachments=${attachments.length}`);

const prompt: ContentBlock[] = [
{ type: 'text', text },
];
const prompt: ContentBlock[] = buildPromptContentBlocks(
text,
attachments,
this.getPromptCapabilities(session),
);

const response = await connInfo.connection.prompt({
sessionId,
Expand Down Expand Up @@ -486,7 +544,7 @@ export class SessionManager extends EventEmitter {
* `mode` — this keeps user keybindings working across agents that have
* migrated to the new API.
*/
async setMode(sessionId: string, modeId: string): Promise<void> {
async setMode(sessionId: string, modeId: string, persist = true): Promise<void> {
const session = this.sessions.get(sessionId);
if (!session) { return; }

Expand All @@ -495,7 +553,7 @@ export class SessionManager extends EventEmitter {
if (session.configOptions && session.configOptions.length > 0) {
const modeOpt = session.configOptions.find(o => o.category === 'mode');
if (modeOpt) {
await this.setConfigOption(sessionId, modeOpt.id, modeId);
await this.setConfigOption(sessionId, modeOpt.id, modeId, persist);
return;
}
}
Expand All @@ -509,6 +567,9 @@ export class SessionManager extends EventEmitter {
if (session.modes) {
session.modes.currentModeId = modeId;
}
if (persist) {
this.savePreferredMode(session.agentName, modeId);
}
this.emit('mode-changed', sessionId, modeId);
}

Expand Down Expand Up @@ -549,7 +610,7 @@ export class SessionManager extends EventEmitter {
* replace our local copy so that cascading changes (e.g. changing the
* model adjusts thought-level options) are reflected.
*/
async setConfigOption(sessionId: string, configId: string, value: string): Promise<SessionConfigOption[] | null> {
async setConfigOption(sessionId: string, configId: string, value: string, persist = true): Promise<SessionConfigOption[] | null> {
const session = this.sessions.get(sessionId);
if (!session) { return null; }

Expand All @@ -564,6 +625,12 @@ export class SessionManager extends EventEmitter {

const options = (response as any)?.configOptions ?? null;
this.applyConfigOptions(sessionId, options);
if (persist) {
const changedOpt = (options ?? session.configOptions)?.find((o: SessionConfigOption) => o.id === configId);
if (changedOpt?.category === 'mode') {
this.savePreferredMode(session.agentName, value);
}
}
return options;
}

Expand Down
Loading