mirror of
https://github.com/RooVetGit/Roo-Code.git
synced 2026-09-21 00:21:25 +00:00
* fix: add image content support to MCP tool responses (#10874) Co-authored-by: Roo Code <roomote@roocode.com> * fix: transform tool blocks to text before condensing (EXT-624) (#10975) * refactor(read_file): Codex-inspired read_file refactor EXT-617 (#10981) * feat: allow import settings in initial welcome screen (#10994) Co-authored-by: Roo Code <roomote@roocode.com> Co-authored-by: Matt Rubens <mrubens@users.noreply.github.com> * fix(code-index): remove deprecated text-embedding-004 and migrate to gemini-embedding-001 (#11038) Co-authored-by: Roo Code <roomote@roocode.com> Co-authored-by: Hannes Rudolph <hrudolph@gmail.com> * chore: treat extension .env as optional (#11116) * fix: sanitize tool_use_id in tool_result blocks to match API history (#11131) Tool IDs from providers like Gemini/OpenRouter contain special characters (e.g., 'functions.read_file:0') that are sanitized when saving tool_use blocks to API history. However, tool_result blocks were using the original unsanitized IDs, causing ToolResultIdMismatchError. This fix ensures tool_result blocks use sanitizeToolUseId() to match the sanitized tool_use IDs in conversation history. Fixes EXT-711 * fix: queue messages during command execution instead of losing them (#11140) * IPC fixes for task cancellation and queued messages (#11162) * feat: add support for AGENTS.local.md personal override files (#11183) Co-authored-by: Roo Code <roomote@roocode.com> Co-authored-by: roomote[bot] <219738659+roomote[bot]@users.noreply.github.com> * fix(cli): resolve race condition causing provider switch during mode changes (#11205) When using slash commands with `mode:` frontmatter (e.g., `/cli-release` with `mode: code`), the CLI would fail with "Could not resolve authentication method" from the Anthropic SDK, even when using a non-Anthropic provider like `--provider roo`. Root cause: In `markWebviewReady()`, the `webviewDidLaunch` message was sent before `updateSettings`, creating a race condition. The `webviewDidLaunch` handler's "first-time init" sync would read `getState()` before CLI-provided settings were applied to the context proxy. Since `getState()` defaults `apiProvider` to "anthropic" when unset, this default was saved to the provider profile. When a slash command triggered `handleModeSwitch()`, it found this corrupted profile with `apiProvider: "anthropic"` (but no API key) and activated it, overwriting the CLI's working roo provider configuration. Fix: 1. Reorder `markWebviewReady()` to send `updateSettings` before `webviewDidLaunch`, ensuring the context proxy has CLI-provided values when the initialization handler runs. 2. Guard the first-time init sync with `checkExistKey(apiConfiguration)` to prevent saving a profile with only the default "anthropic" fallback and no actual API keys configured. Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> * chore: remove dead toolFormat code from getEnvironmentDetails (#11207) Remove the toolFormat constant and <tool_format> line from environment details output. Native tool calling is now the only supported protocol, making this code unnecessary. Fixes #11206 Co-authored-by: Roo Code <roomote@roocode.com> * feat: extract translation and merge resolver modes into reusable skills (#11215) * feat: extract translation and merge resolver modes into reusable skills - Add roo-translation skill with comprehensive i18n guidelines - Add roo-conflict-resolution skill for intelligent merge conflict resolution - Add /roo-translate slash command as shortcut for translation skill - Add /roo-resolve-conflicts slash command as shortcut for conflict resolution skill The existing translate and merge-resolver modes are preserved. These new skills and commands provide reusable access to the same functionality. Closes CLO-722 * feat: add guidances directory with translator guidance file - Add .roo/guidances/roo-translator.md for brand voice, tone, and word choice guidance - Update roo-translation skill to reference the guidance file The guidance file serves as a placeholder for translation style guidelines that will be interpolated at runtime. * fix: rename guidances directory to guidance (singular) * fix: remove language-specific section from translator guidance The guidance file should focus on brand voice, tone, and word choice only. * fix: remove language-specific guidelines section from skill file * Update .roo/skills/roo-translation/SKILL.md Co-authored-by: roomote[bot] <219738659+roomote[bot]@users.noreply.github.com> --------- Co-authored-by: Roo Code <roomote@roocode.com> Co-authored-by: Bruno Bergher <bruno@roocode.com> Co-authored-by: roomote[bot] <219738659+roomote[bot]@users.noreply.github.com> * feat: add Claude Opus 4.6 support across all providers (#11224) * feat: add Claude Opus 4.6 support across all providers Add Claude Opus 4.6 (claude-opus-4-6) model definitions and 1M context support across Anthropic, Bedrock, Vertex AI, OpenRouter, and Vercel AI Gateway providers. - Anthropic: 128K max output, /5 pricing, 1M context tiers - Bedrock: anthropic.claude-opus-4-6-v1:0 with 1M context + global inference - Vertex: claude-opus-4-6 with 1M context tiers - OpenRouter: prompt caching + reasoning budget sets - Vercel AI Gateway: Opus 4.5 and 4.6 added to capability sets - UI: 1M context checkbox for Opus 4.6 on all providers - i18n: Updated 1M context descriptions across 18 locales Also adds Opus 4.5 to Vercel AI Gateway (previously missing) and OpenRouter maxTokens overrides for Opus 4.5/4.6. Closes #11223 * fix: apply tier pricing when 1M context is enabled on Bedrock When awsBedrock1MContext is enabled for tiered models like Opus 4.6, also apply the 1M tier pricing (inputPrice, outputPrice, cache prices) instead of only updating contextWindow. This ensures cost calculations and UI display use the correct >200K rates. * feat: add gpt-5.3-codex model to OpenAI Codex provider (#11225) feat: add gpt-5.3-codex model and make it default for OpenAI Codex provider Co-authored-by: Roo Code <roomote@roocode.com> * fix: prevent parent task state loss during orchestrator delegation (#11281) * fix: make removeClineFromStack() delegation-aware to prevent orphaned parent tasks (#11302) * fix: make removeClineFromStack() delegation-aware to prevent orphaned parent tasks When a delegated child task is removed via removeClineFromStack() (e.g., Clear Task, navigate to history, start new task), the parent task was left orphaned in "delegated" status with a stale awaitingChildId. This made the parent unresumable without manual history repair. This fix captures parentTaskId and childTaskId before abort/dispose, then repairs the parent metadata (status -> active, clear awaitingChildId) when the popped task is a delegated child and awaitingChildId matches. Parent lookup + updateTaskHistory are wrapped in try/catch so failures are non-fatal (logged but do not block the pop). Closes #11301 * fix: add skipDelegationRepair opt-out to removeClineFromStack() for nested delegation --------- Co-authored-by: Roo Code <roomote@roocode.com> * fix(reliability): prevent webview postMessage crashes and make dispose idempotent (#11313) * fix(reliability): prevent webview postMessage crashes and make dispose idempotent Closes: #11311 1. postMessageToWebview() now catches rejections from webview.postMessage() so that messages sent after the webview is disposed do not surface as unhandled promise rejections. 2. dispose() is guarded by a _disposed flag so that repeated calls (e.g. during rapid extension deactivation) are no-ops. 3. CloudService mock in ClineProvider.spec.ts updated to include off() — a pre-existing gap exposed by the new dispose test. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: add early _disposed check in postMessageToWebview Skip the postMessage call entirely when the provider is already disposed, avoiding unnecessary try/catch execution. Added test coverage for this path. * chore: trigger CI --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: daniel-lxs <ricciodaniel98@gmail.com> * fix: resolve race condition in new_task delegation that loses parent task history (#11331) * fix: resolve race condition in new_task delegation that loses parent task history When delegateParentAndOpenChild creates a child task via createTask(), the Task constructor fires startTask() as a fire-and-forget async call. The child immediately begins its task loop and eventually calls saveClineMessages() → updateTaskHistory(), which reads globalState, modifies it, and writes back. Meanwhile, delegateParentAndOpenChild persists the parent's delegation metadata (status: 'delegated', delegatedToId, awaitingChildId, childIds) via a separate updateTaskHistory() call AFTER createTask() returns. These two concurrent read-modify-write operations on globalState race: the last writer wins, overwriting the other's changes. When the child's write lands last, the parent's delegation fields are lost, making the parent task unresumable when the child finishes. Fix: create the child task with startTask: false, persist the parent's delegation metadata first, then manually call child.start(). This ensures the parent metadata is safely in globalState before the child begins writing. * docs: clarify Task.start() only handles new tasks, not history resume * fix: serialize taskHistory writes and fix delegation status overwrite race (#11335) Add a promise-chain mutex (withTaskHistoryLock) to serialize all read-modify-write operations on taskHistory, preventing concurrent interleaving from silently dropping entries. Reorder reopenParentFromDelegation to close the child instance before marking it completed, so the abort path's stale 'active' status write no longer overwrites the 'completed' state. Covered by new tests: RPD-04/05/06, UTH-02/04, and a full mutex concurrency suite. * Fix task resumption in the API module (#11369) * chore: clean up repo-facing mode rules (#11410) * fix: add maxReadFileLine to ExtensionState type for webview compatibility --------- Co-authored-by: roomote[bot] <219738659+roomote[bot]@users.noreply.github.com> Co-authored-by: Roo Code <roomote@roocode.com> Co-authored-by: Daniel <57051444+daniel-lxs@users.noreply.github.com> Co-authored-by: Matt Rubens <mrubens@users.noreply.github.com> Co-authored-by: Chris Estreich <cestreich@gmail.com> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> Co-authored-by: Bruno Bergher <bruno@roocode.com> Co-authored-by: 0xMink <dennis@dennismink.com> Co-authored-by: daniel-lxs <ricciodaniel98@gmail.com>
310 lines
9.6 KiB
TypeScript
310 lines
9.6 KiB
TypeScript
import * as path from "path"
|
|
import * as os from "node:os"
|
|
|
|
import pWaitFor from "p-wait-for"
|
|
import { execa } from "execa"
|
|
|
|
import { type ToolUsage, TaskCommandName, RooCodeEventName, IpcMessageType } from "@roo-code/types"
|
|
import { IpcClient } from "@roo-code/ipc"
|
|
|
|
import { updateTask, createTaskMetrics, updateTaskMetrics, createToolError } from "../db/index"
|
|
import { EVALS_REPO_PATH } from "../exercises/index"
|
|
|
|
import { type RunTaskOptions } from "./types"
|
|
import { mergeToolUsage, waitForSubprocessWithTimeout } from "./utils"
|
|
|
|
/**
|
|
* Run a task using the Roo Code CLI (headless mode).
|
|
* Uses the same IPC protocol as VSCode since the CLI loads the same extension bundle.
|
|
*/
|
|
export const runTaskWithCli = async ({ run, task, publish, logger, jobToken }: RunTaskOptions) => {
|
|
const { language, exercise } = task
|
|
const promptSourcePath = path.resolve(EVALS_REPO_PATH, `prompts/${language}.md`)
|
|
const workspacePath = path.resolve(EVALS_REPO_PATH, language, exercise)
|
|
const ipcSocketPath = path.resolve(os.tmpdir(), `evals-cli-${run.id}-${task.id}.sock`)
|
|
|
|
const env: Record<string, string> = {
|
|
...(process.env as Record<string, string>),
|
|
ROO_CODE_IPC_SOCKET_PATH: ipcSocketPath,
|
|
}
|
|
|
|
if (jobToken) {
|
|
env.ROO_CODE_CLOUD_TOKEN = jobToken
|
|
}
|
|
|
|
const controller = new AbortController()
|
|
const cancelSignal = controller.signal
|
|
|
|
const cliArgs = [
|
|
"--filter",
|
|
"@roo-code/cli",
|
|
"start",
|
|
"--prompt-file",
|
|
promptSourcePath,
|
|
"--workspace",
|
|
workspacePath,
|
|
"--reasoning-effort",
|
|
"disabled",
|
|
"--oneshot",
|
|
]
|
|
|
|
if (run.settings?.mode) {
|
|
cliArgs.push("--mode", run.settings.mode)
|
|
}
|
|
|
|
if (run.settings?.apiProvider) {
|
|
cliArgs.push("--provider", run.settings.apiProvider)
|
|
}
|
|
|
|
const modelId = run.settings?.apiModelId || run.settings?.openRouterModelId
|
|
|
|
if (modelId) {
|
|
cliArgs.push("--model", modelId)
|
|
}
|
|
|
|
logger.info(`CLI command: pnpm ${cliArgs.join(" ")}`)
|
|
const subprocess = execa("pnpm", cliArgs, { env, cancelSignal, cwd: process.cwd() })
|
|
|
|
// Buffer for accumulating streaming output until we have complete lines.
|
|
let stdoutBuffer = ""
|
|
let stderrBuffer = ""
|
|
|
|
// Track subprocess exit code - with -x flag the CLI exits immediately after task completion.
|
|
let subprocessExitCode: number | null = null
|
|
|
|
// Pipe CLI stdout/stderr to the logger for easier debugging.
|
|
// Buffer output and only log complete lines to avoid fragmented token-by-token logging.
|
|
// Use logger.raw() to output without the verbose prefix (timestamp, tag, etc).
|
|
subprocess.stdout?.on("data", (data: Buffer) => {
|
|
stdoutBuffer += data.toString()
|
|
const lines = stdoutBuffer.split("\n")
|
|
|
|
// Keep the last incomplete line in the buffer.
|
|
stdoutBuffer = lines.pop() || ""
|
|
|
|
// Log all complete lines without the verbose prefix.
|
|
for (const line of lines) {
|
|
if (line.trim()) {
|
|
logger.raw(line)
|
|
}
|
|
}
|
|
})
|
|
|
|
subprocess.stderr?.on("data", (data: Buffer) => {
|
|
stderrBuffer += data.toString()
|
|
const lines = stderrBuffer.split("\n")
|
|
|
|
// Keep the last incomplete line in the buffer.
|
|
stderrBuffer = lines.pop() || ""
|
|
|
|
// Log all complete lines without the verbose prefix.
|
|
for (const line of lines) {
|
|
if (line.trim()) {
|
|
logger.raw(line)
|
|
}
|
|
}
|
|
})
|
|
|
|
// Log any remaining buffered output when the subprocess exits.
|
|
subprocess.on("exit", (code) => {
|
|
subprocessExitCode = code
|
|
|
|
if (stdoutBuffer.trim()) {
|
|
logger.raw(stdoutBuffer)
|
|
}
|
|
|
|
if (stderrBuffer.trim()) {
|
|
logger.raw(stderrBuffer)
|
|
}
|
|
})
|
|
|
|
// Give CLI some time to start and create IPC server.
|
|
await new Promise((resolve) => setTimeout(resolve, 5_000))
|
|
|
|
let client: IpcClient | undefined = undefined
|
|
let attempts = 10 // More attempts for CLI startup.
|
|
|
|
while (true) {
|
|
try {
|
|
client = new IpcClient(ipcSocketPath)
|
|
await pWaitFor(() => client!.isReady, { interval: 500, timeout: 2_000 })
|
|
break
|
|
} catch (_error) {
|
|
client?.disconnect()
|
|
attempts--
|
|
|
|
if (attempts <= 0) {
|
|
logger.error(`unable to connect to IPC socket -> ${ipcSocketPath}`)
|
|
throw new Error("Unable to connect to CLI IPC socket.")
|
|
}
|
|
|
|
// Wait a bit before retrying.
|
|
await new Promise((resolve) => setTimeout(resolve, 1_000))
|
|
}
|
|
}
|
|
|
|
// For CLI mode, we need to create taskMetrics immediately because the CLI starts
|
|
// the task right away (from command line args). By the time we connect to IPC,
|
|
// the TaskStarted event may have already been sent and missed.
|
|
// This is different from VSCode mode where we send StartNewTask via IPC and can
|
|
// reliably receive TaskStarted.
|
|
const taskMetrics = await createTaskMetrics({
|
|
cost: 0,
|
|
tokensIn: 0,
|
|
tokensOut: 0,
|
|
tokensContext: 0,
|
|
duration: 0,
|
|
cacheWrites: 0,
|
|
cacheReads: 0,
|
|
})
|
|
|
|
await updateTask(task.id, { taskMetricsId: taskMetrics.id, startedAt: new Date() })
|
|
logger.info(`created taskMetrics with id ${taskMetrics.id}`)
|
|
|
|
// The rest of the logic handles IPC events for metrics updates.
|
|
let taskStartedAt = Date.now()
|
|
let taskFinishedAt: number | undefined
|
|
let taskAbortedAt: number | undefined
|
|
let taskTimedOut: boolean = false
|
|
const taskMetricsId = taskMetrics.id // Already set, no need to wait for TaskStarted.
|
|
let rooTaskId: string | undefined
|
|
let isClientDisconnected = false
|
|
const accumulatedToolUsage: ToolUsage = {}
|
|
|
|
// For CLI mode, we don't need verbose IPC message logging since we're logging stdout instead.
|
|
// We only track what's needed for metrics and task state management.
|
|
const ignoreEventsForBroadcast = [RooCodeEventName.Message]
|
|
let isApiUnstable = false
|
|
|
|
client.on(IpcMessageType.TaskEvent, async (taskEvent) => {
|
|
const { eventName, payload } = taskEvent
|
|
|
|
// Track API instability for retry logic.
|
|
if (
|
|
eventName === RooCodeEventName.Message &&
|
|
payload[0].message.say &&
|
|
["api_req_retry_delayed", "api_req_retried"].includes(payload[0].message.say)
|
|
) {
|
|
isApiUnstable = true
|
|
}
|
|
|
|
// Publish events to Redis (except Message events) for the web UI.
|
|
if (!ignoreEventsForBroadcast.includes(eventName)) {
|
|
await publish({ ...taskEvent, taskId: task.id })
|
|
}
|
|
|
|
// Handle task lifecycle events.
|
|
// For CLI mode, we already created taskMetrics before connecting to IPC,
|
|
// but we still want to capture the rooTaskId from TaskStarted if we receive it.
|
|
if (eventName === RooCodeEventName.TaskStarted) {
|
|
taskStartedAt = Date.now()
|
|
rooTaskId = payload[0]
|
|
logger.info(`received TaskStarted event, rooTaskId: ${rooTaskId}`)
|
|
}
|
|
|
|
if (eventName === RooCodeEventName.TaskToolFailed) {
|
|
const [_taskId, toolName, error] = payload
|
|
await createToolError({ taskId: task.id, toolName, error })
|
|
}
|
|
|
|
if (eventName === RooCodeEventName.TaskTokenUsageUpdated || eventName === RooCodeEventName.TaskCompleted) {
|
|
// In CLI mode, taskMetricsId is always set before we register event handlers.
|
|
const duration = Date.now() - taskStartedAt
|
|
|
|
const { totalCost, totalTokensIn, totalTokensOut, contextTokens, totalCacheWrites, totalCacheReads } =
|
|
payload[1]
|
|
|
|
const incomingToolUsage: ToolUsage = payload[2] ?? {}
|
|
mergeToolUsage(accumulatedToolUsage, incomingToolUsage)
|
|
|
|
await updateTaskMetrics(taskMetricsId, {
|
|
cost: totalCost,
|
|
tokensIn: totalTokensIn,
|
|
tokensOut: totalTokensOut,
|
|
tokensContext: contextTokens,
|
|
duration,
|
|
cacheWrites: totalCacheWrites ?? 0,
|
|
cacheReads: totalCacheReads ?? 0,
|
|
toolUsage: accumulatedToolUsage,
|
|
})
|
|
}
|
|
|
|
if (eventName === RooCodeEventName.TaskAborted) {
|
|
taskAbortedAt = Date.now()
|
|
}
|
|
|
|
if (eventName === RooCodeEventName.TaskCompleted) {
|
|
taskFinishedAt = Date.now()
|
|
}
|
|
})
|
|
|
|
client.on(IpcMessageType.Disconnect, async () => {
|
|
logger.info(`disconnected from IPC socket -> ${ipcSocketPath}`)
|
|
isClientDisconnected = true
|
|
// Note: In CLI mode, we don't need to resolve taskMetricsReady since
|
|
// taskMetrics is created synchronously before event handlers are registered.
|
|
})
|
|
|
|
// Note: We do NOT send StartNewTask via IPC here because the CLI already
|
|
// starts the task from its command line arguments. The IPC connection is
|
|
// only used to receive events (TaskStarted, TaskCompleted, etc.) and metrics.
|
|
// Sending StartNewTask here would start a SECOND task.
|
|
|
|
try {
|
|
const timeoutMs = (run.timeout || 5) * 60 * 1_000
|
|
|
|
await pWaitFor(() => !!taskFinishedAt || !!taskAbortedAt || isClientDisconnected, {
|
|
interval: 1_000,
|
|
timeout: timeoutMs,
|
|
})
|
|
} catch (_error) {
|
|
taskTimedOut = true
|
|
logger.error("time limit reached")
|
|
|
|
if (rooTaskId && !isClientDisconnected) {
|
|
logger.info("cancelling task")
|
|
client.sendCommand({ commandName: TaskCommandName.CancelTask })
|
|
await new Promise((resolve) => setTimeout(resolve, 5_000))
|
|
}
|
|
|
|
taskFinishedAt = Date.now()
|
|
}
|
|
|
|
if (!taskFinishedAt && !taskTimedOut) {
|
|
// With -x flag, CLI exits immediately after task completion, which can cause
|
|
// IPC disconnection before we receive the TaskCompleted event.
|
|
// If subprocess exited cleanly (code 0), treat as successful completion.
|
|
if (subprocessExitCode === 0) {
|
|
taskFinishedAt = Date.now()
|
|
logger.info("subprocess exited cleanly (code 0), treating as task completion")
|
|
} else {
|
|
logger.error(`client disconnected before task finished (subprocess exit code: ${subprocessExitCode})`)
|
|
throw new Error("Client disconnected before task completion.")
|
|
}
|
|
}
|
|
|
|
logger.info("setting task finished at")
|
|
await updateTask(task.id, { finishedAt: new Date() })
|
|
|
|
if (rooTaskId && !isClientDisconnected) {
|
|
logger.info("closing task")
|
|
client.sendCommand({ commandName: TaskCommandName.CloseTask })
|
|
await new Promise((resolve) => setTimeout(resolve, 2_000))
|
|
}
|
|
|
|
if (!isClientDisconnected) {
|
|
logger.info("disconnecting client")
|
|
client.disconnect()
|
|
}
|
|
|
|
logger.info("waiting for subprocess to finish")
|
|
controller.abort()
|
|
|
|
await waitForSubprocessWithTimeout({ subprocess, logger })
|
|
|
|
logger.close()
|
|
|
|
if (isApiUnstable && !taskFinishedAt) {
|
|
throw new Error("API is unstable, throwing to trigger a retry.")
|
|
}
|
|
}
|