diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index ef812b01bbd..5683c2143ea 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -12,6 +12,7 @@ import { } from "./provider-settings.js" import { telemetrySettingsSchema } from "./telemetry.js" import { toolNamesSchema } from "./tool.js" +import { MAX_CONCURRENT_SUBAGENTS, MAX_SUBAGENT_MAX_TURNS, MIN_CONCURRENT_SUBAGENTS } from "./subagent.js" import { type Keys } from "./type-fu.js" import { languagesSchema } from "./vscode.js" import { providerIdentifiers } from "./provider-identifiers.js" @@ -334,6 +335,23 @@ export const globalSettingsSchema = z.object({ * ignored at policy resolution. */ disabledTools: z.array(toolNamesSchema).optional(), + + /** + * Enable the native `spawn_subagent` tool for full-tool modes. + * @default false + */ + subagentsEnabled: z.boolean().optional(), + /** + * Maximum number of subagent runs executing at the same time per provider. + * @default 4 + */ + maxConcurrentSubagents: z.number().int().min(MIN_CONCURRENT_SUBAGENTS).max(MAX_CONCURRENT_SUBAGENTS).optional(), + /** + * Default `maxTurns` for subagents whose definition does not set one. + * `0` means unlimited (the subagent runs until it finishes or is stopped). + * @default 0 (unlimited) + */ + defaultSubagentMaxTurns: z.number().int().min(0).max(MAX_SUBAGENT_MAX_TURNS).optional(), }) export type GlobalSettings = z.infer diff --git a/packages/types/src/history.ts b/packages/types/src/history.ts index 1ba91b02e4c..1363357bf46 100644 --- a/packages/types/src/history.ts +++ b/packages/types/src/history.ts @@ -1,6 +1,7 @@ import { z } from "zod" import { todoItemSchema } from "./todo.js" +import { subagentHistoryMetaSchema } from "./subagent.js" /** * HistoryItem @@ -51,6 +52,8 @@ export const historyItemSchema = z.object({ completedByChildId: z.string().optional(), // Child that completed and resumed this parent completionResultSummary: z.string().optional(), // Summary from completed child pendingAction: pendingTaskActionSchema.optional(), + /** Present when this history entry belongs to a headless subagent run. */ + subagent: subagentHistoryMetaSchema.optional(), }) export type HistoryItem = z.infer diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 82588ae5374..961476364be 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -23,6 +23,7 @@ export * from "./provider-settings.js" export * from "./task.js" export * from "./todo.js" export * from "./skills.js" +export * from "./subagent.js" export * from "./rules.js" export * from "./marketplace.js" export * from "./telemetry.js" diff --git a/packages/types/src/subagent.ts b/packages/types/src/subagent.ts new file mode 100644 index 00000000000..68afe44891c --- /dev/null +++ b/packages/types/src/subagent.ts @@ -0,0 +1,223 @@ +import { z } from "zod" + +/** + * Native subagent definitions and run snapshots. + * + * A subagent is a headless child run that never becomes the active webview + * task. The parent task keeps the chat screen; each subagent streams state + * through `subagentUpdate` messages instead of `clineMessages`. + */ + +export const subagentStatuses = ["queued", "running", "completed", "failed", "cancelled"] as const + +export const subagentStatusSchema = z.enum(subagentStatuses) + +export type SubagentStatus = z.infer + +export const subagentIsolationModes = ["none", "worktree"] as const + +export const subagentIsolationSchema = z.enum(subagentIsolationModes) + +export type SubagentIsolation = z.infer + +export const subagentSources = ["builtin", "project", "user"] as const + +export const subagentSourceSchema = z.enum(subagentSources) + +export type SubagentSource = z.infer + +/** + * Built-in agent names. Custom agents may use any slug that passes + * `subagentNameSchema`; the union with `string` keeps definitions open. + */ +export const builtinSubagentNames = ["explore", "reviewer", "general"] as const + +export const subagentNameSchema = z + .string() + .min(1) + .max(64) + .regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/, "Agent names may contain letters, digits, hyphens and underscores") + +export const subagentDefinitionSchema = z.object({ + name: subagentNameSchema, + /** One or two lines injected into the parent's `spawn_subagent` tool description. */ + description: z.string().min(1).max(500), + /** Full system prompt for the child session. */ + systemPrompt: z.string().min(1), + /** Model id override, or "inherit" to use the parent task's model. */ + model: z.string().min(1).optional(), + tools: z.array(z.string().min(1)).optional(), + disallowedTools: z.array(z.string().min(1)).optional(), + /** Read-only agents get read-class tools and run fully in parallel. */ + readonly: z.boolean().optional(), + maxTurns: z.number().int().min(1).max(100).optional(), + isolation: subagentIsolationSchema.optional(), + color: z.string().optional(), + source: subagentSourceSchema, +}) + +export type SubagentDefinition = z.infer + +/** + * YAML frontmatter accepted in `.zoo/agents/*.md` and `.claude/agents/*.md`. + * `tools`/`disallowedTools` accept either a YAML list or a comma-separated + * string, matching both Claude Code and hand-written files. + */ +const commaSeparated = z + .union([z.array(z.string()), z.string()]) + .optional() + .transform((value) => { + if (value === undefined) { + return undefined + } + + const list = Array.isArray(value) ? value : value.split(",") + + return list.map((entry) => entry.trim()).filter((entry) => entry.length > 0) + }) + +export const subagentFrontmatterSchema = z.object({ + name: subagentNameSchema.optional(), + description: z.string().min(1).max(500).optional(), + model: z.string().min(1).optional(), + tools: commaSeparated, + disallowedTools: commaSeparated, + readonly: z.boolean().optional(), + maxTurns: z.number().int().min(1).max(100).optional(), + isolation: subagentIsolationSchema.optional(), + color: z.string().optional(), +}) + +export type SubagentFrontmatter = z.infer + +export const subagentTokenUsageSchema = z.object({ + input: z.number().min(0), + output: z.number().min(0), +}) + +export type SubagentTokenUsage = z.infer + +/** + * One live tool-call event in a subagent's activity feed. Stella sends only the + * tool name and a short structural tag, never the tool's output, so the live + * feed never leaks child context into the parent conversation. + */ +export const subagentToolActivitySchema = z.object({ + /** Stable per-run id (call counter). */ + id: z.number(), + tool: z.string(), + /** Localized label key, optional when we only know the raw tool name. */ + labelKey: z.string().optional(), + path: z.string().optional(), + ts: z.number(), +}) + +export type SubagentToolActivity = z.infer + +export const subagentToolActivityListSchema = z.array(subagentToolActivitySchema).max(50) + +export const subagentRunSnapshotSchema = z.object({ + runId: z.string(), + parentTaskId: z.string(), + toolUseId: z.string(), + groupId: z.string(), + agentName: z.string(), + description: z.string(), + /** Full instruction the subagent was given, shown on demand in the viewer. */ + prompt: z.string().optional(), + modelId: z.string(), + status: subagentStatusSchema, + startedAt: z.number(), + completedAt: z.number().optional(), + durationMs: z.number().min(0).optional(), + /** Live one-line ticker, e.g. "Reading src/auth/jwt.ts...". */ + currentAction: z.string().optional(), + /** Chronological feed of recent tool calls, newest last (bounded). */ + activity: subagentToolActivityListSchema.optional(), + toolCallCount: z.number().min(0), + tokenUsage: subagentTokenUsageSchema, + summary: z.string().optional(), + error: z.string().optional(), + /** Set when the run stopped at `maxTurns` before finishing on its own. */ + partial: z.boolean().optional(), + readonly: z.boolean().optional(), + isolation: subagentIsolationSchema.optional(), + /** Worktree path and diff summary for `isolation: "worktree"` runs. */ + worktree: z + .object({ + path: z.string(), + kept: z.boolean(), + filesChanged: z.number().min(0).optional(), + diffStat: z.string().optional(), + }) + .optional(), + filesRead: z.array(z.string()), + filesModified: z.array(z.string()), +}) + +export type SubagentRunSnapshot = z.infer + +export const subagentGroupStateSchema = z.object({ + groupId: z.string(), + parentTaskId: z.string(), + startedAt: z.number(), + completedAt: z.number().optional(), + runs: z.array(subagentRunSnapshotSchema), +}) + +export type SubagentGroupState = z.infer + +/** Payload of the extension -> webview `subagentUpdate` message. */ +export const subagentUpdatePayloadSchema = z.object({ + parentTaskId: z.string(), + groupId: z.string(), + runs: z.array(subagentRunSnapshotSchema), +}) + +export type SubagentUpdatePayload = z.infer + +/** Minimal history-item metadata persisted for each subagent run. */ +export const subagentHistoryMetaSchema = z.object({ + runId: z.string(), + groupId: z.string(), + parentTaskId: z.string(), + agentName: z.string(), + /** + * The terminal run status. A save made while the run is still active omits + * it; `SubagentManager` writes it from the terminal snapshot when the group + * completes, so a stored value is never a stale `"running"`. + */ + status: subagentStatusSchema.optional(), + partial: z.boolean().optional(), +}) + +export type SubagentHistoryMeta = z.infer + +export const DEFAULT_MAX_CONCURRENT_SUBAGENTS = 4 +export const MIN_CONCURRENT_SUBAGENTS = 1 +export const MAX_CONCURRENT_SUBAGENTS = 8 +// The default is unlimited (0) so subagents run until they finish or are stopped. +/** Sentinel `maxTurns` meaning "no turn limit". */ +export const UNLIMITED_SUBAGENT_MAX_TURNS = 0 +// Written as a literal (not an alias of UNLIMITED_SUBAGENT_MAX_TURNS) so Knip +// does not flag the two exports as duplicates. +export const DEFAULT_SUBAGENT_MAX_TURNS = 0 +export const MAX_SUBAGENT_MAX_TURNS = 100 + +/** + * Tools a subagent may never call. This enforces the flat two-level hierarchy + * and the non-interactive contract: no nested spawn, no task delegation, no + * mode switching and no blocking question. + */ +export const SUBAGENT_FORBIDDEN_TOOLS = [ + "spawn_subagent", + "resume_subagent", + "new_task", + "ask_followup_question", + "switch_mode", +] as const + +export type SubagentForbiddenTool = (typeof SUBAGENT_FORBIDDEN_TOOLS)[number] + +export const isForbiddenSubagentTool = (toolName: string): boolean => + (SUBAGENT_FORBIDDEN_TOOLS as readonly string[]).includes(toolName) diff --git a/packages/types/src/tool.ts b/packages/types/src/tool.ts index 03c10bc3e70..3bd8dfe3879 100644 --- a/packages/types/src/tool.ts +++ b/packages/types/src/tool.ts @@ -45,6 +45,7 @@ export const toolNames = [ "run_slash_command", "skill", "generate_image", + "spawn_subagent", "custom_tool", "invalid_tool_call", ] as const diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 4e7efff57fc..bea438e02d4 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -8,6 +8,7 @@ import type { Experiments } from "./experiment.js" import type { ClineMessage, MentionSegment, QueuedMessage } from "./message.js" import type { MarketplaceItem, MarketplaceInstalledMetadata, InstallMarketplaceItemOptions } from "./marketplace.js" import type { TodoItem } from "./todo.js" +import type { SubagentRunSnapshot, SubagentUpdatePayload } from "./subagent.js" import type { CloudUserInfo, CloudOrganizationMembership, OrganizationAllowList, ShareVisibility } from "./cloud.js" import type { SerializedCustomToolDefinition } from "./custom-tool.js" import type { GitCommit } from "./git.js" @@ -143,6 +144,7 @@ export interface ExtensionMessage { | "rooHistoryImportProgress" | "themeFixtureProbeRequest" | "diagnosticsRequest" + | "subagentUpdate" text?: string /** For fileContent: { path, content, error? } */ fileContent?: { path: string; content: string | null; error?: string } @@ -303,6 +305,8 @@ export interface ExtensionMessage { copyProgressItemName?: string // folderSelected path?: string + /** Throttled subagent group progress (JSON `SubagentUpdatePayload` in `text`). */ + subagentUpdate?: SubagentUpdatePayload } export interface OpenAiCodexRateLimitsMessage { @@ -386,6 +390,9 @@ export type ExtensionState = Pick< | "requestDelaySeconds" | "showWorktreesInHomeScreen" | "disabledTools" + | "subagentsEnabled" + | "maxConcurrentSubagents" + | "defaultSubagentMaxTurns" > & { lockApiConfigAcrossModes?: boolean version: string @@ -758,8 +765,12 @@ export interface WebviewMessage { | "openRulesDirectory" | "themeFixtureProbeResponse" | "diagnosticsResponse" + // Native subagents + | "cancelSubagent" text?: string taskId?: string + /** Native subagents: target run. */ + runId?: string editedMessageContent?: string tab?: "settings" | "history" | "mcp" | "modes" | "chat" | "marketplace" | "cloud" disabled?: boolean @@ -964,6 +975,8 @@ export interface ClineSayTool { | "runSlashCommand" | "updateTodoList" | "skill" + /** Inline parallel subagent group row (payload fields below). */ + | "spawnSubagent" path?: string // For readCommandOutput readStart?: number @@ -1023,6 +1036,14 @@ export interface ClineSayTool { description?: string // Properties for skill tool skill?: string + // Properties for spawnSubagent tool rows + runId?: string + groupId?: string + agentName?: string + modelId?: string + runStatus?: string + /** Final run snapshots stored on the leader row for reload rendering. */ + runs?: SubagentRunSnapshot[] } export interface ClineAskUseMcpServer { diff --git a/src/core/assistant-message/NativeToolCallParser.ts b/src/core/assistant-message/NativeToolCallParser.ts index 607c2f0c57c..182a83f61b3 100644 --- a/src/core/assistant-message/NativeToolCallParser.ts +++ b/src/core/assistant-message/NativeToolCallParser.ts @@ -1079,6 +1079,30 @@ export class NativeToolCallParser { } break + // Without a dedicated case, spawn_subagent fell through to the + // default branch (non-custom tools), so its arguments were always + // rejected and every call became "missing nativeArgs". + case "spawn_subagent": + if (args.agent !== undefined && args.description !== undefined && args.prompt !== undefined) { + nativeArgs = { + agent: args.agent, + description: args.description, + prompt: args.prompt, + model: args.model, + isolation: args.isolation, + } as NativeArgsFor + } else { + console.warn( + `[spawn_subagent] model returned arguments missing required fields: ` + + JSON.stringify({ + agent: args.agent, + description: args.description, + prompt: args.prompt, + }), + ) + } + break + default: if (customToolRegistry.has(resolvedName)) { nativeArgs = args as NativeArgsFor diff --git a/src/core/assistant-message/__tests__/NativeToolCallParser.spec.ts b/src/core/assistant-message/__tests__/NativeToolCallParser.spec.ts index 49e5427d23b..7af6a68c32b 100644 --- a/src/core/assistant-message/__tests__/NativeToolCallParser.spec.ts +++ b/src/core/assistant-message/__tests__/NativeToolCallParser.spec.ts @@ -2,6 +2,74 @@ import { NativeToolCallParser, type ToolCallStreamEvent } from "../NativeToolCal describe("NativeToolCallParser", () => { describe("parseToolCall", () => { + describe("spawn_subagent tool", () => { + it("should parse the required fields into typed nativeArgs", () => { + const toolCall = { + id: "toolu_spawn", + name: "spawn_subagent" as const, + arguments: JSON.stringify({ + agent: "explore", + description: "Trace JWT refresh failures", + prompt: "Find every place JWT refresh errors are handled.", + model: "my-model", + isolation: "worktree", + }), + } + + const result = NativeToolCallParser.parseToolCall(toolCall) + + expect(result).not.toBeNull() + expect(result?.type).toBe("tool_use") + if (result?.type === "tool_use") { + const nativeArgs = result.nativeArgs as { + agent: string + description: string + prompt: string + model?: string + isolation?: "none" | "worktree" + } + expect(nativeArgs.agent).toBe("explore") + expect(nativeArgs.description).toBe("Trace JWT refresh failures") + expect(nativeArgs.prompt).toContain("JWT refresh") + expect(nativeArgs.model).toBe("my-model") + expect(nativeArgs.isolation).toBe("worktree") + } + }) + + it("should accept optional model and isolation omitted", () => { + const toolCall = { + id: "toolu_spawn2", + name: "spawn_subagent" as const, + arguments: JSON.stringify({ + agent: "general", + description: "Summarize", + prompt: "Summarize the findings.", + }), + } + + const result = NativeToolCallParser.parseToolCall(toolCall) + + expect(result).not.toBeNull() + if (result?.type === "tool_use") { + expect(result.nativeArgs).toMatchObject({ + agent: "general", + description: "Summarize", + prompt: "Summarize the findings.", + }) + } + }) + + it("should fail (return null) when a required field is missing", () => { + const toolCall = { + id: "toolu_spawn3", + name: "spawn_subagent" as const, + arguments: JSON.stringify({}), + } + + expect(NativeToolCallParser.parseToolCall(toolCall)).toBeNull() + }) + }) + describe("read_file tool", () => { it("should parse minimal single-file read_file args", () => { const toolCall = { diff --git a/src/core/assistant-message/__tests__/presentAssistantMessage-custom-tool.spec.ts b/src/core/assistant-message/__tests__/presentAssistantMessage-custom-tool.spec.ts index ba238ceb7d1..600cb716689 100644 --- a/src/core/assistant-message/__tests__/presentAssistantMessage-custom-tool.spec.ts +++ b/src/core/assistant-message/__tests__/presentAssistantMessage-custom-tool.spec.ts @@ -34,6 +34,9 @@ vi.mock("../../tools/AttemptCompletionTool", () => ({ vi.mock("../../tools/AskFollowupQuestionTool", () => ({ askFollowupQuestionTool: { handle: vi.fn().mockResolvedValue(undefined) }, })) +vi.mock("../../tools/NewTaskTool", () => ({ + newTaskTool: { handle: vi.fn().mockResolvedValue(undefined) }, +})) // presentAssistantMessage records tool usage through TelemetryService.instance. vi.mock("@roo-code/telemetry", () => ({ @@ -47,6 +50,8 @@ vi.mock("@roo-code/telemetry", () => ({ })) import { customToolRegistry } from "@roo-code/core" +import { newTaskTool } from "../../tools/NewTaskTool" +import { useMcpToolTool } from "../../tools/UseMcpToolTool" // The snapshot the presenter consumes; the getState doubles below deliberately // disagree with it so any surviving live-read re-entry is caught by assertions. @@ -1081,4 +1086,206 @@ describe("presentAssistantMessage - Custom Tool Recording", () => { expect(mockTask.recordToolUsage).not.toHaveBeenCalled() }) }) + + describe("Subagent hierarchy", () => { + it("rejects new_task from a headless subagent instead of delegating", async () => { + mockTask.subagent = { + runId: "run-1", + groupId: "group-1", + definition: { + name: "explore", + description: "Explores", + systemPrompt: "Explore.", + source: "builtin", + }, + } + mockTask.assistantMessageContent = [ + { + type: "tool_use", + id: "tool_call_delegate", + name: "new_task", + params: { mode: "code", message: "Do more work" }, + nativeArgs: { mode: "code", message: "Do more work" }, + partial: false, + }, + ] + + await presentAssistantMessage(mockTask, baseSnapshot) + + expect(newTaskTool.handle).not.toHaveBeenCalled() + expect(mockTask.userMessageContent).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "tool_result", + tool_use_id: "tool_call_delegate", + is_error: true, + content: expect.stringContaining("not available to a subagent"), + }), + ]), + ) + }) + + it("rejects a tool outside the subagent definition's allowed set", async () => { + mockTask.subagent = { + runId: "run-1", + groupId: "group-1", + definition: { + name: "explore", + description: "Explores", + systemPrompt: "Explore.", + source: "builtin", + readonly: true, + tools: ["read_file"], + }, + } + mockTask.assistantMessageContent = [ + { + type: "tool_use", + id: "tool_call_write", + name: "write_to_file", + params: { path: "src/a.ts", content: "x" }, + nativeArgs: { path: "src/a.ts", content: "x" }, + partial: false, + }, + ] + + await presentAssistantMessage(mockTask, baseSnapshot) + + expect(mockTask.userMessageContent).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "tool_result", + tool_use_id: "tool_call_write", + is_error: true, + content: expect.stringContaining("not available to a subagent"), + }), + ]), + ) + }) + + it("rejects an MCP tool call the subagent definition denies", async () => { + const handle = vi.spyOn(useMcpToolTool, "handle").mockResolvedValue(undefined) + + try { + mockTask.subagent = { + runId: "run-1", + groupId: "group-1", + definition: { + name: "explore", + description: "Explores", + systemPrompt: "Explore.", + source: "builtin", + disallowedTools: ["use_mcp_tool"], + }, + } + mockTask.providerRef = { + deref: () => ({ + getMcpHub: () => ({ findServerNameBySanitizedName: () => "test-server" }), + }), + } + mockTask.assistantMessageContent = [ + { + type: "mcp_tool_use", + id: "tool_call_mcp_denied", + name: "mcp--test-server--test-tool", + serverName: "test-server", + toolName: "test-tool", + arguments: {}, + partial: false, + }, + ] + + await presentAssistantMessage(mockTask, baseSnapshot) + + // The deny list naming use_mcp_tool covers the dynamic mcp-- declaration. + expect(handle).not.toHaveBeenCalled() + expect(mockTask.userMessageContent).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "tool_result", + tool_use_id: "tool_call_mcp_denied", + is_error: true, + content: expect.stringContaining("not available to a subagent"), + }), + ]), + ) + } finally { + handle.mockRestore() + } + }) + + it("runs an MCP tool call the subagent definition allows", async () => { + const handle = vi.spyOn(useMcpToolTool, "handle").mockResolvedValue(undefined) + + try { + mockTask.subagent = { + runId: "run-1", + groupId: "group-1", + definition: { + name: "explore", + description: "Explores", + systemPrompt: "Explore.", + source: "builtin", + }, + } + mockTask.providerRef = { + deref: () => ({ + getMcpHub: () => ({ findServerNameBySanitizedName: () => "test-server" }), + }), + } + mockTask.assistantMessageContent = [ + { + type: "mcp_tool_use", + id: "tool_call_mcp_allowed", + name: "mcp--test-server--test-tool", + serverName: "test-server", + toolName: "test-tool", + arguments: {}, + partial: false, + }, + ] + + await presentAssistantMessage(mockTask, baseSnapshot) + + expect(handle).toHaveBeenCalledTimes(1) + } finally { + handle.mockRestore() + } + }) + + it("allows a tool the subagent definition offers", async () => { + const handle = vi.spyOn(readFileTool, "handle").mockResolvedValue(undefined) + + try { + mockTask.subagent = { + runId: "run-1", + groupId: "group-1", + definition: { + name: "explore", + description: "Explores", + systemPrompt: "Explore.", + source: "builtin", + readonly: true, + tools: ["read_file"], + }, + } + mockTask.assistantMessageContent = [ + { + type: "tool_use", + id: "tool_call_read", + name: "read_file", + params: { path: "src/a.ts" }, + nativeArgs: { path: "src/a.ts" }, + partial: false, + }, + ] + + await presentAssistantMessage(mockTask, baseSnapshot) + + expect(handle).toHaveBeenCalled() + } finally { + handle.mockRestore() + } + }) + }) }) diff --git a/src/core/assistant-message/presentAssistantMessage.ts b/src/core/assistant-message/presentAssistantMessage.ts index 9d69415782e..40b14425b6f 100644 --- a/src/core/assistant-message/presentAssistantMessage.ts +++ b/src/core/assistant-message/presentAssistantMessage.ts @@ -17,6 +17,7 @@ import { buildAutoDenyReason } from "../auto-approval" import { AskIgnoredError } from "../task/AskIgnoredError" import { Task } from "../task/Task" +import { isToolAllowedForSubagent } from "../subagents/toolFilter" import { listFilesTool } from "../tools/ListFilesTool" import { readFileTool } from "../tools/ReadFileTool" @@ -34,6 +35,7 @@ import { askFollowupQuestionTool } from "../tools/AskFollowupQuestionTool" import { switchModeTool } from "../tools/SwitchModeTool" import { attemptCompletionTool, AttemptCompletionCallbacks } from "../tools/AttemptCompletionTool" import { newTaskTool } from "../tools/NewTaskTool" +import { subagentTool } from "../tools/SubagentTool" import { updateTodoListTool } from "../tools/UpdateTodoListTool" import { runSlashCommandTool } from "../tools/RunSlashCommandTool" import { skillTool } from "../tools/SkillTool" @@ -46,6 +48,14 @@ import { codebaseSearchTool } from "../tools/CodebaseSearchTool" import { formatResponse } from "../prompts/responses" import { sanitizeToolUseId } from "../../utils/tool-id" +/** + * True when a `spawn_subagent` batch still owes tool_results for this turn. + * Test doubles that model only the presentation surface omit the method. + */ +function hasQueuedSubagentBatch(cline: Task): boolean { + return typeof cline.hasQueuedSubagentBatch === "function" && cline.hasQueuedSubagentBatch() +} + /** * Maps a raw, potentially model-controlled tool name to a safe analytics key. * Never returns the raw name unless it is a known static tool, so an @@ -368,6 +378,14 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request const includedTools = rawIncludedTools?.map((tool) => resolveToolAlias(tool)) try { + // A subagent definition's tool policy covers MCP calls too. The + // dynamic name resolves against the canonical `use_mcp_tool` + // entry, so a definition that denies MCP tools cannot be bypassed + // by calling a `mcp--server--tool` declaration directly. + if (cline.subagent && !isToolAllowedForSubagent(mcpBlock.name, cline.subagent.definition)) { + throw new Error(`Tool "${mcpBlock.name}" is not available to a subagent.`) + } + // Validate under the canonical "use_mcp_tool" name: the requirements map // is keyed by canonical/alias names, so the dynamic mcp_* name would never // key-match a disabledTools or excludedTools entry naming use_mcp_tool. @@ -773,6 +791,14 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request stateExperiments, includedTools, ) + + // Flat two-level hierarchy: the child prompt omits tools outside + // its definition, and a hallucinated call is rejected here rather + // than delegating, switching the shared mode, spawning a nested + // run, or using a tool the definition excludes. + if (cline.subagent && !isToolAllowedForSubagent(block.name, cline.subagent.definition)) { + throw new Error(`Tool "${block.name}" is not available to a subagent.`) + } } catch (error) { cline.consecutiveMistakeCount++ // For validation errors (unknown tool, tool not allowed for mode), we need to: @@ -807,6 +833,16 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request const recordName = toTelemetryToolName(block.name, isCustomTool, stateExperiments) cline.recordToolUsage(recordName) + // A headless run reports tool starts so the live card can show a + // ticker. The hook is best-effort and never alters execution. + if (cline.subagent?.onToolUse) { + try { + cline.subagent.onToolUse(block.name, (block.params ?? {}) as Record) + } catch { + // A progress hook must not fail a run. + } + } + // Track legacy format usage for read_file tool (for migration monitoring). // Model ids on telemetry events are non-policy labels: a live // `getModel()` read is fine where nothing about this request's tool @@ -1023,6 +1059,11 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request }) break case "new_task": + // A new_task ends this task. Collect every in-flight subagent + // first so its result reaches the conversation before delegation. + if (hasQueuedSubagentBatch(cline)) { + await cline.runSubagentBatch({ immediate: true }) + } await checkpointSaveAndMark(cline) await newTaskTool.handle(cline, block as ToolUse<"new_task">, { askApproval, @@ -1031,6 +1072,14 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request toolCallId, }) break + case "spawn_subagent": + await subagentTool.handle(cline, block as ToolUse<"spawn_subagent">, { + askApproval, + handleError, + pushToolResult, + toolCallId, + }) + break case "attempt_completion": { const completionCallbacks: AttemptCompletionCallbacks = { askApproval, @@ -1159,7 +1208,12 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request // true when out of bounds. This gracefully allows the stream to // continue on and all potential content blocks be presented. // Last block is complete and it is finished executing - cline.userMessageContentReady = true // Will allow `pWaitFor` to continue. + // A queued subagent batch keeps the turn open: its tool_results are + // pushed in call order by `runSubagentBatch`, which owns the ready + // latch for that turn. + if (!hasQueuedSubagentBatch(cline)) { + cline.userMessageContentReady = true // Will allow `pWaitFor` to continue. + } } // Call next block if it exists (if not then read stream will call it @@ -1175,7 +1229,7 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request } else { // CRITICAL FIX: If we're out of bounds and the stream is complete, set userMessageContentReady // This handles the case where assistantMessageContent is empty or becomes empty after processing - if (cline.didCompleteReadingStream) { + if (cline.didCompleteReadingStream && !hasQueuedSubagentBatch(cline)) { cline.userMessageContentReady = true } } diff --git a/src/core/prompts/tools/__tests__/spawn-subagent-schema.spec.ts b/src/core/prompts/tools/__tests__/spawn-subagent-schema.spec.ts new file mode 100644 index 00000000000..37bbfd0967f --- /dev/null +++ b/src/core/prompts/tools/__tests__/spawn-subagent-schema.spec.ts @@ -0,0 +1,35 @@ +// npx vitest run core/prompts/tools/__tests__/spawn-subagent-schema.spec.ts + +import { getNativeTools } from "../native-tools" + +function spawnSubagentTool() { + const tool = getNativeTools().find((t) => "function" in t && t.function?.name === "spawn_subagent") + if (!tool || !("function" in tool)) { + throw new Error("spawn_subagent tool not advertised") + } + const fn = tool.function + const parameters = fn.parameters as { + properties?: Record + required?: string[] + } + return { fn, parameters } +} + +describe("spawn_subagent native schema", () => { + it("does not use strict mode, which would force optional fields into required", () => { + // strict: true makes every property required, so the model must invent a + // value for `model`/`isolation` and often emits an empty argument object + // instead. The tool must stay loose like read_command_output. + expect(spawnSubagentTool().fn.strict).not.toBe(true) + }) + + it("requires only the three real arguments and leaves model/isolation optional", () => { + const { parameters } = spawnSubagentTool() + expect(parameters.required).toEqual(["agent", "description", "prompt"]) + expect(parameters.properties).toHaveProperty("agent") + expect(parameters.properties).toHaveProperty("description") + expect(parameters.properties).toHaveProperty("prompt") + expect(parameters.properties).toHaveProperty("model") + expect(parameters.properties).toHaveProperty("isolation") + }) +}) diff --git a/src/core/prompts/tools/effective-tool-policy.ts b/src/core/prompts/tools/effective-tool-policy.ts index 147ea3d5fe4..3ec14271c4e 100644 --- a/src/core/prompts/tools/effective-tool-policy.ts +++ b/src/core/prompts/tools/effective-tool-policy.ts @@ -158,6 +158,8 @@ export interface EffectiveToolPolicyInput { * `access_mcp_resource` based on resources from disallowed servers. */ allowedMcpServers?: string[] + /** Native subagent tooling is opt-in; a false/absent value removes `spawn_subagent`. */ + subagentsEnabled?: boolean } export interface EffectiveToolPolicy { @@ -252,6 +254,7 @@ export function resolveEffectiveToolPolicy(input: EffectiveToolPolicyInput): Eff todoListEnabled, codeIndexManager, allowedMcpServers, + subagentsEnabled, } = input // A disabledTools entry naming a protocol tool carries no disabling weight; @@ -351,6 +354,13 @@ export function resolveEffectiveToolPolicy(input: EffectiveToolPolicyInput): Eff allowedToolNames.delete("use_mcp_tool") } + // 10b. Drop spawn_subagent unless the feature is enabled. A disabledTools + // entry can also remove it (step 9), but the feature flag is the + // primary gate for every mode, including custom modes. + if (subagentsEnabled !== true) { + allowedToolNames.delete("spawn_subagent") + } + // 11. Protocol guarantee: re-add every protocol tool that the effective // disabledTools list and the model's excludedTools do not suppress. // After the entry partition only an excludedTools entry can suppress diff --git a/src/core/prompts/tools/filter-tools-for-mode.ts b/src/core/prompts/tools/filter-tools-for-mode.ts index 3921ee79fb3..3bfb223ef8b 100644 --- a/src/core/prompts/tools/filter-tools-for-mode.ts +++ b/src/core/prompts/tools/filter-tools-for-mode.ts @@ -76,6 +76,7 @@ export function filterNativeToolsForMode( todoListEnabled?: boolean disabledTools?: string[] modelInfo?: Pick + subagentsEnabled?: boolean }, mcpHub?: McpHub, allowedMcpServers?: string[], @@ -99,6 +100,7 @@ export function filterNativeToolsForMode( todoListEnabled: settings?.todoListEnabled, codeIndexManager, allowedMcpServers, + subagentsEnabled: settings?.subagentsEnabled, }) // Apply model-specific alias renames (canonical -> alias) to the allowed set. diff --git a/src/core/prompts/tools/native-tools/index.ts b/src/core/prompts/tools/native-tools/index.ts index d5f75b590cd..bd3667ba633 100644 --- a/src/core/prompts/tools/native-tools/index.ts +++ b/src/core/prompts/tools/native-tools/index.ts @@ -14,6 +14,7 @@ import readCommandOutput from "./read_command_output" import { createReadFileTool, type ReadFileToolOptions } from "./read_file" import runSlashCommand from "./run_slash_command" import skill from "./skill" +import spawnSubagent from "./spawn_subagent" import searchReplace from "./search_replace" import edit_file from "./edit_file" import searchFiles from "./search_files" @@ -61,6 +62,7 @@ export function getNativeTools(options: NativeToolsOptions = {}): OpenAI.Chat.Ch createReadFileTool(readFileOptions), runSlashCommand, skill, + spawnSubagent, searchReplace, edit_file, editTool, diff --git a/src/core/prompts/tools/native-tools/spawn_subagent.ts b/src/core/prompts/tools/native-tools/spawn_subagent.ts new file mode 100644 index 00000000000..6bd0569a3dc --- /dev/null +++ b/src/core/prompts/tools/native-tools/spawn_subagent.ts @@ -0,0 +1,53 @@ +import type OpenAI from "openai" + +/** + * Native tool definition for `spawn_subagent`. + * + * The description is replaced at request time with one that lists the + * available agent names and their one-line descriptions, so the parent pays + * only a small, bounded prompt cost per agent. + */ +const spawnSubagent: OpenAI.Chat.ChatCompletionTool = { + type: "function", + function: { + name: "spawn_subagent", + // Do not use strict mode: `model` and `isolation` are optional, and a + // strict schema forces every property into `required`, which pressures + // the model to invent a value for optional fields (and often to emit an + // empty argument object instead). Same rationale as `read_command_output`. + description: + "Delegate an isolated investigation or implementation to a subagent. The subagent works in its own context and returns only a final summary; its tool output never enters this conversation. Call this tool multiple times in one response to run agents in parallel. Do not use it for work you can finish with a single read or edit. Only the agent, description and prompt arguments are required; model and isolation are optional.", + parameters: { + type: "object", + properties: { + agent: { + type: "string", + description: "The subagent to run, by name. Use one of the agents listed in this tool description.", + }, + description: { + type: "string", + description: "A short title for the UI card, 5-10 words. Example: 'Trace JWT refresh failures'.", + }, + prompt: { + type: "string", + description: + "Complete instructions for the subagent. It cannot ask you questions, so include every file, symptom, constraint and expected output format it needs.", + }, + model: { + type: "string", + description: "Optional model id override for this run. Omit to inherit the parent model.", + }, + isolation: { + type: "string", + enum: ["none", "worktree"], + description: + "Use 'worktree' when the subagent edits files, so its changes stay off this workspace until you review them. Defaults to 'none'.", + }, + }, + required: ["agent", "description", "prompt"], + additionalProperties: false, + }, + }, +} + +export default spawnSubagent diff --git a/src/core/subagents/SubagentManager.ts b/src/core/subagents/SubagentManager.ts new file mode 100644 index 00000000000..f7af01fc06e --- /dev/null +++ b/src/core/subagents/SubagentManager.ts @@ -0,0 +1,594 @@ +import { + DEFAULT_MAX_CONCURRENT_SUBAGENTS, + DEFAULT_SUBAGENT_MAX_TURNS, + MAX_CONCURRENT_SUBAGENTS, + type SubagentDefinition, + type SubagentRunSnapshot, + type SubagentUpdatePayload, +} from "@roo-code/types" + +import type { Task } from "../task/Task" +import type { ClineProvider } from "../webview/ClineProvider" + +import { SubagentRunner, type RunSubagentOptions } from "./SubagentRunner" +import type { SubagentSpawnRequest, SubagentToolOutcome } from "./types" + +const UPDATE_THROTTLE_MS = 200 + +/** Minimal counting semaphore with FIFO release order. */ +class Semaphore { + private active = 0 + private readonly waiters: Array<() => void> = [] + + constructor(private limit: number) {} + + setLimit(limit: number): void { + this.limit = Math.max(1, limit) + this.drain() + } + + async acquire(): Promise<() => void> { + if (this.active < this.limit) { + this.active++ + return () => this.release() + } + + await new Promise((resolve) => this.waiters.push(resolve)) + return () => this.release() + } + + private release(): void { + this.active = Math.max(0, this.active - 1) + this.drain() + } + + private drain(): void { + while (this.active < this.limit && this.waiters.length > 0) { + const next = this.waiters.shift() + if (!next) { + break + } + // Count the slot before waking the waiter, so this loop cannot + // release more waiters than the limit allows. + this.active++ + next() + } + } +} + +interface RunRecord { + snapshot: SubagentRunSnapshot + runnerRef: { current?: SubagentRunner } + promise: Promise + /** Settles the promise the parent batch awaits. */ + resolve: (outcome: SubagentToolOutcome) => void + parentTask: Task +} + +interface GroupRecord { + groupId: string + parentTaskId: string + startedAt: number + completedAt?: number + order: string[] + runs: Map + emitTimer?: ReturnType + /** + * The in-flight finalization of this group. A second caller (a cancel, a + * delete) must wait for it instead of returning at the `completedAt` guard, + * or it could remove task storage while the leader write still runs. + */ + finalizing?: Promise + /** + * Set when the group is dropped from the manager. The record can stay + * reachable through an in-flight `execute` closure, and a late progress + * patch or transcript must not emit or buffer for a deleted parent. + */ + removed?: boolean +} + +export interface SpawnSubagentParams { + parentTask: Task + definition: SubagentDefinition + request: SubagentSpawnRequest + runId: string + groupId: string + toolUseId: string +} + +export interface SubagentManagerOptions { + provider: ClineProvider + log?: (message: string) => void + /** Overrides runner creation. Tests use it to drive a run without an API. */ + createRunner?: (options: RunSubagentOptions) => SubagentRunner +} + +/** + * Owns every in-flight subagent run for one provider. + * + * Responsibilities: concurrency (a global semaphore plus a single writer + * lock), live group snapshots (throttled `subagentUpdate` posts), cancellation, + * and the final history metadata that links a transcript back to its parent + * turn. It never posts the child as the active task. + */ +export class SubagentManager { + private readonly groups = new Map() + private readonly runToGroup = new Map() + private readonly concurrency = new Semaphore(DEFAULT_MAX_CONCURRENT_SUBAGENTS) + private readonly writeLock = new Semaphore(1) + private disposed = false + + constructor(private readonly options: SubagentManagerOptions) {} + + /** + * Drops every group, run record and timer of a parent task. Called after + * the parent's runs are cancelled (or when the task is deleted), so a + * deleted parent keeps no Task, runner or group reference in this manager. + */ + clearStateForParent(parentTaskId: string): void { + for (const [groupId, group] of [...this.groups]) { + if (group.parentTaskId === parentTaskId) { + this.removeGroup(groupId, group) + } + } + } + + private removeGroup(groupId: string, group: GroupRecord): void { + group.removed = true + + if (group.emitTimer) { + clearTimeout(group.emitTimer) + group.emitTimer = undefined + } + + for (const runId of group.runs.keys()) { + this.runToGroup.delete(runId) + } + + this.groups.delete(groupId) + } + + /** + * Starts a run and returns the promise the parent batch awaits. The call is + * synchronous on purpose: the presenter must keep dispatching sibling + * spawns while a slot is busy. + */ + spawn(params: SpawnSubagentParams): Promise { + const { parentTask, definition, request, runId, groupId, toolUseId } = params + + // A run id owns a task directory, a history row and a worktree path. Two + // runs that share one would overwrite each other, so reject the reuse + // instead of merging the records. + if (this.runToGroup.has(runId)) { + return Promise.reject(new Error(`Duplicate subagent run id: ${runId}`)) + } + + const group = this.getOrCreateGroup(groupId, parentTask.taskId) + const now = Date.now() + + const snapshot: SubagentRunSnapshot = { + runId, + parentTaskId: parentTask.taskId, + toolUseId, + groupId, + agentName: definition.name, + description: request.description, + prompt: request.prompt, + modelId: request.model ?? definition.model ?? "inherit", + status: "queued", + startedAt: now, + toolCallCount: 0, + tokenUsage: { input: 0, output: 0 }, + readonly: definition.readonly, + isolation: request.isolation ?? definition.isolation ?? "none", + filesRead: [], + filesModified: [], + } + + const runnerRef: { current?: SubagentRunner } = {} + let resolveRun!: (outcome: SubagentToolOutcome) => void + const promise = new Promise((resolve) => { + resolveRun = resolve + }) + + const record: RunRecord = { + snapshot, + runnerRef, + promise, + resolve: resolveRun, + parentTask, + } + + group.order.push(runId) + group.runs.set(runId, record) + this.runToGroup.set(runId, groupId) + this.scheduleEmit(group) + + // The record must exist before execution starts so a queued cancellation + // can settle the promise without waiting for a concurrency slot. + void this.execute({ params, group, snapshot, runnerRef }).then((outcome) => { + record.resolve(outcome) + }) + + return promise + } + + /** Cancels one run. A queued run resolves without starting. */ + cancel(runId: string): boolean { + const groupId = this.runToGroup.get(runId) + const group = groupId ? this.groups.get(groupId) : undefined + const run = group?.runs.get(runId) + + if (!run || isTerminal(run.snapshot.status)) { + return false + } + + run.snapshot.status = "cancelled" + run.snapshot.completedAt = Date.now() + + if (run.runnerRef.current) { + run.runnerRef.current.requestCancel() + } else { + // Still queued behind a slot or the write lock: settle now instead of + // making the parent batch wait for an unrelated run to release it. + run.resolve(this.buildCancelledOutcome(run.snapshot, run.snapshot.runId, run.snapshot.agentName)) + } + + if (group) { + this.scheduleEmit(group) + } + return true + } + + /** + * Cancels every non-terminal run of a parent task, e.g. on task cancel or + * "new task". It waits for each cancelled child to settle before it finalizes + * the group, so the terminal snapshot, transcript and history row are written + * before a caller deletes the task storage. After settling the runs it + * finalizes each affected group so the terminal (cancelled) snapshots are + * persisted into the leader message. Without this the webview re-renders + * cancelled runs as still "running" when it rebuilds the chat from saved + * state after an abort. + */ + async cancelAllForParent(parentTaskId: string): Promise { + const affected: GroupRecord[] = [] + const settlements: Promise[] = [] + + for (const group of this.groups.values()) { + if (group.parentTaskId !== parentTaskId) { + continue + } + + for (const run of [...group.runs.values()]) { + // The promise is awaited for every run in the scope, not only for the + // ones this call cancelled: a run cancelled earlier (from the live + // card) has a terminal status but its child may still be winding + // down, and its last save must land before the caller deletes. + this.cancel(run.snapshot.runId) + settlements.push(run.promise) + } + affected.push(group) + } + + // A running child stops asynchronously. Wait for its own settlement, not + // only the cancel request, so it cannot write a history row or transcript + // after the caller removed them. + await Promise.allSettled(settlements) + + for (const group of affected) { + await this.completeGroupIfDone(group) + } + } + + /** + * Settles a group after the parent turn has collected every spawn result. + * Called by `Task#runSubagentBatch`, which is the only point that knows all + * spawns of the turn are registered. + */ + async finalizeGroup(groupId: string): Promise { + const group = this.groups.get(groupId) + if (group) { + await this.completeGroupIfDone(group) + } + } + + dispose(): void { + this.disposed = true + for (const [groupId, group] of [...this.groups]) { + for (const run of group.runs.values()) { + if (!isTerminal(run.snapshot.status)) { + run.runnerRef.current?.requestCancel() + } + } + this.removeGroup(groupId, group) + } + } + + private getOrCreateGroup(groupId: string, parentTaskId: string): GroupRecord { + const existing = this.groups.get(groupId) + + if (existing) { + return existing + } + + const group: GroupRecord = { + groupId, + parentTaskId, + startedAt: Date.now(), + order: [], + runs: new Map(), + } + this.groups.set(groupId, group) + return group + } + + private async execute(context: { + params: SpawnSubagentParams + group: GroupRecord + snapshot: SubagentRunSnapshot + runnerRef: { current?: SubagentRunner } + }): Promise { + const { params, group, snapshot, runnerRef } = context + const { parentTask, definition, request, runId } = params + const log = this.options.log + + try { + const state = await this.options.provider.getState({ includeTaskHistory: false }) + const limit = clampConcurrency(state.maxConcurrentSubagents) + this.concurrency.setLimit(limit) + + const maxTurns = definition.maxTurns ?? state.defaultSubagentMaxTurns ?? DEFAULT_SUBAGENT_MAX_TURNS + + const releaseSlot = await this.concurrency.acquire() + let releaseWrite: (() => void) | undefined + const cancelled = () => this.disposed || snapshot.status === "cancelled" + + try { + if (cancelled()) { + return this.finishCancelled(params) + } + + const needsWriteLock = definition.readonly !== true && snapshot.isolation !== "worktree" + if (needsWriteLock) { + releaseWrite = await this.writeLock.acquire() + } + + if (cancelled()) { + return this.finishCancelled(params) + } + + snapshot.status = "running" + snapshot.startedAt = Date.now() + this.scheduleEmit(group) + + const runnerOptions: RunSubagentOptions = { + provider: this.options.provider, + parentTask, + definition, + request, + runId, + groupId: group.groupId, + toolUseId: snapshot.toolUseId, + maxTurns, + log, + onProgress: (patch) => { + Object.assign(snapshot, patch) + this.scheduleEmit(group) + }, + } + const runner = this.options.createRunner + ? this.options.createRunner(runnerOptions) + : new SubagentRunner(runnerOptions) + + const record = group.runs.get(runId) + if (record) { + record.runnerRef.current = runner + } + runnerRef.current = runner + + const outcome = await runner.run() + this.applyOutcome(snapshot, outcome) + return outcome + } finally { + releaseWrite?.() + releaseSlot() + } + } catch (error) { + const outcome: SubagentToolOutcome = { + runId, + agentName: definition.name, + status: "failed", + summary: "", + error: error instanceof Error ? error.message : String(error), + filesRead: [], + filesModified: [], + toolCallCount: 0, + tokenUsage: { input: 0, output: 0 }, + } + this.applyOutcome(snapshot, outcome) + return outcome + } + } + + private finishCancelled(params: SpawnSubagentParams): SubagentToolOutcome { + const snapshot = this.groups.get(params.groupId)?.runs.get(params.runId)?.snapshot + const outcome = this.buildCancelledOutcome(snapshot, params.runId, params.definition.name) + this.applyOutcome(snapshot, outcome) + return outcome + } + + private buildCancelledOutcome( + snapshot: SubagentRunSnapshot | undefined, + runId: string, + agentName: string, + ): SubagentToolOutcome { + return { + runId: snapshot?.runId ?? runId, + agentName: snapshot?.agentName ?? agentName, + status: "cancelled", + summary: "", + error: "Cancelled before the run started", + filesRead: snapshot?.filesRead ?? [], + filesModified: snapshot?.filesModified ?? [], + toolCallCount: snapshot?.toolCallCount ?? 0, + tokenUsage: snapshot?.tokenUsage ?? { input: 0, output: 0 }, + } + } + + private applyOutcome(snapshot: SubagentRunSnapshot | undefined, outcome: SubagentToolOutcome): void { + if (!snapshot) { + return + } + + snapshot.status = outcome.status + snapshot.completedAt = Date.now() + snapshot.durationMs = outcome.durationMs + snapshot.summary = outcome.summary || undefined + snapshot.error = outcome.error + snapshot.partial = outcome.partial + snapshot.filesRead = outcome.filesRead + snapshot.filesModified = outcome.filesModified + snapshot.toolCallCount = outcome.toolCallCount + snapshot.tokenUsage = outcome.tokenUsage + snapshot.worktree = outcome.worktree + + const groupId = this.runToGroup.get(outcome.runId) + const group = groupId ? this.groups.get(groupId) : undefined + if (group) { + this.scheduleEmit(group) + } + } + + private async completeGroupIfDone(group: GroupRecord): Promise { + // A finalizer already in flight owns the writes for this group; a second + // caller waits for it rather than returning early on `completedAt`. + if (group.finalizing) { + await group.finalizing + return + } + + if (this.disposed || group.removed || group.completedAt) { + return + } + + const runs = group.order + .map((runId) => group.runs.get(runId)?.snapshot) + .filter((snapshot): snapshot is SubagentRunSnapshot => !!snapshot) + + if (runs.length === 0 || runs.some((snapshot) => !isTerminal(snapshot.status))) { + return + } + + group.completedAt = Date.now() + this.scheduleEmit(group) + + const parentTask = group.runs.get(group.order[0])?.parentTask + group.finalizing = (async () => { + if (parentTask) { + // Persist the final group on the leader row so a reloaded chat can + // render the card without the live stream. A failed save leaves the + // group terminal, so it is never retried: it must be logged, not + // dropped silently. + try { + await parentTask.updateSubagentGroupMessage(group.groupId, runs) + } catch (error) { + this.options.log?.( + `[subagent] failed to persist the final group ${group.groupId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + } + } + + await this.persistHistoryMeta(group, runs) + })() + + await group.finalizing + } + + /** + * Writes the terminal run metadata onto each transcript's history row. + * + * Awaited by `completeGroupIfDone`: the caller may delete the rows right + * after, and an unawaited upsert could recreate one. Called only for terminal + * snapshots, so the stored status is the terminal one. + */ + private async persistHistoryMeta(group: GroupRecord, runs: SubagentRunSnapshot[]): Promise { + // Never inside a group/slot lock: the history store has its own lock and + // `atomicReadAndUpdate` is not reentrant. + for (const snapshot of runs) { + // A run that never got a history row has nothing to annotate. The + // store rejects the update for an uncached id, so skip it explicitly. + if (!this.options.provider.taskHistoryStore.get(snapshot.runId)) { + continue + } + + try { + await this.options.provider.taskHistoryStore.atomicReadAndUpdate(snapshot.runId, (item) => ({ + ...item, + subagent: { + runId: snapshot.runId, + groupId: group.groupId, + parentTaskId: group.parentTaskId, + agentName: snapshot.agentName, + status: snapshot.status, + partial: snapshot.partial, + }, + })) + } catch (error) { + // The transcript write already owns durability; a metadata failure + // must not fail the run, but it is no longer silent. + this.options.log?.( + `[subagent] failed to persist history metadata for ${snapshot.runId}: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + } + } + } + + private scheduleEmit(group: GroupRecord): void { + if (this.disposed || group.removed || group.emitTimer) { + return + } + + group.emitTimer = setTimeout(() => { + group.emitTimer = undefined + this.emit(group) + }, UPDATE_THROTTLE_MS) + } + + private emit(group: GroupRecord): void { + if (group.removed) { + return + } + + const runs = group.order + .map((runId) => group.runs.get(runId)?.snapshot) + .filter((snapshot): snapshot is SubagentRunSnapshot => !!snapshot) + + const payload: SubagentUpdatePayload = { + parentTaskId: group.parentTaskId, + groupId: group.groupId, + runs, + } + + void this.options.provider + .postMessageToWebview({ type: "subagentUpdate", subagentUpdate: payload }) + .catch(() => { + // A closed webview is not an error for a headless run. + }) + } +} + +function isTerminal(status: SubagentRunSnapshot["status"]): boolean { + return status === "completed" || status === "failed" || status === "cancelled" +} + +function clampConcurrency(value: number | undefined): number { + if (value === undefined) { + return DEFAULT_MAX_CONCURRENT_SUBAGENTS + } + + return Math.min(MAX_CONCURRENT_SUBAGENTS, Math.max(1, Math.round(value))) +} diff --git a/src/core/subagents/SubagentRegistry.ts b/src/core/subagents/SubagentRegistry.ts new file mode 100644 index 00000000000..8fcc4991444 --- /dev/null +++ b/src/core/subagents/SubagentRegistry.ts @@ -0,0 +1,358 @@ +import * as fs from "fs/promises" +import * as fsSync from "fs" +import * as os from "os" +import * as path from "path" + +import matter from "gray-matter" +import type { SubagentDefinition, SubagentSource } from "@roo-code/types" + +import { subagentDefinitionSchema, subagentFrontmatterSchema } from "@roo-code/types" + +export interface ParseSubagentResult { + definition?: SubagentDefinition + error?: string +} + +/** + * Frontmatter engines that `gray-matter` evaluates as code. A file can select + * one with a language marker after the opening fence (`---javascript`), and + * that marker overrides the configured parser. + */ +const EXECUTABLE_FRONTMATTER_LANGUAGES = new Set(["javascript", "js"]) + +/** The language marker `gray-matter` would read from the line after the opening fence. */ +function frontmatterLanguage(raw: string): string { + const openingLine = raw.match(/^---([^\r\n]*)/) + return openingLine?.[1].trim().toLowerCase() ?? "" +} + +/** + * Parses a Markdown agent definition. + * + * The frontmatter supplies the metadata; the body is the system prompt. A file + * without frontmatter keeps the whole body as the prompt and derives the name + * from the file name, which matches how `.claude/agents` files are often + * written. Validation failures return an error instead of throwing so a single + * broken file never blocks the rest of the registry. + */ +export function parseSubagentMarkdown( + raw: string, + options: { source: SubagentSource; filePath: string; fallbackName?: string }, +): ParseSubagentResult { + // A project file must not run code in the extension host during discovery. + // Reject the executable engines before `matter` can evaluate the block. + if (EXECUTABLE_FRONTMATTER_LANGUAGES.has(frontmatterLanguage(raw))) { + return { error: `Executable frontmatter is not allowed in ${options.filePath}` } + } + + let parsed: { data: Record; content: string } + + try { + parsed = matter(raw) + } catch (error) { + return { error: `Invalid frontmatter in ${options.filePath}: ${(error as Error).message}` } + } + + const frontmatterResult = subagentFrontmatterSchema.safeParse(parsed.data ?? {}) + + if (!frontmatterResult.success) { + return { error: `Invalid frontmatter in ${options.filePath}: ${frontmatterResult.error.message}` } + } + + const frontmatter = frontmatterResult.data + const fallback = options.fallbackName ?? path.basename(options.filePath, path.extname(options.filePath)) + const name = frontmatter.name ?? fallback + const systemPrompt = parsed.content.trim() + + if (!systemPrompt) { + return { error: `Agent file ${options.filePath} has an empty system prompt` } + } + + const description = frontmatter.description ?? `Custom subagent defined in ${path.basename(options.filePath)}.` + + const candidate = { + ...frontmatter, + name, + description, + systemPrompt, + source: options.source, + } + + const result = subagentDefinitionSchema.safeParse(candidate) + + if (!result.success) { + return { error: `Invalid agent definition in ${options.filePath}: ${result.error.message}` } + } + + return { definition: result.data } +} + +/** + * Location a registry scans, in precedence order (first wins). + */ +export interface SubagentSourceDirectory { + path: string + source: SubagentSource +} + +export function getSubagentSourceDirectories(cwd: string, homeDir: string = os.homedir()): SubagentSourceDirectory[] { + return [ + { path: path.join(cwd, ".zoo", "agents"), source: "project" }, + { path: path.join(cwd, ".claude", "agents"), source: "project" }, + { path: path.join(homeDir, ".zoo", "agents"), source: "user" }, + ] +} + +export interface SubagentRegistryOptions { + cwd: string + homeDir?: string + /** Called for every skipped or replaced definition. */ + onWarning?: (message: string) => void + /** Set false in tests to avoid touching the VS Code file watcher. */ + watch?: boolean +} + +/** + * Resolves the subagent definitions available to a workspace. + * + * Precedence: `.zoo/agents` > `.claude/agents` > `~/.zoo/agents` > builtins. + * A project definition overrides a user definition with the same name, and any + * definition overrides a builtin. + */ +export class SubagentRegistry { + private definitions = new Map() + private watchers: Array<{ dispose(): void }> = [] + private reloadTimer?: NodeJS.Timeout + private disposed = false + private readonly options: Required> & + Pick + + constructor(options: SubagentRegistryOptions) { + this.options = { + cwd: options.cwd, + homeDir: options.homeDir ?? os.homedir(), + watch: options.watch ?? true, + onWarning: options.onWarning, + } + } + + /** Loads builtins first, then project/user files, then starts watchers. */ + async load(): Promise { + this.definitions.clear() + for (const definition of getBuiltinSubagents()) { + this.definitions.set(definition.name, definition) + } + + // Lowest precedence first: a later, higher-precedence file overwrites it. + const directories = getSubagentSourceDirectories(this.options.cwd, this.options.homeDir).reverse() + + for (const directory of directories) { + await this.loadDirectory(directory.path, directory.source) + } + + this.startWatching() + } + + get(name: string): SubagentDefinition | undefined { + return this.definitions.get(name) + } + + getAll(): SubagentDefinition[] { + return [...this.definitions.values()].sort((a, b) => { + const rank = (definition: SubagentDefinition) => + definition.source === "project" ? 0 : definition.source === "user" ? 1 : 2 + return rank(a) - rank(b) || a.name.localeCompare(b.name) + }) + } + + /** Compact catalog for the `spawn_subagent` tool description. */ + getCatalog(): Array<{ name: string; description: string }> { + return this.getAll().map(({ name, description }) => ({ name, description })) + } + + has(name: string): boolean { + return this.definitions.has(name) + } + + dispose(): void { + this.disposed = true + if (this.reloadTimer) { + clearTimeout(this.reloadTimer) + this.reloadTimer = undefined + } + for (const watcher of this.watchers) { + watcher.dispose() + } + this.watchers = [] + this.definitions.clear() + } + + private async loadDirectory(directory: string, source: SubagentSource): Promise { + let entries: string[] + try { + entries = await fs.readdir(directory) + } catch { + // Missing directories are expected: every source is optional. + return + } + + for (const entry of entries) { + if (!entry.endsWith(".md") && !entry.endsWith(".mdx")) { + continue + } + + const filePath = path.join(directory, entry) + try { + const raw = await fs.readFile(filePath, "utf8") + const { definition, error } = parseSubagentMarkdown(raw, { + source, + filePath, + fallbackName: path.basename(entry, path.extname(entry)), + }) + + if (error || !definition) { + this.options.onWarning?.(error ?? `Skipped agent file ${filePath}`) + continue + } + + const existing = this.definitions.get(definition.name) + if (existing && existing.source !== "builtin") { + this.options.onWarning?.( + `Agent "${definition.name}" from ${filePath} overrides an existing definition`, + ) + } + + this.definitions.set(definition.name, definition) + } catch (error) { + this.options.onWarning?.(`Failed to read agent file ${filePath}: ${(error as Error).message}`) + } + } + } + + private startWatching(): void { + if (!this.options.watch || this.disposed || this.watchers.length > 0) { + return + } + + let vscode: typeof import("vscode") + try { + // Loaded lazily so pure consumers (and unit tests) can use the registry + // without a VS Code extension host. + vscode = require("vscode") + } catch { + return + } + + for (const directory of getSubagentSourceDirectories(this.options.cwd, this.options.homeDir)) { + try { + if (!fsSync.existsSync(directory.path)) { + continue + } + + const watcher = vscode.workspace.createFileSystemWatcher( + new vscode.RelativePattern(directory.path, "*.{md,mdx}"), + ) + const reload = () => this.scheduleReload() + watcher.onDidCreate(reload) + watcher.onDidChange(reload) + watcher.onDidDelete(reload) + this.watchers.push(watcher) + } catch { + // A watcher failure must never break agent resolution. + } + } + } + + private scheduleReload(): void { + if (this.disposed) { + return + } + if (this.reloadTimer) { + clearTimeout(this.reloadTimer) + } + this.reloadTimer = setTimeout(() => { + this.reloadTimer = undefined + void this.load() + }, 250) + } +} + +/** + * Built-in agents. These are intentionally narrow: `explore` and `reviewer` + * are read-only and cheap to run in parallel; `general` can edit and is + * serialized against other writers by the manager. None sets `maxTurns`, so a + * built-in run uses the user's saved default turn limit like a custom + * definition without its own limit. + */ +export function getBuiltinSubagents(): SubagentDefinition[] { + return [ + { + name: "explore", + description: + "Read-only codebase exploration: locate symbols, trace callers and gather file facts without editing.", + systemPrompt: [ + "You are an exploration subagent. You investigate a codebase and report facts.", + "", + "Rules:", + "- Use read_file, search_files, list_files and codebase_search. Never modify files.", + "- Work from the provided instructions. You cannot ask questions; if something is ambiguous, state the assumption and continue.", + "- Prefer targeted searches over broad reads. Read only the files needed to answer.", + "- Finish with attempt_completion. The result must be a compact report: findings, exact file paths with line numbers, and open questions.", + ].join("\n"), + readonly: true, + tools: [ + "read_file", + "search_files", + "list_files", + "codebase_search", + "attempt_completion", + "update_todo_list", + ], + isolation: "none", + color: "blue", + source: "builtin", + }, + { + name: "reviewer", + description: "Read-only code review: correctness, security, regressions and missing tests.", + systemPrompt: [ + "You are a code review subagent. You audit code and report defects.", + "", + "Rules:", + "- Read the relevant files and tests. Never modify files.", + "- Look for correctness bugs, security issues, race conditions, missing error handling and missing tests.", + "- Do not report style preferences unless they cause a defect.", + "- Finish with attempt_completion. The result must list each finding as: severity, file:line, what is wrong, and why it matters. If you find nothing, say so explicitly.", + ].join("\n"), + readonly: true, + tools: [ + "read_file", + "search_files", + "list_files", + "codebase_search", + "attempt_completion", + "update_todo_list", + ], + isolation: "none", + color: "purple", + source: "builtin", + }, + { + name: "general", + description: "General-purpose worker that can read, edit, run tests and commands, and report back.", + systemPrompt: [ + "You are a general-purpose subagent. You complete the delegated task and report the outcome.", + "", + "Rules:", + "- Stay strictly inside the delegated scope. Do not start unrelated work.", + "- You cannot ask the user or the parent questions. Make reasonable assumptions and state them in the final report.", + "- Make the smallest correct change. Run the narrowest relevant test after editing.", + "- Finish with attempt_completion. The result must summarize what changed, which files were modified, what you verified, and anything that remains.", + ].join("\n"), + readonly: false, + isolation: "none", + color: "green", + source: "builtin", + }, + ] +} diff --git a/src/core/subagents/SubagentRunner.ts b/src/core/subagents/SubagentRunner.ts new file mode 100644 index 00000000000..dba8c034297 --- /dev/null +++ b/src/core/subagents/SubagentRunner.ts @@ -0,0 +1,349 @@ +import * as os from "os" +import * as path from "path" + +import { + providerDefinitionList, + type ClineAsk, + type ProviderSettings, + type SubagentDefinition, + type SubagentRunSnapshot, + type SubagentToolActivity, +} from "@roo-code/types" + +import { Task } from "../task/Task" +import type { ClineProvider } from "../webview/ClineProvider" +import { getTaskDirectoryPath } from "../../utils/storage" + +import { finalizeSubagentWorktree, createSubagentWorktree } from "./worktree" +import type { SubagentAskResult, SubagentSpawnRequest, SubagentTaskContext, SubagentToolOutcome } from "./types" + +const READ_TOOLS = new Set(["read_file"]) +const WRITE_TOOLS = new Set(["write_to_file", "apply_diff", "edit", "search_and_replace", "edit_file", "apply_patch"]) + +/** Upper bound on the live activity feed kept in the run snapshot. */ +const MAX_ACTIVITY = 50 + +/** + * Tool name -> webview i18n key (namespace `chat:subagents.actions`). The feed + * sends these structural keys instead of pre-translated strings so the owning + * locale renders them. + */ +const SUBAGENT_ACTION_LABEL_KEYS: Record = { + read_file: "readfile", + search_files: "searchfiles", + list_files: "listfiles", + codebase_search: "codebasesearch", + execute_command: "executecommand", + write_to_file: "writetofile", + apply_diff: "editfile", + edit: "editfile", + search_and_replace: "editfile", + edit_file: "editfile", + apply_patch: "editfile", + attempt_completion: "completion", +} + +export interface RunSubagentOptions { + provider: ClineProvider + parentTask: Task + definition: SubagentDefinition + request: SubagentSpawnRequest + runId: string + groupId: string + toolUseId: string + maxTurns: number + /** Receives the live snapshot patches for the group card. */ + onProgress: (patch: Partial) => void + log?: (message: string) => void +} + +function resolveModelConfiguration(base: ProviderSettings, override?: string): ProviderSettings { + if (!override || override === "inherit") { + return base + } + + // Each provider reads its model from its own field (`openRouterModelId`, + // `ollamaModelId`, ...), so writing `apiModelId` is ignored there. Use the + // provider definition's field, and keep `apiModelId` for a provider without + // one (for example the custom provider). + const modelIdKey = providerDefinitionList.find( + (definition) => definition.apiProvider === base.apiProvider, + )?.modelIdKey + + return modelIdKey ? { ...base, [modelIdKey]: override } : { ...base, apiModelId: override } +} + +function extractPath(params: Record): string | undefined { + const candidate = params.path ?? params.file_path + return typeof candidate === "string" && candidate.length > 0 ? candidate : undefined +} + +/** + * Executes one headless subagent run. + * + * The runner owns the child `Task` lifetime: it creates the isolated + * workspace (when requested), installs the non-interactive ask policy, tracks + * progress for the live card, and converts the run into a single + * `SubagentToolOutcome` for the parent. + */ +export class SubagentRunner { + private task?: Task + private cancelled = false + private toolCallCount = 0 + private readonly filesRead = new Set() + private readonly filesModified = new Set() + private startedAt = Date.now() + private lastAction?: string + private readonly activity: SubagentToolActivity[] = [] + + constructor(private readonly options: RunSubagentOptions) {} + + requestCancel(): void { + this.cancelled = true + void this.task?.abortTask(true).catch(() => { + // Abort is best-effort; the promise settlement below owns the outcome. + }) + } + + async run(): Promise { + const { provider, parentTask, definition, request, runId, log } = this.options + const isolation = request.isolation ?? definition.isolation ?? "none" + let worktreePath: string | undefined + let worktree: SubagentToolOutcome["worktree"] + + try { + if (isolation === "worktree") { + const candidate = path.join(os.tmpdir(), "zoo-subagent-worktrees", runId) + worktreePath = await createSubagentWorktree({ + repoPath: parentTask.cwd, + worktreePath: candidate, + log, + }) + + // A writable run must not fall back to the shared workspace: the + // manager holds no write lock for a run that asked for a worktree. + // Stop instead of writing there without serialization. + if (!worktreePath && definition.readonly !== true) { + throw new Error("Worktree isolation was requested, but the worktree could not be created.") + } + } + + const context: SubagentTaskContext = { + runId, + groupId: this.options.groupId, + definition, + onToolUse: (toolName, params) => this.handleToolUse(toolName, params), + onAsk: (type) => this.answerAsk(type), + } + + const task = new Task({ + provider, + apiConfiguration: resolveModelConfiguration( + parentTask.apiConfiguration, + request.model ?? definition.model, + ), + // A headless run must not create checkpoints for a workspace the + // user is not looking at, and must not add itself to the task stack. + enableCheckpoints: false, + consecutiveMistakeLimit: parentTask.apiConfiguration.consecutiveMistakeLimit, + toolRepetitionSoftLimit: parentTask.apiConfiguration.toolRepetitionSoftLimit, + task: request.prompt, + images: [], + startTask: false, + taskId: runId, + initialStatus: "active", + workspacePath: worktreePath ?? parentTask.cwd, + parentTaskId: parentTask.taskId, + subagent: context, + maxTurns: this.options.maxTurns, + }) + + this.task = task + + if (this.cancelled) { + await task.abortTask(true).catch(() => {}) + } + + try { + await task.run() + } catch (error) { + log?.(`[subagent] ${runId} ended with an error: ${(error as Error).message}`) + } + + const status = this.cancelled ? "cancelled" : task.subagentStopRequested ? "completed" : "failed" + + const error = + status === "failed" + ? (task.subagentTerminalError ?? + (task.subagentPartial + ? `Reached maxTurns (${this.options.maxTurns}) without attempt_completion` + : "The subagent stopped before calling attempt_completion")) + : undefined + + if (worktreePath) { + worktree = await finalizeSubagentWorktree({ + repoPath: parentTask.cwd, + worktreePath, + log, + }) + } + + const tokenUsage = task.getTokenUsage() + const summary = task.subagentSummary ?? "" + const partial = task.subagentPartial || undefined + const transcriptPath = await getTaskDirectoryPath(provider.context.globalStorageUri.fsPath, runId).then( + (directory) => path.join(directory, "api_conversation_history.json"), + ) + + // The child owns file watchers and context trackers; a headless run is + // never reopened, so they must be released or every spawn keeps them + // registered for the life of the extension host. + await this.disposeChild() + + return { + runId, + agentName: definition.name, + status, + summary, + error, + partial, + filesRead: [...this.filesRead], + filesModified: [...this.filesModified], + durationMs: Date.now() - this.startedAt, + toolCallCount: this.toolCallCount, + tokenUsage: { input: tokenUsage.totalTokensIn ?? 0, output: tokenUsage.totalTokensOut ?? 0 }, + transcriptPath, + worktree, + } + } catch (error) { + if (worktreePath && !worktree) { + worktree = await finalizeSubagentWorktree({ + repoPath: parentTask.cwd, + worktreePath, + log, + }).catch(() => undefined) + } + + // A failed run ends too, so its child is released here as well. + // `disposeChild` is idempotent for a run that already disposed. + await this.disposeChild() + + return { + runId, + agentName: definition.name, + status: this.cancelled ? "cancelled" : "failed", + summary: this.task?.subagentSummary ?? "", + error: this.task?.subagentTerminalError ?? (error instanceof Error ? error.message : String(error)), + filesRead: [...this.filesRead], + filesModified: [...this.filesModified], + durationMs: Date.now() - this.startedAt, + toolCallCount: this.toolCallCount, + tokenUsage: { input: 0, output: 0 }, + worktree, + } + } + } + + /** + * Releases the child task's resources. Idempotent (`Task#dispose` keeps one + * promise), so the cancel path's `abortTask` and this call cannot double-free. + */ + private async disposeChild(): Promise { + const task = this.task + + if (!task) { + return + } + + try { + await task.dispose() + } catch (error) { + this.options.log?.( + `[subagent] ${this.options.runId} failed to dispose its task: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + } + } + + private handleToolUse(toolName: string, params: Record): void { + this.toolCallCount++ + const filePath = extractPath(params) + + if (filePath && READ_TOOLS.has(toolName)) { + this.filesRead.add(filePath) + } + + if (filePath && WRITE_TOOLS.has(toolName)) { + this.filesModified.add(filePath) + } + + this.lastAction = describeAction(toolName, params, filePath) + + this.activity.push({ + id: this.toolCallCount, + tool: toolName, + labelKey: SUBAGENT_ACTION_LABEL_KEYS[toolName], + path: filePath, + ts: Date.now(), + }) + if (this.activity.length > MAX_ACTIVITY) { + this.activity.splice(0, this.activity.length - MAX_ACTIVITY) + } + + this.options.onProgress({ + currentAction: this.lastAction, + activity: this.activity, + toolCallCount: this.toolCallCount, + filesRead: [...this.filesRead], + filesModified: [...this.filesModified], + }) + } + + /** + * Non-interactive policy for asks that carry no approval: the run never waits + * on a human. Completion is accepted immediately and ends the child turn loop + * via `subagentStopRequested` in `Task#ask`. Gated action asks (command, tool, + * use_mcp_server, protected) never reach here; `Task#ask` resolves them + * through `checkAutoApproval` and denies whatever policy does not approve. + */ + private answerAsk(type: ClineAsk): SubagentAskResult { + if (type === "followup") { + return { + response: "messageResponse", + text: "You cannot ask questions. Continue using your best assumption and state it in the final report.", + } + } + + return { response: "yesButtonClicked" } + } +} + +function describeAction(toolName: string, params: Record, filePath?: string): string { + switch (toolName) { + case "read_file": + return filePath ? `Reading ${filePath}` : "Reading a file" + case "search_files": + return typeof params.regex === "string" ? `Searching for ${params.regex}` : "Searching files" + case "list_files": + return filePath ? `Listing ${filePath}` : "Listing files" + case "codebase_search": + return typeof params.query === "string" + ? `Searching the codebase for ${params.query}` + : "Searching the codebase" + case "execute_command": + return typeof params.command === "string" ? `Running ${params.command}` : "Running a command" + case "write_to_file": + return filePath ? `Writing ${filePath}` : "Writing a file" + case "apply_diff": + case "edit": + case "search_and_replace": + case "edit_file": + case "apply_patch": + return filePath ? `Editing ${filePath}` : "Editing files" + case "attempt_completion": + return "Writing the final report" + default: + return `Using ${toolName}` + } +} diff --git a/src/core/subagents/__tests__/SubagentManager.spec.ts b/src/core/subagents/__tests__/SubagentManager.spec.ts new file mode 100644 index 00000000000..f51b46d9d18 --- /dev/null +++ b/src/core/subagents/__tests__/SubagentManager.spec.ts @@ -0,0 +1,490 @@ +// npx vitest run core/subagents/__tests__/SubagentManager.spec.ts + +import type { SubagentDefinition } from "@roo-code/types" + +import { makeExtensionContext, makeUri } from "../../../test-utils/vscode" +import type { Task } from "../../task/Task" +import type { ClineProvider } from "../../webview/ClineProvider" +import { SubagentManager } from "../SubagentManager" +import type { RunSubagentOptions, SubagentRunner } from "../SubagentRunner" +import type { SubagentSpawnRequest, SubagentToolOutcome } from "../types" + +interface FakeRun { + options: RunSubagentOptions + cancelCount: number + promise: Promise + resolve: (outcome: SubagentToolOutcome) => void + reject: (error: Error) => void +} + +function makeRunnerFactory() { + const runs: FakeRun[] = [] + + const createRunner = (options: RunSubagentOptions): SubagentRunner => { + let resolveRun!: (outcome: SubagentToolOutcome) => void + let rejectRun!: (error: Error) => void + const promise = new Promise((resolve, reject) => { + resolveRun = resolve + rejectRun = reject + }) + + const run: FakeRun = { options, cancelCount: 0, promise, resolve: resolveRun, reject: rejectRun } + runs.push(run) + + // The manager only calls these two members on a runner. + return { + requestCancel: () => { + run.cancelCount++ + }, + run: () => promise, + } as unknown as SubagentRunner + } + + return { runs, createRunner } +} + +function makeProvider(state: Record = {}) { + return { + context: makeExtensionContext({ globalStorageUri: makeUri("/mock/global-storage") }), + log: vi.fn(), + getState: vi.fn(async () => ({ maxConcurrentSubagents: 2, defaultSubagentMaxTurns: 5, ...state })), + postMessageToWebview: vi.fn(async (_message: unknown) => undefined), + taskHistoryStore: { + get: vi.fn((taskId: string): { id: string } | undefined => ({ id: taskId })), + atomicReadAndUpdate: vi.fn(async () => undefined), + }, + } +} + +function makeParentTask() { + return { + taskId: "parent-1", + cwd: "/workspace", + updateSubagentGroupMessage: vi.fn(async () => undefined), + } +} + +const definition = (overrides: Partial = {}): SubagentDefinition => ({ + name: "explore", + description: "Explores", + systemPrompt: "Explore.", + source: "builtin", + readonly: true, + ...overrides, +}) + +const outcome = (runId: string, overrides: Partial = {}): SubagentToolOutcome => ({ + runId, + agentName: "explore", + status: "completed", + summary: `${runId} summary`, + filesRead: [], + filesModified: [], + toolCallCount: 0, + tokenUsage: { input: 0, output: 0 }, + ...overrides, +}) + +async function flush(times = 4): Promise { + for (let index = 0; index < times; index++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } +} + +describe("SubagentManager", () => { + let provider: ReturnType + let parentTask: ReturnType + let factory: ReturnType + let manager: SubagentManager + let runCounter: number + + const spawn = ( + overrides: { + definition?: SubagentDefinition + runId?: string + groupId?: string + request?: Partial + } = {}, + ) => { + const runId = overrides.runId ?? `run-${++runCounter}` + + return manager.spawn({ + parentTask: parentTask as unknown as Task, + definition: overrides.definition ?? definition(), + request: { agent: "explore", description: runId, prompt: "Investigate", ...overrides.request }, + runId, + groupId: overrides.groupId ?? "group-1", + toolUseId: runId, + }) + } + + const createManager = (state: Record = {}) => { + provider = makeProvider(state) + factory = makeRunnerFactory() + manager = new SubagentManager({ + provider: provider as unknown as ClineProvider, + createRunner: factory.createRunner, + log: provider.log, + }) + } + + beforeEach(() => { + runCounter = 0 + parentTask = makeParentTask() + createManager() + }) + + afterEach(() => { + manager.dispose() + }) + + it("starts readonly runs in parallel up to the concurrency limit", async () => { + const first = spawn() + const second = spawn() + + await flush() + + expect(factory.runs).toHaveLength(2) + factory.runs[0].resolve(outcome("run-1")) + factory.runs[1].resolve(outcome("run-2")) + + await expect(Promise.all([first, second])).resolves.toEqual([ + expect.objectContaining({ runId: "run-1", status: "completed" }), + expect.objectContaining({ runId: "run-2", status: "completed" }), + ]) + }) + + it("rejects a second run that reuses a run id", async () => { + const first = spawn({ runId: "run-dup" }) + await flush() + + await expect(spawn({ runId: "run-dup" })).rejects.toThrow("Duplicate subagent run id: run-dup") + expect(factory.runs).toHaveLength(1) + + factory.runs[0].resolve(outcome("run-dup")) + await expect(first).resolves.toEqual(expect.objectContaining({ runId: "run-dup", status: "completed" })) + }) + + it("queues runs beyond the configured limit", async () => { + createManager({ maxConcurrentSubagents: 2 }) + + const first = spawn() + spawn() + const third = spawn() + + await flush() + expect(factory.runs).toHaveLength(2) + + factory.runs[0].resolve(outcome("run-1")) + await first + await flush() + + expect(factory.runs).toHaveLength(3) + factory.runs[1].resolve(outcome("run-2")) + factory.runs[2].resolve(outcome("run-3")) + await third + }) + + it("releases only one queued run per freed slot", async () => { + createManager({ maxConcurrentSubagents: 1 }) + + const runs = [spawn(), spawn(), spawn(), spawn()] + await flush() + expect(factory.runs).toHaveLength(1) + + factory.runs[0].resolve(outcome("run-1")) + await runs[0] + await flush() + expect(factory.runs).toHaveLength(2) + + factory.runs[1].resolve(outcome("run-2")) + await runs[1] + await flush() + expect(factory.runs).toHaveLength(3) + + factory.runs[2].resolve(outcome("run-3")) + await runs[2] + factory.runs[3].resolve(outcome("run-4")) + await runs[3] + }) + + it("serializes writers behind a single write lock", async () => { + const writer = definition({ name: "general", readonly: false }) + + const first = spawn({ definition: writer }) + spawn({ definition: writer }) + + await flush() + expect(factory.runs).toHaveLength(1) + + factory.runs[0].resolve(outcome("run-1")) + await first + await flush() + + expect(factory.runs).toHaveLength(2) + factory.runs[1].resolve(outcome("run-2")) + }) + + it("settles a cancelled queued run without waiting for a slot", async () => { + createManager({ maxConcurrentSubagents: 1 }) + + const first = spawn() + const queued = spawn() + + await flush() + expect(factory.runs).toHaveLength(1) + + expect(manager.cancel("run-2")).toBe(true) + await expect(queued).resolves.toMatchObject({ runId: "run-2", status: "cancelled" }) + expect(factory.runs).toHaveLength(1) + + manager.cancel("run-1") + factory.runs[0].resolve(outcome("run-1", { status: "cancelled" })) + await first + }) + + it("cancels a running run through its runner", async () => { + const running = spawn() + await flush() + + expect(manager.cancel("run-1")).toBe(true) + expect(factory.runs[0].cancelCount).toBe(1) + + factory.runs[0].resolve(outcome("run-1", { status: "cancelled" })) + await expect(running).resolves.toMatchObject({ status: "cancelled" }) + }) + + it("cancels every run of the parent task and persists them as cancelled", async () => { + createManager({ maxConcurrentSubagents: 1 }) + + const running = spawn() + const queued = spawn() + await flush() + + const cancelling = manager.cancelAllForParent("parent-1") + await flush() + + expect(factory.runs[0].cancelCount).toBe(1) + await expect(queued).resolves.toMatchObject({ status: "cancelled" }) + + // The group is not finalized while the cancelled child still winds down: + // its last save must land before the parent turns the snapshot terminal. + expect(parentTask.updateSubagentGroupMessage).not.toHaveBeenCalled() + + factory.runs[0].resolve(outcome("run-1", { status: "cancelled" })) + await cancelling + + // The group is finalized so a re-rendered chat shows cancelled runs + // instead of a stale "running" snapshot. + expect(parentTask.updateSubagentGroupMessage).toHaveBeenCalledWith("group-1", [ + expect.objectContaining({ runId: "run-1", status: "cancelled" }), + expect.objectContaining({ runId: "run-2", status: "cancelled" }), + ]) + + await running + }) + + it("waits for a run cancelled earlier before it finalizes the parent", async () => { + const running = spawn() + await flush() + + // The live card's cancel arrives before the parent is deleted, so the + // run is already terminal when cancelAllForParent looks at it. + expect(manager.cancel("run-1")).toBe(true) + expect(factory.runs[0].cancelCount).toBe(1) + + let settled = false + const cancelling = manager.cancelAllForParent("parent-1").then(() => { + settled = true + }) + await flush() + + // The child is still winding down: the barrier must wait for its + // settlement even though cancel() now reports it as already terminal. + expect(settled).toBe(false) + expect(parentTask.updateSubagentGroupMessage).not.toHaveBeenCalled() + + factory.runs[0].resolve(outcome("run-1", { status: "cancelled" })) + await cancelling + + expect(parentTask.updateSubagentGroupMessage).toHaveBeenCalledTimes(1) + await running + }) + + it("makes a concurrent finalizer wait for the in-flight finalization", async () => { + let releaseWrite!: () => void + parentTask.updateSubagentGroupMessage.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseWrite = () => resolve(undefined) + }), + ) + + const run = spawn() + await flush() + factory.runs[0].resolve(outcome("run-1")) + await run + + const first = manager.finalizeGroup("group-1") + await flush() + expect(parentTask.updateSubagentGroupMessage).toHaveBeenCalledTimes(1) + + // A second caller (a delete reaching the same group) must not return + // while the leader write is still in flight. + let secondSettled = false + const second = manager.finalizeGroup("group-1").then(() => { + secondSettled = true + }) + await flush() + expect(secondSettled).toBe(false) + expect(provider.taskHistoryStore.atomicReadAndUpdate).not.toHaveBeenCalled() + + releaseWrite() + await Promise.all([first, second]) + + expect(parentTask.updateSubagentGroupMessage).toHaveBeenCalledTimes(1) + expect(provider.taskHistoryStore.atomicReadAndUpdate).toHaveBeenCalledTimes(1) + }) + + it("logs a failed group snapshot write and still lands the history metadata", async () => { + parentTask.updateSubagentGroupMessage.mockRejectedValueOnce(new Error("disk full")) + + const run = spawn() + await flush() + factory.runs[0].resolve(outcome("run-1")) + await run + + await expect(manager.finalizeGroup("group-1")).resolves.toBeUndefined() + + expect(provider.log).toHaveBeenCalledWith(expect.stringContaining("disk full")) + expect(provider.taskHistoryStore.atomicReadAndUpdate).toHaveBeenCalledTimes(1) + }) + + it("finalizes the group once, writes the leader row and links history metadata", async () => { + const first = spawn() + const second = spawn() + await flush() + + factory.runs[0].resolve(outcome("run-1")) + factory.runs[1].resolve(outcome("run-2", { status: "failed", error: "boom" })) + await Promise.all([first, second]) + + await manager.finalizeGroup("group-1") + await flush() + + expect(parentTask.updateSubagentGroupMessage).toHaveBeenCalledTimes(1) + expect(parentTask.updateSubagentGroupMessage).toHaveBeenCalledWith("group-1", [ + expect.objectContaining({ runId: "run-1", status: "completed" }), + expect.objectContaining({ runId: "run-2", status: "failed" }), + ]) + + expect(provider.taskHistoryStore.atomicReadAndUpdate).toHaveBeenCalledTimes(2) + expect(provider.taskHistoryStore.atomicReadAndUpdate).toHaveBeenCalledWith("run-1", expect.any(Function)) + + await manager.finalizeGroup("group-1") + expect(parentTask.updateSubagentGroupMessage).toHaveBeenCalledTimes(1) + }) + + it("skips history metadata for a run that has no history row", async () => { + provider.taskHistoryStore.get.mockReturnValue(undefined) + + const run = spawn() + await flush() + factory.runs[0].resolve(outcome("run-1")) + await run + + await manager.finalizeGroup("group-1") + + expect(provider.taskHistoryStore.atomicReadAndUpdate).not.toHaveBeenCalled() + }) + + it("logs a failed history metadata write without failing the group", async () => { + provider.taskHistoryStore.atomicReadAndUpdate.mockRejectedValueOnce(new Error("store locked")) + + const run = spawn() + await flush() + factory.runs[0].resolve(outcome("run-1")) + await run + + await expect(manager.finalizeGroup("group-1")).resolves.toBeUndefined() + expect(provider.log).toHaveBeenCalledWith(expect.stringContaining("store locked")) + }) + + it("does not finalize a group while a run is still active", async () => { + const first = spawn() + await flush() + + await manager.finalizeGroup("group-1") + expect(parentTask.updateSubagentGroupMessage).not.toHaveBeenCalled() + + factory.runs[0].resolve(outcome("run-1")) + await first + }) + + it("uses the definition maxTurns over the setting and falls back to the setting", async () => { + createManager({ defaultSubagentMaxTurns: 9 }) + + spawn({ definition: definition({ maxTurns: 3 }) }) + spawn() + await flush() + + expect(factory.runs[0].options.maxTurns).toBe(3) + expect(factory.runs[1].options.maxTurns).toBe(9) + }) + + it("passes an unlimited (0) default maxTurns through to the runner", async () => { + createManager({ defaultSubagentMaxTurns: 0 }) + + spawn() + await flush() + + expect(factory.runs[0].options.maxTurns).toBe(0) + }) + + it("emits only subagentUpdate messages and never posts task state", async () => { + const run = spawn() + await flush() + factory.runs[0].resolve(outcome("run-1")) + await run + + await vi.waitFor(() => expect(provider.postMessageToWebview).toHaveBeenCalled()) + + for (const call of provider.postMessageToWebview.mock.calls) { + expect(call[0]).toMatchObject({ type: "subagentUpdate" }) + } + }) + + it("cancels active runs on dispose", async () => { + const run = spawn() + await flush() + + manager.dispose() + + expect(factory.runs[0].cancelCount).toBe(1) + factory.runs[0].resolve(outcome("run-1", { status: "cancelled" })) + await run + }) + + it("drops the group and run records for a deleted parent", async () => { + const run = spawn({ runId: "run-gone" }) + await flush() + + manager.clearStateForParent("parent-1") + + // The group is gone, so cancelling the run can no longer reach it and the + // runner is not asked to stop. + expect(manager.cancel("run-gone")).toBe(false) + expect(factory.runs[0].cancelCount).toBe(0) + + // Finalizing the removed group writes no history metadata and no leader + // message, so a deleted parent leaves nothing behind. + await manager.finalizeGroup("group-1") + expect(parentTask.updateSubagentGroupMessage).not.toHaveBeenCalled() + expect(provider.taskHistoryStore.atomicReadAndUpdate).not.toHaveBeenCalled() + + // The parent batch still settles: removal drops the record, not the + // promise it already handed to the caller. + factory.runs[0].resolve(outcome("run-gone")) + await expect(run).resolves.toMatchObject({ runId: "run-gone", status: "completed" }) + }) +}) diff --git a/src/core/subagents/__tests__/SubagentRegistry.errors.spec.ts b/src/core/subagents/__tests__/SubagentRegistry.errors.spec.ts new file mode 100644 index 00000000000..4a3cf73d13d --- /dev/null +++ b/src/core/subagents/__tests__/SubagentRegistry.errors.spec.ts @@ -0,0 +1,123 @@ +// npx vitest run core/subagents/__tests__/SubagentRegistry.errors.spec.ts + +import * as fs from "fs/promises" +import * as os from "os" +import * as path from "path" + +import { parseSubagentMarkdown, SubagentRegistry } from "../SubagentRegistry" + +async function makeTempRoot(): Promise { + return fs.mkdtemp(path.join(os.tmpdir(), "zoo-subagent-errors-")) +} + +async function writeAgent(root: string, relativePath: string, content: string): Promise { + const filePath = path.join(root, relativePath) + await fs.mkdir(path.dirname(filePath), { recursive: true }) + await fs.writeFile(filePath, content, "utf8") +} + +describe("parseSubagentMarkdown error paths", () => { + it("returns an error when the markdown frontmatter cannot be parsed", () => { + const result = parseSubagentMarkdown("---\n nope\n---\nbody", { + source: "project", + filePath: "/workspace/.zoo/agents/broken.md", + }) + + expect(result.definition).toBeUndefined() + expect(result.error).toContain("Invalid frontmatter") + }) + + it("returns an error when the frontmatter is present but the file body is empty", () => { + // The empty-prompt guard trips after the frontmatter parses. + const result = parseSubagentMarkdown("---\ndescription: x\n---\n ", { + source: "project", + filePath: "/workspace/.zoo/agents/empty.md", + }) + + expect(result.definition).toBeUndefined() + expect(result.error).toContain("empty system prompt") + }) + + it("skips an invalid frontmatter object that is undefined", () => { + const result = parseSubagentMarkdown("body only", { + source: "user", + filePath: "/home/u/.zoo/agents/plain.md", + }) + + expect(result.definition?.name).toBe("plain") + }) +}) + +describe("SubagentRegistry load error paths", () => { + let root: string + let cwd: string + let homeDir: string + + beforeEach(async () => { + root = await makeTempRoot() + cwd = path.join(root, "workspace") + homeDir = path.join(root, "home") + await fs.mkdir(cwd, { recursive: true }) + await fs.mkdir(homeDir, { recursive: true }) + }) + + afterEach(async () => { + await fs.rm(root, { recursive: true, force: true }) + }) + + it("warns and skips a file that cannot be read", async () => { + const warnings: string[] = [] + // A directory ends with .md but readFile rejects on it. + await fs.mkdir(path.join(cwd, ".zoo", "agents", "opaque.md"), { recursive: true }) + + const registry = new SubagentRegistry({ + cwd, + homeDir, + watch: false, + onWarning: (message) => warnings.push(message), + }) + await registry.load() + + expect(registry.has("opaque")).toBe(false) + expect(warnings.some((message) => message.includes("Failed to read agent file"))).toBe(true) + registry.dispose() + }) + + it("warns when a definition overrides a non-builtin agent", async () => { + const warnings: string[] = [] + await writeAgent(homeDir, ".zoo/agents/explore.md", "---\ndescription: user explore\n---\nuser prompt") + // The same name appears again via a higher-precedence location. + await writeAgent(cwd, ".claude/agents/explore.md", "---\ndescription: claude explore\n---\nclaude prompt") + + const registry = new SubagentRegistry({ + cwd, + homeDir, + watch: false, + onWarning: (message) => warnings.push(message), + }) + await registry.load() + + expect(registry.get("explore")?.description).toBe("claude explore") + expect(warnings.some((message) => message.includes("overrides an existing definition"))).toBe(true) + registry.dispose() + }) + + it("warns and skips a file with invalid schema but keeps valid ones", async () => { + const warnings: string[] = [] + await writeAgent(cwd, ".zoo/agents/bad.md", "---\ndescription: bad\nreadonly: yep\n---\nbody") + await writeAgent(cwd, ".zoo/agents/good.md", "---\ndescription: good\n---\ngood prompt") + + const registry = new SubagentRegistry({ + cwd, + homeDir, + watch: false, + onWarning: (message) => warnings.push(message), + }) + await registry.load() + + expect(registry.has("good")).toBe(true) + expect(registry.has("bad")).toBe(false) + expect(warnings.some((message) => message.includes("Invalid"))).toBe(true) + registry.dispose() + }) +}) diff --git a/src/core/subagents/__tests__/SubagentRegistry.spec.ts b/src/core/subagents/__tests__/SubagentRegistry.spec.ts new file mode 100644 index 00000000000..0cbc4f0a5a4 --- /dev/null +++ b/src/core/subagents/__tests__/SubagentRegistry.spec.ts @@ -0,0 +1,194 @@ +// npx vitest run core/subagents/__tests__/SubagentRegistry.spec.ts + +import * as fs from "fs/promises" +import * as os from "os" +import * as path from "path" + +import { getBuiltinSubagents, parseSubagentMarkdown, SubagentRegistry } from "../SubagentRegistry" + +async function makeTempRoot(): Promise { + return fs.mkdtemp(path.join(os.tmpdir(), "zoo-subagent-registry-")) +} + +async function writeAgent(root: string, relativePath: string, content: string): Promise { + const filePath = path.join(root, relativePath) + await fs.mkdir(path.dirname(filePath), { recursive: true }) + await fs.writeFile(filePath, content, "utf8") +} + +describe("parseSubagentMarkdown", () => { + it("reads frontmatter metadata and the body as the system prompt", () => { + const result = parseSubagentMarkdown( + [ + "---", + "name: reviewer", + "description: Reviews changes", + "tools: read_file, search_files", + "readonly: true", + "maxTurns: 7", + "---", + "You review code.", + ].join("\n"), + { source: "project", filePath: "/workspace/.zoo/agents/reviewer.md" }, + ) + + expect(result.error).toBeUndefined() + expect(result.definition).toMatchObject({ + name: "reviewer", + description: "Reviews changes", + systemPrompt: "You review code.", + tools: ["read_file", "search_files"], + readonly: true, + maxTurns: 7, + source: "project", + }) + }) + + it("derives the name from the file name when frontmatter has none", () => { + const result = parseSubagentMarkdown("Inspect the module.", { + source: "user", + filePath: "/home/user/.zoo/agents/scout.md", + }) + + expect(result.definition?.name).toBe("scout") + expect(result.definition?.description).toContain("scout.md") + expect(result.definition?.systemPrompt).toBe("Inspect the module.") + }) + + it("rejects an empty system prompt", () => { + const result = parseSubagentMarkdown("---\nname: empty\n---\n ", { + source: "project", + filePath: "/workspace/.zoo/agents/empty.md", + }) + + expect(result.definition).toBeUndefined() + expect(result.error).toContain("empty system prompt") + }) + + it("rejects invalid frontmatter without throwing", () => { + const result = parseSubagentMarkdown("---\nmaxTurns: 0\n---\nbody", { + source: "project", + filePath: "/workspace/.zoo/agents/bad.md", + }) + + expect(result.definition).toBeUndefined() + expect(result.error).toContain("Invalid frontmatter") + }) + + it("rejects executable frontmatter without evaluating it", async () => { + const marker = path.join(await makeTempRoot(), "executed") + const raw = [ + "---javascript", + `require("fs").writeFileSync(${JSON.stringify(marker)}, "executed")`, + "---", + "Body", + ].join("\n") + + const result = parseSubagentMarkdown(raw, { + source: "project", + filePath: "/workspace/.zoo/agents/evil.md", + }) + + expect(result.error).toContain("Executable frontmatter is not allowed") + await expect(fs.access(marker)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("rejects the js alias of executable frontmatter", () => { + const result = parseSubagentMarkdown("---JS\n({})\n---\nBody", { + source: "project", + filePath: "/workspace/.zoo/agents/evil.md", + }) + + expect(result.error).toContain("Executable frontmatter is not allowed") + }) +}) + +describe("SubagentRegistry", () => { + let root: string + let cwd: string + let homeDir: string + + beforeEach(async () => { + root = await makeTempRoot() + cwd = path.join(root, "workspace") + homeDir = path.join(root, "home") + await fs.mkdir(cwd, { recursive: true }) + await fs.mkdir(homeDir, { recursive: true }) + }) + + afterEach(async () => { + await fs.rm(root, { recursive: true, force: true }) + }) + + it("loads the builtin agents when no agent directories exist", async () => { + const registry = new SubagentRegistry({ cwd, homeDir, watch: false }) + await registry.load() + + expect(registry.getAll().map((definition) => definition.name)).toEqual(["explore", "general", "reviewer"]) + expect(registry.getCatalog()).toEqual( + expect.arrayContaining([{ name: "explore", description: expect.any(String) }]), + ) + registry.dispose() + }) + + it("applies project > .claude > user > builtin precedence by agent name", async () => { + await writeAgent(cwd, ".zoo/agents/explore.md", "---\ndescription: project explore\n---\nproject prompt") + await writeAgent(cwd, ".claude/agents/helper.md", "---\ndescription: claude helper\n---\nclaude prompt") + await writeAgent(homeDir, ".zoo/agents/explore.md", "---\ndescription: user explore\n---\nuser prompt") + await writeAgent(homeDir, ".zoo/agents/personal.md", "---\ndescription: personal\n---\npersonal prompt") + + const registry = new SubagentRegistry({ cwd, homeDir, watch: false }) + await registry.load() + + expect(registry.get("explore")?.description).toBe("project explore") + expect(registry.get("explore")?.systemPrompt).toBe("project prompt") + expect(registry.get("helper")?.description).toBe("claude helper") + expect(registry.get("personal")?.source).toBe("user") + registry.dispose() + }) + + it("skips a broken file, warns, and still loads the rest", async () => { + const warnings: string[] = [] + await writeAgent(cwd, ".zoo/agents/broken.md", "---\nmaxTurns: nope\n---\nbody") + await writeAgent(cwd, ".zoo/agents/good.md", "---\ndescription: good\n---\ngood prompt") + + const registry = new SubagentRegistry({ + cwd, + homeDir, + watch: false, + onWarning: (message) => warnings.push(message), + }) + await registry.load() + + expect(registry.has("good")).toBe(true) + expect(registry.has("broken")).toBe(false) + expect(warnings.some((message) => message.includes("broken.md"))).toBe(true) + registry.dispose() + }) + + it("ignores files that are not markdown", async () => { + await writeAgent(cwd, ".zoo/agents/notes.txt", "not an agent") + const registry = new SubagentRegistry({ cwd, homeDir, watch: false }) + await registry.load() + + expect(registry.has("notes")).toBe(false) + registry.dispose() + }) + + it("ships builtins with a read-only class for explore and reviewer", () => { + const builtins = new Map(getBuiltinSubagents().map((definition) => [definition.name, definition])) + + expect(builtins.get("explore")?.readonly).toBe(true) + expect(builtins.get("reviewer")?.readonly).toBe(true) + expect(builtins.get("general")?.readonly).toBe(false) + }) + + it("leaves the turn limit of every built-in to the saved default", () => { + // A fixed limit on a builtin would hide the user's setting from that agent. + expect(getBuiltinSubagents().map((definition) => definition.maxTurns)).toEqual([ + undefined, + undefined, + undefined, + ]) + }) +}) diff --git a/src/core/subagents/__tests__/SubagentRunner.spec.ts b/src/core/subagents/__tests__/SubagentRunner.spec.ts new file mode 100644 index 00000000000..d7b9773acbb --- /dev/null +++ b/src/core/subagents/__tests__/SubagentRunner.spec.ts @@ -0,0 +1,495 @@ +// npx vitest run core/subagents/__tests__/SubagentRunner.spec.ts + +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" + +import type { SubagentDefinition } from "@roo-code/types" +import { SubagentRunner, type RunSubagentOptions } from "../SubagentRunner" +import type { SubagentSpawnRequest, SubagentTaskContext } from "../types" + +vi.mock("../../../utils/storage", () => ({ + getTaskDirectoryPath: vi.fn(async () => "/global-storage/run-1"), +})) + +// Holds a reference to the last mock Task instance the runner built. +type MockTaskInstance = { + run: ReturnType + abortTask: ReturnType + dispose: ReturnType + getTokenUsage: () => { totalTokensIn: number; totalTokensOut: number } + subagentStopRequested: boolean + subagentPartial: boolean + subagentTerminalError?: string + subagentSummary?: string + subagent?: SubagentTaskContext + context?: SubagentTaskContext + apiConfiguration?: Record + workspacePath?: string + maxTurns?: number +} +let lastTask: MockTaskInstance +// Set before runner.run() so the mock task's run() can reject on the first call. +let runRejectsWith: Error | undefined + +vi.mock("../../task/Task", () => { + const Task = class { + subagent?: SubagentTaskContext + subagentStopRequested = false + subagentPartial = false + subagentTerminalError?: string + subagentSummary?: string + apiConfiguration?: Record + workspacePath?: string + maxTurns?: number + run = vi.fn(() => (runRejectsWith ? Promise.reject(runRejectsWith) : Promise.resolve(undefined))) + abortTask = vi.fn(async () => undefined) + dispose = vi.fn(async () => undefined) + getTokenUsage = () => ({ totalTokensIn: 12, totalTokensOut: 3 }) + + constructor(options: { + subagent?: SubagentTaskContext + apiConfiguration?: Record + workspacePath?: string + maxTurns?: number + }) { + this.subagent = options.subagent + this.apiConfiguration = options.apiConfiguration + this.workspacePath = options.workspacePath + this.maxTurns = options.maxTurns + lastTask = this as unknown as MockTaskInstance + } + } + return { Task } +}) + +vi.mock("../worktree", () => ({ + createSubagentWorktree: vi.fn(async () => "/worktrees/run-1"), + finalizeSubagentWorktree: vi.fn(async () => ({ + path: "/worktrees/run-1", + kept: false, + filesChanged: 0, + })), +})) + +import { createSubagentWorktree, finalizeSubagentWorktree } from "../worktree" +import { formatSubagentOutcome } from "../formatSubagentResult" + +const createWorktreeMock = vi.mocked(createSubagentWorktree) +const finalizeWorktreeMock = vi.mocked(finalizeSubagentWorktree) + +const definition: SubagentDefinition = { + name: "explore", + description: "Explores", + systemPrompt: "Explore.", + source: "builtin", + readonly: true, +} + +function makeParentTask() { + return { + cwd: "/workspace", + taskId: "parent-1", + apiConfiguration: { + apiProvider: providerIdentifiers.anthropic, + apiKey: "test-key", + consecutiveMistakeLimit: 3, + toolRepetitionSoftLimit: 2, + }, + } +} + +function makeProvider() { + return { + context: { globalStorageUri: { fsPath: "/global-storage" } }, + } +} + +function makeOptions(overrides: Partial = {}): RunSubagentOptions { + return { + provider: makeProvider() as never, + parentTask: makeParentTask() as never, + definition, + request: { + agent: "explore", + description: "run-1", + prompt: "Investigate", + isolation: "none", + } as SubagentSpawnRequest, + runId: "run-1", + groupId: "group-1", + toolUseId: "tool-1", + maxTurns: 5, + onProgress: vi.fn(), + log: vi.fn(), + ...overrides, + } +} + +describe("SubagentRunner", () => { + beforeEach(() => { + lastTask = undefined as unknown as MockTaskInstance + runRejectsWith = undefined + createWorktreeMock.mockReset() + finalizeWorktreeMock.mockReset() + createWorktreeMock.mockResolvedValue("/worktrees/run-1" as never) + finalizeWorktreeMock.mockResolvedValue({ path: "/worktrees/run-1", kept: false, filesChanged: 0 } as never) + }) + + it("runs a subagent and returns a completed outcome", async () => { + const onProgress = vi.fn() + const runner = new SubagentRunner(makeOptions({ onProgress })) + + const promise = runner.run() + expect(lastTask).toBeDefined() + + lastTask.subagentStopRequested = true + lastTask.subagentSummary = "Found it" + const outcome = await promise + + expect(outcome).toMatchObject({ + runId: "run-1", + agentName: "explore", + status: "completed", + summary: "Found it", + toolCallCount: 0, + tokenUsage: { input: 12, output: 3 }, + }) + expect(lastTask.run).toHaveBeenCalledTimes(1) + }) + + it("releases the child task after a completed run", async () => { + const runner = new SubagentRunner(makeOptions()) + const promise = runner.run() + + // The outcome must be captured before disposal clears the child's state. + lastTask.subagentStopRequested = true + lastTask.subagentSummary = "Found it" + const outcome = await promise + + expect(lastTask.dispose).toHaveBeenCalledTimes(1) + expect(outcome).toMatchObject({ status: "completed", summary: "Found it" }) + }) + + it("releases the child task when the run fails", async () => { + runRejectsWith = new Error("api down") + const runner = new SubagentRunner(makeOptions()) + const promise = runner.run() + + lastTask.subagentStopRequested = false + await promise + + expect(lastTask.dispose).toHaveBeenCalledTimes(1) + }) + + it("reports a failed outcome when the task stops without completion", async () => { + const runner = new SubagentRunner(makeOptions()) + const promise = runner.run() + + lastTask.subagentStopRequested = false + const outcome = await promise + + expect(outcome.status).toBe("failed") + expect(outcome.error).toContain("stopped before calling attempt_completion") + }) + + it("reports a terminal ask as the failure reason", async () => { + const runner = new SubagentRunner(makeOptions()) + const promise = runner.run() + + lastTask.subagentTerminalError = "The subagent stopped after reaching its consecutive mistake limit" + const outcome = await promise + + expect(outcome).toMatchObject({ + status: "failed", + error: "The subagent stopped after reaching its consecutive mistake limit", + }) + }) + + it("reports a partial failed outcome at maxTurns", async () => { + const runner = new SubagentRunner(makeOptions()) + const promise = runner.run() + + lastTask.subagentStopRequested = false + lastTask.subagentPartial = true + const outcome = await promise + + expect(outcome.status).toBe("failed") + expect(outcome.partial).toBe(true) + expect(outcome.error).toContain("Reached maxTurns (5)") + }) + + it("marks a run cancelled when requestCancel was called before completion", async () => { + const runner = new SubagentRunner(makeOptions({ maxTurns: 0 })) + const promise = runner.run() + + lastTask.subagentStopRequested = false + runner.requestCancel() + expect(lastTask.abortTask).toHaveBeenCalledWith(true) + + // requestCancel aborts the child; the run is then cancelled. + lastTask.run.mockResolvedValueOnce(undefined) + const outcome = await promise + expect(outcome.status).toBe("cancelled") + }) + + it("reports cancelled when requestCancel fires before the task is created", async () => { + const runner = new SubagentRunner(makeOptions()) + runner.requestCancel() + // The run has not been started, so no task exists yet and abort is + // skipped; the run still labels its outcome cancelled. + const outcome = await runner.run() + expect(outcome.status).toBe("cancelled") + }) + + it("creates a worktree when isolation is worktree", async () => { + const runner = new SubagentRunner( + makeOptions({ request: { agent: "explore", description: "run-1", prompt: "x", isolation: "worktree" } }), + ) + const promise = runner.run() + + expect(createWorktreeMock).toHaveBeenCalledWith({ + repoPath: "/workspace", + worktreePath: expect.stringContaining("run-1"), + log: expect.any(Function), + }) + + await vi.waitFor(() => expect(lastTask).toBeDefined()) + lastTask.subagentStopRequested = true + + const outcome = await promise + expect(finalizeWorktreeMock).toHaveBeenCalledWith({ + repoPath: "/workspace", + worktreePath: "/worktrees/run-1", + log: expect.any(Function), + }) + expect(outcome.worktree).toEqual({ path: "/worktrees/run-1", kept: false, filesChanged: 0 }) + }) + + it("fails a writable run when its worktree cannot be created", async () => { + createWorktreeMock.mockResolvedValueOnce(undefined as never) + lastTask = undefined as unknown as MockTaskInstance + const writable = { ...definition, readonly: false } + const runner = new SubagentRunner( + makeOptions({ + definition: writable, + request: { agent: "general", description: "run-1", prompt: "x", isolation: "worktree" }, + }), + ) + + const outcome = await runner.run() + + // No fallback to the shared workspace: the manager holds no write lock + // for a run that asked for a worktree. + expect(outcome.status).toBe("failed") + expect(outcome.error).toContain("worktree could not be created") + expect(lastTask).toBeUndefined() + }) + + it("keeps a read-only run on the parent workspace when its worktree fails", async () => { + createWorktreeMock.mockResolvedValueOnce(undefined as never) + const runner = new SubagentRunner( + makeOptions({ request: { agent: "explore", description: "run-1", prompt: "x", isolation: "worktree" } }), + ) + const outcome = await runner.run() + + // A read-only run writes nothing, so the shared workspace is safe and the + // run continues instead of failing on the missing worktree. + expect(lastTask.workspacePath).toBe("/workspace") + expect(outcome.error ?? "").not.toContain("worktree") + }) + + it("tracks read and write tool activity through the progress callback", async () => { + const onProgress = vi.fn() + const runner = new SubagentRunner(makeOptions({ onProgress })) + const promise = runner.run() + + const context = lastTask.subagent + expect(context).toBeDefined() + context!.onToolUse?.("read_file", { file_path: "/a.ts" }) + context!.onToolUse?.("write_to_file", { file_path: "/b.ts" }) + + expect(onProgress).toHaveBeenLastCalledWith( + expect.objectContaining({ + filesRead: ["/a.ts"], + filesModified: ["/b.ts"], + toolCallCount: 2, + }), + ) + + lastTask.subagentStopRequested = true + const outcome = await promise + expect(outcome.filesRead).toEqual(["/a.ts"]) + expect(outcome.filesModified).toEqual(["/b.ts"]) + expect(outcome.toolCallCount).toBe(2) + }) + + it("answers a followup ask with an instruction and other asks with yes", async () => { + const runner = new SubagentRunner(makeOptions()) + const promise = runner.run() + + const context = lastTask.subagent + const followup = context!.onAsk?.("followup" as never) + expect(followup).toMatchObject({ + response: "messageResponse", + text: expect.stringContaining("best assumption"), + }) + + const plan = context!.onAsk?.("planModeResponse" as never) + expect(plan).toEqual({ response: "yesButtonClicked" }) + + lastTask.subagentStopRequested = true + await promise + }) + + it("swallows a task run error and reports a failed outcome", async () => { + const log = vi.fn() + runRejectsWith = new Error("api down") + const runner = new SubagentRunner(makeOptions({ log })) + const promise = runner.run() + + lastTask.subagentStopRequested = false + const outcome = await promise + + // run() logs the error instead of rejecting; the run is failed because + // the child did not complete before stopping. + expect(log).toHaveBeenCalledWith(expect.stringContaining("ended with an error: api down")) + expect(outcome.status).toBe("failed") + expect(outcome.error).toContain("stopped before calling attempt_completion") + }) + + it("falls back to a failed outcome when resolution throws before a status", async () => { + const runner = new SubagentRunner(makeOptions()) + const promise = runner.run() + + // Make getTokenUsage throw during the resolution phase. + lastTask.getTokenUsage = (() => { + throw new Error("resolution broke") + }) as never + + await expect(promise).resolves.toMatchObject({ status: "failed", error: "resolution broke" }) + }) + + it("logs a readable formatted outcome", async () => { + const runner = new SubagentRunner(makeOptions()) + const promise = runner.run() + lastTask.subagentStopRequested = true + lastTask.subagentSummary = "done" + const outcome = await promise + + const text = formatSubagentOutcome(outcome) + expect(text).toContain('Subagent "explore" completed.') + expect(text).toContain("Summary:\ndone") + }) + + it("applies a model override to the child api configuration", async () => { + const runner = new SubagentRunner( + makeOptions({ + request: { + agent: "explore", + description: "run-1", + prompt: "x", + isolation: "none", + model: "claude-code", + }, + }), + ) + const promise = runner.run() + + expect(lastTask.apiConfiguration).toMatchObject({ + apiProvider: providerIdentifiers.anthropic, + apiModelId: "claude-code", + }) + expect(lastTask.workspacePath).toBe("/workspace") + + lastTask.subagentStopRequested = true + await promise + }) + + it("writes a model override to the provider's own model field", async () => { + const parentTask = { + ...makeParentTask(), + apiConfiguration: { + apiProvider: providerIdentifiers.openrouter, + openRouterApiKey: "test-key", + openRouterModelId: "old-model", + }, + } + const runner = new SubagentRunner( + makeOptions({ + parentTask: parentTask as never, + request: { + agent: "explore", + description: "run-1", + prompt: "x", + isolation: "none", + model: "new-model", + }, + }), + ) + const promise = runner.run() + + expect(lastTask.apiConfiguration).toMatchObject({ + apiProvider: providerIdentifiers.openrouter, + openRouterModelId: "new-model", + }) + expect(lastTask.apiConfiguration).not.toHaveProperty("apiModelId") + + lastTask.subagentStopRequested = true + await promise + }) + + it("cleans up the worktree when the finalize step throws", async () => { + finalizeWorktreeMock.mockRejectedValue(new Error("busy")) + const runner = new SubagentRunner( + makeOptions({ request: { agent: "explore", description: "run-1", prompt: "x", isolation: "worktree" } }), + ) + const promise = runner.run() + await vi.waitFor(() => expect(lastTask).toBeDefined()) + + lastTask.subagentStopRequested = true + const outcome = await promise + + // The happy-path finalize rejects and the catch fallback retries it + // with a swallow guard, leaving outcome.worktree undefined. + expect(finalizeWorktreeMock).toHaveBeenCalledTimes(2) + expect(outcome.status).toBe("failed") + expect(outcome.worktree).toBeUndefined() + }) + + it("describes every tool action and caps the live activity feed", async () => { + const onProgress = vi.fn() + const runner = new SubagentRunner(makeOptions({ onProgress })) + const promise = runner.run() + + const context = lastTask.subagent + expect(context).toBeDefined() + + const calls: Array<[string, Record]> = [ + ["search_files", { regex: "zoo", path: "/a.ts" }], + ["search_files", { path: "/a.ts" }], + ["list_files", { path: "/src" }], + ["list_files", {}], + ["codebase_search", { query: "provider", path: "/" }], + ["execute_command", { command: "pnpm test" }], + ["write_to_file", { path: "/x.ts" }], + ["edit", { path: "/edit.ts" }], + ["attempt_completion", {}], + ["unbundled_tool", {}], + ] + for (const [tool, params] of calls) { + context!.onToolUse?.(tool, params) + } + + // Overflow MAX_ACTIVITY (50) so the trailing splice runs. + for (let i = 0; i < 55; i++) { + context!.onToolUse?.("read_file", { path: `/file-${i}.ts` }) + } + + const total = calls.length + 55 + lastTask.subagentStopRequested = true + const outcome = await promise + + expect(outcome.toolCallCount).toBe(total) + const lastPatch = onProgress.mock.calls.at(-1)?.[0] + expect(lastPatch?.activity.length).toBe(50) + }) +}) diff --git a/src/core/subagents/__tests__/SubagentTool.spec.ts b/src/core/subagents/__tests__/SubagentTool.spec.ts new file mode 100644 index 00000000000..bd3d5005c0a --- /dev/null +++ b/src/core/subagents/__tests__/SubagentTool.spec.ts @@ -0,0 +1,240 @@ +// npx vitest run core/subagents/__tests__/SubagentTool.spec.ts + +import type { SubagentDefinition } from "@roo-code/types" + +import type { ToolUse } from "../../../shared/tools" +import type { Task } from "../../task/Task" +import { subagentTool } from "../../tools/SubagentTool" +import type { SpawnSubagentParams, SubagentManager } from "../SubagentManager" +import type { SubagentRegistry } from "../SubagentRegistry" +import type { SubagentToolOutcome } from "../types" + +const definition: SubagentDefinition = { + name: "explore", + description: "Explores the codebase", + systemPrompt: "Explore.", + source: "builtin", + readonly: true, +} + +const spawnOutcome: SubagentToolOutcome = { + runId: "tool-1", + agentName: "explore", + status: "completed", + summary: "done", + filesRead: [], + filesModified: [], + toolCallCount: 0, + tokenUsage: { input: 0, output: 0 }, +} + +function makeHarness({ nested = false, enabled = true }: { nested?: boolean; enabled?: boolean } = {}) { + const manager = { spawn: vi.fn(async (_params: SpawnSubagentParams) => spawnOutcome) } + const registry = { + get: vi.fn((name: string) => (name === "explore" ? definition : undefined)), + getAll: vi.fn(() => [definition]), + } + const pushToolResult = vi.fn() + const handleError = vi.fn() + const say = vi.fn(async () => undefined) + const registerSubagentCall = vi.fn() + const sayAndCreateMissingParamError = vi.fn(async () => "missing parameter") + + // Mirrors `Task#getSubagentGroupId`: the first spawn of a turn names the group. + let groupId: string | undefined + + const task = { + subagent: nested ? { runId: "child", groupId: "group", definition } : undefined, + providerRef: { + deref: () => ({ + getSubagentManager: () => manager as unknown as SubagentManager, + getSubagentRegistry: () => registry as unknown as SubagentRegistry, + contextProxy: { getValue: vi.fn(() => enabled) }, + }), + }, + getSubagentGroupId: vi.fn((toolUseId: string) => (groupId ??= toolUseId)), + registerSubagentCall, + say, + consecutiveMistakeCount: 0, + recordToolError: vi.fn(), + sayAndCreateMissingParamError, + } as unknown as Task + + const block = (nativeArgs: Record, id = "tool-1"): ToolUse<"spawn_subagent"> => + ({ + type: "tool_use", + id, + name: "spawn_subagent", + params: {}, + partial: false, + nativeArgs, + }) as unknown as ToolUse<"spawn_subagent"> + + const callbacksFor = (toolCallId = "tool-1") => ({ + askApproval: vi.fn(async () => true), + handleError, + pushToolResult, + toolCallId, + }) + + const callbacks = callbacksFor() + + return { + manager, + registry, + task, + block, + callbacks, + callbacksFor, + pushToolResult, + registerSubagentCall, + say, + sayAndCreateMissingParamError, + } +} + +describe("SubagentTool", () => { + it("starts a run, registers the promise and shows the spawn row without a tool result", async () => { + const harness = makeHarness() + + await subagentTool.handle( + harness.task, + harness.block({ agent: "explore", description: "Find auth", prompt: "Locate auth" }), + harness.callbacks, + ) + + expect(harness.manager.spawn).toHaveBeenCalledWith({ + parentTask: harness.task, + definition, + request: { + agent: "explore", + description: "Find auth", + prompt: "Locate auth", + model: undefined, + isolation: undefined, + }, + runId: expect.stringMatching(/^tool-1-/), + groupId: expect.stringMatching(/^tool-1-/), + toolUseId: "tool-1", + }) + expect(harness.registerSubagentCall).toHaveBeenCalledWith("tool-1", expect.any(Promise)) + expect(harness.say).toHaveBeenCalledWith("tool", expect.stringContaining('"tool":"spawnSubagent"')) + expect(harness.pushToolResult).not.toHaveBeenCalled() + }) + + it("shows one group row for a parallel batch instead of a row per spawn", async () => { + const harness = makeHarness() + const args = { agent: "explore", description: "Find auth", prompt: "Locate auth" } + + await subagentTool.handle(harness.task, harness.block(args, "tool-1"), harness.callbacksFor("tool-1")) + await subagentTool.handle(harness.task, harness.block(args, "tool-2"), harness.callbacksFor("tool-2")) + + expect(harness.registerSubagentCall).toHaveBeenCalledTimes(2) + expect(harness.say).toHaveBeenCalledTimes(1) + expect(harness.manager.spawn).toHaveBeenLastCalledWith( + expect.objectContaining({ + runId: expect.stringMatching(/^tool-2-/), + groupId: expect.stringMatching(/^tool-1-/), + }), + ) + }) + + it("sanitizes the tool call id before using it as the run id", async () => { + const harness = makeHarness() + + await subagentTool.handle( + harness.task, + harness.block({ agent: "explore", description: "Find auth", prompt: "Locate auth" }, "tool:1"), + harness.callbacksFor("tool:1"), + ) + + expect(harness.manager.spawn).toHaveBeenCalledWith( + expect.objectContaining({ + runId: expect.stringMatching(/^tool_1-/), + groupId: expect.stringMatching(/^tool_1-/), + toolUseId: "tool:1", + }), + ) + }) + + it("mints a distinct run id when a provider reuses a tool call id", async () => { + const harness = makeHarness() + const args = { agent: "explore", description: "Find auth", prompt: "Locate auth" } + + // Native Ollama restarts its tool-call index on every request, so two + // spawns from different turns share one provider id. + await subagentTool.handle( + harness.task, + harness.block(args, "ollama-tool-0"), + harness.callbacksFor("ollama-tool-0"), + ) + await subagentTool.handle( + harness.task, + harness.block(args, "ollama-tool-0"), + harness.callbacksFor("ollama-tool-0"), + ) + + const first = harness.manager.spawn.mock.calls[0]?.[0] + const second = harness.manager.spawn.mock.calls[1]?.[0] + + expect(first?.runId).toMatch(/^ollama-tool-0-/) + expect(second?.runId).toMatch(/^ollama-tool-0-/) + expect(first?.runId).not.toBe(second?.runId) + expect(first?.toolUseId).toBe("ollama-tool-0") + expect(second?.toolUseId).toBe("ollama-tool-0") + }) + + it("refuses to spawn when the feature is disabled", async () => { + const harness = makeHarness({ enabled: false }) + + await subagentTool.handle( + harness.task, + harness.block({ agent: "explore", description: "Find auth", prompt: "Locate auth" }), + harness.callbacks, + ) + + expect(harness.manager.spawn).not.toHaveBeenCalled() + expect(harness.registerSubagentCall).not.toHaveBeenCalled() + expect(harness.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Subagents are disabled")) + }) + + it("refuses a nested spawn from inside a subagent run", async () => { + const harness = makeHarness({ nested: true }) + + await subagentTool.handle( + harness.task, + harness.block({ agent: "explore", description: "Nested", prompt: "Nested" }), + harness.callbacks, + ) + + expect(harness.manager.spawn).not.toHaveBeenCalled() + expect(harness.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("cannot spawn another subagent")) + }) + + it("lists the available agents for an unknown name", async () => { + const harness = makeHarness() + + await subagentTool.handle( + harness.task, + harness.block({ agent: "missing", description: "Find auth", prompt: "Locate auth" }), + harness.callbacks, + ) + + expect(harness.manager.spawn).not.toHaveBeenCalled() + expect(harness.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Available agents: explore")) + }) + + it("reports the missing parameter and counts a mistake", async () => { + const harness = makeHarness() + + await subagentTool.handle( + harness.task, + harness.block({ description: "No agent", prompt: "Locate auth" }), + harness.callbacks, + ) + + expect(harness.sayAndCreateMissingParamError).toHaveBeenCalledWith("spawn_subagent", "agent") + expect(harness.pushToolResult).toHaveBeenCalledWith("missing parameter") + expect(harness.manager.spawn).not.toHaveBeenCalled() + }) +}) diff --git a/src/core/subagents/__tests__/formatSubagentResult.spec.ts b/src/core/subagents/__tests__/formatSubagentResult.spec.ts new file mode 100644 index 00000000000..d9163bdadda --- /dev/null +++ b/src/core/subagents/__tests__/formatSubagentResult.spec.ts @@ -0,0 +1,84 @@ +// npx vitest run core/subagents/__tests__/formatSubagentResult.spec.ts + +import type { SubagentToolOutcome } from "../types" +import { formatSubagentOutcome } from "../formatSubagentResult" + +const base = (overrides: Partial = {}): SubagentToolOutcome => ({ + runId: "run-1", + agentName: "explore", + status: "completed", + summary: "", + filesRead: [], + filesModified: [], + toolCallCount: 3, + tokenUsage: { input: 10, output: 4 }, + ...overrides, +}) + +describe("formatSubagentOutcome", () => { + it("reports the agent, status and duration summary", () => { + const text = formatSubagentOutcome(base({ durationMs: 1500 })) + + expect(text).toContain('Subagent "explore" completed.') + expect(text).toContain("Duration 1.5s · tools 3 · tokens in 10 / out 4") + }) + + it("marks a partial run that reached max turns", () => { + const text = formatSubagentOutcome(base({ status: "failed", partial: true })) + + expect(text).toContain('Subagent "explore" failed (partial: max turns reached).') + }) + + it("omits the duration line when durationMs is absent", () => { + const text = formatSubagentOutcome(base({ durationMs: undefined })) + + expect(text).not.toContain("Duration") + }) + + it("lists the files read and modified", () => { + const text = formatSubagentOutcome(base({ filesRead: ["a.ts", "b.ts"], filesModified: ["b.ts"] })) + + expect(text).toContain("Files read: a.ts, b.ts") + expect(text).toContain("Files modified: b.ts") + }) + + it("does not emit empty file sections", () => { + const text = formatSubagentOutcome(base()) + + expect(text).not.toContain("Files read") + expect(text).not.toContain("Files modified") + }) + + it("reports a kept and a removed worktree", () => { + const kept = formatSubagentOutcome( + base({ worktree: { path: "/ws/wt", kept: true, filesChanged: 2, diffStat: "2 files" } }), + ) + expect(kept).toContain("Worktree kept: /ws/wt (2 files changed)") + expect(kept).toContain("Diff stat:\n2 files") + + const removed = formatSubagentOutcome(base({ worktree: { path: "/ws/wt", kept: false } })) + expect(removed).toContain("Worktree removed: /ws/wt") + }) + + it("reports the error when present", () => { + const text = formatSubagentOutcome(base({ error: "boom" })) + + expect(text).toContain("Error: boom") + }) + + it("appends the summary and transcript path when present", () => { + const text = formatSubagentOutcome( + base({ summary: " Found the bug ", transcriptPath: "/log/api_conversation_history.json" }), + ) + + expect(text).toContain("Summary:\nFound the bug") + expect(text).toContain("Full transcript: /log/api_conversation_history.json") + }) + + it("omits the summary and transcript lines when absent", () => { + const text = formatSubagentOutcome(base()) + + expect(text).not.toContain("Summary:") + expect(text).not.toContain("Full transcript") + }) +}) diff --git a/src/core/subagents/__tests__/toolFilter.spec.ts b/src/core/subagents/__tests__/toolFilter.spec.ts new file mode 100644 index 00000000000..bba15f5e113 --- /dev/null +++ b/src/core/subagents/__tests__/toolFilter.spec.ts @@ -0,0 +1,167 @@ +// npx vitest run core/subagents/__tests__/toolFilter.spec.ts + +import type OpenAI from "openai" +import type { SubagentDefinition } from "@roo-code/types" + +import { filterAllowedFunctionNamesForSubagent, filterToolsForSubagent } from "../toolFilter" + +const tool = (name: string): OpenAI.Chat.ChatCompletionTool => ({ + type: "function", + function: { name, description: name, parameters: { type: "object", properties: {} } }, +}) + +const toolNames = (tools: OpenAI.Chat.ChatCompletionTool[]) => + tools.map((entry) => ("function" in entry ? entry.function?.name : undefined)) + +const baseDefinition: SubagentDefinition = { + name: "worker", + description: "test", + systemPrompt: "work", + source: "builtin", +} + +const ALL_TOOLS = [ + tool("read_file"), + tool("list_files"), + tool("write_to_file"), + tool("execute_command"), + tool("spawn_subagent"), + tool("resume_subagent"), + tool("new_task"), + tool("ask_followup_question"), + tool("switch_mode"), + tool("attempt_completion"), +] + +describe("filterToolsForSubagent", () => { + it("always removes the forbidden tools, even when the definition allows them", () => { + const names = toolNames( + filterToolsForSubagent(ALL_TOOLS, { + ...baseDefinition, + tools: ["spawn_subagent", "new_task", "read_file"], + }), + ) + + expect(names).toEqual(["read_file", "attempt_completion"]) + }) + + it("keeps the definition allow list", () => { + expect( + toolNames(filterToolsForSubagent(ALL_TOOLS, { ...baseDefinition, tools: ["read_file", "list_files"] })), + ).toEqual(["read_file", "list_files", "attempt_completion"]) + }) + + it("keeps attempt_completion when the allow list omits it", () => { + // A run that cannot call attempt_completion can never report a finished + // result, so the completion tool survives a narrow allow list. + expect( + toolNames( + filterToolsForSubagent(ALL_TOOLS, { + ...baseDefinition, + tools: ["read_file"], + disallowedTools: ["attempt_completion"], + }), + ), + ).toEqual(["read_file", "attempt_completion"]) + }) + + it("applies the deny list before the allow list", () => { + const names = toolNames( + filterToolsForSubagent(ALL_TOOLS, { + ...baseDefinition, + tools: ["read_file", "list_files"], + disallowedTools: ["list_files"], + }), + ) + + expect(names).toEqual(["read_file", "attempt_completion"]) + }) + + it("limits a read-only agent to read-class tools and attempt_completion", () => { + const names = toolNames(filterToolsForSubagent(ALL_TOOLS, { ...baseDefinition, readonly: true })) + + expect(names).toEqual(["read_file", "list_files", "attempt_completion"]) + }) + + it("never lets a read-only agent keep a write tool through the allow list", () => { + const names = toolNames( + filterToolsForSubagent(ALL_TOOLS, { + ...baseDefinition, + readonly: true, + tools: ["write_to_file", "read_file"], + }), + ) + + expect(names).toEqual(["read_file", "attempt_completion"]) + }) + + it("keeps a tool entry that has no callable name", () => { + const noNameTool = { type: "function", function: {} } as OpenAI.Chat.ChatCompletionTool + expect(toolNames(filterToolsForSubagent([noNameTool], baseDefinition))).toEqual([undefined]) + }) + + it("applies a use_mcp_tool deny to the dynamic mcp-- tool declarations", () => { + // A dynamic MCP declaration is the same capability as use_mcp_tool, so + // denying the canonical name must remove every mcp-- entry. + const names = toolNames( + filterToolsForSubagent([tool("mcp--server--search"), tool("read_file")], { + ...baseDefinition, + disallowedTools: ["use_mcp_tool"], + }), + ) + + expect(names).toEqual(["read_file"]) + expect( + filterAllowedFunctionNamesForSubagent(["mcp--server--search", "read_file"], { + ...baseDefinition, + disallowedTools: ["use_mcp_tool"], + }), + ).toEqual(["read_file"]) + }) + + it("keeps an MCP tool the definition does not deny", () => { + expect(toolNames(filterToolsForSubagent([tool("mcp--server--search")], baseDefinition))).toEqual([ + "mcp--server--search", + ]) + }) + + it("removes MCP tools from a read-only agent", () => { + expect( + toolNames( + filterToolsForSubagent([tool("mcp--server--search"), tool("read_file")], { + ...baseDefinition, + readonly: true, + }), + ), + ).toEqual(["read_file"]) + }) +}) + +describe("filterAllowedFunctionNamesForSubagent", () => { + it("returns undefined when the provider has no callable-name list", () => { + expect(filterAllowedFunctionNamesForSubagent(undefined, baseDefinition)).toBeUndefined() + }) + + it("filters the same way as the tool array", () => { + const names = filterAllowedFunctionNamesForSubagent( + ["read_file", "write_to_file", "spawn_subagent", "attempt_completion"], + { ...baseDefinition, readonly: true }, + ) + + expect(names).toEqual(["read_file", "attempt_completion"]) + }) + + it("applies the deny and allow lists in the callable-name list", () => { + const names = filterAllowedFunctionNamesForSubagent(["read_file", "write_to_file", "list_files"], { + ...baseDefinition, + tools: ["read_file"], + disallowedTools: ["list_files"], + }) + + expect(names).toEqual(["read_file"]) + }) + + it("returns undefined names when the list is empty", () => { + expect(filterAllowedFunctionNamesForSubagent([], baseDefinition)).toEqual([]) + }) +}) diff --git a/src/core/subagents/__tests__/worktree.spec.ts b/src/core/subagents/__tests__/worktree.spec.ts new file mode 100644 index 00000000000..ee7098c9288 --- /dev/null +++ b/src/core/subagents/__tests__/worktree.spec.ts @@ -0,0 +1,144 @@ +// npx vitest run core/subagents/__tests__/worktree.spec.ts + +import { createSubagentWorktree, finalizeSubagentWorktree } from "../worktree" +import { execa } from "execa" + +vi.mock("execa", () => ({ + execa: vi.fn(), +})) + +const execaMock = vi.mocked(execa) + +describe("createSubagentWorktree", () => { + afterEach(() => { + execaMock.mockReset() + }) + + const options = { repoPath: "/repo", worktreePath: "/worktrees/run-1" } + + it("returns the worktree path when the repo is a git worktree and the add succeeds", async () => { + execaMock.mockResolvedValueOnce({ stdout: "true" } as never) + execaMock.mockResolvedValueOnce({ stdout: "" } as never) + + await expect(createSubagentWorktree(options)).resolves.toBe("/worktrees/run-1") + expect(execaMock).toHaveBeenCalledWith("git", ["-C", "/repo", "rev-parse", "--is-inside-work-tree"], { + timeout: 10_000, + }) + expect(execaMock).toHaveBeenCalledWith( + "git", + ["-C", "/repo", "worktree", "add", "--detach", "/worktrees/run-1", "HEAD"], + { timeout: 60_000 }, + ) + }) + + it("uses an explicit ref when provided", async () => { + execaMock.mockResolvedValueOnce({ stdout: "true" } as never) + execaMock.mockResolvedValueOnce({ stdout: "" } as never) + + await expect(createSubagentWorktree({ ...options, ref: "abc123" })).resolves.toBe("/worktrees/run-1") + expect(execaMock).toHaveBeenLastCalledWith( + "git", + ["-C", "/repo", "worktree", "add", "--detach", "/worktrees/run-1", "abc123"], + { timeout: 60_000 }, + ) + }) + + it("returns undefined and logs when the repo is not a git worktree", async () => { + execaMock.mockRejectedValueOnce(new Error("not a repo")) + const log = vi.fn() + + await expect(createSubagentWorktree({ ...options, log })).resolves.toBeUndefined() + expect(log).toHaveBeenCalledWith(expect.stringContaining("is not a git worktree")) + expect(execaMock).toHaveBeenCalledTimes(1) + }) + + it("returns undefined and logs when worktree add fails", async () => { + execaMock.mockResolvedValueOnce({ stdout: "true" } as never) + execaMock.mockRejectedValueOnce(new Error("path exists")) + const log = vi.fn() + + await expect(createSubagentWorktree({ ...options, log })).resolves.toBeUndefined() + expect(log).toHaveBeenCalledWith(expect.stringContaining("failed to create worktree")) + }) +}) + +describe("finalizeSubagentWorktree", () => { + afterEach(() => { + execaMock.mockReset() + }) + + const options = { repoPath: "/repo", worktreePath: "/worktrees/run-1" } + + it("removes a clean worktree without --force", async () => { + execaMock.mockResolvedValueOnce({ stdout: "" } as never) + execaMock.mockResolvedValueOnce({ stdout: "" } as never) + execaMock.mockResolvedValueOnce({ stdout: "" } as never) + + await expect(finalizeSubagentWorktree(options)).resolves.toEqual({ + path: "/worktrees/run-1", + kept: false, + filesChanged: 0, + }) + expect(execaMock).toHaveBeenCalledWith( + "git", + ["-C", "/worktrees/run-1", "status", "--porcelain", "--untracked-files=all"], + { timeout: 20_000 }, + ) + expect(execaMock).toHaveBeenCalledWith("git", ["-C", "/repo", "worktree", "remove", "/worktrees/run-1"], { + timeout: 30_000, + }) + }) + + it("counts untracked files inside a new directory", async () => { + execaMock.mockResolvedValueOnce({ stdout: "?? src/new/a.ts\n?? src/new/b.ts\n" } as never) + execaMock.mockResolvedValueOnce({ stdout: "" } as never) + + await expect(finalizeSubagentWorktree(options)).resolves.toEqual({ + path: "/worktrees/run-1", + kept: true, + filesChanged: 2, + diffStat: undefined, + }) + expect(execaMock).toHaveBeenCalledTimes(2) + }) + + it("counts changed files and keeps a dirty worktree with a diff stat", async () => { + execaMock.mockResolvedValueOnce({ stdout: " M a.ts\n M b.ts\n" } as never) + execaMock.mockResolvedValueOnce({ stdout: " a.ts | 2 +-\n b.ts | 3 +-\n" } as never) + + await expect(finalizeSubagentWorktree(options)).resolves.toEqual({ + path: "/worktrees/run-1", + kept: true, + filesChanged: 2, + diffStat: "a.ts | 2 +-\n b.ts | 3 +-", + }) + expect(execaMock).toHaveBeenCalledTimes(2) + }) + + it("keeps the worktree when removal of a clean tree fails", async () => { + execaMock.mockResolvedValueOnce({ stdout: "" } as never) + execaMock.mockResolvedValueOnce({ stdout: "" } as never) + execaMock.mockRejectedValueOnce(new Error("busy")) + const log = vi.fn() + + await expect(finalizeSubagentWorktree({ ...options, log })).resolves.toEqual({ + path: "/worktrees/run-1", + kept: true, + filesChanged: 0, + }) + expect(log).toHaveBeenCalledWith(expect.stringContaining("failed to remove clean worktree")) + }) + + it("keeps the worktree with an unknown file count when inspection fails", async () => { + execaMock.mockRejectedValueOnce(new Error("not a repo")) + const log = vi.fn() + + await expect(finalizeSubagentWorktree({ ...options, log })).resolves.toEqual({ + path: "/worktrees/run-1", + kept: true, + }) + expect(log).toHaveBeenCalledWith(expect.stringContaining("failed to inspect worktree")) + // A failed inspection never removes the worktree. + expect(execaMock).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/core/subagents/formatSubagentResult.ts b/src/core/subagents/formatSubagentResult.ts new file mode 100644 index 00000000000..d0d5356f6ca --- /dev/null +++ b/src/core/subagents/formatSubagentResult.ts @@ -0,0 +1,52 @@ +import type { SubagentToolOutcome } from "./types" + +/** + * Formats the single `tool_result` the parent receives for a subagent run. + * Deliberately compact: the child's transcript stays on disk. + */ +export function formatSubagentOutcome(outcome: SubagentToolOutcome): string { + const lines: string[] = [] + + lines.push( + `Subagent "${outcome.agentName}" ${outcome.status}${outcome.partial ? " (partial: max turns reached)" : ""}.`, + ) + + if (outcome.durationMs !== undefined) { + lines.push( + `Duration ${(outcome.durationMs / 1000).toFixed(1)}s · tools ${outcome.toolCallCount} · tokens in ${outcome.tokenUsage.input} / out ${outcome.tokenUsage.output}`, + ) + } + + if (outcome.filesRead.length > 0) { + lines.push(`Files read: ${outcome.filesRead.join(", ")}`) + } + + if (outcome.filesModified.length > 0) { + lines.push(`Files modified: ${outcome.filesModified.join(", ")}`) + } + + if (outcome.worktree) { + lines.push( + `Worktree ${outcome.worktree.kept ? "kept" : "removed"}: ${outcome.worktree.path}${ + outcome.worktree.filesChanged !== undefined ? ` (${outcome.worktree.filesChanged} files changed)` : "" + }`, + ) + if (outcome.worktree.diffStat) { + lines.push(`Diff stat:\n${outcome.worktree.diffStat}`) + } + } + + if (outcome.error) { + lines.push(`Error: ${outcome.error}`) + } + + if (outcome.summary.trim()) { + lines.push("", "Summary:", outcome.summary.trim()) + } + + if (outcome.transcriptPath) { + lines.push("", `Full transcript: ${outcome.transcriptPath}`) + } + + return lines.join("\n") +} diff --git a/src/core/subagents/prompt.ts b/src/core/subagents/prompt.ts new file mode 100644 index 00000000000..df1fa309105 --- /dev/null +++ b/src/core/subagents/prompt.ts @@ -0,0 +1,15 @@ +/** + * Operating contract appended to every subagent system prompt. + * + * Subagent prompts come from user-editable Markdown files, so the tool-use + * contract lives here instead: the child must still end through + * `attempt_completion`, must not wait for input, and must not try to delegate + * again. + */ +export const SUBAGENT_TOOL_PROTOCOL = [ + "Tool protocol:", + "- You are a headless subagent. No human will answer you. Never wait for a reply.", + "- Use only the tools you are given. You cannot spawn subagents, delegate with new_task, switch modes or ask follow-up questions.", + "- When the task is done, call attempt_completion with the final report as the result.", + "- The report is the only thing your parent sees. State what you found or changed, exact file paths, what you verified, and any assumptions or open questions.", +].join("\n") diff --git a/src/core/subagents/toolFilter.ts b/src/core/subagents/toolFilter.ts new file mode 100644 index 00000000000..d74384b66a2 --- /dev/null +++ b/src/core/subagents/toolFilter.ts @@ -0,0 +1,102 @@ +import type OpenAI from "openai" + +import { isForbiddenSubagentTool, type SubagentDefinition } from "@roo-code/types" + +import { isMcpTool } from "../../utils/mcp-name" + +/** + * Tools a read-only subagent may keep even when its definition lists no + * explicit tool set. Everything that can mutate the workspace, run commands or + * start other work is excluded. + */ +export const SUBAGENT_READONLY_TOOLS = new Set([ + "read_file", + "search_files", + "list_files", + "codebase_search", + "read_command_output", + "attempt_completion", +]) + +/** + * The only tool that lets a headless run report a finished result. Without it + * the run can never become `completed`, so it stays available even when the + * definition's own lists omit it. + */ +export const SUBAGENT_COMPLETION_TOOL = "attempt_completion" + +function toolName(tool: OpenAI.Chat.ChatCompletionTool): string | undefined { + return "function" in tool ? tool.function?.name : undefined +} + +/** + * Whether the subagent definition allows this tool name. + * + * The order is deliberate: the flat-hierarchy ban wins over everything, then + * the completion tool stays available, then the definition's own deny list, + * its allow list, and finally the read-only class restriction. A definition can + * therefore never re-enable a forbidden tool or remove the only way to finish. + */ +export function isToolAllowedForSubagent(name: string, definition: SubagentDefinition): boolean { + // A dynamic MCP declaration (`mcp--server--tool`) offers exactly the + // capability of `use_mcp_tool`, so the definition's lists must be read under + // that canonical name. Otherwise a deny list naming `use_mcp_tool` would not + // cover the dynamic tools the model can call instead. + const policyName = isMcpTool(name) ? "use_mcp_tool" : name + + if (isForbiddenSubagentTool(name)) { + return false + } + + if (name === SUBAGENT_COMPLETION_TOOL) { + return true + } + + if ((definition.disallowedTools ?? []).includes(policyName)) { + return false + } + + if (definition.tools && !definition.tools.includes(policyName)) { + return false + } + + if (definition.readonly === true && !SUBAGENT_READONLY_TOOLS.has(policyName)) { + return false + } + + return true +} + +/** + * Applies the subagent definition to a built tool array. + */ +export function filterToolsForSubagent( + tools: OpenAI.Chat.ChatCompletionTool[], + definition: SubagentDefinition, +): OpenAI.Chat.ChatCompletionTool[] { + return tools.filter((tool) => { + const name = toolName(tool) + + if (!name) { + return true + } + + return isToolAllowedForSubagent(name, definition) + }) +} + +/** + * Restricts the provider's callable-name list the same way the tool array is + * restricted, for providers that see all definitions but may call only a + * subset. + */ +export function filterAllowedFunctionNamesForSubagent( + names: string[] | undefined, + definition: SubagentDefinition, +): string[] | undefined { + if (!names) { + return undefined + } + + return names.filter((name) => isToolAllowedForSubagent(name, definition)) +} diff --git a/src/core/subagents/types.ts b/src/core/subagents/types.ts new file mode 100644 index 00000000000..469f87ca9be --- /dev/null +++ b/src/core/subagents/types.ts @@ -0,0 +1,56 @@ +import type { ClineAsk, ClineAskResponse, SubagentDefinition, SubagentRunSnapshot } from "@roo-code/types" + +/** + * Result of a headless ask. Subagents never block on user input. + */ +export interface SubagentAskResult { + response: ClineAskResponse + text?: string + images?: string[] +} + +/** + * Task-local hooks a headless subagent run installs on its `Task`. + * + * `Task` imports this type only, so the runner and the task loop stay free of a + * runtime module cycle. + */ +export interface SubagentTaskContext { + runId: string + /** Shared by every spawn of the same parent turn. */ + groupId: string + definition: SubagentDefinition + /** Called as the child starts each tool call. Used for the live ticker. */ + onToolUse?: (toolName: string, params: Record) => void + /** Resolves a headless ask without user interaction. */ + onAsk?: (type: ClineAsk, text?: string) => SubagentAskResult +} + +/** + * The value a queued `spawn_subagent` call resolves to. The parent receives + * only this summary; child tool output never enters the parent conversation. + */ +export interface SubagentToolOutcome { + runId: string + agentName: string + status: SubagentRunSnapshot["status"] + summary: string + error?: string + partial?: boolean + filesRead: string[] + filesModified: string[] + durationMs?: number + toolCallCount: number + tokenUsage: { input: number; output: number } + transcriptPath?: string + worktree?: SubagentRunSnapshot["worktree"] +} + +/** Payload of a single queued `spawn_subagent` call. */ +export interface SubagentSpawnRequest { + agent: string + description: string + prompt: string + model?: string + isolation?: "none" | "worktree" +} diff --git a/src/core/subagents/worktree.ts b/src/core/subagents/worktree.ts new file mode 100644 index 00000000000..4f0a67f9c7c --- /dev/null +++ b/src/core/subagents/worktree.ts @@ -0,0 +1,95 @@ +import { execa } from "execa" + +export interface WorktreeInfo { + path: string + kept: boolean + filesChanged?: number + diffStat?: string +} + +export interface CreateWorktreeOptions { + repoPath: string + /** Directory the worktree is created in. Must not exist yet. */ + worktreePath: string + /** Ref to check out. Detached HEAD keeps branches untouched. */ + ref?: string + log?: (message: string) => void +} + +/** + * Creates a temporary detached worktree for one subagent run. + * + * Returns `undefined` when the workspace is not a git repository, or when the + * worktree cannot be created. In that case the run falls back to the parent + * workspace instead of failing. + */ +export async function createSubagentWorktree(options: CreateWorktreeOptions): Promise { + const { repoPath, worktreePath, ref = "HEAD", log } = options + + try { + await execa("git", ["-C", repoPath, "rev-parse", "--is-inside-work-tree"], { timeout: 10_000 }) + } catch { + log?.(`[subagent] ${repoPath} is not a git worktree; running in the workspace`) + return undefined + } + + try { + await execa("git", ["-C", repoPath, "worktree", "add", "--detach", worktreePath, ref], { timeout: 60_000 }) + return worktreePath + } catch (error) { + log?.(`[subagent] failed to create worktree at ${worktreePath}: ${(error as Error).message}`) + return undefined + } +} + +/** + * Reports what changed in a subagent worktree and removes it when it is clean. + * A worktree with changes is kept so the parent can review or merge it. + */ +export async function finalizeSubagentWorktree(options: { + repoPath: string + worktreePath: string + log?: (message: string) => void +}): Promise { + const { repoPath, worktreePath, log } = options + + let status: string + let diffStat = "" + + try { + // `--untracked-files=all` lists every untracked file, not only the + // top-level directory, so a new directory with files counts what it holds. + const { stdout } = await execa("git", ["-C", worktreePath, "status", "--porcelain", "--untracked-files=all"], { + timeout: 20_000, + }) + status = stdout + const { stdout: stat } = await execa("git", ["-C", worktreePath, "diff", "HEAD", "--stat"], { + timeout: 20_000, + }) + diffStat = stat + } catch (error) { + // A failed inspection is not proof of a clean tree. Keep the worktree + // instead of deleting uncommitted work, and report the count as unknown. + log?.(`[subagent] failed to inspect worktree ${worktreePath}: ${(error as Error).message}`) + return { path: worktreePath, kept: true } + } + + const filesChanged = status + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0).length + + if (filesChanged === 0) { + try { + // No `--force`: if a write lands after the status read, git refuses + // the removal and the worktree is kept instead of losing that write. + await execa("git", ["-C", repoPath, "worktree", "remove", worktreePath], { timeout: 30_000 }) + return { path: worktreePath, kept: false, filesChanged: 0 } + } catch (error) { + log?.(`[subagent] failed to remove clean worktree ${worktreePath}: ${(error as Error).message}`) + return { path: worktreePath, kept: true, filesChanged: 0 } + } + } + + return { path: worktreePath, kept: true, filesChanged, diffStat: diffStat.trim() || undefined } +} diff --git a/src/core/task-persistence/TaskHistoryStore.ts b/src/core/task-persistence/TaskHistoryStore.ts index e0bb54998c3..294dbb02e68 100644 --- a/src/core/task-persistence/TaskHistoryStore.ts +++ b/src/core/task-persistence/TaskHistoryStore.ts @@ -18,6 +18,12 @@ import { computeHistoryDelta, DeltaRejectedError, mergeHistoryDelta } from "./ta export { assertValidTransition, type HistoryItemStatus } from "./taskLifecycle" export { DeltaRejectedError } from "./taskStoreConcurrency" +/** + * Upper bound on the in-memory deleted-task tombstones. A long session can + * delete many tasks, and only a write that races the deletion needs the guard. + */ +const MAX_DELETED_TOMBSTONES = 1000 + /** * Build a `safeWriteJson` merge callback that applies only `delta` to the * current disk state, preserving fields written by another process. @@ -87,6 +93,13 @@ export class TaskHistoryStore { private readonly onWrite?: (items: HistoryItem[]) => Promise private cache: Map = new Map() private taskFileMtimes: Map = new Map() + /** + * Task ids deleted in this instance. A task id is unique per task, so a write + * that arrives after deletion (a finishing child, a throttled save) must not + * recreate the row. Insertion-ordered and bounded; eviction only weakens the + * guard for the oldest deletions. + */ + private readonly deletedTaskIds = new Set() private writeLock: Promise = Promise.resolve() private fsWatcher: fsSync.FSWatcher | null = null private reconcileTimer: ReturnType | null = null @@ -211,6 +224,12 @@ export class TaskHistoryStore { item: HistoryItem, options: { skipTransitionCheck?: boolean } = {}, ): Promise { + // A save that lost the race against a deletion must not recreate the row. + // Task ids are unique, so a tombstoned id is never a new task. + if (this.deletedTaskIds.has(item.id)) { + return this.getAll() + } + const existing = this.cache.get(item.id) // Enforce transition validity at the write boundary so that any caller @@ -266,6 +285,20 @@ export class TaskHistoryStore { return all } + /** + * Record that a task was deleted, so a later `upsert` cannot resurrect it. + * Must be called from within `withLock` (both delete paths already hold it). + */ + private markDeleted(taskId: string): void { + this.deletedTaskIds.add(taskId) + if (this.deletedTaskIds.size > MAX_DELETED_TOMBSTONES) { + const oldest = this.deletedTaskIds.values().next().value + if (oldest !== undefined) { + this.deletedTaskIds.delete(oldest) + } + } + } + /** * Delete a single task's history item. * @@ -278,6 +311,7 @@ export class TaskHistoryStore { */ async delete(taskId: string): Promise { return this.withLock(async () => { + this.markDeleted(taskId) this.cache.delete(taskId) this.taskFileMtimes.delete(taskId) @@ -308,6 +342,7 @@ export class TaskHistoryStore { async deleteMany(taskIds: string[]): Promise { return this.withLock(async () => { for (const taskId of taskIds) { + this.markDeleted(taskId) this.cache.delete(taskId) this.taskFileMtimes.delete(taskId) @@ -357,6 +392,13 @@ export class TaskHistoryStore { const liveIds = new Set() for (const taskId of onDiskIds) { + // A tombstoned id was deleted on purpose. A file that survived a + // failed unlink must not bring the row back: once restored, later + // upserts would be dropped by the same tombstone. + if (this.deletedTaskIds.has(taskId)) { + continue + } + try { const taskFilePath = await this.getTaskFilePath(taskId) const { mtimeMs } = await fs.stat(taskFilePath).catch(async (error: unknown) => { @@ -786,6 +828,14 @@ export class TaskHistoryStore { */ async invalidate(taskId: string): Promise { return this.withLock(async () => { + // Re-reading a deleted task would restore a row the tombstone keeps + // refusing to write, so the cache stays empty for that id. + if (this.deletedTaskIds.has(taskId)) { + this.cache.delete(taskId) + this.taskFileMtimes.delete(taskId) + return + } + try { const item = await this.readTaskFile(taskId) if (item) { diff --git a/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts b/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts index 875c7dcb9a7..b26d97b2738 100644 --- a/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts +++ b/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts @@ -126,6 +126,27 @@ describe("TaskHistoryStore best-effort deletion semantics", () => { }, ) + it.each(["delete", "deleteMany"] as const)( + "%s leaves a tombstone so a late upsert cannot recreate history", + async (operation) => { + const store = createStore() + await store.initialize() + const history = makeHistoryItem({ id: "late-writer" }) + await store.upsert(history) + + if (operation === "delete") await store.delete(history.id) + else await store.deleteMany([history.id]) + + // A finishing child or a throttled save can upsert after the delete. + await store.upsert({ ...history, task: "Late save" }) + + expect(store.get(history.id)).toBeUndefined() + await expect(readFileWithMissingRetry(historyFilePath(storagePath, history.id))).rejects.toMatchObject({ + code: "ENOENT", + }) + }, + ) + it.each(["delete", "deleteMany"] as const)( "%s preserves the canonical file if backup cleanup fails", async (operation) => { @@ -147,6 +168,53 @@ describe("TaskHistoryStore best-effort deletion semantics", () => { }, ) + describe("tombstones survive a reader that sees the leftover file", () => { + it.each(["delete", "deleteMany"] as const)( + "%s keeps reconcile from restoring a row whose unlink failed", + async (operation) => { + const store = createStore() + await store.initialize() + const history = makeHistoryItem({ id: "restore-guard" }) + await store.upsert(history) + const filePath = historyFilePath(storagePath, history.id) + + // A non-ENOENT unlink failure leaves the canonical file behind. + vi.mocked(fs.unlink).mockRejectedValue( + Object.assign(new Error("EACCES: permission denied, unlink"), { code: "EACCES" }), + ) + if (operation === "delete") await store.delete(history.id) + else await store.deleteMany([history.id]) + expect(store.get(history.id)).toBeUndefined() + await expect(fs.access(filePath)).resolves.toBeUndefined() + + vi.mocked(fs.unlink).mockImplementation(actualFs.unlink) + + // The leftover file must not reappear as history: a restored row + // would silently drop every later write through the tombstone. + await store.reconcile({ forceRefresh: true }) + + expect(store.get(history.id)).toBeUndefined() + }, + ) + + it("keeps invalidate() from restoring a deleted task", async () => { + const store = createStore() + await store.initialize() + const history = makeHistoryItem({ id: "invalidate-guard" }) + await store.upsert(history) + + vi.mocked(fs.unlink).mockRejectedValue( + Object.assign(new Error("EACCES: permission denied, unlink"), { code: "EACCES" }), + ) + await store.delete(history.id) + vi.mocked(fs.unlink).mockImplementation(actualFs.unlink) + + await store.invalidate("invalidate-guard") + + expect(store.get("invalidate-guard")).toBeUndefined() + }) + }) + describe("delete()", () => { it("unlinks under the shared per-file lock, evicts cache and mtime, and writes through once", async () => { const store = createStore() diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 47a28aaaeb5..87c0f9f34f7 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -31,6 +31,7 @@ import { type ClineSay, type ClineAsk, type ExtensionState, + type ExtensionMessage, type ToolProgressStatus, type HistoryItem, type PendingTaskAction, @@ -101,7 +102,7 @@ import { formatResponse } from "../prompts/responses" import { SYSTEM_PROMPT } from "../prompts/system" import type { InstructionFailureCollector } from "../prompts/sections/custom-instructions" import { partitionDisabledToolsForProtocol } from "../prompts/tools/effective-tool-policy" -import { buildNativeToolsArrayWithRestrictions } from "./build-tools" +import { buildNativeToolsArrayWithRestrictions, describeAvailableSubagents } from "./build-tools" // core modules import { ToolRepetitionDetector } from "../tools/ToolRepetitionDetector" @@ -150,6 +151,11 @@ import { detachOnAbort } from "../../api/providers/utils/abort-signal" import { getApiRequestTimeout } from "../../api/providers/utils/timeout-config" import { shouldAddUserMessageToHistory } from "./messageCounting" import { type TaskExecutionContext } from "./providerHandoff" +import type { SubagentTaskContext, SubagentToolOutcome } from "../subagents/types" +import type { SubagentRunSnapshot } from "@roo-code/types" +import { formatSubagentOutcome } from "../subagents/formatSubagentResult" +import { filterToolsForSubagent, filterAllowedFunctionNamesForSubagent } from "../subagents/toolFilter" +import { SUBAGENT_TOOL_PROTOCOL } from "../subagents/prompt" import { abort, abortReason, initialRunState, type Ask, type RunEvent, type RunState } from "./run-state/runState" import { applyRunEvent, type RunRejection } from "./run-state/runStateShadow" import { @@ -247,6 +253,35 @@ function queuedResponseForAsk(type: ClineAsk, text?: string): QueuedAskResolutio const FORCED_CONTEXT_REDUCTION_PERCENT = 75 // Keep 75% of context (remove 25%) on context window errors const MAX_CONTEXT_WINDOW_RETRIES = 3 // Maximum retries for context window errors +// A headless run may set `maxTurns` to 0 (unlimited). Retries are not turns, so +// cap them to keep a failing provider from spending without a bound. +const MAX_SUBAGENT_STREAM_RETRIES = 3 + +/** + * Asks that end a headless run instead of returning an automatic answer. + * + * A child has no user to retry a failed request, raise a mistake limit or + * approve more spending. Answering "yes" would retry a failing request or + * keep a run alive past its intended end, so the run records the reason and + * stops at the next request boundary. + */ +function subagentTerminalAskReason(type: ClineAsk, text?: string): string | undefined { + switch (type) { + case "api_req_failed": { + const detail = text?.split("\n")[0]?.slice(0, 200) + + return detail + ? `The subagent stopped because the API request failed: ${detail}` + : "The subagent stopped because the API request failed" + } + case "mistake_limit_reached": + return "The subagent stopped after reaching its consecutive mistake limit" + case "auto_approval_max_req_reached": + return "The subagent stopped after reaching the auto-approval limit" + default: + return undefined + } +} export interface ToolExecutionContext { toolCallId: string @@ -278,6 +313,15 @@ export interface TaskOptions extends CreateTaskOptions { diffFuzzyThreshold?: number /** Explicit task-local execution context for a delegated child. */ handoffExecutionContext?: TaskExecutionContext + /** + * Runs this task as a headless subagent: no webview posting, non-interactive + * asks, a restricted tool set and a turn cap. + */ + subagent?: SubagentTaskContext + /** Maximum API turns for a subagent run. Ignored for normal tasks. */ + maxTurns?: number + /** Parent task id for a headless run that has no `parentTask` instance (worktrees). */ + parentTaskId?: string } type AssistantMessagePersistenceResult = boolean @@ -310,6 +354,22 @@ export class Task extends EventEmitter implements TaskLike { todoList?: TodoItem[] + /** Set only for headless subagent runs. */ + readonly subagent?: SubagentTaskContext + readonly maxTurns?: number + subagentTurnCount = 0 + subagentPartial = false + subagentStopRequested = false + /** Why a headless run ended on a terminal ask; absent when it did not. */ + subagentTerminalError?: string + /** Final `attempt_completion` result of a headless run. */ + subagentSummary?: string + private subagentBatch?: { + calls: Array<{ toolUseId: string; promise: Promise }> + } + /** First spawn tool call of the current turn; all spawns of a turn share it. */ + private currentSubagentGroupId?: string + readonly rootTask: Task | undefined = undefined readonly parentTask: Task | undefined = undefined readonly taskNumber: number @@ -643,6 +703,160 @@ export class Task extends EventEmitter implements TaskLike { return true } + /** + * Registers a `spawn_subagent` call with the current turn's batch. The + * presenter keeps the tool_result open; `runSubagentBatch` fills it once the + * turn's presentation is complete, so parallel children never interleave + * their results into the parent conversation. + */ + public registerSubagentCall(toolUseId: string, promise: Promise): void { + this.subagentBatch ??= { calls: [] } + this.subagentBatch.calls.push({ toolUseId, promise }) + } + + /** True while a spawn batch still owes tool_results to the current turn. */ + public hasQueuedSubagentBatch(): boolean { + return (this.subagentBatch?.calls.length ?? 0) > 0 + } + + /** True when the current assistant message asked for at least one spawn. */ + private hasSubagentSpawnToolUse(): boolean { + return this.assistantMessageContent.some( + (block) => block.type === "tool_use" && block.name === "spawn_subagent", + ) + } + + /** + * Returns the group id shared by every spawn of this turn. The first spawn's + * tool_use id is the group id, which makes the batch id stable across + * reloads without extra persistence. + */ + public getSubagentGroupId(toolUseId: string): string { + this.currentSubagentGroupId ??= toolUseId + return this.currentSubagentGroupId + } + + /** + * True when the assistant turn has finished streaming and every block has + * been presented. The subagent flush waits for this so a late spawn block + * cannot join the batch after results were already pushed. + */ + private isAssistantTurnFullyPresented(): boolean { + if (!this.didCompleteReadingStream || this.dispatchState !== DispatchState.IDLE) { + return false + } + + if (this.currentStreamingContentIndex < this.assistantMessageContent.length) { + return false + } + + return this.assistantMessageContent.every((block) => !block.partial) + } + + /** + * Awaits every queued subagent and pushes one ordered tool_result per call. + * + * Results keep call order rather than completion order so the parent sees a + * deterministic transcript. Cancellation is a normal terminal outcome: the + * runner resolves with a `cancelled` snapshot, never rejects. + */ + public async runSubagentBatch(options: { immediate?: boolean } = {}): Promise { + const requested = this.hasQueuedSubagentBatch() || this.hasSubagentSpawnToolUse() + + if (!requested) { + return + } + + if (!options.immediate) { + await pWaitFor(() => this.isAssistantTurnFullyPresented() || this.abort || this.abandoned) + } + + if (this.abort || this.abandoned) { + return + } + + const batch = this.subagentBatch + + // Presentation can finish without a batch when every spawn was rejected + // before it registered (disabled tool, unknown agent, bad params). The + // presenter's ready latch then needs this turn to release it instead. + if (!batch) { + this.userMessageContentReady = true + return + } + + this.subagentBatch = undefined + const groupId = this.currentSubagentGroupId + + for (const call of batch.calls) { + let outcome: SubagentToolOutcome + + try { + outcome = await call.promise + } catch (error) { + outcome = { + runId: call.toolUseId, + agentName: "unknown", + status: "failed", + summary: "", + error: error instanceof Error ? error.message : String(error), + filesRead: [], + filesModified: [], + toolCallCount: 0, + tokenUsage: { input: 0, output: 0 }, + } + } + + this.pushToolResultToUserContent({ + type: "tool_result", + tool_use_id: sanitizeToolUseId(call.toolUseId), + content: formatSubagentOutcome(outcome), + ...(outcome.status === "failed" ? { is_error: true } : {}), + }) + } + + this.currentSubagentGroupId = undefined + this.userMessageContentReady = true + + if (groupId) { + await this.providerRef.deref()?.getSubagentManager?.()?.finalizeGroup(groupId) + } + } + + /** + * Rewrites the leader `spawnSubagent` row with the final run snapshots so a + * reloaded chat can render the group without the live update stream. + */ + public async updateSubagentGroupMessage(groupId: string, runs: SubagentRunSnapshot[]): Promise { + const message = this.clineMessages.find((candidate) => { + if (candidate.type !== "say" || candidate.say !== "tool" || !candidate.text) { + return false + } + + try { + const parsed = JSON.parse(candidate.text) + return parsed?.tool === "spawnSubagent" && parsed?.runId === groupId + } catch { + return false + } + }) + + if (!message || !message.text) { + return + } + + try { + const parsed = JSON.parse(message.text) + message.text = JSON.stringify({ ...parsed, runs }) + await this.saveClineMessages() + this.updateClineMessage(message).catch((error) => { + console.error("[Task#updateSubagentGroupMessage] updateClineMessage failed:", error) + }) + } catch { + // A malformed row must not break run completion. + } + } + /** * Derives terminal tool-turn readiness from the protocol state instead of * relying exclusively on the presenter's one-shot boolean latch. @@ -747,6 +961,9 @@ export class Task extends EventEmitter implements TaskLike { rateLimitClock, diffFuzzyThreshold, handoffExecutionContext, + subagent, + maxTurns, + parentTaskId: optionsParentTaskId, }: TaskOptions) { super() this.segments = segments @@ -773,7 +990,7 @@ export class Task extends EventEmitter implements TaskLike { this.taskId = historyItem ? historyItem.id : (taskId ?? uuidv7()) this.rootTaskId = historyItem ? historyItem.rootTaskId : rootTask?.taskId - this.parentTaskId = historyItem ? historyItem.parentTaskId : parentTask?.taskId + this.parentTaskId = historyItem ? historyItem.parentTaskId : (parentTask?.taskId ?? optionsParentTaskId) this.childTaskId = undefined this.metadata = { @@ -817,6 +1034,8 @@ export class Task extends EventEmitter implements TaskLike { this.parentTask = parentTask this.taskNumber = taskNumber + this.subagent = subagent + this.maxTurns = maxTurns this.initialStatus = initialStatus ?? historyItem?.status this.pendingAction = historyItem?.pendingAction @@ -851,6 +1070,9 @@ export class Task extends EventEmitter implements TaskLike { this.messageQueueStateChangedHandler = () => { this.emit(RooCodeEventName.TaskUserMessage, this.taskId) this.emit(RooCodeEventName.QueuedMessagesUpdated, this.taskId, this.messageQueueService.messages) + if (this.subagent) { + return + } void this.providerRef .deref() ?.postStateToWebviewThrottled() @@ -1731,16 +1953,18 @@ export class Task extends EventEmitter implements TaskLike { // Partial *asks* still flush, via the clause below — `Task#ask` adds them without // `isAnswered`, so they keep the ordering guarantee that unanswered asks depend on. const requiresImmediateState = message.type === "ask" && message.isAnswered !== true - try { - await provider?.postStateToWebviewThrottled() - } catch (error) { - console.error("[Task#addToClineMessages] postStateToWebviewThrottled failed:", error) - } - if (requiresImmediateState) { + if (!this.subagent) { try { - await provider?.flushPostStateToWebviewThrottled() + await provider?.postStateToWebviewThrottled() } catch (error) { - console.error("[Task#addToClineMessages] flushPostStateToWebviewThrottled failed:", error) + console.error("[Task#addToClineMessages] postStateToWebviewThrottled failed:", error) + } + if (requiresImmediateState) { + try { + await provider?.flushPostStateToWebviewThrottled() + } catch (error) { + console.error("[Task#addToClineMessages] flushPostStateToWebviewThrottled failed:", error) + } } } this.emit(RooCodeEventName.Message, { action: "created", message }) @@ -1834,10 +2058,24 @@ export class Task extends EventEmitter implements TaskLike { private async updateClineMessage(message: ClineMessage) { const provider = this.providerRef.deref() - await provider?.postMessageToWebview({ type: "messageUpdated", clineMessage: message }) + if (!this.subagent) { + await provider?.postMessageToWebview({ type: "messageUpdated", clineMessage: message }) + } this.emit(RooCodeEventName.Message, { action: "updated", message }) } + /** + * Posts an extension message for interactive tasks. A headless subagent has + * no screen, so every webview-only signal is dropped here rather than at + * each call site. + */ + private async postToWebviewIfInteractive(message: ExtensionMessage): Promise { + if (this.subagent) { + return + } + await this.providerRef.deref()?.postMessageToWebview(message) + } + /** * Persist the message array, then refresh the derived metadata / task-history entries. * @@ -1891,7 +2129,26 @@ export class Task extends EventEmitter implements TaskLike { const provider = this.providerRef.deref() const existingStatus = provider?.taskHistoryStore.get(this.taskId)?.status - await provider?.updateTaskHistory(existingStatus ? { ...historyItem, status: existingStatus } : historyItem) + const item = existingStatus ? { ...historyItem, status: existingStatus } : historyItem + // A headless run is persisted for its transcript, but never broadcast to + // the webview's task list. It also carries the run metadata the history + // can use to link a transcript back to its parent turn. + if (this.subagent) { + await provider?.updateTaskHistory( + { + ...item, + subagent: { + runId: this.subagent.runId, + groupId: this.subagent.groupId, + parentTaskId: this.parentTaskId ?? "", + agentName: this.subagent.definition.name, + }, + }, + { broadcast: false }, + ) + } else { + await provider?.updateTaskHistory(item) + } } catch (error) { // The message array was persisted above; a metadata or task-history failure must // not mask that write (see the method docs). The next saveClineMessages() call @@ -1948,6 +2205,69 @@ export class Task extends EventEmitter implements TaskLike { throw new Error(`[RooCode#ask] task ${this.taskId}.${this.instanceId} aborted`) } + // A headless subagent never blocks on the webview, but it must not bypass + // the approval policy either. Gated action asks (commands, tools, MCP use + // and protected writes) go through the same `checkAutoApproval` gate as the + // parent. With no user to answer an "ask" decision, only an explicit policy + // approval runs; everything else denies. Non-action asks (followup, + // completion_result, command_output, ...) keep the non-interactive answer. + if (this.subagent) { + const isGatedAsk = + isProtected === true || type === "command" || type === "tool" || type === "use_mcp_server" + + if (!isGatedAsk) { + // A terminal ask fails the run: nobody can answer it, and "yes" + // would retry a failed request, clear the mistake limit or raise + // the approval limit for a run that must stop. + const terminalReason = subagentTerminalAskReason(type, text) + + if (terminalReason) { + this.subagentTerminalError ??= terminalReason + return { response: "noButtonClicked" } + } + + const answer = this.subagent.onAsk?.(type, text) ?? { + response: "yesButtonClicked" as ClineAskResponse, + } + + if (type === "completion_result" && answer.response === "yesButtonClicked") { + this.subagentStopRequested = true + } + + return answer + } + + const gatedProvider = this.providerRef.deref() + const gatedState = gatedProvider ? await gatedProvider.getState() : undefined + + // Re-check: an abort during the getState/checkAutoApproval awaits must + // not let a gated action through. + if (this.abort) { + throw new Error(`[RooCode#ask] task ${this.taskId}.${this.instanceId} aborted`) + } + + const approval = await checkAutoApproval({ + state: gatedState, + cwd: this.cwd, + ask: type, + text, + isProtected, + dcgDecision: autoApprovalContext?.dcgDecision, + fileTargets: autoApprovalContext?.fileTargets, + }) + + if (approval.decision === "approve") { + return { response: "yesButtonClicked" } + } + + // Deny, or an "ask" that nobody can answer. Report the structured denial + // (denylist, DCG, blanket, protected) back to the model. + return { + response: "noButtonClicked", + autoDenyDetail: approval.decision === "deny" ? approval.autoDeny : undefined, + } + } + let askTs: number // Resolve auto-approval before adding the message so the state snapshot @@ -2747,6 +3067,7 @@ export class Task extends EventEmitter implements TaskLike { experiments: state?.experiments, apiConfiguration, disabledTools: state?.disabledTools, + subagentsEnabled: state?.subagentsEnabled, modelInfo: requestModelInfo, includeAllToolsWithRestrictions: false, }) @@ -2862,6 +3183,10 @@ export class Task extends EventEmitter implements TaskLike { throw new Error(`[RooCode#say] task ${this.taskId}.${this.instanceId} aborted`) } + if (this.subagent && type === "completion_result") { + this.subagentSummary = text ?? "" + } + if (partial !== undefined) { const lastMessage = this.clineMessages.at(-1) @@ -3126,7 +3451,9 @@ export class Task extends EventEmitter implements TaskLike { // The todo list is already set in the constructor if initialTodos were provided // No need to add any messages - the todoList property is already set - await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory() + if (!this.subagent) { + await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory() + } await this.say("text", task, images) @@ -3684,7 +4011,9 @@ export class Task extends EventEmitter implements TaskLike { this.emitFinalTokenUsageUpdate() try { - await this.providerRef.deref()?.flushPostStateToWebviewThrottled() + if (!this.subagent) { + await this.providerRef.deref()?.flushPostStateToWebviewThrottled() + } } catch (error) { console.error( `[Task#abortTask] flushPostStateToWebviewThrottled failed for ${this.taskId}.${this.instanceId}:`, @@ -4037,6 +4366,26 @@ export class Task extends EventEmitter implements TaskLike { throw new Error(`[RooCode#recursivelyMakeRooRequests] task ${this.taskId}.${this.instanceId} aborted`) } + // A terminal ask already failed this headless run. Stop at the next + // request boundary so no further request or retry is sent. + if (this.subagentTerminalError) { + return true + } + + // A headless run stops at its turn cap at the request boundary, not + // only at the outer loop: one call to this method can send several + // requests through the stack. A retry of the current request belongs + // to the same turn. `maxTurns` of 0 means unlimited. + const isRequestRetry = (currentItem.retryAttempt ?? 0) > 0 + if (this.subagent && !isRequestRetry) { + if (this.maxTurns !== undefined && this.maxTurns > 0 && this.subagentTurnCount >= this.maxTurns) { + this.subagentPartial = true + return true + } + + this.subagentTurnCount++ + } + if (this.consecutiveMistakeLimit > 0 && this.consecutiveMistakeCount >= this.consecutiveMistakeLimit) { // Track consecutive mistake errors in telemetry via a named event. // The reason is "unknown" because many paths increment consecutiveMistakeCount @@ -4147,7 +4496,9 @@ export class Task extends EventEmitter implements TaskLike { } satisfies ClineApiReqInfo) await this.saveClineMessages() - await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory() + if (!this.subagent) { + await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory() + } try { let cacheWriteTokens = 0 @@ -4277,6 +4628,12 @@ export class Task extends EventEmitter implements TaskLike { // Yields only if the first chunk is successful, otherwise will // allow the user to retry the request (most likely due to rate // limit error, which gets thrown on the first chunk). + // The mistake-limit ask above can end a headless run; do not + // send the request it was asked about. + if (this.subagentTerminalError) { + return true + } + const requestApi = this.api const requestApiConfiguration = { ...this.apiConfiguration } const stream = this.attemptApiRequest(currentItem.retryAttempt ?? 0, { @@ -4792,6 +5149,12 @@ export class Task extends EventEmitter implements TaskLike { // Clean up partial state await abortStream(cancelReason, streamingFailedMessage) + // A terminal ask caused this failure. The reason is already + // recorded; end the run instead of retrying or asking again. + if (this.subagentTerminalError) { + return true + } + if (this.abort) { // A cancel can land during abortStream after cancelReason was computed; setAbortReason keeps the first reason. this.setAbortReason("user_cancelled") @@ -4884,6 +5247,13 @@ export class Task extends EventEmitter implements TaskLike { `[Task#${this.taskId}.${this.instanceId}] Stream failed, will retry: ${streamingFailedMessage}`, ) + // Retries are not turns, so an uncapped child would keep + // spending even with an unlimited `maxTurns`. Bound them. + if (this.subagent && (currentItem.retryAttempt ?? 0) >= MAX_SUBAGENT_STREAM_RETRIES) { + this.subagentTerminalError ??= `The subagent stopped after ${MAX_SUBAGENT_STREAM_RETRIES} failed stream retries: ${rawErrorMessage}` + return true + } + // Apply exponential backoff similar to first-chunk errors when auto-resubmit is enabled const stateForBackoff = await this.providerRef.deref()?.getState() if (stateForBackoff?.autoApprovalEnabled) { @@ -5059,7 +5429,9 @@ export class Task extends EventEmitter implements TaskLike { } await this.saveClineMessages() - await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory() + if (!this.subagent) { + await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory() + } // No legacy text-stream tool parser state to reset. @@ -5228,6 +5600,13 @@ export class Task extends EventEmitter implements TaskLike { } if (hasTextContent || hasToolUses) { + // A spawn request owns the rest of this turn: wait for the + // presentation to finish and the children to settle, then push + // their results in call order before the next request. + if (this.hasQueuedSubagentBatch() || this.hasSubagentSpawnToolUse()) { + await this.runSubagentBatch() + } + // NOTE: This comment is here for future reference - this was a // workaround for `userMessageContent` not getting set to true. // It was due to it not recursively calling for partial blocks @@ -5258,6 +5637,12 @@ export class Task extends EventEmitter implements TaskLike { ) } + // A headless run accepts its own completion in `ask`; end the + // request loop here instead of sending another API request. + if (this.subagent && this.subagentStopRequested) { + return true + } + // If the model did not tool use, then we need to tell it to // either use a tool or attempt_completion. const didToolUse = this.assistantMessageContent.some( @@ -5402,6 +5787,13 @@ export class Task extends EventEmitter implements TaskLike { requestModelInfo?: ModelInfo, failures?: InstructionFailureCollector, ): Promise { + // A headless run uses its own agent prompt instead of the mode prompt. + // The protocol addendum keeps the completion contract even when a user + // writes a terse agent file. + if (this.subagent) { + return `${this.subagent.definition.systemPrompt}\n\n${SUBAGENT_TOOL_PROTOCOL}` + } + const { mcpEnabled } = requestState ?? {} let mcpHub: McpHub | undefined if (mcpEnabled ?? true) { @@ -5632,7 +6024,7 @@ export class Task extends EventEmitter implements TaskLike { `Forcing truncation to ${FORCED_CONTEXT_REDUCTION_PERCENT}% of current context.`, ) // Send condenseTaskContextStarted to show in-progress indicator - await this.providerRef.deref()?.postMessageToWebview({ type: "condenseTaskContextStarted", text: this.taskId }) + await this.postToWebviewIfInteractive({ type: "condenseTaskContextStarted", text: this.taskId }) // Build tools for condensing metadata (same tools used for normal API calls) const provider = this.providerRef.deref() @@ -5646,6 +6038,7 @@ export class Task extends EventEmitter implements TaskLike { experiments: state?.experiments, apiConfiguration, disabledTools: state?.disabledTools, + subagentsEnabled: state?.subagentsEnabled, modelInfo, includeAllToolsWithRestrictions: false, }) @@ -5711,9 +6104,7 @@ export class Task extends EventEmitter implements TaskLike { } finally { // Notify webview that context management is complete (removes in-progress spinner) // IMPORTANT: Must always be sent to dismiss the spinner, even on error - await this.providerRef - .deref() - ?.postMessageToWebview({ type: "condenseTaskContextResponse", text: this.taskId }) + await this.postToWebviewIfInteractive({ type: "condenseTaskContextResponse", text: this.taskId }) } } @@ -5889,9 +6280,7 @@ export class Task extends EventEmitter implements TaskLike { // This notification must be sent here (not earlier) because the early check uses stale token count // (before user message is added to history), which could incorrectly skip showing the indicator if (contextManagementWillRun && autoCondenseContext) { - await this.providerRef - .deref() - ?.postMessageToWebview({ type: "condenseTaskContextStarted", text: this.taskId }) + await this.postToWebviewIfInteractive({ type: "condenseTaskContextStarted", text: this.taskId }) } // Build tools for condensing metadata (same tools used for normal API calls) @@ -5908,6 +6297,7 @@ export class Task extends EventEmitter implements TaskLike { experiments: state?.experiments, apiConfiguration, disabledTools: state?.disabledTools, + subagentsEnabled: state?.subagentsEnabled, modelInfo: requestModelInfo, includeAllToolsWithRestrictions: false, }) @@ -5985,9 +6375,10 @@ export class Task extends EventEmitter implements TaskLike { // This removes the in-progress spinner and allows the completed result to show // IMPORTANT: Must always be sent to dismiss the spinner, even on error if (contextManagementWillRun && autoCondenseContext) { - await this.providerRef - .deref() - ?.postMessageToWebview({ type: "condenseTaskContextResponse", text: this.taskId }) + await this.postToWebviewIfInteractive({ + type: "condenseTaskContextResponse", + text: this.taskId, + }) } } } @@ -6057,6 +6448,7 @@ export class Task extends EventEmitter implements TaskLike { experiments: state?.experiments, apiConfiguration, disabledTools: state?.disabledTools, + subagentsEnabled: state?.subagentsEnabled, modelInfo, includeAllToolsWithRestrictions: supportsAllowedFunctionNames, }) @@ -6064,6 +6456,17 @@ export class Task extends EventEmitter implements TaskLike { allowedFunctionNames = toolsResult.allowedFunctionNames } + if (this.subagent) { + // Headless runs use their definition's tool policy: no nested spawn, + // no delegation, no mode switch, no blocking question. + allTools = filterToolsForSubagent(allTools, this.subagent.definition) + allowedFunctionNames = filterAllowedFunctionNamesForSubagent(allowedFunctionNames, this.subagent.definition) + } else if (allTools.some((tool) => "function" in tool && tool.function?.name === "spawn_subagent")) { + // The parent prompt pays only for the agents this workspace exposes. + const catalog = this.providerRef.deref()?.getSubagentRegistry?.()?.getCatalog() ?? [] + allTools = describeAvailableSubagents(allTools, catalog) + } + const shouldIncludeTools = allTools.length > 0 // Create an AbortController to allow cancelling the request mid-stream @@ -6177,7 +6580,10 @@ export class Task extends EventEmitter implements TaskLike { } // note that this api_req_failed ask is unique in that we only present this option if the api hasn't streamed any content yet (ie it fails on the first chunk due), as it would allow them to hit a retry button. However if the api failed mid-stream, it could be in any arbitrary state where some tools may have executed, so that error is handled differently and requires cancelling the task entirely. - if (autoApprovalEnabled) { + // A headless child never auto-retries a first-chunk failure: its + // `api_req_failed` ask is terminal, so the failure ends the run + // instead of recursing through an unbounded retry chain. + if (autoApprovalEnabled && !this.subagent) { // Apply shared exponential backoff and countdown UX await this.backoffAndAnnounce(retryAttempt, error) @@ -6202,8 +6608,8 @@ export class Task extends EventEmitter implements TaskLike { ) if (response !== "yesButtonClicked") { - // This will never happen since if noButtonClicked, we will - // clear current task, aborting this instance. + // A user denial clears the current task; a child's terminal + // ask records its reason and the request loop ends on it. throw new Error("API request failed") } diff --git a/src/core/task/__tests__/Task.subagent-max-turns.spec.ts b/src/core/task/__tests__/Task.subagent-max-turns.spec.ts new file mode 100644 index 00000000000..f09f235b98e --- /dev/null +++ b/src/core/task/__tests__/Task.subagent-max-turns.spec.ts @@ -0,0 +1,242 @@ +// npx vitest run core/task/__tests__/Task.subagent-max-turns.spec.ts + +import * as os from "os" +import * as path from "path" + +import type { GlobalState, ProviderSettings, SubagentDefinition } from "@roo-code/types" +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" +import { TelemetryService } from "@roo-code/telemetry" + +import { Task } from "../Task" +import { ClineProvider } from "../../webview/ClineProvider" + +const { mockSaveTaskMessages, mockSaveApiMessages } = vi.hoisted(() => ({ + mockSaveTaskMessages: vi.fn().mockResolvedValue(undefined), + mockSaveApiMessages: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("delay", () => ({ __esModule: true, default: vi.fn().mockResolvedValue(undefined) })) +vi.mock("execa", () => ({ execa: vi.fn() })) +vi.mock("p-wait-for", () => ({ default: vi.fn().mockResolvedValue(undefined) })) + +vi.mock("../../task-persistence", async (importOriginal) => { + const mod = await importOriginal() + return { + ...mod, + saveApiMessages: mockSaveApiMessages, + saveTaskMessages: mockSaveTaskMessages, + TaskHistoryStore: vi.fn().mockImplementation(function () { + return { + initialize: vi.fn().mockResolvedValue(undefined), + dispose: vi.fn(), + get: vi.fn(), + getAll: vi.fn().mockReturnValue([]), + upsert: vi.fn().mockResolvedValue([]), + delete: vi.fn().mockResolvedValue(undefined), + deleteMany: vi.fn().mockResolvedValue(undefined), + reconcile: vi.fn().mockResolvedValue(undefined), + initialized: Promise.resolve(), + } + }), + } +}) + +vi.mock("../../mentions", () => ({ + parseMentions: vi + .fn() + .mockImplementation((text) => + Promise.resolve({ text: `processed: ${text}`, mode: undefined, contentBlocks: [] }), + ), + openMention: vi.fn(), + getLatestTerminalOutput: vi.fn(), +})) + +vi.mock("../../../integrations/misc/extract-text", () => ({ + extractTextFromFile: vi.fn().mockResolvedValue(""), +})) + +vi.mock("../../environment/getEnvironmentDetails", () => ({ + getEnvironmentDetails: vi.fn().mockResolvedValue(""), +})) + +vi.mock("../../ignore/RooIgnoreController") + +vi.mock("../../../utils/storage", () => ({ + getTaskDirectoryPath: vi + .fn() + .mockImplementation((base: string, id: string) => Promise.resolve(`${base}/tasks/${id}`)), + getSettingsDirectoryPath: vi.fn().mockImplementation((base: string) => Promise.resolve(`${base}/settings`)), +})) + +vi.mock("../../../utils/fs", () => ({ + fileExistsAtPath: vi.fn().mockReturnValue(false), +})) + +vi.mock("../../../i18n", () => ({ + t: (key: string) => key, +})) + +const definition: SubagentDefinition = { + name: "explore", + description: "Explores", + systemPrompt: "Explore.", + source: "builtin", + readonly: true, +} + +function makeMockProvider() { + return { + log: vi.fn(), + taskHistoryStore: { get: () => undefined }, + updateTaskHistory: vi.fn().mockResolvedValue([]), + getState: vi.fn().mockResolvedValue({}), + getSkillsManager: vi.fn().mockReturnValue(undefined), + postStateToWebviewWithoutTaskHistory: vi.fn().mockResolvedValue(undefined), + flushPostStateToWebviewThrottled: vi.fn().mockResolvedValue(undefined), + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + postStateToWebview: vi.fn().mockResolvedValue(undefined), + postStateToWebviewThrottled: vi.fn().mockResolvedValue(undefined), + context: { + globalStorageUri: { fsPath: path.join(os.tmpdir(), "test-storage-max-turns") }, + globalState: { + get: vi.fn().mockImplementation((_key: keyof GlobalState) => undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + workspaceState: { + get: vi.fn().mockImplementation(() => undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + secrets: { + get: vi.fn().mockResolvedValue(undefined), + store: vi.fn().mockResolvedValue(undefined), + delete: vi.fn().mockResolvedValue(undefined), + }, + extensionUri: { fsPath: "/mock/extension" }, + extension: { packageJSON: { version: "1.0.0" } }, + }, + } +} + +describe("Task subagent maxTurns", () => { + let mockApiConfig: ProviderSettings + + beforeEach(() => { + vi.clearAllMocks() + mockSaveTaskMessages.mockResolvedValue(undefined) + + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } + + mockApiConfig = { + apiProvider: providerIdentifiers.anthropic, + apiModelId: "claude-3-5-sonnet-20241022", + apiKey: "test-api-key", + } + }) + + function makeTask(maxTurns: number | undefined) { + const mockProvider = makeMockProvider() + + // Double cast: plain object satisfies only the methods called by this code path. + const task = new Task({ + provider: mockProvider as unknown as ClineProvider, + apiConfiguration: mockApiConfig, + task: "child task", + startTask: false, + parentTaskId: "parent-1", + subagent: { runId: "child-1", groupId: "group-1", definition }, + maxTurns, + }) + + vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined) + vi.spyOn(task, "dispose").mockResolvedValue(undefined) + vi.spyOn(task, "abortTask").mockResolvedValue(undefined) + + const requests: number[] = [] + task["attemptApiRequest"] = async function* () { + requests.push(1) + yield { type: "text", text: "I will read the file." } as never + } + + return { task, requests } + } + + it("stops at the cap when a tool turn would start another request", async () => { + const { task, requests } = makeTask(1) + + // Step 1: one API request. Its response continues the stack (the loop asks + // the model for a tool call), and the next pop must stop at the cap. + const result = await task.recursivelyMakeClineRequests([{ type: "text", text: "start" }]) + + expect(result).toBe(true) + expect(task.subagentPartial).toBe(true) + expect(requests).toHaveLength(1) + expect(task.subagentTurnCount).toBe(1) + }) + + it("stops before the first request when the cap is already reached", async () => { + const { task, requests } = makeTask(2) + task.subagentTurnCount = 2 + + await expect(task.recursivelyMakeClineRequests([{ type: "text", text: "start" }])).resolves.toBe(true) + + expect(task.subagentPartial).toBe(true) + expect(requests).toHaveLength(0) + }) + + it("keeps a run without a cap unlimited", async () => { + const { task, requests } = makeTask(0) + task.subagentTurnCount = 1000 + task.subagentStopRequested = true + + await expect(task.recursivelyMakeClineRequests([{ type: "text", text: "start" }])).resolves.toBe(true) + + // The request ran despite the large turn count, and it completed normally. + expect(requests).toHaveLength(1) + expect(task.subagentPartial).toBe(false) + expect(task.subagentTurnCount).toBe(1001) + }) + + it.each([ + ["api_req_failed", "rate limited", "The subagent stopped because the API request failed: rate limited"], + ["mistake_limit_reached", undefined, "The subagent stopped after reaching its consecutive mistake limit"], + [ + "auto_approval_max_req_reached", + '{"count":1,"type":"requests"}', + "The subagent stopped after reaching the auto-approval limit", + ], + ] as const)("ends the run on a terminal %s ask", async (type, text, reason) => { + const { task } = makeTask(0) + + const answer = await task.ask(type, text) + + // Nobody can approve or retry for a child, so the ask denies and records + // why the run must stop. + expect(answer.response).toBe("noButtonClicked") + expect(task.subagentTerminalError).toBe(reason) + }) + + it("stops before the next request once a terminal ask recorded its reason", async () => { + const { task, requests } = makeTask(0) + task.subagentTerminalError = "The subagent stopped after reaching the auto-approval limit" + + await expect(task.recursivelyMakeClineRequests([{ type: "text", text: "start" }])).resolves.toBe(true) + + expect(requests).toHaveLength(0) + }) + + it("stops when the mistake limit ask is terminal for a child", async () => { + const { task, requests } = makeTask(0) + task.consecutiveMistakeLimit = 1 + task.consecutiveMistakeCount = 1 + + await expect(task.recursivelyMakeClineRequests([{ type: "text", text: "start" }])).resolves.toBe(true) + + // The limit ask ends the run before the request it was guarding. + expect(requests).toHaveLength(0) + expect(task.subagentTerminalError).toBe("The subagent stopped after reaching its consecutive mistake limit") + }) +}) diff --git a/src/core/task/__tests__/Task.subagent.spec.ts b/src/core/task/__tests__/Task.subagent.spec.ts new file mode 100644 index 00000000000..510216e4fd7 --- /dev/null +++ b/src/core/task/__tests__/Task.subagent.spec.ts @@ -0,0 +1,311 @@ +// npx vitest run core/task/__tests__/Task.subagent.spec.ts + +import { Anthropic } from "@anthropic-ai/sdk" +import { TelemetryService } from "@roo-code/telemetry" +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" +import type { SubagentDefinition, SubagentRunSnapshot } from "@roo-code/types" + +import { makeExtensionContext, makeUri } from "../../../test-utils/vscode" +import type { AssistantMessageContent } from "../../assistant-message/types" +import type { ClineProvider } from "../../webview/ClineProvider" +import { Task } from "../Task" +import type { SubagentToolOutcome } from "../../subagents/types" + +vi.mock("../../../i18n", () => ({ t: (key: string) => key })) +vi.mock("../../ignore/RooIgnoreController") + +const definition: SubagentDefinition = { + name: "explore", + description: "Explores", + systemPrompt: "Explore.", + source: "builtin", + readonly: true, +} + +function makeProvider(stateOverride: Record = {}) { + const finalizeGroup = vi.fn(async () => undefined) + + const provider = { + log: vi.fn(), + context: makeExtensionContext({ globalStorageUri: makeUri("/mock/global-storage") }), + getState: vi.fn(async () => ({ mode: "code", currentApiConfigName: "default", ...stateOverride })), + getSubagentManager: () => ({ finalizeGroup }), + postMessageToWebview: vi.fn(async () => undefined), + postStateToWebviewThrottled: vi.fn(async () => undefined), + updateTaskHistory: vi.fn(async () => undefined), + taskHistoryStore: { get: vi.fn(() => undefined) }, + } + + return { provider, finalizeGroup } +} + +function makeTask({ headless = false, state = {} }: { headless?: boolean; state?: Record } = {}) { + const { provider, finalizeGroup } = makeProvider(state) + + const task = new Task({ + provider: provider as unknown as ClineProvider, + apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "test-api-key" }, + task: "parent task", + startTask: false, + parentTaskId: "parent-1", + ...(headless ? { subagent: { runId: "child-1", groupId: "group-1", definition }, maxTurns: 5 } : {}), + }) + + return { task, provider, finalizeGroup } +} + +const outcome = (runId: string, overrides: Partial = {}): SubagentToolOutcome => ({ + runId, + agentName: "explore", + status: "completed", + summary: `${runId} summary`, + filesRead: [], + filesModified: [], + toolCallCount: 1, + tokenUsage: { input: 10, output: 5 }, + ...overrides, +}) + +const toolResults = (task: Task) => + task.userMessageContent.filter((block): block is Anthropic.ToolResultBlockParam => block.type === "tool_result") + +describe("Task subagent batch", () => { + beforeEach(() => { + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } + }) + + it("pushes one tool_result per spawn in call order, regardless of completion order", async () => { + const { task, finalizeGroup } = makeTask() + const groupId = task.getSubagentGroupId("tool-1") + const toolResultsBefore = toolResults(task).length + + let resolveFirst!: (value: SubagentToolOutcome) => void + let resolveSecond!: (value: SubagentToolOutcome) => void + + task.registerSubagentCall( + "tool-1", + new Promise((resolve) => { + resolveFirst = resolve + }), + ) + task.registerSubagentCall( + "tool-2", + new Promise((resolve) => { + resolveSecond = resolve + }), + ) + + expect(task.hasQueuedSubagentBatch()).toBe(true) + + const batch = task.runSubagentBatch({ immediate: true }) + resolveSecond(outcome("run-2", { summary: "second finished" })) + resolveFirst(outcome("run-1", { summary: "first finished" })) + await batch + + const results = toolResults(task).slice(toolResultsBefore) + + expect(results.map((result) => result.tool_use_id)).toEqual(["tool-1", "tool-2"]) + expect(results[0].content).toContain("first finished") + expect(results[1].content).toContain("second finished") + expect(task.hasQueuedSubagentBatch()).toBe(false) + expect(task.userMessageContentReady).toBe(true) + expect(task["currentSubagentGroupId"]).toBeUndefined() + expect(finalizeGroup).toHaveBeenCalledWith(groupId) + }) + + it("keeps parent context isolated: only the structured summary reaches the parent turn", async () => { + const { task } = makeTask() + const clineMessagesBefore = task.clineMessages.length + const apiHistoryBefore = [...task.apiConversationHistory] + + task.registerSubagentCall("tool-1", Promise.resolve(outcome("run-1"))) + + await task.runSubagentBatch({ immediate: true }) + + const results = toolResults(task) + + expect(results).toHaveLength(1) + expect(results[0].content).toContain('Subagent "explore" completed') + expect(results[0].content).toContain("run-1 summary") + expect(task.clineMessages).toHaveLength(clineMessagesBefore) + expect(task.apiConversationHistory).toEqual(apiHistoryBefore) + }) + + it("marks a failed run as a tool error and survives a rejected promise", async () => { + const { task } = makeTask() + + task.registerSubagentCall( + "tool-1", + Promise.reject(new Error("runner exploded")) as Promise, + ) + task.registerSubagentCall( + "tool-2", + Promise.resolve(outcome("run-2", { status: "failed", error: "no completion", summary: "" })), + ) + + await task.runSubagentBatch({ immediate: true }) + + const [rejected, failed] = toolResults(task) + + expect(rejected).toMatchObject({ tool_use_id: "tool-1", is_error: true }) + expect(rejected.content).toContain("runner exploded") + expect(failed).toMatchObject({ tool_use_id: "tool-2", is_error: true }) + }) + + it("waits for the assistant turn to finish presenting before settling", async () => { + const { task } = makeTask() + let settled = false + + task.registerSubagentCall("tool-1", Promise.resolve(outcome("run-1"))) + + const batch = task.runSubagentBatch().then(() => { + settled = true + }) + + await new Promise((resolve) => setTimeout(resolve, 5)) + expect(settled).toBe(false) + + task.didCompleteReadingStream = true + task.currentStreamingContentIndex = task.assistantMessageContent.length + await batch + + expect(settled).toBe(true) + expect(task.userMessageContentReady).toBe(true) + }) + + it("releases the turn when a spawn request produced no run", async () => { + const { task, finalizeGroup } = makeTask() + + task.assistantMessageContent = [ + { + type: "tool_use", + id: "tool-1", + name: "spawn_subagent", + params: {}, + partial: false, + } as AssistantMessageContent, + ] + task.didCompleteReadingStream = true + task.currentStreamingContentIndex = 1 + + await task.runSubagentBatch() + + expect(task.userMessageContentReady).toBe(true) + expect(toolResults(task)).toHaveLength(0) + expect(finalizeGroup).not.toHaveBeenCalled() + }) +}) + +describe("Task headless mode", () => { + it("answers a completion_result ask without the webview and flags the stop", async () => { + const { task, provider } = makeTask({ headless: true }) + + const answer = await task.ask("completion_result", "final report") + + expect(answer).toEqual({ response: "yesButtonClicked" }) + expect(task.subagentStopRequested).toBe(true) + expect(provider.postMessageToWebview).not.toHaveBeenCalled() + }) + + it("denies a gated tool ask the policy does not approve (no user to answer)", async () => { + const { task, provider } = makeTask({ headless: true }) + + // Auto-approval is off, so a tool ask resolves to "ask"; a headless run + // has no approver and must deny instead of auto-approving. + await expect(task.ask("tool", "{}")).resolves.toMatchObject({ response: "noButtonClicked" }) + expect(task.subagentStopRequested).toBe(false) + expect(provider.postMessageToWebview).not.toHaveBeenCalled() + }) + + it("approves a gated tool ask when the policy allows it", async () => { + const { task } = makeTask({ headless: true, state: { autoApprovalEnabled: true, alwaysAllowReadOnly: true } }) + const text = JSON.stringify({ tool: "readFile", path: "src/a.ts" }) + + await expect(task.ask("tool", text)).resolves.toMatchObject({ response: "yesButtonClicked" }) + }) + + it("denies a denylisted command ask for a headless run and reports the detail", async () => { + const { task } = makeTask({ + headless: true, + state: { + autoApprovalEnabled: true, + alwaysAllowExecute: true, + allowedCommands: [], + deniedCommands: ["rm -rf"], + }, + }) + + const answer = await task.ask("command", "rm -rf /tmp/x") + + expect(answer).toMatchObject({ response: "noButtonClicked" }) + expect(answer.autoDenyDetail).toMatchObject({ kind: "denylist" }) + }) + + it("denies a protected-file write unless protected writes are auto-approved", async () => { + const { task } = makeTask({ + headless: true, + state: { autoApprovalEnabled: true, alwaysAllowWrite: true, alwaysAllowWriteProtected: false }, + }) + const text = JSON.stringify({ tool: "writeToFile", path: "AGENTS.md" }) + + await expect(task.ask("tool", text, undefined, undefined, true)).resolves.toMatchObject({ + response: "noButtonClicked", + }) + }) + + it("records the final summary when the run says completion_result", async () => { + const { task } = makeTask({ headless: true }) + + await task.say("completion_result", "the report") + + expect(task.subagentSummary).toBe("the report") + }) +}) + +describe("Task#updateSubagentGroupMessage", () => { + it("writes the final runs onto the leader spawn row only", async () => { + const { task } = makeTask() + + const leader = { + type: "say" as const, + say: "tool" as const, + ts: 1, + text: JSON.stringify({ tool: "spawnSubagent", runId: "group-1", groupId: "group-1" }), + } + const follower = { + type: "say" as const, + say: "tool" as const, + ts: 2, + text: JSON.stringify({ tool: "spawnSubagent", runId: "run-2", groupId: "group-1" }), + } + task.clineMessages.push(leader, follower) + + const runs: SubagentRunSnapshot[] = [ + { + runId: "run-1", + parentTaskId: "parent-1", + toolUseId: "run-1", + groupId: "group-1", + agentName: "explore", + description: "Explore", + modelId: "inherit", + status: "completed", + startedAt: 1, + toolCallCount: 0, + tokenUsage: { input: 0, output: 0 }, + filesRead: [], + filesModified: [], + }, + ] + + await task.updateSubagentGroupMessage("group-1", runs) + + const leaderText = JSON.parse(leader.text) as { runs?: SubagentRunSnapshot[] } + const followerText = JSON.parse(follower.text) as { runs?: SubagentRunSnapshot[] } + + expect(leaderText.runs).toEqual(runs) + expect(followerText.runs).toBeUndefined() + }) +}) diff --git a/src/core/task/build-tools.ts b/src/core/task/build-tools.ts index c5ee7a163ce..be2bd80ea9a 100644 --- a/src/core/task/build-tools.ts +++ b/src/core/task/build-tools.ts @@ -25,6 +25,8 @@ interface BuildToolsOptions { apiConfiguration: ProviderSettings | undefined disabledTools?: string[] modelInfo?: ModelInfo + /** Native subagent tooling is opt-in. */ + subagentsEnabled?: boolean /** * If true, returns all tools without mode filtering, but also includes * the list of allowed tool names for use with allowedFunctionNames. @@ -88,6 +90,7 @@ export async function buildNativeToolsArrayWithRestrictions(options: BuildToolsO apiConfiguration, disabledTools, modelInfo, + subagentsEnabled, includeAllToolsWithRestrictions, } = options @@ -102,6 +105,7 @@ export async function buildNativeToolsArrayWithRestrictions(options: BuildToolsO todoListEnabled: apiConfiguration?.todoListEnabled ?? true, disabledTools, modelInfo, + subagentsEnabled, } // Check if the model supports images for read_file tool description. @@ -178,3 +182,33 @@ export async function buildNativeToolsArrayWithRestrictions(options: BuildToolsO tools: filteredTools, } } + +/** + * Replaces the `spawn_subagent` description with one that lists the agents + * available in this workspace. Only names and one-line descriptions are added, + * so the parent's prompt cost stays bounded. + */ +export function describeAvailableSubagents( + tools: OpenAI.Chat.ChatCompletionTool[], + agents: Array<{ name: string; description: string }>, +): OpenAI.Chat.ChatCompletionTool[] { + if (agents.length === 0) { + return tools + } + + const catalog = agents.map((agent) => `- ${agent.name}: ${agent.description}`).join("\n") + + return tools.map((tool) => { + if (!("function" in tool) || tool.function?.name !== "spawn_subagent") { + return tool + } + + return { + ...tool, + function: { + ...tool.function, + description: `${tool.function.description}\n\nAvailable agents:\n${catalog}`, + }, + } + }) +} diff --git a/src/core/tools/SubagentTool.ts b/src/core/tools/SubagentTool.ts new file mode 100644 index 00000000000..c91ebcdd786 --- /dev/null +++ b/src/core/tools/SubagentTool.ts @@ -0,0 +1,130 @@ +import crypto from "crypto" + +import type { SubagentSpawnRequest } from "../subagents/types" +import type { SpawnSubagentParams as ManagerSpawnParams } from "../subagents/SubagentManager" + +import { Task } from "../task/Task" +import { BaseTool, ToolCallbacks } from "./BaseTool" +import type { ToolUse } from "../../shared/tools" +import { formatResponse } from "../prompts/responses" +import { sanitizeToolUseId } from "../../utils/tool-id" + +interface SpawnSubagentToolParams { + agent: string + description: string + prompt: string + model?: string + isolation?: "none" | "worktree" +} + +/** + * `spawn_subagent` starts one headless child and returns immediately. + * + * The parent's tool_result stays open until `Task#runSubagentBatch` collects + * every spawn of the turn, so the child's output never enters this + * conversation directly. + */ +export class SubagentTool extends BaseTool<"spawn_subagent"> { + readonly name = "spawn_subagent" as const + + async execute(params: SpawnSubagentToolParams, task: Task, callbacks: ToolCallbacks): Promise { + const { agent, description, prompt, model, isolation } = params + const { pushToolResult, toolCallId } = callbacks + + if (task.subagent) { + // Flat two-level hierarchy: a child can never spawn another child. + pushToolResult(formatResponse.toolError("A subagent cannot spawn another subagent.")) + return + } + + if (!agent || !description || !prompt) { + task.consecutiveMistakeCount++ + task.recordToolError("spawn_subagent") + const missing = !agent ? "agent" : !description ? "description" : "prompt" + pushToolResult(await task.sayAndCreateMissingParamError("spawn_subagent", missing)) + return + } + + const provider = task.providerRef.deref() + + if (!provider) { + pushToolResult(formatResponse.toolError("Provider reference lost")) + return + } + + // The prompt omits the tool when the feature is off; enforce the same + // flag at execution so a hallucinated call cannot start a child run. + if (provider.contextProxy?.getValue("subagentsEnabled") !== true) { + pushToolResult(formatResponse.toolError("Subagents are disabled. Turn them on in Settings > Subagents.")) + return + } + + const manager = provider.getSubagentManager?.() + const registry = provider.getSubagentRegistry?.() + + if (!manager || !registry) { + pushToolResult(formatResponse.toolError("Subagents are not available in this window.")) + return + } + + const definition = registry.get(agent) + + if (!definition) { + task.consecutiveMistakeCount++ + task.recordToolError("spawn_subagent") + const available = registry + .getAll() + .map(({ name }) => name) + .join(", ") + pushToolResult( + formatResponse.toolError(`Unknown subagent "${agent}". Available agents: ${available || "(none)"}.`), + ) + return + } + + // The run id doubles as the child's storage directory name, history row id + // and worktree path segment. Provider tool-call ids repeat across + // requests (native Ollama restarts its index at zero), so a random suffix + // keeps every spawn distinct. The tool-use id stays the provider's value + // for result pairing. + const runId = sanitizeToolUseId(`${toolCallId}-${crypto.randomUUID()}`) + const groupId = task.getSubagentGroupId(runId) + const request: SubagentSpawnRequest = { agent, description, prompt, model, isolation } + + const spawnParams: ManagerSpawnParams = { + parentTask: task, + definition, + request, + runId, + groupId, + toolUseId: toolCallId, + } + + const promise = manager.spawn(spawnParams) + task.registerSubagentCall(toolCallId, promise) + task.consecutiveMistakeCount = 0 + + // Only the leader row renders, and it renders the whole group card. + // A row per spawn would leave an empty block for every follower. + if (runId === groupId) { + await task.say( + "tool", + JSON.stringify({ + tool: "spawnSubagent", + runId, + groupId, + agentName: definition.name, + modelId: request.model ?? definition.model ?? "inherit", + runStatus: "queued", + }), + ) + } + } + + override async handlePartial(_task: Task, _block: ToolUse<"spawn_subagent">): Promise { + // The group card appears once the complete call is dispatched; partial + // spawns would create duplicate rows for one run. + } +} + +export const subagentTool = new SubagentTool() diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 32714067fa2..ef528449ee0 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -71,6 +71,8 @@ import { ORGANIZATION_ALLOW_ALL, DEFAULT_MODES, DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, + DEFAULT_MAX_CONCURRENT_SUBAGENTS, + DEFAULT_SUBAGENT_MAX_TURNS, getModelId, isRetiredProvider, modelIdKeys, @@ -137,6 +139,8 @@ import { withoutInvalidDisplaySettings } from "../config/displaySettings" import { ProviderSettingsManager } from "../config/ProviderSettingsManager" import { CustomModesManager } from "../config/CustomModesManager" import { PendingActionSettlementError, Task } from "../task/Task" +import { SubagentManager } from "../subagents/SubagentManager" +import { SubagentRegistry } from "../subagents/SubagentRegistry" import { webviewMessageHandler } from "./webviewMessageHandler" import type { WebviewFocusTracker } from "./WebviewFocusTracker" @@ -330,6 +334,10 @@ export class ClineProvider private recentTasksCache?: string[] public readonly taskHistoryStore: TaskHistoryStore + + /** Lazily created native-subagent registry and run manager for this window. */ + private subagentRegistryInstance?: SubagentRegistry + private subagentManagerInstance?: SubagentManager private readonly taskTitleService: TaskTitleService private taskHistoryStoreInitialized = false public static readonly PENDING_OPERATION_TIMEOUT_MS = 30000 // 30 seconds @@ -808,6 +816,18 @@ export class ClineProvider public async evictCurrentTask(): Promise { const current = this.getCurrentTask() const storedHistory = current ? this.taskHistoryStore.get(current.taskId) : undefined + if (current) { + // The task we are leaving is removed from the stack but its headless + // subagents would otherwise keep running. Cancel and persist them so + // they stop and no longer show as "running" after a new task / switch. + // Guard the manager because test stubs implement this method without + // constructing a SubagentManager. + try { + await this.getSubagentManager?.().cancelAllForParent(current.taskId) + } catch { + // A closed manager or failing store must not block the switch. + } + } await this.removeClineFromStack() if (storedHistory?.status === "active" && storedHistory.parentTaskId) { await this.markDelegatedChildInterrupted({ @@ -1061,6 +1081,10 @@ export class ClineProvider await this.marketplaceManager?.cleanup() this.customModesManager?.dispose() this.taskTitleService.dispose() + this.subagentManagerInstance?.dispose() + this.subagentManagerInstance = undefined + this.subagentRegistryInstance?.dispose() + this.subagentRegistryInstance = undefined this.taskHistoryStore.dispose() this.log("Disposed all disposables") ClineProvider.activeInstances.delete(this) @@ -2984,6 +3008,36 @@ export class ClineProvider await collectChildIds(id) } + // Hidden subagent transcripts are stored as history rows owned by the + // task that spawned them. They are not delegated children, so collect + // them separately to avoid orphaning their rows and directories. + const deleting = new Set(allIdsToDelete) + + try { + for (const item of this.taskHistoryStore.getAll()) { + const parentTaskId = item.subagent?.parentTaskId + + if (parentTaskId && deleting.has(parentTaskId) && !deleting.has(item.id)) { + deleting.add(item.id) + allIdsToDelete.push(item.id) + } + } + } catch (error) { + // Row enumeration is best-effort; a store that cannot enumerate + // rows must never abort deleting the directly targeted tasks. + console.error( + `[deleteTaskWithId${id}] failed to collect owned subagent rows: ${ + error instanceof Error ? error.message : String(error) + }`, + ) + } + + // Stop any child that is still running; its storage disappears below. + for (const taskId of allIdsToDelete) { + await this.subagentManagerInstance?.cancelAllForParent(taskId) + this.subagentManagerInstance?.clearStateForParent(taskId) + } + // Remove from stack if any of the tasks to delete are in the current task stack for (const taskId of allIdsToDelete) { if (taskId === this.getCurrentTask()?.taskId) { @@ -3274,6 +3328,9 @@ export class ClineProvider maxOpenTabsContext, maxWorkspaceFiles, disabledTools, + subagentsEnabled, + maxConcurrentSubagents, + defaultSubagentMaxTurns, telemetrySetting, showRooIgnoredFiles, enableSubfolderRules, @@ -3416,7 +3473,7 @@ export class ClineProvider currentTaskTodos: currentTask?.todoList || [], messageQueue: currentTask?.messageQueueService?.messages, taskHistory: includeTaskHistory - ? this.taskHistoryStore.getAll().filter((item: HistoryItem) => item.ts && item.task) + ? this.getVisibleTaskHistory().filter((item: HistoryItem) => item.ts && item.task) : [], soundEnabled: soundEnabled ?? false, ttsEnabled: ttsEnabled ?? false, @@ -3457,6 +3514,9 @@ export class ClineProvider maxWorkspaceFiles: maxWorkspaceFiles ?? 200, cwd, disabledTools, + subagentsEnabled: subagentsEnabled ?? false, + maxConcurrentSubagents: maxConcurrentSubagents ?? DEFAULT_MAX_CONCURRENT_SUBAGENTS, + defaultSubagentMaxTurns: defaultSubagentMaxTurns ?? DEFAULT_SUBAGENT_MAX_TURNS, telemetrySetting, telemetryKey, machineId, @@ -3661,7 +3721,7 @@ export class ClineProvider allowedMaxCost: stateValues.allowedMaxCost, autoCondenseContext: stateValues.autoCondenseContext ?? true, autoCondenseContextPercent: stateValues.autoCondenseContextPercent ?? 100, - taskHistory: includeTaskHistory ? this.taskHistoryStore.getAll() : [], + taskHistory: includeTaskHistory ? this.getVisibleTaskHistory() : [], allowedCommands: stateValues.allowedCommands, deniedCommands: stateValues.deniedCommands, soundEnabled: stateValues.soundEnabled ?? false, @@ -3701,6 +3761,9 @@ export class ClineProvider maxOpenTabsContext: stateValues.maxOpenTabsContext ?? 20, maxWorkspaceFiles: stateValues.maxWorkspaceFiles ?? 200, disabledTools: stateValues.disabledTools, + subagentsEnabled: stateValues.subagentsEnabled ?? false, + maxConcurrentSubagents: stateValues.maxConcurrentSubagents ?? DEFAULT_MAX_CONCURRENT_SUBAGENTS, + defaultSubagentMaxTurns: stateValues.defaultSubagentMaxTurns ?? DEFAULT_SUBAGENT_MAX_TURNS, telemetrySetting: stateValues.telemetrySetting || "unset", showRooIgnoredFiles: stateValues.showRooIgnoredFiles ?? false, enableSubfolderRules: stateValues.enableSubfolderRules ?? false, @@ -3807,7 +3870,7 @@ export class ClineProvider // Sort and filter the history the same way as getStateToPostToWebview const sortedHistory = taskHistory - .filter((item: HistoryItem) => item.ts && item.task) + .filter((item: HistoryItem) => !item.subagent && item.ts && item.task) .sort((a: HistoryItem, b: HistoryItem) => b.ts - a.ts) await this.postMessageToWebview({ @@ -3816,6 +3879,14 @@ export class ClineProvider }) } + /** + * History rows the user sees. A headless subagent transcript stays on disk + * for the inspector, but it is not a user task and never joins the list. + */ + private getVisibleTaskHistory(): HistoryItem[] { + return this.taskHistoryStore.getAll().filter((item) => !item.subagent) + } + // ContextProxy // @deprecated - Use `ContextProxy#setValue` instead. @@ -4353,6 +4424,10 @@ export class ClineProvider const workspaceTasks: HistoryItem[] = [] for (const item of history) { + if (item.subagent) { + continue + } + if (!item.ts || !item.task || item.workspace !== this.cwd) { continue } @@ -4504,6 +4579,39 @@ export class ClineProvider return task } + /** + * Returns the workspace's subagent registry, creating it on first use. + * Builtins are available synchronously; project and user agent files load + * in the background and replace builtins as they arrive. + */ + public getSubagentRegistry(): SubagentRegistry { + if (!this.subagentRegistryInstance) { + const cwd = this.currentWorkspacePath || getWorkspacePath() || process.cwd() + const registry = new SubagentRegistry({ + cwd, + onWarning: (message) => this.log(`[subagents] ${message}`), + }) + this.subagentRegistryInstance = registry + void registry.load().catch((error) => { + this.log( + `[subagents] failed to load agent definitions: ${error instanceof Error ? error.message : String(error)}`, + ) + }) + } + + return this.subagentRegistryInstance + } + + /** Returns this window's subagent run manager, creating it on first use. */ + public getSubagentManager(): SubagentManager { + this.subagentManagerInstance ??= new SubagentManager({ + provider: this, + log: (message) => this.log(message), + }) + + return this.subagentManagerInstance + } + public async cancelTask(): Promise { const task = this.getCurrentTask() @@ -4538,6 +4646,9 @@ export class ClineProvider // Mark this as a user-initiated cancellation so provider-only rehydration can occur task.setAbortReason("user_cancelled") + // Stop every headless child of this task before the parent unwinds. + await this.getSubagentManager().cancelAllForParent(task.taskId) + // Capture the current instance to detect if rehydrate already occurred elsewhere const originalInstanceId = task.instanceId diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index b364b5baa79..f672ea314fb 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -4,6 +4,7 @@ import fs from "fs" import fsPromises from "fs/promises" import * as path from "path" import { TaskRegistry } from "../../task/TaskRegistry" +import { SubagentManager } from "../../subagents/SubagentManager" import Anthropic from "@anthropic-ai/sdk" import * as vscode from "vscode" @@ -21,6 +22,8 @@ import { ORGANIZATION_ALLOW_ALL, DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, DEFAULT_DIFF_FUZZY_THRESHOLD, + DEFAULT_MAX_CONCURRENT_SUBAGENTS, + DEFAULT_SUBAGENT_MAX_TURNS, DEFAULT_WRITE_DELAY_MS, providerIdentifiers, openAiModelInfoSaneDefaults, @@ -619,6 +622,21 @@ describe("ClineProvider", () => { expect(provider.workspacePath).toBeUndefined() }) + test("evictCurrentTask cancels and persists the leaving task's subagents", async () => { + const leavingTask = new Task({ ...defaultTaskOptions }) + provider["taskRegistry"].push(leavingTask) + const cancelAll = vi.fn().mockResolvedValue(undefined) + vi.spyOn(provider, "getSubagentManager").mockReturnValue({ + cancelAllForParent: cancelAll, + } as unknown as SubagentManager) + + await provider.evictCurrentTask() + + expect(provider.getSubagentManager()).toBeDefined() + expect(cancelAll).toHaveBeenCalledTimes(1) + expect(cancelAll).toHaveBeenCalledWith(leavingTask.taskId) + }) + test("constructor initializes correctly", () => { expect(provider).toBeInstanceOf(ClineProvider) // Since getVisibleInstance returns the last instance where view.visible is true @@ -4242,6 +4260,71 @@ describe("ClineProvider", () => { expect(state).toHaveProperty("writeDelayMs") }) + test("returns subagent settings to the webview with defaults, then the saved values", async () => { + await provider.resolveWebviewView(mockWebviewView) + + const initial = await provider.getStateToPostToWebview() + expect(initial.subagentsEnabled).toBe(false) + expect(initial.maxConcurrentSubagents).toBe(DEFAULT_MAX_CONCURRENT_SUBAGENTS) + expect(initial.defaultSubagentMaxTurns).toBe(DEFAULT_SUBAGENT_MAX_TURNS) + + await provider.contextProxy.setValue("subagentsEnabled", true) + await provider.contextProxy.setValue("maxConcurrentSubagents", 6) + await provider.contextProxy.setValue("defaultSubagentMaxTurns", 30) + + const saved = { subagentsEnabled: true, maxConcurrentSubagents: 6, defaultSubagentMaxTurns: 30 } + expect(await provider.getStateToPostToWebview()).toMatchObject(saved) + expect(await provider.getState()).toMatchObject(saved) + }) + + test("preserves an unlimited (0) default maxTurns through save and load", async () => { + await provider.resolveWebviewView(mockWebviewView) + + await provider.contextProxy.setValue("defaultSubagentMaxTurns", 0) + + expect(await provider.getStateToPostToWebview()).toMatchObject({ defaultSubagentMaxTurns: 0 }) + expect(await provider.getState()).toMatchObject({ defaultSubagentMaxTurns: 0 }) + }) + + test("keeps headless subagent transcripts out of the webview task history", async () => { + await provider.resolveWebviewView(mockWebviewView) + + const baseHistoryItem = { + number: 1, + ts: Date.now(), + tokensIn: 0, + tokensOut: 0, + totalCost: 0, + } + + const getAll = vi.spyOn(provider.taskHistoryStore, "getAll").mockReturnValue([ + { ...baseHistoryItem, id: "parent-task", task: "Parent task" }, + { + ...baseHistoryItem, + id: "run-1", + task: "Child prompt", + parentTaskId: "parent-task", + subagent: { + runId: "run-1", + groupId: "group-1", + parentTaskId: "parent-task", + agentName: "explore", + status: "completed", + }, + }, + ]) + + try { + const posted = await provider.getStateToPostToWebview() + expect(posted.taskHistory?.map((item) => item.id)).toEqual(["parent-task"]) + + const state = await provider.getState() + expect(state.taskHistory.map((item) => item.id)).toEqual(["parent-task"]) + } finally { + getAll.mockRestore() + } + }) + test("getState and getStateToPostToWebview return the complete NanoGPT configuration", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setProviderSettings({ diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index e16badb3482..cde491aab89 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -2,6 +2,7 @@ import { WebviewFocusTracker } from "../WebviewFocusTracker" // pnpm --filter roo-cline test core/webview/__tests__/ClineProvider.taskHistory.spec.ts import * as vscode from "vscode" +import * as fs from "fs/promises" import { makeCompositeDisposable } from "../../../test-utils/vscode" import type { HistoryItem } from "@roo-code/types" import { providerIdentifiers, RooCodeEventName } from "@roo-code/types" @@ -11,6 +12,7 @@ import { ContextProxy } from "../../config/ContextProxy" import { Task } from "../../task/Task" import { ProfileValidator } from "../../../shared/ProfileValidator" import { ClineProvider } from "../ClineProvider" +import type { SubagentManager } from "../../subagents/SubagentManager" import { safeWriteJson } from "../../../utils/safeWriteJson" import { ShadowCheckpointService } from "../../../services/checkpoints/ShadowCheckpointService" @@ -20,16 +22,21 @@ vi.mock("p-wait-for", () => ({ default: vi.fn().mockResolvedValue(undefined), })) -vi.mock("fs/promises", () => ({ - mkdir: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(""), - readdir: vi.fn().mockResolvedValue([]), - unlink: vi.fn().mockResolvedValue(undefined), - rmdir: vi.fn().mockResolvedValue(undefined), - access: vi.fn().mockResolvedValue(undefined), - rm: vi.fn().mockResolvedValue(undefined), -})) +vi.mock("fs/promises", () => { + const mockedFs = { + mkdir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), + readFile: vi.fn().mockResolvedValue(""), + readdir: vi.fn().mockResolvedValue([]), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), + access: vi.fn().mockResolvedValue(undefined), + rm: vi.fn().mockResolvedValue(undefined), + } + // `ClineProvider` imports the default export; mirror the named exports on it + // so the mocked `rm` is the one the directory-cleanup path calls. + return { ...mockedFs, default: mockedFs } +}) vi.mock("axios", () => ({ default: { @@ -1320,4 +1327,132 @@ describe("ClineProvider Task History Synchronization", () => { }, ) }) + + describe("deleteTaskWithId", () => { + it("waits for an active child run to settle before rows and directories are removed", async () => { + await provider.updateTaskHistory(createHistoryItem({ id: "live-parent", task: "Parent" }), { + broadcast: false, + }) + const subagentMeta = { + runId: "live-run", + groupId: "live-parent", + parentTaskId: "live-parent", + agentName: "explore", + } + const child = createHistoryItem({ + id: "live-run", + task: "Active run", + parentTaskId: "live-parent", + subagent: subagentMeta, + }) + await provider.updateTaskHistory(child, { broadcast: false }) + + const order: string[] = [] + // The double provides the two members deleteTaskWithId calls. + provider["subagentManagerInstance"] = { + cancelAllForParent: vi.fn(async () => { + order.push("cancel") + // The child's own final save lands while the parent awaits it. + await provider.updateTaskHistory( + { ...child, subagent: { ...subagentMeta, status: "cancelled" } }, + { broadcast: false }, + ) + order.push("settled") + }), + clearStateForParent: vi.fn(() => { + order.push("clear") + }), + } as unknown as SubagentManager + + vi.spyOn(ShadowCheckpointService, "deleteTask").mockResolvedValue(undefined) + const removeRows = provider.taskHistoryStore.deleteMany.bind(provider.taskHistoryStore) + vi.spyOn(provider.taskHistoryStore, "deleteMany").mockImplementation(async (ids) => { + order.push("deleteMany") + await removeRows(ids) + }) + vi.mocked(fs.rm).mockImplementation(async () => { + order.push("rm") + }) + + try { + await provider.deleteTaskWithId("live-parent") + } finally { + vi.mocked(fs.rm).mockResolvedValue(undefined) + } + + expect(provider.taskHistoryStore.get("live-parent")).toBeUndefined() + expect(provider.taskHistoryStore.get("live-run")).toBeUndefined() + // The rows and the directory go only after the run settled; the + // directory goes last so nothing can write into it again. + expect(order.indexOf("settled")).toBeLessThan(order.indexOf("deleteMany")) + expect(order.indexOf("deleteMany")).toBeLessThan(order.indexOf("rm")) + expect(vi.mocked(fs.rm)).toHaveBeenCalledWith("/test/task/path", { recursive: true, force: true }) + }) + + it("deletes hidden subagent transcripts owned by the deleted task", async () => { + await provider.updateTaskHistory(createHistoryItem({ id: "agent-parent", task: "Parent" }), { + broadcast: false, + }) + await provider.updateTaskHistory( + createHistoryItem({ + id: "agent-run", + task: "Subagent run", + parentTaskId: "agent-parent", + subagent: { + runId: "agent-run", + groupId: "agent-run", + parentTaskId: "agent-parent", + agentName: "explore", + status: "completed", + }, + }), + { broadcast: false }, + ) + + vi.spyOn(ShadowCheckpointService, "deleteTask").mockResolvedValue(undefined) + const deleteMany = vi.spyOn(provider.taskHistoryStore, "deleteMany") + + await provider.deleteTaskWithId("agent-parent") + + expect(deleteMany).toHaveBeenCalledOnce() + expect(deleteMany.mock.calls[0]?.[0]).toEqual(expect.arrayContaining(["agent-parent", "agent-run"])) + expect(provider.taskHistoryStore.get("agent-run")).toBeUndefined() + }) + + it("deletes the targeted task when subagent row enumeration throws", async () => { + await provider.updateTaskHistory(createHistoryItem({ id: "enum-parent", task: "Parent" }), { + broadcast: false, + }) + + vi.spyOn(ShadowCheckpointService, "deleteTask").mockResolvedValue(undefined) + // The in-memory store cannot throw on its own, so force the failure + // path the best-effort enumeration guard exists for. The final state + // post reads the store again, so it is stubbed for this test. + const getAll = vi.spyOn(provider.taskHistoryStore, "getAll").mockImplementation(() => { + throw new Error("cache unavailable") + }) + vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined) + const deleteMany = vi.spyOn(provider.taskHistoryStore, "deleteMany") + const cancelAllForParent = vi.fn(async () => undefined) + const clearStateForParent = vi.fn() + provider["subagentManagerInstance"] = { + cancelAllForParent, + clearStateForParent, + } as unknown as SubagentManager + const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}) + + try { + await expect(provider.deleteTaskWithId("enum-parent")).resolves.toBeUndefined() + } finally { + consoleError.mockRestore() + } + + expect(getAll).toHaveBeenCalled() + // The directly targeted task is still cancelled, cleared and deleted. + expect(cancelAllForParent).toHaveBeenCalledWith("enum-parent") + expect(clearStateForParent).toHaveBeenCalledWith("enum-parent") + expect(deleteMany).toHaveBeenCalledExactlyOnceWith(["enum-parent"]) + expect(provider.taskHistoryStore.get("enum-parent")).toBeUndefined() + }) + }) }) diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6641ff259f1..beec4ee8dfa 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -4478,6 +4478,13 @@ export const webviewMessageHandler = async ( break } + case "cancelSubagent": { + if (message.runId) { + provider.getSubagentManager().cancel(message.runId) + } + break + } + default: { // console.log(`Unhandled message type: ${message.type}`) // diff --git a/src/shared/tools.ts b/src/shared/tools.ts index ba799efe9c6..92427d1ff84 100644 --- a/src/shared/tools.ts +++ b/src/shared/tools.ts @@ -106,6 +106,13 @@ export const toolParamNames = [ "timeout", // execute_command parameter "artifact_id", // read_command_output parameter "search", // read_command_output parameter for grep-like search + // spawn_subagent parameters + "agent", + "description", + "prompt", + "model", + "isolation", + "run_id", "offset", // read_command_output and read_file parameter "limit", // read_command_output and read_file parameter // read_file indentation mode parameters @@ -146,6 +153,13 @@ export type NativeToolArgs = { } codebase_search: { query: string; path?: string } generate_image: GenerateImageParams + spawn_subagent: { + agent: string + description: string + prompt: string + model?: string + isolation?: "none" | "worktree" + } run_slash_command: { command: string; args?: string } skill: { skill: string; args?: string } search_files: { path: string; regex: string; file_pattern?: string | null } @@ -226,7 +240,7 @@ export const TOOL_GROUPS: Record = { tools: ["use_mcp_tool", "access_mcp_resource"], }, modes: { - tools: ["switch_mode", "new_task"], + tools: ["switch_mode", "new_task", "spawn_subagent"], alwaysAvailable: true, }, } @@ -240,6 +254,7 @@ export const ALWAYS_AVAILABLE_TOOLS: ToolName[] = [ "update_todo_list", "run_slash_command", "skill", + "spawn_subagent", ] as const /** diff --git a/webview-ui/playwright/gallery/stories.tsx b/webview-ui/playwright/gallery/stories.tsx index b0e7fcc1449..c2daacfc1cd 100644 --- a/webview-ui/playwright/gallery/stories.tsx +++ b/webview-ui/playwright/gallery/stories.tsx @@ -537,6 +537,20 @@ export const stories: Record = { await import("@/components/settings/__tests__/ExperimentalSettings.visual.fixture") return }, + "subagent-group-card": async () => { + const { SubagentGroupCardStory } = await import("@/components/chat/__tests__/SubagentGroupCard.visual.fixture") + return + }, + "subagent-activity-feed": async () => { + const { SubagentActivityFeedStory } = + await import("@/components/chat/__tests__/SubagentActivityFeed.visual.fixture") + return + }, + "subagent-header-chip": async () => { + const { SubagentHeaderChipStory } = + await import("@/components/chat/__tests__/SubagentHeaderChip.visual.fixture") + return + }, "ui-settings-long-locale": async () => { const { UISettingsStory } = await import("@/components/settings/__tests__/UISettings.visual.fixture") return diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index 47e8bf1f783..a55088f8da4 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -47,6 +47,7 @@ import { BatchDiffApproval } from "./BatchDiffApproval" import { ProgressIndicator } from "./ProgressIndicator" import { Markdown } from "./Markdown" import { CommandExecution } from "./CommandExecution" +import { SubagentGroupCard } from "./SubagentGroupCard" import { CommandExecutionError } from "./CommandExecutionError" import { AutoApprovedRequestLimitWarning } from "./AutoApprovedRequestLimitWarning" import { InProgressRow, CondensationResultRow, CondensationErrorRow, TruncationResultRow } from "./context-management" @@ -1492,6 +1493,15 @@ export const ChatRowContent = ({ if (!sayTool) return null switch (sayTool.tool) { + case "spawnSubagent": { + // Every spawn of a turn shares a group id; only the leader + // row (the first spawn) renders the group card. + if (!sayTool.groupId || sayTool.runId !== sayTool.groupId) { + return null + } + + return + } case "runSlashCommand": { const slashCommandInfo = sayTool return ( diff --git a/webview-ui/src/components/chat/SubagentActivityFeed.tsx b/webview-ui/src/components/chat/SubagentActivityFeed.tsx new file mode 100644 index 00000000000..24e16566ca3 --- /dev/null +++ b/webview-ui/src/components/chat/SubagentActivityFeed.tsx @@ -0,0 +1,80 @@ +import { useEffect, useMemo, useRef } from "react" +import { BookOpen, Braces, CheckCircle2, FileEdit, FolderSearch, Search, Terminal } from "lucide-react" + +import type { SubagentToolActivity } from "@roo-code/types" + +import { useAppTranslation } from "@src/i18n/TranslationContext" + +function actionIcon(tool: string) { + switch (tool) { + case "read_file": + return + case "search_files": + return + case "list_files": + return + case "codebase_search": + return + case "execute_command": + return + case "write_to_file": + case "apply_diff": + case "edit": + case "search_and_replace": + case "edit_file": + case "apply_patch": + return + case "attempt_completion": + return + default: + return + } +} + +/** + * Collapsible rolling log of a subagent's recent tool calls. Renders only the + * structural activity (tool + short label + path), never tool output, so the + * strict context-isolation contract holds. + */ +export const SubagentActivityFeed = ({ activity }: { activity: SubagentToolActivity[] }) => { + const { t } = useAppTranslation() + const scrollRef = useRef(null) + + useEffect(() => { + const el = scrollRef.current + if (el) { + el.scrollTop = el.scrollHeight + } + }, [activity.length]) + + const rows = useMemo( + () => + activity.map((a) => { + const label = a.labelKey ? t(`chat:subagents.actions.${a.labelKey}`) : a.tool + return { a, label } + }), + [activity, t], + ) + + if (activity.length === 0) { + return
{t("chat:subagents.noActivity")}
+ } + + return ( +
+
    + {rows.map(({ a, label }) => ( +
  1. + {actionIcon(a.tool)} + + {label} + {a.path ? · {a.path} : null} + +
  2. + ))} +
+
+ ) +} diff --git a/webview-ui/src/components/chat/SubagentGroupCard.tsx b/webview-ui/src/components/chat/SubagentGroupCard.tsx new file mode 100644 index 00000000000..527ac031ab9 --- /dev/null +++ b/webview-ui/src/components/chat/SubagentGroupCard.tsx @@ -0,0 +1,308 @@ +import { useCallback, useEffect, useMemo, useState } from "react" +import { useEvent } from "react-use" +import { useAppTranslation } from "@src/i18n/TranslationContext" +import { Ban, CheckCircle2, ChevronDown, ChevronRight, Loader2, MonitorPlay } from "lucide-react" + +import type { ExtensionMessage, SubagentRunSnapshot, SubagentStatus } from "@roo-code/types" + +import { vscode } from "@src/utils/vscode" +import { cn } from "@src/lib/utils" + +import { Button, StandardTooltip } from "@src/components/ui" +import { SubagentActivityFeed } from "./SubagentActivityFeed" +import { SubagentLiveViewer } from "./SubagentLiveViewer" + +/** + * Latest group snapshot for every group seen in this webview session. + * + * A card can mount after the extension already sent updates (for example when + * the chat list virtualizes), so it recovers from this cache first and then + * follows the live stream. + */ +const groupCache = new Map() + +function statusTone(status: SubagentStatus): string { + switch (status) { + case "completed": + return "text-green-600" + case "failed": + return "text-red-600" + case "cancelled": + return "text-vscode-descriptionForeground" + case "running": + return "text-yellow-600" + default: + return "text-vscode-descriptionForeground" + } +} + +function isTerminal(status: SubagentStatus): boolean { + return status === "completed" || status === "failed" || status === "cancelled" +} + +function mergeRuns(current: SubagentRunSnapshot[], next: SubagentRunSnapshot[]): SubagentRunSnapshot[] { + const byId = new Map(current.map((run) => [run.runId, run])) + for (const run of next) { + byId.set(run.runId, { ...byId.get(run.runId), ...run }) + } + + // Preserve the order the runs were announced in; new runs append. + const order = [...current.map((run) => run.runId)] + for (const run of next) { + if (!order.includes(run.runId)) { + order.push(run.runId) + } + } + + return order.map((runId) => byId.get(runId)!).filter(Boolean) +} + +export interface SubagentGroupCardProps { + groupId: string + initialRuns?: SubagentRunSnapshot[] +} + +export const SubagentGroupCard = ({ groupId, initialRuns }: SubagentGroupCardProps) => { + const { t } = useAppTranslation() + const [runs, setRuns] = useState(() => groupCache.get(groupId) ?? initialRuns ?? []) + + useEffect(() => { + if (initialRuns && initialRuns.length > 0) { + setRuns((current) => { + const merged = mergeRuns(current, initialRuns) + groupCache.set(groupId, merged) + return merged + }) + } + }, [groupId, initialRuns]) + + const onMessage = useCallback( + (event: MessageEvent) => { + const message: ExtensionMessage = event.data + + if (message.type !== "subagentUpdate" || !message.subagentUpdate) { + return + } + + if (message.subagentUpdate.groupId !== groupId) { + return + } + + setRuns((current) => { + const merged = mergeRuns(current, message.subagentUpdate!.runs) + groupCache.set(groupId, merged) + return merged + }) + }, + [groupId], + ) + + useEvent("message", onMessage) + + const activeCount = runs.filter((run) => !isTerminal(run.status)).length + const completedCount = runs.filter((run) => run.status === "completed").length + const failedCount = runs.filter((run) => run.status === "failed").length + const finishedCount = runs.filter((run) => isTerminal(run.status)).length + + const header = useMemo(() => { + if (activeCount > 0) { + return t("chat:subagents.groupRunning", { active: activeCount, total: runs.length }) + } + + // A cancelled run is finished but not completed; failures get their own + // count so they never hide inside the total. + if (failedCount > 0) { + return t("chat:subagents.groupDoneWithFailures", { + completed: completedCount, + failed: failedCount, + total: runs.length, + }) + } + + return t("chat:subagents.groupDone", { + completed: finishedCount, + failed: failedCount, + total: runs.length, + }) + }, [activeCount, completedCount, failedCount, finishedCount, runs.length, t]) + + if (runs.length === 0) { + return null + } + + return ( +
+
+ {activeCount > 0 ? ( + + ) : ( + + )} + {header} +
+
+ {runs.map((run) => ( + + ))} +
+
+ ) +} + +const SubagentCard = ({ run }: { run: SubagentRunSnapshot }) => { + const { t } = useAppTranslation() + const [expanded, setExpanded] = useState(false) + const [liveOpen, setLiveOpen] = useState(false) + const terminal = isTerminal(run.status) + const duration = run.durationMs !== undefined ? `${(run.durationMs / 1000).toFixed(1)}s` : undefined + const meta = runMeta(run, t) + const hasActivity = (run.activity?.length ?? 0) > 0 + + return ( +
+
+
+
+ + {hasActivity && ( + + )} + {run.description || run.agentName} + {run.agentName} +
+
+ {run.status === "running" && (run.currentAction || t("chat:subagents.starting"))} + {run.status === "queued" && t("chat:subagents.queued")} + {run.status === "completed" && (duration ?? t("chat:subagents.completed"))} + {run.status === "failed" && (run.error ?? t("chat:subagents.failed"))} + {run.status === "cancelled" && t("chat:subagents.cancelled")} +
+
+
+ {run.partial && {t("chat:subagents.partial")}} + + + + {!terminal && ( + + + + )} +
+
+ + {run.summary && ( +
{run.summary}
+ )} + + {meta &&
{meta}
} + + {expanded && hasActivity && run.activity && } + + setLiveOpen(false)} + /> +
+ ) +} + +function runMeta(run: SubagentRunSnapshot, t: ReturnType["t"]): string | null { + const parts: string[] = [] + if (run.toolCallCount > 0) { + parts.push(t("chat:subagents.metaTools", { count: run.toolCallCount })) + } + if (run.filesRead.length > 0) { + parts.push(t("chat:subagents.metaRead", { count: run.filesRead.length })) + } + if (run.filesModified.length > 0) { + parts.push(t("chat:subagents.metaWritten", { count: run.filesModified.length })) + } + if (run.worktree) { + parts.push(t(run.worktree.kept ? "chat:subagents.worktreeKept" : "chat:subagents.worktreeRemoved")) + } + + return parts.length > 0 ? parts.join(" · ") : null +} + +function statusDot(status: SubagentStatus): string { + switch (status) { + case "completed": + return "bg-green-600" + case "failed": + return "bg-red-600" + case "cancelled": + return "bg-vscode-descriptionForeground" + case "running": + return "bg-yellow-500 animate-pulse" + default: + return "bg-vscode-descriptionForeground" + } +} + +/** + * Header chip that sums the non-terminal runs of the current task. It listens + * to the same throttled update stream as the cards. + */ +export const SubagentActivityChip = ({ parentTaskId }: { parentTaskId?: string }) => { + const { t } = useAppTranslation() + const [active, setActive] = useState(0) + + const onMessage = useCallback( + (event: MessageEvent) => { + const message: ExtensionMessage = event.data + + if (message.type !== "subagentUpdate" || !message.subagentUpdate) { + return + } + + if (parentTaskId && message.subagentUpdate.parentTaskId !== parentTaskId) { + return + } + + const count = message.subagentUpdate.runs.filter((run) => !isTerminal(run.status)).length + setActive(count) + }, + [parentTaskId], + ) + + useEvent("message", onMessage) + + if (active === 0) { + return null + } + + return ( + +
+ + {active} +
+
+ ) +} diff --git a/webview-ui/src/components/chat/SubagentLiveViewer.tsx b/webview-ui/src/components/chat/SubagentLiveViewer.tsx new file mode 100644 index 00000000000..5a36c61d331 --- /dev/null +++ b/webview-ui/src/components/chat/SubagentLiveViewer.tsx @@ -0,0 +1,312 @@ +import { useCallback, useEffect, useState } from "react" +import { useEvent } from "react-use" +import { Bot, CheckCircle2, ChevronDown, ChevronUp, ClipboardList, ListChecks, X } from "lucide-react" + +import type { ExtensionMessage, SubagentRunSnapshot, SubagentToolActivity } from "@roo-code/types" + +import { useAppTranslation } from "@src/i18n/TranslationContext" +import { Modal } from "@src/components/common/Modal" +import { Button } from "@src/components/ui" +import { cn } from "@src/lib/utils" + +import { Markdown } from "./Markdown" + +interface SubagentLiveViewerProps { + runId: string + title: string + isOpen: boolean + /** Latest run snapshot, so the dashboard can show progress without fetching. */ + run?: SubagentRunSnapshot + /** True when the run already reached a terminal state. */ + ended?: boolean + onClose: () => void +} + +/** Formats a millisecond duration as a compact string, e.g. `2m 5s`, `8.4s`. */ +function formatDuration(ms: number): string { + if (!Number.isFinite(ms) || ms < 0) { + return "" + } + const totalSeconds = ms / 1000 + if (totalSeconds < 60) { + return `${totalSeconds.toFixed(1)}s` + } + const minutes = Math.floor(totalSeconds / 60) + const seconds = Math.round(totalSeconds % 60) + return `${minutes}m ${seconds}s` +} + +function statusLabel(status: SubagentRunSnapshot["status"]): { key: string; tone: string } { + switch (status) { + case "running": + return { key: "chat:subagents.dashRunning", tone: "text-yellow-600" } + case "completed": + return { key: "chat:subagents.dashCompleted", tone: "text-green-600" } + case "failed": + return { key: "chat:subagents.dashFailed", tone: "text-red-600" } + case "cancelled": + return { key: "chat:subagents.dashCancelled", tone: "text-vscode-descriptionForeground" } + default: + return { key: "chat:subagents.dashQueued", tone: "text-vscode-descriptionForeground" } + } +} + +/** Human label for one activity entry, falling back to the raw tool name. */ +function actionLabel(activity: SubagentToolActivity, t: (k: string) => string): string { + return activity.labelKey ? t(`chat:subagents.actions.${activity.labelKey}`) : activity.tool +} + +/** + * Read-only progress view for one subagent run. It leads with the instruction + * the subagent was given, then shows the sequence of steps it has performed so + * far, and the conclusion appears at the bottom once the run finishes. The raw + * conversation (tool calls, outputs) is intentionally not shown here. + */ +export const SubagentLiveViewer = ({ runId, title, isOpen, run, ended = false, onClose }: SubagentLiveViewerProps) => { + const { t } = useAppTranslation() + const [snapshot, setSnapshot] = useState(run) + const [now, setNow] = useState(Date.now()) + const [progressExpanded, setProgressExpanded] = useState(false) + + useEffect(() => { + if (!isOpen || !runId) { + return + } + setSnapshot(run) + }, [isOpen, runId, run]) + + // Tick once a second while open so the elapsed clock moves for active runs. + // Terminal runs ignore `now` in the render (they use `durationMs`). + useEffect(() => { + if (!isOpen) { + return + } + const id = setInterval(() => setNow(Date.now()), 1000) + return () => clearInterval(id) + }, [isOpen]) + + const onMessage = useCallback( + (event: MessageEvent) => { + const message: ExtensionMessage = event.data + if (message.type === "subagentUpdate" && message.subagentUpdate) { + const match = message.subagentUpdate.runs.find((snap) => snap.runId === runId) + if (match) { + setSnapshot((prev) => ({ ...prev, ...match })) + } + } + }, + [runId], + ) + + useEvent("message", onMessage) + + const status: SubagentRunSnapshot["status"] = snapshot?.status ?? (ended ? "completed" : "running") + const badge = statusLabel(status) + const isTerminal = status === "completed" || status === "failed" || status === "cancelled" + const startedAt = snapshot?.startedAt + const elapsed = + startedAt === undefined ? undefined : formatDuration(snapshot?.durationMs ?? (isTerminal ? 0 : now - startedAt)) + const runActivity = snapshot?.activity ?? [] + + // The activity is appended in chronological order (oldest to newest). The + // dashboard stays compact by showing only the most recent few entries; the + // rest are revealed when the "show all" toggle is opened. + const RECENT_ACTIVITY_LIMIT = 5 + const hasMoreActivity = runActivity.length > RECENT_ACTIVITY_LIMIT + const visibleActivity = + hasMoreActivity && !progressExpanded ? runActivity.slice(-RECENT_ACTIVITY_LIMIT) : runActivity + const hiddenCount = hasMoreActivity && !progressExpanded ? runActivity.length - RECENT_ACTIVITY_LIMIT : 0 + + return ( + +
+
+ + {snapshot?.agentName ?? title} +
+
+ {t(badge.key)} + {elapsed && ( + + {elapsed} + + )} + +
+
+ +
+
} label={t("chat:subagents.dashInstruction")}> + +
+ +
} + label={t("chat:subagents.dashProgress")} + action={ + hasMoreActivity ? ( + + ) : undefined + }> + {runActivity.length === 0 ? ( +
+ {t("chat:subagents.dashStarting")} +
+ ) : ( +
+ {visibleActivity.map((activity) => ( +
+ + {runActivity.findIndex((candidate) => candidate.id === activity.id) + 1} + + + {actionLabel(activity, t)} + {activity.path && ( + + {" "} + · {activity.path} + + )} + +
+ ))} +
+ )} + {status === "running" && snapshot?.currentAction && ( +
+ + + {t("chat:subagents.dashWorkingOn")} + + {snapshot.currentAction} +
+ )} +
+ + +
+
+ ) +} + +function Section({ + icon, + label, + action, + children, +}: { + icon: React.ReactNode + label: string + action?: React.ReactNode + children: React.ReactNode +}) { + return ( +
+
+ {icon} + {label} + {action && {action}} +
+ {children} +
+ ) +} + +/** + * The instruction the subagent was given. It shows the short description by + * default; clicking the description toggles the full prompt open, so the + * dashboard stays compact at a glance but the exact task text is one click + * away. + */ +function Instruction({ snapshot, t }: { snapshot?: SubagentRunSnapshot; t: (k: string) => string }) { + const [open, setOpen] = useState(false) + const prompt = snapshot?.prompt + const canToggle = Boolean(prompt && prompt !== snapshot?.description) + return ( +
+ + {open && prompt && ( +
+					{prompt}
+				
+ )} +
+ ) +} + +/** Terminal state only: the conclusion appears once the run finishes. */ +function Conclusion({ + snapshot, + status, + t, +}: { + snapshot?: SubagentRunSnapshot + status: SubagentRunSnapshot["status"] + t: (k: string) => string +}) { + if (status === "running" || status === "queued") { + return null + } + + let body: React.ReactNode + let tone: string + if (status === "failed") { + tone = "text-red-600" + body =
{snapshot?.error}
+ } else if (status === "cancelled") { + tone = "text-vscode-descriptionForeground" + body = ( +
{t("chat:subagents.dashCancelledOutcome")}
+ ) + } else { + tone = "text-green-600" + const summary = snapshot?.summary + body = summary ? ( + + ) : ( +
{t("chat:subagents.dashNoSummary")}
+ ) + } + + return ( +
} label={t("chat:subagents.dashConclusion")}> +
+ {snapshot?.partial && ( +
{t("chat:subagents.dashPartial")}
+ )} + {body} +
+
+ ) +} diff --git a/webview-ui/src/components/chat/TaskHeader.tsx b/webview-ui/src/components/chat/TaskHeader.tsx index 1cbf82a3a2e..433bf5781ce 100644 --- a/webview-ui/src/components/chat/TaskHeader.tsx +++ b/webview-ui/src/components/chat/TaskHeader.tsx @@ -30,6 +30,7 @@ import { ContextWindowProgress } from "./ContextWindowProgress" import { Mention } from "./Mention" import { TodoListDisplay } from "./TodoListDisplay" import { LucideIconButton } from "./LucideIconButton" +import { SubagentActivityChip } from "./SubagentGroupCard" export interface TaskHeaderProps { task: ClineMessage @@ -204,6 +205,7 @@ const TaskHeader = ({ )}
e.stopPropagation()}> +
) diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 9cd74faf1c4..95908c8aa86 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -40,6 +40,8 @@ import { DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES, DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, DEFAULT_TASK_TITLE_GENERATION_ENABLED, + DEFAULT_MAX_CONCURRENT_SUBAGENTS, + DEFAULT_SUBAGENT_MAX_TURNS, ImageGenerationProvider, } from "@roo-code/types" @@ -241,6 +243,9 @@ const SettingsView = forwardRef(({ onDone, t autoCloseZooOpenedFiles, autoCloseZooOpenedFilesAfterUserEdited, autoCloseZooOpenedNewFiles, + subagentsEnabled, + maxConcurrentSubagents, + defaultSubagentMaxTurns, } = cachedState const apiConfiguration = cachedState.apiConfiguration @@ -489,6 +494,9 @@ const SettingsView = forwardRef(({ onDone, t autoCloseZooOpenedFilesAfterUserEdited: autoCloseZooOpenedFilesAfterUserEdited ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED, autoCloseZooOpenedNewFiles: autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES, + subagentsEnabled: subagentsEnabled ?? false, + maxConcurrentSubagents: maxConcurrentSubagents ?? DEFAULT_MAX_CONCURRENT_SUBAGENTS, + defaultSubagentMaxTurns: defaultSubagentMaxTurns ?? DEFAULT_SUBAGENT_MAX_TURNS, profileThresholds, imageGenerationProvider, openRouterImageApiKey, @@ -1039,6 +1047,10 @@ const SettingsView = forwardRef(({ onDone, t setImageGenerationProvider={setImageGenerationProvider} setOpenRouterImageApiKey={setOpenRouterImageApiKey} setImageGenerationSelectedModel={setImageGenerationSelectedModel} + subagentsEnabled={subagentsEnabled} + maxConcurrentSubagents={maxConcurrentSubagents} + defaultSubagentMaxTurns={defaultSubagentMaxTurns} + setCachedStateField={setCachedStateField} /> )} diff --git a/webview-ui/src/components/settings/SubagentSettings.tsx b/webview-ui/src/components/settings/SubagentSettings.tsx new file mode 100644 index 00000000000..c9b34c7523d --- /dev/null +++ b/webview-ui/src/components/settings/SubagentSettings.tsx @@ -0,0 +1,131 @@ +import { HTMLAttributes } from "react" +import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" +import { + DEFAULT_MAX_CONCURRENT_SUBAGENTS, + DEFAULT_SUBAGENT_MAX_TURNS, + MAX_CONCURRENT_SUBAGENTS, + MAX_SUBAGENT_MAX_TURNS, + MIN_CONCURRENT_SUBAGENTS, + UNLIMITED_SUBAGENT_MAX_TURNS, +} from "@roo-code/types" + +import { useAppTranslation } from "@/i18n/TranslationContext" +import { Slider } from "@/components/ui" + +import { SetCachedStateField } from "./types" +import { SectionHeader } from "./SectionHeader" +import { Section } from "./Section" +import { SearchableSetting } from "./SearchableSetting" + +type SubagentSettingsProps = HTMLAttributes & { + subagentsEnabled?: boolean + maxConcurrentSubagents?: number + defaultSubagentMaxTurns?: number + setCachedStateField: SetCachedStateField<"subagentsEnabled" | "maxConcurrentSubagents" | "defaultSubagentMaxTurns"> + /** Render the settings as sibling rows of another section, without a top-level header or wrapper. */ + embedded?: boolean +} + +export const SubagentSettings = ({ + subagentsEnabled, + maxConcurrentSubagents, + defaultSubagentMaxTurns, + setCachedStateField, + embedded = false, + ...props +}: SubagentSettingsProps) => { + const { t } = useAppTranslation() + + // Separation between rows matches the surrounding section: the embedded + // case inherits the parent Section's gap, so no per-row margin is needed. + const rowGap = embedded ? "" : "mt-4" + + const currentMaxTurns = defaultSubagentMaxTurns ?? DEFAULT_SUBAGENT_MAX_TURNS + const isUnlimited = currentMaxTurns === UNLIMITED_SUBAGENT_MAX_TURNS + + const rows = [ + + { + setCachedStateField("subagentsEnabled", (e.target as HTMLInputElement).checked) + }}> + {t("settings:subagents.enable.label")} + +
+ {t("settings:subagents.enable.description")} +
+
, + + +
+ { + setCachedStateField("maxConcurrentSubagents", value) + }} + className="flex-1" + data-testid="subagent-concurrency-slider" + /> + {maxConcurrentSubagents ?? DEFAULT_MAX_CONCURRENT_SUBAGENTS} +
+
+ {t("settings:subagents.concurrency.description")} +
+
, + + +
+ { + setCachedStateField("defaultSubagentMaxTurns", value) + }} + className="flex-1" + data-testid="subagent-max-turns-slider" + /> + {isUnlimited ? "∞" : currentMaxTurns} +
+
+ {t("settings:subagents.maxTurns.description")} +
+
, + ] + + // The concurrency and max-turn sub-options only appear when subagents are enabled. + const visibleRows = subagentsEnabled ? rows : rows.slice(0, 1) + + return ( +
+ {/* Embedded: rows render as siblings of the surrounding section's rows. */} + {embedded ? ( +
{visibleRows}
+ ) : ( + <> + {t("settings:sections.subagents")} +
{visibleRows}
+ + )} +
+ ) +} diff --git a/webview-ui/src/components/settings/__tests__/ExperimentalSettings.visual.fixture.tsx b/webview-ui/src/components/settings/__tests__/ExperimentalSettings.visual.fixture.tsx index 2d844499d18..b8aee23b9ea 100644 --- a/webview-ui/src/components/settings/__tests__/ExperimentalSettings.visual.fixture.tsx +++ b/webview-ui/src/components/settings/__tests__/ExperimentalSettings.visual.fixture.tsx @@ -13,6 +13,12 @@ export function ExperimentalSettingsStory() { [EXPERIMENT_IDS.DYNAMIC_THINKING_EFFORT]: true, }) + // The subagent section renders only with a cached-state setter; a live value + // keeps the screenshot deterministic and shows the enabled controls. + const [subagentsEnabled, setSubagentsEnabled] = useState(true) + const [maxConcurrentSubagents, setMaxConcurrentSubagents] = useState(3) + const [defaultSubagentMaxTurns, setDefaultSubagentMaxTurns] = useState(12) + return (
setExperiments((current) => ({ ...current, [id]: enabled }))} + subagentsEnabled={subagentsEnabled} + maxConcurrentSubagents={maxConcurrentSubagents} + defaultSubagentMaxTurns={defaultSubagentMaxTurns} + setCachedStateField={(field, value) => { + if (field === "subagentsEnabled") { + setSubagentsEnabled(Boolean(value)) + } + if (field === "maxConcurrentSubagents") { + setMaxConcurrentSubagents(Number(value)) + } + if (field === "defaultSubagentMaxTurns") { + setDefaultSubagentMaxTurns(Number(value)) + } + }} />
diff --git a/webview-ui/src/components/settings/__tests__/SubagentSettings.spec.tsx b/webview-ui/src/components/settings/__tests__/SubagentSettings.spec.tsx new file mode 100644 index 00000000000..17eb947a6b7 --- /dev/null +++ b/webview-ui/src/components/settings/__tests__/SubagentSettings.spec.tsx @@ -0,0 +1,144 @@ +import React from "react" + +import { fireEvent, render, screen } from "@/utils/test-utils" + +import { SubagentSettings } from "../SubagentSettings" + +vi.mock("@/i18n/TranslationContext", () => ({ + useAppTranslation: () => ({ + t: (key: string) => key, + }), +})) + +// The toolkit checkbox is a custom element; a native input makes the click path visible to jsdom. +vi.mock("@vscode/webview-ui-toolkit/react", () => ({ + VSCodeCheckbox: ({ + checked, + onChange, + children, + }: { + checked?: boolean + onChange?: (event: React.ChangeEvent) => void + children?: React.ReactNode + }) => ( + + ), +})) + +// Radix needs pointer events; a range input exercises the same value/onValueChange contract. +vi.mock("@/components/ui", async (importOriginal) => ({ + ...(await importOriginal()), + Slider: ({ + value, + onValueChange, + "data-testid": testId, + }: { + value?: number[] + onValueChange?: (value: number[]) => void + "data-testid"?: string + }) => ( + onValueChange?.([Number(event.target.value)])} + data-testid={testId} + /> + ), +})) + +const renderSettings = (overrides: Partial> = {}) => { + const setCachedStateField = vi.fn() + + render( + , + ) + + return { setCachedStateField } +} + +describe("SubagentSettings", () => { + const enableLabel = "settings:subagents.enable.label" + + it("shows the saved settings", () => { + renderSettings({ subagentsEnabled: true, maxConcurrentSubagents: 6, defaultSubagentMaxTurns: 30 }) + + expect(screen.getByLabelText(enableLabel)).toBeChecked() + expect(screen.getByTestId("subagent-concurrency-slider")).toHaveValue("6") + expect(screen.getByTestId("subagent-max-turns-slider")).toHaveValue("30") + }) + + it("writes each edit to the cached state instead of saving immediately", () => { + const { setCachedStateField } = renderSettings({ subagentsEnabled: true }) + + fireEvent.click(screen.getByLabelText(enableLabel)) + expect(setCachedStateField).toHaveBeenCalledWith("subagentsEnabled", false) + + fireEvent.change(screen.getByTestId("subagent-concurrency-slider"), { target: { value: "7" } }) + expect(setCachedStateField).toHaveBeenCalledWith("maxConcurrentSubagents", 7) + + fireEvent.change(screen.getByTestId("subagent-max-turns-slider"), { target: { value: "22" } }) + expect(setCachedStateField).toHaveBeenCalledWith("defaultSubagentMaxTurns", 22) + }) + + it("falls back to the documented defaults when a setting is unset", () => { + renderSettings({ + subagentsEnabled: true, + maxConcurrentSubagents: undefined, + defaultSubagentMaxTurns: undefined, + }) + + expect(screen.getByLabelText(enableLabel)).toBeChecked() + expect(screen.getByTestId("subagent-concurrency-slider")).toHaveValue("4") + expect(screen.getByTestId("subagent-max-turns-slider")).toHaveValue("0") + expect(screen.getByText("∞")).toBeInTheDocument() + }) + + it("keeps the concurrency and max-turn options hidden until subagents are enabled", () => { + renderSettings({ subagentsEnabled: false }) + + // The enable control is always visible; the sub-options only appear once enabled. + expect(screen.getByLabelText(enableLabel)).not.toBeChecked() + expect(screen.queryByTestId("subagent-concurrency-slider")).not.toBeInTheDocument() + expect(screen.queryByTestId("subagent-max-turns-slider")).not.toBeInTheDocument() + }) + + it("writes an unlimited (0) limit when the max-turn slider is moved to 0", () => { + const { setCachedStateField } = renderSettings({ subagentsEnabled: true, defaultSubagentMaxTurns: 30 }) + + fireEvent.change(screen.getByTestId("subagent-max-turns-slider"), { target: { value: "0" } }) + expect(setCachedStateField).toHaveBeenCalledWith("defaultSubagentMaxTurns", 0) + }) + + it("shows ∞ when the max-turn limit is 0 (unlimited)", () => { + renderSettings({ subagentsEnabled: true, defaultSubagentMaxTurns: 0 }) + + expect(screen.getByTestId("subagent-max-turns-slider")).toHaveValue("0") + expect(screen.getByText("∞")).toBeInTheDocument() + }) + + it("writes a finite limit when the max-turn slider is moved away from 0", () => { + const { setCachedStateField } = renderSettings({ subagentsEnabled: true, defaultSubagentMaxTurns: 0 }) + + fireEvent.change(screen.getByTestId("subagent-max-turns-slider"), { target: { value: "12" } }) + expect(setCachedStateField).toHaveBeenCalledWith("defaultSubagentMaxTurns", 12) + }) + + it("renders the settings as sibling rows without a top-level header when embedded", () => { + renderSettings({ subagentsEnabled: true, embedded: true }) + + // No sticky "Subagents" section header when embedded inside another section. + expect(screen.queryByText("settings:sections.subagents")).not.toBeInTheDocument() + expect(screen.getByLabelText(enableLabel)).toBeChecked() + expect(screen.getByTestId("subagent-concurrency-slider")).toBeInTheDocument() + expect(screen.getByTestId("subagent-max-turns-slider")).toBeInTheDocument() + }) +}) diff --git a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-dark.png b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-dark.png index 1bfbbcf884d..5be5530211b 100644 Binary files a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-dark.png and b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-dark.png differ diff --git a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast-light.png b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast-light.png index e4d9385b5ee..63e145a3d28 100644 Binary files a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast-light.png and b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast-light.png differ diff --git a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast.png b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast.png index c83298d0ead..37a50e2a739 100644 Binary files a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast.png and b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-high-contrast.png differ diff --git a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-light.png b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-light.png index 55216d50cc1..e8fbd833c7a 100644 Binary files a/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-light.png and b/webview-ui/src/components/settings/__tests__/__screenshots__/experimental-settings-light.png differ diff --git a/webview-ui/src/i18n/locales/ca/chat.json b/webview-ui/src/i18n/locales/ca/chat.json index 85828170a16..274b63d4069 100644 --- a/webview-ui/src/i18n/locales/ca/chat.json +++ b/webview-ui/src/i18n/locales/ca/chat.json @@ -523,5 +523,59 @@ "hiddenLines_one": "{{count}} línia oculta", "hiddenLines_many": "{{count}} de línies ocultes", "hiddenLines_other": "{{count}} línies ocultes" + }, + "subagents": { + "groupRunning": "Subagents · {{active}} de {{total}} en execució", + "groupDone": "Subagents · {{completed}} de {{total}} acabats", + "groupDoneWithFailures": "Subagents · {{completed}} completats · {{failed}} fallits", + "starting": "Iniciant...", + "queued": "En cua", + "completed": "Completat", + "failed": "Fallit", + "cancelled": "Cancel·lat", + "partial": "parcial", + "cancel": "Cancel·la el subagent", + "inspect": "Obre la transcripció", + "headerChip": "{{count}} subagent(s) en execució", + "metaTools": "{{count}} eines", + "metaRead": "{{count}} lectures", + "metaWritten": "{{count}} escriptures", + "dashRunning": "En execució", + "dashCompleted": "Completat", + "dashFailed": "Ha fallat", + "dashCancelled": "Cancel·lat", + "dashQueued": "En cua", + "dashWorkingOn": "Treballant en", + "dashStarting": "Iniciant…", + "dashInstruction": "Instrucció", + "dashProgress": "Progrés", + "dashConclusion": "Conclusió", + "dashPartial": "S'ha aturat al límit de torns abans d'acabar", + "dashNoSummary": "No s'ha retornat cap resum", + "dashCancelledOutcome": "Execució cancel·lada", + "dashShowMoreCount": "Mostra'n {{count}} més", + "dashShowLess": "Mostra'n menys", + "worktreeKept": "worktree conservat", + "worktreeRemoved": "worktree eliminat", + "viewLive": "Veure en directe", + "liveTitle": "Transcripció en directe", + "close": "Tanca", + "loadEarlier": "Carrega'n de més abans", + "noActivity": "Encara no hi ha activitat d'eines", + "liveEnded": "Execució finalitzada", + "roleUser": "Usuari", + "roleAssistant": "Agent", + "reasoning": "Raonament", + "result": "Resultat", + "actions": { + "readfile": "Llegir fitxer", + "searchfiles": "Cercar fitxers", + "listfiles": "Llistar directori", + "codebasesearch": "Cercar al codi", + "executecommand": "Executar ordre", + "writetofile": "Escriure fitxer", + "editfile": "Editar fitxer", + "completion": "Escriure l'informe final" + } } } diff --git a/webview-ui/src/i18n/locales/ca/settings.json b/webview-ui/src/i18n/locales/ca/settings.json index c891ef350dc..3e5c850b28d 100644 --- a/webview-ui/src/i18n/locales/ca/settings.json +++ b/webview-ui/src/i18n/locales/ca/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Proveïdors", "modes": "Modes", + "subagents": "Subagents", "mcp": "Servidors MCP", "worktrees": "Worktrees", "autoApprove": "Auto-aprovació", @@ -709,6 +710,20 @@ "setupInstructions": "Instruccions de configuració" } }, + "subagents": { + "enable": { + "label": "Habilita els subagents", + "description": "Si està habilitat, els modes d'eines completes poden generar subagents headless que s'executen en paral·lel. Cada subagent treballa en el seu propi context i només retorna un resum al xat principal." + }, + "concurrency": { + "label": "Màxim de subagents simultanis", + "description": "Quants subagents poden executar-se alhora. Les execucions addicionals esperen en una cua." + }, + "maxTurns": { + "label": "Torns màxims predeterminats per subagent", + "description": "Límit de torns per als subagents la definició dels quals no n'estableix cap. Un subagent que assoleix el límit s'atura i retorna un resum parcial. 0 vol dir il·limitat." + } + }, "checkpoints": { "timeout": { "label": "Temps d'espera per inicialitzar el punt de control (segons)", diff --git a/webview-ui/src/i18n/locales/de/chat.json b/webview-ui/src/i18n/locales/de/chat.json index 99863d222a6..b46915e45d0 100644 --- a/webview-ui/src/i18n/locales/de/chat.json +++ b/webview-ui/src/i18n/locales/de/chat.json @@ -515,5 +515,59 @@ "diffView": { "hiddenLines_one": "{{count}} ausgeblendete Zeile", "hiddenLines_other": "{{count}} ausgeblendete Zeilen" + }, + "subagents": { + "groupRunning": "Subagenten · {{active}} von {{total}} laufen", + "groupDone": "Subagenten · {{completed}} von {{total}} fertig", + "groupDoneWithFailures": "Subagenten · {{completed}} abgeschlossen · {{failed}} fehlgeschlagen", + "starting": "Starte...", + "queued": "In Warteschlange", + "completed": "Abgeschlossen", + "failed": "Fehlgeschlagen", + "cancelled": "Abgebrochen", + "partial": "teilweise", + "cancel": "Subagent abbrechen", + "inspect": "Transkript öffnen", + "headerChip": "{{count}} Subagent(en) laufen", + "metaTools": "{{count}} Werkzeuge", + "metaRead": "{{count}} gelesen", + "metaWritten": "{{count}} geschrieben", + "dashRunning": "Läuft", + "dashCompleted": "Abgeschlossen", + "dashFailed": "Fehlgeschlagen", + "dashCancelled": "Abgebrochen", + "dashQueued": "In Warteschlange", + "dashWorkingOn": "Arbeitet an", + "dashStarting": "Startet…", + "dashInstruction": "Anweisung", + "dashProgress": "Fortschritt", + "dashConclusion": "Fazit", + "dashPartial": "Vor dem Abschluss an der Turn-Limitierung gestoppt", + "dashNoSummary": "Keine Zusammenfassung zurückgegeben", + "dashCancelledOutcome": "Lauf abgebrochen", + "dashShowMoreCount": "{{count}} weitere anzeigen", + "dashShowLess": "Weniger anzeigen", + "worktreeKept": "Worktree beibehalten", + "worktreeRemoved": "Worktree entfernt", + "viewLive": "Live ansehen", + "liveTitle": "Live-Transkript", + "close": "Schließen", + "loadEarlier": "Frühere laden", + "noActivity": "Noch keine Tool-Aktivität", + "liveEnded": "Lauf beendet", + "roleUser": "Benutzer", + "roleAssistant": "Agent", + "reasoning": "Begründung", + "result": "Ergebnis", + "actions": { + "readfile": "Datei lesen", + "searchfiles": "Dateien durchsuchen", + "listfiles": "Verzeichnis auflisten", + "codebasesearch": "Code durchsuchen", + "executecommand": "Befehl ausführen", + "writetofile": "Datei schreiben", + "editfile": "Datei bearbeiten", + "completion": "Abschlussbericht schreiben" + } } } diff --git a/webview-ui/src/i18n/locales/de/settings.json b/webview-ui/src/i18n/locales/de/settings.json index e2e9f63e100..5c51fa4294c 100644 --- a/webview-ui/src/i18n/locales/de/settings.json +++ b/webview-ui/src/i18n/locales/de/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Anbieter", "modes": "Modi", + "subagents": "Subagenten", "mcp": "MCP-Server", "worktrees": "Worktrees", "autoApprove": "Auto-Genehmigung", @@ -708,6 +709,20 @@ "setupInstructions": "Einrichtungsanleitung" } }, + "subagents": { + "enable": { + "label": "Subagenten aktivieren", + "description": "Wenn aktiviert, können Vollwerkzeug-Modi headless Subagenten erzeugen, die parallel laufen. Jeder Subagent arbeitet in seinem eigenen Kontext und gibt nur eine Zusammenfassung an den Hauptchat zurück." + }, + "concurrency": { + "label": "Maximale gleichzeitige Subagenten", + "description": "Wie viele Subagenten gleichzeitig laufen dürfen. Weitere Läufe warten in einer Warteschlange." + }, + "maxTurns": { + "label": "Standardmäßige maximale Turns pro Subagent", + "description": "Turn-Limit für Subagenten, deren Definition kein Limit festlegt. Ein Subagent, der das Limit erreicht, stoppt und gibt eine Teilzusammenfassung. 0 bedeutet unbegrenzt." + } + }, "checkpoints": { "timeout": { "label": "Timeout für Checkpoint-Initialisierung (Sekunden)", diff --git a/webview-ui/src/i18n/locales/en/chat.json b/webview-ui/src/i18n/locales/en/chat.json index c169dee3d85..45e1e09f0af 100644 --- a/webview-ui/src/i18n/locales/en/chat.json +++ b/webview-ui/src/i18n/locales/en/chat.json @@ -503,5 +503,59 @@ "diffView": { "hiddenLines_one": "{{count}} hidden line", "hiddenLines_other": "{{count}} hidden lines" + }, + "subagents": { + "groupRunning": "Subagents · {{active}} of {{total}} running", + "groupDone": "Subagents · {{completed}} of {{total}} finished", + "groupDoneWithFailures": "Subagents · {{completed}} completed · {{failed}} failed", + "starting": "Starting...", + "queued": "Queued", + "completed": "Completed", + "failed": "Failed", + "cancelled": "Cancelled", + "partial": "partial", + "cancel": "Cancel subagent", + "inspect": "Open transcript", + "headerChip": "{{count}} subagent(s) running", + "metaTools": "{{count}} tools", + "metaRead": "{{count}} read", + "metaWritten": "{{count}} written", + "dashRunning": "Running", + "dashCompleted": "Completed", + "dashFailed": "Failed", + "dashCancelled": "Cancelled", + "dashQueued": "Queued", + "dashWorkingOn": "Working on", + "dashStarting": "Starting…", + "dashInstruction": "Instruction", + "dashProgress": "Progress", + "dashConclusion": "Conclusion", + "dashPartial": "Stopped at the turn limit before finishing", + "dashNoSummary": "No summary returned", + "dashCancelledOutcome": "Run cancelled", + "dashShowMoreCount": "Show {{count}} more", + "dashShowLess": "Show fewer", + "worktreeKept": "worktree kept", + "worktreeRemoved": "worktree removed", + "viewLive": "View live", + "liveTitle": "Live transcript", + "close": "Close", + "loadEarlier": "Load earlier", + "noActivity": "No tool activity yet", + "liveEnded": "Run finished", + "roleUser": "User", + "roleAssistant": "Agent", + "reasoning": "Reasoning", + "result": "Result", + "actions": { + "readfile": "Read file", + "searchfiles": "Search files", + "listfiles": "List directory", + "codebasesearch": "Search codebase", + "executecommand": "Run command", + "writetofile": "Write file", + "editfile": "Edit file", + "completion": "Write final report" + } } } diff --git a/webview-ui/src/i18n/locales/en/settings.json b/webview-ui/src/i18n/locales/en/settings.json index 860ffbea17c..7f114912a8f 100644 --- a/webview-ui/src/i18n/locales/en/settings.json +++ b/webview-ui/src/i18n/locales/en/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Providers", "modes": "Modes", + "subagents": "Subagents", "mcp": "MCP Servers", "worktrees": "Worktrees", "skills": "Skills", @@ -781,6 +782,20 @@ "setupInstructions": "Setup Instructions" } }, + "subagents": { + "enable": { + "label": "Enable subagents", + "description": "When enabled, full-tool modes can spawn headless subagents that run in parallel. Each subagent works in its own context and returns only a summary to the main chat." + }, + "concurrency": { + "label": "Maximum concurrent subagents", + "description": "How many subagents may run at the same time. Additional runs wait in a queue." + }, + "maxTurns": { + "label": "Default maximum turns per subagent", + "description": "Turn limit for subagents whose definition does not set one. A subagent that reaches the limit stops and returns a partial summary. 0 means unlimited." + } + }, "checkpoints": { "timeout": { "label": "Checkpoint initialization timeout (seconds)", diff --git a/webview-ui/src/i18n/locales/es/chat.json b/webview-ui/src/i18n/locales/es/chat.json index 1ab4abbf528..19ebaa46352 100644 --- a/webview-ui/src/i18n/locales/es/chat.json +++ b/webview-ui/src/i18n/locales/es/chat.json @@ -523,5 +523,59 @@ "hiddenLines_one": "{{count}} línea oculta", "hiddenLines_many": "{{count}} de líneas ocultas", "hiddenLines_other": "{{count}} líneas ocultas" + }, + "subagents": { + "groupRunning": "Subagentes · {{active}} de {{total}} en ejecución", + "groupDone": "Subagentes · {{completed}} de {{total}} terminados", + "groupDoneWithFailures": "Subagentes · {{completed}} completados · {{failed}} fallidos", + "starting": "Iniciando...", + "queued": "En cola", + "completed": "Completado", + "failed": "Fallido", + "cancelled": "Cancelado", + "partial": "parcial", + "cancel": "Cancelar subagente", + "inspect": "Abrir transcripción", + "headerChip": "{{count}} subagente(s) en ejecución", + "metaTools": "{{count}} herramientas", + "metaRead": "{{count}} lecturas", + "metaWritten": "{{count}} escrituras", + "dashRunning": "En ejecución", + "dashCompleted": "Completado", + "dashFailed": "Fallido", + "dashCancelled": "Cancelado", + "dashQueued": "En cola", + "dashWorkingOn": "Trabajando en", + "dashStarting": "Iniciando…", + "dashInstruction": "Instrucción", + "dashProgress": "Progreso", + "dashConclusion": "Conclusión", + "dashPartial": "Se detuvo en el límite de turnos antes de terminar", + "dashNoSummary": "No se devolvió ningún resumen", + "dashCancelledOutcome": "Ejecución cancelada", + "dashShowMoreCount": "Mostrar {{count}} más", + "dashShowLess": "Mostrar menos", + "worktreeKept": "worktree conservado", + "worktreeRemoved": "worktree eliminado", + "viewLive": "Ver en vivo", + "liveTitle": "Transcripción en vivo", + "close": "Cerrar", + "loadEarlier": "Cargar anteriores", + "noActivity": "Aún no hay actividad de herramientas", + "liveEnded": "Ejecución finalizada", + "roleUser": "Usuario", + "roleAssistant": "Agente", + "reasoning": "Razonamiento", + "result": "Resultado", + "actions": { + "readfile": "Leer archivo", + "searchfiles": "Buscar archivos", + "listfiles": "Listar directorio", + "codebasesearch": "Buscar en el código", + "executecommand": "Ejecutar comando", + "writetofile": "Escribir archivo", + "editfile": "Editar archivo", + "completion": "Escribir el informe final" + } } } diff --git a/webview-ui/src/i18n/locales/es/settings.json b/webview-ui/src/i18n/locales/es/settings.json index 7704941410a..b951e041019 100644 --- a/webview-ui/src/i18n/locales/es/settings.json +++ b/webview-ui/src/i18n/locales/es/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Proveedores", "modes": "Modos", + "subagents": "Subagentes", "mcp": "Servidores MCP", "worktrees": "Worktrees", "autoApprove": "Auto-aprobación", @@ -709,6 +710,20 @@ "setupInstructions": "Instrucciones de configuración" } }, + "subagents": { + "enable": { + "label": "Habilitar subagentes", + "description": "Al habilitarlo, los modos de herramientas completas pueden generar subagentes headless que se ejecutan en paralelo. Cada subagente trabaja en su propio contexto y devuelve solo un resumen al chat principal." + }, + "concurrency": { + "label": "Máximo de subagentes simultáneos", + "description": "Cuántos subagentes pueden ejecutarse a la vez. Las ejecuciones adicionales esperan en una cola." + }, + "maxTurns": { + "label": "Turns máximos predeterminados por subagente", + "description": "Límite de turnos para subagentes cuya definición no establece uno. Un subagente que alcanza el límite se detiene y devuelve un resumen parcial. 0 significa ilimitado." + } + }, "checkpoints": { "timeout": { "label": "Tiempo de espera para inicializar el punto de control (segundos)", diff --git a/webview-ui/src/i18n/locales/fr/chat.json b/webview-ui/src/i18n/locales/fr/chat.json index cab4858c7bb..790f3b81123 100644 --- a/webview-ui/src/i18n/locales/fr/chat.json +++ b/webview-ui/src/i18n/locales/fr/chat.json @@ -523,5 +523,59 @@ "hiddenLines_one": "{{count}} ligne masquée", "hiddenLines_many": "{{count}} de lignes masquées", "hiddenLines_other": "{{count}} lignes masquées" + }, + "subagents": { + "groupRunning": "Sous-agents · {{active}} sur {{total}} en cours", + "groupDone": "Sous-agents · {{completed}} sur {{total}} terminés", + "groupDoneWithFailures": "Sous-agents · {{completed}} terminés · {{failed}} échecs", + "starting": "Démarrage...", + "queued": "En file", + "completed": "Terminé", + "failed": "Échec", + "cancelled": "Annulé", + "partial": "partiel", + "cancel": "Annuler le sous-agent", + "inspect": "Ouvrir la transcription", + "headerChip": "{{count}} sous-agent(s) en cours", + "metaTools": "{{count}} outils", + "metaRead": "{{count}} lectures", + "metaWritten": "{{count}} écritures", + "dashRunning": "En cours", + "dashCompleted": "Terminé", + "dashFailed": "Échoué", + "dashCancelled": "Annulé", + "dashQueued": "En file d'attente", + "dashWorkingOn": "En train de faire", + "dashStarting": "Démarrage…", + "dashInstruction": "Consigne", + "dashProgress": "Progression", + "dashConclusion": "Conclusion", + "dashPartial": "Arrêté avant la fin par la limite de tours", + "dashNoSummary": "Aucun résumé renvoyé", + "dashCancelledOutcome": "Exécution annulée", + "dashShowMoreCount": "Afficher {{count}} de plus", + "dashShowLess": "Afficher moins", + "worktreeKept": "worktree conservé", + "worktreeRemoved": "worktree supprimé", + "viewLive": "Voir en direct", + "liveTitle": "Transcription en direct", + "close": "Fermer", + "loadEarlier": "Charger plus tôt", + "noActivity": "Aucune activité d'outil pour l'instant", + "liveEnded": "Exécution terminée", + "roleUser": "Utilisateur", + "roleAssistant": "Agent", + "reasoning": "Raisonnement", + "result": "Résultat", + "actions": { + "readfile": "Lire le fichier", + "searchfiles": "Rechercher des fichiers", + "listfiles": "Lister le répertoire", + "codebasesearch": "Rechercher dans le code", + "executecommand": "Exécuter la commande", + "writetofile": "Écrire le fichier", + "editfile": "Modifier le fichier", + "completion": "Écrire le rapport final" + } } } diff --git a/webview-ui/src/i18n/locales/fr/settings.json b/webview-ui/src/i18n/locales/fr/settings.json index f804a236017..476bd42ccd2 100644 --- a/webview-ui/src/i18n/locales/fr/settings.json +++ b/webview-ui/src/i18n/locales/fr/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Fournisseurs", "modes": "Modes", + "subagents": "Sous-agents", "mcp": "Serveurs MCP", "worktrees": "Worktrees", "autoApprove": "Auto-approbation", @@ -709,6 +710,20 @@ "setupInstructions": "Instructions de configuration" } }, + "subagents": { + "enable": { + "label": "Activer les sous-agents", + "description": "Lorsqu'elle est activée, les modes pleins outils peuvent générer des sous-agents headless qui s'exécutent en parallèle. Chaque sous-agent travaille dans son propre contexte et ne renvoie qu'un résumé au chat principal." + }, + "concurrency": { + "label": "Nombre maximal de sous-agents simultanés", + "description": "Combien de sous-agents peuvent s'exécuter en même temps. Les exécutions supplémentaires attendent dans une file." + }, + "maxTurns": { + "label": "Tours maximum par défaut par sous-agent", + "description": "Limite de tours pour les sous-agents dont la définition n'en fixe pas. Un sous-agent qui atteint la limite s'arrête et renvoie un résumé partiel. 0 signifie illimité." + } + }, "checkpoints": { "timeout": { "label": "Délai d'initialisation du point de contrôle (secondes)", diff --git a/webview-ui/src/i18n/locales/hi/chat.json b/webview-ui/src/i18n/locales/hi/chat.json index 7a01903634d..bd60019b574 100644 --- a/webview-ui/src/i18n/locales/hi/chat.json +++ b/webview-ui/src/i18n/locales/hi/chat.json @@ -515,5 +515,59 @@ "diffView": { "hiddenLines_one": "{{count}} छिपी हुई पंक्ति", "hiddenLines_other": "{{count}} छिपी हुई पंक्तियाँ" + }, + "subagents": { + "groupRunning": "सबएजेंट · {{total}} में से {{active}} चल रहे हैं", + "groupDone": "सबएजेंट · {{total}} में से {{completed}} पूर्ण हुए", + "groupDoneWithFailures": "सबएजेंट · {{completed}} पूर्ण · {{failed}} विफल", + "starting": "प्रारंभ हो रहा है...", + "queued": "कतार में", + "completed": "पूर्ण", + "failed": "विफल", + "cancelled": "रद्द", + "partial": "आंशिक", + "cancel": "सबएजेंट रद्द करें", + "inspect": "ट्रांसक्रिप्ट खोलें", + "headerChip": "{{count}} सबएजेंट चल रहे हैं", + "metaTools": "{{count}} टूल", + "metaRead": "{{count}} पठन", + "metaWritten": "{{count}} लेखन", + "dashRunning": "चल रहा है", + "dashCompleted": "पूर्ण", + "dashFailed": "विफल", + "dashCancelled": "रद्द", + "dashQueued": "कतार में", + "dashWorkingOn": "कार्य कर रहा है", + "dashStarting": "प्रारंभ हो रहा है…", + "dashInstruction": "निर्देश", + "dashProgress": "प्रगति", + "dashConclusion": "निष्कर्ष", + "dashPartial": "समाप्त करने से पहले टर्न सीमा पर रोक दिया गया", + "dashNoSummary": "कोई सारांश नहीं लौटाया गया", + "dashCancelledOutcome": "चलन रद्द", + "dashShowMoreCount": "{{count}} और दिखाएँ", + "dashShowLess": "कम दिखाएँ", + "worktreeKept": "वर्कट्री रखा गया", + "worktreeRemoved": "वर्कट्री हटाया गया", + "viewLive": "लाइव देखें", + "liveTitle": "लाइव ट्रांसक्रिप्ट", + "close": "बंद करें", + "loadEarlier": "पहले के लोड करें", + "noActivity": "अभी तक कोई टूल गतिविधि नहीं", + "liveEnded": "रन समाप्त", + "roleUser": "उपयोगकर्ता", + "roleAssistant": "एजेंट", + "reasoning": "तर्क", + "result": "परिणाम", + "actions": { + "readfile": "फ़ाइल पढ़ें", + "searchfiles": "फ़ाइलें खोजें", + "listfiles": "निर्देशिका सूची करें", + "codebasesearch": "कोडबेस खोजें", + "executecommand": "कमांड चलाएँ", + "writetofile": "फ़ाइल लिखें", + "editfile": "फ़ाइल संपादित करें", + "completion": "अंतिम रिपोर्ट लिखें" + } } } diff --git a/webview-ui/src/i18n/locales/hi/settings.json b/webview-ui/src/i18n/locales/hi/settings.json index f7db8b690a1..2405a2b6f34 100644 --- a/webview-ui/src/i18n/locales/hi/settings.json +++ b/webview-ui/src/i18n/locales/hi/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "प्रदाता", "modes": "मोड", + "subagents": "सबएजेंट", "mcp": "एमसीपी सर्वर", "worktrees": "Worktrees", "autoApprove": "अनुमोदन", @@ -708,6 +709,20 @@ "setupInstructions": "सेटअप निर्देश" } }, + "subagents": { + "enable": { + "label": "सबएजेंट सक्षम करें", + "description": "सक्षम होने पर, फुल-टूल मोड हेडलेस सबएजेंट बना सकते हैं जो समानांतर चलते हैं। प्रत्येक सबएजेंट अपने स्वयं के संदर्भ में काम करता है और मुख्य चैट में केवल सारांश लौटाता है।" + }, + "concurrency": { + "label": "अधिकतम समवर्ती सबएजेंट", + "description": "एक साथ कितने सबएजेंट चल सकते हैं। अतिरिक्त रन कतार में प्रतीक्षा करते हैं।" + }, + "maxTurns": { + "label": "प्रति सबएजेंट डिफ़ॉल्ट अधिकतम टर्न", + "description": "उन सबएजेंट के लिए टर्न सीमा जिनकी परिभाषा कोई सीमा निर्धारित नहीं करती। सीमा तक पहुँचने वाला सबएजेंट रुक जाता है और आंशिक सारांश लौटाता है। 0 का अर्थ असीमित है।" + } + }, "checkpoints": { "timeout": { "label": "चेकपॉइंट इनिशियलाइज़ेशन टाइमआउट (सेकंड)", diff --git a/webview-ui/src/i18n/locales/id/chat.json b/webview-ui/src/i18n/locales/id/chat.json index 2cc81e8ce40..4708705c3dc 100644 --- a/webview-ui/src/i18n/locales/id/chat.json +++ b/webview-ui/src/i18n/locales/id/chat.json @@ -513,5 +513,59 @@ }, "diffView": { "hiddenLines_other": "{{count}} baris tersembunyi" + }, + "subagents": { + "groupRunning": "Subagen · {{active}} dari {{total}} berjalan", + "groupDone": "Subagen · {{completed}} dari {{total}} selesai", + "groupDoneWithFailures": "Subagen · {{completed}} selesai · {{failed}} gagal", + "starting": "Memulai...", + "queued": "Antrean", + "completed": "Selesai", + "failed": "Gagal", + "cancelled": "Dibatalkan", + "partial": "sebagian", + "cancel": "Batalkan subagen", + "inspect": "Buka transkrip", + "headerChip": "{{count}} subagen berjalan", + "metaTools": "{{count}} alat", + "metaRead": "{{count}} baca", + "metaWritten": "{{count}} tulis", + "dashRunning": "Berjalan", + "dashCompleted": "Selesai", + "dashFailed": "Gagal", + "dashCancelled": "Dibatalkan", + "dashQueued": "Dalam antrean", + "dashWorkingOn": "Mengerjakan", + "dashStarting": "Memulai…", + "dashInstruction": "Instruksi", + "dashProgress": "Kemajuan", + "dashConclusion": "Kesimpulan", + "dashPartial": "Berhenti di batas giliran sebelum selesai", + "dashNoSummary": "Tidak ada ringkasan yang dikembalikan", + "dashCancelledOutcome": "Eksekusi dibatalkan", + "dashShowMoreCount": "Tampilkan {{count}} lainnya", + "dashShowLess": "Tampilkan lebih sedikit", + "worktreeKept": "worktree dipertahankan", + "worktreeRemoved": "worktree dihapus", + "viewLive": "Lihat langsung", + "liveTitle": "Transkrip langsung", + "close": "Tutup", + "loadEarlier": "Muat lebih awal", + "noActivity": "Belum ada aktivitas alat", + "liveEnded": "Jalur selesai", + "roleUser": "Pengguna", + "roleAssistant": "Agen", + "reasoning": "Penalaran", + "result": "Hasil", + "actions": { + "readfile": "Baca berkas", + "searchfiles": "Cari berkas", + "listfiles": "Daftar direktori", + "codebasesearch": "Cari kode", + "executecommand": "Jalankan perintah", + "writetofile": "Tulis berkas", + "editfile": "Edit berkas", + "completion": "Tulis laporan akhir" + } } } diff --git a/webview-ui/src/i18n/locales/id/settings.json b/webview-ui/src/i18n/locales/id/settings.json index 5867d6d7c0f..de626e722b3 100644 --- a/webview-ui/src/i18n/locales/id/settings.json +++ b/webview-ui/src/i18n/locales/id/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Provider", "modes": "Mode", + "subagents": "Subagen", "mcp": "Server MCP", "worktrees": "Worktrees", "autoApprove": "Auto-Approve", @@ -707,6 +708,20 @@ "setupInstructions": "Petunjuk penyiapan" } }, + "subagents": { + "enable": { + "label": "Aktifkan subagen", + "description": "Saat diaktifkan, mode tool lengkap dapat membuat subagen headless yang berjalan paralel. Setiap subagen bekerja dalam konteksnya sendiri dan hanya mengembalikan ringkasan ke obrolan utama." + }, + "concurrency": { + "label": "Subagen bersamaan maksimum", + "description": "Berapa banyak subagen yang dapat berjalan sekaligus. Jalur tambahan menunggu dalam antrean." + }, + "maxTurns": { + "label": "Putaran maksimum default per subagen", + "description": "Batas putaran untuk subagen yang definisinya tidak menetapkannya. Subagen yang mencapai batas berhenti dan mengembalikan ringkasan parsial. 0 berarti tanpa batas." + } + }, "checkpoints": { "timeout": { "label": "Batas waktu inisialisasi checkpoint (detik)", diff --git a/webview-ui/src/i18n/locales/it/chat.json b/webview-ui/src/i18n/locales/it/chat.json index 5feab1f5e6e..85c2e3d99d8 100644 --- a/webview-ui/src/i18n/locales/it/chat.json +++ b/webview-ui/src/i18n/locales/it/chat.json @@ -523,5 +523,59 @@ "hiddenLines_one": "{{count}} riga nascosta", "hiddenLines_many": "{{count}} di righe nascoste", "hiddenLines_other": "{{count}} righe nascoste" + }, + "subagents": { + "groupRunning": "Sottoagenti · {{active}} di {{total}} in esecuzione", + "groupDone": "Sottoagenti · {{completed}} di {{total}} completati", + "groupDoneWithFailures": "Sottoagenti · {{completed}} completati · {{failed}} falliti", + "starting": "Avvio...", + "queued": "In coda", + "completed": "Completato", + "failed": "Fallito", + "cancelled": "Annullato", + "partial": "parziale", + "cancel": "Annulla sottoagente", + "inspect": "Apri trascrizione", + "headerChip": "{{count}} sottoagente/i in esecuzione", + "metaTools": "{{count}} strumenti", + "metaRead": "{{count}} letture", + "metaWritten": "{{count}} scritture", + "dashRunning": "In esecuzione", + "dashCompleted": "Completato", + "dashFailed": "Fallito", + "dashCancelled": "Annullato", + "dashQueued": "In coda", + "dashWorkingOn": "Lavorando su", + "dashStarting": "Avvio…", + "dashInstruction": "Istruzione", + "dashProgress": "Avanzamento", + "dashConclusion": "Conclusione", + "dashPartial": "Interrotto al limite di turni prima di finire", + "dashNoSummary": "Nessun riepilogo restituito", + "dashCancelledOutcome": "Esecuzione annullata", + "dashShowMoreCount": "Mostra altri {{count}}", + "dashShowLess": "Mostra meno", + "worktreeKept": "worktree mantenuto", + "worktreeRemoved": "worktree rimosso", + "viewLive": "Vedi in diretta", + "liveTitle": "Trascrizione in diretta", + "close": "Chiudi", + "loadEarlier": "Carica prima", + "noActivity": "Ancora nessuna attività strumento", + "liveEnded": "Esecuzione terminata", + "roleUser": "Utente", + "roleAssistant": "Agente", + "reasoning": "Ragionamento", + "result": "Risultato", + "actions": { + "readfile": "Leggi file", + "searchfiles": "Cerca file", + "listfiles": "Elenca directory", + "codebasesearch": "Cerca nel codice", + "executecommand": "Esegui comando", + "writetofile": "Scrivi file", + "editfile": "Modifica file", + "completion": "Scrivi rapporto finale" + } } } diff --git a/webview-ui/src/i18n/locales/it/settings.json b/webview-ui/src/i18n/locales/it/settings.json index e039482ea87..05cafbb2fbd 100644 --- a/webview-ui/src/i18n/locales/it/settings.json +++ b/webview-ui/src/i18n/locales/it/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Fornitori", "modes": "Modalità", + "subagents": "Sottoagenti", "mcp": "Server MCP", "worktrees": "Worktrees", "autoApprove": "Auto-approvazione", @@ -709,6 +710,20 @@ "setupInstructions": "Istruzioni di configurazione" } }, + "subagents": { + "enable": { + "label": "Abilita sottoagenti", + "description": "Se abilitata, le modalità complete possono generare sottoagenti headless che girano in parallelo. Ogni sottoagente lavora nel proprio contesto e restituisce solo un riepilogo alla chat principale." + }, + "concurrency": { + "label": "Massimo sottoagenti concorrenti", + "description": "Quanti sottoagenti possono girare contemporaneamente. Le esecuzioni aggiuntive attendono in coda." + }, + "maxTurns": { + "label": "Turni massimi predefiniti per sottoagente", + "description": "Limite di turni per sottoagenti la cui definizione non ne imposta uno. Un sottoagente che raggiunge il limite si ferma e restituisce un riepilogo parziale. 0 significa illimitato." + } + }, "checkpoints": { "timeout": { "label": "Timeout inizializzazione checkpoint (secondi)", diff --git a/webview-ui/src/i18n/locales/ja/chat.json b/webview-ui/src/i18n/locales/ja/chat.json index 09502e1a5fa..c184fabd773 100644 --- a/webview-ui/src/i18n/locales/ja/chat.json +++ b/webview-ui/src/i18n/locales/ja/chat.json @@ -507,5 +507,59 @@ }, "diffView": { "hiddenLines_other": "{{count}} 行が非表示" + }, + "subagents": { + "groupRunning": "サブエージェント · {{total}}件中{{active}}件実行中", + "groupDone": "サブエージェント · {{total}}件中{{completed}}件完了", + "groupDoneWithFailures": "サブエージェント · {{completed}}件完了 · {{failed}}件失敗", + "starting": "起動中...", + "queued": "待機中", + "completed": "完了", + "failed": "失敗", + "cancelled": "キャンセル", + "partial": "部分的", + "cancel": "サブエージェントをキャンセル", + "inspect": "トランスクリプトを開く", + "headerChip": "{{count}}個のサブエージェントが実行中", + "metaTools": "ツール{{count}}件", + "metaRead": "読み取り{{count}}件", + "metaWritten": "書き込み{{count}}件", + "dashRunning": "実行中", + "dashCompleted": "完了", + "dashFailed": "失敗", + "dashCancelled": "キャンセル済み", + "dashQueued": "待機中", + "dashWorkingOn": "作業中", + "dashStarting": "開始中…", + "dashInstruction": "指示", + "dashProgress": "進捗", + "dashConclusion": "結論", + "dashPartial": "制限ターンに達して完了前に停止", + "dashNoSummary": "要約が返されませんでした", + "dashCancelledOutcome": "実行をキャンセル", + "dashShowMoreCount": "さらに{{count}}件表示", + "dashShowLess": "表示を減らす", + "worktreeKept": "ワークツリーを保持", + "worktreeRemoved": "ワークツリーを削除", + "viewLive": "ライブで見る", + "liveTitle": "ライブトランスクリプト", + "close": "閉じる", + "loadEarlier": "以前を読み込む", + "noActivity": "ツールのアクティビティはまだありません", + "liveEnded": "実行が終了しました", + "roleUser": "ユーザー", + "roleAssistant": "エージェント", + "reasoning": "推論", + "result": "結果", + "actions": { + "readfile": "ファイルを読む", + "searchfiles": "ファイルを検索", + "listfiles": "ディレクトリを一覧", + "codebasesearch": "コードベースを検索", + "executecommand": "コマンドを実行", + "writetofile": "ファイルを書く", + "editfile": "ファイルを編集", + "completion": "最終レポートを書く" + } } } diff --git a/webview-ui/src/i18n/locales/ja/settings.json b/webview-ui/src/i18n/locales/ja/settings.json index 993a824113b..ae941de5042 100644 --- a/webview-ui/src/i18n/locales/ja/settings.json +++ b/webview-ui/src/i18n/locales/ja/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "プロバイダー", "modes": "モード", + "subagents": "サブエージェント", "mcp": "MCPサーバー", "worktrees": "Worktrees", "autoApprove": "自動承認", @@ -707,6 +708,20 @@ "setupInstructions": "セットアップ手順" } }, + "subagents": { + "enable": { + "label": "サブエージェントを有効化", + "description": "有効にすると、フルツールモードは並行して実行されるヘッドレスサブエージェントを生成できます。各サブエージェントは独自のコンテキストで動作し、メインチャットには概要のみを返します。" + }, + "concurrency": { + "label": "最大同時サブエージェント数", + "description": "同時に実行できるサブエージェントの数です。超過分はキューで待機します。" + }, + "maxTurns": { + "label": "サブエージェントあたりのデフォルト最大ターン数", + "description": "定義で設定されていないサブエージェントに適用されるターン制限です。制限に達したサブエージェントは停止し、部分的な概要を返します。 0は無制限を意味します。" + } + }, "checkpoints": { "timeout": { "label": "チェックポイント初期化タイムアウト(秒)", diff --git a/webview-ui/src/i18n/locales/ko/chat.json b/webview-ui/src/i18n/locales/ko/chat.json index e721f4c9295..019f40bce15 100644 --- a/webview-ui/src/i18n/locales/ko/chat.json +++ b/webview-ui/src/i18n/locales/ko/chat.json @@ -507,5 +507,59 @@ }, "diffView": { "hiddenLines_other": "숨겨진 줄 {{count}}개" + }, + "subagents": { + "groupRunning": "서브에이전트 · {{total}}개 중 {{active}}개 실행 중", + "groupDone": "서브에이전트 · {{total}}개 중 {{completed}}개 완료", + "groupDoneWithFailures": "서브에이전트 · {{completed}}개 완료 · {{failed}}개 실패", + "starting": "시작 중...", + "queued": "대기 중", + "completed": "완료됨", + "failed": "실패함", + "cancelled": "취소됨", + "partial": "부분 완료", + "cancel": "서브에이전트 취소", + "inspect": "트랜스크립트 열기", + "headerChip": "서브에이전트 {{count}}개 실행 중", + "metaTools": "도구 {{count}}개", + "metaRead": "읽기 {{count}}개", + "metaWritten": "쓰기 {{count}}개", + "dashRunning": "실행 중", + "dashCompleted": "완료", + "dashFailed": "실패", + "dashCancelled": "취소됨", + "dashQueued": "대기 중", + "dashWorkingOn": "작업 중", + "dashStarting": "시작 중…", + "dashInstruction": "지시", + "dashProgress": "진행", + "dashConclusion": "결론", + "dashPartial": "완료 전에 턴 제한에서 중지됨", + "dashNoSummary": "반환된 요약이 없습니다", + "dashCancelledOutcome": "실행 취소됨", + "dashShowMoreCount": "{{count}}개 더 보기", + "dashShowLess": "간단히 보기", + "worktreeKept": "워크트리 유지됨", + "worktreeRemoved": "워크트리 삭제됨", + "viewLive": "라이브 보기", + "liveTitle": "라이브 트랜스크립트", + "close": "닫기", + "loadEarlier": "이전 항목 불러오기", + "noActivity": "아직 툴 활동 없음", + "liveEnded": "실행 종료", + "roleUser": "사용자", + "roleAssistant": "에이전트", + "reasoning": "추론", + "result": "결과", + "actions": { + "readfile": "파일 읽기", + "searchfiles": "파일 검색", + "listfiles": "디렉터리 나열", + "codebasesearch": "코드베이스 검색", + "executecommand": "명령 실행", + "writetofile": "파일 쓰기", + "editfile": "파일 편집", + "completion": "최종 보고서 작성" + } } } diff --git a/webview-ui/src/i18n/locales/ko/settings.json b/webview-ui/src/i18n/locales/ko/settings.json index dfd40fef0c0..ebd945dd44e 100644 --- a/webview-ui/src/i18n/locales/ko/settings.json +++ b/webview-ui/src/i18n/locales/ko/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "공급자", "modes": "모드", + "subagents": "서브에이전트", "mcp": "MCP 서버", "worktrees": "Worktrees", "autoApprove": "자동 승인", @@ -707,6 +708,20 @@ "setupInstructions": "설정 안내" } }, + "subagents": { + "enable": { + "label": "서브에이전트 활성화", + "description": "활성화하면 전체 도구 모드가 병렬로 실행되는 헤드리스 서브에이전트를 생성할 수 있습니다. 각 서브에이전트는 자체 컨텍스트에서 작업하고 요약만 메인 채팅으로 반환합니다." + }, + "concurrency": { + "label": "최대 동시 서브에이전트 수", + "description": "동시에 실행할 수 있는 서브에이전트 수입니다. 초과된 실행은 대기열에서 기다립니다." + }, + "maxTurns": { + "label": "서브에이전트 기본 최대 턴 수", + "description": "정의에 최대 턴 수가 없는 서브에이전트에 적용되는 턴 제한입니다. 제한에 도달한 서브에이전트는 중단하고 부분 요약을 반환합니다. 0이면 무제한입니다." + } + }, "checkpoints": { "timeout": { "label": "체크포인트 초기화 타임아웃(초)", diff --git a/webview-ui/src/i18n/locales/nl/chat.json b/webview-ui/src/i18n/locales/nl/chat.json index d44c502e456..5ac9b066f4a 100644 --- a/webview-ui/src/i18n/locales/nl/chat.json +++ b/webview-ui/src/i18n/locales/nl/chat.json @@ -515,5 +515,59 @@ "diffView": { "hiddenLines_one": "{{count}} verborgen regel", "hiddenLines_other": "{{count}} verborgen regels" + }, + "subagents": { + "groupRunning": "Subagenten · {{active}} van {{total}} actief", + "groupDone": "Subagenten · {{completed}} van {{total}} klaar", + "groupDoneWithFailures": "Subagenten · {{completed}} voltooid · {{failed}} mislukt", + "starting": "Starten...", + "queued": "In wachtrij", + "completed": "Voltooid", + "failed": "Mislukt", + "cancelled": "Geannuleerd", + "partial": "gedeeltelijk", + "cancel": "Subagent annuleren", + "inspect": "Transcript openen", + "headerChip": "{{count}} subagent(en) actief", + "metaTools": "{{count}} tools", + "metaRead": "{{count}} gelezen", + "metaWritten": "{{count}} geschreven", + "dashRunning": "Bezig", + "dashCompleted": "Voltooid", + "dashFailed": "Mislukt", + "dashCancelled": "Geannuleerd", + "dashQueued": "In wachtrij", + "dashWorkingOn": "Werkt aan", + "dashStarting": "Start…", + "dashInstruction": "Instructie", + "dashProgress": "Voortgang", + "dashConclusion": "Conclusie", + "dashPartial": "Gestopt bij de turnlimiet vóór voltooiing", + "dashNoSummary": "Geen samenvatting geretourneerd", + "dashCancelledOutcome": "Uitvoering geannuleerd", + "dashShowMoreCount": "Nog {{count}} meer weergeven", + "dashShowLess": "Minder weergeven", + "worktreeKept": "worktree behouden", + "worktreeRemoved": "worktree verwijderd", + "viewLive": "Live bekijken", + "liveTitle": "Live-transcript", + "close": "Sluiten", + "loadEarlier": "Eerder laden", + "noActivity": "Nog geen tool-activiteit", + "liveEnded": "Uitvoering beëindigd", + "roleUser": "Gebruiker", + "roleAssistant": "Agent", + "reasoning": "Redenering", + "result": "Resultaat", + "actions": { + "readfile": "Bestand lezen", + "searchfiles": "Bestanden zoeken", + "listfiles": "Map weergeven", + "codebasesearch": "Code doorzoeken", + "executecommand": "Opdracht uitvoeren", + "writetofile": "Bestand schrijven", + "editfile": "Bestand bewerken", + "completion": "Eindrapport schrijven" + } } } diff --git a/webview-ui/src/i18n/locales/nl/settings.json b/webview-ui/src/i18n/locales/nl/settings.json index eb89ef8a169..b4a797a38af 100644 --- a/webview-ui/src/i18n/locales/nl/settings.json +++ b/webview-ui/src/i18n/locales/nl/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Providers", "modes": "Modi", + "subagents": "Subagenten", "mcp": "MCP-servers", "worktrees": "Worktrees", "autoApprove": "Auto-goedkeuren", @@ -708,6 +709,20 @@ "setupInstructions": "Installatie-instructies" } }, + "subagents": { + "enable": { + "label": "Subagenten inschakelen", + "description": "Indien ingeschakeld kunnen volledige-toolmodi headless subagenten maken die parallel draaien. Elke subagent werkt in eigen context en geeft alleen een samenvatting terug aan de hoofdchat." + }, + "concurrency": { + "label": "Maximale gelijktijdige subagenten", + "description": "Hoeveel subagenten er tegelijk mogen draaien. Extra runs wachten in een wachtrij." + }, + "maxTurns": { + "label": "Standaard maximale beurten per subagent", + "description": "Beurtenlimiet voor subagenten waarvan de definitie er geen heeft. Een subagent die de limiet bereikt stopt en geeft een gedeeltelijke samenvatting. 0 betekent onbeperkt." + } + }, "checkpoints": { "timeout": { "label": "Timeout voor checkpoint-initialisatie (seconden)", diff --git a/webview-ui/src/i18n/locales/pl/chat.json b/webview-ui/src/i18n/locales/pl/chat.json index 858661602f4..86073b5e763 100644 --- a/webview-ui/src/i18n/locales/pl/chat.json +++ b/webview-ui/src/i18n/locales/pl/chat.json @@ -531,5 +531,59 @@ "hiddenLines_few": "{{count}} ukryte wiersze", "hiddenLines_many": "{{count}} ukrytych wierszy", "hiddenLines_other": "{{count}} ukrytego wiersza" + }, + "subagents": { + "groupRunning": "Podagenci · {{active}} z {{total}} działa", + "groupDone": "Podagenci · {{completed}} z {{total}} zakończonych", + "groupDoneWithFailures": "Podagenci · {{completed}} ukończonych · {{failed}} nieudanych", + "starting": "Uruchamianie...", + "queued": "W kolejce", + "completed": "Ukończono", + "failed": "Niepowodzenie", + "cancelled": "Anulowano", + "partial": "częściowy", + "cancel": "Anuluj podagenta", + "inspect": "Otwórz transkrypt", + "headerChip": "{{count}} podagentów działa", + "metaTools": "{{count}} narzędzi", + "metaRead": "{{count}} odczytów", + "metaWritten": "{{count}} zapisów", + "dashRunning": "Działa", + "dashCompleted": "Ukończono", + "dashFailed": "Niepowodzenie", + "dashCancelled": "Anulowano", + "dashQueued": "W kolejce", + "dashWorkingOn": "Pracuje nad", + "dashStarting": "Uruchamianie…", + "dashInstruction": "Instrukcja", + "dashProgress": "Postęp", + "dashConclusion": "Podsumowanie", + "dashPartial": "Zatrzymano na limicie tur przed ukończeniem", + "dashNoSummary": "Nie zwrócono podsumowania", + "dashCancelledOutcome": "Uruchomienie anulowane", + "dashShowMoreCount": "Pokaż {{count}} więcej", + "dashShowLess": "Pokaż mniej", + "worktreeKept": "worktree zachowany", + "worktreeRemoved": "worktree usunięty", + "viewLive": "Oglądaj na żywo", + "liveTitle": "Transkrypt na żywo", + "close": "Zamknij", + "loadEarlier": "Załaduj wcześniejsze", + "noActivity": "Brak aktywności narzędzi", + "liveEnded": "Uruchomienie zakończone", + "roleUser": "Użytkownik", + "roleAssistant": "Agent", + "reasoning": "Rozumowanie", + "result": "Wynik", + "actions": { + "readfile": "Czytaj plik", + "searchfiles": "Szukaj plików", + "listfiles": "Lista katalogu", + "codebasesearch": "Szukaj w kodzie", + "executecommand": "Wykonaj polecenie", + "writetofile": "Napisz plik", + "editfile": "Edytuj plik", + "completion": "Napisz raport końcowy" + } } } diff --git a/webview-ui/src/i18n/locales/pl/settings.json b/webview-ui/src/i18n/locales/pl/settings.json index 7c8a1b7b0f4..e2cbfb3a983 100644 --- a/webview-ui/src/i18n/locales/pl/settings.json +++ b/webview-ui/src/i18n/locales/pl/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Dostawcy", "modes": "Tryby", + "subagents": "Podagenci", "mcp": "Serwery MCP", "worktrees": "Worktrees", "autoApprove": "Auto-zatwierdzanie", @@ -710,6 +711,20 @@ "setupInstructions": "Instrukcja konfiguracji" } }, + "subagents": { + "enable": { + "label": "Włącz podagentów", + "description": "Po włączeniu tryby pełnych narzędzi mogą tworzyć bezgłowych podagentów działających równolegle. Każdy podagent działa we własnym kontekście i zwraca do głównego czatu tylko podsumowanie." + }, + "concurrency": { + "label": "Maksymalna liczba równoczesnych podagentów", + "description": "Ile podagentów może działać jednocześnie. Dodatkowe uruchomienia czekają w kolejce." + }, + "maxTurns": { + "label": "Domyślna maksymalna liczba tur na podagenta", + "description": "Limit tur dla podagentów, których definicja go nie określa. Podagent, który osiągnie limit, zatrzymuje się i zwraca częściowe podsumowanie. 0 oznacza nieograniczony." + } + }, "checkpoints": { "timeout": { "label": "Limit czasu inicjalizacji punktu kontrolnego (sekundy)", diff --git a/webview-ui/src/i18n/locales/pt-BR/chat.json b/webview-ui/src/i18n/locales/pt-BR/chat.json index 75227312095..87b59c8bcdb 100644 --- a/webview-ui/src/i18n/locales/pt-BR/chat.json +++ b/webview-ui/src/i18n/locales/pt-BR/chat.json @@ -523,5 +523,59 @@ "hiddenLines_one": "{{count}} linha oculta", "hiddenLines_many": "{{count}} de linhas ocultas", "hiddenLines_other": "{{count}} linhas ocultas" + }, + "subagents": { + "groupRunning": "Subagentes · {{active}} de {{total}} em execução", + "groupDone": "Subagentes · {{completed}} de {{total}} concluídos", + "groupDoneWithFailures": "Subagentes · {{completed}} concluídos · {{failed}} com falha", + "starting": "Iniciando...", + "queued": "Na fila", + "completed": "Concluído", + "failed": "Falhou", + "cancelled": "Cancelado", + "partial": "parcial", + "cancel": "Cancelar subagente", + "inspect": "Abrir transcrição", + "headerChip": "{{count}} subagente(s) em execução", + "metaTools": "{{count}} ferramentas", + "metaRead": "{{count}} leituras", + "metaWritten": "{{count}} escritas", + "dashRunning": "Em execução", + "dashCompleted": "Concluído", + "dashFailed": "Falhou", + "dashCancelled": "Cancelado", + "dashQueued": "Na fila", + "dashWorkingOn": "Trabalhando em", + "dashStarting": "Iniciando…", + "dashInstruction": "Instrução", + "dashProgress": "Progresso", + "dashConclusion": "Conclusão", + "dashPartial": "Parado no limite de turnos antes de concluir", + "dashNoSummary": "Nenhum resumo retornado", + "dashCancelledOutcome": "Execução cancelada", + "dashShowMoreCount": "Mostrar mais {{count}}", + "dashShowLess": "Mostrar menos", + "worktreeKept": "worktree mantido", + "worktreeRemoved": "worktree removido", + "viewLive": "Ver ao vivo", + "liveTitle": "Transcrição ao vivo", + "close": "Fechar", + "loadEarlier": "Carregar anteriores", + "noActivity": "Ainda sem atividade de ferramentas", + "liveEnded": "Execução encerrada", + "roleUser": "Usuário", + "roleAssistant": "Agente", + "reasoning": "Raciocínio", + "result": "Resultado", + "actions": { + "readfile": "Ler arquivo", + "searchfiles": "Buscar arquivos", + "listfiles": "Listar diretório", + "codebasesearch": "Buscar no código", + "executecommand": "Executar comando", + "writetofile": "Escrever arquivo", + "editfile": "Editar arquivo", + "completion": "Escrever relatório final" + } } } diff --git a/webview-ui/src/i18n/locales/pt-BR/settings.json b/webview-ui/src/i18n/locales/pt-BR/settings.json index 00373b0c758..0552edd67b9 100644 --- a/webview-ui/src/i18n/locales/pt-BR/settings.json +++ b/webview-ui/src/i18n/locales/pt-BR/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Provedores", "modes": "Modos", + "subagents": "Subagentes", "mcp": "Servidores MCP", "worktrees": "Worktrees", "autoApprove": "Aprovação", @@ -709,6 +710,20 @@ "setupInstructions": "Instruções de configuração" } }, + "subagents": { + "enable": { + "label": "Habilitar subagentes", + "description": "Quando habilitado, os modos completos podem gerar subagentes headless que rodam em paralelo. Cada subagente trabalha em seu próprio contexto e retorna apenas um resumo ao chat principal." + }, + "concurrency": { + "label": "Máximo de subagentes simultâneos", + "description": "Quantos subagentes podem rodar ao mesmo tempo. Execuções adicionais aguardam em uma fila." + }, + "maxTurns": { + "label": "Máximo de turnos padrão por subagente", + "description": "Limite de turnos para subagentes cuja definição não define um. Um subagente que atinge o limite para e retorna um resumo parcial. 0 significa sem limite." + } + }, "checkpoints": { "timeout": { "label": "Tempo limite para inicialização do checkpoint (segundos)", diff --git a/webview-ui/src/i18n/locales/ru/chat.json b/webview-ui/src/i18n/locales/ru/chat.json index a96573ec152..6b90c2629d4 100644 --- a/webview-ui/src/i18n/locales/ru/chat.json +++ b/webview-ui/src/i18n/locales/ru/chat.json @@ -532,5 +532,59 @@ "hiddenLines_few": "{{count}} скрытые строки", "hiddenLines_many": "{{count}} скрытых строк", "hiddenLines_other": "{{count}} скрытой строки" + }, + "subagents": { + "groupRunning": "Суб-агенты · {{active}} из {{total}} выполняется", + "groupDone": "Суб-агенты · {{completed}} из {{total}} завершено", + "groupDoneWithFailures": "Суб-агенты · {{completed}} завершено · {{failed}} с ошибкой", + "starting": "Запуск...", + "queued": "В очереди", + "completed": "Завершено", + "failed": "Ошибка", + "cancelled": "Отменено", + "partial": "частично", + "cancel": "Отменить суб-агента", + "inspect": "Открыть стенограмму", + "headerChip": "{{count}} суб-агента работает", + "metaTools": "{{count}} инструментов", + "metaRead": "{{count}} чтений", + "metaWritten": "{{count}} записей", + "dashRunning": "Выполняется", + "dashCompleted": "Завершено", + "dashFailed": "Ошибка", + "dashCancelled": "Отменено", + "dashQueued": "В очереди", + "dashWorkingOn": "Работает над", + "dashStarting": "Запуск…", + "dashInstruction": "Задача", + "dashProgress": "Выполнение", + "dashConclusion": "Вывод", + "dashPartial": "Остановлено на лимите ходов перед завершением", + "dashNoSummary": "Резюме не возвращено", + "dashCancelledOutcome": "Выполнение отменено", + "dashShowMoreCount": "Показать ещё {{count}}", + "dashShowLess": "Показать меньше", + "worktreeKept": "worktree сохранён", + "worktreeRemoved": "worktree удалён", + "viewLive": "Смотреть вживую", + "liveTitle": "Живая стенограмма", + "close": "Закрыть", + "loadEarlier": "Загрузить раньше", + "noActivity": "Пока нет действий инструментов", + "liveEnded": "Выполнение завершено", + "roleUser": "Пользователь", + "roleAssistant": "Агент", + "reasoning": "Рассуждение", + "result": "Результат", + "actions": { + "readfile": "Читать файл", + "searchfiles": "Искать файлы", + "listfiles": "Список каталога", + "codebasesearch": "Искать в коде", + "executecommand": "Выполнить команду", + "writetofile": "Записать файл", + "editfile": "Редактировать файл", + "completion": "Написать итоговый отчёт" + } } } diff --git a/webview-ui/src/i18n/locales/ru/settings.json b/webview-ui/src/i18n/locales/ru/settings.json index 1bf867bd627..bef3e402e7c 100644 --- a/webview-ui/src/i18n/locales/ru/settings.json +++ b/webview-ui/src/i18n/locales/ru/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Провайдеры", "modes": "Режимы", + "subagents": "Суб-агенты", "mcp": "Серверы MCP", "worktrees": "Worktrees", "autoApprove": "Автоодобрение", @@ -710,6 +711,20 @@ "setupInstructions": "Инструкция по настройке" } }, + "subagents": { + "enable": { + "label": "Включить суб-агентов", + "description": "При включении полноинструментальные режимы могут создавать headless суб-агентов, работающих параллельно. Каждый суб-агент работает в своём контексте и возвращает в основной чат только сводку." + }, + "concurrency": { + "label": "Максимум одновременных суб-агентов", + "description": "Сколько суб-агентов может работать одновременно. Дополнительные запуски ожидают в очереди." + }, + "maxTurns": { + "label": "Максимум ходов по умолчанию на суб-агента", + "description": "Лимит ходов для суб-агентов, в определении которых он не задан. Суб-агент, достигший лимита, останавливается и возвращает частичную сводку. 0 означает без ограничений." + } + }, "checkpoints": { "timeout": { "label": "Таймаут инициализации контрольной точки (секунды)", diff --git a/webview-ui/src/i18n/locales/tr/chat.json b/webview-ui/src/i18n/locales/tr/chat.json index 973518476e1..bd684a83a77 100644 --- a/webview-ui/src/i18n/locales/tr/chat.json +++ b/webview-ui/src/i18n/locales/tr/chat.json @@ -516,5 +516,59 @@ "diffView": { "hiddenLines_one": "{{count}} gizli satır", "hiddenLines_other": "{{count}} gizli satır" + }, + "subagents": { + "groupRunning": "Alt ajanlar · {{total}} üzerinden {{active}} çalışıyor", + "groupDone": "Alt ajanlar · {{total}} üzerinden {{completed}} tamamlandı", + "groupDoneWithFailures": "Alt ajanlar · {{completed}} tamamlandı · {{failed}} başarısız", + "starting": "Başlatılıyor...", + "queued": "Sırada", + "completed": "Tamamlandı", + "failed": "Başarısız", + "cancelled": "İptal edildi", + "partial": "kısmi", + "cancel": "Alt ajanı iptal et", + "inspect": "Dökümü aç", + "headerChip": "{{count}} alt ajan çalışıyor", + "metaTools": "{{count}} araç", + "metaRead": "{{count}} okuma", + "metaWritten": "{{count}} yazma", + "dashRunning": "Çalışıyor", + "dashCompleted": "Tamamlandı", + "dashFailed": "Başarısız", + "dashCancelled": "İptal edildi", + "dashQueued": "Sırada", + "dashWorkingOn": "Üzerinde çalışıyor", + "dashStarting": "Başlatılıyor…", + "dashInstruction": "Talimat", + "dashProgress": "İlerleme", + "dashConclusion": "Sonuç", + "dashPartial": "Bitirmeden önce tur sınırında durduruldu", + "dashNoSummary": "Özet döndürülmedi", + "dashCancelledOutcome": "Çalıştırma iptal edildi", + "dashShowMoreCount": "{{count}} tane daha göster", + "dashShowLess": "Daha az göster", + "worktreeKept": "worktree korundu", + "worktreeRemoved": "worktree kaldırıldı", + "viewLive": "Canlı izle", + "liveTitle": "Canlı döküm", + "close": "Kapat", + "loadEarlier": "Daha öncekileri yükle", + "noActivity": "Henüz araç etkinliği yok", + "liveEnded": "Çalıştırma sona erdi", + "roleUser": "Kullanıcı", + "roleAssistant": "Ajan", + "reasoning": "Gerekçe", + "result": "Sonuç", + "actions": { + "readfile": "Dosya oku", + "searchfiles": "Dosya ara", + "listfiles": "Dizini listele", + "codebasesearch": "Kodda ara", + "executecommand": "Komut çalıştır", + "writetofile": "Dosya yaz", + "editfile": "Dosyayı düzenle", + "completion": "Son raporu yaz" + } } } diff --git a/webview-ui/src/i18n/locales/tr/settings.json b/webview-ui/src/i18n/locales/tr/settings.json index 0223b80b2a1..9c482b248d5 100644 --- a/webview-ui/src/i18n/locales/tr/settings.json +++ b/webview-ui/src/i18n/locales/tr/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Sağlayıcılar", "modes": "Modlar", + "subagents": "Alt ajanlar", "mcp": "MCP Sunucuları", "worktrees": "Worktrees", "autoApprove": "Oto-Onay", @@ -708,6 +709,20 @@ "setupInstructions": "Kurulum talimatları" } }, + "subagents": { + "enable": { + "label": "Alt ajanları etkinleştir", + "description": "Etkinleştirildiğinde, tam araç modları paralel çalışan headless alt ajanlar oluşturabilir. Her alt ajan kendi bağlamında çalışır ve ana sohbete yalnızca bir özet döndürür." + }, + "concurrency": { + "label": "Maksimum eşzamanlı alt ajan", + "description": "Aynı anda kaç alt ajanın çalışabileceği. Ek çalıştırmalar kuyrukta bekler." + }, + "maxTurns": { + "label": "Alt ajan başına varsayılan maksimum tur", + "description": "Tanımında belirtilmemiş alt ajanlar için tur sınırı. Sınıra ulaşan bir alt ajan durur ve kısmi bir özet döndürür. 0 sınırsız anlamına gelir." + } + }, "checkpoints": { "timeout": { "label": "Kontrol noktası başlatma zaman aşımı (saniye)", diff --git a/webview-ui/src/i18n/locales/vi/chat.json b/webview-ui/src/i18n/locales/vi/chat.json index 548d4992714..7f2b738113e 100644 --- a/webview-ui/src/i18n/locales/vi/chat.json +++ b/webview-ui/src/i18n/locales/vi/chat.json @@ -508,5 +508,59 @@ }, "diffView": { "hiddenLines_other": "{{count}} dòng bị ẩn" + }, + "subagents": { + "groupRunning": "Tiểu tác nhân · {{active}} trên {{total}} đang chạy", + "groupDone": "Tiểu tác nhân · {{completed}} trên {{total}} đã hoàn thành", + "groupDoneWithFailures": "Tiểu tác nhân · {{completed}} hoàn thành · {{failed}} thất bại", + "starting": "Đang bắt đầu...", + "queued": "Đang chờ", + "completed": "Đã hoàn thành", + "failed": "Thất bại", + "cancelled": "Đã hủy", + "partial": "một phần", + "cancel": "Hủy tiểu tác nhân", + "inspect": "Mở bản ghi", + "headerChip": "{{count}} tiểu tác nhân đang chạy", + "metaTools": "{{count}} công cụ", + "metaRead": "{{count}} lần đọc", + "metaWritten": "{{count}} lần ghi", + "dashRunning": "Đang chạy", + "dashCompleted": "Hoàn tất", + "dashFailed": "Thất bại", + "dashCancelled": "Đã hủy", + "dashQueued": "Đang xếp hàng", + "dashWorkingOn": "Đang thực hiện", + "dashStarting": "Đang bắt đầu…", + "dashInstruction": "Chỉ dẫn", + "dashProgress": "Tiến trình", + "dashConclusion": "Kết luận", + "dashPartial": "Bị dừng ở giới hạn lượt trước khi hoàn tất", + "dashNoSummary": "Không có tóm tắt trả về", + "dashCancelledOutcome": "Đã hủy quá trình chạy", + "dashShowMoreCount": "Hiển thị thêm {{count}}", + "dashShowLess": "Thu gọn", + "worktreeKept": "worktree được giữ", + "worktreeRemoved": "worktree đã xóa", + "viewLive": "Xem trực tiếp", + "liveTitle": "Phiên ghi trực tiếp", + "close": "Đóng", + "loadEarlier": "Tải thêm trước đó", + "noActivity": "Chưa có hoạt động công cụ", + "liveEnded": "Quá trình đã kết thúc", + "roleUser": "Người dùng", + "roleAssistant": "Tác nhân", + "reasoning": "Suy luận", + "result": "Kết quả", + "actions": { + "readfile": "Đọc tệp", + "searchfiles": "Tìm tệp", + "listfiles": "Liệt kê thư mục", + "codebasesearch": "Tìm trong mã", + "executecommand": "Chạy lệnh", + "writetofile": "Ghi tệp", + "editfile": "Sửa tệp", + "completion": "Viết báo cáo cuối" + } } } diff --git a/webview-ui/src/i18n/locales/vi/settings.json b/webview-ui/src/i18n/locales/vi/settings.json index 09976a50fed..784b572ce96 100644 --- a/webview-ui/src/i18n/locales/vi/settings.json +++ b/webview-ui/src/i18n/locales/vi/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "Nhà cung cấp", "modes": "Chế độ", + "subagents": "Tiểu tác nhân", "mcp": "Máy chủ MCP", "worktrees": "Worktrees", "autoApprove": "Phê duyệt", @@ -707,6 +708,20 @@ "setupInstructions": "Hướng dẫn thiết lập" } }, + "subagents": { + "enable": { + "label": "Bật tiểu tác nhân", + "description": "Khi được bật, các chế độ đầy đủ công cụ có thể tạo ra các tiểu tác nhân headless chạy song song. Mỗi tiểu tác nhân làm việc trong ngữ cảnh riêng và chỉ trả về một bản tóm tắt cho cuộc trò chuyện chính." + }, + "concurrency": { + "label": "Số tiểu tác nhân đồng thời tối đa", + "description": "Bao nhiêu tiểu tác nhân có thể chạy cùng lúc. Các lần chạy thêm sẽ chờ trong hàng đợi." + }, + "maxTurns": { + "label": "Số lượt tối đa mặc định cho mỗi tiểu tác nhân", + "description": "Giới hạn lượt cho tiểu tác nhân mà định nghĩa không đặt một lượt. Tiểu tác nhân đạt giới hạn sẽ dừng lại và trả về bản tóm tắt một phần. 0 có nghĩa là không giới hạn." + } + }, "checkpoints": { "timeout": { "label": "Thời gian chờ khởi tạo điểm kiểm tra (giây)", diff --git a/webview-ui/src/i18n/locales/zh-CN/chat.json b/webview-ui/src/i18n/locales/zh-CN/chat.json index 1a4bb6d76e6..13ce1623d66 100644 --- a/webview-ui/src/i18n/locales/zh-CN/chat.json +++ b/webview-ui/src/i18n/locales/zh-CN/chat.json @@ -508,5 +508,59 @@ }, "diffView": { "hiddenLines_other": "已隐藏 {{count}} 行" + }, + "subagents": { + "groupRunning": "子代理 · 共{{total}}个,正在运行{{active}}个", + "groupDone": "子代理 · 共{{total}}个,已完成{{completed}}个", + "groupDoneWithFailures": "子代理 · {{completed}}个已完成 · {{failed}}个失败", + "starting": "正在启动...", + "queued": "等待中", + "completed": "已完成", + "failed": "失败", + "cancelled": "已取消", + "partial": "部分完成", + "cancel": "取消子代理", + "inspect": "打开记录", + "headerChip": "{{count}}个子代理正在运行", + "metaTools": "{{count}}个工具", + "metaRead": "{{count}}次读取", + "metaWritten": "{{count}}次写入", + "dashRunning": "运行中", + "dashCompleted": "已完成", + "dashFailed": "失败", + "dashCancelled": "已取消", + "dashQueued": "排队中", + "dashWorkingOn": "正在处理", + "dashStarting": "正在启动…", + "dashInstruction": "指示", + "dashProgress": "进度", + "dashConclusion": "结论", + "dashPartial": "在完成前于轮次上限处停止", + "dashNoSummary": "未返回摘要", + "dashCancelledOutcome": "已取消运行", + "dashShowMoreCount": "显示更多 {{count}} 条", + "dashShowLess": "显示更少", + "worktreeKept": "工作树已保留", + "worktreeRemoved": "工作树已删除", + "viewLive": "实时查看", + "liveTitle": "实时记录", + "close": "关闭", + "loadEarlier": "加载更早内容", + "noActivity": "暂无工具活动", + "liveEnded": "运行已结束", + "roleUser": "用户", + "roleAssistant": "代理", + "reasoning": "推理", + "result": "结果", + "actions": { + "readfile": "读取文件", + "searchfiles": "搜索文件", + "listfiles": "列出目录", + "codebasesearch": "搜索代码库", + "executecommand": "运行命令", + "writetofile": "写入文件", + "editfile": "编辑文件", + "completion": "编写最终报告" + } } } diff --git a/webview-ui/src/i18n/locales/zh-CN/settings.json b/webview-ui/src/i18n/locales/zh-CN/settings.json index 398b1d6ce04..d0c76334d15 100644 --- a/webview-ui/src/i18n/locales/zh-CN/settings.json +++ b/webview-ui/src/i18n/locales/zh-CN/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "提供商", "modes": "模式", + "subagents": "子代理", "mcp": "MCP 服务", "worktrees": "Worktrees", "autoApprove": "自动批准", @@ -707,6 +708,20 @@ "setupInstructions": "设置说明" } }, + "subagents": { + "enable": { + "label": "启用子代理", + "description": "启用后,完整工具模式可以创建并行运行的无头子代理。每个子代理在各自的上下文中工作,并仅向主聊天返回摘要。" + }, + "concurrency": { + "label": "最大并发子代理数", + "description": "同时可以运行多少个子代理。额外的运行会在队列中等待。" + }, + "maxTurns": { + "label": "每个子代理的默认最大轮次", + "description": "适用于未在定义中设置该值的子代理的轮次限制。达到限制的子代理会停止并返回部分摘要。 0 表示无限制。" + } + }, "checkpoints": { "timeout": { "label": "存档点初始化超时时间(秒)", diff --git a/webview-ui/src/i18n/locales/zh-TW/chat.json b/webview-ui/src/i18n/locales/zh-TW/chat.json index f38ae3619ce..088d07dc547 100644 --- a/webview-ui/src/i18n/locales/zh-TW/chat.json +++ b/webview-ui/src/i18n/locales/zh-TW/chat.json @@ -498,5 +498,59 @@ }, "diffView": { "hiddenLines_other": "已隱藏 {{count}} 行" + }, + "subagents": { + "groupRunning": "子代理 · 共{{total}}個,正在執行{{active}}個", + "groupDone": "子代理 · 共{{total}}個,已完成{{completed}}個", + "groupDoneWithFailures": "子代理 · {{completed}}個已完成 · {{failed}}個失敗", + "starting": "正在啟動...", + "queued": "等待中", + "completed": "已完成", + "failed": "失敗", + "cancelled": "已取消", + "partial": "部分完成", + "cancel": "取消子代理", + "inspect": "開啟記錄", + "headerChip": "{{count}}個子代理正在執行", + "metaTools": "{{count}}個工具", + "metaRead": "{{count}}次讀取", + "metaWritten": "{{count}}次寫入", + "dashRunning": "執行中", + "dashCompleted": "已完成", + "dashFailed": "失敗", + "dashCancelled": "已取消", + "dashQueued": "排隊中", + "dashWorkingOn": "正在處理", + "dashStarting": "正在啟動…", + "dashInstruction": "指示", + "dashProgress": "進度", + "dashConclusion": "結論", + "dashPartial": "在完成前於回合限制處停止", + "dashNoSummary": "未傳回摘要", + "dashCancelledOutcome": "已取消執行", + "dashShowMoreCount": "顯示更多 {{count}} 條", + "dashShowLess": "顯示更少", + "worktreeKept": "工作樹已保留", + "worktreeRemoved": "工作樹已刪除", + "viewLive": "即時查看", + "liveTitle": "即時記錄", + "close": "關閉", + "loadEarlier": "載入更早內容", + "noActivity": "暫無工具活動", + "liveEnded": "執行已結束", + "roleUser": "使用者", + "roleAssistant": "代理", + "reasoning": "推理", + "result": "結果", + "actions": { + "readfile": "讀取檔案", + "searchfiles": "搜尋檔案", + "listfiles": "列出目錄", + "codebasesearch": "搜尋程式碼庫", + "executecommand": "執行命令", + "writetofile": "寫入檔案", + "editfile": "編輯檔案", + "completion": "撰寫最終報告" + } } } diff --git a/webview-ui/src/i18n/locales/zh-TW/settings.json b/webview-ui/src/i18n/locales/zh-TW/settings.json index 64c0cc7a172..e3a6febf724 100644 --- a/webview-ui/src/i18n/locales/zh-TW/settings.json +++ b/webview-ui/src/i18n/locales/zh-TW/settings.json @@ -28,6 +28,7 @@ "sections": { "providers": "供應商", "modes": "模式", + "subagents": "子代理", "mcp": "MCP 伺服器", "worktrees": "Worktree", "autoApprove": "自動核准", @@ -734,6 +735,20 @@ "setupInstructions": "設定說明" } }, + "subagents": { + "enable": { + "label": "啟用子代理", + "description": "啟用後,完整工具模式可以建立並行執行的無頭子代理。每個子代理在各自的內容中工作,並僅向主聊天傳回摘要。" + }, + "concurrency": { + "label": "最大並行子代理數", + "description": "可以同時執行多少個子代理。多出的執行會在佇列中等待。" + }, + "maxTurns": { + "label": "每個子代理的預設最大輪次", + "description": "適用於未在定義中設定該值的子代理的輪次限制。達到限制的子代理會停止並傳回部分摘要。 0 表示不限。" + } + }, "checkpoints": { "timeout": { "label": "檢查點初始化逾時(秒)", diff --git a/webview-ui/src/index.css b/webview-ui/src/index.css index de889f41680..5cf10aba603 100644 --- a/webview-ui/src/index.css +++ b/webview-ui/src/index.css @@ -71,6 +71,8 @@ --color-vscode-editorGroup-border: var(--vscode-editorGroup-border); + --color-vscode-editorWidget-background: var(--vscode-editorWidget-background); + --color-vscode-editorWarning-foreground: var(--vscode-editorWarning-foreground); --color-vscode-editorWarning-background: var(--vscode-editorWarning-background);