Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions extensions/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,10 +200,6 @@ addCommonOptions(program)
)
.option("--resume", "Resume from last session")
.option("--fork <sessionId>", "Fork from an existing session ID")
.option(
"--beta-subagent-tool",
"Enable beta Subagent tool for invoking subagents",
)
.action(async (prompt, options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "cn" });
Expand Down
277 changes: 277 additions & 0 deletions extensions/cli/src/services/SubAgentService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,277 @@
import { AsyncLocalStorage } from "node:async_hooks";

import type { ChatHistoryItem } from "core";

import { streamChatResponse } from "../stream/streamChatResponse.js";
import { escapeEvents } from "../util/cli.js";
import { logger } from "../util/logger.js";

import { BaseService } from "./BaseService.js";
import { serviceContainer } from "./ServiceContainer.js";
import type { ToolPermissionServiceState } from "./ToolPermissionService.js";
import { type ModelServiceState, SERVICE_NAMES } from "./types.js";

/** Service */

export class SubAgentService extends BaseService<SubAgentServiceState> {
constructor() {
super("SubAgentService", {
activeExecutions: new Map(),
});
}

async doInitialize(): Promise<SubAgentServiceState> {
return {
activeExecutions: new Map(),
};
}

private generateExecutionId(): string {
return `subagent-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
}

isInsideSubagent(): boolean {
return subAgentExecutionContext.getStore() !== undefined;
}

private async buildAgentSystemMessage(
agent: ModelServiceState,
services: any,
): Promise<string> {
const baseMessage = services.systemMessage
? await services.systemMessage.getSystemMessage(
services.toolPermissions.getState().currentMode,
)
: "";

const agentPrompt = agent.model?.chatOptions?.baseSystemMessage || "";

if (agentPrompt) {
return `${baseMessage}\n\n${agentPrompt}`;
}

return baseMessage;
}

async executeSubAgent(
options: SubAgentExecutionOptions,
): Promise<SubAgentResult> {
if (this.isInsideSubagent()) {
return {
success: false,
response: "",
error: "Nested subagent invocation is not allowed",
};
}

const { agent: subAgent, prompt, abortController } = options;
const executionId = this.generateExecutionId();
const agentName = subAgent.model?.name || "unknown";

const mainAgentPermissionsState =
await serviceContainer.get<ToolPermissionServiceState>(
SERVICE_NAMES.TOOL_PERMISSIONS,
);

const execution: PendingExecution = {
executionId,
agentName,
startTime: Date.now(),
};

const activeExecutions = new Map(this.currentState.activeExecutions);
activeExecutions.set(executionId, execution);
this.setState({ activeExecutions });

this.emit("subagentStarted", {
executionId,
agentName: subAgent.model?.name,
prompt,
});

try {
logger.debug("Starting subagent execution", {
executionId,
agent: subAgent.model?.name,
});

const { model, llmApi } = subAgent;
if (!model || !llmApi) {
throw new Error("Model or LLM API not available");
}

const { services } = await import("./index.js");

// Build agent system message
const systemMessage = await this.buildAgentSystemMessage(
subAgent,
services,
);

// allow all tools for now
// todo: eventually we want to show the same prompt in a dialog whether asking whether that tool call is allowed or not
const subAgentPermissions: ToolPermissionServiceState = {
...mainAgentPermissionsState,
permissions: {
policies: [{ tool: "*", permission: "allow" }],
},
};

const chatHistorySvc = services.chatHistory;
const originalIsReady =
chatHistorySvc && typeof chatHistorySvc.isReady === "function"
? chatHistorySvc.isReady
: undefined;

if (chatHistorySvc && originalIsReady) {
chatHistorySvc.isReady = () => false;
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Mar 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Parallel subagent executions race on the global chatHistorySvc.isReady override, so completion order can restore a stale override and leave chat history disabled or re-enable it while another subagent still runs.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At extensions/cli/src/services/SubAgentService.ts, line 127:

<comment>Parallel subagent executions race on the global chatHistorySvc.isReady override, so completion order can restore a stale override and leave chat history disabled or re-enable it while another subagent still runs.</comment>

<file context>
@@ -0,0 +1,277 @@
+          : undefined;
+
+      if (chatHistorySvc && originalIsReady) {
+        chatHistorySvc.isReady = () => false;
+      }
+
</file context>
Fix with Cubic

}

const chatHistory = [
{
message: { role: "user", content: prompt },
contextItems: [],
},
] as ChatHistoryItem[];

const escapeHandler = () => {
abortController.abort();
chatHistory.push({
message: {
role: "user",
content: "Subagent execution was cancelled by the user.",
},
contextItems: [],
});
};

escapeEvents.on("user-escape", escapeHandler);

try {
const result = await subAgentExecutionContext.run(
{
executionId,
systemMessage,
permissions: subAgentPermissions,
},
async () => {
await streamChatResponse(
chatHistory,
model,
llmApi,
abortController,
{
onContent: (content: string) => {
this.emit("subagentContent", {
executionId,
agentName: model?.name,
content,
type: "content",
});
},
onToolResult: (result: string) => {
this.emit("subagentContent", {
executionId,
agentName: model?.name,
content: result,
type: "toolResult",
});
},
},
false,
);

const lastMessage = chatHistory.at(-1);
const response =
typeof lastMessage?.message?.content === "string"
? lastMessage.message.content
: "";

return { success: true as const, response };
},
);

logger.debug("Subagent execution completed", {
executionId,
agent: model?.name,
responseLength: result.response.length,
});

this.emit("subagentCompleted", {
executionId,
agentName: model?.name,
success: true,
});

return result;
} finally {
escapeEvents.removeListener("user-escape", escapeHandler);

if (chatHistorySvc && originalIsReady) {
chatHistorySvc.isReady = originalIsReady;
}
}
} catch (error: any) {
logger.error("Subagent execution failed", {
executionId,
agent: subAgent.model?.name,
error: error.message,
});

this.emit("subagentFailed", {
executionId,
agentName: subAgent.model?.name,
error: error.message,
});

return {
success: false,
response: "",
error: error.message,
};
} finally {
const updatedExecutions = new Map(this.currentState.activeExecutions);
updatedExecutions.delete(executionId);
this.setState({ activeExecutions: updatedExecutions });
}
}
}

export const subAgentService = new SubAgentService();

// Subagent execution context

interface ExecutionContext {
executionId: string;
systemMessage: string;
permissions: ToolPermissionServiceState;
}

/* Scopes system messages and tool permissions per subagent execution for enabling parallel execution*/
export const subAgentExecutionContext =
new AsyncLocalStorage<ExecutionContext>();

// Types

export interface SubAgentExecutionOptions {
agent: ModelServiceState;
prompt: string;
parentSessionId: string;
abortController: AbortController;
}

export interface SubAgentResult {
success: boolean;
response: string;
error?: string;
}

export interface PendingExecution {
executionId: string;
agentName: string;
startTime: number;
}

export interface SubAgentServiceState {
activeExecutions: Map<string, PendingExecution>;
}
16 changes: 9 additions & 7 deletions extensions/cli/src/services/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { loadAuthConfig } from "../auth/workos.js";
import { initializeWithOnboarding } from "../onboarding.js";
import {
setBetaSubagentToolEnabled,
setBetaUploadArtifactToolEnabled,
} from "../tools/toolsConfig.js";
import { setBetaUploadArtifactToolEnabled } from "../tools/toolsConfig.js";
import { logger } from "../util/logger.js";

import { AgentFileService } from "./AgentFileService.js";
Expand All @@ -21,6 +18,7 @@ import { quizService } from "./QuizService.js";
import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { StorageSyncService } from "./StorageSyncService.js";
import { subAgentService } from "./SubAgentService.js";
import { SystemMessageService } from "./SystemMessageService.js";
import {
InitializeToolServiceOverrides,
Expand Down Expand Up @@ -67,9 +65,6 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
if (commandOptions.betaUploadArtifactTool) {
setBetaUploadArtifactToolEnabled(true);
}
if (commandOptions.betaSubagentTool) {
setBetaSubagentToolEnabled(true);
}
// Handle onboarding for TUI mode (headless: false) unless explicitly skipped
if (!initOptions.headless && !initOptions.skipOnboarding) {
const authConfig = loadAuthConfig();
Expand Down Expand Up @@ -332,6 +327,12 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
[], // No dependencies
);

serviceContainer.register(
SERVICE_NAMES.SUBAGENT,
() => subAgentService.initialize(),
[], // No dependencies
);

// Eagerly initialize all services to ensure they're ready when needed
// This avoids race conditions and "service not ready" errors
await serviceContainer.initializeAll();
Expand Down Expand Up @@ -397,6 +398,7 @@ export const services = {
gitAiIntegration: gitAiIntegrationService,
backgroundJobs: backgroundJobService,
quiz: quizService,
subAgent: subAgentService,
} as const;

export type ServicesType = typeof services;
Expand Down
6 changes: 6 additions & 0 deletions extensions/cli/src/services/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ export interface ArtifactUploadServiceState {
lastError: string | null;
}

export type {
PendingExecution,
SubAgentServiceState,
} from "./SubAgentService.js";

export type {
BackgroundJob,
BackgroundJobStatus,
Expand Down Expand Up @@ -159,6 +164,7 @@ export const SERVICE_NAMES = {
GIT_AI_INTEGRATION: "gitAiIntegration",
BACKGROUND_JOBS: "backgroundJobs",
QUIZ: "quiz",
SUBAGENT: "subagent",
} as const;

/**
Expand Down
Loading
Loading