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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
.DS_Store
node_modules
*.tsbuildinfo
.env
.env.*
*.log
.gstack/
dist/
.vscode/
vscode-extension/out/
*.vsix
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,11 +283,36 @@ Typical usage: **$5-20/month** for active development. Start with free models
| `/help` | List all commands |
| `/exit` | Quit |

## VS Code Extension

RunCode is also available as a VS Code sidebar extension.

### Install from VSIX

```bash
cd vscode-extension
npm install && npm run compile
npx @vscode/vsce package
code --install-extension runcode-vscode-0.1.0.vsix
```

Or in VS Code: Extensions panel → `...` → **Install from VSIX...**

### Install from Source (Development)

1. Open the repo in VS Code
2. Run `npm install && npm run build` in the root
3. Run `npm install && npm run compile` in `vscode-extension/`
4. Press `F5` to launch the Extension Development Host

The extension appears as a **RunCode** panel in the sidebar with the same agent capabilities as the CLI: model switching, live balance tracking, tool execution, and all slash commands.

## Architecture

```
src/
├── agent/ # Core agent loop, LLM client, token optimization
├── api/ # Headless session API (VS Code host)
├── tools/ # 10 built-in tools (read, write, edit, bash, ...)
├── ui/ # Terminal UI + model picker
├── proxy/ # Payment proxy for Claude Code
Expand All @@ -297,6 +322,11 @@ src/
├── stats/ # Usage tracking
├── config.ts # Global configuration
└── index.ts # Entry point
vscode-extension/
├── src/extension.ts # Webview provider + live balance tracking
├── media/icon.svg # Extension icon
├── package.json # VS Code extension manifest
└── tsconfig.json
```

## Development
Expand Down
122 changes: 115 additions & 7 deletions dist/agent/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { BLOCKRUN_DIR, VERSION } from '../config.js';
import { estimateHistoryTokens, getAnchoredTokenCount, getContextWindow, resetTokenAnchor } from './tokens.js';
import { forceCompact } from './compact.js';
import { getStatsSummary } from '../stats/tracker.js';
import { resolveModel } from '../ui/model-picker.js';
import { formatModelPickerListText, listPickerModelsFlat, resolveModel } from '../ui/model-picker.js';
import { listSessions, loadSessionHistory, } from '../session/storage.js';
// ─── Git helpers ──────────────────────────────────────────────────────────
function gitExec(cmd, cwd, timeout = 5000, maxBuffer) {
Expand Down Expand Up @@ -145,6 +145,49 @@ const DIRECT_COMMANDS = {
});
emitDone(ctx);
},
'/history': (ctx) => {
const { history, config } = ctx;
const modelName = config.model.split('/').pop() || config.model;
let output = '**Conversation History**\n\n';
if (history.length === 0) {
output += 'No history in the current session yet.\n';
}
else {
for (let i = 0; i < history.length; i++) {
const turn = history[i];
const rolePrefix = turn.role === 'user' ? '[user]' : `[${modelName}]`;
const numPrefix = `[${i + 1}]`;
let turnText = '';
if (typeof turn.content === 'string') {
turnText = turn.content;
}
else if (Array.isArray(turn.content)) {
const textParts = turn.content
.filter(p => p.type === 'text' && p.text.trim())
.map(p => p.text.trim());
if (textParts.length > 0) {
turnText = textParts.join(' ');
}
else {
const toolCall = turn.content.find(p => p.type === 'tool_use');
if (toolCall) {
turnText = `(Thinking and using tool: ${toolCall.name})`;
}
const toolResult = turn.content.find(p => p.type === 'tool_result');
if (toolResult) {
turnText = `(Processing tool result)`;
}
}
}
if (turnText.trim()) {
output += `${numPrefix} ${rolePrefix} ${turnText.trim()}\n\n`;
}
}
}
output += '\nUse `/delete <number>` to remove turns (e.g., `/delete 2` or `/delete 3-5`).\n';
ctx.onEvent({ kind: 'text_delta', text: output });
emitDone(ctx);
},
'/bug': (ctx) => {
ctx.onEvent({ kind: 'text_delta', text: 'Report issues at: https://github.com/BlockRunAI/runcode/issues\n' });
emitDone(ctx);
Expand Down Expand Up @@ -407,17 +450,31 @@ export async function handleSlashCommand(input, ctx) {
await DIRECT_COMMANDS[input](ctx);
return { handled: true };
}
// /model — show current model or switch with /model <name>
if (input === '/model' || input.startsWith('/model ')) {
if (input === '/model') {
ctx.onEvent({ kind: 'text_delta', text: `Current model: **${ctx.config.model}**\n` +
`Switch with: \`/model <name>\` (e.g. \`/model sonnet\`, \`/model free\`, \`/model gemini\`)\n`
// /model — show current model + full list (via onEvent, not stderr) or switch with /model <name|n>
if (input === '/model' || input === '/models' || input.startsWith('/model ')) {
if (input === '/model' || input === '/models') {
const listText = formatModelPickerListText(ctx.config.model);
ctx.onEvent({
kind: 'text_delta',
text: `**Select a model**\n\n` +
`Current: **${ctx.config.model}**\n\n` +
`${listText}\n`,
});
}
else {
const newModel = resolveModel(input.slice(7).trim());
const arg = input.slice(7).trim();
const flat = listPickerModelsFlat();
const num = parseInt(arg, 10);
let newModel;
if (!isNaN(num) && num >= 1 && num <= flat.length) {
newModel = flat[num - 1].id;
}
else {
newModel = resolveModel(arg);
}
ctx.config.model = newModel;
ctx.onEvent({ kind: 'text_delta', text: `Model → **${newModel}**\n` });
ctx.onEvent({ kind: 'status_update', model: newModel });
}
emitDone(ctx);
return { handled: true };
Expand All @@ -439,6 +496,57 @@ export async function handleSlashCommand(input, ctx) {
emitDone(ctx);
return { handled: true };
}
// /delete <...>
if (input.startsWith('/delete ')) {
const arg = input.slice('/delete '.length).trim();
if (!arg) {
ctx.onEvent({ kind: 'text_delta', text: 'Usage: /delete <turn_number> (e.g., /delete 3, /delete 2,5, /delete 4-7)\n' });
emitDone(ctx);
return { handled: true };
}
const indicesToDelete = new Set();
const parts = arg.split(',').map(p => p.trim());
for (const part of parts) {
if (part.includes('-')) {
const [start, end] = part.split('-').map(n => parseInt(n, 10));
if (!isNaN(start) && !isNaN(end) && start <= end) {
for (let i = start; i <= end; i++) {
indicesToDelete.add(i - 1); // User sees 1-based, we use 0-based
}
}
}
else {
const index = parseInt(part, 10);
if (!isNaN(index)) {
indicesToDelete.add(index - 1); // 0-based
}
}
}
if (indicesToDelete.size === 0) {
ctx.onEvent({ kind: 'text_delta', text: 'No valid turn numbers provided.\n' });
emitDone(ctx);
return { handled: true };
}
const sortedIndices = Array.from(indicesToDelete).sort((a, b) => b - a); // Sort descending
let deletedCount = 0;
const deletedNumbers = [];
for (const index of sortedIndices) {
if (index >= 0 && index < ctx.history.length) {
ctx.history.splice(index, 1);
deletedCount++;
deletedNumbers.push(index + 1);
}
}
if (deletedCount > 0) {
resetTokenAnchor();
ctx.onEvent({ kind: 'text_delta', text: `Deleted turn(s) ${deletedNumbers.reverse().join(', ')} from history.\n` });
}
else {
ctx.onEvent({ kind: 'text_delta', text: `No matching turns found to delete.\n` });
}
emitDone(ctx);
return { handled: true };
}
// /resume <id>
if (input.startsWith('/resume ')) {
const targetId = input.slice(8).trim();
Expand Down
7 changes: 6 additions & 1 deletion dist/agent/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,12 @@ export interface StreamUsageInfo {
model: string;
calls: number;
}
export type StreamEvent = StreamTextDelta | StreamThinkingDelta | StreamCapabilityStart | StreamCapabilityInputDelta | StreamCapabilityProgress | StreamCapabilityDone | StreamTurnDone | StreamUsageInfo;
/** UI hosts (e.g. VS Code) — update persistent model display without stderr */
export interface StreamStatusUpdate {
kind: 'status_update';
model: string;
}
export type StreamEvent = StreamTextDelta | StreamThinkingDelta | StreamCapabilityStart | StreamCapabilityInputDelta | StreamCapabilityProgress | StreamCapabilityDone | StreamTurnDone | StreamUsageInfo | StreamStatusUpdate;
export interface AgentConfig {
model: string;
apiUrl: string;
Expand Down
3 changes: 3 additions & 0 deletions dist/banner.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
/** Plain-text banner lines (Run + Code ASCII side by side) for non-terminal UIs (e.g. VS Code webview). */
export declare function getBannerPlainLines(): string[];
export declare function getBannerFooterLines(version: string): string[];
export declare function printBanner(version: string): void;
14 changes: 14 additions & 0 deletions dist/banner.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ const CODE_ART = [
'╚██████╗╚██████╔╝██████╔╝███████╗',
' ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝',
];
/** Plain-text banner lines (Run + Code ASCII side by side) for non-terminal UIs (e.g. VS Code webview). */
export function getBannerPlainLines() {
const lines = [];
for (let i = 0; i < RUN_ART.length; i++) {
lines.push(RUN_ART[i] + CODE_ART[i]);
}
return lines;
}
export function getBannerFooterLines(version) {
return [
' RunCode · AI Coding Agent · blockrun.ai · v' + version,
' 41+ models · Pay per use with USDC · /help for commands',
];
}
export function printBanner(version) {
const runColor = chalk.hex('#FFD700'); // Gold for "Run"
const codeColor = chalk.cyan; // Cyan for "Code"
Expand Down
1 change: 0 additions & 1 deletion dist/commands/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ function saveConfig(config) {
}
catch (err) {
console.error(chalk.red(`Failed to save config: ${err.message}`));
process.exit(1);
}
}
function isValidKey(key) {
Expand Down
5 changes: 5 additions & 0 deletions dist/commands/history.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
interface HistoryOptions {
n?: string;
}
export declare function historyCommand(options: HistoryOptions): void;
export {};
31 changes: 31 additions & 0 deletions dist/commands/history.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import chalk from 'chalk';
import { loadStats } from '../stats/tracker.js';
export function historyCommand(options) {
const { history } = loadStats();
const limit = Math.min(parseInt(options.n || '20', 10), history.length);
console.log(chalk.bold(`
📜 Last ${limit} Requests\n`));
console.log('─'.repeat(55));
if (history.length === 0) {
console.log(chalk.gray('\n No history recorded yet.\n'));
console.log('─'.repeat(55) + '\n');
return;
}
const recent = history.slice(-limit).reverse();
for (const record of recent) {
const time = new Date(record.timestamp).toLocaleString();
const model = record.model.split('/').pop() || record.model;
const cost = '$' + record.costUsd.toFixed(5);
const tokens = `${record.inputTokens}+${record.outputTokens}`.padEnd(10);
const latency = `${record.latencyMs}ms`.padEnd(8);
const fallbackMark = record.fallback ? chalk.yellow(' ↺') : '';
console.log(chalk.gray(`[${time}]`) +
` ${model.padEnd(20)}${fallbackMark} ` +
chalk.cyan(tokens) +
chalk.magenta(latency) +
chalk.green(cost));
}
console.log('\n' + '─'.repeat(55));
console.log(chalk.gray(` Showing ${limit} of ${history.length} total records.`));
console.log(chalk.gray(' Run `runcode stats` for more detailed statistics.\n'));
}
4 changes: 4 additions & 0 deletions dist/ui/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,10 @@ function RunCodeApp({ initialModel, workDir, walletAddress, walletBalance, chain
});
break;
}
case 'status_update': {
setCurrentModel(event.model);
break;
}
case 'usage': {
setCurrentModel(event.model);
setTurnTokens(prev => ({
Expand Down
14 changes: 14 additions & 0 deletions dist/ui/model-picker.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,22 @@ export declare const MODEL_SHORTCUTS: Record<string, string>;
* Resolve a model name — supports shortcuts.
*/
export declare function resolveModel(input: string): string;
interface ModelEntry {
id: string;
shortcut: string;
label: string;
price: string;
}
/** Flat curated list in picker order (for numbering / `/model 3`, etc.). */
export declare function listPickerModelsFlat(): ModelEntry[];
/**
* Plain-text model list (same layout as interactive pickModel), for non-TTY hosts
* (e.g. VS Code webview) that only receive StreamEvents — not console.error.
*/
export declare function formatModelPickerListText(currentModel?: string): string;
/**
* Show interactive model picker. Returns the selected model ID.
* Falls back to text input if terminal doesn't support raw mode.
*/
export declare function pickModel(currentModel?: string): Promise<string | null>;
export {};
32 changes: 28 additions & 4 deletions dist/ui/model-picker.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,16 +103,40 @@ const PICKER_MODELS = [
],
},
];
/** Flat curated list in picker order (for numbering / `/model 3`, etc.). */
export function listPickerModelsFlat() {
const out = [];
for (const cat of PICKER_MODELS) {
out.push(...cat.models);
}
return out;
}
/**
* Plain-text model list (same layout as interactive pickModel), for non-TTY hosts
* (e.g. VS Code webview) that only receive StreamEvents — not console.error.
*/
export function formatModelPickerListText(currentModel) {
const lines = [];
let idx = 1;
for (const cat of PICKER_MODELS) {
lines.push(`── ${cat.category} ──`);
for (const m of cat.models) {
const cur = m.id === currentModel ? ' <- current' : '';
lines.push(` ${String(idx).padStart(2)}. ${m.label.padEnd(26)} ${m.shortcut.padEnd(14)} ${m.price}${cur}`);
idx++;
}
lines.push('');
}
lines.push('Enter a number, shortcut, or use `/model <name>` (e.g. `/model 1`, `/model sonnet`, `/model free`).');
return lines.join('\n');
}
/**
* Show interactive model picker. Returns the selected model ID.
* Falls back to text input if terminal doesn't support raw mode.
*/
export async function pickModel(currentModel) {
// Flatten for numbering
const allModels = [];
for (const cat of PICKER_MODELS) {
allModels.push(...cat.models);
}
const allModels = listPickerModelsFlat();
// Display
console.error('');
console.error(chalk.bold(' Select a model:\n'));
Expand Down
2 changes: 2 additions & 0 deletions dist/ui/terminal.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,8 @@ export class TerminalUI {
if (event.model)
this.sessionModel = event.model;
break;
case 'status_update':
break;
case 'turn_done': {
this.spinner.stop();
// Flush any remaining markdown
Expand Down
Loading