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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion extensions/cli/src/commands/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { type AssistantConfig } from "@continuedev/sdk";

// Export command functions
export { chat } from "./chat.js";
export { review } from "./review.js";
export { login } from "./login.js";
export { logout } from "./logout.js";
export { listSessionsCommand } from "./ls.js";
export { remote } from "./remote.js";
export { review } from "./review.js";
export { serve } from "./serve.js";

export interface SlashCommand {
Expand Down Expand Up @@ -101,6 +101,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Exit the chat",
category: "system",
},
{
name: "jobs",
description: "List background jobs",
category: "system",
},
];

// Remote mode specific commands
Expand Down
224 changes: 224 additions & 0 deletions extensions/cli/src/services/BackgroundJobService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
import { ChildProcess, spawn } from "child_process";

import { logger } from "../util/logger.js";

export type BackgroundJobStatus =
| "pending"
| "running"
| "completed"
| "failed"
| "cancelled";

export interface BackgroundJob {
id: string;
status: BackgroundJobStatus;
command: string;
output: string;
exitCode: number | null;
startTime: Date;
endTime: Date | null;
error?: string;
}

const MAX_CONCURRENT_JOBS = 5;
const MAX_OUTPUT_LINES = 1000;

/**
* Service for managing background job execution and lifecycle
* Handles spawning, tracking, and cleanup of background processes
*/
export class BackgroundJobService {
private jobs: Map<string, BackgroundJob> = new Map();
private processes: Map<string, ChildProcess> = new Map();
private jobCounter = 0;

createJob(command: string): BackgroundJob | null {
const runningCount = this.getRunningJobCount();
if (runningCount >= MAX_CONCURRENT_JOBS) {
logger.warn(
`Cannot create background job: limit of ${MAX_CONCURRENT_JOBS} reached`,
);
return null;
}

const id = `bg-${++this.jobCounter}-${Date.now()}`;
const job: BackgroundJob = {
id,
status: "pending",
command,
output: "",
exitCode: null,
startTime: new Date(),
endTime: null,
};

this.jobs.set(id, job);
return job;
}

startJob(jobId: string, shell: string, args: string[]): ChildProcess | null {
const job = this.jobs.get(jobId);
if (!job) {
logger.error(`Cannot start job ${jobId}: job not found`);
return null;
}

job.status = "running";

const child = spawn(shell, args, { stdio: "pipe" });
this.processes.set(jobId, child);

child.stdout?.setEncoding("utf8");
child.stderr?.setEncoding("utf8");

child.stdout?.on("data", (data: string) => {
this.appendOutput(jobId, data);
});

child.stderr?.on("data", (data: string) => {
this.appendOutput(jobId, data);
});

child.on("close", (code: number | null) => {
this.completeJob(jobId, code ?? 0);
});

child.on("error", (error: Error) => {
this.failJob(jobId, error.message);
});

return child;
}

createJobWithProcess(
command: string,
child: ChildProcess,
existingOutput: string = "",
): BackgroundJob | null {
const runningCount = this.getRunningJobCount();
if (runningCount >= MAX_CONCURRENT_JOBS) {
logger.warn(
`Cannot create background job: limit of ${MAX_CONCURRENT_JOBS} reached`,
);
return null;
}

const id = `bg-${++this.jobCounter}-${Date.now()}`;
const job: BackgroundJob = {
id,
status: "running",
command,
output: existingOutput,
exitCode: null,
startTime: new Date(),
endTime: null,
};

this.jobs.set(id, job);
this.processes.set(id, child);

child.stdout?.setEncoding("utf8");
child.stderr?.setEncoding("utf8");

child.stdout?.on("data", (data: string) => {
this.appendOutput(id, data);
});

child.stderr?.on("data", (data: string) => {
this.appendOutput(id, data);
});

child.on("close", (code: number | null) => {
this.completeJob(id, code ?? 0);
});

child.on("error", (error: Error) => {
this.failJob(id, error.message);
});

return job;
}

// todo: improve write efficiency with ring buffer or similar
appendOutput(jobId: string, data: string): void {
const job = this.jobs.get(jobId);
if (job) {
job.output += data;
const lines = job.output.split("\n");
if (lines.length > MAX_OUTPUT_LINES) {
job.output = lines.slice(-MAX_OUTPUT_LINES).join("\n");
}
}
}

completeJob(jobId: string, exitCode: number): void {
const job = this.jobs.get(jobId);
if (job) {
if (job.status === "cancelled") {
return;
}
job.status = exitCode === 0 ? "completed" : "failed";
job.exitCode = exitCode;
job.endTime = new Date();
this.processes.delete(jobId);
}
}

failJob(jobId: string, error: string): void {
const job = this.jobs.get(jobId);
if (job) {
job.status = "failed";
job.error = error;
job.endTime = new Date();
this.processes.delete(jobId);
}
}

cancelJob(jobId: string): boolean {
const job = this.jobs.get(jobId);
const process = this.processes.get(jobId);

if (!job) return false;

if (process) {
process.kill();
this.processes.delete(jobId);
}

job.status = "cancelled";
job.endTime = new Date();
return true;
}

getJob(jobId: string): BackgroundJob | undefined {
return this.jobs.get(jobId);
}

getRunningJobs(): BackgroundJob[] {
return Array.from(this.jobs.values()).filter(
(job) => job.status === "running" || job.status === "pending",
);
}

getAllJobs(): BackgroundJob[] {
return Array.from(this.jobs.values());
}

getRunningJobCount(): number {
return this.getRunningJobs().length;
}

killAllJobs(): void {
for (const [jobId, process] of this.processes) {
process.kill();
const job = this.jobs.get(jobId);
if (job) {
job.status = "cancelled";
job.endTime = new Date();
}
}
this.processes.clear();
}
}

export const backgroundJobService = new BackgroundJobService();
4 changes: 2 additions & 2 deletions extensions/cli/src/services/ToolPermissionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import {
AUTO_MODE_POLICIES,
PLAN_MODE_POLICIES,
} from "src/permissions/defaultPolicies.js";
import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js";

import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js";
import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js";
Expand All @@ -11,6 +10,7 @@ import {
ToolPermissionPolicy,
ToolPermissions,
} from "../permissions/types.js";
import { BUILT_IN_TOOL_NAMES } from "../tools/builtInToolNames.js";
import { logger } from "../util/logger.js";

import { BaseService, ServiceWithDependencies } from "./BaseService.js";
Expand Down Expand Up @@ -147,7 +147,7 @@ export class ToolPermissionService
}));
policies.push(...allowed);
const specificBuiltInSet = new Set(specificBuiltIns);
const notMentioned = ALL_BUILT_IN_TOOLS.map((t) => t.name).filter(
const notMentioned = BUILT_IN_TOOL_NAMES.filter(
(name) => !specificBuiltInSet.has(name),
);
const disallowed: ToolPermissionPolicy[] = notMentioned.map((tool) => ({
Expand Down
2 changes: 2 additions & 0 deletions extensions/cli/src/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { AgentFileService } from "./AgentFileService.js";
import { ApiClientService } from "./ApiClientService.js";
import { ArtifactUploadService } from "./ArtifactUploadService.js";
import { AuthService } from "./AuthService.js";
import { backgroundJobService } from "./BackgroundJobService.js";
import { ChatHistoryService } from "./ChatHistoryService.js";
import { ConfigService } from "./ConfigService.js";
import { FileIndexService } from "./FileIndexService.js";
Expand Down Expand Up @@ -387,6 +388,7 @@ export const services = {
toolPermissions: toolPermissionService,
artifactUpload: artifactUploadService,
gitAiIntegration: gitAiIntegrationService,
backgroundJobs: backgroundJobService,
} as const;

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

export type {
BackgroundJob,
BackgroundJobStatus,
} from "./BackgroundJobService.js";
export type { ChatHistoryState } from "./ChatHistoryService.js";
export type { FileIndexServiceState } from "./FileIndexService.js";
export type { GitAiIntegrationServiceState } from "./GitAiIntegrationService.js";
Expand All @@ -153,6 +157,7 @@ export const SERVICE_NAMES = {
AGENT_FILE: "agentFile",
ARTIFACT_UPLOAD: "artifactUpload",
GIT_AI_INTEGRATION: "gitAiIntegration",
BACKGROUND_JOBS: "backgroundJobs",
} as const;

/**
Expand Down
5 changes: 5 additions & 0 deletions extensions/cli/src/slashCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ function handleTitle(args: string[]) {
}
}

function handleJobs() {
return { openJobsSelector: true };
}

const commandHandlers: Record<string, CommandHandler> = {
help: handleHelp,
clear: () => {
Expand Down Expand Up @@ -203,6 +207,7 @@ const commandHandlers: Record<string, CommandHandler> = {
update: () => {
return { openUpdateSelector: true };
},
jobs: handleJobs,
};

export async function handleSlashCommands(
Expand Down
25 changes: 25 additions & 0 deletions extensions/cli/src/tools/builtInToolNames.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Static list of built-in tool names.
* Kept separate from allBuiltIns.ts to avoid circular dependency:
* ToolPermissionService -> allBuiltIns -> runTerminalCommand -> services/index -> ToolPermissionService
*
* When adding a new built-in tool, update both this list and ALL_BUILT_IN_TOOLS in allBuiltIns.ts.
*/
export const BUILT_IN_TOOL_NAMES = [
"Edit",
"Exit",
"Fetch",
"List",
"MultiEdit",
"Read",
"ReportFailure",
"Bash",
"Search",
"Status",
"Subagent",
"Skills",
"UploadArtifact",
"Diff",
"Checklist",
"Write",
] as const;
Loading
Loading