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
21 changes: 21 additions & 0 deletions packages/agent/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
installCommand,
} from './commands/install.js';
import { addConfigCommands } from './commands/config/index.js';
import { sessionCommand } from './commands/session.js';
import { getAgentVersion } from './version.js';

// Common types
Expand Down Expand Up @@ -77,6 +78,26 @@ program
)
.action(runCommand);

program
.command('session')
.description('Start an interactive session with an AI Coding Agent')
.argument('<agent>', 'Ai Coding Agent to use', value => {
if (!Object.values(AI_AGENT).includes(value as AI_AGENT)) {
throw new Error(
`Invalid agent '${value}'. Valid agents are: ${Object.values(AI_AGENT).join(', ')}`
);
}
return value as AI_AGENT;
})
.argument('[initialPrompt]', 'Initial prompt to start the session with')
.option(
'--pre-context-file <path>',
'Path to JSON file containing pre-context data to inject into the workflow (can be specified multiple times)',
collect,
[]
)
.action(sessionCommand);

// Install workflow dependencies
program
.command('install')
Expand Down
160 changes: 160 additions & 0 deletions packages/agent/src/commands/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { IterationStatusManager, PreContextDataManager } from 'rover-schemas';
import colors from 'ansi-colors';
import { CommandOutput } from '../cli.js';
import {
getVersion,
launch,
ProcessManager,
showRegularHeader,
VERBOSE,
} from 'rover-common';
import { createAgent } from '../lib/agents/index.js';
import {
copyFileSync,
existsSync,
mkdirSync,
readFileSync,
rmSync,
} from 'node:fs';
import { basename } from 'node:path';
import { V } from 'vitest/dist/chunks/reporters.nr4dxCkA.js';

interface SessionCommandOptions {
// Paths to pre-context JSON files
preContextFile: string[];
}

/**
* The session command allows users to run an agent in interactive mode.
* Users can provide a pre-context file to the agent to provide context.
*/
export const sessionCommand = async (
agent: string,
initialPrompt?: string,
options: SessionCommandOptions = { preContextFile: [] }
) => {
const version = getVersion();
showRegularHeader(version, '/workspace', 'Rover Agent');

const processManager = new ProcessManager({
title: 'Start interactive session',
});
processManager?.start();

const preContextFiles: string[] = options.preContextFile || [];
const agentInstance = createAgent(agent);

// Load and validate pre-context files
if (options.preContextFile && options.preContextFile.length > 0) {
processManager.addItem('Load context information for this session');
let successContext = true;

if (VERBOSE) {
console.log(
colors.gray(
`\nLoading pre-context files for this session: ${colors.cyan(
options.preContextFile.join(', ')
)}`
)
);
}

options.preContextFile.forEach(preContextFilePath => {
if (!existsSync(preContextFilePath)) {
successContext = false;

if (VERBOSE) {
console.warn(
`\n⚠ Pre-context file not found at ${preContextFilePath}. Skipping this file.`
);
}
} else {
try {
if (VERBOSE) {
console.log(
colors.gray(
`\nLoading pre-context file: ${colors.cyan(preContextFilePath)}`
)
);
}
// Load and validate pre-context data using PreContextDataManager
const rawData = readFileSync(preContextFilePath, 'utf-8');
const parsedData = JSON.parse(rawData);
// Validate by creating a PreContextDataManager instance
new PreContextDataManager(parsedData, preContextFilePath);

// Track the file path for later use
preContextFiles.push(preContextFilePath);

if (VERBOSE) {
console.log(
colors.gray(
`\nLoaded pre-context file: ${colors.cyan(preContextFilePath)}`
)
);
}
} catch (err) {
successContext = false;

if (VERBOSE) {
console.warn(
`\n⚠ Failed to load pre-context file ${preContextFilePath}: ${err instanceof Error ? err.message : String(err)}. Skipping this file.`
);
}
}
}
});

if (successContext) {
processManager.completeLastItem();
} else {
processManager.failLastItem(
'There were errors reading the context files. Skipping them'
);
}
}

processManager.addItem('Creating temporary context folder');

// To ensure all agents can read it, we will move the pre context files to the workspace:
const targetDir = '/workspace/.rover-context';
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
let projectContextPaths = ``;

processManager.completeLastItem();
processManager.addItem('Starting agent');

preContextFiles.forEach(el => {
const targetPath = `${targetDir}/${basename(el)}`;
copyFileSync(el, targetPath);
projectContextPaths = `${projectContextPaths}
- ${targetPath}`;
});

const preContextInstructions = `You are helping the user iterate over the existing changes in this project. There are already changes in the project, so it's critical you get familiar with the current changes before continuing. Do not use git, as it's not available. Instead, read the following files for context. Just read them, do not apply any new change until the user asks explicitly. The context files are:
${projectContextPaths}

After reading the context files (it's mandatory), ask the user for the new changes and follow the new instructions you get rigorously.`;

processManager.completeLastItem();
processManager.finish();

await launch(
agentInstance.binary,
agentInstance.toolInteractiveArguments(
preContextInstructions,
initialPrompt
),
{
reject: false,
stdio: 'inherit', // This gives full control to the user
}
);

// Clean up the context files
console.log(colors.green('\n✓ Session ended successfully'));
console.log(colors.gray('\nCleaning up temporary context files...'));
rmSync(targetDir, { recursive: true, force: true });
};
5 changes: 5 additions & 0 deletions packages/agent/src/lib/agents/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ export abstract class BaseAgent implements Agent {
envs: string[],
headers: string[]
): Promise<void>;
abstract toolArguments(): string[];
abstract toolInteractiveArguments(
precontext: string,
initialPrompt?: string
): string[];

protected ensureDirectory(dirPath: string): void {
try {
Expand Down
21 changes: 21 additions & 0 deletions packages/agent/src/lib/agents/claude.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,25 @@ export class ClaudeAgent extends BaseAgent {
);
}
}

toolArguments(): string[] {
return ['--dangerously-skip-permissions', '--output-format', 'json', '-p'];
}

toolInteractiveArguments(
precontext: string,
initialPrompt?: string
): string[] {
const args = [
// In this case, let's use the "default approach" and allow agent asking for permissionsk
'--append-system-prompt',
precontext,
];

if (initialPrompt) {
args.push(initialPrompt);
}

return args;
}
}
22 changes: 22 additions & 0 deletions packages/agent/src/lib/agents/codex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,26 @@ export class CodexAgent extends BaseAgent {
);
}
}

toolArguments(): string[] {
return [
'exec',
'--dangerously-bypass-approvals-and-sandbox',
'--skip-git-repo-check',
'-',
];
}

toolInteractiveArguments(
precontext: string,
initialPrompt?: string
): string[] {
let prompt = precontext;

if (initialPrompt) {
prompt += `\n\nInitial User Prompt:\n\n${initialPrompt}`;
}

return [prompt];
}
}
25 changes: 25 additions & 0 deletions packages/agent/src/lib/agents/cursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,29 @@ export class CursorAgent extends BaseAgent {
colors.green(`✓ MCP server "${name}" configured for ${this.name}`)
);
}

toolArguments(): string[] {
return [
'agent',
'--approve-mcps',
'--browser',
'--force',
'--print',
'--output-format',
'json',
];
}

toolInteractiveArguments(
precontext: string,
initialPrompt?: string
): string[] {
let prompt = precontext;

if (initialPrompt) {
prompt += `\n\nInitial User Prompt:\n\n${initialPrompt}`;
}

return ['--approve-mcps', prompt];
}
}
17 changes: 17 additions & 0 deletions packages/agent/src/lib/agents/gemini.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,21 @@ export class GeminiAgent extends BaseAgent {
);
}
}

toolArguments(): string[] {
return ['--yolo', '--output-format', 'json'];
}

toolInteractiveArguments(
precontext: string,
initialPrompt?: string
): string[] {
let prompt = precontext;

if (initialPrompt) {
prompt += `\n\nInitial User Prompt:\n\n${initialPrompt}`;
}

return ['-i', prompt];
}
}
17 changes: 17 additions & 0 deletions packages/agent/src/lib/agents/qwen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,21 @@ export class QwenAgent extends BaseAgent {
);
}
}

toolArguments(): string[] {
return ['--yolo', '-p'];
}

toolInteractiveArguments(
precontext: string,
initialPrompt?: string
): string[] {
let prompt = precontext;

if (initialPrompt) {
prompt += `\n\nInitial User Prompt:\n\n${initialPrompt}`;
}

return ['-i', prompt];
}
}
5 changes: 5 additions & 0 deletions packages/agent/src/lib/agents/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,9 @@ export interface Agent {
): Promise<void>;
copyCredentials(targetDir: string): Promise<void>;
isInstalled(): Promise<boolean>;
toolArguments(): string[];
toolInteractiveArguments(
precontext: string,
initialPrompt?: string
): string[];
}
Loading