Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into mcp-flag
Changesetc4ec337463d80b3892bab0de8fcd53e112789a2d3a2158931d577f9131be8e8f
AuthorNate <sestinj@gmail.com> · 2025-08-24 18:38 -07:00
CommitterNate <sestinj@gmail.com> · 2025-08-24 18:38 -07:00
Parents19e18753af70, b931dc13c72f

Browse the files at this changeset

30 files changed

modified .github/workflows/compliance.yaml +1 −1
@@ -36,7 +36,7 @@
3636 else
3737 echo "❌ PR title does not follow conventional commit format"
3838 echo "valid=false" >> $GITHUB_OUTPUT
39- exit 1
39+ # Don't exit with failure - just mark as invalid for comment
4040 fi
4141
4242 - name: Add PR title guidance comment
modified binary/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/cli/src/__mocks__/args.ts +3 −1
@@ -1,3 +1,5 @@
11 import { vi } from "vitest";
22
3-export const processRule = vi.fn<(rule: string) => Promise<string>>();
3+export const processPromptOrRule = vi.fn<(spec: string) => Promise<string>>();
4+
5+export const processPrompt = vi.fn<(prompt: string) => Promise<string>>();
added extensions/cli/src/args.prompt.test.ts +84 −0
@@ -0,0 +1,84 @@
1+import { describe, it, expect, beforeEach, afterAll } from "vitest";
2+
3+import { parseArgs, processPromptOrRule } from "./args.js";
4+
5+describe("args --prompt flag", () => {
6+ const originalArgv = process.argv;
7+
8+ beforeEach(() => {
9+ // Reset process.argv for each test
10+ process.argv = ["node", "script.js"];
11+ });
12+
13+ afterAll(() => {
14+ // Restore original process.argv after all tests
15+ process.argv = originalArgv;
16+ });
17+
18+ it("should parse single prompt from --prompt flag", () => {
19+ process.argv = ["node", "script.js", "--prompt", "my-prompt"];
20+ const result = parseArgs();
21+ expect(result.prompts).toEqual(["my-prompt"]);
22+ });
23+
24+ it("should parse multiple prompts from multiple --prompt flags", () => {
25+ process.argv = [
26+ "node",
27+ "script.js",
28+ "--prompt",
29+ "prompt1",
30+ "--prompt",
31+ "prompt2",
32+ ];
33+ const result = parseArgs();
34+ expect(result.prompts).toEqual(["prompt1", "prompt2"]);
35+ });
36+
37+ it("should handle mixed flags including --prompt", () => {
38+ process.argv = [
39+ "node",
40+ "script.js",
41+ "--config",
42+ "myconfig",
43+ "--prompt",
44+ "myprompt",
45+ "--resume",
46+ ];
47+ const result = parseArgs();
48+ expect(result.configPath).toBe("myconfig");
49+ expect(result.prompts).toEqual(["myprompt"]);
50+ expect(result.resume).toBe(true);
51+ });
52+
53+ it("should not include --prompt value in non-flag arguments", () => {
54+ process.argv = [
55+ "node",
56+ "script.js",
57+ "--prompt",
58+ "prompt-value",
59+ "actual-prompt",
60+ ];
61+ const result = parseArgs();
62+ expect(result.prompts).toEqual(["prompt-value"]);
63+ expect(result.prompt).toBe("actual-prompt");
64+ });
65+
66+ it("should handle both --rule and --prompt flags", () => {
67+ process.argv = [
68+ "node",
69+ "script.js",
70+ "--rule",
71+ "my-rule",
72+ "--prompt",
73+ "my-prompt",
74+ ];
75+ const result = parseArgs();
76+ expect(result.rules).toEqual(["my-rule"]);
77+ expect(result.prompts).toEqual(["my-prompt"]);
78+ });
79+
80+ it("should process direct string content", async () => {
81+ const result = await processPromptOrRule("This is a direct prompt");
82+ expect(result).toBe("This is a direct prompt");
83+ });
84+});
modified extensions/cli/src/args.test.ts +27 −15
@@ -1,6 +1,6 @@
11 import { vi } from "vitest";
22
3-import { parseArgs, processRule } from "./args.js";
3+import { parseArgs, processPromptOrRule } from "./args.js";
44
55 describe("parseArgs", () => {
66 const originalArgv = process.argv;
@@ -217,7 +217,7 @@
217217 });
218218 });
219219
220-describe("processRule (loadRuleFromHub integration)", () => {
220+describe("processPromptOrRule (loadRuleFromHub integration)", () => {
221221 // Mock fetch for hub tests
222222 const originalFetch = global.fetch;
223223 const mockFetch = vi.fn() as any;
@@ -251,7 +251,7 @@
251251 arrayBuffer: () => Promise.resolve(zipBuffer),
252252 } as Response);
253253
254- const result = await processRule("continuedev/sentry-nextjs");
254+ const result = await processPromptOrRule("continuedev/sentry-nextjs");
255255
256256 expect(result).toBe(ruleContent);
257257 expect(mockFetch).toHaveBeenCalledWith(
@@ -269,7 +269,9 @@
269269 statusText: "Not Found",
270270 } as Response);
271271
272- await expect(processRule("continuedev/nonexistent-rule")).rejects.toThrow(
272+ await expect(
273+ processPromptOrRule("continuedev/nonexistent-rule"),
274+ ).rejects.toThrow(
273275 'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found',
274276 );
275277 });
@@ -277,7 +279,9 @@
277279 it("should handle network errors when loading from hub", async () => {
278280 mockFetch.mockRejectedValue(new Error("Network error"));
279281
280- await expect(processRule("continuedev/sentry-nextjs")).rejects.toThrow(
282+ await expect(
283+ processPromptOrRule("continuedev/sentry-nextjs"),
284+ ).rejects.toThrow(
281285 'Failed to load rule from hub "continuedev/sentry-nextjs": Network error',
282286 );
283287 });
@@ -285,7 +289,9 @@
285289 it("should handle invalid slug format", async () => {
286290 // "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug
287291 // Let's test with a slug that has wrong format but contains "/"
288- await expect(processRule("invalid/slug/too/many/parts")).rejects.toThrow(
292+ await expect(
293+ processPromptOrRule("invalid/slug/too/many/parts"),
294+ ).rejects.toThrow(
289295 'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts',
290296 );
291297 });
@@ -300,7 +306,9 @@
300306 arrayBuffer: () => Promise.resolve(zipBuffer),
301307 } as Response);
302308
303- await expect(processRule("continuedev/empty-rule")).rejects.toThrow(
309+ await expect(
310+ processPromptOrRule("continuedev/empty-rule"),
311+ ).rejects.toThrow(
304312 'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file',
305313 );
306314 });
@@ -316,7 +324,9 @@
316324 arrayBuffer: () => Promise.resolve(zipBuffer),
317325 } as Response);
318326
319- await expect(processRule("continuedev/directory-only")).rejects.toThrow(
327+ await expect(
328+ processPromptOrRule("continuedev/directory-only"),
329+ ).rejects.toThrow(
320330 'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file',
321331 );
322332 });
@@ -338,7 +348,7 @@
338348 arrayBuffer: () => Promise.resolve(zipBuffer),
339349 } as Response);
340350
341- const result = await processRule("continuedev/mixed-files");
351+ const result = await processPromptOrRule("continuedev/mixed-files");
342352
343353 expect(result).toBe(mdContent);
344354 });
@@ -359,7 +369,7 @@
359369 arrayBuffer: () => Promise.resolve(zipBuffer),
360370 } as Response);
361371
362- const result = await processRule("continuedev/multiple-rules");
372+ const result = await processPromptOrRule("continuedev/multiple-rules");
363373
364374 // Should use the first markdown file found (alphabetically)
365375 expect(result).toBe(rule1Content);
@@ -373,13 +383,15 @@
373383 arrayBuffer: () => Promise.resolve(invalidZipBuffer),
374384 } as Response);
375385
376- await expect(processRule("continuedev/corrupted-zip")).rejects.toThrow(
386+ await expect(
387+ processPromptOrRule("continuedev/corrupted-zip"),
388+ ).rejects.toThrow(
377389 'Failed to load rule from hub "continuedev/corrupted-zip"',
378390 );
379391 });
380392 });
381393
382- describe("processRule logic", () => {
394+ describe("processPromptOrRule logic", () => {
383395 it("should identify hub slugs correctly", async () => {
384396 const JSZip = (await import("jszip")).default;
385397 const zip = new JSZip();
@@ -391,14 +403,14 @@
391403 arrayBuffer: () => Promise.resolve(zipBuffer),
392404 } as Response);
393405
394- const result = await processRule("owner/package");
406+ const result = await processPromptOrRule("owner/package");
395407 expect(result).toBe("# Hub Rule");
396408 expect(mockFetch).toHaveBeenCalled();
397409 });
398410
399411 it("should treat direct strings as content", async () => {
400412 const directContent = "This is direct rule content";
401- const result = await processRule(directContent);
413+ const result = await processPromptOrRule(directContent);
402414 expect(result).toBe(directContent);
403415 expect(mockFetch).not.toHaveBeenCalled();
404416 });
@@ -406,7 +418,7 @@
406418 it("should distinguish between hub slugs and file paths", async () => {
407419 // This would be treated as a file path, not a hub slug
408420 // since it starts with "."
409- await expect(processRule("./owner/package")).rejects.toThrow(
421+ await expect(processPromptOrRule("./owner/package")).rejects.toThrow(
410422 'Failed to read rule file "./owner/package": Rule file not found',
411423 );
412424 expect(mockFetch).not.toHaveBeenCalled();
modified extensions/cli/src/args.ts +2 −0
@@ -13,6 +13,8 @@
1313
1414 // Re-export hub loader functions for backward compatibility
1515 export { loadMcpFromHub, processRule } from "./hubLoader.js";
16+// Alias processRule as processPromptOrRule for backward compatibility
17+export { processRule as processPromptOrRule } from "./hubLoader.js";
1618
1719 /**
1820 * Extract values for a specific flag that can appear multiple times
modified extensions/cli/src/commands/chat.ts +13 −3
@@ -391,17 +391,26 @@
391391 compactionIndex = findCompactionIndex(chatHistory);
392392 }
393393
394+ // Handle additional prompts from --prompt flags
395+ const { processAndCombinePrompts } = await import(
396+ "../util/promptProcessor.js"
397+ );
398+ const initialUserInput = await processAndCombinePrompts(
399+ options.prompt,
400+ prompt,
401+ );
402+
394403 let isFirstMessage = true;
395404 while (true) {
396405 // When in headless mode, don't ask for user input
397- if (!isFirstMessage && prompt && options.headless) {
406+ if (!isFirstMessage && initialUserInput && options.headless) {
398407 break;
399408 }
400409
401410 // Get user input
402411 const userInput =
403- isFirstMessage && prompt
404- ? prompt
412+ isFirstMessage && initialUserInput
413+ ? initialUserInput
405414 : readlineSync.question(`\n${chalk.bold.green("You:")} `);
406415
407416 isFirstMessage = false;
@@ -466,6 +475,7 @@
466475 config: options.config,
467476 org: options.org,
468477 rule: options.rule,
478+ prompt: options.prompt,
469479 toolPermissionOverrides: permissionOverrides,
470480 skipOnboarding: true,
471481 };
modified extensions/cli/src/e2e/basic-commands.test.ts +1 −0
@@ -40,6 +40,7 @@
4040 expect(result.stdout).toContain("--readonly");
4141 expect(result.stdout).toContain("--auto");
4242 expect(result.stdout).toContain("--rule <rule>");
43+ expect(result.stdout).toContain("--prompt <prompt>");
4344 });
4445
4546 it("should show available commands", async () => {
modified extensions/cli/src/onboarding.ts +2 −2
@@ -7,7 +7,7 @@
77 import chalk from "chalk";
88 import * as readlineSync from "readline-sync";
99
10-import { processRule } from "./args.js";
10+import { processPromptOrRule } from "./args.js";
1111 import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
1212 import { initialize } from "./config.js";
1313 import { env } from "./env.js";
@@ -239,7 +239,7 @@
239239 const processedRules: string[] = [];
240240 for (const ruleSpec of rules) {
241241 try {
242- const processedRule = await processRule(ruleSpec);
242+ const processedRule = await processPromptOrRule(ruleSpec);
243243 processedRules.push(processedRule);
244244 } catch (error: any) {
245245 console.warn(
modified extensions/cli/src/services/ConfigService.test.ts +0 −1
@@ -3,7 +3,6 @@
33 // Mock modules
44 vi.mock("../auth/workos.js");
55 vi.mock("../configLoader.js");
6-vi.mock("../args.js");
76 vi.mock("../configEnhancer.js");
87 vi.mock("./ServiceContainer.js");
98
modified extensions/cli/src/services/ConfigService.ts +4 −4
@@ -41,7 +41,7 @@
4141 async doInitialize(
4242 authConfig: AuthConfig,
4343 configPath: string | undefined,
44- organizationId: string | null,
44+ _organizationId: string | null,
4545 apiClient: DefaultApiInterface,
4646 injectedConfigOptions?: BaseCommandOptions,
4747 ): Promise<ConfigServiceState> {
@@ -80,7 +80,7 @@
8080 async switchConfig(
8181 newConfigPath: string,
8282 authConfig: AuthConfig,
83- organizationId: string | null,
83+ _organizationId: string | null,
8484 apiClient: DefaultApiInterface,
8585 injectedConfigOptions?: BaseCommandOptions,
8686 ): Promise<ConfigServiceState> {
@@ -137,7 +137,7 @@
137137 */
138138 async reload(
139139 authConfig: AuthConfig,
140- organizationId: string | null,
140+ _organizationId: string | null,
141141 apiClient: DefaultApiInterface,
142142 injectedConfigOptions?: BaseCommandOptions,
143143 ): Promise<ConfigServiceState> {
@@ -150,7 +150,7 @@
150150 return this.switchConfig(
151151 this.currentState.configPath,
152152 authConfig,
153- organizationId,
153+ _organizationId,
154154 apiClient,
155155 injectedConfigOptions,
156156 );
added extensions/cli/src/services/ResourceMonitoringService.test.ts +108 −0
@@ -0,0 +1,108 @@
1+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+
3+import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
4+
5+// Mock the logger and BaseService
6+vi.mock("../util/logger.js", () => ({
7+ logger: {
8+ debug: vi.fn(),
9+ info: vi.fn(),
10+ warn: vi.fn(),
11+ error: vi.fn(),
12+ },
13+}));
14+
15+vi.mock("./BaseService.js", () => ({
16+ BaseService: class MockBaseService {
17+ logger = {
18+ debug: vi.fn(),
19+ info: vi.fn(),
20+ warn: vi.fn(),
21+ error: vi.fn(),
22+ };
23+ },
24+}));
25+
26+describe("ResourceMonitoringService", () => {
27+ let service: ResourceMonitoringService;
28+
29+ beforeEach(async () => {
30+ // Remove process event listeners to prevent interference
31+ process.removeAllListeners("exit");
32+ process.removeAllListeners("SIGINT");
33+ process.removeAllListeners("SIGTERM");
34+
35+ service = new ResourceMonitoringService();
36+ await service.initialize();
37+ });
38+
39+ afterEach(async () => {
40+ if (service) {
41+ service.stopMonitoring(); // Ensure monitoring is stopped
42+ await service.cleanup();
43+ }
44+ });
45+
46+ it("should initialize without starting monitoring by default", () => {
47+ expect(service).toBeDefined();
48+ // Should not be monitoring unless --verbose is passed
49+ const usage = service.getCurrentResourceUsage();
50+ expect(usage.timestamp).toBeGreaterThan(0);
51+ });
52+
53+ it("should collect current resource usage", () => {
54+ const usage = service.getCurrentResourceUsage();
55+
56+ expect(usage.timestamp).toBeGreaterThan(0);
57+ expect(usage.memory.rss).toBeGreaterThan(0);
58+ expect(usage.memory.heapTotal).toBeGreaterThan(0);
59+ expect(usage.memory.heapUsed).toBeGreaterThan(0);
60+ expect(usage.cpu.user).toBeGreaterThanOrEqual(0);
61+ expect(usage.cpu.system).toBeGreaterThanOrEqual(0);
62+ expect(usage.system.uptime).toBeGreaterThan(0);
63+ expect(usage.system.totalMemory).toBeGreaterThan(0);
64+ expect(usage.eventLoop.lag).toBeGreaterThanOrEqual(0);
65+ });
66+
67+ it("should provide resource summary", () => {
68+ const summary = service.getResourceSummary();
69+
70+ expect(summary.current).toBeDefined();
71+ expect(summary.peak).toBeDefined();
72+ expect(summary.average).toBeDefined();
73+
74+ expect(summary.peak.memory).toBeGreaterThan(0);
75+ expect(summary.peak.cpu).toBeGreaterThanOrEqual(0);
76+
77+ expect(summary.average.memory).toBeGreaterThan(0);
78+ expect(summary.average.cpu).toBeGreaterThanOrEqual(0);
79+ });
80+
81+ it("should start and stop monitoring", async () => {
82+ service.startMonitoring(100); // 100ms interval for test
83+
84+ // Wait for some data collection
85+ await new Promise((resolve) => setTimeout(resolve, 250));
86+
87+ const history = service.getResourceHistory();
88+ expect(history.length).toBeGreaterThan(0);
89+
90+ service.stopMonitoring();
91+ });
92+
93+ it("should handle verbose mode initialization", async () => {
94+ // Mock argv to include --verbose
95+ const originalArgv = process.argv;
96+ process.argv = [...originalArgv, "--verbose"];
97+
98+ const verboseService = new ResourceMonitoringService();
99+ await verboseService.initialize();
100+
101+ // Should start monitoring automatically
102+ // Note: Testing this properly would require checking internal state
103+ // which isn't directly exposed
104+
105+ await verboseService.cleanup();
106+ process.argv = originalArgv;
107+ });
108+});
added extensions/cli/src/services/ResourceMonitoringService.ts +312 −0
@@ -0,0 +1,312 @@
1+import { exec } from "child_process";
2+import * as os from "os";
3+import { promisify } from "util";
4+
5+import { logger } from "../util/logger.js";
6+
7+const execAsync = promisify(exec);
8+
9+export interface ResourceUsage {
10+ timestamp: number;
11+ memory: {
12+ rss: number; // Resident Set Size
13+ heapTotal: number;
14+ heapUsed: number;
15+ external: number;
16+ arrayBuffers: number;
17+ };
18+ cpu: {
19+ user: number;
20+ system: number;
21+ percent?: number; // CPU percentage (calculated)
22+ };
23+ system: {
24+ loadAverage: number[];
25+ uptime: number;
26+ freeMemory: number;
27+ totalMemory: number;
28+ };
29+ eventLoop: {
30+ lag: number;
31+ };
32+ fileDescriptors?: number;
33+}
34+
35+export interface ResourceMonitoringState {
36+ isMonitoring: boolean;
37+ resourceHistory: ResourceUsage[];
38+}
39+
40+class ResourceMonitoringService {
41+ private isMonitoring = false;
42+ private monitoringInterval?: NodeJS.Timeout;
43+ private intervalMs = 1000; // Default 1 second
44+ private resourceHistory: ResourceUsage[] = [];
45+ private maxHistorySize = 300; // Keep 5 minutes at 1s intervals
46+ private lastCpuUsage = process.cpuUsage();
47+ private lastTimestamp = Date.now();
48+
49+ async initialize(): Promise<void> {
50+ // Start monitoring if verbose mode is enabled
51+ if (process.argv.includes("--verbose")) {
52+ this.startMonitoring();
53+ }
54+
55+ // Cleanup on exit
56+ process.on("exit", () => this.cleanup());
57+ process.on("SIGINT", () => this.cleanup());
58+ process.on("SIGTERM", () => this.cleanup());
59+ }
60+
61+ async cleanup(): Promise<void> {
62+ this.stopMonitoring();
63+ }
64+
65+ public startMonitoring(intervalMs = 1000): void {
66+ if (this.isMonitoring) return;
67+
68+ this.intervalMs = intervalMs;
69+ this.isMonitoring = true;
70+ this.lastCpuUsage = process.cpuUsage();
71+ this.lastTimestamp = Date.now();
72+
73+ this.monitoringInterval = setInterval(() => {
74+ this.collectResourceUsage();
75+ }, this.intervalMs);
76+
77+ logger.debug("Resource monitoring started", { intervalMs });
78+ }
79+
80+ public stopMonitoring(): void {
81+ if (!this.isMonitoring) return;
82+
83+ this.isMonitoring = false;
84+ if (this.monitoringInterval) {
85+ clearInterval(this.monitoringInterval);
86+ this.monitoringInterval = undefined;
87+ }
88+
89+ logger.debug("Resource monitoring stopped");
90+ }
91+
92+ public getCurrentResourceUsage(): ResourceUsage {
93+ const now = Date.now();
94+ const currentCpuUsage = process.cpuUsage();
95+ const timeDiff = now - this.lastTimestamp;
96+
97+ // Calculate CPU percentage
98+ const userDiff = currentCpuUsage.user - this.lastCpuUsage.user;
99+ const systemDiff = currentCpuUsage.system - this.lastCpuUsage.system;
100+ const totalDiff = userDiff + systemDiff;
101+ const cpuPercent = timeDiff > 0 ? (totalDiff / (timeDiff * 1000)) * 100 : 0;
102+
103+ const memoryUsage = process.memoryUsage();
104+
105+ const usage: ResourceUsage = {
106+ timestamp: now,
107+ memory: {
108+ rss: memoryUsage.rss,
109+ heapTotal: memoryUsage.heapTotal,
110+ heapUsed: memoryUsage.heapUsed,
111+ external: memoryUsage.external,
112+ arrayBuffers: memoryUsage.arrayBuffers,
113+ },
114+ cpu: {
115+ user: currentCpuUsage.user,
116+ system: currentCpuUsage.system,
117+ percent: Math.min(cpuPercent, 100), // Cap at 100%
118+ },
119+ system: {
120+ loadAverage: this.getLoadAverage(),
121+ uptime: this.getProcessUptime(),
122+ freeMemory: this.getFreeMemory(),
123+ totalMemory: this.getTotalMemory(),
124+ },
125+ eventLoop: {
126+ lag: this.measureEventLoopLag(),
127+ },
128+ };
129+
130+ // Try to get file descriptor count (Unix only)
131+ this.getFileDescriptorCount()
132+ .then((count) => {
133+ if (count !== null) {
134+ usage.fileDescriptors = count;
135+ }
136+ })
137+ .catch(() => {
138+ // Ignore errors for file descriptor counting
139+ });
140+
141+ return usage;
142+ }
143+
144+ public getResourceHistory(): ResourceUsage[] {
145+ return [...this.resourceHistory];
146+ }
147+
148+ public getResourceSummary(): {
149+ current: ResourceUsage;
150+ peak: {
151+ memory: number;
152+ cpu: number;
153+ };
154+ average: {
155+ memory: number;
156+ cpu: number;
157+ };
158+ } {
159+ const current = this.getCurrentResourceUsage();
160+
161+ if (this.resourceHistory.length === 0) {
162+ return {
163+ current,
164+ peak: {
165+ memory: current.memory.rss,
166+ cpu: current.cpu.percent || 0,
167+ },
168+ average: {
169+ memory: current.memory.rss,
170+ cpu: current.cpu.percent || 0,
171+ },
172+ };
173+ }
174+
175+ const peakMemory = Math.max(
176+ ...this.resourceHistory.map((r) => r.memory.rss),
177+ );
178+ const peakCpu = Math.max(
179+ ...this.resourceHistory.map((r) => r.cpu.percent || 0),
180+ );
181+
182+ const avgMemory =
183+ this.resourceHistory.reduce((sum, r) => sum + r.memory.rss, 0) /
184+ this.resourceHistory.length;
185+ const avgCpu =
186+ this.resourceHistory.reduce((sum, r) => sum + (r.cpu.percent || 0), 0) /
187+ this.resourceHistory.length;
188+
189+ return {
190+ current,
191+ peak: {
192+ memory: Math.max(peakMemory, current.memory.rss),
193+ cpu: Math.max(peakCpu, current.cpu.percent || 0),
194+ },
195+ average: {
196+ memory: avgMemory,
197+ cpu: avgCpu,
198+ },
199+ };
200+ }
201+
202+ private collectResourceUsage(): void {
203+ try {
204+ const usage = this.getCurrentResourceUsage();
205+
206+ // Update for next CPU calculation
207+ this.lastCpuUsage = process.cpuUsage();
208+ this.lastTimestamp = usage.timestamp;
209+
210+ // Add to history
211+ this.resourceHistory.push(usage);
212+
213+ // Trim history if too large
214+ if (this.resourceHistory.length > this.maxHistorySize) {
215+ this.resourceHistory = this.resourceHistory.slice(-this.maxHistorySize);
216+ }
217+
218+ // Check for potential issues and log warnings
219+ this.checkResourceThresholds(usage);
220+ } catch (error) {
221+ logger.error("Error collecting resource usage", error);
222+ }
223+ }
224+
225+ private checkResourceThresholds(usage: ResourceUsage): void {
226+ const memoryUsageMB = usage.memory.rss / 1024 / 1024;
227+ const cpuPercent = usage.cpu.percent || 0;
228+
229+ // Memory threshold: 500MB
230+ if (memoryUsageMB > 500) {
231+ logger.warn("High memory usage detected", {
232+ memoryMB: Math.round(memoryUsageMB),
233+ threshold: 500,
234+ });
235+ }
236+
237+ // CPU threshold: 80%
238+ if (cpuPercent > 80) {
239+ logger.warn("High CPU usage detected", {
240+ cpuPercent: Math.round(cpuPercent),
241+ threshold: 80,
242+ });
243+ }
244+
245+ // Event loop lag threshold: 100ms
246+ if (usage.eventLoop.lag > 100) {
247+ logger.warn("High event loop lag detected", {
248+ lagMs: Math.round(usage.eventLoop.lag),
249+ threshold: 100,
250+ });
251+ }
252+ }
253+
254+ private async getFileDescriptorCount(): Promise<number | null> {
255+ if (process.platform === "win32") {
256+ return null; // Not supported on Windows
257+ }
258+
259+ try {
260+ const { stdout } = await execAsync(`lsof -p ${process.pid} | wc -l`);
261+ return parseInt(stdout.trim(), 10) - 1; // Subtract 1 for header line
262+ } catch {
263+ return null;
264+ }
265+ }
266+
267+ private getLoadAverage(): number[] {
268+ try {
269+ return process.platform === "win32" ? [0, 0, 0] : os.loadavg();
270+ } catch {
271+ return [0, 0, 0];
272+ }
273+ }
274+
275+ private getProcessUptime(): number {
276+ try {
277+ return typeof process.uptime === "function" ? process.uptime() : 0;
278+ } catch {
279+ return 0;
280+ }
281+ }
282+
283+ private getFreeMemory(): number {
284+ try {
285+ return os.freemem();
286+ } catch {
287+ return 0;
288+ }
289+ }
290+
291+ private getTotalMemory(): number {
292+ try {
293+ return os.totalmem();
294+ } catch {
295+ return 1024 * 1024 * 1024; // 1GB default fallback
296+ }
297+ }
298+
299+ // Synchronous approximation of event loop lag
300+ private measureEventLoopLag(): number {
301+ // Return a simple approximation based on load average on Unix systems
302+ const loadAvg = this.getLoadAverage();
303+ if (loadAvg[0] > 0) {
304+ // Rough approximation: higher load = higher lag
305+ return Math.min(loadAvg[0] * 10, 200); // Cap at 200ms
306+ }
307+
308+ return 0;
309+ }
310+}
311+
312+export { ResourceMonitoringService };
modified extensions/cli/src/services/index.ts +10 −0
@@ -9,6 +9,7 @@
99 import { MCPService } from "./MCPService.js";
1010 import { ModelService } from "./ModelService.js";
1111 import { modeService } from "./ModeService.js";
12+import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
1213 import { serviceContainer } from "./ServiceContainer.js";
1314 import {
1415 ApiClientServiceState,
@@ -26,6 +27,7 @@
2627 const apiClientService = new ApiClientService();
2728 const mcpService = new MCPService();
2829 const fileIndexService = new FileIndexService();
30+const resourceMonitoringService = new ResourceMonitoringService();
2931
3032 /**
3133 * Initialize all services and register them with the service container
@@ -220,6 +222,12 @@
220222 [],
221223 );
222224
225+ serviceContainer.register(
226+ SERVICE_NAMES.RESOURCE_MONITORING,
227+ () => resourceMonitoringService.initialize(),
228+ [],
229+ );
230+
223231 // Eagerly initialize all services to ensure they're ready when needed
224232 // This avoids race conditions and "service not ready" errors
225233 await serviceContainer.initializeAll();
@@ -262,6 +270,7 @@
262270 SERVICE_NAMES.MODEL,
263271 SERVICE_NAMES.MCP,
264272 SERVICE_NAMES.FILE_INDEX,
273+ SERVICE_NAMES.RESOURCE_MONITORING,
265274 ].every((name) => serviceContainer.isReady(name));
266275 }
267276
@@ -283,6 +292,7 @@
283292 mcp: mcpService,
284293 fileIndex: fileIndexService,
285294 mode: modeService,
295+ resourceMonitoring: resourceMonitoringService,
286296 } as const;
287297
288298 // Export the service container for advanced usage
modified extensions/cli/src/services/types.ts +1 −0
@@ -105,6 +105,7 @@
105105 API_CLIENT: "apiClient",
106106 TOOL_PERMISSIONS: "toolPermissions",
107107 FILE_INDEX: "fileIndex",
108+ RESOURCE_MONITORING: "resourceMonitoring",
108109 } as const;
109110
110111 /**
modified extensions/cli/src/shared-options.ts +2 −2
@@ -45,8 +45,8 @@
4545 [] as string[],
4646 )
4747 .option(
48- "--prompt <slug>",
49- "Add a prompt from the hub (slug in format 'owner/package'). Can be specified multiple times.",
48+ "--prompt <prompt>",
49+ "Add to the initial user message (can be a file path, hub slug, or string content). Can be specified multiple times.",
5050 (value: string, previous: string[] | undefined) => {
5151 const array = Array.isArray(previous) ? previous : [];
5252 array.push(value);
modified extensions/cli/src/systemMessage.test.ts +104 −3
@@ -11,11 +11,11 @@
1111 },
1212 }));
1313
14-// Mock processRule to avoid file system operations in tests
14+// Mock processPromptOrRule to avoid file system operations in tests
1515 vi.mock("./args.js", () => ({
16- processRule: vi
16+ processPromptOrRule: vi
1717 .fn()
18- .mockImplementation((rule: string) => Promise.resolve(rule)),
18+ .mockImplementation((spec: string) => Promise.resolve(spec)),
1919 }));
2020
2121 describe("constructSystemMessage", () => {
@@ -146,4 +146,105 @@
146146 expect(result).not.toContain("IMPORTANT: You are running in headless mode");
147147 expect(result).not.toContain("Provide ONLY your final answer");
148148 });
149+
150+ it("should add JSON format instructions when format is json", async () => {
151+ const result = await constructSystemMessage(undefined, "json");
152+
153+ expect(result).toContain("You are an agent in the Continue CLI");
154+ expect(result).toContain(
155+ "IMPORTANT: You are operating in JSON output mode",
156+ );
157+ expect(result).toContain("Your final response MUST be valid JSON");
158+ expect(result).toContain("JSON.parse()");
159+ });
160+
161+ it("should add plan mode instructions when mode is plan", async () => {
162+ const result = await constructSystemMessage(
163+ undefined,
164+ undefined,
165+ false,
166+ "plan",
167+ );
168+
169+ expect(result).toContain("You are an agent in the Continue CLI");
170+ expect(result).toContain("PLAN MODE: You are operating in plan mode");
171+ expect(result).toContain(
172+ "which means that your goal is to help the user investigate their ideas",
173+ );
174+ expect(result).toContain("develop a plan before taking action");
175+ expect(result).toContain("read-only tools");
176+ expect(result).toContain(
177+ "should not attempt to circumvent them to write / delete / create files",
178+ );
179+ });
180+
181+ it("should not add plan mode instructions when mode is not plan", async () => {
182+ const result = await constructSystemMessage(
183+ undefined,
184+ undefined,
185+ false,
186+ "normal",
187+ );
188+
189+ expect(result).toContain("You are an agent in the Continue CLI");
190+ expect(result).not.toContain("PLAN MODE: You are operating in plan mode");
191+ expect(result).not.toContain(
192+ "which means that your goal is to help the user investigate their ideas",
193+ );
194+ });
195+
196+ it("should not add plan mode instructions when mode is undefined", async () => {
197+ const result = await constructSystemMessage();
198+
199+ expect(result).toContain("You are an agent in the Continue CLI");
200+ expect(result).not.toContain("PLAN MODE: You are operating in plan mode");
201+ expect(result).not.toContain(
202+ "which means that your goal is to help the user investigate their ideas",
203+ );
204+ });
205+
206+ it("should include basic plan mode description", async () => {
207+ const result = await constructSystemMessage(
208+ undefined,
209+ undefined,
210+ false,
211+ "plan",
212+ );
213+
214+ expect(result).toContain("PLAN MODE: You are operating in plan mode");
215+ expect(result).toContain("read-only tools");
216+ expect(result).toContain("write / delete / create files");
217+ });
218+
219+ it("should combine plan mode with headless mode instructions", async () => {
220+ const result = await constructSystemMessage(
221+ undefined,
222+ undefined,
223+ true,
224+ "plan",
225+ );
226+
227+ expect(result).toContain("IMPORTANT: You are running in headless mode");
228+ expect(result).toContain("PLAN MODE: You are operating in plan mode");
229+ expect(result).toContain(
230+ "which means that your goal is to help the user investigate their ideas",
231+ );
232+ });
233+
234+ it("should combine plan mode with JSON format instructions", async () => {
235+ const result = await constructSystemMessage(
236+ undefined,
237+ "json",
238+ false,
239+ "plan",
240+ );
241+
242+ expect(result).toContain(
243+ "IMPORTANT: You are operating in JSON output mode",
244+ );
245+ expect(result).toContain("PLAN MODE: You are operating in plan mode");
246+ expect(result).toContain(
247+ "which means that your goal is to help the user investigate their ideas",
248+ );
249+ });
149250 });
modified extensions/cli/src/systemMessage.ts +16 −3
@@ -5,7 +5,9 @@
55 import pkg from "ignore-walk";
66 import { Minimatch } from "minimatch";
77
8-import { processRule } from "./args.js";
8+import { processPromptOrRule } from "./args.js";
9+import { PermissionMode } from "./permissions/types.js";
10+import { modeService } from "./services/ModeService.js";
911 import { serviceContainer } from "./services/ServiceContainer.js";
1012 import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js";
1113 const { WalkerSync } = pkg;
@@ -116,16 +118,17 @@
116118
117119 /**
118120 * Load and construct a comprehensive system message with base message and rules section
119- * @param rulesSystemMessage - The rules system message from the assistant
120121 * @param additionalRules - Additional rules from --rule flags
121122 * @param format - Output format for headless mode
122123 * @param headless - Whether running in headless mode
124+ * @param mode - Current permission mode
123125 * @returns The comprehensive system message with base message and rules section
124126 */
125127 export async function constructSystemMessage(
126128 additionalRules?: string[],
127129 format?: "json",
128130 headless?: boolean,
131+ mode?: PermissionMode,
129132 ): Promise<string> {
130133 const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"];
131134
@@ -150,7 +153,7 @@
150153 if (additionalRules && additionalRules.length > 0) {
151154 for (const ruleSpec of additionalRules) {
152155 try {
153- const processedRule = await processRule(ruleSpec);
156+ const processedRule = await processPromptOrRule(ruleSpec);
154157 processedRules.push(processedRule);
155158 } catch (error: any) {
156159 console.warn(
@@ -163,6 +166,9 @@
163166 const configYamlRules = await getConfigYamlRules();
164167 processedRules.push(...configYamlRules);
165168
169+ // Get current mode if not provided
170+ const currentMode = mode ?? modeService.getCurrentMode();
171+
166172 // Construct the comprehensive system message
167173 let systemMessage = baseSystemMessage;
168174
@@ -185,6 +191,13 @@
185191 }`;
186192 }
187193
194+ // Add plan mode specific instructions if in plan mode
195+ if (currentMode === "plan") {
196+ systemMessage += `
197+
198+PLAN MODE: You are operating in plan mode, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files.`;
199+ }
200+
188201 // Add rules section if we have any rules or agent content
189202 if (agentContent || processedRules.length > 0) {
190203 systemMessage += '\n\n<context name="userRules">';
modified extensions/cli/src/ui/AppRoot.tsx +1 −0
@@ -9,6 +9,7 @@
99 initialPrompt?: string;
1010 resume?: boolean;
1111 additionalRules?: string[];
12+ additionalPrompts?: string[];
1213 }
1314
1415 /**
modified extensions/cli/src/ui/SessionSelector.tsx +3 −3
@@ -63,7 +63,7 @@
6363 if (displaySessions[selectedIndex]) {
6464 onSelect(displaySessions[selectedIndex].id);
6565 }
66- } else if (key.escape || (key.ctrl && input === "c")) {
66+ } else if (key.escape || (key.ctrl && input === "d")) {
6767 onExit();
6868 }
6969 });
@@ -73,7 +73,7 @@
7373 <Box flexDirection="column" padding={1}>
7474 <Text color="yellow">No previous sessions found.</Text>
7575 <Text color="gray">Start a new conversation with: cn</Text>
76- <Text color="gray">Press ESC to exit</Text>
76+ <Text color="gray">Press ESC or Ctrl+D to exit</Text>
7777 </Box>
7878 );
7979 }
@@ -84,7 +84,7 @@
8484 Recent Sessions
8585 </Text>
8686 <Text color="gray">
87- Use ↑↓ arrows to navigate, Enter to select, ESC to exit
87+ Use ↑↓ arrows to navigate, Enter to select, ESC or Ctrl+D to exit
8888 </Text>
8989 <Text> </Text>
9090
modified extensions/cli/src/ui/TUIChat.tsx +141 −68
@@ -1,5 +1,11 @@
11 import { Box, Text } from "ink";
2-import React, { useMemo, useState } from "react";
2+import React, {
3+ useCallback,
4+ useEffect,
5+ useMemo,
6+ useRef,
7+ useState,
8+} from "react";
39
410 import { useServices } from "../hooks/useService.js";
511 import {
@@ -9,8 +15,10 @@
915 MCPServiceState,
1016 ModelServiceState,
1117 } from "../services/types.js";
18+import { logger } from "../util/logger.js";
1219
1320 import { BottomStatusBar } from "./components/BottomStatusBar.js";
21+import { ResourceDebugBar } from "./components/ResourceDebugBar.js";
1422 import { ScreenContent } from "./components/ScreenContent.js";
1523 import { StaticChatContent } from "./components/StaticChatContent.js";
1624 import { useNavigation } from "./context/NavigationContext.js";
@@ -36,23 +44,61 @@
3644 initialPrompt?: string;
3745 resume?: boolean;
3846 additionalRules?: string[];
47+ additionalPrompts?: string[];
3948 }
4049
41-const TUIChat: React.FC<TUIChatProps> = ({
42- remoteUrl,
43- configPath,
44- initialPrompt,
45- resume,
46- additionalRules,
47-}) => {
48- // Check if we're in remote mode
49- const isRemoteMode = useMemo(() => {
50- return !!remoteUrl;
51- }, [remoteUrl]);
50+// Helper function to load and set session
51+async function loadAndSetSession(
52+ sessionId: string,
53+ closeCurrentScreen: () => void,
54+ setChatHistory: (history: any) => void,
55+ setMessages: (messages: any) => void,
56+ setShowIntroMessage: (show: boolean) => void,
57+) {
58+ try {
59+ // Close the session selector
60+ closeCurrentScreen();
61+
62+ // Import session functions
63+ const { loadSessionById } = await import("../session.js");
64+
65+ // Load the session history
66+ const sessionHistory = loadSessionById(sessionId);
67+ if (!sessionHistory) {
68+ logger.error(`Session ${sessionId} could not be loaded.`);
69+ return;
70+ }
5271
53- const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [remoteUrl]);
72+ // Set the session ID so future operations use this session
73+ process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
74+ "continue-cli-",
75+ "",
76+ );
77+
78+ // Directly set the chat history and messages to the loaded session
79+ setChatHistory(sessionHistory);
80+
81+ // Convert chat history to display messages (exclude system messages)
82+ const displayMessages = sessionHistory
83+ .filter((msg: any) => msg.role !== "system")
84+ .map((msg: any) => ({
85+ role: msg.role,
86+ content: msg.content as string,
87+ }));
88+
89+ setMessages(displayMessages);
90+
91+ // Clear the intro message since we're now showing a resumed session
92+ setShowIntroMessage(false);
93+ } catch (error) {
94+ console.error("Error loading session:", error);
95+ }
96+}
97+
98+// Custom hook to manage services
99+function useTUIChatServices(remoteUrl?: string) {
100+ const isRemoteMode = useMemo(() => !!remoteUrl, [remoteUrl]);
54101
55- // Get all services reactively - only in normal mode
56102 const { services, allReady: allServicesReady } = useServices<{
57103 auth: AuthServiceState;
58104 config: ConfigServiceState;
@@ -61,6 +107,57 @@
61107 apiClient: ApiClientServiceState;
62108 }>(["auth", "config", "model", "mcp", "apiClient"]);
63109
110+ return { services, allServicesReady, isRemoteMode };
111+}
112+
113+// Custom hook for chat handlers
114+function useChatHandlers(
115+ setShowIntroMessage: (show: boolean) => void,
116+ setStaticRefreshTrigger: React.Dispatch<React.SetStateAction<number>>,
117+) {
118+ // Temporary refs to avoid circular dependency
119+ const resetChatHistoryRef = useRef<(() => void) | null>(null);
120+
121+ // Handle clearing chat and resetting intro message
122+ const handleClear = useCallback(() => {
123+ setShowIntroMessage(true);
124+ // Trigger static content refresh by incrementing the trigger
125+ setStaticRefreshTrigger((prev) => prev + 1);
126+ }, [setShowIntroMessage, setStaticRefreshTrigger]);
127+
128+ // Service reload handlers - these will trigger reactive updates
129+ const handleReload = useCallback(async () => {
130+ // Services will automatically update the UI when they reload
131+ // We just need to reset chat history, intro message, and clear the screen
132+ if (resetChatHistoryRef.current) {
133+ resetChatHistoryRef.current();
134+ }
135+ setShowIntroMessage(false);
136+ process.stdout.write("\x1b[2J\x1b[H");
137+ }, [setShowIntroMessage]);
138+
139+ return {
140+ handleClear,
141+ handleReload,
142+ resetChatHistoryRef,
143+ };
144+}
145+
146+// eslint-disable-next-line complexity
147+const TUIChat: React.FC<TUIChatProps> = ({
148+ remoteUrl,
149+ configPath,
150+ initialPrompt,
151+ resume,
152+ additionalRules,
153+ additionalPrompts,
154+}) => {
155+ // Use custom hook for services
156+ const { services, allServicesReady, isRemoteMode } =
157+ useTUIChatServices(remoteUrl);
158+
159+ const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [remoteUrl]);
160+
64161 // Use navigation context
65162 const {
66163 state: navState,
@@ -86,24 +183,14 @@
86183 closeCurrentScreen,
87184 );
88185
89- // Service reload handlers - these will trigger reactive updates
90- const handleReload = async () => {
91- // Services will automatically update the UI when they reload
92- // We just need to reset chat history, intro message, and clear the screen
93- resetChatHistory();
94- setShowIntroMessage(false);
95- process.stdout.write("\x1b[2J\x1b[H");
96- };
97-
98186 // State to trigger static content refresh for /clear command
99187 const [staticRefreshTrigger, setStaticRefreshTrigger] = useState(0);
100188
101- // Handle clearing chat and resetting intro message
102- const handleClear = () => {
103- setShowIntroMessage(true);
104- // Trigger static content refresh by incrementing the trigger
105- setStaticRefreshTrigger((prev) => prev + 1);
106- };
189+ // Use chat handlers hook
190+ const { handleClear, handleReload, resetChatHistoryRef } = useChatHandlers(
191+ setShowIntroMessage,
192+ setStaticRefreshTrigger,
193+ );
107194
108195 const {
109196 messages,
@@ -126,6 +213,7 @@
126213 initialPrompt,
127214 resume,
128215 additionalRules,
216+ additionalPrompts,
129217 onShowConfigSelector: () => navigateTo("config"),
130218 onShowModelSelector: () => navigateTo("model"),
131219 onShowMCPSelector: () => navigateTo("mcp"),
@@ -138,6 +226,11 @@
138226 remoteUrl,
139227 });
140228
229+ // Update ref after useChat returns
230+ useEffect(() => {
231+ resetChatHistoryRef.current = resetChatHistory;
232+ }, [resetChatHistory]);
233+
141234 // Calculate context percentage
142235 const contextData = useContextPercentage({
143236 chatHistory,
@@ -153,52 +246,27 @@
153246 );
154247
155248 // Session selection handler
156- const handleSessionSelect = async (sessionId: string) => {
157- try {
158- // Close the session selector
159- closeCurrentScreen();
160-
161- // Import session functions
162- const { loadSessionById } = await import("../session.js");
163-
164- // Load the session history
165- const sessionHistory = loadSessionById(sessionId);
166- if (!sessionHistory) {
167- console.error(`Session ${sessionId} could not be loaded.`);
168- return;
169- }
170-
171- // Set the session ID so future operations use this session
172- process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
173- "continue-cli-",
174- "",
249+ const handleSessionSelect = useCallback(
250+ async (sessionId: string) => {
251+ await loadAndSetSession(
252+ sessionId,
253+ closeCurrentScreen,
254+ setChatHistory,
255+ setMessages,
256+ setShowIntroMessage,
175257 );
176-
177- // Directly set the chat history and messages to the loaded session
178- setChatHistory(sessionHistory);
179-
180- // Convert chat history to display messages (exclude system messages)
181- const displayMessages = sessionHistory
182- .filter((msg) => msg.role !== "system")
183- .map((msg) => ({
184- role: msg.role,
185- content: msg.content as string,
186- }));
187-
188- setMessages(displayMessages);
189-
190- // Clear the intro message since we're now showing a resumed session
191- setShowIntroMessage(false);
192- } catch (error) {
193- console.error("Error loading session:", error);
194- }
195- };
258+ },
259+ [closeCurrentScreen, setChatHistory, setMessages, setShowIntroMessage],
260+ );
196261
197262 // Determine if input should be disabled
198263 // Allow input even when services are loading, but disable for UI overlays
199264 const isInputDisabled =
200265 navState.currentScreen !== "chat" || !!activePermissionRequest;
201266
267+ // Check if verbose mode is enabled for resource debugging
268+ const isVerboseMode = useMemo(() => process.argv.includes("--verbose"), []);
269+
202270 return (
203271 <Box flexDirection="column" height="100%">
204272 {/* Chat history - takes up all available space above input */}
@@ -265,6 +333,11 @@
265333 isRemoteMode={isRemoteMode}
266334 />
267335
336+ {/* Resource debug bar - only in verbose mode */}
337+ {isVerboseMode && !isRemoteMode && (
338+ <ResourceDebugBar visible={navState.currentScreen === "chat"} />
339+ )}
340+
268341 {/* Free trial status and Continue CLI info - always show */}
269342 <BottomStatusBar
270343 currentMode={currentMode}
modified extensions/cli/src/ui/UserInput.tsx +11 −0
@@ -412,6 +412,16 @@
412412 return false;
413413 };
414414
415+ // Clear input function
416+ const clearInput = () => {
417+ textBuffer.clear();
418+ setInputText("");
419+ setCursorPosition(0);
420+ setShowSlashCommands(false);
421+ setShowFileSearch(false);
422+ inputHistory.resetNavigation();
423+ };
424+
415425 useInput((input, key) => {
416426 // Don't handle any input when disabled
417427 if (disabled) {
@@ -427,6 +437,7 @@
427437 showSlashCommands,
428438 showFileSearch,
429439 cycleModes,
440+ clearInput,
430441 })
431442 ) {
432443 return;
added extensions/cli/src/ui/components/ResourceDebugBar.tsx +184 −0
@@ -0,0 +1,184 @@
1+import { Box, Text } from "ink";
2+import React, { useEffect, useState } from "react";
3+
4+import { services } from "../../services/index.js";
5+import { ResourceUsage } from "../../services/ResourceMonitoringService.js";
6+
7+interface ResourceDebugBarProps {
8+ visible: boolean;
9+}
10+
11+function formatBytes(bytes: number): string {
12+ const mb = bytes / 1024 / 1024;
13+ return mb >= 1 ? `${mb.toFixed(1)}MB` : `${(bytes / 1024).toFixed(1)}KB`;
14+}
15+
16+function formatPercent(percent: number): string {
17+ return `${Math.round(percent)}%`;
18+}
19+
20+function formatTime(ms: number): string {
21+ if (ms < 1000) return `${Math.round(ms)}ms`;
22+ return `${(ms / 1000).toFixed(1)}s`;
23+}
24+
25+export function ResourceDebugBar({ visible }: ResourceDebugBarProps) {
26+ const [resourceData, setResourceData] = useState<ResourceUsage | null>(null);
27+ const [isError, setIsError] = useState(false);
28+
29+ useEffect(() => {
30+ if (!visible) return;
31+
32+ const updateResourceData = () => {
33+ try {
34+ const usage = services.resourceMonitoring.getCurrentResourceUsage();
35+ setResourceData(usage);
36+ setIsError(false);
37+ } catch {
38+ setIsError(true);
39+ }
40+ };
41+
42+ // Initial update
43+ updateResourceData();
44+
45+ // Update every 2 seconds
46+ const intervalId = setInterval(updateResourceData, 2000);
47+
48+ return () => {
49+ clearInterval(intervalId);
50+ };
51+ }, [visible]);
52+
53+ if (!visible) {
54+ return null;
55+ }
56+
57+ if (isError) {
58+ return (
59+ <Box paddingX={1}>
60+ <Text color="red">Resource monitoring error</Text>
61+ </Box>
62+ );
63+ }
64+
65+ if (!resourceData) {
66+ return null;
67+ }
68+
69+ const memoryPercent =
70+ (resourceData.memory.rss / resourceData.system.totalMemory) * 100;
71+ const cpuPercent = resourceData.cpu.percent || 0;
72+ const heapPercent =
73+ (resourceData.memory.heapUsed / resourceData.memory.heapTotal) * 100;
74+
75+ // Color coding based on usage levels
76+ const getMemoryColor = () => {
77+ if (memoryPercent > 80) return "red";
78+ if (memoryPercent > 60) return "yellow";
79+ return "green";
80+ };
81+
82+ const getCpuColor = () => {
83+ if (cpuPercent > 80) return "red";
84+ if (cpuPercent > 60) return "yellow";
85+ return "green";
86+ };
87+
88+ const getEventLoopColor = () => {
89+ if (resourceData.eventLoop.lag > 100) return "red";
90+ if (resourceData.eventLoop.lag > 50) return "yellow";
91+ return "green";
92+ };
93+
94+ return (
95+ <Box paddingX={1}>
96+ <Text color="gray">Debug: </Text>
97+
98+ <Text color={getMemoryColor()}>
99+ MEM: {formatBytes(resourceData.memory.rss)}
100+ </Text>
101+ <Text color="gray"> | </Text>
102+
103+ <Text color="gray">HEAP: {formatPercent(heapPercent)}</Text>
104+ <Text color="gray"> | </Text>
105+
106+ <Text color={getCpuColor()}>CPU: {formatPercent(cpuPercent)}</Text>
107+ <Text color="gray"> | </Text>
108+
109+ <Text color={getEventLoopColor()}>
110+ LAG: {formatTime(resourceData.eventLoop.lag)}
111+ </Text>
112+
113+ {resourceData.fileDescriptors && (
114+ <>
115+ <Text color="gray"> | </Text>
116+ <Text color="gray">FD: {resourceData.fileDescriptors}</Text>
117+ </>
118+ )}
119+
120+ <Text color="gray"> | </Text>
121+ <Text color="gray">
122+ UP: {formatTime(resourceData.system.uptime * 1000)}
123+ </Text>
124+ </Box>
125+ );
126+}
127+
128+export function ResourceDebugDetails({ visible }: { visible: boolean }) {
129+ const [summary, setSummary] = useState<any>(null);
130+
131+ useEffect(() => {
132+ if (!visible) return;
133+
134+ const updateData = () => {
135+ try {
136+ const summaryData = services.resourceMonitoring.getResourceSummary();
137+ setSummary(summaryData);
138+ } catch {
139+ // Handle error silently
140+ }
141+ };
142+
143+ updateData();
144+ const intervalId = setInterval(updateData, 3000);
145+
146+ return () => clearInterval(intervalId);
147+ }, [visible]);
148+
149+ if (!visible || !summary) {
150+ return null;
151+ }
152+
153+ return (
154+ <Box
155+ flexDirection="column"
156+ borderStyle="single"
157+ borderColor="gray"
158+ paddingX={1}
159+ marginTop={1}
160+ >
161+ <Text color="cyan" bold>
162+ Resource Usage Summary
163+ </Text>
164+
165+ <Box marginTop={1}>
166+ <Text color="gray">Current: </Text>
167+ <Text>{formatBytes(summary.current.memory.rss)} mem, </Text>
168+ <Text>{formatPercent(summary.current.cpu.percent || 0)} cpu</Text>
169+ </Box>
170+
171+ <Box>
172+ <Text color="gray">Peak: </Text>
173+ <Text>{formatBytes(summary.peak.memory)} mem, </Text>
174+ <Text>{formatPercent(summary.peak.cpu)} cpu</Text>
175+ </Box>
176+
177+ <Box>
178+ <Text color="gray">Average: </Text>
179+ <Text>{formatBytes(summary.average.memory)} mem, </Text>
180+ <Text>{formatPercent(summary.average.cpu)} cpu</Text>
181+ </Box>
182+ </Box>
183+ );
184+}
modified extensions/cli/src/ui/hooks/useChat.ts +21 −3
@@ -42,6 +42,7 @@
4242 initialPrompt,
4343 resume,
4444 additionalRules,
45+ additionalPrompts,
4546 onShowConfigSelector,
4647 onShowModelSelector,
4748 onShowMCPSelector,
@@ -163,10 +164,27 @@
163164 useEffect(() => {
164165 // Only handle initial prompt after chat history is initialized
165166 // This prevents race conditions where the prompt runs before system message is loaded
166- if (initialPrompt && isChatHistoryInitialized) {
167- handleUserMessage(initialPrompt);
167+ if (
168+ (initialPrompt || (additionalPrompts && additionalPrompts.length > 0)) &&
169+ isChatHistoryInitialized
170+ ) {
171+ const processPrompts = async () => {
172+ const { processAndCombinePrompts } = await import(
173+ "../../util/promptProcessor.js"
174+ );
175+ const finalMessage = await processAndCombinePrompts(
176+ additionalPrompts,
177+ initialPrompt,
178+ );
179+
180+ if (finalMessage) {
181+ await handleUserMessage(finalMessage);
182+ }
183+ };
184+
185+ processPrompts().catch(console.error);
168186 }
169- }, [initialPrompt, isChatHistoryInitialized]);
187+ }, [initialPrompt, additionalPrompts, isChatHistoryInitialized]);
170188
171189 const executeStreamingResponse = async (
172190 newHistory: ChatCompletionMessageParam[],
modified extensions/cli/src/ui/hooks/useChat.types.ts +1 −0
@@ -11,6 +11,7 @@
1111 initialPrompt?: string;
1212 resume?: boolean;
1313 additionalRules?: string[];
14+ additionalPrompts?: string[];
1415 onShowConfigSelector: () => void;
1516 onShowMCPSelector: () => void;
1617 onShowModelSelector?: () => void;
modified extensions/cli/src/ui/hooks/useUserInput.ts +18 −4
@@ -9,14 +9,28 @@
99 showSlashCommands: boolean;
1010 showFileSearch: boolean;
1111 cycleModes: () => Promise<PermissionMode>;
12+ clearInput?: () => void;
1213 }
1314
1415 export function handleControlKeys(options: ControlKeysOptions): boolean {
15- const { input, key, exit, showSlashCommands, showFileSearch, cycleModes } =
16- options;
16+ const {
17+ input,
18+ key,
19+ exit,
20+ showSlashCommands,
21+ showFileSearch,
22+ cycleModes,
23+ clearInput,
24+ } = options;
1725
18- // Handle Ctrl+C and Ctrl+D
19- if (key.ctrl && (input === "c" || input === "d")) {
26+ // Handle Ctrl+C to clear input
27+ if (key.ctrl && input === "c" && clearInput) {
28+ clearInput();
29+ return true;
30+ }
31+
32+ // Handle Ctrl+D to exit
33+ if (key.ctrl && input === "d") {
2034 exit();
2135 return true;
2236 }
modified extensions/cli/src/ui/index.ts +4 −1
@@ -15,6 +15,7 @@
1515 config?: string;
1616 org?: string;
1717 rule?: string[];
18+ prompt?: string[];
1819 toolPermissionOverrides?: {
1920 allow?: string[];
2021 ask?: string[];
@@ -33,6 +34,7 @@
3334 config,
3435 org,
3536 rule,
37+ prompt,
3638 toolPermissionOverrides,
3739 skipOnboarding,
3840 customStdin,
@@ -41,7 +43,7 @@
4143 // Initialize services only if not already done (skipOnboarding means already initialized)
4244 if (!skipOnboarding) {
4345 await initializeServices({
44- options: { config, org, rule },
46+ options: { config, org, rule, prompt },
4547 headless: false,
4648 toolPermissionOverrides,
4749 });
@@ -62,6 +64,7 @@
6264 initialPrompt,
6365 resume,
6466 additionalRules: rule,
67+ additionalPrompts: prompt,
6568 }),
6669 }),
6770 renderOptions,
added extensions/cli/src/util/promptProcessor.test.ts +127 −0
@@ -0,0 +1,127 @@
1+import { describe, it, expect, vi, beforeEach } from "vitest";
2+
3+import * as args from "../args.js";
4+
5+import { processAndCombinePrompts } from "./promptProcessor.js";
6+
7+// Mock the args module
8+vi.mock("../args.js", () => ({
9+ processPromptOrRule: vi.fn(),
10+}));
11+
12+// Mock the logger
13+vi.mock("./logger.js", () => ({
14+ logger: {
15+ warn: vi.fn(),
16+ },
17+}));
18+
19+describe("promptProcessor", () => {
20+ beforeEach(() => {
21+ vi.clearAllMocks();
22+ });
23+
24+ describe("processAndCombinePrompts", () => {
25+ it("should return initial prompt when no additional prompts", async () => {
26+ const result = await processAndCombinePrompts(undefined, "initial");
27+ expect(result).toBe("initial");
28+ });
29+
30+ it("should return initial prompt when empty additional prompts array", async () => {
31+ const result = await processAndCombinePrompts([], "initial");
32+ expect(result).toBe("initial");
33+ });
34+
35+ it("should return undefined when no prompts at all", async () => {
36+ const result = await processAndCombinePrompts();
37+ expect(result).toBeUndefined();
38+ });
39+
40+ it("should process single additional prompt without initial", async () => {
41+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
42+ mockProcessPromptOrRule.mockResolvedValue("processed prompt");
43+
44+ const result = await processAndCombinePrompts(["prompt1"]);
45+
46+ expect(mockProcessPromptOrRule).toHaveBeenCalledWith("prompt1");
47+ expect(result).toBe("processed prompt");
48+ });
49+
50+ it("should combine multiple processed prompts", async () => {
51+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
52+ mockProcessPromptOrRule
53+ .mockResolvedValueOnce("first prompt")
54+ .mockResolvedValueOnce("second prompt");
55+
56+ const result = await processAndCombinePrompts(["prompt1", "prompt2"]);
57+
58+ expect(mockProcessPromptOrRule).toHaveBeenCalledTimes(2);
59+ expect(mockProcessPromptOrRule).toHaveBeenNthCalledWith(1, "prompt1");
60+ expect(mockProcessPromptOrRule).toHaveBeenNthCalledWith(2, "prompt2");
61+ expect(result).toBe("first prompt\n\nsecond prompt");
62+ });
63+
64+ it("should combine processed prompts with initial prompt", async () => {
65+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
66+ mockProcessPromptOrRule
67+ .mockResolvedValueOnce("processed1")
68+ .mockResolvedValueOnce("processed2");
69+
70+ const result = await processAndCombinePrompts(
71+ ["prompt1", "prompt2"],
72+ "initial",
73+ );
74+
75+ expect(result).toBe("processed1\n\nprocessed2\n\ninitial");
76+ });
77+
78+ it("should handle processing errors and continue with successful ones", async () => {
79+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
80+ mockProcessPromptOrRule
81+ .mockResolvedValueOnce("success1")
82+ .mockRejectedValueOnce(new Error("processing failed"))
83+ .mockResolvedValueOnce("success2");
84+
85+ const result = await processAndCombinePrompts(["good1", "bad", "good2"]);
86+
87+ expect(mockProcessPromptOrRule).toHaveBeenCalledTimes(3);
88+ expect(result).toBe("success1\n\nsuccess2");
89+ });
90+
91+ it("should return initial prompt when all processing fails", async () => {
92+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
93+ mockProcessPromptOrRule
94+ .mockRejectedValueOnce(new Error("fail1"))
95+ .mockRejectedValueOnce(new Error("fail2"));
96+
97+ const result = await processAndCombinePrompts(
98+ ["bad1", "bad2"],
99+ "initial",
100+ );
101+
102+ expect(result).toBe("initial");
103+ });
104+
105+ it("should return undefined when all processing fails and no initial", async () => {
106+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
107+ mockProcessPromptOrRule.mockRejectedValue(new Error("processing failed"));
108+
109+ const result = await processAndCombinePrompts(["bad"]);
110+
111+ expect(result).toBeUndefined();
112+ });
113+
114+ it("should warn when processing fails", async () => {
115+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
116+ mockProcessPromptOrRule.mockRejectedValue(new Error("test error"));
117+
118+ const { logger } = await import("./logger.js");
119+
120+ await processAndCombinePrompts(["bad-prompt"]);
121+
122+ expect(logger.warn).toHaveBeenCalledWith(
123+ 'Failed to process prompt "bad-prompt": test error',
124+ );
125+ });
126+ });
127+});
added extensions/cli/src/util/promptProcessor.ts +38 −0
@@ -0,0 +1,38 @@
1+import { processPromptOrRule } from "../args.js";
2+
3+import { logger } from "./logger.js";
4+
5+/**
6+ * Process additional prompts from --prompt flags and combine with initial prompt
7+ * @param additionalPrompts - Array of prompt specifications to process
8+ * @param initialPrompt - Optional initial prompt to combine with
9+ * @returns Combined prompt string or undefined if no prompts
10+ */
11+export async function processAndCombinePrompts(
12+ additionalPrompts?: string[],
13+ initialPrompt?: string,
14+): Promise<string | undefined> {
15+ if (!additionalPrompts || additionalPrompts.length === 0) {
16+ return initialPrompt;
17+ }
18+
19+ const processedPrompts: string[] = [];
20+
21+ for (const promptSpec of additionalPrompts) {
22+ try {
23+ const processed = await processPromptOrRule(promptSpec);
24+ processedPrompts.push(processed);
25+ } catch (error: any) {
26+ logger.warn(`Failed to process prompt "${promptSpec}": ${error.message}`);
27+ }
28+ }
29+
30+ if (processedPrompts.length === 0) {
31+ return initialPrompt;
32+ }
33+
34+ const combinedPrompts = processedPrompts.join("\n\n");
35+ return initialPrompt
36+ ? `${combinedPrompts}\n\n${initialPrompt}`
37+ : combinedPrompts;
38+}
modified packages/continue-sdk/typescript/package-lock.json +6 −5
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/sdk",
3- "version": "0.0.12",
3+ "version": "0.0.13",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/sdk",
9- "version": "0.0.12",
9+ "version": "0.0.13",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "openai": "^4.96.2"
@@ -1963,14 +1963,15 @@
19631963 }
19641964 },
19651965 "node_modules/form-data": {
1966- "version": "4.0.2",
1967- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
1968- "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
1966+ "version": "4.0.4",
1967+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
1968+ "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
19691969 "license": "MIT",
19701970 "dependencies": {
19711971 "asynckit": "^0.4.0",
19721972 "combined-stream": "^1.0.8",
19731973 "es-set-tostringtag": "^2.1.0",
1974+ "hasown": "^2.0.2",
19741975 "mime-types": "^2.1.12"
19751976 },
19761977 "engines": {