Hello & goodbye
\r\nHello&goodbye
`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 39, + endIndex: 95, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match content surrounded by different types of whitespace", () => { + const fileContent = `\tconst data = {\n\t\tname: "John",\n\t\tage: 30,\n\t\taddress: {\n\t\t\tstreet: "Main St",\n\t\t\tcity: "NYC"\n\t\t}\n\t};`; + const searchContent = `address:{street:"MainSt",city:"NYC"}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 45, + endIndex: 96, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + // IMPORTANT string.length and string.slice both count UTF-16 units so emojis will count as 2 in both + it("should handle unicode characters with whitespace differences", () => { + const fileContent = `const message = {\n greeting: "Hello π",\n emoji: "π",\n unicode: "cafΓ©",\n symbol: "β"\n};`; + const searchContent = `emoji:"π",unicode:"cafΓ©",symbol:"β"`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 44, + endIndex: 89, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match across multiple nested blocks with varying indentation", () => { + const fileContent = `class Calculator {\n add(a, b) {\n if (typeof a === 'number' && typeof b === 'number') {\n return a + b;\n }\n throw new Error('Invalid input');\n }\n\n multiply(x, y) {\n return x * y;\n }\n}`; + const searchContent = `if(typeofa==='number'&&typeofb==='number'){returna+b;}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 43, + endIndex: 132, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle regex-like patterns with escaped characters", () => { + const fileContent = `const pattern = /\\d+\\.\\d+/g;\nconst test = \"123.456\";\nif (pattern.test(test)) {\n console.log(\"Match found\");\n}`; + const searchContent = `consttest="123.456";if(pattern.test(test)){console.log("Matchfound");}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 29, + endIndex: 110, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match SQL-like content with varying whitespace", () => { + const fileContent = `SELECT users.name,\n users.email,\n profiles.bio\nFROM users\nINNER JOIN profiles ON users.id = profiles.user_id\nWHERE users.active = true\nORDER BY users.name;`; + const searchContent = `SELECTusers.name,users.email,profiles.bioFROMusersINNERJOINprofiles`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 89, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle content with form feeds, vertical tabs, and other rare whitespace", () => { + const fileContent = `function\fprocess\vdata(input)\u0020{\u00A0\n\treturn\u2000input.trim();\u2009\n}`; + const searchContent = `functionprocessdata(input){returninput.trim();}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 56, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match content with Windows-style CRLF line endings", () => { + const fileContent = `@echo off\r\nset PATH=%PATH%;C:\\tools\r\nif \"%1\"==\"\" (\r\n echo Usage: script.bat filename\r\n exit /b 1\r\n)\r\necho Processing %1...\r\necho Done.`; + const searchContent = `if\"%1\"==\"\"(echo Usage: script.bat filename exit/b 1)`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 37, + endIndex: 105, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle deeply nested JSON with mixed formatting", () => { + const fileContent = `{\n \"config\": {\n \"database\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"credentials\": {\n \"username\": \"admin\",\n \"password\": \"secret\"\n },\n \"options\": {\n \"ssl\": true,\n \"timeout\": 30000\n }\n }\n }\n}`; + const searchContent = `\"credentials\":{\"username\":\"admin\",\"password\":\"secret\"},\"options\":{\"ssl\":true,\"timeout\":30000}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 87, + endIndex: 243, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match XML content with attribute spacing differences", () => { + const fileContent = `\nHello World
+Hello World
/v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict
@@ -234,13 +238,16 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
headers: {
- ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
+ ...(shouldCacheSystemMessage || shouldCachePrompt
? { "anthropic-beta": "prompt-caching-2024-07-31" }
: {}),
},
body: JSON.stringify({
...this._anthropicConvertArgs(options),
- messages: this.anthropicInstance.convertMessages(messages),
+ messages: this.anthropicInstance.convertMessages(
+ messages,
+ shouldCachePrompt,
+ ),
system: shouldCacheSystemMessage
? [
{
diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts
index 7a058ced7..6ef57eae3 100644
--- a/core/llm/llms/index.ts
+++ b/core/llm/llms/index.ts
@@ -17,6 +17,7 @@ import BedrockImport from "./BedrockImport";
import Cerebras from "./Cerebras";
import Cloudflare from "./Cloudflare";
import Cohere from "./Cohere";
+import CometAPI from "./CometAPI";
import DeepInfra from "./DeepInfra";
import Deepseek from "./Deepseek";
import Docker from "./Docker";
@@ -33,6 +34,7 @@ import Kindo from "./Kindo";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import LlamaStack from "./LlamaStack";
+import Lemonade from "./Lemonade";
import LMStudio from "./LMStudio";
import Mistral from "./Mistral";
import MockLLM from "./Mock";
@@ -66,6 +68,7 @@ import xAI from "./xAI";
export const LLMClasses = [
Anthropic,
Cohere,
+ CometAPI,
FunctionNetwork,
Gemini,
Llamafile,
@@ -82,6 +85,7 @@ export const LLMClasses = [
LlamaCpp,
OpenAI,
OVHcloud,
+ Lemonade,
LMStudio,
Mistral,
Bedrock,
diff --git a/core/llm/llms/xAI.ts b/core/llm/llms/xAI.ts
index a6b29f01a..13a69c5fc 100644
--- a/core/llm/llms/xAI.ts
+++ b/core/llm/llms/xAI.ts
@@ -7,14 +7,6 @@ class xAI extends OpenAI {
static defaultOptions: Partial = {
apiBase: "https://api.x.ai/v1/",
};
-
- private static MODEL_IDS: { [name: string]: string } = {
- "grok-beta": "grok-beta", // Future names might not line up
- };
-
- protected _convertModelName(model: string) {
- return xAI.MODEL_IDS[model] || this.model;
- }
}
export default xAI;
diff --git a/core/llm/rules/alwaysApply.vitest.ts b/core/llm/rules/alwaysApply.vitest.ts
index f8d6e1160..f586ff87d 100644
--- a/core/llm/rules/alwaysApply.vitest.ts
+++ b/core/llm/rules/alwaysApply.vitest.ts
@@ -44,7 +44,7 @@ describe("alwaysApply Behavior", () => {
alwaysApply: true,
globs: "**/*.tsx", // Should be ignored since alwaysApply is true
source: "rules-block",
- ruleFile: ".continue/rules.md",
+ sourceFile: ".continue/rules.md",
};
// Test with no file context
@@ -83,7 +83,7 @@ describe("alwaysApply Behavior", () => {
alwaysApply: false,
globs: "**/*.tsx",
source: "rules-block",
- ruleFile: ".continue/rules.md",
+ sourceFile: ".continue/rules.md",
};
// Rule with alwaysApply: false and no globs
@@ -93,7 +93,7 @@ describe("alwaysApply Behavior", () => {
alwaysApply: false,
// No globs
source: "rules-block",
- ruleFile: ".continue/rules.md",
+ sourceFile: ".continue/rules.md",
};
// Test with no file context
@@ -131,7 +131,7 @@ describe("alwaysApply Behavior", () => {
name: "Default No Globs Rule",
rule: "Default rule with no globs",
source: "rules-block",
- ruleFile: ".continue/rules.md",
+ sourceFile: ".continue/rules.md",
// No alwaysApply, no globs
};
@@ -141,7 +141,7 @@ describe("alwaysApply Behavior", () => {
rule: "Default rule with globs",
globs: "**/*.tsx",
source: "rules-block",
- ruleFile: ".continue/rules.md",
+ sourceFile: ".continue/rules.md",
// No alwaysApply, with globs
};
diff --git a/core/llm/rules/alwaysApplyRules.vitest.ts b/core/llm/rules/alwaysApplyRules.vitest.ts
index 538ab03cf..b6073bf7d 100644
--- a/core/llm/rules/alwaysApplyRules.vitest.ts
+++ b/core/llm/rules/alwaysApplyRules.vitest.ts
@@ -15,7 +15,7 @@ describe("Rule application with alwaysApply", () => {
rule: "This rule should always be applied",
alwaysApply: true,
source: "rules-block",
- ruleFile: ".continue/always-apply.md",
+ sourceFile: ".continue/always-apply.md",
};
// Create a colocated rule in a nested directory
@@ -23,7 +23,7 @@ describe("Rule application with alwaysApply", () => {
name: "Nested Directory Rule",
rule: "This rule applies to files in the nested directory",
source: "rules-block",
- ruleFile: "nested-folder/rules.md",
+ sourceFile: "nested-folder/rules.md",
};
it("should apply alwaysApply rules even with no file references", () => {
@@ -145,7 +145,7 @@ describe("Rule application with alwaysApply", () => {
rule: "This rule has alwaysApply: true but is blocked by rulePolicies",
alwaysApply: true,
source: "rules-block",
- ruleFile: "src/some/path.md",
+ sourceFile: "src/some/path.md",
};
// Message with no code blocks or file references
diff --git a/core/llm/rules/fileProtocolMatching.vitest.ts b/core/llm/rules/fileProtocolMatching.vitest.ts
index 075ca0472..310e868c5 100644
--- a/core/llm/rules/fileProtocolMatching.vitest.ts
+++ b/core/llm/rules/fileProtocolMatching.vitest.ts
@@ -8,7 +8,7 @@ describe("File Path Protocol Matching", () => {
name: "Rule with file:// protocol",
rule: "This is a test rule",
source: "rules-block",
- ruleFile: "file:///Users/user/project/nested-folder/rules.md",
+ sourceFile: "file:///Users/user/project/nested-folder/rules.md",
};
it("should match relative paths with file:// protocol paths", () => {
diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts
index dc03ad43f..078a2dcdf 100644
--- a/core/llm/rules/getSystemMessageWithRules.ts
+++ b/core/llm/rules/getSystemMessageWithRules.ts
@@ -132,7 +132,7 @@ const isFileInDirectory = (
* Checks if a rule is a root-level rule (.continue directory or no file path)
*/
const isRootLevelRule = (rule: RuleWithSource): boolean => {
- return !rule.ruleFile || rule.ruleFile.includes(".continue/"); // ruleFile path is absolute - hence we need to check for it in between
+ return !rule.sourceFile || rule.sourceFile.includes(".continue/"); // sourceFile path is absolute - hence we need to check for it in between
};
/**
@@ -230,8 +230,8 @@ export const shouldApplyRule = (
const isRootRule = isRootLevelRule(rule);
// For non-root rules, we need to check if any files are in the rule's directory
- if (!isRootRule && rule.ruleFile) {
- const ruleDirectory = getCleanUriPath(rule.ruleFile);
+ if (!isRootRule && rule.sourceFile) {
+ const ruleDirectory = getCleanUriPath(rule.sourceFile);
const lastSlashIndex = ruleDirectory.lastIndexOf("/");
const ruleDirPath =
lastSlashIndex !== -1 ? ruleDirectory.substring(0, lastSlashIndex) : "";
@@ -325,7 +325,7 @@ export const getApplicableRules = (
};
export function getRuleId(rule: RuleWithSource): string {
- return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source;
+ return rule.slug ?? rule.sourceFile ?? rule.name ?? rule.source;
}
export const getSystemMessageWithRules = ({
diff --git a/core/llm/rules/getSystemMessageWithRules.vitest.ts b/core/llm/rules/getSystemMessageWithRules.vitest.ts
index 9f350197d..104ceecf8 100644
--- a/core/llm/rules/getSystemMessageWithRules.vitest.ts
+++ b/core/llm/rules/getSystemMessageWithRules.vitest.ts
@@ -20,7 +20,7 @@ describe("Rule colocation glob matching", () => {
name: "Components Rule",
rule: "Use functional components with hooks",
source: "rules-block",
- ruleFile: "src/components/rules.md",
+ sourceFile: "src/components/rules.md",
// No explicit globs - should only apply to files in src/components/ directory
};
@@ -43,7 +43,7 @@ describe("Rule colocation glob matching", () => {
rule: "Use TypeScript with React components",
globs: "**/*.tsx", // Only .tsx files
source: "rules-block",
- ruleFile: "src/components/rules.md",
+ sourceFile: "src/components/rules.md",
// Should only apply to .tsx files in src/components/ directory
};
@@ -69,7 +69,7 @@ describe("Rule colocation glob matching", () => {
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
- ruleFile: "/path/to/repo/.continue/rules.md",
+ sourceFile: "/path/to/repo/.continue/rules.md",
// No restriction, should apply to all files
};
@@ -89,7 +89,7 @@ describe("Rule colocation glob matching", () => {
rule: "Follow these guidelines always",
alwaysApply: true,
source: "rules-block",
- ruleFile: "src/specific/rules.md",
+ sourceFile: "src/specific/rules.md",
// Should apply to all files regardless of directory
};
@@ -107,7 +107,7 @@ describe("Rule colocation glob matching", () => {
rule: "This rule should never apply",
alwaysApply: false,
source: "rules-block",
- ruleFile: "src/specific/rules.md",
+ sourceFile: "src/specific/rules.md",
// Should never apply since alwaysApply is false and there are no globs
};
@@ -121,7 +121,7 @@ describe("Rule colocation glob matching", () => {
rule: "Apply to TS files but not test files",
globs: ["**/*.ts", "!**/*.test.ts", "!**/*.spec.ts"],
source: "rules-block",
- ruleFile: "src/utils/rules.md",
+ sourceFile: "src/utils/rules.md",
// Should only apply to non-test TS files in src/utils/
};
@@ -147,7 +147,7 @@ describe("Rule policies", () => {
name: "Components Rule",
rule: "Use functional components with hooks",
source: "rules-block",
- ruleFile: "src/components/rules.md",
+ sourceFile: "src/components/rules.md",
};
const testFiles = ["src/components/Button.tsx"];
@@ -167,7 +167,7 @@ describe("Rule policies", () => {
rule: "This rule would normally always apply",
alwaysApply: true,
source: "rules-block",
- ruleFile: "src/components/rules.md",
+ sourceFile: "src/components/rules.md",
};
const offPolicies: RulePolicies = {
@@ -212,7 +212,7 @@ describe("Rule policies", () => {
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
- ruleFile: "/my/project/.continue/rules.md",
+ sourceFile: "/my/project/.continue/rules.md",
};
// Off policy should override even global rules
@@ -238,7 +238,7 @@ describe("Rule policies", () => {
alwaysApply: true,
globs: "**/*.ts",
source: "rules-block",
- ruleFile: "src/utils/rules.md",
+ sourceFile: "src/utils/rules.md",
};
// Off policy should win over everything
@@ -261,7 +261,7 @@ describe("Content pattern matching", () => {
rule: "Follow React component standards",
regex: "export (function|const) \\w+.*\\(",
source: "rules-block",
- ruleFile: "src/components/rules.md",
+ sourceFile: "src/components/rules.md",
};
// File that matches the pattern
@@ -293,7 +293,7 @@ describe("Content pattern matching", () => {
rule: "Apply to functions or classes",
regex: ["function\\s+\\w+", "class\\s+\\w+"],
source: "rules-block",
- ruleFile: "src/utils/rules.md",
+ sourceFile: "src/utils/rules.md",
};
const filePath = "src/utils/helper.ts";
@@ -332,7 +332,7 @@ describe("Content pattern matching", () => {
globs: "**/*.ts",
regex: "class\\s+\\w+",
source: "rules-block",
- ruleFile: "src/models/rules.md",
+ sourceFile: "src/models/rules.md",
};
const tsFilePath = "src/models/User.ts";
@@ -371,7 +371,7 @@ describe("Content pattern matching", () => {
rule: "Use arrow functions for better this binding",
regex: "const\\s+\\w+\\s*=\\s*\\(",
source: "rules-block",
- ruleFile: "src/utils/rules.md",
+ sourceFile: "src/utils/rules.md",
};
// Message with code block containing a matching pattern
@@ -433,7 +433,7 @@ describe("Content pattern matching", () => {
rule: "This rule has an invalid regex pattern",
regex: "([unclosed parenthesis",
source: "rules-block",
- ruleFile: "src/utils/rules.md",
+ sourceFile: "src/utils/rules.md",
};
const filePath = "src/utils/helper.ts";
@@ -454,7 +454,7 @@ describe("Content pattern matching", () => {
rule: "Apply only to model files with interfaces",
regex: "interface\\s+\\w+",
source: "rules-block",
- ruleFile: "src/models/rules.md",
+ sourceFile: "src/models/rules.md",
};
// File in the correct directory with matching content
diff --git a/core/llm/rules/implicitGlobalRules.vitest.ts b/core/llm/rules/implicitGlobalRules.vitest.ts
index 3d9d62004..baa13745f 100644
--- a/core/llm/rules/implicitGlobalRules.vitest.ts
+++ b/core/llm/rules/implicitGlobalRules.vitest.ts
@@ -8,7 +8,7 @@ describe("Implicit global rules application", () => {
name: "Implicit Global Rule",
rule: "This rule should be applied to all messages (implicit global)",
source: "rules-block",
- ruleFile: ".continue/global-rule.md",
+ sourceFile: ".continue/global-rule.md",
// No alwaysApply specified
// No globs specified
};
@@ -19,7 +19,7 @@ describe("Implicit global rules application", () => {
rule: "This rule should always be applied (explicit global)",
alwaysApply: true,
source: "rules-block",
- ruleFile: ".continue/explicit-global.md",
+ sourceFile: ".continue/explicit-global.md",
};
// Create a colocated rule in a nested directory
@@ -27,7 +27,7 @@ describe("Implicit global rules application", () => {
name: "Nested Directory Rule",
rule: "This rule applies to files in the nested directory",
source: "rules-block",
- ruleFile: "nested-folder/rules.md",
+ sourceFile: "nested-folder/rules.md",
};
it("should apply rules with no alwaysApply and no globs to all messages, even with no file references", () => {
@@ -63,7 +63,7 @@ describe("Implicit global rules application", () => {
name: "Root No Globs Rule",
rule: "This is a root-level rule with no globs",
source: "rules-block",
- ruleFile: ".continue/rules.md",
+ sourceFile: ".continue/rules.md",
// No alwaysApply, no globs
};
@@ -119,7 +119,7 @@ describe("Implicit global rules application", () => {
name: "Assistant Guidelines",
rule: "SOLID Design Principles - Coding Assistant Guidelines",
source: "rules-block",
- ruleFile: ".continue/rules.md",
+ sourceFile: ".continue/rules.md",
// No alwaysApply, no globs - should still apply
};
diff --git a/core/llm/rules/nestedDirectoryRules.vitest.ts b/core/llm/rules/nestedDirectoryRules.vitest.ts
index 7f55bc7c3..97f8f8238 100644
--- a/core/llm/rules/nestedDirectoryRules.vitest.ts
+++ b/core/llm/rules/nestedDirectoryRules.vitest.ts
@@ -13,7 +13,7 @@ describe("Nested directory rules application", () => {
name: "Nested Folder Rule",
rule: "HELLO WORLD THIS IS A RULE",
source: "rules-block",
- ruleFile: "manual-testing-sandbox/nested-folder/rules.md",
+ sourceFile: "manual-testing-sandbox/nested-folder/rules.md",
// No globs specified
};
@@ -22,7 +22,7 @@ describe("Nested directory rules application", () => {
name: "Global Rule",
rule: "SOLID Design Principles - Coding Agent Guidelines",
source: "rules-block",
- ruleFile: ".continue/rules.md",
+ sourceFile: ".continue/rules.md",
};
it("should apply nested directory rules to files in that directory", () => {
@@ -103,7 +103,7 @@ describe("Nested directory rules application", () => {
rule: "Follow Python best practices for src directory",
globs: "**/*.py", // This should only match .py files in src/ and subdirectories
source: "rules-block",
- ruleFile: "src/rules.md",
+ sourceFile: "src/rules.md",
};
// A rule in utils/ that targets *.py files
@@ -112,7 +112,7 @@ describe("Nested directory rules application", () => {
rule: "Follow Python best practices for utils directory",
globs: "**/*.py", // This should only match .py files in utils/ and subdirectories
source: "rules-block",
- ruleFile: "utils/rules.md",
+ sourceFile: "utils/rules.md",
};
// A file in src/
diff --git a/core/llm/rules/ruleColocation.vitest.ts b/core/llm/rules/ruleColocation.vitest.ts
index 6bee635b0..644bfb957 100644
--- a/core/llm/rules/ruleColocation.vitest.ts
+++ b/core/llm/rules/ruleColocation.vitest.ts
@@ -10,7 +10,7 @@ describe("Rule colocation - glob pattern matching", () => {
name: "General Rule",
rule: "Follow coding standards",
source: "colocated-markdown",
- ruleFile: "src/rules.md",
+ sourceFile: "src/rules.md",
},
// Redux-specific rule with specific directory/file type pattern
@@ -19,7 +19,7 @@ describe("Rule colocation - glob pattern matching", () => {
rule: "Use Redux Toolkit",
globs: "src/redux/**/*.{ts,tsx}",
source: "colocated-markdown",
- ruleFile: "src/redux/rules.md",
+ sourceFile: "src/redux/rules.md",
},
// Component-specific rule with array of globs
@@ -28,7 +28,7 @@ describe("Rule colocation - glob pattern matching", () => {
rule: "Use functional components",
globs: ["src/components/**/*.tsx", "src/components/**/*.jsx"],
source: "colocated-markdown",
- ruleFile: "src/components/rules.md",
+ sourceFile: "src/components/rules.md",
},
// Rule with explicit alwaysApply: true
@@ -38,7 +38,7 @@ describe("Rule colocation - glob pattern matching", () => {
alwaysApply: true,
globs: "src/specific/**/*.ts", // Should be ignored since alwaysApply is true
source: "colocated-markdown",
- ruleFile: ".continue/rules.md",
+ sourceFile: ".continue/rules.md",
},
// Rule with explicit alwaysApply: false
@@ -48,7 +48,7 @@ describe("Rule colocation - glob pattern matching", () => {
alwaysApply: false,
// No globs, so should never apply
source: "colocated-markdown",
- ruleFile: ".continue/rules.md",
+ sourceFile: ".continue/rules.md",
},
// Rule with explicit alwaysApply: false but with globs
@@ -58,7 +58,7 @@ describe("Rule colocation - glob pattern matching", () => {
alwaysApply: false,
globs: "src/utils/**/*.ts",
source: "colocated-markdown",
- ruleFile: "src/utils/rules.md",
+ sourceFile: "src/utils/rules.md",
},
};
@@ -128,7 +128,7 @@ describe("Rule colocation - glob pattern matching", () => {
// Fix: Specify the exact path prefix to restrict to this directory structure
globs: "src/features/auth/utils/**/*.ts",
source: "colocated-markdown",
- ruleFile: "src/features/auth/utils/rules.md",
+ sourceFile: "src/features/auth/utils/rules.md",
};
it("should apply nested rules to files in the same directory and subdirectories", () => {
@@ -158,7 +158,7 @@ describe("Rule colocation - glob pattern matching", () => {
// Testing with standard pattern instead
globs: "src/**/[!.]*.ts",
source: "colocated-markdown",
- ruleFile: "src/rules.md",
+ sourceFile: "src/rules.md",
};
it("should apply to matching files that are not excluded", () => {
@@ -175,7 +175,7 @@ describe("Rule colocation - glob pattern matching", () => {
globs: ["src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"],
alwaysApply: false,
source: "colocated-markdown",
- ruleFile: "src/rules.md",
+ sourceFile: "src/rules.md",
};
// Using alwaysApply:false with a more specific test
diff --git a/core/llm/rules/rules-utils.ts b/core/llm/rules/rules-utils.ts
new file mode 100644
index 000000000..41afc7cc0
--- /dev/null
+++ b/core/llm/rules/rules-utils.ts
@@ -0,0 +1,46 @@
+import { RuleWithSource } from "../..";
+import { getLastNPathParts } from "../../util/uri";
+
+export function getRuleDisplayName(rule: RuleWithSource): string {
+ if (rule.name) {
+ return rule.name;
+ }
+ return getRuleSourceDisplayName(rule);
+}
+
+export function getRuleSourceDisplayName(rule: RuleWithSource): string {
+ switch (rule.source) {
+ case ".continuerules":
+ return "Project rules";
+ case "default-chat":
+ return "Default chat system message";
+ case "default-plan":
+ return "Default plan mode system message";
+ case "default-agent":
+ return "Default agent system message";
+ case "json-systemMessage":
+ return "System Message (JSON)";
+ case "model-options-agent":
+ return "Base System Agent Message";
+ case "model-options-plan":
+ return "Base System Plan Message";
+ case "model-options-chat":
+ return "Base System Chat Message";
+ case "agent-file":
+ if (rule.sourceFile) {
+ return getLastNPathParts(rule.sourceFile, 2);
+ } else {
+ return "Agent file";
+ }
+ case "colocated-markdown":
+ if (rule.sourceFile) {
+ return getLastNPathParts(rule.sourceFile, 2);
+ } else {
+ return "rules.md";
+ }
+ case "rules-block":
+ return "Rules Block";
+ default:
+ return rule.source;
+ }
+}
diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts
index bef15522e..d1a0d4fe0 100644
--- a/core/llm/streamChat.ts
+++ b/core/llm/streamChat.ts
@@ -95,7 +95,7 @@ export async function* llmStreamChat(
...init,
signal: abortController.signal,
},
- config.requestOptions,
+ model.requestOptions,
),
completionOptions,
abortController,
diff --git a/core/llm/templates/edit/gpt.ts b/core/llm/templates/edit/gpt.ts
index 61d23a732..bafad3f3b 100644
--- a/core/llm/templates/edit/gpt.ts
+++ b/core/llm/templates/edit/gpt.ts
@@ -71,3 +71,10 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => {
return paragraphs.join("\n\n");
};
+
+export const defaultApplyPrompt: PromptTemplateFunction = (
+ history,
+ otherData,
+) => {
+ return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code.`;
+};
diff --git a/core/llm/toolSupport.test.ts b/core/llm/toolSupport.test.ts
index 71f70485f..ad883e4cb 100644
--- a/core/llm/toolSupport.test.ts
+++ b/core/llm/toolSupport.test.ts
@@ -41,7 +41,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
it("should return true for Gemini models", () => {
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-pro")).toBe(true);
- expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-1.5-pro")).toBe(
+ expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-2.5-pro")).toBe(
true,
);
});
@@ -139,7 +139,6 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
it("should return true for all Gemini models", () => {
expect(supportsFn("gemini-pro")).toBe(true);
- expect(supportsFn("gemini-1.5-pro")).toBe(true);
expect(supportsFn("gemini-ultra")).toBe(true);
});
@@ -150,7 +149,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
it("should handle case insensitivity", () => {
expect(supportsFn("GEMINI-pro")).toBe(true);
- expect(supportsFn("Gemini-1.5-Pro")).toBe(true);
+ expect(supportsFn("Gemini-2.5-Pro")).toBe(true);
});
});
@@ -280,6 +279,23 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
});
});
+ describe("xAI", () => {
+ const supportsFn = PROVIDER_TOOL_SUPPORT["xAI"];
+
+ it("should return true for Grok-3 models", () => {
+ expect(supportsFn("grok-3")).toBe(true);
+ expect(supportsFn("grok-3-mini")).toBe(true);
+ expect(supportsFn("grok-3-fast")).toBe(true);
+ });
+
+ it("should return true for Grok-4 models", () => {
+ expect(supportsFn("grok-4")).toBe(true);
+ expect(supportsFn("grok-4-fast-non-reasoning")).toBe(true);
+ expect(supportsFn("grok-4-fast-reasoning")).toBe(true);
+ expect(supportsFn("Grok-4-Fast")).toBe(true);
+ });
+ });
+
describe("novita", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["novita"];
diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts
index ed40733a5..7cdbd02cd 100644
--- a/core/llm/toolSupport.ts
+++ b/core/llm/toolSupport.ts
@@ -110,6 +110,10 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> =
}
return ["claude", "gemini"].some((val) => lowerCaseModel.includes(val));
},
+ xAI: (model) => {
+ const lowerCaseModel = model.toLowerCase();
+ return ["grok-3", "grok-4"].some((val) => lowerCaseModel.includes(val));
+ },
bedrock: (model) => {
if (
[
@@ -203,7 +207,9 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> =
if (
model.toLowerCase().startsWith("meta-llama-3") ||
model.toLowerCase().includes("llama-4") ||
- model.toLowerCase().includes("deepseek")
+ model.toLowerCase().includes("deepseek") ||
+ model.toLowerCase().includes("gpt") ||
+ model.toLowerCase().includes("qwen")
) {
return true;
}
@@ -374,9 +380,8 @@ export function isRecommendedAgentModel(modelName: string): boolean {
[/o[134]/],
[/deepseek/, /r1|reasoner/],
[/gemini/, /2\.5/, /pro/],
- [/gpt/, /4/],
[/gpt-5/],
- [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/],
+ [/claude/, /sonnet/, /3\.7|3-7|-4/],
[/claude/, /opus/, /-4/],
];
for (const combo of recs) {
diff --git a/core/llm/utils/getSecureID.test.ts b/core/llm/utils/getSecureID.test.ts
index a8d41a230..32404ce58 100644
--- a/core/llm/utils/getSecureID.test.ts
+++ b/core/llm/utils/getSecureID.test.ts
@@ -1,49 +1,47 @@
import { getSecureID } from "./getSecureID";
-// Mock the crypto.randomUUID function
-const mockRandomUUID = jest.fn();
-global.crypto = {
- ...global.crypto,
- randomUUID: mockRandomUUID,
-};
-
describe("getSecureID", () => {
beforeEach(() => {
// Reset the static property before each test
(getSecureID as any).uuid = undefined;
-
- // Reset the mock implementation
- mockRandomUUID.mockReset();
- // Setup a mock implementation that returns a fixed value for testing
- mockRandomUUID.mockReturnValue("test-uuid-1234");
});
test("should generate a UUID on first call", () => {
const result = getSecureID();
- expect(mockRandomUUID).toHaveBeenCalledTimes(1);
- expect(result).toBe("");
+
+ // Should return a properly formatted string with SID comment
+ expect(result).toMatch(
+ /^$/,
+ );
+
+ // Should have set the static uuid property
+ expect((getSecureID as any).uuid).toBeDefined();
+ expect(typeof (getSecureID as any).uuid).toBe("string");
});
test("should reuse the same UUID on subsequent calls", () => {
const firstResult = getSecureID();
const secondResult = getSecureID();
- // The UUID generation should only happen once
- expect(mockRandomUUID).toHaveBeenCalledTimes(1);
-
// Both results should be identical
expect(firstResult).toBe(secondResult);
- expect(firstResult).toBe("");
+
+ // Should match UUID format
+ expect(firstResult).toMatch(
+ /^$/,
+ );
});
test("should maintain the same UUID across different test cases if not reset", () => {
- // Don't reset the UUID here to test persistence
+ // Set a specific UUID to test persistence
(getSecureID as any).uuid = "persistent-uuid";
const result = getSecureID();
- // No new UUID should be generated
- expect(mockRandomUUID).not.toHaveBeenCalled();
+ // Should use the pre-existing UUID
expect(result).toBe("");
+
+ // The static property should remain unchanged
+ expect((getSecureID as any).uuid).toBe("persistent-uuid");
});
});
diff --git a/core/llm/utils/getSecureID.ts b/core/llm/utils/getSecureID.ts
index b05fefab6..33a092603 100644
--- a/core/llm/utils/getSecureID.ts
+++ b/core/llm/utils/getSecureID.ts
@@ -1,8 +1,10 @@
+import { v4 as uuidv4 } from "uuid";
+
// Utility function to get or generate UUID for LLM prompts
export function getSecureID(): string {
// Adding a type declaration for the static property
if (!(getSecureID as any).uuid) {
- (getSecureID as any).uuid = crypto.randomUUID();
+ (getSecureID as any).uuid = uuidv4();
}
return ``;
}
diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts
index ad6a1afa2..806be4873 100644
--- a/core/nextEdit/NextEditEditableRegionCalculator.ts
+++ b/core/nextEdit/NextEditEditableRegionCalculator.ts
@@ -13,6 +13,10 @@ export enum EditableRegionStrategy {
Static = "static",
}
+/**
+ * This was an attempt to find next edit locations deterministically.
+ * I was intending to use this in tandem with the prefetching logic, but we are not using it anymore.
+ */
export async function getNextEditableRegion(
strategy: EditableRegionStrategy,
ctx: any,
diff --git a/core/nextEdit/NextEditLoggingService.ts b/core/nextEdit/NextEditLoggingService.ts
index 4ed9ed4e9..6d003e5d9 100644
--- a/core/nextEdit/NextEditLoggingService.ts
+++ b/core/nextEdit/NextEditLoggingService.ts
@@ -1,5 +1,7 @@
import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters";
+import { fetchwithRequestOptions } from "@continuedev/fetch";
+import { getControlPlaneEnvSync } from "../control-plane/env";
import { DataLogger } from "../data/log";
import { Telemetry } from "../util/posthog";
import { NextEditOutcome } from "./types";
@@ -93,6 +95,9 @@ export class NextEditLoggingService {
outcome.accepted = true;
outcome.aborted = false;
this.logNextEditOutcome(outcome);
+ if (outcome.requestId) {
+ void this.logAcceptReject(outcome.requestId, true);
+ }
this._outcomes.delete(completionId);
return outcome;
}
@@ -111,6 +116,9 @@ export class NextEditLoggingService {
outcome.accepted = false;
outcome.aborted = false;
this.logNextEditOutcome(outcome);
+ if (outcome.requestId) {
+ void this.logAcceptReject(outcome.requestId, false);
+ }
this._outcomes.delete(completionId);
return outcome;
}
@@ -121,6 +129,7 @@ export class NextEditLoggingService {
clearTimeout(this._logRejectionTimeouts.get(completionId)!);
this._logRejectionTimeouts.delete(completionId);
}
+
if (this._outcomes.has(completionId)) {
this._outcomes.delete(completionId);
}
@@ -142,6 +151,9 @@ export class NextEditLoggingService {
outcome.accepted = false;
outcome.aborted = false;
this.logNextEditOutcome(outcome);
+ if (outcome.requestId) {
+ void this.logAcceptReject(outcome.requestId, false);
+ }
this._logRejectionTimeouts.delete(completionId);
this._outcomes.delete(completionId);
}, COUNT_COMPLETION_REJECTED_AFTER);
@@ -245,4 +257,30 @@ export class NextEditLoggingService {
// const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
void Telemetry.capture("nextEditOutcome", outcome, true);
}
+
+ private async logAcceptReject(
+ requestId: string,
+ accepted: boolean,
+ ): Promise {
+ try {
+ if (!Telemetry.client) {
+ return;
+ }
+
+ const controlPlaneEnv = getControlPlaneEnvSync("production");
+ await fetchwithRequestOptions(
+ new URL("model-proxy/v1/feedback", controlPlaneEnv.CONTROL_PLANE_URL),
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ requestId,
+ accepted,
+ }),
+ },
+ );
+ } catch (error) {}
+ }
}
diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts
index 9037f218f..ad35db3b9 100644
--- a/core/nextEdit/NextEditPrefetchQueue.ts
+++ b/core/nextEdit/NextEditPrefetchQueue.ts
@@ -10,6 +10,11 @@ export interface ProcessedItem {
/**
* Keeps a queue of the broken down diffs from a changed editable range, as determined in core/nextEdit/diff.ts
*/
+/**
+ * This is where the chain is stored. Think of it as a regular queue, but being a singleton because we need one source of truth for the chain.
+ * I originally intended this to be a separate data structure to handle prefetching next edit outcomes from the model in the background.
+ * Due to subpar results, lack of satisfactory next edit location suggestion algorithms and token cost/latency issues, I scratched the idea.
+ */
export class PrefetchQueue {
private static instance: PrefetchQueue | null = null;
diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts
index 3d0f5350f..4d9216914 100644
--- a/core/nextEdit/NextEditProvider.ts
+++ b/core/nextEdit/NextEditProvider.ts
@@ -19,7 +19,6 @@ import { HelperVars } from "../autocomplete/util/HelperVars.js";
import { AutocompleteInput } from "../autocomplete/util/types.js";
import { isSecurityConcern } from "../indexing/ignore.js";
import { modelSupportsNextEdit } from "../llm/autodetect.js";
-import { countTokens } from "../llm/countTokens.js";
import { localPathOrUriToPath } from "../util/pathToUri.js";
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
@@ -45,6 +44,14 @@ const ERRORS_TO_IGNORE = [
"operation was aborted",
];
+/**
+ * This is the next edit analogue to autocomplete's CompletionProvider.
+ * You will see a lot of similar if not identical methods to CompletionProvider methods.
+ * All logic used to live inside this class, but that became untenable quickly.
+ * I moved a lot of the model-specific logic (prompt building, pre/post processing, etc.) to the BaseNextEditProvider and the children inheriting from it.
+ * Keeping this class around might be a good idea because it handles lots of delicate logic such as abort signals, chains, logging, etc.
+ * There being a singleton also gives a lot of guarantees about the state of the next edit state machine.
+ */
export class NextEditProvider {
private static instance: NextEditProvider | null = null;
@@ -62,7 +69,6 @@ export class NextEditProvider {
private currentEditChainId: string | null = null;
private previousRequest: AutocompleteInput | null = null;
private previousCompletions: NextEditOutcome[] = [];
- // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
// Model-specific provider instance.
private modelProvider: BaseNextEditModelProvider | null = null;
@@ -223,14 +229,14 @@ export class NextEditProvider {
this.currentEditChainId = null;
this.previousCompletions = [];
- // TODO: this should be cleaned up in the prefetch queue.
- // this.nextEditableRegionsInTheCurrentChain = [];
if (this.previousRequest) {
const fileContent = (
await this.ide.readFile(this.previousRequest.filepath)
).toString();
+
const ast = await getAst(this.previousRequest.filepath, fileContent);
+
if (ast) {
DocumentHistoryTracker.getInstance().push(
localPathOrUriToPath(this.previousRequest.filepath),
@@ -253,6 +259,9 @@ export class NextEditProvider {
return this.previousCompletions.length === 1;
}
+ /**
+ * This is the main entry point to this class.
+ */
public async provideInlineCompletionItems(
input: AutocompleteInput,
token: AbortSignal | undefined,
@@ -370,6 +379,8 @@ export class NextEditProvider {
throw new Error("Model provider not initialized");
}
+ // NOTE: getAllSnippetsWithoutRace doesn't seem to incur much performance penalties when compared to getAllSnippets.
+ // Use getAllSnippets if snippet gathering becomes noticably slow.
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippetsWithoutRace({
helper,
@@ -445,6 +456,9 @@ export class NextEditProvider {
}
// Send prompts to LLM (using only user prompt for fine-tuned models).
+ // prompts[1] extracts the user prompt from the system-user prompt pair.
+ // NOTE: Stream is currently set to false, but this should ideally be a per-model flag.
+ // Mercury Coder currently does not support streaming.
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
stream: false,
});
@@ -484,7 +498,7 @@ export class NextEditProvider {
}
if (outcome) {
- // Handle NextEditProvider-specific state
+ // Handle NextEditProvider-specific state.
this.previousCompletions.push(outcome);
// Mark as displayed for JetBrains
@@ -494,97 +508,6 @@ export class NextEditProvider {
return outcome;
}
- private _calculateOptimalEditableRegion(
- helper: HelperVars,
- heuristic: "fourChars" | "tokenizer" = "tokenizer",
- ): {
- editableRegionStartLine: number;
- editableRegionEndLine: number;
- } {
- const cursorLine = helper.pos.line;
- const fileLines = helper.fileLines;
- const MAX_TOKENS = 512;
-
- // Initialize with cursor line.
- let editableRegionStartLine = cursorLine;
- let editableRegionEndLine = cursorLine;
-
- // Get initial content and token count.
- let currentContent = fileLines[cursorLine];
- let totalTokens =
- heuristic === "tokenizer"
- ? countTokens(currentContent, helper.modelName)
- : Math.ceil(currentContent.length / 4);
-
- // Expand outward alternating between adding lines above and below.
- let addingAbove = true;
-
- while (totalTokens < MAX_TOKENS) {
- let addedLine = false;
-
- if (addingAbove) {
- // Try to add a line above.
- if (editableRegionStartLine > 0) {
- editableRegionStartLine--;
- const lineContent = fileLines[editableRegionStartLine];
- const lineTokens =
- heuristic === "tokenizer"
- ? countTokens(lineContent, helper.modelName)
- : Math.ceil(lineContent.length / 4);
-
- totalTokens += lineTokens;
- addedLine = true;
- }
- } else {
- // Try to add a line below.
- if (editableRegionEndLine < fileLines.length - 1) {
- editableRegionEndLine++;
- const lineContent = fileLines[editableRegionEndLine];
- const lineTokens =
- heuristic === "tokenizer"
- ? countTokens(lineContent, helper.modelName)
- : Math.ceil(lineContent.length / 4);
-
- totalTokens += lineTokens;
- addedLine = true;
- }
- }
-
- // If we can't add in the current direction, try the other.
- if (!addedLine) {
- // If we're already at both file boundaries, we're done.
- if (
- editableRegionStartLine === 0 &&
- editableRegionEndLine === fileLines.length - 1
- ) {
- break;
- }
-
- // If we couldn't add in one direction, force the next attempt in the other direction.
- addingAbove = !addingAbove;
- continue;
- }
-
- // If we exceeded the token limit, revert the last addition.
- if (totalTokens > MAX_TOKENS) {
- if (addingAbove) {
- editableRegionStartLine++;
- } else {
- editableRegionEndLine--;
- }
- break;
- }
-
- // Alternate between adding above and below for balanced context.
- addingAbove = !addingAbove;
- }
-
- return {
- editableRegionStartLine,
- editableRegionEndLine,
- };
- }
-
private async _markDisplayedIfJetBrains(
completionId: string,
outcome: NextEditOutcome,
@@ -595,6 +518,12 @@ export class NextEditProvider {
}
}
+ /**
+ * This is a wrapper around provideInlineCompletionItems.
+ * This is invoked when we call the model in the background using prefetch.
+ * It's not currently used anywhere (references are not used either), but I decided to keep it in case we actually need to use prefetch.
+ * You will see that calls to this method is made from NextEditPrefetchQueue.proecss(), which is wrapped in `if (!this.usingFullFileDiff)`.
+ */
public async provideInlineCompletionItemsWithChain(
ctx: {
completionId: string;
diff --git a/core/nextEdit/NextEditProvider.vitest.ts b/core/nextEdit/NextEditProvider.vitest.ts
deleted file mode 100644
index a86cc8a34..000000000
--- a/core/nextEdit/NextEditProvider.vitest.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
-import { HelperVars } from "../autocomplete/util/HelperVars.js";
-import { ConfigHandler } from "../config/ConfigHandler.js";
-import { IDE, ILLM } from "../index.js";
-import { NextEditProvider } from "./NextEditProvider.js";
-
-// Mock the countTokens function
-vi.mock("../llm/countTokens.js", () => ({
- countTokens: (text: string) => {
- // Simple mock that counts 1 token per character for predictable tests
- return text.length;
- },
-}));
-
-// Create a helper function to set up the test context
-function createMockHelper(
- fileContents: string,
- cursorLine: number,
-): HelperVars {
- const fileLines = fileContents.split("\n");
-
- return {
- fileLines,
- fileContents,
- pos: { line: cursorLine, character: 0 },
- modelName: "gpt-4",
- lang: { name: "typescript" },
- filepath: "test/file.ts",
- workspaceUris: ["test/workspace"],
- options: {},
- input: { completionId: "test-completion-id" },
- } as unknown as HelperVars;
-}
-
-// TODO: Add more tests for other methods.
-describe("_calculateOptimalEditableRegion", () => {
- let nextEditProvider: NextEditProvider;
- let mockConfigHandler: ConfigHandler;
- let mockIde: IDE;
- let mockGetLlm: () => Promise;
- let mockOnError: (e: any) => void;
- let mockGetDefinitionsFromLsp: GetLspDefinitionsFunction;
-
- beforeEach(() => {
- // Create comprehensive mocks for all dependencies
- mockConfigHandler = {
- loadConfig: vi.fn().mockResolvedValue({ config: {} }),
- } as unknown as ConfigHandler;
-
- mockIde = {
- readFile: vi.fn().mockResolvedValue(""),
- getWorkspaceDirs: vi.fn().mockResolvedValue([]),
- getRepoName: vi.fn().mockResolvedValue("test-repo"),
- getUniqueId: vi.fn().mockResolvedValue("test-id"),
- getIdeInfo: vi.fn().mockResolvedValue({ ideType: "vscode" }),
- onDidChangeActiveTextEditor: vi.fn().mockImplementation((callback) => {
- // Return a disposable object that does nothing when disposed
- return {
- dispose: () => {},
- };
- }),
- } as unknown as IDE;
-
- mockGetLlm = vi.fn().mockResolvedValue({
- model: "gpt-4",
- providerName: "openai",
- underlyingProviderName: "openai",
- completionOptions: {},
- chat: vi.fn(),
- });
-
- mockOnError = vi.fn();
- mockGetDefinitionsFromLsp = vi.fn();
-
- // Initialize NextEditProvider with mocked dependencies
- nextEditProvider = NextEditProvider.initialize(
- mockConfigHandler,
- mockIde,
- mockGetLlm,
- mockOnError,
- mockGetDefinitionsFromLsp,
- "default",
- );
-
- // Expose the private method for testing
- // This is a bit of a hack, but necessary for testing private methods
- (nextEditProvider as any)._calculateOptimalEditableRegion = (
- NextEditProvider.prototype as any
- )._calculateOptimalEditableRegion.bind(nextEditProvider);
- });
-
- // Test cases remain the same as before...
- it("should include only the cursor line when it already exceeds token limit", () => {
- // Create a mock helper with a very long cursor line (>500 characters)
- const longLine = "X".repeat(600);
- const helper = createMockHelper(longLine, 0);
-
- //@ts-ignore
- const result = nextEditProvider._calculateOptimalEditableRegion(
- helper,
- "tokenizer",
- );
-
- expect(result.editableRegionStartLine).toBe(0);
- expect(result.editableRegionEndLine).toBe(0);
- });
-
- it("should expand symmetrically when possible", () => {
- // Create content with identical lines and cursor in the middle
- const lines = Array(11).fill("A".repeat(40)).join("\n"); // 11 lines of 40 chars each
- const helper = createMockHelper(lines, 5); // Cursor in the middle (line 5)
-
- //@ts-ignore
- const result = nextEditProvider._calculateOptimalEditableRegion(
- helper,
- "tokenizer",
- );
-
- // Should expand 5 lines in each direction (total 11 lines) for symmetry
- expect(result.editableRegionStartLine).toBe(0);
- expect(result.editableRegionEndLine).toBe(10);
- });
-
- it("should expand asymmetrically when hitting a file boundary", () => {
- // Create content with cursor near the top
- const lines = Array(20).fill("B".repeat(20)).join("\n"); // 20 lines of 20 chars each
- const helper = createMockHelper(lines, 1); // Cursor near the top (line 1)
-
- //@ts-ignore
- const result = nextEditProvider._calculateOptimalEditableRegion(
- helper,
- "tokenizer",
- );
-
- // Should include more lines below since it can't expand much above
- expect(result.editableRegionStartLine).toBe(0);
- // Should include many more lines below to reach token limit
- expect(result.editableRegionEndLine).toBeGreaterThan(10);
- });
-
- it("should handle files with varying line lengths", () => {
- // Create content with varying line lengths
- const fileContents = [
- "Short line", // 10 chars
- "A".repeat(100), // 100 chars
- "Medium length line here", // 24 chars
- "B".repeat(200), // 200 chars
- "Another typical line of code", // 28 chars
- ].join("\n");
-
- const helper = createMockHelper(fileContents, 2); // Cursor on the medium line
-
- //@ts-ignore
- const result = nextEditProvider._calculateOptimalEditableRegion(
- helper,
- "tokenizer",
- );
-
- // Should include all lines since total tokens < 500
- expect(result.editableRegionStartLine).toBe(0);
- expect(result.editableRegionEndLine).toBe(4);
- });
-
- it("should respect the token limit and not include too many lines", () => {
- // Create content with many small lines (10 chars each)
- const lines = Array(600).fill("C".repeat(10)).join("\n");
- const helper = createMockHelper(lines, 300); // Cursor in the middle
-
- //@ts-ignore
- const result = nextEditProvider._calculateOptimalEditableRegion(
- helper,
- "tokenizer",
- );
-
- // Each line is 10 chars = 10 tokens per line with our mock.
- // So with 500 token limit, we should get 50 lines total.
- // 25 above, 25 below, +1 current
- const totalLines =
- result.editableRegionEndLine - result.editableRegionStartLine + 1;
- expect(totalLines).toBe(51); // Not more than 51 lines (25 above, 25 below, +1 for current line)
- });
-
- it("should use character approximation when using fourChars heuristic", () => {
- // In this test, we're setting up a situation where tiktoken and fourChars would give different results
- // Creating 5 lines, each 100 characters
- const lines = Array(10).fill("D".repeat(100)).join("\n");
- const helper = createMockHelper(lines, 2); // Cursor in the middle
-
- // Mock for tiktoken counting (1 char = 1 token)
- //@ts-ignore
- const tokenizerResult = nextEditProvider._calculateOptimalEditableRegion(
- helper,
- "tokenizer",
- );
-
- // Mock for fourChars counting (1 token = 4 chars)
- // This should include more lines since each line is counted as 25 tokens instead of 100
- //@ts-ignore
- const fourCharsResult = nextEditProvider._calculateOptimalEditableRegion(
- helper,
- "fourChars",
- );
-
- // The fourChars approach should include more lines since it estimates fewer tokens per line
- expect(
- fourCharsResult.editableRegionEndLine -
- fourCharsResult.editableRegionStartLine,
- ).toBeGreaterThan(
- tokenizerResult.editableRegionEndLine -
- tokenizerResult.editableRegionStartLine,
- );
- });
-
- it("should include the entire file if it's within token limit", () => {
- // Create a small file
- const smallFile = "Small file\nwith just\na few lines\nof text";
- const helper = createMockHelper(smallFile, 1);
-
- //@ts-ignore
- const result = nextEditProvider._calculateOptimalEditableRegion(
- helper,
- "tokenizer",
- );
-
- // Should include all lines
- expect(result.editableRegionStartLine).toBe(0);
- expect(result.editableRegionEndLine).toBe(3);
- });
-
- it("should prioritize balanced context when token limit allows", () => {
- // Create content with alternating long and short lines
- const fileContents = [
- "Short", // 5 chars
- "E".repeat(80), // 80 chars
- "Also short", // 10 chars
- "F".repeat(80), // 80 chars
- "Another short one", // 17 chars
- "G".repeat(80), // 80 chars
- "Final short line", // 16 chars
- ].join("\n");
-
- const helper = createMockHelper(fileContents, 3); // Cursor on the long line (index 3)
-
- //@ts-ignore
- const result = nextEditProvider._calculateOptimalEditableRegion(
- helper,
- "tokenizer",
- );
-
- // Should try to include equal number of lines above and below cursor
- const linesAbove = result.editableRegionStartLine;
- const linesBelow =
- helper.fileLines.length - 1 - result.editableRegionEndLine;
-
- // Difference between lines above and below should be minimal
- expect(Math.abs(linesAbove - linesBelow)).toBeLessThanOrEqual(1);
- });
-});
diff --git a/core/nextEdit/providers/BaseNextEditProvider.ts b/core/nextEdit/providers/BaseNextEditProvider.ts
index af8f77026..4eb601fd9 100644
--- a/core/nextEdit/providers/BaseNextEditProvider.ts
+++ b/core/nextEdit/providers/BaseNextEditProvider.ts
@@ -19,6 +19,11 @@ import {
} from "../types.js";
import { isWhitespaceOnlyDeletion } from "../utils.js";
+/**
+ * This class is used as an abstract base class for model-specific providers.
+ * This and its children are responsible for pre/post processing of prompts and outcomes.
+ * Different next edit models have very different requirements.
+ */
export abstract class BaseNextEditModelProvider {
protected readonly modelName: string;
@@ -304,6 +309,7 @@ export abstract class BaseNextEditModelProvider {
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath),
uniqueId: await outcomeCtx.ide.getUniqueId(),
+ requestId: outcomeCtx.llm.lastRequestId,
timestamp: Date.now(),
fileUri: outcomeCtx.helper.filepath,
workspaceDirUri:
diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts
index 8d08f8216..2e6c8d40b 100644
--- a/core/nextEdit/types.ts
+++ b/core/nextEdit/types.ts
@@ -50,6 +50,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions {
completionId: string;
gitRepo?: string;
uniqueId: string;
+ requestId?: string;
timestamp: number;
// New for Next Edit.
diff --git a/core/package-lock.json b/core/package-lock.json
index 974a50300..1c830c623 100644
--- a/core/package-lock.json
+++ b/core/package-lock.json
@@ -9,6 +9,7 @@
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
+ "@anthropic-ai/sdk": "^0.62.0",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
"@aws-sdk/credential-providers": "^3.778.0",
@@ -17,6 +18,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
+ "@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@@ -67,6 +69,7 @@
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",
"request": "^2.88.2",
+ "shell-quote": "^1.8.3",
"socket.io-client": "^4.7.3",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
@@ -101,6 +104,7 @@
"@types/pg": "^8.11.6",
"@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
+ "@types/shell-quote": "^1.7.5",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
@@ -149,10 +153,10 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
- "version": "1.0.96",
+ "version": "1.23.0",
"license": "Apache-2.0",
"dependencies": {
- "@continuedev/config-types": "file:../config-types",
+ "@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},
@@ -176,40 +180,51 @@
},
"../packages/fetch": {
"name": "@continuedev/fetch",
- "version": "1.0.16",
+ "version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
- "@continuedev/config-types": "file:../config-types",
+ "@continuedev/config-types": "^1.0.14",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"node-fetch": "^3.3.2"
},
"devDependencies": {
+ "@semantic-release/changelog": "^6.0.3",
+ "@semantic-release/git": "^10.0.1",
+ "@semantic-release/github": "^9.2.6",
+ "@semantic-release/npm": "^10.0.6",
"@types/follow-redirects": "^1.14.4",
+ "semantic-release": "^21.1.2",
"typescript": "^5.0.0",
"vitest": "^3.2.0"
}
},
"../packages/llm-info": {
"name": "@continuedev/llm-info",
- "version": "1.0.9",
+ "version": "1.0.10",
"license": "Apache-2.0",
"devDependencies": {
+ "@semantic-release/changelog": "^6.0.3",
+ "@semantic-release/git": "^10.0.1",
+ "@semantic-release/github": "^9.2.6",
+ "@semantic-release/npm": "^10.0.6",
"@types/node": "^22.15.29",
+ "semantic-release": "^21.1.2",
"typescript": "^5.5.2"
}
},
"../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
- "version": "1.5.1",
+ "version": "1.15.0",
"license": "Apache-2.0",
"dependencies": {
+ "@anthropic-ai/sdk": "^0.62.0",
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.14",
- "@continuedev/config-yaml": "^1.8.0",
- "@continuedev/fetch": "^1.0.16",
+ "@continuedev/config-yaml": "^1.14.0",
+ "@continuedev/fetch": "^1.1.0",
"dotenv": "^16.5.0",
"google-auth-library": "^10.1.0",
"json-schema": "^0.4.0",
@@ -236,6 +251,20 @@
"vitest": "^3.2.4"
}
},
+ "../packages/terminal-security": {
+ "name": "@continuedev/terminal-security",
+ "version": "1.0.0",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "shell-quote": "^1.8.1"
+ },
+ "devDependencies": {
+ "@types/node": "^20.11.19",
+ "@types/shell-quote": "^1.7.5",
+ "typescript": "^5.5.2",
+ "vitest": "^3.2.4"
+ }
+ },
"node_modules/@75lb/deep-merge": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz",
@@ -270,6 +299,15 @@
"node": ">=6.0.0"
}
},
+ "node_modules/@anthropic-ai/sdk": {
+ "version": "0.62.0",
+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.62.0.tgz",
+ "integrity": "sha512-gT2VFKX0gSp7KJNlav/vzRFjJOPYDZxCJRx7MYUc+fqURc5aS6OI/UJeD2KytJkjsIWv0OOwH1ePc1S5QE2GZw==",
+ "license": "MIT",
+ "bin": {
+ "anthropic-ai-sdk": "bin/cli"
+ }
+ },
"node_modules/@apache-arrow/ts": {
"version": "14.0.2",
"resolved": "https://registry.npmjs.org/@apache-arrow/ts/-/ts-14.0.2.tgz",
@@ -2955,6 +2993,10 @@
"resolved": "../packages/openai-adapters",
"link": true
},
+ "node_modules/@continuedev/terminal-security": {
+ "resolved": "../packages/terminal-security",
+ "link": true
+ },
"node_modules/@dabh/diagnostics": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz",
@@ -6892,6 +6934,13 @@
"node": ">= 0.12"
}
},
+ "node_modules/@types/shell-quote": {
+ "version": "1.7.5",
+ "resolved": "https://registry.npmjs.org/@types/shell-quote/-/shell-quote-1.7.5.tgz",
+ "integrity": "sha512-+UE8GAGRPbJVQDdxi16dgadcBfQ+KG2vgZhV1+3A1XmHbmwcdwhCUwIdy+d3pAGrbvgRoVSjeI9vOWyq376Yzw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/shimmer": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz",
@@ -7875,13 +7924,13 @@
"integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw=="
},
"node_modules/axios": {
- "version": "1.8.2",
- "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz",
- "integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==",
+ "version": "1.12.0",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.12.0.tgz",
+ "integrity": "sha512-oXTDccv8PcfjZmPGlWsPSwtOJCZ/b6W5jAMCNcfwJbCzDckwG0jrYJFaWH1yvivfCXjVzV/SPDEhMB3Q+DSurg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
- "form-data": "^4.0.0",
+ "form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},
@@ -9894,14 +9943,15 @@
}
},
"node_modules/es-set-tostringtag": {
- "version": "2.0.3",
- "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz",
- "integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==",
- "peer": true,
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "license": "MIT",
"dependencies": {
- "get-intrinsic": "^1.2.4",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
- "hasown": "^2.0.1"
+ "hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
@@ -11298,12 +11348,15 @@
}
},
"node_modules/form-data": {
- "version": "4.0.1",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz",
- "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==",
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
+ "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
+ "license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
@@ -11952,7 +12005,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
- "peer": true,
"dependencies": {
"has-symbols": "^1.0.3"
},
@@ -16312,9 +16364,9 @@
}
},
"node_modules/prebuild-install/node_modules/tar-fs": {
- "version": "2.1.3",
- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.3.tgz",
- "integrity": "sha512-090nwYJDmlhwFwEW3QQl+vaNnxsO2yVsd45eTKRBzSzu+hlb1w2K9inVq5b0ngXuLVqQ4ApvsUHHnu/zQNkWAg==",
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
+ "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",
"license": "MIT",
"dependencies": {
"chownr": "^1.1.1",
@@ -17459,6 +17511,18 @@
"node": ">=8"
}
},
+ "node_modules/shell-quote": {
+ "version": "1.8.3",
+ "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
+ "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/shiki": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/shiki/-/shiki-3.7.0.tgz",
@@ -18259,9 +18323,9 @@
}
},
"node_modules/tar-fs": {
- "version": "3.0.9",
- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.9.tgz",
- "integrity": "sha512-XF4w9Xp+ZQgifKakjZYmFdkLoSWd34VGKcsTCwlNWM7QG3ZbaxnTsaBwnjFZqHRf/rROxaR8rXnbtwdvaDI+lA==",
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.1.tgz",
+ "integrity": "sha512-LZA0oaPOc2fVo82Txf3gw+AkEd38szODlptMYejQUhndHMLQ9M059uXR+AfS7DNo0NpINvSqDsvyaCrBVkptWg==",
"license": "MIT",
"dependencies": {
"pump": "^3.0.0",
@@ -19311,9 +19375,9 @@
}
},
"node_modules/vite": {
- "version": "6.3.5",
- "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz",
- "integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
+ "version": "6.3.6",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.6.tgz",
+ "integrity": "sha512-0msEVHJEScQbhkbVTb/4iHZdJ6SXp/AvxL2sjwYQFfBqleHtnCqv1J3sa9zbWz/6kW1m9Tfzn92vW+kZ1WV6QA==",
"dev": true,
"license": "MIT",
"dependencies": {
diff --git a/core/package.json b/core/package.json
index c7ca9158d..f20ba384b 100644
--- a/core/package.json
+++ b/core/package.json
@@ -34,6 +34,7 @@
"@types/pg": "^8.11.6",
"@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
+ "@types/shell-quote": "^1.7.5",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
@@ -53,6 +54,7 @@
"vitest": "^3.1.4"
},
"dependencies": {
+ "@anthropic-ai/sdk": "^0.62.0",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
"@aws-sdk/credential-providers": "^3.778.0",
@@ -61,6 +63,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
+ "@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@@ -111,6 +114,7 @@
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",
"request": "^2.88.2",
+ "shell-quote": "^1.8.3",
"socket.io-client": "^4.7.3",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/getPromptFiles.ts
index 8ca4f1966..59c0151d4 100644
--- a/core/promptFiles/getPromptFiles.ts
+++ b/core/promptFiles/getPromptFiles.ts
@@ -4,81 +4,6 @@ import { walkDir } from "../indexing/walkDir";
import { readAllGlobalPromptFiles } from "../util/paths";
import { joinPathsToUri } from "../util/uri";
-// The hardcoded init prompt content
-const INIT_PROMPT_CONTENT = `name: Init
-description: Initialize Codebase
----
-You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project.
-
-## Step 1: Check Required Tools
-First, verify that you have access to the necessary tools:
-- builtin_file_glob_search: To discover project files
-- builtin_read_file: To analyze file contents
-- builtin_ls: To explore directory structure
-- builtin_create_new_file: To generate the CONTINUE.md file
-
-If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding.
-
-## Step 2: Project Analysis
-Analyze the project structure and key files to understand:
-- The programming languages and frameworks used
-- The overall architecture and organization
-- Key components and their responsibilities
-- Important configuration files
-- Build/deployment system
-
-## Step 3: Generate CONTINUE.md
-Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections:
-
-1. **Project Overview**
- - Brief description of the project's purpose
- - Key technologies used
- - High-level architecture
-
-2. **Getting Started**
- - Prerequisites (required software, dependencies)
- - Installation instructions
- - Basic usage examples
- - Running tests
-
-3. **Project Structure**
- - Overview of main directories and their purpose
- - Key files and their roles
- - Important configuration files
-
-4. **Development Workflow**
- - Coding standards or conventions
- - Testing approach
- - Build and deployment process
- - Contribution guidelines
-
-5. **Key Concepts**
- - Domain-specific terminology
- - Core abstractions
- - Design patterns used
-
-6. **Common Tasks**
- - Step-by-step guides for frequent development tasks
- - Examples of common operations
-
-7. **Troubleshooting**
- - Common issues and their solutions
- - Debugging tips
-
-8. **References**
- - Links to relevant documentation
- - Important resources
-
-Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification.
-
-## Step 4: Finalize
-After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to:
-1. Review and edit the file as needed
-2. Commit it to their repository to share with their team
-3. Explain that Continue will automatically load this file into context when working with the project
-
-Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`;
-
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
export async function getPromptFilesFromDir(
@@ -131,20 +56,11 @@ export async function getAllPromptFiles(
await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir)))
).flat();
- // Also read from ~/.continue/.prompts
+ // Also read from ~/.continue/prompts
promptFiles.push(...readAllGlobalPromptFiles());
- // Add hardcoded init prompt
- promptFiles.push({
- path: "builtin:/init.prompt",
- content: INIT_PROMPT_CONTENT,
- });
-
return await Promise.all(
promptFiles.map(async (file) => {
- if (file.path.startsWith("builtin:")) {
- return file;
- }
const content = await ide.readFile(file.path);
return { path: file.path, content };
}),
diff --git a/core/promptFiles/initPrompt.ts b/core/promptFiles/initPrompt.ts
new file mode 100644
index 000000000..f436d6e43
--- /dev/null
+++ b/core/promptFiles/initPrompt.ts
@@ -0,0 +1,86 @@
+import { SlashCommandWithSource } from "..";
+import { RULES_MARKDOWN_FILENAME } from "../llm/rules/constants";
+import { BuiltInToolNames } from "../tools/builtIn";
+
+const initFilename = "CONTINUE.md";
+
+// Prompt for init slash command
+export const INIT_PROMPT_CONTENT = `
+You are an expert development assistant. Your task is to create a comprehensive ${initFilename} project guide for the user's codebase to help them and their team better understand and work with the project.
+
+## Step 1: Check Required Tools
+First, verify that you have access to the necessary tools:
+- ${BuiltInToolNames.FileGlobSearch}: To discover project files
+- ${BuiltInToolNames.ReadFile}: To analyze file contents
+- ${BuiltInToolNames.LSTool}: To explore directory structure
+- ${BuiltInToolNames.CreateNewFile}: To generate the ${initFilename} file
+
+If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding.
+
+## Step 2: Project Analysis
+Analyze the project structure and key files to understand:
+- The programming languages and frameworks used
+- The overall architecture and organization
+- Key components and their responsibilities
+- Important configuration files
+- Build/deployment system
+
+## Step 3: Generate ${initFilename}
+Create a comprehensive ${initFilename} file in the .continue/rules/ directory with the following sections:
+
+1. **Project Overview**
+ - Brief description of the project's purpose
+ - Key technologies used
+ - High-level architecture
+
+2. **Getting Started**
+ - Prerequisites (required software, dependencies)
+ - Installation instructions
+ - Basic usage examples
+ - Running tests
+
+3. **Project Structure**
+ - Overview of main directories and their purpose
+ - Key files and their roles
+ - Important configuration files
+
+4. **Development Workflow**
+ - Coding standards or conventions
+ - Testing approach
+ - Build and deployment process
+ - Contribution guidelines
+
+5. **Key Concepts**
+ - Domain-specific terminology
+ - Core abstractions
+ - Design patterns used
+
+6. **Common Tasks**
+ - Step-by-step guides for frequent development tasks
+ - Examples of common operations
+
+7. **Troubleshooting**
+ - Common issues and their solutions
+ - Debugging tips
+
+8. **References**
+ - Links to relevant documentation
+ - Important resources
+
+Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification.
+
+## Step 4: Finalize
+After creating the .continue/rules/${initFilename} file, provide a summary of what you've created and remind the user to:
+1. Review and edit the file as needed
+2. Commit it to their repository to share with their team
+3. Explain that Continue will automatically load this file into context when working with the project
+
+Also inform the user that they can create additional ${RULES_MARKDOWN_FILENAME} files in subdirectories for more specific documentation related to those components.
+`.trim();
+
+export const initSlashCommand: SlashCommandWithSource = {
+ name: "Init",
+ description: "Initialize Codebase",
+ source: "built-in",
+ prompt: INIT_PROMPT_CONTENT,
+};
diff --git a/core/protocol/core.ts b/core/protocol/core.ts
index b6d3ffe96..c559d9f64 100644
--- a/core/protocol/core.ts
+++ b/core/protocol/core.ts
@@ -4,6 +4,7 @@ import {
DevDataLogEvent,
ModelRole,
} from "@continuedev/config-yaml";
+import { ToolPolicy } from "@continuedev/terminal-security";
import {
AutocompleteInput,
@@ -13,6 +14,7 @@ import { SharedConfigSchema } from "../config/sharedConfig";
import { GlobalContextModelSelections } from "../util/GlobalContext";
import {
+ BaseSessionMetadata,
BrowserSerializedContinueConfig,
ChatMessage,
CompiledMessagesResult,
@@ -26,7 +28,6 @@ import {
FileSymbolMap,
IdeSettings,
LLMFullCompletionOptions,
- MCPServerStatus,
MessageOption,
ModelDescription,
PromptLog,
@@ -34,7 +35,6 @@ import {
RangeInFileWithNextEditInfo,
SerializedContinueConfig,
Session,
- SessionMetadata,
SiteIndexingConfig,
SlashCommandDescWithSource,
StreamDiffLinesPayload,
@@ -48,9 +48,13 @@ import {
ControlPlaneEnv,
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes";
-import { FreeTrialStatus } from "../control-plane/client";
+import {
+ FreeTrialStatus,
+ RemoteSessionMetadata,
+} from "../control-plane/client";
import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
import { NextEditOutcome } from "../nextEdit/types";
+import { ContinueErrorReason } from "../util/errors";
export enum OnboardingModes {
API_KEY = "API Key",
@@ -70,10 +74,15 @@ export type ToCoreFromIdeOrWebviewProtocol = {
cancelApply: [undefined, void];
// History
- "history/list": [ListHistoryOptions, SessionMetadata[]];
+ "history/list": [
+ ListHistoryOptions,
+ (BaseSessionMetadata | RemoteSessionMetadata)[],
+ ];
"history/delete": [{ id: string }, void];
"history/load": [{ id: string }, Session];
+ "history/loadRemote": [{ remoteId: string }, Session];
"history/save": [Session, void];
+ "history/share": [{ id: string; outputDir?: string }, void];
"history/clear": [undefined, void];
"devdata/log": [DevDataLogEvent, void];
"config/addOpenAiKey": [string, void];
@@ -85,6 +94,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
void,
];
"config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void];
+ "config/addGlobalRule": [undefined, void];
"config/newPromptFile": [undefined, void];
"config/newAssistantFile": [undefined, void];
"config/ideSettingsUpdate": [IdeSettings, void];
@@ -109,10 +119,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
),
void,
];
- "config/openProfile": [
- { profileId: string | undefined; element?: { sourceFile?: string } },
- void,
- ];
+ "config/openProfile": [{ profileId: string | undefined }, void];
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
"config/updateSelectedModel": [
{
@@ -139,6 +146,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
void,
];
+ "mcp/setServerEnabled": [{ id: string; enabled: boolean }, void];
"mcp/getPrompt": [
{
serverName: string;
@@ -150,9 +158,20 @@ export type ToCoreFromIdeOrWebviewProtocol = {
description: string | undefined;
},
];
- "mcp/startAuthentication": [MCPServerStatus, void];
- "mcp/removeAuthentication": [MCPServerStatus, void];
-
+ "mcp/startAuthentication": [
+ {
+ serverId: string;
+ serverUrl: string;
+ },
+ void,
+ ];
+ "mcp/removeAuthentication": [
+ {
+ serverId: string;
+ serverUrl: string;
+ },
+ void,
+ ];
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"autocomplete/complete": [AutocompleteInput, string[]];
@@ -293,6 +312,18 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ toolCall: ToolCall },
{ contextItems: ContextItem[]; errorMessage?: string },
];
+ "tools/evaluatePolicy": [
+ { toolName: string; basePolicy: ToolPolicy; args: Record },
+ { policy: ToolPolicy; displayValue?: string },
+ ];
+ "tools/preprocessArgs": [
+ { toolName: string; args: Record },
+ {
+ preprocessedArgs?: Record;
+ errorReason?: ContinueErrorReason;
+ errorMessage?: string;
+ },
+ ];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
"controlPlane/getEnvironment": [undefined, ControlPlaneEnv];
@@ -308,5 +339,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"process/markAsBackgrounded": [{ toolCallId: string }, void];
"process/isBackgrounded": [{ toolCallId: string }, boolean];
+ "process/killTerminalProcess": [{ toolCallId: string }, void];
"mdm/setLicenseKey": [{ licenseKey: string }, boolean];
};
diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts
index 232953f88..21eab1f7f 100644
--- a/core/protocol/ideWebview.ts
+++ b/core/protocol/ideWebview.ts
@@ -48,6 +48,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
];
"edit/addCurrentSelection": [undefined, void];
"edit/clearDecorations": [undefined, void];
+ "session/share": [{ sessionId: string }, void];
};
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts
index db1b9eb9a..5a6f45eba 100644
--- a/core/protocol/passThrough.ts
+++ b/core/protocol/passThrough.ts
@@ -13,6 +13,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"history/list",
"history/delete",
"history/load",
+ "history/loadRemote",
"history/save",
"history/clear",
"devdata/log",
@@ -21,6 +22,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/newAssistantFile",
"config/ideSettingsUpdate",
"config/addLocalWorkspaceBlock",
+ "config/addGlobalRule",
"config/getSerializedProfileInfo",
"config/deleteModel",
"config/refreshProfiles",
@@ -31,6 +33,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"mcp/getPrompt",
"mcp/startAuthentication",
"mcp/removeAuthentication",
+ "mcp/setServerEnabled",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
@@ -78,6 +81,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"didChangeSelectedProfile",
"didChangeSelectedOrg",
"tools/call",
+ "tools/evaluatePolicy",
+ "tools/preprocessArgs",
"controlPlane/getEnvironment",
"controlPlane/getFreeTrialStatus",
"controlPlane/getModelsAddOnUpgradeUrl",
@@ -85,6 +90,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
+ "process/killTerminalProcess",
];
// Message types to pass through from core to webview
diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts
index 0b98bb256..51c90d9ef 100644
--- a/core/test/fixtures.ts
+++ b/core/test/fixtures.ts
@@ -12,13 +12,11 @@ export const ideSettingsPromise = testIde.getIdeSettings();
export const testControlPlaneClient = new ControlPlaneClient(
Promise.resolve(undefined),
- ideSettingsPromise,
- testIde.getIdeInfo(),
+ testIde,
);
export const testConfigHandler = new ConfigHandler(
testIde,
- ideSettingsPromise,
new LLMLogger(),
Promise.resolve(undefined),
);
diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts
index 3f740da1c..47cd6769f 100644
--- a/core/tools/builtIn.ts
+++ b/core/tools/builtIn.ts
@@ -1,5 +1,6 @@
export enum BuiltInToolNames {
ReadFile = "read_file",
+ ReadFileRange = "read_file_range",
EditExistingFile = "edit_existing_file",
SingleFindAndReplace = "single_find_and_replace",
MultiEdit = "multi_edit",
diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts
index f24210511..faec8a94b 100644
--- a/core/tools/callTool.ts
+++ b/core/tools/callTool.ts
@@ -1,3 +1,4 @@
+import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
import { ContextItem, Tool, ToolCall, ToolExtras } from "..";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import { canParseUrl } from "../util/url";
@@ -12,6 +13,8 @@ import { grepSearchImpl } from "./implementations/grepSearch";
import { lsToolImpl } from "./implementations/lsTool";
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
import { readFileImpl } from "./implementations/readFile";
+
+import { readFileRangeImpl } from "./implementations/readFileRange";
import { requestRuleImpl } from "./implementations/requestRule";
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
import { searchWebImpl } from "./implementations/searchWeb";
@@ -85,10 +88,14 @@ async function callToolFromUri(
if (!client) {
throw new Error("MCP connection not found");
}
- const response = await client.client.callTool({
- name: toolName,
- arguments: args,
- });
+ const response = await client.client.callTool(
+ {
+ name: toolName,
+ arguments: args,
+ },
+ CallToolResultSchema,
+ { timeout: client.options.timeout },
+ );
if (response.isError === true) {
throw new Error(JSON.stringify(response.content));
@@ -145,6 +152,8 @@ export async function callBuiltInTool(
switch (functionName) {
case BuiltInToolNames.ReadFile:
return await readFileImpl(args, extras);
+ case BuiltInToolNames.ReadFileRange:
+ return await readFileRangeImpl(args, extras);
case BuiltInToolNames.CreateNewFile:
return await createNewFileImpl(args, extras);
case BuiltInToolNames.GrepSearch:
diff --git a/core/tools/constants.ts b/core/tools/constants.ts
index 0b5278209..332a270ef 100644
--- a/core/tools/constants.ts
+++ b/core/tools/constants.ts
@@ -1,2 +1,4 @@
export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output";
export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call.";
+export const ERRORED_TOOL_CALL_OUTPUT_MESSAGE =
+ "There was an error calling the tool.";
diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts
index 8f651a601..4d52cd665 100644
--- a/core/tools/definitions/createNewFile.ts
+++ b/core/tools/definitions/createNewFile.ts
@@ -4,9 +4,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const createNewFileTool: Tool = {
type: "function",
displayTitle: "Create New File",
- wouldLikeTo: "create a new file at {{{ filepath }}}",
- isCurrently: "creating a new file at {{{ filepath }}}",
- hasAlready: "created a new file at {{{ filepath }}}",
+ wouldLikeTo: "create {{{ filepath }}}",
+ isCurrently: "creating {{{ filepath }}}",
+ hasAlready: "created {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: true,
diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts
index 7dcb8cd51..2b8f1c4ed 100644
--- a/core/tools/definitions/createRuleBlock.ts
+++ b/core/tools/definitions/createRuleBlock.ts
@@ -84,4 +84,5 @@ For example:`,
["alwaysApply", "false"],
],
},
+ toolCallIcon: "PencilIcon",
};
diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts
index 1b12af8fb..9ca5b6b63 100644
--- a/core/tools/definitions/editFile.ts
+++ b/core/tools/definitions/editFile.ts
@@ -7,8 +7,8 @@ export interface EditToolArgs {
changes: string;
}
-export const NO_PARALLEL_TOOL_CALLING_INTSRUCTION =
- "Note this tool CANNOT be called in parallel with other tools.";
+export const NO_PARALLEL_TOOL_CALLING_INSTRUCTION =
+ "This tool CANNOT be called in parallel with other tools.";
const CHANGES_DESCRIPTION =
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'";
@@ -24,7 +24,7 @@ export const editFileTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.EditExistingFile,
- description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}`,
+ description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSTRUCTION}`,
parameters: {
type: "object",
required: ["filepath", "changes"],
diff --git a/core/tools/definitions/fetchUrlContent.ts b/core/tools/definitions/fetchUrlContent.ts
index 07a76a991..2498dcc59 100644
--- a/core/tools/definitions/fetchUrlContent.ts
+++ b/core/tools/definitions/fetchUrlContent.ts
@@ -6,7 +6,7 @@ export const fetchUrlContentTool: Tool = {
displayTitle: "Read URL",
wouldLikeTo: "fetch {{{ url }}}",
isCurrently: "fetching {{{ url }}}",
- hasAlready: "viewed {{{ url }}}",
+ hasAlready: "fetched {{{ url }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@@ -30,4 +30,5 @@ export const fetchUrlContentTool: Tool = {
prefix: `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`,
exampleArgs: [["url", "https://example.com"]],
},
+ toolCallIcon: "GlobeAltIcon",
};
diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts
index 5e710c04b..5159ea3ea 100644
--- a/core/tools/definitions/globSearch.ts
+++ b/core/tools/definitions/globSearch.ts
@@ -4,16 +4,16 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const globSearchTool: Tool = {
type: "function",
displayTitle: "Glob File Search",
- wouldLikeTo: 'find file matches for "{{{ pattern }}}"',
- isCurrently: 'finding file matches for "{{{ pattern }}}"',
- hasAlready: 'retrieved file matches for "{{{ pattern }}}"',
+ wouldLikeTo: 'search for files like "{{{ pattern }}}"',
+ isCurrently: 'searching for files like "{{{ pattern }}}"',
+ hasAlready: 'searched for files like "{{{ pattern }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.FileGlobSearch,
description:
- "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns",
+ "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Will not show many build, cache, secrets dirs/files (can use ls tool instead). Output may be truncated; use targeted patterns",
parameters: {
type: "object",
required: ["pattern"],
@@ -30,4 +30,5 @@ export const globSearchTool: Tool = {
prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,
exampleArgs: [["pattern", "*.py"]],
},
+ toolCallIcon: "MagnifyingGlassIcon",
};
diff --git a/core/tools/definitions/grepSearch.ts b/core/tools/definitions/grepSearch.ts
index cc4f9c49c..c9e78d62d 100644
--- a/core/tools/definitions/grepSearch.ts
+++ b/core/tools/definitions/grepSearch.ts
@@ -4,16 +4,16 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const grepSearchTool: Tool = {
type: "function",
displayTitle: "Grep Search",
- wouldLikeTo: 'search for "{{{ query }}}" in the repository',
- isCurrently: 'getting search results for "{{{ query }}}"',
- hasAlready: 'retrieved search results for "{{{ query }}}"',
+ wouldLikeTo: 'search for "{{{ query }}}"',
+ isCurrently: 'searching for "{{{ query }}}"',
+ hasAlready: 'searched for "{{{ query }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.GrepSearch,
description:
- "Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries",
+ "Perform a search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries",
parameters: {
type: "object",
required: ["query"],
@@ -31,4 +31,5 @@ export const grepSearchTool: Tool = {
prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,
exampleArgs: [["query", ".*main_services.*"]],
},
+ toolCallIcon: "MagnifyingGlassIcon",
};
diff --git a/core/tools/definitions/index.ts b/core/tools/definitions/index.ts
index 413157e4d..bf3dc02d9 100644
--- a/core/tools/definitions/index.ts
+++ b/core/tools/definitions/index.ts
@@ -9,6 +9,8 @@ export { lsTool } from "./ls";
export { multiEditTool } from "./multiEdit";
export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
export { readFileTool } from "./readFile";
+
+export { readFileRangeTool } from "./readFileRange";
export { requestRuleTool } from "./requestRule";
export { runTerminalCommandTool } from "./runTerminalCommand";
export { searchWebTool } from "./searchWeb";
diff --git a/core/tools/definitions/ls.ts b/core/tools/definitions/ls.ts
index 86d9581af..49ac5b1c6 100644
--- a/core/tools/definitions/ls.ts
+++ b/core/tools/definitions/ls.ts
@@ -5,9 +5,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const lsTool: Tool = {
type: "function",
displayTitle: "ls",
- wouldLikeTo: "list files and folders in {{{ dirPath }}}",
- isCurrently: "listing files and folders in {{{ dirPath }}}",
- hasAlready: "listed files and folders in {{{ dirPath }}}",
+ wouldLikeTo: "list files in {{{ dirPath }}}",
+ isCurrently: "listing files in {{{ dirPath }}}",
+ hasAlready: "listed files in {{{ dirPath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@@ -38,4 +38,5 @@ export const lsTool: Tool = {
["recursive", "false"],
],
},
+ toolCallIcon: "FolderIcon",
};
diff --git a/core/tools/definitions/multiEdit.ts b/core/tools/definitions/multiEdit.ts
index 09a26be5b..e526b90e5 100644
--- a/core/tools/definitions/multiEdit.ts
+++ b/core/tools/definitions/multiEdit.ts
@@ -1,6 +1,9 @@
import { Tool } from "../..";
+import { validateMultiEdit } from "../../edit/searchAndReplace/multiEditValidation";
+import { executeMultiFindAndReplace } from "../../edit/searchAndReplace/performReplace";
+import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
-import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
+import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
export interface EditOperation {
old_string: string;
@@ -24,60 +27,35 @@ export const multiEditTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.MultiEdit,
- description: `This is a tool for making multiple edits to a single file in one operation. It
-is built on top of the single find and replace tool and allows you to perform multiple
-find-and-replace operations efficiently. Prefer this tool over the single find and replace tool
-when you need to make multiple edits to the same file.
+ description: `Use this tool to make multiple edits to a single file in one operation. It allows you to perform multiple find-and-replace operations efficiently.
-Before using this tool:
-
-1. Use the read_file tool to understand the file's contents and context
-2. Verify the directory path is correct
-
-To make multiple file edits, provide the following:
-
-1. filepath: The path to the file to modify (relative to the root of the workspace)
+To make multiple edits to a file, provide the following:
+1. filepath: The path to the file to modify, RELATIVE to the project/workspace root (verify the directory path is correct)
2. edits: An array of edit operations to perform, where each edit contains:
- - old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)
+ - old_string: The text to replace (must match the old file contents exactly, including all whitespace/indentation)
- new_string: The edited text to replace the old_string
- replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false.
IMPORTANT:
+- Files may be modified between tool calls by users, linters, etc, so always make all edits in one tool call where possible. For example, do not only edit imports if there are other changes in the file, as unused imports may be removed by a linter between tool calls.
- All edits are applied in sequence, in the order they are provided
-- Each edit operates on the result of the previous edit
-- All edits must be valid for the operation to succeed - if any edit fails,
-none will be applied
-- This tool is ideal when you need to make several changes to different parts
-of the same file
+- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations
+- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied
+- This tool is ideal when you need to make several changes to different parts of the same file
CRITICAL REQUIREMENTS:
-
-1. All edits follow the same requirements as the single find and replace tool
-2. The edits are atomic - either all succeed or none are applied
-3. Plan your edits carefully to avoid conflicts between sequential operations
-4. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
-
-WARNING:
-
-- The tool will fail if edits.old_string doesn't match the file contents
-exactly (including whitespace)
-- The tool will fail if edits.old_string and edits.new_string are the same
-- Since edits are applied in sequence, ensure that earlier edits don't affect
-the text that later edits are trying to find
-
-When making edits:
-
+1. ALWAYS use the ${BuiltInToolNames.ReadFile} tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it.
+2. ${NO_PARALLEL_TOOL_CALLING_INSTRUCTION}
+3. When making edits:
- Ensure all edits result in idiomatic, correct code
- Do not leave the code in a broken state
-- Only use emojis if the user explicitly requests it. Avoid adding emojis to
-files unless asked.
-- Use replace_all for replacing and renaming strings across the file. This
-parameter is useful if you want to rename a variable for instance.
+- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked
+- Use replace_all for replacing and renaming all matches for a string across the file. This parameter is useful if you want to rename a variable, for instance
-If you want to create a new file, use:
-- A new file path
-- First edit: empty old_string and the new file's contents as new_string
-- Subsequent edits are not allowed - there is no need since you are creating`,
+WARNINGS:
+- If earlier edits affect the text that later edits are trying to find, files can become mangled
+- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
+- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different`,
parameters: {
type: "object",
required: ["filepath", "edits"],
@@ -97,16 +75,18 @@ If you want to create a new file, use:
properties: {
old_string: {
type: "string",
- description: "The text to replace",
+ description:
+ "The text to replace (exact match including whitespace/indentation)",
},
new_string: {
type: "string",
- description: "The text to replace it with",
+ description:
+ "The text to replace it with. MUST be different than old_string.",
},
replace_all: {
type: "boolean",
description:
- "Replace all occurrences of old_string (default false)",
+ "Replace all occurrences of old_string (default false) in the file",
},
},
},
@@ -130,4 +110,24 @@ If you want to create a new file, use:
],
},
defaultToolPolicy: "allowedWithPermission",
+ preprocessArgs: async (args, extras) => {
+ const { edits } = validateMultiEdit(args);
+ const fileUri = await validateSearchAndReplaceFilepath(
+ args.filepath,
+ extras.ide,
+ );
+
+ const editingFileContents = await extras.ide.readFile(fileUri);
+ const newFileContents = executeMultiFindAndReplace(
+ editingFileContents,
+ edits,
+ );
+
+ return {
+ ...args,
+ fileUri,
+ editingFileContents,
+ newFileContents,
+ };
+ },
};
diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts
index da1cb129b..87d1adc22 100644
--- a/core/tools/definitions/readCurrentlyOpenFile.ts
+++ b/core/tools/definitions/readCurrentlyOpenFile.ts
@@ -6,7 +6,7 @@ export const readCurrentlyOpenFileTool: Tool = {
displayTitle: "Read Currently Open File",
wouldLikeTo: "read the current file",
isCurrently: "reading the current file",
- hasAlready: "viewed the current file",
+ hasAlready: "read the current file",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@@ -24,4 +24,5 @@ export const readCurrentlyOpenFileTool: Tool = {
prefix: `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
If the user is asking about a file and you don't see any code, use this to check the current file`,
},
+ toolCallIcon: "DocumentTextIcon",
};
diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts
index 2fc606883..ee6c1c91c 100644
--- a/core/tools/definitions/readFile.ts
+++ b/core/tools/definitions/readFile.ts
@@ -6,7 +6,7 @@ export const readFileTool: Tool = {
displayTitle: "Read File",
wouldLikeTo: "read {{{ filepath }}}",
isCurrently: "reading {{{ filepath }}}",
- hasAlready: "viewed {{{ filepath }}}",
+ hasAlready: "read {{{ filepath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@@ -31,4 +31,5 @@ export const readFileTool: Tool = {
exampleArgs: [["filepath", "path/to/the_file.txt"]],
},
defaultToolPolicy: "allowedWithoutPermission",
+ toolCallIcon: "DocumentIcon",
};
diff --git a/core/tools/definitions/readFileRange.ts b/core/tools/definitions/readFileRange.ts
new file mode 100644
index 000000000..41a7bfcfd
--- /dev/null
+++ b/core/tools/definitions/readFileRange.ts
@@ -0,0 +1,52 @@
+import { Tool } from "../..";
+import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
+
+export const readFileRangeTool: Tool = {
+ type: "function",
+ displayTitle: "Read File Range",
+ wouldLikeTo:
+ "read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
+ isCurrently:
+ "reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
+ hasAlready:
+ "read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
+ readonly: true,
+ isInstant: true,
+ group: BUILT_IN_GROUP_NAME,
+ function: {
+ name: BuiltInToolNames.ReadFileRange,
+ description:
+ "Use this tool to read a specific range of lines from an existing file. Only supports positive line numbers (1-based from start). For reading from the end of a file, use the terminal tool with 'tail' command instead.",
+ parameters: {
+ type: "object",
+ required: ["filepath", "startLine", "endLine"],
+ properties: {
+ filepath: {
+ type: "string",
+ description:
+ "The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)",
+ },
+ startLine: {
+ type: "number",
+ description:
+ "The starting line number (1-based from start). Must be a positive integer. Example: 1 = first line, 10 = tenth line",
+ },
+ endLine: {
+ type: "number",
+ description:
+ "The ending line number (1-based from start). Must be a positive integer greater than or equal to startLine. Example: 10 = tenth line, 20 = twentieth line",
+ },
+ },
+ },
+ },
+ systemMessageDescription: {
+ prefix: `To read a specific range of lines from a file, use the ${BuiltInToolNames.ReadFileRange} tool. Only supports positive line numbers (1-based from start). For reading from the end of files, use the terminal tool with 'tail' command instead:`,
+ exampleArgs: [
+ ["filepath", "path/to/the_file.txt"],
+ ["startLine", 10],
+ ["endLine", 20],
+ ],
+ },
+ defaultToolPolicy: "allowedWithoutPermission",
+ toolCallIcon: "DocumentIcon",
+};
diff --git a/core/tools/definitions/requestRule.test.ts b/core/tools/definitions/requestRule.test.ts
index 0fd7b5de8..b2d924ec9 100644
--- a/core/tools/definitions/requestRule.test.ts
+++ b/core/tools/definitions/requestRule.test.ts
@@ -10,7 +10,7 @@ describe("getRequestRuleDescription", () => {
source: "default-chat",
rule: "Always use semicolons",
alwaysApply: true,
- ruleFile: "/path/to/rule1.md",
+ sourceFile: "/path/to/rule1.md",
},
{
name: "Rule with Globs",
@@ -18,7 +18,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Use TypeScript",
globs: "**/*.ts",
- ruleFile: "/path/to/rule2.md",
+ sourceFile: "/path/to/rule2.md",
},
];
@@ -38,7 +38,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Use consistent formatting",
alwaysApply: false,
- ruleFile: "/path/to/agent-rule1.md",
+ sourceFile: "/path/to/agent-rule1.md",
},
{
name: "Agent Rule 2",
@@ -46,7 +46,7 @@ describe("getRequestRuleDescription", () => {
source: "default-agent",
rule: "Follow naming conventions",
alwaysApply: false,
- ruleFile: "/path/to/agent-rule2.md",
+ sourceFile: "/path/to/agent-rule2.md",
},
// These should be filtered out
{
@@ -55,7 +55,7 @@ describe("getRequestRuleDescription", () => {
source: "default-chat",
rule: "Always use semicolons",
alwaysApply: true,
- ruleFile: "/path/to/rule1.md",
+ sourceFile: "/path/to/rule1.md",
},
{
name: "Rule with Globs",
@@ -63,7 +63,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Use TypeScript",
globs: "**/*.ts",
- ruleFile: "/path/to/rule2.md",
+ sourceFile: "/path/to/rule2.md",
},
];
@@ -84,7 +84,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Some rule content",
alwaysApply: false,
- ruleFile: "/path/to/no-desc-rule.md",
+ sourceFile: "/path/to/no-desc-rule.md",
},
];
@@ -104,7 +104,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Some rule content",
alwaysApply: false,
- ruleFile: "/path/to/no-name-rule.md",
+ sourceFile: "/path/to/no-name-rule.md",
},
];
@@ -117,7 +117,7 @@ describe("getRequestRuleDescription", () => {
expect(result).toBe(expected);
});
- it("should handle rules with missing ruleFile", () => {
+ it("should handle rules with missing sourceFile", () => {
const rules: RuleWithSource[] = [
{
name: "Rule Without File",
@@ -144,7 +144,7 @@ describe("getRequestRuleDescription", () => {
description: "This should be filtered out",
source: "rules-block",
rule: "Some rule",
- ruleFile: "/path/to/rule.md",
+ sourceFile: "/path/to/rule.md",
// alwaysApply is undefined, which is truthy in the filter condition
},
{
@@ -153,7 +153,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Some rule",
alwaysApply: false,
- ruleFile: "/path/to/valid-rule.md",
+ sourceFile: "/path/to/valid-rule.md",
},
];
@@ -175,7 +175,7 @@ describe("getRequestRuleDescription", () => {
rule: "Some rule",
alwaysApply: false,
globs: "**/*.ts",
- ruleFile: "/path/to/rule1.md",
+ sourceFile: "/path/to/rule1.md",
},
{
name: "Rule with array globs",
@@ -184,7 +184,7 @@ describe("getRequestRuleDescription", () => {
rule: "Some rule",
alwaysApply: false,
globs: ["**/*.ts", "**/*.js"],
- ruleFile: "/path/to/rule2.md",
+ sourceFile: "/path/to/rule2.md",
},
{
name: "Valid Agent Rule",
@@ -192,7 +192,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Some rule",
alwaysApply: false,
- ruleFile: "/path/to/valid-rule.md",
+ sourceFile: "/path/to/valid-rule.md",
},
];
@@ -224,7 +224,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Follow this guideline",
alwaysApply: false,
- ruleFile: "/path/to/single-rule.md",
+ sourceFile: "/path/to/single-rule.md",
},
];
diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts
index b2dc74316..dbeaa5c05 100644
--- a/core/tools/definitions/runTerminalCommand.ts
+++ b/core/tools/definitions/runTerminalCommand.ts
@@ -1,6 +1,10 @@
import os from "os";
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
+import {
+ evaluateTerminalCommandSecurity,
+ ToolPolicy,
+} from "@continuedev/terminal-security";
/**
* Get the preferred shell for the current platform
@@ -56,6 +60,15 @@ export const runTerminalCommandTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
+ evaluateToolCallPolicy: (
+ basePolicy: ToolPolicy,
+ parsedArgs: Record,
+ ): ToolPolicy => {
+ return evaluateTerminalCommandSecurity(
+ basePolicy,
+ parsedArgs.command as string,
+ );
+ },
systemMessageDescription: {
prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
${RUN_COMMAND_NOTES}
diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts
index aa1555e15..7740cb45a 100644
--- a/core/tools/definitions/searchWeb.ts
+++ b/core/tools/definitions/searchWeb.ts
@@ -30,4 +30,5 @@ export const searchWebTool: Tool = {
prefix: `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`,
exampleArgs: [["query", "What is the current weather in San Francisco?"]],
},
+ toolCallIcon: "GlobeAltIcon",
};
diff --git a/core/tools/definitions/singleFindAndReplace.ts b/core/tools/definitions/singleFindAndReplace.ts
index a8a9fc15b..c5b2995e1 100644
--- a/core/tools/definitions/singleFindAndReplace.ts
+++ b/core/tools/definitions/singleFindAndReplace.ts
@@ -1,6 +1,9 @@
import { Tool } from "../..";
+import { validateSingleEdit } from "../../edit/searchAndReplace/findAndReplaceUtils";
+import { executeFindAndReplace } from "../../edit/searchAndReplace/performReplace";
+import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
-import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
+import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
export interface SingleFindAndReplaceArgs {
filepath: string;
@@ -12,41 +15,26 @@ export interface SingleFindAndReplaceArgs {
export const singleFindAndReplaceTool: Tool = {
type: "function",
displayTitle: "Find and Replace",
- wouldLikeTo: "find and replace in {{{ filepath }}}",
- isCurrently: "finding and replacing in {{{ filepath }}}",
- hasAlready: "found and replaced in {{{ filepath }}}",
+ wouldLikeTo: "edit {{{ filepath }}}",
+ isCurrently: "editing {{{ filepath }}}",
+ hasAlready: "edited {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: false,
function: {
name: BuiltInToolNames.SingleFindAndReplace,
- description: `Performs exact string replacements in files.
+ description: `Performs exact string replacements in a file.
-Usage:
+IMPORTANT:
+- ALWAYS use the \`${BuiltInToolNames.ReadFile}\` tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it.
+- ${NO_PARALLEL_TOOL_CALLING_INSTRUCTION}
+- When editing text from \`${BuiltInToolNames.ReadFile}\` tool output, ensure you preserve exact whitespace/indentation.
+- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
+- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance.
-- You must use your \`read_file\` tool at least once in the conversation before
-editing. This tool will error if you attempt an edit without reading the file.
-
-- When editing text from read_file tool output, ensure you preserve the exact
-indentation (tabs/spaces) as it appears AFTER the line number prefix. The line
-number prefix format is: spaces + line number + tab. Everything after that tab
-is the actual file content to match. Never include any part of the line number
-prefix in the old_string or new_string.
-
-- ALWAYS prefer editing existing files in the codebase. NEVER write new files
-unless explicitly required.
-
-- Only use emojis if the user explicitly requests it. Avoid adding emojis to
-files unless asked.
-
-- ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
-
-- The edit will FAIL if \`old_string\` is not unique in the file. Either provide
-a larger string with more surrounding context to make it unique or use
-\`replace_all\` to change every instance of \`old_string\`.
-
-- Use \`replace_all\` for replacing and renaming strings across the file. This
-parameter is useful if you want to rename a variable for instance.`,
+WARNINGS:
+- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
+- The edit will likely fail if you have not recently used the \`${BuiltInToolNames.ReadFile}\` tool to view up-to-date file contents.`,
parameters: {
type: "object",
required: ["filepath", "old_string", "new_string"],
@@ -58,12 +46,13 @@ parameter is useful if you want to rename a variable for instance.`,
},
old_string: {
type: "string",
- description: "The text to replace",
+ description:
+ "The text to replace - must be exact including whitespace/indentation",
},
new_string: {
type: "string",
description:
- "The text to replace it with (must be different from old_string)",
+ "The text to replace it with (MUST be different from old_string)",
},
replace_all: {
type: "boolean",
@@ -84,4 +73,31 @@ parameter is useful if you want to rename a variable for instance.`,
],
},
defaultToolPolicy: "allowedWithPermission",
+ preprocessArgs: async (args, extras) => {
+ const { oldString, newString, replaceAll } = validateSingleEdit(
+ args.old_string,
+ args.new_string,
+ args.replace_all,
+ );
+ const fileUri = await validateSearchAndReplaceFilepath(
+ args.filepath,
+ extras.ide,
+ );
+
+ const editingFileContents = await extras.ide.readFile(fileUri);
+ const newFileContents = executeFindAndReplace(
+ editingFileContents,
+ oldString,
+ newString,
+ replaceAll ?? false,
+ 0,
+ );
+
+ return {
+ ...args,
+ fileUri,
+ editingFileContents,
+ newFileContents,
+ };
+ },
};
diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts
index 14d6176f2..4c397a04b 100644
--- a/core/tools/definitions/viewDiff.ts
+++ b/core/tools/definitions/viewDiff.ts
@@ -23,4 +23,5 @@ export const viewDiffTool: Tool = {
prefix: `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`,
},
defaultToolPolicy: "allowedWithoutPermission",
+ toolCallIcon: "CodeBracketIcon",
};
diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts
index 0d1d94046..176855e2b 100644
--- a/core/tools/definitions/viewRepoMap.ts
+++ b/core/tools/definitions/viewRepoMap.ts
@@ -23,4 +23,5 @@ export const viewRepoMapTool: Tool = {
prefix: `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,
},
defaultToolPolicy: "allowedWithPermission",
+ toolCallIcon: "MapIcon",
};
diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts
index 4ef686445..f8776716f 100644
--- a/core/tools/definitions/viewSubdirectory.ts
+++ b/core/tools/definitions/viewSubdirectory.ts
@@ -30,4 +30,5 @@ export const viewSubdirectoryTool: Tool = {
exampleArgs: [["directory_path", "path/to/subdirectory"]],
},
defaultToolPolicy: "allowedWithPermission",
+ toolCallIcon: "FolderOpenIcon",
};
diff --git a/core/tools/implementations/readFileRange.integration.vitest.ts b/core/tools/implementations/readFileRange.integration.vitest.ts
new file mode 100644
index 000000000..945d03e41
--- /dev/null
+++ b/core/tools/implementations/readFileRange.integration.vitest.ts
@@ -0,0 +1,204 @@
+import { expect, test, vi } from "vitest";
+import { ToolExtras } from "../..";
+import { readFileRangeImpl } from "./readFileRange";
+
+// Mock the dependencies
+vi.mock("../../util/ideUtils", () => ({
+ resolveRelativePathInDir: vi.fn(),
+}));
+
+vi.mock("../../util/uri", () => ({
+ getUriPathBasename: vi.fn(),
+}));
+
+vi.mock("./readFileLimit", () => ({
+ throwIfFileExceedsHalfOfContext: vi.fn(),
+}));
+
+test("readFileRangeImpl handles out-of-bounds ranges gracefully", async () => {
+ const { resolveRelativePathInDir } = await import("../../util/ideUtils");
+ const { getUriPathBasename } = await import("../../util/uri");
+ const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit");
+
+ // Mock the utility functions
+ vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt");
+ vi.mocked(getUriPathBasename).mockReturnValue("test.txt");
+ vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined);
+
+ // Test case 1: Start line beyond end of file
+ const mockIdeOutOfBounds = {
+ readRangeInFile: vi.fn().mockResolvedValue(""), // IDE returns empty string
+ };
+
+ const mockExtras1 = {
+ ide: mockIdeOutOfBounds,
+ config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
+ } as unknown as ToolExtras;
+
+ const result1 = await readFileRangeImpl(
+ {
+ filepath: "test.txt",
+ startLine: 100, // Beyond end of file
+ endLine: 105,
+ },
+ mockExtras1,
+ );
+
+ expect(result1).toHaveLength(1);
+ expect(result1[0].content).toBe("");
+ expect(result1[0].description).toBe("test.txt (lines 100-105)");
+
+ // Test case 2: End line beyond end of file
+ const mockIdePartialRange = {
+ readRangeInFile: vi.fn().mockResolvedValue("line5\nline6"), // IDE returns available content
+ };
+
+ const mockExtras2 = {
+ ide: mockIdePartialRange,
+ config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
+ } as unknown as ToolExtras;
+
+ const result2 = await readFileRangeImpl(
+ {
+ filepath: "test.txt",
+ startLine: 5,
+ endLine: 100, // Beyond end of file
+ },
+ mockExtras2,
+ );
+
+ expect(result2).toHaveLength(1);
+ expect(result2[0].content).toBe("line5\nline6");
+ expect(result2[0].description).toBe("test.txt (lines 5-100)");
+
+ // Verify that IDE methods were called with correct 0-based ranges
+ expect(mockIdeOutOfBounds.readRangeInFile).toHaveBeenCalledWith(
+ "file:///test.txt",
+ {
+ start: { line: 99, character: 0 }, // 100 - 1
+ end: { line: 104, character: Number.MAX_SAFE_INTEGER }, // 105 - 1
+ },
+ );
+
+ expect(mockIdePartialRange.readRangeInFile).toHaveBeenCalledWith(
+ "file:///test.txt",
+ {
+ start: { line: 4, character: 0 }, // 5 - 1
+ end: { line: 99, character: Number.MAX_SAFE_INTEGER }, // 100 - 1
+ },
+ );
+});
+
+test("readFileRangeImpl validates line number constraints", async () => {
+ const mockExtras = {
+ ide: { readRangeInFile: vi.fn(), readFile: vi.fn() },
+ config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
+ } as unknown as ToolExtras;
+
+ // Test startLine < 1 (invalid)
+ await expect(
+ readFileRangeImpl(
+ {
+ filepath: "test.txt",
+ startLine: 0,
+ endLine: 5,
+ },
+ mockExtras,
+ ),
+ ).rejects.toThrow("startLine must be 1 or greater");
+
+ // Test negative startLine (no longer supported)
+ await expect(
+ readFileRangeImpl(
+ {
+ filepath: "test.txt",
+ startLine: -1,
+ endLine: 5,
+ },
+ mockExtras,
+ ),
+ ).rejects.toThrow("Negative line numbers are not supported");
+
+ // Test endLine < 1 (invalid)
+ await expect(
+ readFileRangeImpl(
+ {
+ filepath: "test.txt",
+ startLine: 1,
+ endLine: 0,
+ },
+ mockExtras,
+ ),
+ ).rejects.toThrow("endLine must be 1 or greater");
+
+ // Test negative endLine (no longer supported)
+ await expect(
+ readFileRangeImpl(
+ {
+ filepath: "test.txt",
+ startLine: 1,
+ endLine: -1,
+ },
+ mockExtras,
+ ),
+ ).rejects.toThrow("Negative line numbers are not supported");
+
+ // Test endLine < startLine
+ await expect(
+ readFileRangeImpl(
+ {
+ filepath: "test.txt",
+ startLine: 10,
+ endLine: 5,
+ },
+ mockExtras,
+ ),
+ ).rejects.toThrow(
+ "endLine (5) must be greater than or equal to startLine (10)",
+ );
+});
+
+test("readFileRangeImpl handles normal ranges correctly", async () => {
+ const { resolveRelativePathInDir } = await import("../../util/ideUtils");
+ const { getUriPathBasename } = await import("../../util/uri");
+ const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit");
+
+ vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt");
+ vi.mocked(getUriPathBasename).mockReturnValue("test.txt");
+ vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined);
+
+ const mockIde = {
+ readRangeInFile: vi.fn().mockResolvedValue("line2\nline3\nline4"),
+ };
+
+ const mockExtras = {
+ ide: mockIde,
+ config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
+ } as unknown as ToolExtras;
+
+ const result = await readFileRangeImpl(
+ {
+ filepath: "src/test.py",
+ startLine: 2,
+ endLine: 4,
+ },
+ mockExtras,
+ );
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({
+ name: "test.txt",
+ description: "src/test.py (lines 2-4)",
+ content: "line2\nline3\nline4",
+ uri: {
+ type: "file",
+ value: "file:///test.txt",
+ },
+ });
+
+ // Verify correct 0-based conversion
+ expect(mockIde.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", {
+ start: { line: 1, character: 0 }, // 2 - 1
+ end: { line: 3, character: Number.MAX_SAFE_INTEGER }, // 4 - 1
+ });
+});
diff --git a/core/tools/implementations/readFileRange.ts b/core/tools/implementations/readFileRange.ts
new file mode 100644
index 000000000..c313f4bff
--- /dev/null
+++ b/core/tools/implementations/readFileRange.ts
@@ -0,0 +1,68 @@
+import { resolveRelativePathInDir } from "../../util/ideUtils";
+import { getUriPathBasename } from "../../util/uri";
+
+import { ToolImpl } from ".";
+import { getNumberArg, getStringArg } from "../parseArgs";
+import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
+
+export const readFileRangeImpl: ToolImpl = async (args, extras) => {
+ const filepath = getStringArg(args, "filepath");
+ const startLine = getNumberArg(args, "startLine");
+ const endLine = getNumberArg(args, "endLine");
+
+ // Validate that line numbers are positive integers
+ if (startLine < 1) {
+ throw new Error(
+ "startLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.",
+ );
+ }
+ if (endLine < 1) {
+ throw new Error(
+ "endLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.",
+ );
+ }
+ if (endLine < startLine) {
+ throw new Error(
+ `endLine (${endLine}) must be greater than or equal to startLine (${startLine})`,
+ );
+ }
+
+ const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
+ if (!firstUriMatch) {
+ throw new Error(
+ `File "${filepath}" does not exist. You might want to check the path and try again.`,
+ );
+ }
+
+ // Use the IDE's readRangeInFile method with 0-based range (IDE expects 0-based internally)
+ const content = await extras.ide.readRangeInFile(firstUriMatch, {
+ start: {
+ line: startLine - 1, // Convert from 1-based to 0-based
+ character: 0,
+ },
+ end: {
+ line: endLine - 1, // Convert from 1-based to 0-based
+ character: Number.MAX_SAFE_INTEGER, // Read to end of line
+ },
+ });
+
+ await throwIfFileExceedsHalfOfContext(
+ filepath,
+ content,
+ extras.config.selectedModelByRole.chat,
+ );
+
+ const rangeDescription = `${filepath} (lines ${startLine}-${endLine})`;
+
+ return [
+ {
+ name: getUriPathBasename(firstUriMatch),
+ description: rangeDescription,
+ content,
+ uri: {
+ type: "file",
+ value: firstUriMatch,
+ },
+ },
+ ];
+};
diff --git a/core/tools/implementations/readFileRange.vitest.ts b/core/tools/implementations/readFileRange.vitest.ts
new file mode 100644
index 000000000..b8a172d1c
--- /dev/null
+++ b/core/tools/implementations/readFileRange.vitest.ts
@@ -0,0 +1,60 @@
+import { expect, test } from "vitest";
+import { getNumberArg } from "../parseArgs";
+
+test("readFileRange should validate positive line number arguments", () => {
+ // Test positive startLine validation
+ expect(() => getNumberArg({ startLine: 1 }, "startLine")).not.toThrow();
+ expect(() => getNumberArg({ startLine: "1" }, "startLine")).not.toThrow();
+ expect(() => getNumberArg({ startLine: 100 }, "startLine")).not.toThrow();
+
+ // Test positive endLine validation
+ expect(() => getNumberArg({ endLine: 5 }, "endLine")).not.toThrow();
+ expect(() => getNumberArg({ endLine: "10" }, "endLine")).not.toThrow();
+ expect(() => getNumberArg({ endLine: 1000 }, "endLine")).not.toThrow();
+
+ // Test missing arguments
+ expect(() => getNumberArg({}, "startLine")).toThrow(
+ "Argument `startLine` is required (type number)",
+ );
+ expect(() => getNumberArg({}, "endLine")).toThrow(
+ "Argument `endLine` is required (type number)",
+ );
+
+ // Test invalid arguments
+ expect(() =>
+ getNumberArg({ startLine: "not-a-number" }, "startLine"),
+ ).toThrow("Argument `startLine` must be a valid number");
+ expect(() => getNumberArg({ endLine: true }, "endLine")).toThrow(
+ "Argument `endLine` must be a valid number",
+ );
+});
+
+test("readFileRange should handle line number conversion", () => {
+ // Test that our parsing function converts correctly
+ expect(getNumberArg({ line: 1 }, "line")).toBe(1);
+ expect(getNumberArg({ line: "5" }, "line")).toBe(5);
+ expect(getNumberArg({ line: 10.7 }, "line")).toBe(10); // Should floor
+ expect(getNumberArg({ line: "15.9" }, "line")).toBe(15); // Should floor
+});
+
+test("readFileRange parses negative numbers (validation happens in implementation)", () => {
+ // The parseArgs function should parse negative numbers correctly
+ // but the implementation will reject them with helpful error messages
+ expect(getNumberArg({ line: -1 }, "line")).toBe(-1);
+ expect(getNumberArg({ line: -10 }, "line")).toBe(-10);
+ expect(getNumberArg({ line: "-5" }, "line")).toBe(-5);
+});
+
+test("readFileRange handles out-of-bounds ranges gracefully", () => {
+ // IDE implementations handle out-of-bounds gracefully:
+ // - VS Code: Uses array.slice() which handles out-of-bounds gracefully
+ // - IntelliJ: Uses lines.getOrNull() which returns null for out-of-bounds
+ // Both return empty content or available content without throwing errors
+
+ expect(() => {
+ const startLine = getNumberArg({ startLine: 1000 }, "startLine");
+ const endLine = getNumberArg({ endLine: 2000 }, "endLine");
+ expect(startLine).toBe(1000);
+ expect(endLine).toBe(2000);
+ }).not.toThrow();
+});
diff --git a/core/tools/implementations/requestRule.ts b/core/tools/implementations/requestRule.ts
index 61467e429..c5c312e70 100644
--- a/core/tools/implementations/requestRule.ts
+++ b/core/tools/implementations/requestRule.ts
@@ -7,7 +7,7 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => {
// Find the rule by name in the config
const rule = extras.config.rules.find((r) => r.name === name);
- if (!rule || !rule.ruleFile) {
+ if (!rule || !rule.sourceFile) {
throw new Error(`Rule with name "${name}" not found or has no file path`);
}
@@ -18,7 +18,7 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => {
content: rule.rule,
uri: {
type: "file",
- value: rule.ruleFile,
+ value: rule.sourceFile,
},
},
];
diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts
index b106396af..cccf3353b 100644
--- a/core/tools/implementations/runTerminalCommand.ts
+++ b/core/tools/implementations/runTerminalCommand.ts
@@ -36,8 +36,11 @@ import { fileURLToPath } from "node:url";
import { ToolImpl } from ".";
import {
isProcessBackgrounded,
+ markProcessAsRunning,
removeBackgroundedProcess,
-} from "../../util/processTerminalBackgroundStates";
+ removeRunningProcess,
+ updateProcessOutput,
+} from "../../util/processTerminalStates";
import { getBooleanArg, getStringArg } from "../parseArgs";
const asyncExec = util.promisify(childProcess.exec);
@@ -120,6 +123,16 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
env: getColorEnv(), // Add enhanced environment for colors
});
+ // Track this process for foreground cancellation
+ if (toolCallId && waitForCompletion) {
+ markProcessAsRunning(
+ toolCallId,
+ childProc,
+ extras.onPartialOutput,
+ terminalOutput,
+ );
+ }
+
childProc.stdout?.on("data", (data) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
@@ -127,6 +140,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
+ // Update the tracked output for potential cancellation notifications
+ if (toolCallId && waitForCompletion) {
+ updateProcessOutput(toolCallId, terminalOutput);
+ }
+
// Send partial output to UI
if (extras.onPartialOutput) {
const status = waitForCompletion
@@ -153,6 +171,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
+ // Update the tracked output for potential cancellation notifications
+ if (toolCallId && waitForCompletion) {
+ updateProcessOutput(toolCallId, terminalOutput);
+ }
+
// Send partial output to UI, status is not required
if (extras.onPartialOutput) {
extras.onPartialOutput({
@@ -182,15 +205,19 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
}
childProc.on("close", (code) => {
- // If this process has been backgrounded, clean it up from the map and return
- if (isProcessBackgrounded(toolCallId)) {
- removeBackgroundedProcess(toolCallId);
- return;
+ // Clean up process tracking
+ if (toolCallId) {
+ if (isProcessBackgrounded(toolCallId)) {
+ removeBackgroundedProcess(toolCallId);
+ return;
+ }
+ // Remove from foreground tracking if it was tracked
+ removeRunningProcess(toolCallId);
}
if (waitForCompletion) {
// Normal completion, resolve now
- if (code === 0) {
+ if (!code || code === 0) {
const status = "Command completed";
resolve([
{
@@ -234,10 +261,14 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("error", (error) => {
- // If this process has been backgrounded, clean it up from the map and return
- if (isProcessBackgrounded(toolCallId)) {
- removeBackgroundedProcess(toolCallId);
- return;
+ // Clean up process tracking
+ if (toolCallId) {
+ if (isProcessBackgrounded(toolCallId)) {
+ removeBackgroundedProcess(toolCallId);
+ return;
+ }
+ // Remove from foreground tracking if it was tracked
+ removeRunningProcess(toolCallId);
}
reject(error);
@@ -281,6 +312,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
},
);
+ // Track this process for foreground cancellation
+ if (toolCallId) {
+ markProcessAsRunning(toolCallId, childProc, undefined, "");
+ }
+
let stdout = "";
let stderr = "";
@@ -293,6 +329,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("close", (code) => {
+ // Clean up process tracking
+ if (toolCallId) {
+ removeRunningProcess(toolCallId);
+ }
+
if (code === 0) {
resolve({ stdout, stderr });
} else {
@@ -305,6 +346,10 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("error", (error) => {
+ // Clean up process tracking
+ if (toolCallId) {
+ removeRunningProcess(toolCallId);
+ }
reject(error);
});
},
diff --git a/core/tools/implementations/runTerminalCommand.test.ts b/core/tools/implementations/runTerminalCommand.vitest.ts
similarity index 75%
rename from core/tools/implementations/runTerminalCommand.test.ts
rename to core/tools/implementations/runTerminalCommand.vitest.ts
index e744ea4f1..230d482f7 100644
--- a/core/tools/implementations/runTerminalCommand.test.ts
+++ b/core/tools/implementations/runTerminalCommand.vitest.ts
@@ -1,22 +1,31 @@
-import { jest } from "@jest/globals";
+import {
+ describe,
+ it,
+ expect,
+ beforeEach,
+ afterEach,
+ afterAll,
+ vi,
+} from "vitest";
import * as childProcess from "node:child_process";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { IDE, ToolExtras } from "../..";
-import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
+import * as processTerminalStates from "../../util/processTerminalStates";
import { runTerminalCommandImpl } from "./runTerminalCommand";
+import { runTerminalCommandTool } from "../definitions/runTerminalCommand";
// We're using real child processes, so ensure these aren't mocked
-jest.unmock("node:child_process");
-jest.unmock("node:util");
+vi.unmock("node:child_process");
+vi.unmock("node:util");
describe("runTerminalCommandImpl", () => {
// Setup mocks and spies
- const mockGetIdeInfo = jest.fn();
- const mockGetWorkspaceDirs = jest.fn();
- const mockOnPartialOutput = jest.fn();
- const mockRunCommand = jest.fn();
+ const mockGetIdeInfo = vi.fn();
+ const mockGetWorkspaceDirs = vi.fn();
+ const mockOnPartialOutput = vi.fn();
+ const mockRunCommand = vi.fn();
// Use a simple approach to ensure background processes are terminated
let testPid: number | null = null;
@@ -27,15 +36,11 @@ describe("runTerminalCommandImpl", () => {
);
beforeEach(() => {
- jest.resetAllMocks();
+ vi.resetAllMocks();
// Setup backgrounded processes handling - don't mock, just make sure it's empty
- // Get any processes that might be already tracked and clear them
- const processMap = (processBackgroundStates as any)
- .processTerminalBackgroundStates;
- if (processMap && typeof processMap.clear === "function") {
- processMap.clear();
- }
+ // Clear any processes that might be already tracked
+ processTerminalStates.clearAllBackgroundProcesses();
// Setup IDE mocks
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));
@@ -73,7 +78,7 @@ describe("runTerminalCommandImpl", () => {
// Helper function to create a ToolExtras object
const createMockExtras = (
overrides: Partial<{
- onPartialOutput?: jest.Mock;
+ onPartialOutput?: any;
remoteName?: string;
}> = {},
): ToolExtras => {
@@ -90,16 +95,16 @@ describe("runTerminalCommandImpl", () => {
getWorkspaceDirs: mockGetWorkspaceDirs,
runCommand: mockRunCommand,
// Add stubs for other required IDE methods
- getIdeSettings: jest.fn(),
- getDiff: jest.fn(),
- getClipboardContent: jest.fn(),
- isTelemetryEnabled: jest.fn(),
- readFile: jest.fn(),
- writeFile: jest.fn(),
- renameFile: jest.fn(),
- deleteFile: jest.fn(),
- globFiles: jest.fn(),
- ls: jest.fn(),
+ getIdeSettings: vi.fn(),
+ getDiff: vi.fn(),
+ getClipboardContent: vi.fn(),
+ isTelemetryEnabled: vi.fn(),
+ readFile: vi.fn(),
+ writeFile: vi.fn(),
+ renameFile: vi.fn(),
+ deleteFile: vi.fn(),
+ globFiles: vi.fn(),
+ ls: vi.fn(),
};
// Create a base ToolExtras object with required properties
@@ -147,7 +152,7 @@ describe("runTerminalCommandImpl", () => {
"`;
const args = { command, waitForCompletion: true };
- const mockOutputFn = jest.fn();
+ const mockOutputFn = vi.fn();
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
// Execute the command with streaming
@@ -191,7 +196,7 @@ describe("runTerminalCommandImpl", () => {
"`;
const args = { command, waitForCompletion: false };
- const mockOutputFn = jest.fn();
+ const mockOutputFn = vi.fn();
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
const result = await runTerminalCommandImpl(args, extras);
@@ -355,25 +360,25 @@ describe("runTerminalCommandImpl", () => {
it("should handle missing workspace directory gracefully", async () => {
// Mock IDE to return empty workspace directories
- const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([]));
+ const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([]));
// Create IDE mock with empty workspace
const mockIde = {
- getIdeInfo: jest
+ getIdeInfo: vi
.fn()
.mockReturnValue(Promise.resolve({ remoteName: "local" })),
getWorkspaceDirs: mockEmptyWorkspace,
- runCommand: jest.fn(),
- getIdeSettings: jest.fn(),
- getDiff: jest.fn(),
- getClipboardContent: jest.fn(),
- isTelemetryEnabled: jest.fn(),
- readFile: jest.fn(),
- writeFile: jest.fn(),
- renameFile: jest.fn(),
- deleteFile: jest.fn(),
- globFiles: jest.fn(),
- ls: jest.fn(),
+ runCommand: vi.fn(),
+ getIdeSettings: vi.fn(),
+ getDiff: vi.fn(),
+ getClipboardContent: vi.fn(),
+ isTelemetryEnabled: vi.fn(),
+ readFile: vi.fn(),
+ writeFile: vi.fn(),
+ renameFile: vi.fn(),
+ deleteFile: vi.fn(),
+ globFiles: vi.fn(),
+ ls: vi.fn(),
};
const extras = {
@@ -402,7 +407,7 @@ describe("runTerminalCommandImpl", () => {
it("should handle case where cwd fallbacks all fail", async () => {
// Mock IDE to return empty workspace directories
- const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([]));
+ const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([]));
// Save original environment variables and process.cwd
const originalHome = process.env.HOME;
@@ -413,27 +418,27 @@ describe("runTerminalCommandImpl", () => {
// Mock all fallbacks to fail
delete process.env.HOME;
delete process.env.USERPROFILE;
- process.cwd = jest.fn().mockImplementation(() => {
+ process.cwd = vi.fn().mockImplementation(() => {
throw new Error("Current directory unavailable");
- }) as jest.MockedFunction<() => string>;
+ }) as any;
// Create IDE mock with empty workspace
const mockIde = {
- getIdeInfo: jest
+ getIdeInfo: vi
.fn()
.mockReturnValue(Promise.resolve({ remoteName: "local" })),
getWorkspaceDirs: mockEmptyWorkspace,
- runCommand: jest.fn(),
- getIdeSettings: jest.fn(),
- getDiff: jest.fn(),
- getClipboardContent: jest.fn(),
- isTelemetryEnabled: jest.fn(),
- readFile: jest.fn(),
- writeFile: jest.fn(),
- renameFile: jest.fn(),
- deleteFile: jest.fn(),
- globFiles: jest.fn(),
- ls: jest.fn(),
+ runCommand: vi.fn(),
+ getIdeSettings: vi.fn(),
+ getDiff: vi.fn(),
+ getClipboardContent: vi.fn(),
+ isTelemetryEnabled: vi.fn(),
+ readFile: vi.fn(),
+ writeFile: vi.fn(),
+ renameFile: vi.fn(),
+ deleteFile: vi.fn(),
+ globFiles: vi.fn(),
+ ls: vi.fn(),
};
const extras = {
@@ -472,3 +477,125 @@ describe("runTerminalCommandImpl", () => {
}
});
});
+
+describe("runTerminalCommandTool.evaluateToolCallPolicy", () => {
+ it("should return base policy for safe commands like echo", () => {
+ const basePolicy = "allowedWithoutPermission";
+ const args = { command: "echo hello world" };
+
+ const result = runTerminalCommandTool.evaluateToolCallPolicy!(
+ basePolicy,
+ args,
+ );
+
+ expect(result).toBe("allowedWithoutPermission");
+ });
+
+ it("should respect disabled policy even for non-echo commands", () => {
+ const basePolicy = "disabled";
+ const args = { command: "ls -la" };
+
+ const result = runTerminalCommandTool.evaluateToolCallPolicy!(
+ basePolicy,
+ args,
+ );
+
+ expect(result).toBe("disabled");
+ });
+
+ it("should respect disabled policy even for safe commands", () => {
+ const basePolicy = "disabled";
+ const args = { command: "echo test" };
+
+ const result = runTerminalCommandTool.evaluateToolCallPolicy!(
+ basePolicy,
+ args,
+ );
+
+ expect(result).toBe("disabled");
+ });
+
+ it("should return base policy for non-echo commands", () => {
+ const basePolicy = "allowedWithoutPermission";
+ const args = { command: "ls -la" };
+
+ const result = runTerminalCommandTool.evaluateToolCallPolicy!(
+ basePolicy,
+ args,
+ );
+
+ expect(result).toBe("allowedWithoutPermission");
+ });
+
+ it("should return base policy for git commands", () => {
+ const basePolicy = "allowedWithPermission";
+ const args = { command: "git status" };
+
+ const result = runTerminalCommandTool.evaluateToolCallPolicy!(
+ basePolicy,
+ args,
+ );
+
+ expect(result).toBe("allowedWithPermission");
+ });
+
+ it("should handle undefined command gracefully", () => {
+ const basePolicy = "allowedWithoutPermission";
+ const args = { command: undefined };
+
+ const result = runTerminalCommandTool.evaluateToolCallPolicy!(
+ basePolicy,
+ args,
+ );
+
+ expect(result).toBe("allowedWithoutPermission");
+ });
+
+ it("should handle null command gracefully", () => {
+ const basePolicy = "allowedWithoutPermission";
+ const args = { command: null };
+
+ const result = runTerminalCommandTool.evaluateToolCallPolicy!(
+ basePolicy,
+ args,
+ );
+
+ expect(result).toBe("allowedWithoutPermission");
+ });
+
+ it("should handle empty command string", () => {
+ const basePolicy = "allowedWithoutPermission";
+ const args = { command: "" };
+
+ const result = runTerminalCommandTool.evaluateToolCallPolicy!(
+ basePolicy,
+ args,
+ );
+
+ expect(result).toBe("allowedWithoutPermission");
+ });
+
+ it("should disable dangerous commands like rm -rf /", () => {
+ const basePolicy = "allowedWithoutPermission";
+ const args = { command: "rm -rf /" };
+
+ const result = runTerminalCommandTool.evaluateToolCallPolicy!(
+ basePolicy,
+ args,
+ );
+
+ expect(result).toBe("disabled");
+ });
+
+ it("should require permission for high-risk network commands", () => {
+ const basePolicy = "allowedWithoutPermission";
+ const args = { command: "curl http://example.com" };
+
+ const result = runTerminalCommandTool.evaluateToolCallPolicy!(
+ basePolicy,
+ args,
+ );
+
+ expect(result).toBe("allowedWithPermission");
+ });
+});
diff --git a/core/tools/implementations/viewDiff.ts b/core/tools/implementations/viewDiff.ts
index 9df82e78d..7d9b5256e 100644
--- a/core/tools/implementations/viewDiff.ts
+++ b/core/tools/implementations/viewDiff.ts
@@ -9,6 +9,17 @@ export const viewDiffImpl: ToolImpl = async (args, extras) => {
// TODO includeUnstaged should be an option
const combinedDiff = diffs.join("\n");
+
+ if (!combinedDiff.trim()) {
+ return [
+ {
+ name: "Diff",
+ description: "current Git diff",
+ content: "The current diff is empty",
+ },
+ ];
+ }
+
const diffLines = combinedDiff.split("\n");
let truncated = false;
diff --git a/core/tools/index.ts b/core/tools/index.ts
index 0277da6a7..bdc519dc9 100644
--- a/core/tools/index.ts
+++ b/core/tools/index.ts
@@ -1,4 +1,5 @@
import { ConfigDependentToolParams, Tool } from "..";
+import { isRecommendedAgentModel } from "../llm/toolSupport";
import * as toolDefinitions from "./definitions";
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
@@ -12,7 +13,6 @@ export const getBaseToolDefinitions = () => [
toolDefinitions.lsTool,
toolDefinitions.createRuleBlock,
toolDefinitions.fetchUrlContentTool,
- toolDefinitions.singleFindAndReplaceTool,
];
export const getConfigDependentToolDefinitions = (
@@ -33,13 +33,15 @@ export const getConfigDependentToolDefinitions = (
toolDefinitions.viewRepoMapTool,
toolDefinitions.viewSubdirectoryTool,
toolDefinitions.codebaseTool,
+ toolDefinitions.readFileRangeTool,
);
}
- if (modelName?.includes("claude") || modelName?.includes("gpt-5")) {
+ if (modelName && isRecommendedAgentModel(modelName)) {
tools.push(toolDefinitions.multiEditTool);
} else {
tools.push(toolDefinitions.editFileTool);
+ tools.push(toolDefinitions.singleFindAndReplaceTool);
}
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
@@ -49,3 +51,8 @@ export const getConfigDependentToolDefinitions = (
return tools;
};
+
+export function serializeTool(tool: Tool) {
+ const { preprocessArgs, evaluateToolCallPolicy, ...rest } = tool;
+ return rest;
+}
diff --git a/core/tools/mcpToolName.ts b/core/tools/mcpToolName.ts
index 6440ef5e7..30ed18cec 100644
--- a/core/tools/mcpToolName.ts
+++ b/core/tools/mcpToolName.ts
@@ -1,7 +1,12 @@
import { MCPServerStatus, MCPTool } from "..";
-
export function getMCPToolName(server: MCPServerStatus, tool: MCPTool) {
- const serverPrefix = server.name.split(" ").join("_").toLowerCase();
+ // Replace any sequence of non-alphanumeric characters with a single underscore
+ const serverPrefix = server.name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "_")
+ .replace(/^_+|_+$/g, "") // Remove leading/trailing underscores
+ .replace(/_+/g, "_"); // Replace multiple sequential underscores with single underscore
+
if (tool.name.startsWith(serverPrefix)) {
return tool.name;
}
diff --git a/core/tools/mcpToolName.vitest.ts b/core/tools/mcpToolName.vitest.ts
index ff60d5200..c49f4e852 100644
--- a/core/tools/mcpToolName.vitest.ts
+++ b/core/tools/mcpToolName.vitest.ts
@@ -5,16 +5,15 @@ import { getMCPToolName } from "./mcpToolName";
const createMcpServer = (name: string): MCPServerStatus => ({
name,
errors: [],
+ infos: [],
prompts: [],
tools: [],
resources: [],
resourceTemplates: [],
status: "connected",
id: "",
- transport: {
- type: "sse",
- url: "",
- },
+ type: "sse",
+ url: "",
isProtectedResource: false,
});
@@ -56,3 +55,54 @@ test("getMCPToolName - handles mixed case in server names", () => {
const result = getMCPToolName(server, tool);
expect(result).toBe("gitlab_create_merge_request");
});
+
+test("getMCPToolName - handles server names with special characters (parentheses)", () => {
+ const server = createMcpServer("Linear MCP (SSE)");
+ const tool = createMCPTool("create_issue");
+
+ const result = getMCPToolName(server, tool);
+ // Should only contain alphanumeric characters and underscores
+ expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
+ expect(result).toBe("linear_mcp_sse_create_issue");
+});
+
+test("getMCPToolName - handles server names with dots and other special characters", () => {
+ const server = createMcpServer("My.Server@Test!");
+ const tool = createMCPTool("test_action");
+
+ const result = getMCPToolName(server, tool);
+ // Should only contain alphanumeric characters and underscores
+ expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
+ expect(result).toBe("my_server_test_test_action");
+});
+
+test("getMCPToolName - handles server names with multiple consecutive special characters", () => {
+ const server = createMcpServer("Server@@##Name");
+ const tool = createMCPTool("action");
+
+ const result = getMCPToolName(server, tool);
+ // Should only contain alphanumeric characters and underscores (no hyphens or multiple underscores)
+ expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
+ expect(result).toBe("server_name_action");
+});
+
+test("getMCPToolName - handles server names with hyphens", () => {
+ const server = createMcpServer("My-Server-Name");
+ const tool = createMCPTool("test_action");
+
+ const result = getMCPToolName(server, tool);
+ // Should only contain alphanumeric characters and underscores
+ expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
+ expect(result).toBe("my_server_name_test_action");
+});
+
+test("getMCPToolName - handles multiple consecutive underscores in server name", () => {
+ const server = createMcpServer("Linear__MCP");
+ const tool = createMCPTool("create_issue");
+
+ const result = getMCPToolName(server, tool);
+ // Should only contain alphanumeric characters and single underscores
+ expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
+ expect(result).not.toMatch(/__/);
+ expect(result).toBe("linear_mcp_create_issue");
+});
diff --git a/core/tools/parseArgs.ts b/core/tools/parseArgs.ts
index a31267854..543e6ba53 100644
--- a/core/tools/parseArgs.ts
+++ b/core/tools/parseArgs.ts
@@ -40,6 +40,24 @@ export function getOptionalStringArg(
return getStringArg(args, argName, allowEmpty);
}
+export function getNumberArg(args: any, argName: string): number {
+ if (!args || !(argName in args)) {
+ throw new Error(`Argument \`${argName}\` is required (type number)`);
+ }
+ const value = args[argName];
+ if (typeof value === "string") {
+ const parsed = parseInt(value, 10);
+ if (isNaN(parsed)) {
+ throw new Error(`Argument \`${argName}\` must be a valid number`);
+ }
+ return parsed;
+ }
+ if (typeof value !== "number" || isNaN(value)) {
+ throw new Error(`Argument \`${argName}\` must be a valid number`);
+ }
+ return Math.floor(value); // Ensure integer for line numbers (supports negative numbers)
+}
+
export function getBooleanArg(args: any, argName: string, required = false) {
if (!args || !(argName in args)) {
if (required) {
diff --git a/core/tools/parseArgs.vitest.ts b/core/tools/parseArgs.vitest.ts
index b2cee9fc5..71bfc0cc5 100644
--- a/core/tools/parseArgs.vitest.ts
+++ b/core/tools/parseArgs.vitest.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { ToolCallDelta } from "..";
import {
getBooleanArg,
+ getNumberArg,
getOptionalStringArg,
getStringArg,
safeParseToolCallArgs,
@@ -246,3 +247,86 @@ describe("getBooleanArg", () => {
);
});
});
+
+describe("getNumberArg", () => {
+ it("should return number argument when valid", () => {
+ const args = { count: 42 };
+ const result = getNumberArg(args, "count");
+ expect(result).toBe(42);
+ });
+
+ it("should parse string numbers", () => {
+ const args = { count: "42" };
+ const result = getNumberArg(args, "count");
+ expect(result).toBe(42);
+ });
+
+ it("should floor decimal numbers", () => {
+ const args = { count: 42.7 };
+ const result = getNumberArg(args, "count");
+ expect(result).toBe(42);
+ });
+
+ it("should parse and floor string decimal numbers", () => {
+ const args = { count: "42.7" };
+ const result = getNumberArg(args, "count");
+ expect(result).toBe(42);
+ });
+
+ it("should throw error when argument is missing", () => {
+ const args = { otherArg: 42 };
+ expect(() => getNumberArg(args, "count")).toThrowError(
+ "Argument `count` is required (type number)",
+ );
+ });
+
+ it("should throw error when argument is not a number", () => {
+ const argsString = { count: "not-a-number" };
+ const argsBoolean = { count: true };
+ const argsObject = { count: {} };
+
+ expect(() => getNumberArg(argsString, "count")).toThrowError(
+ "Argument `count` must be a valid number",
+ );
+ expect(() => getNumberArg(argsBoolean, "count")).toThrowError(
+ "Argument `count` must be a valid number",
+ );
+ expect(() => getNumberArg(argsObject, "count")).toThrowError(
+ "Argument `count` must be a valid number",
+ );
+ });
+
+ it("should throw error when argument is NaN", () => {
+ const args = { count: NaN };
+ expect(() => getNumberArg(args, "count")).toThrowError(
+ "Argument `count` must be a valid number",
+ );
+ });
+
+ it("should handle negative numbers", () => {
+ const args = { count: -5 };
+ const result = getNumberArg(args, "count");
+ expect(result).toBe(-5);
+ });
+
+ it("should handle negative string numbers", () => {
+ const args = { count: "-10" };
+ const result = getNumberArg(args, "count");
+ expect(result).toBe(-10);
+ });
+
+ it("should handle zero", () => {
+ const args = { count: 0 };
+ const result = getNumberArg(args, "count");
+ expect(result).toBe(0);
+ });
+
+ it("should handle null or undefined args", () => {
+ expect(() => getNumberArg(null, "count")).toThrowError(
+ "Argument `count` is required (type number)",
+ );
+ expect(() => getNumberArg(undefined, "count")).toThrowError(
+ "Argument `count` is required (type number)",
+ );
+ });
+});
diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts
index 59daf21c9..44b9b5f11 100644
--- a/core/util/GlobalContext.ts
+++ b/core/util/GlobalContext.ts
@@ -30,6 +30,7 @@ export type GlobalContextType = {
selectedModelsByProfileId: {
[profileId: string]: GlobalContextModelSelections;
};
+ cliSelectedModel?: string; // CLI-specific model selection for unauthenticated users
/**
* This is needed to handle the case where a JetBrains user has created
@@ -44,9 +45,8 @@ export type GlobalContextType = {
isSupportedLanceDbCpuTargetForLinux: boolean;
sharedConfig: SharedConfigSchema;
failedDocs: SiteIndexingConfig[];
- shownDeprecatedProviderWarnings: {
- [providerTitle: string]: boolean;
- };
+ shownDeprecatedProviderWarnings: { [providerTitle: string]: boolean };
+ autoUpdateCli: boolean;
mcpOauthStorage: {
[serverUrl: string]: {
clientInformation?: OAuthClientInformationFull;
@@ -66,16 +66,7 @@ export class GlobalContext {
) {
const filepath = getGlobalContextFilePath();
if (!fs.existsSync(filepath)) {
- fs.writeFileSync(
- filepath,
- JSON.stringify(
- {
- [key]: value,
- },
- null,
- 2,
- ),
- );
+ fs.writeFileSync(filepath, JSON.stringify({ [key]: value }, null, 2));
} else {
const data = fs.readFileSync(filepath, "utf-8");
@@ -113,10 +104,7 @@ export class GlobalContext {
}
// Recreate the file with salvaged values plus the new value
- const newData = {
- ...salvaged,
- [key]: value,
- };
+ const newData = { ...salvaged, [key]: value };
fs.writeFileSync(filepath, JSON.stringify(newData, null, 2));
return;
@@ -174,10 +162,7 @@ export class GlobalContext {
newValues: Partial,
): SharedConfigSchema {
const currentSharedConfig = this.getSharedConfig();
- const updatedSharedConfig = {
- ...currentSharedConfig,
- ...newValues,
- };
+ const updatedSharedConfig = { ...currentSharedConfig, ...newValues };
this.update("sharedConfig", updatedSharedConfig);
return updatedSharedConfig;
}
@@ -189,10 +174,7 @@ export class GlobalContext {
): GlobalContextModelSelections {
const currentSelections = this.get("selectedModelsByProfileId") ?? {};
const forProfile = currentSelections[profileId] ?? {};
- const newSelections = {
- ...forProfile,
- [role]: title,
- };
+ const newSelections = { ...forProfile, [role]: title };
this.update("selectedModelsByProfileId", {
...currentSelections,
diff --git a/core/util/errors.ts b/core/util/errors.ts
index f80fa6b70..4c6cfb16d 100644
--- a/core/util/errors.ts
+++ b/core/util/errors.ts
@@ -10,3 +10,45 @@ export function getRootCause(err: any): any {
}
return err;
}
+
+export class ContinueError extends Error {
+ reason: ContinueErrorReason;
+
+ constructor(reason: ContinueErrorReason, message?: string) {
+ super(message);
+ this.reason = reason;
+ this.name = "ContinueError";
+ }
+}
+
+export enum ContinueErrorReason {
+ // Find and Replace validation errors
+ FindAndReplaceIdenticalOldAndNewStrings = "find_and_replace_identical_old_and_new_strings",
+ FindAndReplaceMissingOldString = "find_and_replace_missing_old_string",
+ FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string",
+ FindAndReplaceMissingNewString = "find_and_replace_missing_new_string",
+ FindAndReplaceInvalidReplaceAll = "find_and_replace_invalid_replace_all",
+ FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found",
+ FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences",
+ FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath",
+
+ // Multi-edit
+ MultiEditEditsArrayRequired = "multi_edit_edits_array_required",
+ MultiEditEditsArrayEmpty = "multi_edit_edits_array_empty",
+ MultiEditSubsequentEditsOnCreation = "multi_edit_subsequent_edits_on_creation",
+ MultiEditEmptyOldStringNotFirst = "multi_edit_empty_old_string_not_first",
+
+ // General Edit
+ EditToolFileNotRead = "edit_tool_file_not_yet_read",
+
+ // General File
+ FileAlreadyExists = "file_already_exists",
+ FileNotFound = "file_not_found",
+ FileWriteError = "file_write_error",
+ FileIsSecurityConcern = "file_is_security_concern",
+ ParentDirectoryNotFound = "parent_directory_not_found",
+
+ // Other
+ Unspecified = "unspecified", // I.e. a known error but no specific code for it
+ Unknown = "unknown", // I.e. an unexpected error
+}
diff --git a/core/util/history.ts b/core/util/history.ts
index 447249ded..02e3f8fee 100644
--- a/core/util/history.ts
+++ b/core/util/history.ts
@@ -1,6 +1,6 @@
import * as fs from "fs";
-import { Session, SessionMetadata } from "../index.js";
+import { Session, BaseSessionMetadata } from "../index.js";
import { ListHistoryOptions } from "../protocol/core.js";
import { NEW_SESSION_TITLE } from "./constants.js";
@@ -22,14 +22,14 @@ function safeParseArray(
}
export class HistoryManager {
- list(options: ListHistoryOptions): SessionMetadata[] {
+ list(options: ListHistoryOptions): BaseSessionMetadata[] {
const filepath = getSessionsListPath();
if (!fs.existsSync(filepath)) {
return [];
}
const content = fs.readFileSync(filepath, "utf8");
- let sessions = safeParseArray(content) ?? [];
+ let sessions = safeParseArray(content) ?? [];
sessions = sessions
.filter((session: any) => {
// Filter out old format
@@ -59,7 +59,7 @@ export class HistoryManager {
const sessionsListFile = getSessionsListPath();
const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8");
let sessionsList =
- safeParseArray(
+ safeParseArray(
sessionsListRaw,
"Error parsing sessions.json",
) ?? [];
@@ -118,7 +118,7 @@ export class HistoryManager {
try {
const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8");
- let sessionsList: SessionMetadata[];
+ let sessionsList: BaseSessionMetadata[];
try {
sessionsList = JSON.parse(rawSessionsList);
} catch (e) {
@@ -141,7 +141,7 @@ export class HistoryManager {
}
if (!found) {
- const sessionMetadata: SessionMetadata = {
+ const sessionMetadata: BaseSessionMetadata = {
sessionId: session.sessionId,
title: session.title,
dateCreated: String(Date.now()),
diff --git a/core/util/historyUtils.ts b/core/util/historyUtils.ts
new file mode 100644
index 000000000..fc0939c7b
--- /dev/null
+++ b/core/util/historyUtils.ts
@@ -0,0 +1,105 @@
+import fs from "fs";
+import { homedir } from "node:os";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import path from "path";
+
+import { languageForFilepath } from "../autocomplete/constants/AutocompleteLanguageInfo.js";
+import { ChatMessage, IDE } from "../index.js";
+import { renderChatMessage } from "../util/messageContent.js";
+import { getContinueGlobalPath } from "../util/paths.js";
+
+// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
+function getOffsetDatetime(date: Date): Date {
+ const offset = date.getTimezoneOffset();
+ const offsetHours = Math.floor(offset / 60);
+ const offsetMinutes = offset % 60;
+ date.setHours(date.getHours() - offsetHours);
+ date.setMinutes(date.getMinutes() - offsetMinutes);
+
+ return date;
+}
+
+function asBasicISOString(date: Date): string {
+ const isoString = date.toISOString();
+
+ return isoString.replace(/[-:]|(\.\d+Z)/g, "");
+}
+
+function reformatCodeBlocks(msgText: string): string {
+ const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
+ msgText = msgText.replace(
+ codeBlockFenceRegex,
+ (match, metadata, filename, extension) => {
+ const lang = languageForFilepath(filename);
+ return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
+ },
+ );
+ // Appease the markdown linter
+ return msgText.replace(/```\n```/g, "```\n\n```");
+}
+
+export function toMarkDown(history: ChatMessage[], time?: Date): string {
+ if (!time) {
+ time = new Date();
+ }
+ let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${time.toLocaleString()}`;
+
+ for (const msg of history) {
+ let msgText = renderChatMessage(msg);
+ if (!msgText) {
+ continue; // Skip messages without content
+ }
+
+ if (msg.role === "user" && msgText.search("```") > -1) {
+ msgText = reformatCodeBlocks(msgText);
+ }
+
+ // format messages as blockquotes
+ msgText = msgText.replace(/^/gm, "> ");
+
+ content += `\n\n#### ${
+ msg.role === "user" ? "_User_" : "_Assistant_"
+ }\n\n${msgText}`;
+ }
+ return content;
+}
+
+export async function shareSession(
+ ide: IDE,
+ history: ChatMessage[],
+ outputDir?: string,
+) {
+ const now = new Date();
+ const content = toMarkDown(history, now);
+
+ outputDir = outputDir ?? getContinueGlobalPath();
+
+ if (outputDir.startsWith("~")) {
+ outputDir = outputDir.replace(/^~/, homedir);
+ } else if (
+ outputDir.startsWith("./") ||
+ outputDir.startsWith(".\\") ||
+ outputDir === "."
+ ) {
+ const workspaceDirs = await ide.getWorkspaceDirs();
+ // Although the most common situation is to have one directory open in a
+ // workspace it's also possible to have just a file open without an
+ // associated directory or to use multi-root workspaces in which multiple
+ // folders are included. We default to using the first item in the list, if
+ // it exists.
+ const workspaceDirectory = workspaceDirs?.[0] || "";
+ outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
+ }
+
+ if (!fs.existsSync(outputDir)) {
+ fs.mkdirSync(outputDir, { recursive: true });
+ }
+
+ const dtString = asBasicISOString(getOffsetDatetime(now));
+ const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
+
+ const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
+ await ide.writeFile(fileUrl, content);
+ await ide.openFile(fileUrl);
+ return fileUrl;
+}
diff --git a/core/util/lemonadeHelper.ts b/core/util/lemonadeHelper.ts
new file mode 100644
index 000000000..ff8d4dfbc
--- /dev/null
+++ b/core/util/lemonadeHelper.ts
@@ -0,0 +1,59 @@
+import { exec } from "node:child_process";
+import { IDE } from "..";
+
+export async function isLemonadeInstalled(): Promise {
+ // On Windows, check if lemonade-server command exists
+ if (process.platform === "win32") {
+ return new Promise((resolve, _reject) => {
+ exec("where.exe lemonade-server", (error, _stdout, _stderr) => {
+ resolve(!error);
+ });
+ });
+ }
+
+ // On Linux, check if the health endpoint is accessible
+ try {
+ const response = await fetch("http://localhost:8000/api/v1/health", {
+ method: "GET",
+ signal: AbortSignal.timeout(3000), // 3 second timeout
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ return data.status === "ok";
+ }
+ return false;
+ } catch {
+ return false;
+ }
+}
+
+export async function startLocalLemonade(ide: IDE): Promise {
+ let startCommand: string | undefined;
+
+ switch (process.platform) {
+ case "linux": // Linux
+ // On Linux, direct users to start Lemonade manually
+ return ide.showToast(
+ "info",
+ "Please start Lemonade manually. Visit https://lemonade-server.ai for instructions.",
+ );
+
+ case "win32": // Windows
+ startCommand = "lemonade-server serve\n";
+ break;
+
+ default:
+ return ide.showToast(
+ "error",
+ "Cannot start Lemonade: platform not supported!",
+ );
+ }
+
+ if (startCommand) {
+ return ide.runCommand(startCommand, {
+ reuseTerminal: true,
+ terminalName: "Start Lemonade",
+ });
+ }
+}
diff --git a/core/util/messageContent.ts b/core/util/messageContent.ts
index 31c447389..5a0bc95bf 100644
--- a/core/util/messageContent.ts
+++ b/core/util/messageContent.ts
@@ -35,6 +35,21 @@ export function renderContextItems(contextItems: ContextItem[]): string {
return contextItems.map((item) => item.content).join("\n\n");
}
+export function renderContextItemsWithStatus(contextItems: any[]): string {
+ return contextItems
+ .map((item) => {
+ let result = item.content;
+
+ // If this item has a status, append it directly after the content
+ if (item.status) {
+ result += `\n[Status: ${item.status}]`;
+ }
+
+ return result;
+ })
+ .join("\n\n");
+}
+
export function normalizeToMessageParts(message: ChatMessage): MessagePart[] {
switch (message.role) {
case "user":
diff --git a/core/util/parameters.ts b/core/util/parameters.ts
index fbcdbca66..9bdb5544b 100644
--- a/core/util/parameters.ts
+++ b/core/util/parameters.ts
@@ -21,7 +21,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
transform: true,
showWhateverWeHaveAtXMs: 300,
// Experimental options: true = enabled, false = disabled, number = enabled w priority
- experimental_includeClipboard: true,
+ experimental_includeClipboard: false,
experimental_includeRecentlyVisitedRanges: true,
experimental_includeRecentlyEditedRanges: true,
experimental_includeDiff: true,
diff --git a/core/util/processTerminalBackgroundStates.test.ts b/core/util/processTerminalBackgroundStates.test.ts
deleted file mode 100644
index 03a6e3de5..000000000
--- a/core/util/processTerminalBackgroundStates.test.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import {
- markProcessAsBackgrounded,
- isProcessBackgrounded,
- removeBackgroundedProcess,
-} from "./processTerminalBackgroundStates";
-
-describe("processTerminalBackgroundStates", () => {
- beforeEach(() => {
- // Clear any backgrounded processes before each test
- const backgroundedProcesses = Array.from(
- Object.getOwnPropertySymbols(global),
- ).find(
- (symbol) => String(symbol) === "Symbol(processTerminalBackgroundStates)",
- );
-
- if (backgroundedProcesses) {
- // Reset the map by reimporting the module
- jest.resetModules();
- }
- });
-
- test("should mark a process as backgrounded", () => {
- const toolCallId = "test-123";
- markProcessAsBackgrounded(toolCallId);
- expect(isProcessBackgrounded(toolCallId)).toBe(true);
- });
-
- test("should correctly identify non-backgrounded processes", () => {
- const toolCallId = "test-123";
- const anotherToolCallId = "test-456";
-
- markProcessAsBackgrounded(toolCallId);
-
- expect(isProcessBackgrounded(toolCallId)).toBe(true);
- expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
- });
-
- test("should remove a process from backgrounded state", () => {
- const toolCallId = "test-123";
-
- markProcessAsBackgrounded(toolCallId);
- expect(isProcessBackgrounded(toolCallId)).toBe(true);
-
- removeBackgroundedProcess(toolCallId);
- expect(isProcessBackgrounded(toolCallId)).toBe(false);
- });
-
- test("should handle removing non-existent processes", () => {
- const toolCallId = "test-123";
-
- // Should not throw an error
- removeBackgroundedProcess(toolCallId);
- expect(isProcessBackgrounded(toolCallId)).toBe(false);
- });
-
- test("should handle multiple processes", () => {
- const toolCallId1 = "test-123";
- const toolCallId2 = "test-456";
- const toolCallId3 = "test-789";
-
- markProcessAsBackgrounded(toolCallId1);
- markProcessAsBackgrounded(toolCallId2);
-
- expect(isProcessBackgrounded(toolCallId1)).toBe(true);
- expect(isProcessBackgrounded(toolCallId2)).toBe(true);
- expect(isProcessBackgrounded(toolCallId3)).toBe(false);
-
- removeBackgroundedProcess(toolCallId1);
-
- expect(isProcessBackgrounded(toolCallId1)).toBe(false);
- expect(isProcessBackgrounded(toolCallId2)).toBe(true);
- });
-});
diff --git a/core/util/processTerminalBackgroundStates.ts b/core/util/processTerminalBackgroundStates.ts
deleted file mode 100644
index 437b90925..000000000
--- a/core/util/processTerminalBackgroundStates.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-// Track which processes have been backgrounded
-const processTerminalBackgroundStates = new Map();
-
-// Function to mark a process as backgrounded
-export function markProcessAsBackgrounded(toolCallId: string): void {
- processTerminalBackgroundStates.set(toolCallId, true);
-}
-
-// Function to check if a process is backgrounded
-export function isProcessBackgrounded(toolCallId: string): boolean {
- return processTerminalBackgroundStates.has(toolCallId);
-}
-
-// Function to remove a process from the backgrounded processes map
-export function removeBackgroundedProcess(toolCallId: string): void {
- processTerminalBackgroundStates.delete(toolCallId);
-}
diff --git a/core/util/processTerminalStates.test.ts b/core/util/processTerminalStates.test.ts
new file mode 100644
index 000000000..6b9e39f00
--- /dev/null
+++ b/core/util/processTerminalStates.test.ts
@@ -0,0 +1,367 @@
+import { ChildProcess } from "child_process";
+import {
+ clearAllBackgroundProcesses,
+ getAllBackgroundedProcessIds,
+ getAllRunningProcessIds,
+ getRunningProcess,
+ isProcessBackgrounded,
+ isProcessRunning,
+ killAllRunningTerminalProcesses,
+ killMultipleTerminalProcesses,
+ killTerminalProcess,
+ markProcessAsBackgrounded,
+ markProcessAsRunning,
+ removeBackgroundedProcess,
+ removeRunningProcess,
+ updateProcessOutput,
+} from "./processTerminalStates";
+
+// Mock ChildProcess
+const createMockProcess = (
+ pid: number = 123,
+ killed: boolean = false,
+): jest.Mocked => {
+ const mockProcess = {
+ pid,
+ killed,
+ kill: jest.fn(),
+ } as unknown as jest.Mocked;
+
+ // Make kill() update the killed property
+ mockProcess.kill.mockImplementation(() => {
+ (mockProcess as any).killed = true;
+ return true;
+ });
+
+ return mockProcess;
+};
+
+describe("processTerminalStates", () => {
+ beforeEach(() => {
+ // Clear all running processes
+ const runningIds = getAllRunningProcessIds();
+ runningIds.forEach((id) => removeRunningProcess(id));
+
+ // Clear all backgrounded processes
+ const backgroundedIds = getAllBackgroundedProcessIds();
+ backgroundedIds.forEach((id) => removeBackgroundedProcess(id));
+
+ // Clear all timers
+ jest.clearAllTimers();
+ });
+
+ test("should mark a process as backgrounded", () => {
+ const toolCallId = "test-123";
+ markProcessAsBackgrounded(toolCallId);
+ expect(isProcessBackgrounded(toolCallId)).toBe(true);
+ });
+
+ test("should correctly identify non-backgrounded processes", () => {
+ const toolCallId = "test-123";
+ const anotherToolCallId = "test-456";
+
+ markProcessAsBackgrounded(toolCallId);
+
+ expect(isProcessBackgrounded(toolCallId)).toBe(true);
+ expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
+ });
+
+ test("should remove a process from backgrounded state", () => {
+ const toolCallId = "test-123";
+
+ markProcessAsBackgrounded(toolCallId);
+ expect(isProcessBackgrounded(toolCallId)).toBe(true);
+
+ removeBackgroundedProcess(toolCallId);
+ expect(isProcessBackgrounded(toolCallId)).toBe(false);
+ });
+
+ test("should handle removing non-existent processes", () => {
+ const toolCallId = "test-123";
+
+ // Should not throw an error
+ removeBackgroundedProcess(toolCallId);
+ expect(isProcessBackgrounded(toolCallId)).toBe(false);
+ });
+
+ test("should handle multiple processes", () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+ const toolCallId3 = "test-789";
+
+ markProcessAsBackgrounded(toolCallId1);
+ markProcessAsBackgrounded(toolCallId2);
+
+ expect(isProcessBackgrounded(toolCallId1)).toBe(true);
+ expect(isProcessBackgrounded(toolCallId2)).toBe(true);
+ expect(isProcessBackgrounded(toolCallId3)).toBe(false);
+
+ removeBackgroundedProcess(toolCallId1);
+
+ expect(isProcessBackgrounded(toolCallId1)).toBe(false);
+ expect(isProcessBackgrounded(toolCallId2)).toBe(true);
+ });
+
+ describe("foreground process functions", () => {
+ test("should mark a process as running", () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+ const mockCallback = jest.fn();
+ const initialOutput = "initial output";
+
+ markProcessAsRunning(
+ toolCallId,
+ mockProcess,
+ mockCallback,
+ initialOutput,
+ );
+
+ expect(isProcessRunning(toolCallId)).toBe(true);
+ expect(getRunningProcess(toolCallId)).toBe(mockProcess);
+ });
+
+ test("should handle process without callback or initial output", () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+
+ markProcessAsRunning(toolCallId, mockProcess);
+
+ expect(isProcessRunning(toolCallId)).toBe(true);
+ expect(getRunningProcess(toolCallId)).toBe(mockProcess);
+ });
+
+ test("should correctly identify non-running processes", () => {
+ const toolCallId = "test-123";
+ const anotherToolCallId = "test-456";
+ const mockProcess = createMockProcess();
+
+ markProcessAsRunning(toolCallId, mockProcess);
+
+ expect(isProcessRunning(toolCallId)).toBe(true);
+ expect(isProcessRunning(anotherToolCallId)).toBe(false);
+ });
+
+ test("should update process output", () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+ const initialOutput = "initial";
+ const updatedOutput = "updated output";
+
+ markProcessAsRunning(toolCallId, mockProcess, undefined, initialOutput);
+ updateProcessOutput(toolCallId, updatedOutput);
+
+ // We can't directly test the output value, but we can ensure the function doesn't throw
+ expect(() =>
+ updateProcessOutput(toolCallId, updatedOutput),
+ ).not.toThrow();
+ });
+
+ test("should handle updating output for non-existent process", () => {
+ const toolCallId = "non-existent";
+
+ expect(() =>
+ updateProcessOutput(toolCallId, "some output"),
+ ).not.toThrow();
+ });
+
+ test("should remove a process from running state", () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+
+ markProcessAsRunning(toolCallId, mockProcess);
+ expect(isProcessRunning(toolCallId)).toBe(true);
+
+ removeRunningProcess(toolCallId);
+ expect(isProcessRunning(toolCallId)).toBe(false);
+ expect(getRunningProcess(toolCallId)).toBeUndefined();
+ });
+
+ test("should handle removing non-existent running processes", () => {
+ const toolCallId = "test-123";
+
+ expect(() => removeRunningProcess(toolCallId)).not.toThrow();
+ expect(isProcessRunning(toolCallId)).toBe(false);
+ });
+
+ test("should return undefined for non-existent running process", () => {
+ const toolCallId = "non-existent";
+
+ expect(getRunningProcess(toolCallId)).toBeUndefined();
+ });
+ });
+
+ describe("terminal command cancellation", () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ test("should cancel a running terminal command", async () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+
+ markProcessAsRunning(toolCallId, mockProcess);
+ expect(isProcessRunning(toolCallId)).toBe(true);
+
+ await killTerminalProcess(toolCallId);
+
+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(isProcessRunning(toolCallId)).toBe(false);
+ });
+
+ test("should handle cancelling non-existent process", async () => {
+ const toolCallId = "non-existent";
+
+ await expect(killTerminalProcess(toolCallId)).resolves.not.toThrow();
+ });
+
+ test("should handle cancelling already killed process", async () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess(123, true); // Already killed
+
+ markProcessAsRunning(toolCallId, mockProcess);
+
+ await killTerminalProcess(toolCallId);
+
+ expect(mockProcess.kill).not.toHaveBeenCalled();
+ });
+
+ test("should send SIGKILL after timeout if process not killed", async () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+
+ // Mock kill to not actually set killed=true for SIGTERM
+ mockProcess.kill.mockImplementation((signal) => {
+ if (signal === "SIGKILL") {
+ (mockProcess as any).killed = true;
+ }
+ return true;
+ });
+
+ markProcessAsRunning(toolCallId, mockProcess);
+
+ const cancelPromise = killTerminalProcess(toolCallId);
+
+ // Fast-forward time to trigger the timeout
+ jest.advanceTimersByTime(5000);
+
+ await cancelPromise;
+
+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGKILL");
+ });
+
+ test("should not send SIGKILL if process was already killed", async () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+
+ markProcessAsRunning(toolCallId, mockProcess);
+
+ const cancelPromise = killTerminalProcess(toolCallId);
+
+ // Fast-forward time to trigger the timeout
+ jest.advanceTimersByTime(5000);
+
+ await cancelPromise;
+
+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(mockProcess.kill).toHaveBeenCalledTimes(1); // Only SIGTERM, no SIGKILL
+ });
+ });
+
+ describe("utility functions", () => {
+ test("should get all running process IDs", () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+ const mockProcess1 = createMockProcess(123);
+ const mockProcess2 = createMockProcess(456);
+
+ markProcessAsRunning(toolCallId1, mockProcess1);
+ markProcessAsRunning(toolCallId2, mockProcess2);
+
+ const runningIds = getAllRunningProcessIds();
+ expect(runningIds).toContain(toolCallId1);
+ expect(runningIds).toContain(toolCallId2);
+ expect(runningIds).toHaveLength(2);
+ });
+
+ test("should get all backgrounded process IDs", () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+
+ markProcessAsBackgrounded(toolCallId1);
+ markProcessAsBackgrounded(toolCallId2);
+
+ const backgroundedIds = getAllBackgroundedProcessIds();
+ expect(backgroundedIds).toContain(toolCallId1);
+ expect(backgroundedIds).toContain(toolCallId2);
+ expect(backgroundedIds).toHaveLength(2);
+ });
+
+ test("should return empty arrays when no processes", () => {
+ expect(getAllRunningProcessIds()).toEqual([]);
+ expect(getAllBackgroundedProcessIds()).toEqual([]);
+ });
+
+ test("should cancel multiple terminal commands", async () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+ const mockProcess1 = createMockProcess(123);
+ const mockProcess2 = createMockProcess(456);
+
+ markProcessAsRunning(toolCallId1, mockProcess1);
+ markProcessAsRunning(toolCallId2, mockProcess2);
+
+ await killMultipleTerminalProcesses([toolCallId1, toolCallId2]);
+
+ expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(isProcessRunning(toolCallId1)).toBe(false);
+ expect(isProcessRunning(toolCallId2)).toBe(false);
+ });
+
+ test("should cancel all running terminal commands", async () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+ const mockProcess1 = createMockProcess(123);
+ const mockProcess2 = createMockProcess(456);
+
+ markProcessAsRunning(toolCallId1, mockProcess1);
+ markProcessAsRunning(toolCallId2, mockProcess2);
+
+ const cancelledIds = await killAllRunningTerminalProcesses();
+
+ expect(cancelledIds).toContain(toolCallId1);
+ expect(cancelledIds).toContain(toolCallId2);
+ expect(cancelledIds).toHaveLength(2);
+ expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(isProcessRunning(toolCallId1)).toBe(false);
+ expect(isProcessRunning(toolCallId2)).toBe(false);
+ });
+
+ test("should return empty array when no running commands to cancel", async () => {
+ const cancelledIds = await killAllRunningTerminalProcesses();
+ expect(cancelledIds).toEqual([]);
+ });
+
+ test("should clear all background processes", () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+
+ markProcessAsBackgrounded(toolCallId1);
+ markProcessAsBackgrounded(toolCallId2);
+
+ expect(getAllBackgroundedProcessIds()).toHaveLength(2);
+
+ clearAllBackgroundProcesses();
+
+ expect(getAllBackgroundedProcessIds()).toEqual([]);
+ expect(isProcessBackgrounded(toolCallId1)).toBe(false);
+ expect(isProcessBackgrounded(toolCallId2)).toBe(false);
+ });
+ });
+});
diff --git a/core/util/processTerminalStates.ts b/core/util/processTerminalStates.ts
new file mode 100644
index 000000000..cad243a82
--- /dev/null
+++ b/core/util/processTerminalStates.ts
@@ -0,0 +1,119 @@
+import { ChildProcess } from "child_process";
+
+// Track which processes have been backgrounded
+const processTerminalBackgroundStates = new Map();
+
+// Track which foreground processes are currently running
+interface RunningProcessInfo {
+ process: ChildProcess;
+ onPartialOutput?: (params: {
+ toolCallId: string;
+ contextItems: any[];
+ }) => void;
+ currentOutput: string;
+}
+
+const processTerminalForegroundStates = new Map();
+
+// Background process functions (existing)
+export function markProcessAsBackgrounded(toolCallId: string): void {
+ processTerminalBackgroundStates.set(toolCallId, true);
+}
+
+export function isProcessBackgrounded(toolCallId: string): boolean {
+ return processTerminalBackgroundStates.has(toolCallId);
+}
+
+export function removeBackgroundedProcess(toolCallId: string): void {
+ processTerminalBackgroundStates.delete(toolCallId);
+}
+
+// Foreground process functions (new)
+export function markProcessAsRunning(
+ toolCallId: string,
+ process: ChildProcess,
+ onPartialOutput?: (params: {
+ toolCallId: string;
+ contextItems: any[];
+ }) => void,
+ currentOutput: string = "",
+): void {
+ processTerminalForegroundStates.set(toolCallId, {
+ process,
+ onPartialOutput,
+ currentOutput,
+ });
+}
+
+export function isProcessRunning(toolCallId: string): boolean {
+ return processTerminalForegroundStates.has(toolCallId);
+}
+
+export function getRunningProcess(
+ toolCallId: string,
+): ChildProcess | undefined {
+ const info = processTerminalForegroundStates.get(toolCallId);
+ return info?.process;
+}
+
+export function updateProcessOutput(toolCallId: string, output: string): void {
+ const info = processTerminalForegroundStates.get(toolCallId);
+ if (info) {
+ info.currentOutput = output;
+ }
+}
+
+export function removeRunningProcess(toolCallId: string): void {
+ processTerminalForegroundStates.delete(toolCallId);
+}
+
+export async function killTerminalProcess(toolCallId: string): Promise {
+ const processInfo = processTerminalForegroundStates.get(toolCallId);
+ if (processInfo && !processInfo.process.killed) {
+ const { process } = processInfo;
+
+ process.kill("SIGTERM");
+
+ // Force kill after 5 seconds if still running
+ setTimeout(() => {
+ if (!process.killed) {
+ process.kill("SIGKILL");
+ }
+ }, 5000);
+
+ processTerminalForegroundStates.delete(toolCallId);
+ }
+}
+
+// Function to cancel multiple terminal commands at once
+export async function killMultipleTerminalProcesses(
+ toolCallIds: string[],
+): Promise {
+ const cancelPromises = toolCallIds.map((toolCallId) =>
+ killTerminalProcess(toolCallId),
+ );
+ await Promise.all(cancelPromises);
+}
+
+// Function to cancel ALL currently running terminal commands
+export async function killAllRunningTerminalProcesses(): Promise {
+ const runningIds = getAllRunningProcessIds();
+ if (runningIds.length > 0) {
+ await killMultipleTerminalProcesses(runningIds);
+ }
+ return runningIds; // Return the IDs that were cancelled
+}
+
+// Utility functions
+export function getAllRunningProcessIds(): string[] {
+ return Array.from(processTerminalForegroundStates.keys());
+}
+
+export function getAllBackgroundedProcessIds(): string[] {
+ return Array.from(processTerminalBackgroundStates.keys());
+}
+
+// Utility function for testing - clears all background process states
+export function clearAllBackgroundProcesses(): void {
+ processTerminalBackgroundStates.clear();
+}
diff --git a/docs/CONTRIBUTING.mdx b/docs/CONTRIBUTING.mdx
new file mode 100644
index 000000000..33cd1ac17
--- /dev/null
+++ b/docs/CONTRIBUTING.mdx
@@ -0,0 +1,318 @@
+---
+title: "Contributing to Continue Documentation"
+sidebarTitle: "Docs Contributions"
+description: "Welcome to the Continue documentation! We're excited that you want to contribute. This guide will help you get started with our documentation workflow and tools."
+---
+
+## π Quick Start
+
+### Prerequisites
+
+1. **Node.js** (v20 or higher)
+2. **Git** for version control
+3. **GitHub CLI** - Install from [cli.github.com](https://cli.github.com/)
+
+### Setup Steps
+
+1. **Fork and clone the repository**
+
+ ```bash
+ # Fork the repository (this will also clone it locally)
+ gh repo fork continuedev/continue
+ cd continue/docs
+ ```
+
+2. **Install dependencies**
+
+ ```bash
+ npm install
+ ```
+
+3. **Start the local development server**
+ ```bash
+ npm run dev
+ ```
+ Your docs will be available at `http://localhost:3000`
+
+## π¬ Creating Discussions and Issues
+
+Before creating any issues, we ask that you start with a GitHub Discussion. This helps us organize feedback and determine the best path forward.
+
+### Starting a Discussion
+
+
+
+ Visit the [Continue GitHub Discussions](https://github.com/continuedev/continue/discussions) page.
+
+
+
+ Select the **Docs** category for documentation improvements, corrections, or suggestions.
+
+
+
+
+ Include the following in your discussion:
+ - Clear description of the issue or suggestion
+ - Steps to reproduce (if applicable)
+ - Expected vs. actual behavior
+ - Screenshots or code examples when helpful
+ - Your environment (OS, IDE, Continue version)
+
+
+
+### Issue Escalation Process
+
+
+
+ **Important**: All issues should start as discussions. The Continue team will determine if and when a discussion should be escalated to a GitHub issue.
+
+
+
+The Continue team will review discussions and may:
+- Provide a solution or clarification directly in the discussion
+- Ask for additional information or testing
+- Convert the discussion to an issue if it requires code changes or is a confirmed bug
+- Close the discussion if it's resolved or not actionable
+
+### When Discussions Become Issues
+
+A discussion will typically be converted to an issue when:
+- A bug in the documentation is confirmed
+- A new feature or significant documentation change is approved
+- Community consensus supports the proposed change
+- Technical implementation is required
+
+## π€ AI-Powered Documentation with Continue
+
+We strongly encourage using Continue's AI assistance to maintain consistency and quality in our documentation. Here are three ways to set this up:
+
+### Option 1: Use the Pre-Built Documentation Agent (Recommended)
+
+The easiest way to get started is using our pre-configured documentation agent:
+
+
+
+ Visit [the Docs Assistant - Mintlify in the Hub](https://hub.continue.dev/continuedev/docs-mintlify) and click "Install" to add it to your Continue setup. This agent comes pre-configured with all our documentation standards.
+
+
+ Learn more about Continue Agents in our [agent documentation](/guides/understanding-agents).
+
+
+
+
+
+
+ ```bash
+ # Install the Continue CLI if you haven't already
+ npm install -g @continuedev/cli
+
+ # Use the agent from the command line
+ cn "Create a new guide for using the Continue CLI with Linear" --config continuedev/docs-mintlify
+ ```
+
+
+
+ 1. Open Continue in your IDE
+ 2. Select the "Docs Assistant - Mintlify" agent from the model dropdown
+ 3. Ask it to help you create or edit documentation
+
+ Example prompts:
+ - "Create a new guide for using the Continue CLI with Linear"
+ - "Update the getting-started guide with the new installation process"
+ - "Format this documentation according to Mintlify standards"
+
+
+
+
+
+
+You can also remix this agent to customize it for your specific needs. Learn how to create your own remix in our [remix agent documentation](/hub/agents/create-an-agent#how-to-remix-an-agent).
+
+
+### Option 2: Create Your Own Custom Agent
+
+If you want more control or customization, you can create your own documentation agent:
+
+
+
+ Follow our [agent creation guide](/hub/agents/create-an-agent) to set up your own agent.
+
+
+
+ Install from Continue Hub: https://hub.continue.dev/continuedev/continue-docs-mcp
+
+ This MCP provides context about Continue's documentation structure and standards.
+
+
+
+ Install from Continue Hub: https://hub.continue.dev/mintlify/technical-writing-rule
+
+ This rule ensures proper Mintlify component formatting.
+
+
+
+
+
+ ```bash
+ # Install the Continue CLI if you haven't already
+ npm install -g @continuedev/cli
+
+ # Use your agent from the command line
+ cn --config your-org/your-agent-name "Create a new guide for API authentication"
+ ```
+
+
+
+ 1. Open Continue in your IDE
+ 2. Select your custom agent from the model dropdown
+ 3. Ask it to help you create or edit documentation
+
+ Example prompts:
+ - "Help me format this documentation according to Mintlify standards"
+ - "Create a troubleshooting section for this feature"
+
+
+
+
+
+## π Documentation Standards
+
+### Mintlify Component Guidelines
+
+When using Mintlify components, follow these formatting rules:
+
+#### Cards and Info Boxes
+
+```mdx
+
+
+Always include blank lines and proper indentation:
+
+- Use 2-space indentation
+- Add blank lines after opening tags
+- Format lists as bullet points
+
+
+```
+
+#### Warning and Note Components
+
+```mdx
+
+
+Important information should be formatted clearly:
+
+- Each point on its own line
+- Consistent indentation
+- Clear, concise language
+
+
+```
+
+### Writing Style
+
+1. **Be concise**: Get to the point quickly
+2. **Use examples**: Show, don't just tell
+3. **Include code blocks**: Provide working examples
+4. **Add visuals**: Screenshots and diagrams help understanding
+5. **Test your changes**: Ensure all links and code examples work
+
+
+If you are creating a new guide, please test the steps yourself to ensure accuracy.
+
+
+## π§ Common Tasks
+
+### Adding a New Guide
+
+1. Create a new `.mdx` file in the guides directory
+2. Add frontmatter:
+ ```mdx
+ ---
+ title: "Your Guide Title"
+ description: "Brief description of what this guide covers"
+ ---
+ ```
+3. Use the Continue agent to help format your content
+4. Update `docs.json` to include your new page in the navigation
+
+
+We have both guides and cookbooks. Use guides for step-by-step instructions and cookbooks for creating agents for the CLI.
+
+
+### Updating Existing Documentation
+
+1. Use the Continue agent with prompts like:
+ - "Update the installation guide with the new npm package"
+ - "Add a troubleshooting section for connection issues"
+2. The agent will maintain consistent formatting automatically
+
+### Adding Code Examples
+
+Use language-specific code blocks:
+
+````mdx
+```typescript
+// Your TypeScript code here
+const example = "Hello, Continue!";
+```
+````
+
+## π Testing Your Changes
+
+1. **Local preview**: In the docs directory, run `npm run dev` and check your changes
+2. **Link validation**: Ensure all internal and external links work
+3. **Format check**: Use the Continue agent to validate Mintlify formatting
+4. **Build test**: Run `npm run build` to ensure no build errors
+
+## π€ Submitting Your Contribution
+
+1. **Create a feature branch**
+
+ ```bash
+ git checkout -b docs/your-feature-name
+ ```
+
+2. **Commit your changes**
+
+ ```bash
+ git add .
+ git commit -m "docs: describe your changes"
+ ```
+
+3. **Push and create a Pull Request**
+
+ ```bash
+ # Push to your fork and create a PR
+ git push origin docs/your-feature-name
+ gh pr create --web
+ ```
+
+
+
+ The `gh pr create` command will automatically:
+ - Push your branch to your fork
+ - Create a pull request to the main repository
+ - Allow you to add a title, description, and reference issues
+ - Open the PR in your browser if using `--web`
+
+
+
+## π‘ Tips for Success
+
+- **Use the Continue agent**: It knows our documentation standards and will save you time
+- **Preview frequently**: Check your changes in the local dev server
+- **Ask questions**: Open an issue or discussion if you need clarification
+- **Small PRs are better**: Focus on one topic or fix per PR
+- **Update examples**: Ensure code examples reflect the latest API
+
+
+## π Getting Help
+
+- **Start a Discussion**: Use [GitHub Discussions](https://github.com/continuedev/continue/discussions) for documentation issues, suggestions, or questions
+- **Continue agent questions**: Check the [Continue Hub page](https://hub.continue.dev/continuedev/docs-mintlify)
+- **Discord community**: Join our Discord for real-time help
+- **Existing docs**: Review similar pages for formatting examples
+---
+
+Thank you for contributing to Continue! Your efforts help make our documentation better for everyone. To learn more about contibuting to other parts of the project, check out our [main CONTRIBUTING guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md) π
diff --git a/docs/chat/how-to-use-it.mdx b/docs/chat/how-to-use-it.mdx
index 3acf5f1b5..94257fdb7 100644
--- a/docs/chat/how-to-use-it.mdx
+++ b/docs/chat/how-to-use-it.mdx
@@ -2,7 +2,7 @@
title: "Chat"
sidebarTitle: "How To Use AI Chat"
icon: "circle-question"
-description: "Learn how to use Continue's AI chat assistant to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models"
+description: "Learn how to use Continue's AI chat agent to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models"
---
diff --git a/docs/cli/install.mdx b/docs/cli/install.mdx
new file mode 100644
index 000000000..d9d0db43a
--- /dev/null
+++ b/docs/cli/install.mdx
@@ -0,0 +1,134 @@
+---
+title: "Install Continue CLI"
+description: "Get Continue CLI installed and configured for command-line AI coding assistance and automation"
+sidebarTitle: "Install"
+---
+
+
+ Make sure you have [Node.js 18 or higher
+ installed](https://nodejs.org/en/download/).
+
+
+## Installation
+
+Install Continue CLI globally using npm:
+
+```bash
+npm i -g @continuedev/cli
+```
+
+## Two Ways to Use Continue CLI
+
+
+ **Quick Overview**: Continue CLI works in two modes - TUI for interactive
+ conversations or headless for automated commands.
+
+
+
+
+**Interactive development sessions**
+
+Start a conversation with AI in your terminal:
+
+```bash
+cn
+> @src/app.js Generate unit tests for this component
+```
+
+Perfect for exploration, debugging, and iterative development.
+
+
+
+
+**Automation and scripting**
+
+Single commands that return results:
+
+```bash
+cn -p "Generate a commit message for current changes"
+cn -p "Review the last 5 commits for issues"
+```
+
+Perfect for CI/CD, git hooks, and automated workflows.
+
+
+
+
+## Setup
+
+
+
+
+For interactive development and exploration:
+
+
+
+```bash
+cn login
+```
+This will open your browser to authenticate with Continue Hub.
+
+
+
+Start an interactive session:
+```bash
+cn
+```
+
+Try asking a question:
+
+```
+> Tell me about the CLI
+```
+
+
+
+
+
+
+For automation workflows and scripting:
+
+
+
+For automation workflows, get an API key:
+1. Visit [Continue Hub API Keys](https://hub.continue.dev/settings/api-keys)
+2. Click **"+ New API Key"**
+3. Copy the API key immediately (you won't see it again!)
+4. Login using your Continue account
+
+
+
+Store secure credentials for CLI workflows:
+1. Visit [Continue Hub Secrets](https://hub.continue.dev/settings/secrets)
+2. Add your API keys and sensitive data
+3. Reference in configurations with `${{ secrets.SECRET_NAME }}`
+
+
+
+Try headless mode for automation:
+```bash
+cn -p "Generate a conventional commit message for the current git changes"
+```
+
+
+
+
+
+## What's Next?
+
+
+
+ Learn basic usage with practical examples
+
+
+
+ Build automated workflows with Continue CLI
+
+
+
+## Getting Help
+
+If you encounter issues:
+
+- Ask for help in [our discussions](https://github.com/continuedev/continue/discussions)
+- Report bugs on [GitHub](https://github.com/continuedev/continue)
diff --git a/docs/cli/overview.mdx b/docs/cli/overview.mdx
new file mode 100644
index 000000000..a94bfdce5
--- /dev/null
+++ b/docs/cli/overview.mdx
@@ -0,0 +1,228 @@
+---
+title: "Continue CLI (cn) Overview"
+description: "Command-line interface for automated coding tasks, scripting, and headless development workflows with Continue's AI coding capabilities"
+sidebarTitle: "Overview"
+---
+
+
+
+
+
+**Continue enables developers to ship faster with Continuous AI.**
+
+
+ Build features from descriptions. Debug and fix issues. Navigate any codebase.
+ Automate tedious tasks.
+
+
+## Get started in 30 seconds
+
+Prerequisites:
+
+- [Node.js 18 or newer](https://nodejs.org/en/download/)
+- A [Continue Hub](https://hub.continue.dev) account (recommended) or local configuration
+
+```bash npm
+# Install Continue CLI
+npm install -g @continuedev/cli
+
+# Navigate to your project
+
+cd your-awesome-project
+
+# Start coding with Continue
+
+cn
+
+# You'll be prompted to set up on first use
+
+```
+
+That's it! You're ready to start automating with Continue CLI.
+
+[Continue with CLI Quickstart β](/cli/quick-start)
+
+## Two Ways to Use Continue CLI
+
+Continue CLI offers two distinct modes designed for different workflows:
+
+### TUI Mode: Interactive Development
+
+**Perfect for exploration, debugging, and iterating on AI workflows**
+
+```bash
+cn
+> @src/components/UserProfile.js Review this component for security issues
+> Generate comprehensive unit tests
+> Suggest performance improvements
+```
+
+- **Interactive conversations** with your codebase
+- **Iterate and refine** prompts and approaches
+- **Explore and understand** complex codebases
+- **Perfect for experimentation** and learning
+
+### Headless Mode: Production Automation
+
+**Perfect for CI/CD, automation, and reliable workflows**
+
+```bash
+cn -p "Generate a conventional commit message for staged changes"
+cn -p "Review pull request changes for security vulnerabilities"
+cn -p "Update documentation based on recent code changes"
+```
+
+- **Single-command execution** for automation
+- **Reliable, repeatable results** for production use
+- **CI/CD and pipeline integration**
+- **Git hooks and automated workflows**
+
+### Development Workflow: TUI β Headless
+
+
+ **Pro Tip**: Start in TUI mode to iterate on your AI agent and prompts. Once
+ you have a workflow that works reliably, deploy it as a Continuous AI
+ automation.
+
+
+1. **Experiment in TUI mode** to perfect your prompts and agent configuration
+2. **Test different approaches** interactively until you get consistent results
+3. **Convert successful workflows** to automated Continuous AI commands
+4. **Deploy in production** with confidence in your proven approach
+
+## Why developers love Continue CLI
+
+- **Works in your terminal**: Not another chat window. Not another IDE. Continue CLI meets you where you already work, with the tools you already love.
+- **Takes action**: Continue CLI can directly edit files, run commands, and create commits. Need more? Check out our [MCPs](/customize/deep-dives/mcp).
+- **Automate tasks**: Create issues from PostHog data, automatically assign labels to issues, and more. Do all this in a single command from your developer machines, or automatically in CI.
+- **Flexible development flow**: Start interactive, then automate proven workflows.
+
+## Key Capabilities
+
+### Context Engineering
+
+- Use `@` to reference files and provide context
+- Use `/` to run slash commands for specific tasks
+- Access the same context providers as IDE extensions
+
+### Tool Integration
+
+- File editing and creation
+- Terminal command execution
+- Codebase understanding and analysis
+- Git integration
+- Web search and documentation access
+
+### Model Flexibility
+
+- Switch between models with `/model` command
+- Use any model configured in your `config.yaml`
+- Access Continue Hub models and configurations
+
+## Continue Hub Integration
+
+Continue CLI integrates seamlessly with [Continue Hub](https://hub.continue.dev) for:
+
+### API Access
+
+Get an API key for automation workflows:
+
+1. Visit [Continue Hub API Keys](https://hub.continue.dev/settings/api-keys)
+2. Create a new API key
+3. Use with `cn login` or in your automation scripts
+
+### Secrets Management
+
+Store secure credentials for CLI workflows:
+
+1. Visit [Continue Hub Secrets](https://hub.continue.dev/settings/secrets)
+2. Add your API keys and sensitive data
+3. Reference in configurations with `${{ secrets.SECRET_NAME }}`
+
+### Configuration Sync
+
+- Cloud-managed configurations automatically sync
+- Share configurations across team members
+- Version control for your AI workflows
+
+## Common Use Cases
+
+### TUI Mode Examples
+
+**Interactive development and exploration:**
+
+
+```bash Codebase Exploration
+# Start interactive session
+cn
+> @src/components Find all unused React components
+> /explain How does authentication work in this codebase?
+> @auth/ What security patterns are used here?
+```
+
+```bash Iterative Debugging
+# Debug issues interactively
+cn
+> @tests/auth.test.js This test is failing, help me understand why
+> @src/auth/middleware.js Let's examine this middleware
+> /debug What could be causing the timeout error?
+```
+
+```bash Workflow Development
+# Develop and test automation workflows
+cn
+> @package.json @CHANGELOG.md Generate a release notes template
+> # Test and refine the approach
+> # Once working, convert to: cn -p "Generate release notes"
+```
+
+
+
+### Headless Mode Examples
+
+**Production automation and scripting:**
+
+
+```bash Git Automation
+# Generate commit messages
+cn -p "Generate a conventional commit message for the current changes"
+
+# Code review automation
+
+cn -p "Review the current git changes for bugs and suggest improvements"
+
+````
+
+```bash CI/CD Integration
+# In your pipeline scripts
+cn -p "Analyze test failures and suggest fixes"
+
+# Automated documentation updates
+cn -p "@README.md Update this documentation based on recent changes"
+````
+
+```bash Issue Management
+# Create GitHub issues from PostHog data
+cn -p "@posthog-data.json Create GitHub issues for UX problems found in this session data"
+
+# Automated security audits
+cn -p "Scan the codebase for potential security vulnerabilities"
+```
+
+
+
+## Next steps
+
+
+
+ Learn basic commands and common workflows
+
+
+
+ Install Continue CLI and set up your environment
+
+
+
+ Task-specific tutorials and examples
+
+
diff --git a/docs/cli/quick-start.mdx b/docs/cli/quick-start.mdx
new file mode 100644
index 000000000..79a481ecd
--- /dev/null
+++ b/docs/cli/quick-start.mdx
@@ -0,0 +1,176 @@
+---
+title: "Continue CLI Quick Start"
+description: "Get hands-on experience with Continue CLI through practical examples and common use cases"
+sidebarTitle: "Quick Start"
+---
+
+Get hands-on experience with Continue CLI through practical development workflows.
+
+
+
+ TUI Mode (`cn` command) is for **large development tasks** that require
+ agentic workflows with human oversight. Perfect for complex refactors,
+ feature implementation, or one-off automation tasks that need monitoring and
+ iteration.
+
+
+ Headless Mode (`-p` flag) is for **reliable, repeatable tasks** that no
+ longer need constant supervision. Perfect for CI/CD pipelines, git hooks,
+ and automated workflows you've already tested and refined.
+
+
+
+## TUI Mode: Large Development Tasks
+
+Make sure you have [Continue CLI installed](/cli/install) and are in a project directory.
+
+### Example: Implementing a New Feature
+
+```bash
+# Navigate to your project directory
+cd your-awesome-project
+
+# Start TUI Mode for complex development work
+cn
+```
+
+**Example workflow for adding authentication:**
+
+```
+> I need to add JWT authentication to this Express app. Let me start by showing you the current structure.
+
+> @src/app.js @package.json Here's my current setup. Can you implement JWT auth with middleware, login/register routes, and user model?
+
+> [Agent analyzes codebase and implements auth system]
+> [You review changes, test, and provide feedback]
+> [Agent iterates based on your input until the feature is complete]
+```
+
+### Example: Complex Refactoring
+
+```bash
+cn
+```
+
+**Refactoring a monolithic component:**
+
+```
+> @src/components/Dashboard.jsx This component is 800 lines and does too much. Help me break it into smaller, reusable components.
+
+> [Agent analyzes component structure]
+> [Proposes component breakdown strategy]
+> [You approve approach]
+> [Agent implements the refactor with proper props and state management]
+> [You test and request adjustments]
+```
+
+### When to Use TUI Mode
+
+β
**Large development tasks** that need oversight
+β
**Complex refactors** requiring multiple steps
+β
**New feature implementation** with unknowns
+β
**One-off automation tasks** you haven't done before
+β
**Debugging complex issues** that need exploration
+
+## Headless Mode: Automated Workflows
+
+Once you've refined a workflow in TUI Mode, convert it to Continuous AI for automation.
+
+### Example: From REPL β Continuous AI
+
+**Step 1: Develop in TUI Mode**
+
+```bash
+cn
+> @package.json @CHANGELOG.md Generate release notes for version 2.1.0
+> [Test and refine the prompt until it works perfectly]
+```
+
+**Step 2: Convert to Continuous AI**
+
+```bash
+# Now use the refined workflow in automation
+cn -p "Generate release notes for the current version based on package.json and recent commits"
+```
+
+### Common Continuous AI Workflows
+
+```bash
+# Git automation
+cn -p "Generate a conventional commit message for staged changes"
+cn -p "Review the last 3 commits for potential issues"
+
+# Code quality
+cn -p "Fix all TypeScript errors in the src/ directory"
+cn -p "Update outdated dependencies and fix breaking changes"
+
+# Documentation
+cn -p "@README.md Update documentation based on recent changes"
+cn -p "Generate API documentation from JSDoc comments"
+
+# CI/CD integration
+cn -p "Analyze test failures and create GitHub issue with findings"
+cn -p "Update version numbers and create release branch"
+```
+
+### When to Use Headless Mode
+
+β
**Proven workflows** you've tested in TUI Mode
+β
**Repetitive tasks** that no longer need oversight
+β
**CI/CD automation** in pipelines
+β
**Git hooks** for automated checks
+β
**Scheduled tasks** that run unattended
+
+### Available Slash Commands
+
+Common slash commands available in CLI:
+
+- `/clear` - Clear the chat history
+- `/compact` - Summarize chat history into a compact form
+- `/config` - Switch configuration or organization
+- `/exit` - Exit the chat
+- `/fork` - Start a forked chat session from the current history
+- `/help` - Show help message
+- `/info` - Show session information
+- `/init` - Create an AGENTS.md file
+- `/login` - Authenticate with your account
+- `/logout` - Sign out of your current session
+- `/mcp` - Manage MCP server connections
+- `/model` - Switch between available chat models
+- `/resume` - Resume a previous chat session
+- `/whoami` - Check who you're currently logged in as
+
+Use `/help` to see all available commands.
+
+## The Development Workflow
+
+
+ **Recommended Approach**: Start complex tasks in TUI Mode to iterate and
+ refine your approach. Once you have a reliable workflow, convert it to
+ Headless Mode for automation.
+
+
+### Workflow Pattern
+
+1. **π¬ Experiment in TUI Mode**
+
+ - Try complex development tasks with human oversight
+ - Iterate on prompts and approaches until they work reliably
+ - Test edge cases and refine the agent's behavior
+
+2. **β‘ Automate with Continuous AI**
+ - Convert proven REPL workflows to single commands
+ - Deploy in CI/CD, git hooks, or scheduled tasks
+ - Run with confidence knowing the approach is tested
+
+## Next Steps
+
+
+
+ Build an automated PostHog to GitHub issues workflow
+
+
+
+ Learn to build and deploy AI-powered development workflows
+
+
diff --git a/docs/customization/models.mdx b/docs/customization/models.mdx
index 779cf0f07..1060b3867 100644
--- a/docs/customization/models.mdx
+++ b/docs/customization/models.mdx
@@ -65,10 +65,10 @@ Read more about [model roles](/customize/model-roles), [model capabilities](/cus
3. Add `GEMINI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
4. Click `Reload config` in the agent selector in the Continue IDE extension
-[Grok 4](https://hub.continue.dev/xai/grok-4) from xAI
+[Grok Code Fast 1](https://hub.continue.dev/xai/grok-code-fast-1) from xAI
1. Get your API key from [xAI](https://console.x.ai/)
-2. Add [Grok 4](https://hub.continue.dev/xai/grok-4) to an agent on Continue Hub
+2. Add [Grok Code Fast 1](https://hub.continue.dev/xai/grok-code-fast-1) to an agent on Continue Hub
3. Add `XAI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
4. Click `Reload config` in the agent selector in the Continue IDE extension
diff --git a/docs/customization/overview.mdx b/docs/customization/overview.mdx
index 1889806d6..cd01670e9 100644
--- a/docs/customization/overview.mdx
+++ b/docs/customization/overview.mdx
@@ -1,6 +1,6 @@
---
title: "Customization Overview"
-description: "Learn how to customize Continue with model providers, context providers, slash commands, and tools to create your perfect AI coding assistant"
+description: "Learn how to customize Continue with model providers, context providers, slash commands, and tools to create your perfect AI coding agent"
---
Continue can be deeply customized to fit your specific development workflow and preferences. This guide covers the main ways you can customize Continue to enhance your coding experience.
@@ -15,21 +15,21 @@ Different Continue features can use different models. We call these _model roles
## Create a Slash Command
-Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/deep-dives/slash-commands).
+Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/deep-dives/prompts).
## Call External Tools and Functions
Unchain your LLM with the power of tools using [Agent](/features/agent/quick-start). Add custom tools using [MCP Servers](/customization/mcp-tools)
-Whatever you choose, you'll probably start by editing your Assistant.
+Whatever you choose, you'll probably start by editing your Agent.
-## Edit Your Assistant
+## Edit Your Agent
-You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon.
+You can easily access your agent configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Agent selector above the main chat input. Then, you can hover over an agent and click the `new window` (hub agents) or `gear` (local agents) icon.
-
+
-## Manage Your Assistant
+## Manage Your Agent
-- See [Editing Hub Assistants](/hub/assistants/edit-an-assistant) for more details on managing your hub assistant
-- See the [Config Deep Dive](/reference) for more details on configuring local assistants.
+- See [Editing Hub Agents](/hub/agents/edit-an-agent) for more details on managing your hub agent
+- See the [Config Deep Dive](/reference) for more details on configuring local agents.
diff --git a/docs/customization/prompts.mdx b/docs/customization/prompts.mdx
index cf229284d..8b41a2e56 100644
--- a/docs/customization/prompts.mdx
+++ b/docs/customization/prompts.mdx
@@ -13,4 +13,6 @@ description: "These are the specialized instructions that shape how models respo
## Learn More
-Prompts have the same syntax as [prompt files](/customization/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).
+- [Explore prompts](https://hub.continue.dev/?type=prompts) on the Hub
+- Learn more in the [prompts deep dive](/customize/deep-dives/prompts)
+- View [`prompts`](/reference#prompts) in the YAML Reference for more details
diff --git a/docs/customization/rules.mdx b/docs/customization/rules.mdx
index 37ab76ff9..e685e8303 100644
--- a/docs/customization/rules.mdx
+++ b/docs/customization/rules.mdx
@@ -1,18 +1,42 @@
---
title: "Rules"
-description: "Rules allow you to provide specific instructions that guide how the AI assistant behaves when working with your code. Instead of the AI making assumptions about your coding standards, architecture patterns, or project-specific requirements, you can explicitly define guidelines that ensure consistent, contextually appropriate responses."
+description: "Rules allow you to provide specific instructions that guide how the AI agent behaves when working with your code. Instead of the AI making assumptions about your coding standards, architecture patterns, or project-specific requirements, you can explicitly define guidelines that ensure consistent, contextually appropriate responses."
---
-Think of these as the guardrails for your AI coding assistants:
+Think of these as the guardrails for your AI coding agents:
- **Enforce company-specific coding standards** and security practices
- **Implement quality checks** that match your engineering culture
- **Create paved paths** for developers to follow organizational best practices
-By implementing rules, you transform the AI from a generic coding assistant into a knowledgeable team member that understands your project's unique requirements and constraints.
+By implementing rules, you transform the AI from a generic coding agent into a knowledgeable team member that understands your project's unique requirements and constraints.
## How Rules Work
-Your assistant detects rules and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes.
+Your agent detects rules and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes.
+
+## Where to Manage Rules
+
+
+
+- Create files in `.continue/rules` folder
+- Automatically appear with Hub assistants
+- Edit directly in your file system
+- Version controlled alongside your code
+- Best for project-specific rules (e.g., "remember to generate migrations after modifying the db")
+
+
+
+- Manage on [Continue Hub](https://hub.continue.dev)
+- Reference in config.yaml with `uses:`
+- Share with team and community
+- Easy to include in multiple agents
+- Best for organization-wide rules (e.g., "always use X library for Y task")
+
+
+
+
+**Quick Setup**: Start with local rules for immediate use, then promote commonly used rules to the Hub for sharing and reuse.
+
Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.
\ No newline at end of file
diff --git a/docs/customization/settings.mdx b/docs/customization/settings.mdx
new file mode 100644
index 000000000..4ff298c34
--- /dev/null
+++ b/docs/customization/settings.mdx
@@ -0,0 +1,190 @@
+---
+title: Settings
+description: Configure Continue through VS Code's streamlined settings interface
+---
+
+
+
+The new settings experience introduces a **card-based layout** that reduces visual clutter while maintaining powerful functionality. Every setting is more discoverable and easier to modify, whether you're on an ultrawide monitor or a small laptop screen.
+
+## Quick Access
+
+
+
+ Click the gear in the Continue sidebar
+
+
+ File β Preferences β Settings β Extensions β Continue
+
+
+ Edit `config.yml` directly for advanced options
+
+
+
+
+ Use the toolbar buttons for quick access to specific settings: - **Rules**
+ (pencil icon) - Custom coding preferences - **Tools** (wrench icon) - Manage
+ integrations - **Models** (cube icon) - Configure AI providers
+
+
+## Core Settings
+
+
+
+
+
+ | Setting | Description |
+ |---------|-------------|
+ | Session Tabs | Manage multiple chat sessions |
+ | Code Wrapping | Auto-wrap long code lines |
+ | Markdown Display | Show raw markdown vs rendered |
+ | Chat Scrollbar | Toggle scrollbar visibility |
+
+
+
+ | Setting | Description |
+ |---------|-------------|
+ | Auto-accept Diffs | Apply code changes automatically |
+ | Tool Rejection | Continue after tool rejection |
+ | Auto-naming | Generate session titles automatically |
+
+
+
+
+
+ Configure code completions:
+
+
+
+
+ Autocomplete models need to be added to your agent to enable selecting an autocomplete model. If none is available, you will be linked to the docs showing recommended models. See our [model recommendations](/customize/model-roles/autocomplete) for the best autocomplete models.
+
+
+
+
+
+ To better understand how to set up agents and models, see our [Understanding Agents guide](/guides/understanding-agents).
+
+
+
+
+
+ Control how Continue understands your codebase:
+
+
+
+
+
+ Toggle codebase indexing in the settings panel
+
+
+ Watch real-time status in the UI
+
+
+ Check which files are indexed via the status indicator
+
+
+
+
+ Indexing enables Continue to understand your entire codebase structure, significantly improving context awareness and suggestions.
+
+
+
+
+
+
+ These features are in beta and may change or have stability issues.
+
+
+ | Feature | Purpose |
+ |---------|---------|
+ | Add Current File by Default | The currently open file is added as context in every new conversation |
+ | Enable experimental tools | Enables access to experimental tools that are still in development |
+ | Only use system message tools | Continue will not attempt to use native tool calling and will only use system message tools |
+ | @Codebase: use tool calling only | @codebase context provider will only use tool calling for code retrieval |
+ | Stream after tool rejection | Streaming will continue after the tool call is rejected |
+
+
+
+
+## Model & Assistant Selection
+
+
+
+The refined assistant selector features:
+
+- **Organization badges** for easy provider identification
+- **Smart error handling** that sorts problematic configurations while keeping them selectable
+- **Keyboard navigation** for quick model switching
+
+## Privacy & Data
+
+
+
+ All code analysis happens locally unless explicitly shared
+
+
+ Opt in/out of anonymous usage statistics
+
+
+ Sessions auto-save and restore between IDE restarts
+
+
+
+## Troubleshooting
+
+
+
+ - Verify API keys in `config.yml` - Check network connectivity - Confirm
+ endpoint URLs are correct
+
+
+
+ - Review MCP server configurations - Check tool permissions - Verify tool
+ dependencies are installed
+
+
+
+ - Check file permissions
+ - Review `.gitignore` patterns
+ - Verify sufficient disk space
+
+
+
+
+
+ Still having issues? Check our comprehensive [troubleshooting
+ guide](/troubleshooting) or visit the [FAQs](/faqs) for more solutions.
+
+
+## Next Steps
+
+
+
+ Set up your AI providers
+
+
+ Extend Continue with MCP tools
+
+
+ Define coding preferences
+
+
+ Customize AI behavior
+
+
diff --git a/docs/customize/custom-providers.mdx b/docs/customize/custom-providers.mdx
index 068f0cdca..b66559487 100644
--- a/docs/customize/custom-providers.mdx
+++ b/docs/customize/custom-providers.mdx
@@ -19,116 +19,62 @@ You can add any built-in context-providers in your config file as shown below:
Reference any file in your current workspace.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: file
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "file" }] }
-```
-
### @Code Context Provider β Reference Functions and Classes
Reference specific functions or classes from throughout your project.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: code
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "code" }] }
-```
-
### @Git Diff Context Provider β Reference Branch Changes
Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: diff
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "diff" }] }
-```
-
### @Current File Context Provider β Reference the Active File
Reference the currently open file.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: currentFile
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "currentFile" }] }
-```
-
### @Terminal Context Provider β Reference Last Terminal Command and Output
Reference the last command you ran in your IDE's terminal and its output.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: terminal
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "terminal" }] }
-```
-
### @Docs Context Provider β Reference Documentation Site Content
Reference the contents from any documentation site.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: docs
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "docs" }] }
-```
-
Note that this will only enable the `@Docs` context provider.
To use it, you need to add a documentation site to your config file. See the [docs](/customize/overview#documentation-context) page for more information.
@@ -137,9 +83,6 @@ To use it, you need to add a documentation site to your config file. See the [do
Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
-- YAML
-- JSON
-
config.yaml
```
@@ -149,21 +92,12 @@ context:
onlyPinned: true
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "open", "params": { "onlyPinned": true } }] }
-```
-
### @Web Context Provider β Reference Relevant Web Pages
Reference relevant pages from across the web, automatically determined from your input.
Optionally, set `n` to limit the number of results returned (default 6).
-- YAML
-- JSON
-
config.yaml
```
@@ -173,19 +107,10 @@ context:
n: 5
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "web", "params": { "n": 5 } }] }
-```
-
### @Codebase Context Provider β Reference Relevant Codebase Snippets
Reference the most relevant snippets from your codebase.
-- YAML
-- JSON
-
config.yaml
```
@@ -193,40 +118,22 @@ context:
- provider: codebase
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "codebase" }] }
-```
-
Read more about indexing and retrieval [here](/customize/overview#codebase-context).
### @Folder Context Provider β Reference Code from a Specific Folder
Uses the same retrieval mechanism as `@Codebase`, but only on a single folder.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: folder
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "folder" }] }
-```
-
### @Search Context Provider β Reference Code Search Results
Reference the results of codebase search, just like the results you would get from VS Code search.
-- YAML
-- JSON
-
config.yaml
```
@@ -236,21 +143,12 @@ context:
maxResults: 100 # optional, defaults to 200
```
-config.json
-
-```json
-{ "contextProviders": [ { "name": "search", "params": { "maxResults": 100 // optional, defaults to 200 } } ]}
-```
-
This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep).
### @Url Context Provider β Reference Content from a URL
Reference the markdown converted contents of a given URL.
-- YAML
-- JSON
-
config.yaml
```
@@ -258,19 +156,10 @@ context:
- provider: url
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "url" }] }
-```
-
### @Clipboard Context Provider β Reference Clipboard Items
Reference recent clipboard items
-- YAML
-- JSON
-
config.yaml
```
@@ -278,19 +167,10 @@ context:
- provider: clipboard
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "clipboard" }] }
-```
-
### @Tree Context Provider β Reference Workspace File Structure
Reference the structure of your current workspace.
-- YAML
-- JSON
-
config.yaml
```
@@ -298,19 +178,10 @@ context:
- provider: tree
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "tree" }] }
-```
-
### @Problems Context Provider β Reference Problems in the Current File
Get Problems from the current file.
-- YAML
-- JSON
-
config.yaml
```
@@ -318,19 +189,10 @@ context:
- provider: problems
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "problems" }] }
-```
-
### @Debugger Context Provider β Reference Debugger Local Variables
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
-- YAML
-- JSON
-
config.yaml
```
@@ -340,12 +202,6 @@ context:
stackDepth: 3
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "debugger", "params": { "stackDepth": 3 } }] }
-```
-
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
### @Repository Map Context Provider β Reference Codebase Outline and Signatures
@@ -354,9 +210,6 @@ Reference the outline of your codebase. By default, signatures are included alon
`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled.
-- YAML
-- JSON
-
config.yaml
```
@@ -366,12 +219,6 @@ context:
includeSignatures: false # default true
```
-config.json
-
-```json
-{ "contextProviders": [ { "name": "repo-map", "params": { "includeSignatures": false // default true } } ]}
-```
-
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repository map from.
@@ -382,9 +229,6 @@ This context provider is inspired by [Aider's repository map](https://aider.chat
Reference the architecture and platform of your current operating system.
-- YAML
-- JSON
-
config.yaml
```
@@ -392,19 +236,10 @@ context:
- provider: os
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "os" }] }
-```
-
### Using the Model Context Protocol (MCP) in Continue
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this:
-- YAML
-- JSON
-
config.yaml
```
@@ -417,24 +252,6 @@ mcpServers:
- /Users/NAME/test.db
```
-config.json
-
-```json
-{
- "experimental": {
- "modelContextProtocolServers": [
- {
- "transport": {
- "type": "stdio",
- "command": "uvx",
- "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
- }
- }
- ]
- }
-}
-```
-
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
### How to Request a New Context Provider in Continue
diff --git a/docs/customize/deep-dives/configuration.mdx b/docs/customize/deep-dives/configuration.mdx
index 4291dfbd8..ba7f35123 100644
--- a/docs/customize/deep-dives/configuration.mdx
+++ b/docs/customize/deep-dives/configuration.mdx
@@ -1,26 +1,26 @@
---
-title: "How to Configure Continue Assistants"
-description: Learn how to access and manage Continue assistant configurations through Hub or local YAML files
+title: "How to Configure Continue Agents"
+description: Learn how to access and manage Continue agent configurations through Hub or local YAML files
keywords: [config, settings, customize]
-sidebarTitle: "Assistant Configuration"
+sidebarTitle: "Agent Configuration"
---
-You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon.
+You can easily access your agent configuration from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the Agent selector above the main chat input. Then, you can hover over an agent and click the `new window` (hub agents) or `gear` (local agents) icon.
-
+
-## How to Manage Hub Assistants
+## How to Manage Hub Agents
-Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editing an Assistant](../../hub/assistants/edit-an-assistant.md)
+Hub Agents can be managed in [the Hub](https://hub.continue.dev). See [Editing an Agent](../../hub/agents/edit-an-agent.md)
-## How to Configure Local Assistants with YAML
+## How to Configure Local Agents with YAML
Local user-level configuration is stored and can be edited in your home directory in `config.yaml`:
- `~/.continue/config.yaml` (MacOS / Linux)
- `%USERPROFILE%\.continue\config.yaml` (Windows)
-To open this `config.yaml`, you need to open the assistants dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Assistant" option, select the cog icon. It will open the local `config.yaml`.
+To open this `config.yaml`, you need to open the agents dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Agent" option, select the cog icon. It will open the local `config.yaml`.

@@ -31,7 +31,7 @@ See the full reference for `config.yaml` [here](/reference).
## Legacy Configuration Methods (Deprecated)
- View the `config.json` migration guide [here](../yaml-migration)
+ View the `config.json` migration guide [here](/reference/yaml-migration)
- [`config.json`](/reference) - The original configuration format which is stored in a file at the same location as `config.yaml`
@@ -63,7 +63,7 @@ Example
The `slashCommands` array shown below is deprecated. For creating custom slash
- commands, use [prompt files](./slash-commands) instead.
+ commands, use [prompt files](./prompts) instead.
```ts title="config.ts"
diff --git a/docs/customize/deep-dives/custom-providers.mdx b/docs/customize/deep-dives/custom-providers.mdx
index dd604646b..9adc078ab 100644
--- a/docs/customize/deep-dives/custom-providers.mdx
+++ b/docs/customize/deep-dives/custom-providers.mdx
@@ -15,251 +15,95 @@ You can add any built-in context-providers in your config file as shown below:
Reference any file in your current workspace.
-
-
- ```yaml config.yaml
- context:
- - provider: file
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "file"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: file
+```
### `@Code`
Reference specific functions or classes from throughout your project.
-
-
- ```yaml config.yaml
- context:
- - provider: code
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "code"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: code
+```
### `@Git Diff`
Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
-
-
- ```yaml config.yaml
- context:
- - provider: diff
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "diff"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: diff
+```
### `@Current File`
Reference the currently open file.
-
-
- ```yaml config.yaml
- context:
- - provider: currentFile
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "currentFile"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: currentFile
+```
### `@Terminal`
Reference the last command you ran in your IDE's terminal and its output.
-
-
- ```yaml config.yaml
- context:
- - provider: terminal
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "terminal"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: terminal
+```
### `@Open`
Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
-
-
- ```yaml config.yaml
- context:
- - provider: open
- params:
- onlyPinned: true
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "open",
- "params": {
- "onlyPinned": true
- }
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: open
+ params:
+ onlyPinned: true
+```
### `@Clipboard`
Reference recent clipboard items
-
-
- ```yaml config.yaml
- context:
- - provider: clipboard
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "clipboard"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: clipboard
+```
### `@Tree`
Reference the structure of your current workspace.
-
-
- ```yaml config.yaml
- context:
- - provider: tree
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "tree"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: tree
+```
### `@Problems`
Get Problems from the current file.
-
-
- ```yaml config.yaml
- context:
- - provider: problems
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "problems"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: problems
+```
### `@Debugger`
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
-
-
- ```yaml config.yaml
- context:
- - provider: debugger
- params:
- stackDepth: 3
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "debugger",
- "params": {
- "stackDepth": 3
- }
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: debugger
+ params:
+ stackDepth: 3
+```
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
@@ -269,30 +113,12 @@ Reference the outline of your codebase. By default, signatures are included alon
`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled.
-
-
- ```yaml config.yaml
- context:
- - provider: repo-map
- params:
- includeSignatures: false # default true
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "repo-map",
- "params": {
- "includeSignatures": false // default true
- }
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: repo-map
+ params:
+ includeSignatures: false # default true
+```
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
@@ -304,54 +130,23 @@ This context provider is inpsired by [Aider's repository map](https://aider.chat
Reference the architecture and platform of your current operating system.
-
-
- ```yaml config.yaml
- context:
- - provider: os
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "os"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: os
+```
### `@HTTP`
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
-
-
- ```yaml config.yaml
- context:
- - provider: http
- params:
- url: "https://api.example.com/v1/users"
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "http",
- "params": {
- "url": "https://api.example.com/v1/users"
- }
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: http
+ params:
+ url: "https://api.example.com/v1/users"
+ headers:
+ - Authorization: "Bearer "
+```
The receiving URL should expect to receive the following parameters:
@@ -373,43 +168,23 @@ Response
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this:
-
-
- ```yaml config.yaml
- mcpServers:
- - name: My MCP Server
- command: uvx
- args:
- - mcp-server-sqlite
- - --db-path
- - /Users/NAME/test.db
- ```
-
-
- ```json config.json
- {
- "experimental": {
- "modelContextProtocolServers": [
- {
- "transport": {
- "type": "stdio",
- "command": "uvx",
- "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
- }
- }
- ]
- }
- }
- ```
-
-
+```yaml config.yaml
+mcpServers:
+ - name: My MCP Server
+ command: uvx
+ args:
+ - mcp-server-sqlite
+ - --db-path
+ - /Users/NAME/test.db
+```
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
## Deprecated Context Providers
- To provide conext beyond the built-in context providers, we now recommend using [MCP Servers](/customization/mcp-tools)
+ To provide conext beyond the built-in context providers, we now recommend
+ using [MCP Servers](/customization/mcp-tools)
View the [deprecated context providers](/reference/deprecated-context-providers) for documentation on:
@@ -427,4 +202,4 @@ View the [deprecated context providers](/reference/deprecated-context-providers)
- `@Issue` - GitHub issues
- `@Url` - URL content
- `@Search` - Codebase search
-- `@Web` - Web search results
\ No newline at end of file
+- `@Web` - Web search results
diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx
index 7b6230923..074448104 100644
--- a/docs/customize/deep-dives/mcp.mdx
+++ b/docs/customize/deep-dives/mcp.mdx
@@ -19,7 +19,7 @@ that can be set up with custom tools.
Currently custom tools can be configured using the Model Context
Protocol standard to unify prompts, context, and tool use.
-MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can
+MCP Servers can be added to hub Agents using `mcpServers` blocks. You can
explore available MCP server blocks
[here](https://hub.continue.dev/explore/mcp).
@@ -27,7 +27,7 @@ explore available MCP server blocks
## Quick Start: How to Set Up Your First MCP Server
-Below is a quick example of setting up a new MCP server for use in your assistant:
+Below is a quick example of setting up a new MCP server for use in your agent:
1. Create a folder called `.continue/mcpServers` at the top level of your workspace
2. Add a file called `playwright-mcp.yaml` to this folder.
diff --git a/docs/customize/deep-dives/model-capabilities.mdx b/docs/customize/deep-dives/model-capabilities.mdx
index 3e8a998eb..eca29cf04 100644
--- a/docs/customize/deep-dives/model-capabilities.mdx
+++ b/docs/customize/deep-dives/model-capabilities.mdx
@@ -210,9 +210,14 @@ This matrix shows which models support tool use and image input capabilities. Co
### xAI
-| Model | Tool Use | Image Input | Context Window |
-| :----- | -------- | ----------- | -------------- |
-| Grok 4 | Yes | Yes | 128k |
+| Model | Tool Use | Image Input | Context Window |
+| :------------------------ | -------- | ----------- | -------------- |
+| Grok Code Fast 1 | Yes | Yes | 256k |
+| Grok 4 Fast Reasoning | Yes | Yes | 2M |
+| Grok 4 Fast Non-Reasoning | Yes | Yes | 2M |
+| Grok 4 | Yes | Yes | 256k |
+| Grok 3 | Yes | Yes | 131k |
+| Grok 3 Mini | Yes | Yes | 131k |
### Moonshot AI
@@ -231,12 +236,13 @@ This matrix shows which models support tool use and image input capabilities. Co
| Model | Tool Use | Image Input | Context Window |
| :------------- | -------- | ----------- | -------------- |
| Qwen 3 Coder | Yes | No | 32k |
+| Qwen 2.5 VL | No | Yes | 128k |
| Devstral Small | Yes | No | 32k |
| Llama 3.1 | Yes | No | 128k |
| Llama 3 | Yes | No | 8k |
| Mistral | Yes | No | 32k |
| Codestral | Yes | No | 32k |
-| Gemma 3 4B | Yes | No | 8k |
+| Gemma 3 4B | Yes | Yes | 128k |
### Notes
diff --git a/docs/customize/deep-dives/prompts.mdx b/docs/customize/deep-dives/prompts.mdx
index d80466da7..53579b778 100644
--- a/docs/customize/deep-dives/prompts.mdx
+++ b/docs/customize/deep-dives/prompts.mdx
@@ -1,62 +1,106 @@
---
-title: "Creating Custom Prompts in Continue"
-description: "Learn how to create reusable prompt files in Continue to streamline repetitive tasks, including examples for code reviews, security checks, and entity generation"
+title: "How to Create and Manage Prompts in Continue"
+description: "Prompts are used to kick off tasks for Agent, Plan, and Chat requests"
+keywords: [prompts, context, slash command]
+sidebarTitle: "Prompts"
---
-Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks.
+Prompts are included as user messages and are especially useful as instructions for repetitive and/or complex tasks.
-
- Prompts were previously defined in a `.prompt` file format, but for
- consistency we now recommend using the same Markdown format as
- [rules](./rules) and adding `alwaysApply: false` to the frontmatter so
- that they are manually triggered.
-
+## Slash commands
-## Quick Start: How to Create Your First Prompt File
+By setting `invokable` to `true`, you make the markdown file a prompt, which will be available when you type / in Chat, Plan, and Agent mode.
-Below is a quick example of setting up a prompt file:
-
-1. Create a folder called `.continue/rules` at the top level of your workspace
-2. Add a file called `review-prompt.md` to this folder.
-3. Write the following contents to `review-prompt.md` and save.
-
-```md title="review-prompt.md"
+```md title="explain-invokable.md"
---
-name: Redux best practices review
-alwaysApply: false
+name: Explain invokable
+description: Explains what happens when you set invokable to true
+invokable: true
---
-Review the currently open file for adherence to Redux best practices, as explained in their style guide at https://redux.js.org/style-guide/.
+Explain that when `invokable` is set to `true`, a slash command becomes available in the IDE extensions and CLI
```
-Now to use this prompt, you can open Chat, type /, select the prompt, and type out any additional instructions you'd like to add.
+These slash commands can be combined with other instructions, including highlighted code, to provide additional context.
-## Example Prompt Templates for Common Use Cases
+## Example: `Create Supabase functions` prompt
-Below are more examples to get you started. You can also visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts).
+Here is a prompt that generates high-quality PostgreSQL functions that adhere to best practices:
-### How to Create a Security Review Prompt
-
-```md title="security-review.md"
+```md title="supabase-create-functions.md"
---
-name: Security best practices review
-alwaysApply: false
+name: Create Supabase functions
+description: Guidelines for writing Supabase database functions
+invokable: true
---
-Review the changes in the current git diff for these security best practices:
+# Database: Create functions
-- Does the architecture follow security-by-design principles?
-- Are there potential security vulnerabilities in the system design?
-- Is sensitive data handled appropriately throughout the lifecycle?
+You're a Supabase Postgres expert in writing database functions. Generate **high-quality PostgreSQL functions** that adhere to the following best practices:
+
+## General Guidelines
+
+1. **Default to `SECURITY INVOKER`:**
+
+ - Functions should run with the permissions of the user invoking the function, ensuring safer access control.
+ - Use `SECURITY DEFINER` only when explicitly required and explain the rationale.
+
+2. **Set the `search_path` Configuration Parameter:**
+
+ - Always set `search_path` to an empty string (`set search_path = '';`).
+ - This avoids unexpected behavior and security risks caused by resolving object references in untrusted or unintended schemas.
+ - Use fully qualified names (e.g., `schema_name.table_name`) for all database objects referenced within the function.
+
+3. **Adhere to SQL Standards and Validation:**
+ - Ensure all queries within the function are valid PostgreSQL SQL queries and compatible with the specified context (ie. Supabase).
+
+...
```
-### How to Create a Prompt That References Existing Files
+You can read the rest of the `Create Supabase functions` prompt [here](http://hub.continue.dev/supabase/create-functions)
-```md title="typeorm-entity-generator.md"
----
-name: Generate a new TypeORM entity
-alwaysApply: false
----
+If you are using a local `config.yaml`, you can add it to your agent like this:
-Referencing `src/db/dataSource.ts` and `src/db/entity/SampleEntity.ts`, generate a new TypeORM entity based on the following requirements:
+```md title="config.yaml"
+...
+
+prompts:
+ - uses: supabase/create-functions
+
+...
```
+
+If you are using Continue Hub, you can add it to your agent by selecting "Use Rule" [here](https://hub.continue.dev/supabase/create-functions)
+
+To use this prompt, you can open Chat / Agent / Edit, type /, select the prompt, and type out any additional instructions you'd like to add.
+
+## Using a prompt with `cn (TUI mode)`
+
+You can run this command to start [cn](../../guides/cli) with the [Create Supabase functions](http://hub.continue.dev/supabase/create-functions) prompt.
+
+```
+cn --prompt supabase/create-functions "I need a function that checks for the health status"
+```
+Alternatively, you can start [cn](../../guides/cli) and then type / to manually invoke the prompt yourself.
+
+## Using a prompt to kick off a Continuous AI workflow with `cn (Headless mode)
+
+You can kick off Continuous AI workflows using a prompt with [cn](../../guides/cli) by adding the `-p` flag.
+
+For example, say you are building a SaaS application and must repeatedly create custom Supabase validation functions for each new feature that accepts user input.
+
+These functions require you to interpret business requirements, implement complex cross-table logic (like checking user permissions, tier limits, and time-based restrictions), and make judgment calls about edge cases.
+
+Each function is unique enough that it can't be templated or scripted. This is where kicking off a Continuous AI workflow to get you started can be quite helpful.
+
+Here is a command that you could run whenever you have a new feature:
+
+```
+ cn -p --prompt supabase/create-functions "I need a function for the new feature on my current branch similar to my existing database functions"
+```
+
+You can see the entire `Create Supabase functions` prompt [here](http://hub.continue.dev/supabase/create-functions)
+
+When you run this workflow, [cn](../../guides/cli) will checkout your current branch, explore the new and existing code, and then draft a function for you.
+
+You will then be able to review the implementation and improve it before you merge the new feature.
\ No newline at end of file
diff --git a/docs/customize/deep-dives/rules.mdx b/docs/customize/deep-dives/rules.mdx
index 2f9411bc9..449fc272d 100644
--- a/docs/customize/deep-dives/rules.mdx
+++ b/docs/customize/deep-dives/rules.mdx
@@ -1,7 +1,7 @@
---
title: "How to Create and Manage Rules in Continue"
-description: "Rules are used to provide instructions to the model for Agent, Chat, and Edit requests."
-keywords: [rules, .continuerules, system, prompt, message]
+description: "Rules are used to provide system message instructions to the model for Agent, Chat, and Edit requests"
+keywords: [rules, system, prompt, message]
sidebarTitle: "Rules"
---
@@ -20,6 +20,42 @@ You can view the current rules by clicking the pen icon above the main toolbar:
To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#how-to-customize-chat-system-message)).
+## Understanding Hub vs Local Rules Integration
+
+
+**Important:** Rules created in different locations behave differently and have different synchronization patterns.
+
+
+Continue supports two types of rules with different behaviors:
+
+
+
+- **Location**: `.continue/rules` folder in your workspace
+- **Visibility**: Automatically visible when using Hub assistants
+- **Creation**: Add rules button in VSCode or manual file creation
+- **File Management**: Creates actual `.md` files you can edit directly
+
+
+
+- **Location**: Stored on Continue Hub, referenced in config.yaml
+- **Visibility**: Only appear when referenced in assistant configuration
+- **Creation**: Created directly on Hub or copied from local rules
+- **File Management**: No local files created, managed through Hub interface
+
+
+
+### How Rules Are Applied
+
+When using Continue, rules are loaded in this order:
+1. **Hub assistant rules** (if using a Hub-based assistant)
+2. **Referenced Hub rules** (via `uses:` in config.yaml)
+3. **Local workspace rules** (from `.continue/rules` folder)
+4. **Global rules** (from `~/.continue/rules` folder)
+
+
+**TL;DR**: Local rules show up automatically when using Hub assistants. Hub rules show up automatically when referenced in your config.
+
+
## Quick Start: How to Create Your First Rule File
Below is a quick example of setting up a new rule file:
@@ -42,7 +78,9 @@ Now test your rules by asking a question about a file in chat.
## How to Create Rules Blocks
-Rules can be added locally using the "Add Rules" button while viewing the Local Assistant's rules.
+### Creating Local Rules
+
+Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules.

@@ -50,12 +88,44 @@ Rules can be added locally using the "Add Rules" button while viewing the Local
**Automatically create local rule blocks**: When in Agent mode, you can prompt the agent to create a rule for you using the `create_rule_block` tool if enabled.
For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation.
-
-Rules can also be added to an Assistant on the Continue Hub.
+### Creating Hub Rules
-Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
+Rules can also be created and managed on the Continue Hub:
+
+1. **Browse existing rules**: [Explore available rules](https://hub.continue.dev)
+2. **Create new rules**: [Create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub
+3. **Copy from local rules**: Copy/paste content from your `.continue/rules` files to create Hub rules
+
+### Working Between Hub and Local Rules
+
+
+
+To use Hub rules in your local setup:
+
+1. Reference them in your `config.yaml`:
+ ```yaml
+ rules:
+ - uses: username/my-hub-rule
+ ```
+2. The rule will automatically appear in your rules toolbar
+3. **Note**: No local file is created - the rule exists only on the Hub
+
+
+
+To move local rules to the Hub:
+
+1. Copy the content from your `.continue/rules/rule-name.md` file
+2. Go to [Create new rule](https://hub.continue.dev/new?type=block&blockType=rules)
+3. Paste the content and configure the rule
+4. Optionally, remove the local file and reference the Hub rule in your config
+
+
+**Current Limitation**: There's no automatic sync from local to Hub. You must manually copy/paste rule content.
+
+
+
### How to Configure Rule Properties and Syntax
@@ -150,19 +220,46 @@ globs: ["**/*.ts", "**/*.tsx"]
- modularize components into smaller, reusable pieces
```
+## Troubleshooting Rules
+
+### Issue: Rules Created in Different Places Don't Sync
+
+**Problem**: You created rules in the Hub but don't see them in VSCode, or vice versa.
+
+**Solution**:
+- **Hub rules** only appear when referenced in your config.yaml using the `uses:` syntax
+- **Local rules** automatically appear when using Hub assistants
+- There's currently no automatic bidirectional sync
+
+### Issue: "Edit" Links Point to Wrong Location
+
+**Problem**: When you click "Edit" on a rule in VSCode, it tries to open the Hub even though the rule is local, or shows an incorrect URL.
+
+**Root Cause**: This happens when you have a mix of local and Hub rules, and Continue can't properly determine where each rule originates.
+
+**Workaround**:
+1. **For local rules**: Navigate directly to `.continue/rules/` folder and edit the `.md` file
+2. **For Hub rules**: Go directly to your assistant page on [Continue Hub](https://hub.continue.dev) and edit from there
+3. Keep track of which rules are local vs Hub-based to avoid confusion
+
+
+**Known Issue**: This link accuracy problem is tracked in [Linear issue CON-3084](https://linear.app/continue/issue/CON-3084) and will be fixed in a future update.
+
+
+### Issue: Rules Don't Appear in Assistant
+
+**Problem**: Your rules exist but don't show up in the rules toolbar.
+
+**Check These**:
+1. **File location**: Ensure local rules are in `.continue/rules/` (not `.continue/rule/`)
+2. **File format**: Rules should be `.md` files with proper YAML frontmatter
+3. **Config reference**: Hub rules must be referenced in `config.yaml`
+4. **Assistant type**: Ensure you're using the correct assistant (local vs Hub)
+
### How to Customize Chat System Message
Continue includes a simple default system message for [Agent](../../features/agent/quick-start) and [Chat](../../features/chat/quick-start) requests, to help the model provide reliable codeblock formats in its output.
This can be viewed in the rules section of the toolbar (see above), or in the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4).
-Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](/reference#models).
-
-### Legacy: .continuerules File (Deprecated)
-
-
- `.continuerules` will be deprecated in a future release. Please use the
- `.continue/rules` folder instead.
-
-
-You can create project-specific rules by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules.
+Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](/reference#models).
\ No newline at end of file
diff --git a/docs/customize/deep-dives/rules.mdx.backup b/docs/customize/deep-dives/rules.mdx.backup
index 0971568a8..5338df40d 100644
--- a/docs/customize/deep-dives/rules.mdx.backup
+++ b/docs/customize/deep-dives/rules.mdx.backup
@@ -39,7 +39,7 @@ Now test your rules by asking a question about a file in chat.
## Creating `rules` blocks
-Rules can be added locally using the "Add Rules" button while viewing the Local Assistant's rules.
+Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules.

@@ -49,7 +49,7 @@ Automatically create local rule blocks: When in Agent mode, you can prompt the a
For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation.
-Rules can also be added to an Assistant on the Continue Hub.
+Rules can also be added to an Agent on the Continue Hub.
Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
@@ -133,7 +133,7 @@ name: New rule
Always give concise responses
```
-This is also done when selecting "Add Rule" in the Assistant settings. This will create a new folder in `.continue/rules` with a default file named `new-rule.md`.
+This is also done when selecting "Add Rule" in the Agent settings. This will create a new folder in `.continue/rules` with a default file named `new-rule.md`.
### Examples
diff --git a/docs/customize/deep-dives/slash-commands.mdx b/docs/customize/deep-dives/slash-commands.mdx
deleted file mode 100644
index 3f041ada2..000000000
--- a/docs/customize/deep-dives/slash-commands.mdx
+++ /dev/null
@@ -1,36 +0,0 @@
----
-title: "Using Slash Commands in Continue"
-description: "Learn how to use and create Slash Commands in Continue to run custom prompts, access context providers, and speed up coding tasks."
-keywords: [slash command, custom commands, step]
-sidebarTitle: "Slash Commands"
----
-
-
-
-Slash commands are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown.
-
-
-Slash commands can be combined with additional instructions, including highlighted code.
-
-
- **Recommended approach**: Use prompt files to create slash commands instead of
- the deprecated `config.json` approach. The methods described below provide
- better flexibility and are the actively maintained ways to add custom
- commands.
-
-
-## Ways to Create Slash Commands in Continue
-
-### Assistant Prompt Blocks
-
-The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works).
-
-### Prompt Files
-
-It is also possible to write your own slash command by defining a β.prompt file.β Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more.
-
-Learn more about prompt files [here](./prompts).
-
-### MCP Server Prompts
-
-Any prompts provided by [Model Context Protocol](https://modelcontextprotocol.io/introduction) servers are also accessible in chat as Slash Commands. See the [MCP Server Deep Dive](./mcp) for more details.
diff --git a/docs/customize/model-providers/assets/tetrate-get-api-key.png b/docs/customize/model-providers/assets/tetrate-get-api-key.png
new file mode 100644
index 000000000..e6f88b4bd
Binary files /dev/null and b/docs/customize/model-providers/assets/tetrate-get-api-key.png differ
diff --git a/docs/customize/model-providers/assets/tetrate-remix.png b/docs/customize/model-providers/assets/tetrate-remix.png
new file mode 100644
index 000000000..a418f8a81
Binary files /dev/null and b/docs/customize/model-providers/assets/tetrate-remix.png differ
diff --git a/docs/customize/model-providers/assets/tetrate-sign-in.png b/docs/customize/model-providers/assets/tetrate-sign-in.png
new file mode 100644
index 000000000..0833ab383
Binary files /dev/null and b/docs/customize/model-providers/assets/tetrate-sign-in.png differ
diff --git a/docs/customize/model-providers/more/SambaNova.mdx b/docs/customize/model-providers/more/SambaNova.mdx
index acd83a682..4b46333d1 100644
--- a/docs/customize/model-providers/more/SambaNova.mdx
+++ b/docs/customize/model-providers/more/SambaNova.mdx
@@ -1,6 +1,6 @@
---
title: "SambaNova"
-description: "Configure SambaNova Cloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance"
+description: "Configure SambaCloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance"
---
The SambaNova Cloud is a cloud platform for running large AI models with the world record open source models performance. You can follow the instructions in [this blog post](https://sambanova.ai/blog/accelerating-coding-with-sambanova-cloud?ref=blog.continue.dev) to configure your setup.
@@ -9,9 +9,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor
```yaml title="config.yaml"
models:
- - name: SambaNova Llama 4 Scout
+ - name: GPT OSS 120B
provider: sambanova
- model: Llama-4-Scout-17B-16E-Instruct
+ model: gpt-oss-120b
apiKey:
```
@@ -20,9 +20,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor
{
"models": [
{
- "title": "SambaNova Llama 4 Scout",
+ "title": "GPT OSS 120B",
"provider": "sambanova",
- "model": "Llama-4-Scout-17B-16E-Instruct",
+ "model": "gpt-oss-120b",
"apiKey": ""
}
]
diff --git a/docs/customize/model-providers/more/lemonade.mdx b/docs/customize/model-providers/more/lemonade.mdx
new file mode 100644
index 000000000..79afd957d
--- /dev/null
+++ b/docs/customize/model-providers/more/lemonade.mdx
@@ -0,0 +1,81 @@
+---
+title: "Lemonade Server"
+description: "Configure Lemonade Server with Continue for refreshingly fast local LLM inference on GPUs and NPUs"
+---
+
+
+ Get started with [Lemonade Server](https://lemonade-server.ai/) - Refreshingly fast LLMs on GPUs and NPUs with seamless Continue integration
+
+
+## Overview
+
+Lemonade Server provides optimized local LLM inference with support for GPU and NPU hardware acceleration. It offers an OpenAI-compatible API that seamlessly integrates with Continue and other open-source platforms.
+
+## Installation
+
+Download and install Lemonade Server from [lemonade-server.ai](https://lemonade-server.ai/).
+
+## Configuration
+
+Lemonade Server is available directly in the Continue UI as a provider. You can select it from the model provider dropdown without manual configuration.
+
+### Option 1: Using the Continue UI (Recommended)
+
+1. Click on the model selector dropdown in Continue
+2. Select "Add Model"
+3. Choose "Lemonade Server" from the provider list
+4. Continue will automatically configure the connection
+
+### Option 2: Manual Configuration
+
+If you need custom settings, you can manually configure Lemonade:
+
+
+
+ ```yaml title="config.yaml"
+ models:
+ - name: Lemonade
+ provider: lemonade
+ model:
+ apiBase: http://localhost:8000/api/v1/
+ ```
+
+
+ ```json title="config.json"
+ {
+ "models": [
+ {
+ "title": "Lemonade",
+ "provider": "lemonade",
+ "model": "",
+ "apiBase": "http://localhost:8000/api/v1/"
+ }
+ ]
+ }
+ ```
+
+
+
+## Getting Started
+
+1. **Install Lemonade Server**: Download from [lemonade-server.ai](https://lemonade-server.ai/)
+2. **Start the server**: Launch Lemonade Server (runs on `http://localhost:8000/api/v1/` by default)
+3. **Add to Continue**: Select Lemonade Server from the model provider dropdown in Continue
+4. **Load a model**: Choose your preferred model through the interface
+
+## Hardware Support
+
+Lemonade Server automatically detects and optimizes for available hardware:
+- **NPU**: Neural Processing Unit acceleration for efficient inference
+- **GPU**: Full GPU acceleration support
+- **CPU**: Optimized CPU fallback when accelerators are unavailable
+
+## Key Features
+
+- OpenAI-compatible API for seamless integration
+- Support for popular model formats
+- Automatic hardware detection and optimization
+- Integration with Continue, Open WebUI, Gaia, and AnythingLLM
+- Active open-source community
+
+[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Lemonade.ts)
\ No newline at end of file
diff --git a/docs/customize/model-providers/more/tetrate_agent_router_service.mdx b/docs/customize/model-providers/more/tetrate_agent_router_service.mdx
deleted file mode 100644
index 163dee253..000000000
--- a/docs/customize/model-providers/more/tetrate_agent_router_service.mdx
+++ /dev/null
@@ -1,44 +0,0 @@
----
-title: "Tetrate Agent Router Service"
----
-
-The Tetrate Agent Router Service (TARS) provides a unified API gateway for accessing various AI models with fast inference capabilities. TARS acts as an intelligent router that can distribute requests across multiple model providers, offering enterprise-grade reliability and performance optimization.
-
-## Getting Started
-
-1. Obtain an API key from the [Tetrate Agent Router Service portal](https://api.router.tetrate.ai/)
-2. Configure Continue to use TARS as your model provider
-
-## Configuration
-
-Update your Continue configuration file (`~/.continue/config.json` or `~/.continue/config.yaml`) with your TARS API key:
-
-
-
- ```yaml title="config.yaml"
- models:
- - name: TARS GPT-5 Mini
- provider: tars
- model: gpt-5-mini
- apiKey:
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "TARS GPT-5 Mini",
- "provider": "tars",
- "model": "gpt-5-mini",
- "apiKey": ""
- }
- ]
- }
- ```
-
-
-
-## Available Models
-
-TARS supports routing to various models. Go to the [Tetrate Agent Router Service model catalog](https://router.tetrate.ai/models) for a full list of supported models.
diff --git a/docs/customize/model-providers/more/xAI.mdx b/docs/customize/model-providers/more/xAI.mdx
index 803befe49..c90b2196e 100644
--- a/docs/customize/model-providers/more/xAI.mdx
+++ b/docs/customize/model-providers/more/xAI.mdx
@@ -3,13 +3,9 @@ title: xAI
slug: ../xai
---
-
- **Discover xAI models [here](https://hub.continue.dev/xai)**
-
+**Discover xAI models [here](https://hub.continue.dev/xai)**
-
- Get an API key from the [xAI Console](https://console.x.ai/)
-
+Get an API key from the [xAI Console](https://console.x.ai/)
## Configuration
@@ -29,7 +25,7 @@ slug: ../xai
"models": [
{
"title": "",
- "provider": "anthropic",
+ "provider": "xai",
"model": "",
"apiKey": ""
}
@@ -40,5 +36,6 @@ slug: ../xai
- **Check out a more advanced configuration [here](https://hub.continue.dev/xai/grok-4?view=config)**
-
\ No newline at end of file
+ **Check out a more advanced configuration
+ [here](https://hub.continue.dev/xai/grok-code-fast-1?view=config)**
+
diff --git a/docs/customize/model-providers/overview.mdx b/docs/customize/model-providers/overview.mdx
index 617d400c5..fd5fa8344 100644
--- a/docs/customize/model-providers/overview.mdx
+++ b/docs/customize/model-providers/overview.mdx
@@ -33,6 +33,7 @@ Beyond the top-level providers, Continue supports many other options:
| [Together AI](/customize/model-providers/more/together) | Platform for running a variety of open models |
| [DeepInfra](/customize/model-providers/more/deepinfra) | Hosting for various open source models |
| [OpenRouter](/customize/model-providers/top-level/openrouter) | Gateway to multiple model providers |
+| [Tetrate Agent Router Service](/customize/model-providers/top-level/tetrate_agent_router_service) | Gateway with intelligent routing across multiple model providers |
| [Cohere](/customize/model-providers/more/cohere) | Models specialized for semantic search and text generation |
| [NVIDIA](/customize/model-providers/more/nvidia) | GPU-accelerated model hosting |
| [Cloudflare](/customize/model-providers/more/cloudflare) | Edge-based AI inference services |
diff --git a/docs/customize/model-providers/top-level/openai.mdx b/docs/customize/model-providers/top-level/openai.mdx
index d57b8cd3c..9537ac133 100644
--- a/docs/customize/model-providers/top-level/openai.mdx
+++ b/docs/customize/model-providers/top-level/openai.mdx
@@ -30,7 +30,7 @@ sidebarTitle: "OpenAI"
"models": [
{
"title": "",
- "provider": "openai",
+ "provider": "openai",
"model": "",
"apiKey": ""
}
@@ -56,6 +56,7 @@ OpenAI API compatible providers include
- [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples)
- [vLLM](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html)
- [BerriAI/litellm](https://github.com/BerriAI/litellm)
+- [Tetrate Agent Router Service](https://router.tetrate.ai)
If you are using an OpenAI API compatible providers, you can change the `apiBase` like this:
@@ -75,7 +76,7 @@ If you are using an OpenAI API compatible providers, you can change the `apiBase
{
"models": [
{
- "title": "",
+ "title": "",
"provider": "openai",
"model": "",
"apiKey": "",
@@ -110,7 +111,7 @@ To force usage of `chat/completions` instead of `completions` endpoint you can s
"title": "",
"provider": "openai",
"model": "",
- "apiBase": "http://localhost:8000/v1",
+ "apiBase": "http://localhost:8000/v1",
"useLegacyCompletionsEndpoint": true
}
]
diff --git a/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx b/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx
new file mode 100644
index 000000000..a074eef7d
--- /dev/null
+++ b/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx
@@ -0,0 +1,252 @@
+---
+title: "Tetrate Agent Router Service"
+sidebarTitle: "Tetrate Agent Router Service"
+slug: ../tetrate-agent-router-service
+---
+The **Tetrate Agent Router Service** provides a unified Gateway for accessing various AI models with fast inference capabilities.
+
+This gateway acts as an intelligent router that can distribute requests across multiple model providers, offering enterprise-grade reliability and performance optimization.
+
+
+Want to get started quickly? Sign up for the [Tetrate Agent Router Service](https://router.tetrate.ai/) to get an API key, then use [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) to get started fast.
+
+
+## Setup
+
+
+
+Visit the [Agent Router Service portal](https://router.tetrate.ai/) and create an account to get your API key
+
+
+
+
+Go to the [API keys page](https://router.tetrate.ai/api-keys) to get your key
+
+
+
+
+- Choose a configuration method below.
+- If you use the Continue VS Code extension, install version `>=1.2.3`.
+
+
+
+
+
+### Quickstart with Continue Hub
+
+Fastest way: use preconfigured models from Tetrate on Continue Hub
+
+
+
+Open [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) and pick a model (e.g., [Claude Sonnet 4](https://hub.continue.dev/tetrate/claude-sonnet-4))
+
+
+
+Click "Use Model", or "Remix" to change the model ID if needed
+
+
+
+Add your API key to Continue. See [adding secrets in Continue Hub](/hub/secrets/secret-types) and [managing local secrets in the FAQ](/faqs#managing-local-secrets-and-environment-variables)
+
+Add it as a Continue Hub secret named `TETRATE_API_KEY` to reuse across projects.
+
+
+
+
+
+
+
+If a model is missing, remix a similar one and set the `model` field to the target ID.
+
+
+### Configuration Methods
+
+
+
+ Use a Tetrate model block from the Hub or define it directly in your local agent configuration.
+
+
+ Use a Tetrate model block from the Hub or define your own on the Hub.
+
+
+ Create a local model block for reuse across agents without publishing it to the Hub.
+
+
+
+
+### Configuration Examples
+
+**Click a tab** to see an example.
+
+
+
+
+**When to use**: Simple local setups (like using the VS Code extension) when you don't need shared or published blocks.
+
+Use a Tetrate model block from the Hub in your local agent configuration:
+
+```yaml title="~/.continue/config.yaml"
+name: Local Agent
+version: 1.0.0
+schema: v1
+models:
+ - uses: tetrate/claude-sonnet-4
+ with:
+ TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
+context:
+ - provider: code
+ - provider: docs
+ - provider: diff
+ - provider: terminal
+ - provider: problems
+ - provider: folder
+ - provider: codebase
+```
+
+Or define the model directly:
+
+```yaml title="~/.continue/config.yaml"
+name: Local Agent
+version: 1.0.0
+schema: v1
+models:
+ - name: Claude Sonnet 4
+ provider: tars
+ model: claude-4-sonnet-20250514
+ apiKey: ${{ secrets.TETRATE_API_KEY }}
+ roles:
+ - chat
+ - edit
+ - apply
+ capabilities:
+ - tool_use
+context:
+ - provider: code
+ - provider: docs
+ - provider: diff
+ - provider: terminal
+ - provider: problems
+ - provider: folder
+ - provider: codebase
+```
+
+
+**When to use**: Share configurations across teams or contribute to the community.
+
+**The Model Block:**
+
+```yaml title="tetrate/claude-sonnet-4"
+name: Claude Sonnet 4
+version: 1.0.14
+schema: v1
+models:
+ - name: Claude Sonnet 4 - Tetrate
+ provider: tars
+ model: claude-4-sonnet-20250514
+ apiKey: ${{ inputs.TETRATE_API_KEY }}
+ roles:
+ - chat
+ - edit
+ - apply
+ capabilities:
+ - tool_use
+```
+View the model block `tetrate/claude-sonnet-4` on the [Continue Hub](https://hub.continue.dev/tetrate/claude-sonnet-4).
+
+**Reference it in your Agent configuration:**
+
+```yaml title="my-agent"
+name: My Agent
+version: 1.0.0
+schema: v1
+models:
+ - uses: tetrate/claude-sonnet-4
+ with:
+ TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
+context:
+ - uses: continuedev/diff-context
+ - uses: continuedev/terminal-context
+ - uses: continuedev/file-context
+```
+
+To customize, see the [model block creation guide](/hub/blocks/create-a-block).
+
+
+
+
+
+**When to use**: Reuse configurations across agents and keep them local or in GitHub (not on Continue Hub).
+
+**The Local Model Block:**
+
+Name the file `my-claude-4-model.yaml` so you can reference it in the Agent.
+
+
+```yaml title="~/.continue/models/my-claude-4-model.yaml"
+name: Claude Sonnet 4
+version: 1.0.1
+schema: v1
+models:
+ - name: Claude Sonnet 4
+ provider: tars
+ model: claude-4-sonnet-20250514
+ apiKey: ${{ inputs.TETRATE_API_KEY }}
+ roles:
+ - chat
+ - edit
+ - apply
+ capabilities:
+ - tool_use
+```
+Reference it as `my-claude-4-model` in your Agent configuration:
+
+```yaml title="~/.continue/agents/simple-agent.yaml"
+name: Simple Agent
+version: 1.0.0
+schema: v1
+models:
+ - uses: my-claude-4-model
+ with:
+ TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
+context:
+ - uses: continuedev/diff-context
+ - uses: continuedev/terminal-context
+ - uses: continuedev/file-context
+```
+
+
+Learn more about [model blocks](/reference#models) and [local blocks](/reference#local-blocks).
+
+
+
+
+
+---
+
+## Troubleshooting Common Issues
+
+
+
+ Verify your API key is active and has no extra spaces.
+
+
+ Confirm the model ID matches the Tetrate catalog.
+
+
+ Check your network or try a less-loaded model. Contact Tetrate support if issues persist.
+
+
+ Validate YAML syntax and review error messages in Continue. If using Hub, ensure the block is published.
+
+
+
+---
+
+## Join the Community
+Connect with Tetrate and other builders for help and discussion.
+
+
+
+Get answers, insights, and best practices for secure, scalable infrastructure
+
+
diff --git a/docs/customize/model-roles.mdx b/docs/customize/model-roles.mdx
index 8db06d857..7349ad539 100644
--- a/docs/customize/model-roles.mdx
+++ b/docs/customize/model-roles.mdx
@@ -2,7 +2,7 @@
title: "Model roles"
sidebarTitle: Overview
icon: "circle-info"
-description: "Learn about the different model roles in Continue including chat, autocomplete, edit, apply, embeddings, and reranking for customizing your AI coding assistant's capabilities"
+description: "Learn about the different model roles in Continue including chat, autocomplete, edit, apply, embeddings, and reranking for customizing your AI coding agent's capabilities"
---
diff --git a/docs/customize/model-roles/00-intro.mdx b/docs/customize/model-roles/00-intro.mdx
index b82c9bd71..941ea0f4d 100644
--- a/docs/customize/model-roles/00-intro.mdx
+++ b/docs/customize/model-roles/00-intro.mdx
@@ -23,7 +23,7 @@ These roles can be specified for a `config.yaml` model block using `roles`. See
## Selecting model roles
-You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role.
+You can control which of the models in your agent for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role.

diff --git a/docs/customize/model-roles/chat.mdx b/docs/customize/model-roles/chat.mdx
index afafb8591..f7fbedbc3 100644
--- a/docs/customize/model-roles/chat.mdx
+++ b/docs/customize/model-roles/chat.mdx
@@ -36,20 +36,6 @@ Our current top recommendations are Claude Opus 4.1 and Claude Sonnet 4 from [An
apiKey:
```
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Claude Opus 4.1",
- "provider": "anthropic",
- "model": "claude-4-1-opus",
- "apiKey": ""
- }
- ]
- }
- ```
-
### Gemma from Google DeepMind
@@ -88,37 +74,6 @@ If you prefer to use an open-weight model, then the Gemma family of Models from
-
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Gemma 3 27B",
- "provider": "ollama",
- "model": "gemma3:27b"
- }
- ]
- }
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Gemma 3 27B",
- "provider": "together",
- "model": "google/gemma-2-27b-it",
- "apiKey": ""
- }
- ]
- }
- ```
-
-
-
### GPT-4o from OpenAI
@@ -138,20 +93,6 @@ If you prefer to use a model from [OpenAI](../model-providers/top-level/openai),
apiKey:
```
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "GPT-4o",
- "provider": "openai",
- "model": "",
- "apiKey": ""
- }
- ]
- }
- ```
-
### Grok-2 from xAI
@@ -171,20 +112,6 @@ If you prefer to use a model from [xAI](../model-providers/more/xAI), then we re
apiKey:
```
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Grok-2",
- "provider": "xAI",
- "model": "grok-2-latest",
- "apiKey": ""
- }
- ]
- }
- ```
-
### Gemini 2.0 Flash from Google
@@ -204,20 +131,6 @@ If you prefer to use a model from [Google](../model-providers/top-level/gemini),
apiKey:
```
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Gemini 2.0 Flash",
- "provider": "gemini",
- "model": "gemini-2.0-flash",
- "apiKey": ""
- }
- ]
- }
- ```
-
## Local, offline experience
@@ -268,49 +181,6 @@ If your local machine can run an 8B parameter model, then we recommend running L
-
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Llama 3.1 8B",
- "provider": "ollama",
- "model": "llama3.1:8b"
- }
- ]
- }
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Llama 3.1 8B",
- "provider": "lmstudio",
- "model": "llama3.1-8b"
- }
- ]
- }
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Llama 3.1 8B",
- "provider": "msty",
- "model": "llama3.1-8b"
- }
- ]
- }
- ```
-
-
-
### DeepSeek Coder 2 16B
@@ -357,50 +227,6 @@ If your local machine can run a 16B parameter model, then we recommend running D
-
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "DeepSeek Coder 2 16B",
- "provider": "ollama",
- "model": "deepseek-coder-v2:16b",
- "apiBase": "http://localhost:11434"
- }
- ]
- }
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "DeepSeek Coder 2 16B",
- "provider": "lmstudio",
- "model": "deepseek-coder-v2:16b"
- }
- ]
- }
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "DeepSeek Coder 2 16B",
- "provider": "msty",
- "model": "deepseek-coder-v2:16b"
- }
- ]
- }
- ```
-
-
-
## Other experiences
diff --git a/docs/customize/model-roles/edit.mdx b/docs/customize/model-roles/edit.mdx
index e60d47017..3fe2b9143 100644
--- a/docs/customize/model-roles/edit.mdx
+++ b/docs/customize/model-roles/edit.mdx
@@ -6,42 +6,19 @@ sidebar_position: 3
---
import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx'
-It's often useful to select a different model to respond to Edit prompts than for chat prompts, as Edits are often more code-specific and may require less conversational readability.
+It's often useful to select a different model to respond to Edit instructions than for Chat instructions, as Edits are often more code-specific and may require less conversational readability.
In Continue, you can add `edit` to a model's roles to specify that it can be used for Edit requests. If no edit models are specified, the selected `chat` model is used.
-
-
- Use model roles.
- ```yaml title="config.yaml"
- models:
- - name: Claude 3.5 Sonnet
- provider: anthropic
- model: claude-3-5-sonnet-latest
- apiKey:
- roles:
- - edit
- ```
-
-
- Set the `experimental.modelRoles.inlineEdit` property in `config.json`.
- ```json title="config.json"
- {
- "models": {
- "name": "Claude 3.5 Sonnet",
- "provider": "anthropic",
- "model": "claude-3-5-sonnet-latest",
- "apiKey": ""
- },
- "experimental": {
- "modelRoles": {
- "inlineEdit": "Claude 3.5 Sonnet",
- }
- }
- }
- ```
-
-
+```yaml title="config.yaml"
+models:
+ - name: Claude 4 Sonnet
+ provider: anthropic
+ model: claude-3-5-sonnet-latest
+ apiKey:
+ roles:
+ - edit
+```
Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat.
diff --git a/docs/customize/model-roles/embeddings.mdx b/docs/customize/model-roles/embeddings.mdx
index a81bb2322..ea1019c5d 100644
--- a/docs/customize/model-roles/embeddings.mdx
+++ b/docs/customize/model-roles/embeddings.mdx
@@ -7,7 +7,7 @@ sidebar_position: 5
An "embeddings model" is trained to convert a piece of text into a vector, which can later be rapidly compared to other vectors to determine similarity between the pieces of text. Embeddings models are typically much smaller than LLMs, and will be extremely fast and cheap in comparison.
-In Continue, embeddings are generated during indexing and then used by [@Codebase](../context/codebase) to perform similarity search over your codebase.
+In Continue, embeddings are generated during indexing and then used by [codebase awareness](/guides/codebase-documentation-awareness) to perform similarity search over your codebase.
You can add `embed` to a model's `roles` to specify that it can be used to embed.
diff --git a/docs/customize/model-roles/intro.mdx b/docs/customize/model-roles/intro.mdx
index fdba06544..9fa344afe 100644
--- a/docs/customize/model-roles/intro.mdx
+++ b/docs/customize/model-roles/intro.mdx
@@ -7,7 +7,7 @@ icon: "book-open"
- [`chat`](/customize/model-roles/chat): Used for chat conversations in the extension sidebar
- [`autocomplete`](/customize/model-roles/autocomplete): Used for autocomplete code suggestions in the editor
-- [`edit`](/customize/model-roles/edit): Used to generate code based on edit prompts
+- [`edit`](/customize/model-roles/edit): Used to generate code based on edit instructions
- [`apply`](/customize/model-roles/apply): Used to decide how to apply edits to a file
- [`embed`](/customize/model-roles/embeddings): Used to generate embeddings used for vector search (@Codebase and @Docs context providers)
- [`rerank`](/customize/model-roles/reranking): Used to rerank results from vector search
@@ -16,7 +16,7 @@ These roles can be specified for a `config.yaml` model block using `roles`. See
## Selecting model roles
-You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role.
+You can control which of the models in your agent for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role.
diff --git a/docs/customize/model-roles/reranking.mdx b/docs/customize/model-roles/reranking.mdx
index ed5974b4b..93829f46c 100644
--- a/docs/customize/model-roles/reranking.mdx
+++ b/docs/customize/model-roles/reranking.mdx
@@ -7,7 +7,7 @@ sidebar_position: 6
A "reranking model" is trained to take two pieces of text (often a user question and a document) and return a relevancy score between 0 and 1, estimating how useful the document will be in answering the question. Rerankers are typically much smaller than LLMs, and will be extremely fast and cheap in comparison.
-In Continue, rerankers are designated using the `rerank` role and used by [@Codebase](../context/codebase) in order to select the most relevant code snippets after vector search.
+In Continue, rerankers are designated using the `rerank` role and used by [codebase awareness](/guides/codebase-documentation-awareness) in order to select the most relevant code snippets after vector search.
## Recommended reranking models
@@ -23,7 +23,10 @@ Voyage AI offers the best reranking model for code with their `rerank-2` model.
- [Voyage Rerank 2 Block](https://hub.continue.dev/voyageai/rerank-2)
+ ```yaml title="config.yaml"
+ models:
+ - uses: voyageai/rerank-2
+ ```
```yaml title="config.yaml"
@@ -36,19 +39,6 @@ Voyage AI offers the best reranking model for code with their `rerank-2` model.
- rerank
```
-
- ```json title="config.json"
- {
- "reranker": {
- "name": "voyage",
- "params": {
- "model": "rerank-2",
- "apiKey": ""
- }
- }
- }
- ```
-
### Cohere
@@ -71,19 +61,6 @@ See Cohere's documentation for rerankers [here](https://docs.cohere.com/docs/rer
- rerank
```
-
- ```json title="config.json"
- {
- "reranker": {
- "name": "cohere",
- "params": {
- "model": "rerank-english-v3.0",
- "apiKey": ""
- }
- }
- }
- ```
-
### LLM
@@ -105,21 +82,9 @@ If you only have access to a single LLM, then you can use it as a reranker. This
- rerank
```
-
- ```json title="config.json"
- {
- "reranker": {
- "name": "llm",
- "params": {
- "modelTitle": "My Model Title"
- }
- }
- }
- ```
-
-The `"modelTitle"` field must match one of the models in your "models" array in config.json.
+
### Text Embeddings Inference
@@ -142,17 +107,4 @@ The `"modelTitle"` field must match one of the models in your "models" array in
- rerank
```
-
- ```json title="config.json"
- {
- "reranker": {
- "name": "huggingface-tei",
- "params": {
- "apiBase": "http://localhost:8080",
- "apiKey": ""
- }
- }
- }
- ```
-
diff --git a/docs/customize/overview.mdx b/docs/customize/overview.mdx
index f46d43e03..59d8fde68 100644
--- a/docs/customize/overview.mdx
+++ b/docs/customize/overview.mdx
@@ -7,7 +7,7 @@ description: "Explore Continue's advanced capabilities for power users and compl
Specialized context features for codebase understanding and documentation integration.
-[Browse Context Features β](/guides/understanding-assistants)
+[Browse Context Features β](/guides/understanding-agents)
## Deep Dives
diff --git a/docs/docs.json b/docs/docs.json
index 1d6eb5b42..1e783f7ee 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -23,6 +23,11 @@
"getting-started/quick-start"
]
},
+ {
+ "group": "CLI",
+ "icon": "terminal",
+ "pages": ["cli/overview", "cli/install", "cli/quick-start"]
+ },
{
"group": "Features",
"icon": "star",
@@ -83,13 +88,14 @@
"customization/models",
"customization/mcp-tools",
"customization/rules",
- "customization/prompts"
+ "customization/prompts",
+ "customization/settings"
]
},
{
"group": "Help",
"icon": "book-open",
- "pages": ["faqs", "troubleshooting"]
+ "pages": ["faqs", "troubleshooting", "CONTRIBUTING"]
}
]
},
@@ -117,6 +123,7 @@
"customize/model-providers/top-level/ollama",
"customize/model-providers/top-level/openrouter",
"customize/model-providers/top-level/openai",
+ "customize/model-providers/top-level/tetrate_agent_router_service",
"customize/model-providers/top-level/vertexai"
]
},
@@ -179,13 +186,13 @@
"pages": [
"hub/introduction",
{
- "group": "Assistants",
+ "group": "Agents",
"icon": "robot",
"pages": [
- "hub/assistants/intro",
- "hub/assistants/use-an-assistant",
- "hub/assistants/create-an-assistant",
- "hub/assistants/edit-an-assistant"
+ "hub/agents/intro",
+ "hub/agents/use-an-agent",
+ "hub/agents/create-an-agent",
+ "hub/agents/edit-an-agent"
]
},
{
@@ -215,6 +222,11 @@
"hub/secrets/secret-resolution"
]
},
+ {
+ "group": "Workflows",
+ "icon": "cloud",
+ "pages": ["hub/workflows/intro"]
+ },
"hub/sharing",
"hub/source-control"
]
@@ -228,15 +240,32 @@
"group": "Guides",
"pages": [
"guides/overview",
- "guides/understanding-assistants",
+ "guides/understanding-agents",
+ "guides/configuring-models-rules-tools",
"guides/codebase-documentation-awareness",
"guides/cli",
+ "guides/doc-writing-agent-cli",
+ "guides/continuous-ai",
+ "guides/continuous-ai-readiness-assessment",
"guides/plan-mode-guide",
"guides/ollama-guide",
+ "guides/instinct",
"guides/running-continue-without-internet",
"guides/custom-code-rag",
"guides/how-to-self-host-a-model"
]
+ },
+ {
+ "group": "Cookbooks",
+ "icon": "book-open-cover",
+ "pages": [
+ "guides/posthog-github-continuous-ai",
+ "guides/continue-docs-mcp-cookbook",
+ "guides/sanity-mcp-continue-cookbook",
+ "guides/snyk-mcp-continue-cookbook",
+ "guides/dlt-mcp-continue-cookbook",
+ "guides/netlify-mcp-continuous-deployment"
+ ]
}
]
},
@@ -346,18 +375,10 @@
"source": "/hub/secrets",
"destination": "/hub/secrets/secret-types"
},
- {
- "source": "/hub/assistants",
- "destination": "/hub/assistants/intro"
- },
{
"source": "/hub/blocks",
"destination": "/hub/blocks/intro"
},
- {
- "source": "/hub/agents/intro",
- "destination": "/hub/assistants/intro"
- },
{
"source": "/customize",
"destination": "/customization/overview"
@@ -1104,7 +1125,7 @@
},
{
"source": "/troubleshooting#changes-to-assistants-not-showing-in-vs-code",
- "destination": "/faqs#changes-to-assistants-not-showing-in-vs-code"
+ "destination": "/faqs#changes-to-agents-not-showing-in-vs-code"
},
{
"source": "/troubleshooting#i-installed-continue-but-dont-see-the-sidebar-window",
@@ -1173,6 +1194,26 @@
{
"source": "/features/edit/next-edit",
"destination": "/features/autocomplete/next-edit"
+ },
+ {
+ "source": "/hub/assistants/intro",
+ "destination": "/hub/agents/intro"
+ },
+ {
+ "source": "/hub/assistants/use-an-assistant",
+ "destination": "/hub/agents/use-an-agent"
+ },
+ {
+ "source": "/hub/assistants/create-an-assistant",
+ "destination": "/hub/agents/create-an-agent"
+ },
+ {
+ "source": "/hub/assistants/edit-an-assistant",
+ "destination": "/hub/agents/edit-an-agent"
+ },
+ {
+ "source": "/guides/understanding-assistants",
+ "destination": "/guides/understanding-agents"
}
]
}
diff --git a/docs/faqs.mdx b/docs/faqs.mdx
index 7836ef9d3..36b93ff77 100644
--- a/docs/faqs.mdx
+++ b/docs/faqs.mdx
@@ -48,15 +48,15 @@ If you are using VS Code and require requests to be made through a proxy, you ar
Continue can be used in [code-server](https://coder.com/), but if you are running across an error in the logs that includes "This is likely because the editor is not running in a secure context", please see [their documentation on securely exposing code-server](https://coder.com/docs/code-server/latest/guide#expose-code-server).
-## Changes to assistants not showing in VS Code
+## Changes to agents not showing in VS Code
-If you've made changes to assistants (adding, modifying, or removing them) but the changes aren't appearing in the Continue extension in VS Code, try reloading the VS Code window:
+If you've made changes to agents (adding, modifying, or removing them) but the changes aren't appearing in the Continue extension in VS Code, try reloading the VS Code window:
1. Open the command palette (`cmd/ctrl` + `shift` + `P`)
2. Type "Reload Window"
3. Select the reload option
-This will restart VS Code and reload all extensions, which should make your assistant changes visible.
+This will restart VS Code and reload all extensions, which should make your agent changes visible.
## I installed Continue, but don't see the sidebar window
@@ -256,7 +256,7 @@ If you're getting parse errors with remote Ollama:
3. **Check URL format**: Ensure you're using `http://` not `https://` for local network addresses
-## Local Assistant
+## Local Agent
### Managing Local Secrets and Environment Variables
@@ -318,7 +318,7 @@ If your API keys aren't being recognized:
### Using Model Addons Locally
-You can leverage model addons from the Continue Hub in your local assistant configurations using the `uses:` syntax. This allows you to reference pre-configured model blocks without duplicating configuration.
+You can leverage model addons from the Continue Hub in your local agent configurations using the `uses:` syntax. This allows you to reference pre-configured model blocks without duplicating configuration.
#### Requirements
@@ -330,7 +330,7 @@ You can leverage model addons from the Continue Hub in your local assistant conf
In your local `config.yaml`, reference model addons using the format `provider/model-name`:
```yaml
-name: My Local Assistant
+name: My Local Agent
version: 0.0.1
schema: v1
models:
@@ -344,7 +344,7 @@ models:
You can combine hub model addons with local models:
```yaml
-name: My Local Assistant
+name: My Local Agent
version: 0.0.1
schema: v1
models:
diff --git a/docs/features/agent/how-to-customize.mdx b/docs/features/agent/how-to-customize.mdx
index b26994906..1cf18bf31 100644
--- a/docs/features/agent/how-to-customize.mdx
+++ b/docs/features/agent/how-to-customize.mdx
@@ -6,7 +6,7 @@ sidebarTitle: "Customize Agent"
## How to Add Rules Blocks
-Adding Rules can be done in your assistant locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details.
+Adding Rules can be done in your agent locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details.
## How to Customize System Messages
@@ -18,14 +18,14 @@ models:
provider: openai
model: gpt-4o
chatOptions:
- baseSystemMessage: "You are a helpful coding assistant."
- baseAgentSystemMessage: "You are a systematic coding assistant. Break down problems methodically."
- basePlanSystemMessage: "You are a planning assistant. Create clear, actionable steps."
+ baseSystemMessage: "You are a helpful coding agent."
+ baseAgentSystemMessage: "You are a systematic coding agent. Break down problems methodically."
+ basePlanSystemMessage: "You are a planning agent. Create clear, actionable steps."
```
## How to Add MCP Tools
-You can add MCP servers to your assistant to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details.
+You can add MCP servers to your agent to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details.
## How to Configure Tool Policies
diff --git a/docs/features/autocomplete/how-to-customize.mdx b/docs/features/autocomplete/how-to-customize.mdx
index 854be157e..4fab64383 100644
--- a/docs/features/autocomplete/how-to-customize.mdx
+++ b/docs/features/autocomplete/how-to-customize.mdx
@@ -3,6 +3,6 @@ title: βCustomize Autocomplete Settings in Continueβ
description: βLearn how to customize autocomplete behavior in Continue, including user settings, configuration options, and adjustments to improve AI code suggestions in your IDE.β
---
-Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings.
+Continue offers a handful of settings to customize autocomplete behavior. Visit the User Settings Page (Gear Icon) to manage these settings.
For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete).
diff --git a/docs/features/autocomplete/next-edit.mdx b/docs/features/autocomplete/next-edit.mdx
index edeb77463..c39148427 100644
--- a/docs/features/autocomplete/next-edit.mdx
+++ b/docs/features/autocomplete/next-edit.mdx
@@ -4,8 +4,9 @@ description: "Learn how Continue's Next Edit feature predicts and suggests your
---
- Next Edit is currently an experimental feature. It requires [Mercury Coder
- model](https://hub.continue.dev/inceptionlabs/mercury-coder) configured in
+ Next Edit is currently an experimental feature. It requires
+ [Instinct](https://hub.continue.dev/continuedev/instinct) or [Mercury Coder
+ model](https://hub.continue.dev/inception/mercury-coder) configured in
your Continue autocomplete settings and is not yet available for JetBrains
use.
@@ -71,18 +72,17 @@ Next Edit activates automatically when:
Next Edit requires:
-- Compatible AI models (Mercury Coder)
-- Continue development team access
+- Compatible AI models (Mercury Coder or Instinct)
- VS Code (JetBrains support coming soon)
- **API Keys**: Organizations can add API keys to [org secrets](/hub/secrets/secret-types) for team-wide access. Individual users need to provide their own API keys in their [model configuration](/customize/model-providers/overview)
- To use Next Edit, you must have the Mercury Coder model configured in your
- Continue autocomplete model settings. This model is specifically designed for
- next edit predictions. Once it's been loaded, you must reload VS Code to
- activate it.
+ To use Next Edit, you must have the Instinct or Mercury Coder model configured
+ in your Continue autocomplete model settings. This model is specifically
+ designed for next edit predictions. Once it's been loaded, you must reload VS
+ Code to activate it.
@@ -117,6 +117,7 @@ Next Edit requires:
Next Edit requires AI models specifically trained for code prediction:
- **Mercury Coder**: Primary model optimized for next edit prediction
+- **Instinct**: The leading open Next Edit model, trained by Continue
### Automatic Detection
diff --git a/docs/features/chat/how-it-works.mdx b/docs/features/chat/how-it-works.mdx
index 381b49b7c..252ce2898 100644
--- a/docs/features/chat/how-it-works.mdx
+++ b/docs/features/chat/how-it-works.mdx
@@ -48,7 +48,7 @@ View the exact prompt sent to the AI model in the [prompt logs](/troubleshooting
Learn more about how you can bring in context:
-- [Codebase Context](/customize/context/codebase)
+- [Codebase Context](/guides/codebase-documentation-awareness)
- [Documentation Context](/guides/codebase-documentation-awareness)
- [Built-in Context Providers](/customize/deep-dives/custom-providers)
diff --git a/docs/features/edit/how-to-customize.mdx b/docs/features/edit/how-to-customize.mdx
index b200e2e67..f6925e764 100644
--- a/docs/features/edit/how-to-customize.mdx
+++ b/docs/features/edit/how-to-customize.mdx
@@ -6,7 +6,7 @@ sidebarTitle: "Customize Edit"
## How to Set Active Edit/Apply Model
-You can configure particular models from your Assistant to be used for Edit and Apply requests.
+You can configure particular models from your Agent to be used for Edit and Apply requests.
1. Click the 3 dots above the main input
2. Click the cube icon to expand the "Models" section
diff --git a/docs/getting-started/extensions.mdx b/docs/getting-started/extensions.mdx
index 1904b97bc..9b38a02ee 100644
--- a/docs/getting-started/extensions.mdx
+++ b/docs/getting-started/extensions.mdx
@@ -1,6 +1,6 @@
---
-title: "Understanding Assistants"
+title: "Understanding Agents"
description: "Continue offers two ways to configure your AI assistants"
---
-This content has moved to our comprehensive guide: [Understanding Assistants: Hub vs Local Configuration](/guides/understanding-assistants)
+This content has moved to our comprehensive guide: [Understanding Agents: Hub vs Local Configuration](/guides/understanding-agents)
diff --git a/docs/getting-started/install.mdx b/docs/getting-started/install.mdx
index c76a6515b..739f88394 100644
--- a/docs/getting-started/install.mdx
+++ b/docs/getting-started/install.mdx
@@ -24,7 +24,7 @@ The Continue logo will appear on the left sidebar. For a better experience, move
-[Sign in to the hub](https://auth.continue.dev/) to get started with your first assistant
+[Sign in to the hub](https://auth.continue.dev/) to get started with your first agent
@@ -54,7 +54,7 @@ Click `Install`, which will cause the Continue logo to show up on the right tool
-[Sign in to the hub](https://auth.continue.dev/) to get started with your first assistant
+[Sign in to the hub](https://auth.continue.dev/) to get started with your first agent
@@ -68,6 +68,6 @@ Click `Install`, which will cause the Continue logo to show up on the right tool
## Signing in
-Click "Get started" to sign in to the hub and start using assistants.
+Click "Get started" to sign in to the hub and start using agents.

diff --git a/docs/getting-started/overview.mdx b/docs/getting-started/overview.mdx
index 18d8b67f3..a0afaabfa 100644
--- a/docs/getting-started/overview.mdx
+++ b/docs/getting-started/overview.mdx
@@ -57,6 +57,6 @@ description: "To quickly understand what you can do with Continue, check out eac
-## AI Coding Assistants
+## AI Coding Agents
-Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Assistants** for easy setup and synchronization, or **Local Assistants** for complete control and privacy. Learn more about [understanding and configuring assistants](/guides/understanding-assistants).
+Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Agents** for easy setup and synchronization, or **Local Agents** for complete control and privacy. Learn more about [understanding and configuring agents](/guides/understanding-agents).
diff --git a/docs/getting-started/quick-start.mdx b/docs/getting-started/quick-start.mdx
index f27899dd7..83b7ac8cb 100644
--- a/docs/getting-started/quick-start.mdx
+++ b/docs/getting-started/quick-start.mdx
@@ -247,12 +247,12 @@ Ready to master specific features? Check out these detailed guides:
Discover [effective prompting techniques](/customize/deep-dives/prompts), [hub
- v. local assistants](/guides/understanding-assistants), and [custom slash
- commands](/customize/deep-dives/slash-commands).
+ v. local agents](/guides/understanding-agents), and [custom slash
+ commands](/customize/deep-dives/prompts).
- Explore [Hub Assistants](/hub/assistants/intro), [organization
+ Explore [Hub Agents](/hub/agents/intro), [organization
management](/hub/governance/creating-an-org), and [sharing
configurations](/hub/sharing).
diff --git a/docs/guides/cli.mdx b/docs/guides/cli.mdx
index 069bf640a..4610d6301 100644
--- a/docs/guides/cli.mdx
+++ b/docs/guides/cli.mdx
@@ -87,6 +87,12 @@ cn --ask Bash(curl*)
cn --exclude Fetch
```
+## API Key Authentication
+
+For automation in CI or other headless environments, you can use an API key to authenticate with Continue. First, obtain your personal API key [here](https://hub.continue.dev/settings/api-keys). Then, set it as the `CONTINUE_API_KEY` environment variable. You can now use `cn -p` (headless mode) without needing to log in.
+
+If you wish to run an automation on behalf of your organization you can obtain an organization-scoped API key by going to [your organization's settings](https://hub.continue.dev/settings/organizations) -> API Keys.
+
## Troubleshooting
Run `cn` with the `--verbose` flag to see more detailed logs. These will be output to `~/.continue/logs/cn.log`.
diff --git a/docs/guides/codebase-documentation-awareness.mdx b/docs/guides/codebase-documentation-awareness.mdx
index 055055360..dbc03609b 100644
--- a/docs/guides/codebase-documentation-awareness.mdx
+++ b/docs/guides/codebase-documentation-awareness.mdx
@@ -1,11 +1,10 @@
---
-title: How to make your agent aware of codebases and documentation
+title: How to Make Your Agent Aware of Codebases and Documentation
description: Learn how to give your AI agent access to codebases and documentation for more context-aware assistance
keywords: [agent, codebase, documentation, MCP, context, RAG, tools]
+sidebarTitle: Codebase and Documentation Awareness
---
-# How to make your agent aware of codebases and documentation
-
AI coding agents work best when they understand the context of your project. This guide shows you how to give your agent access to codebases and documentation, making it more helpful and accurate.
## Make your agent aware of your open codebase
@@ -28,18 +27,21 @@ Rules guide your agent's behavior and understanding. Place markdown files in `.c
# Project Architecture
This is a React application with:
+
- Components in `/src/components`
- API routes in `/src/api`
- State management using Redux in `/src/store`
## Coding Standards
+
- Use TypeScript for all new files
- Follow the existing naming conventions
- Write tests for all new features
```
- Place rules files at different levels of your project hierarchy to scope when they trigger
+ Place rules files at different levels of your project hierarchy to scope when
+ they trigger
Learn more about [rules configuration](/customize/deep-dives/rules).
@@ -60,6 +62,7 @@ Create rules that point to external codebases:
# External Dependencies
Our authentication system is based on:
+
- [Auth.js documentation](https://authjs.dev/)
- [Example implementation](https://github.com/nextauthjs/next-auth-example)
@@ -76,6 +79,7 @@ Add rules to guide CLI usage:
# Repository Access
You can use the `gh` CLI to:
+
- Search for issues: `gh issue list --repo owner/repo`
- View pull requests: `gh pr list --repo owner/repo`
- Clone repositories: `gh repo clone owner/repo`
@@ -84,9 +88,9 @@ You can use the `gh` CLI to:
#### DeepWiki MCP
[DeepWiki MCP](https://hub.continue.dev/deepwiki/deepwiki-mcp) lets your agent explore any public GitHub repository.
-```
Once configured, your agent can explore repositories like:
+
- "Explore the React repository structure"
- "Find how authentication is implemented in NextAuth.js"
@@ -116,6 +120,7 @@ Guide your agent to relevant documentation:
# Documentation Resources
For framework-specific questions, refer to:
+
- React: https://react.dev/reference/react
- Next.js: https://nextjs.org/docs
- Tailwind CSS: https://tailwindcss.com/docs
@@ -128,6 +133,7 @@ Always cite documentation when explaining concepts.
[Context7 MCP](https://hub.continue.dev/upstash/context7-mcp) enables your agent to search and retrieve information from public documentation:
Your agent can then answer questions like:
+
- "How do I use React hooks?"
- "What's the syntax for Tailwind CSS animations?"
@@ -143,6 +149,7 @@ Create rules that reference internal resources:
# Internal Documentation
Our team documentation is available at:
+
- API Documentation: https://internal.docs/api
- Architecture Guide: https://internal.docs/architecture
- Deployment Process: https://internal.docs/deployment
@@ -180,4 +187,4 @@ The new approach provides better integration with Continue's Agent features and
- Learn more about [MCP servers](/reference/continue-mcp)
- Explore [rules configuration](/customize/deep-dives/rules)
-- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains
\ No newline at end of file
+- Set up [custom agents](/guides/understanding-agents) with specific knowledge domains
diff --git a/docs/guides/configuring-models-rules-tools.mdx b/docs/guides/configuring-models-rules-tools.mdx
new file mode 100644
index 000000000..2a2d3d87e
--- /dev/null
+++ b/docs/guides/configuring-models-rules-tools.mdx
@@ -0,0 +1,168 @@
+---
+title: "Configuring Models, Rules, and Tools"
+description: "Learn how to work with Continue's configuration system. Understand how to use hub models, rules, and tools, create local configurations, and organize your setup for maximum reusability."
+---
+
+## What Are Models, Rules, and Tools?
+
+Continue agents are built from three main types of configuration:
+
+
+
+Language models that power different capabilities like chat, autocomplete, and agent mode
+
+
+
+ Guidelines and instructions that shape how the AI behaves and responds
+
+
+
+MCP tools that provide additional capabilities like database access, web search, or custom functions
+
+
+
+There are two places where you can define these configurations:
+
+
+
+Custom configurations you create and manage in your workspace or globally
+
+
+
+Pre-built models, rules, and tools from the Continue community that you can import and use immediately
+
+
+
+## Local
+
+Local configurations let you create custom models, rules, and tools that automatically apply to multiple agents, reducing duplication and ensuring consistency across your setup.
+
+
+
+Applied to all agents across all workspaces. Ideal for personal preferences, universal coding standards, or tools you use everywhere.
+
+
+Applied automatically to all agents when working in a specific project.
+
+Perfect for project-specific setups like TypeScript rules for web apps or the Playwright MCP tool.
+
+
+
+
+
+## Hub
+
+Continue hub uses a slug in the format of `owner/item-name` to resolve blocks.
+
+For example, to use the [Claude 4 Sonnet model](https://hub.continue.dev/anthropic/claude-4-sonnet), you'd reference it as `anthropic/claude-4-sonnet`.
+
+Import from the hub using the `uses` syntax alongside your custom configurations:
+
+```yaml config.yaml highlight={6}
+name: Team Agent
+version: 1.0.0
+schema: v1
+
+models:
+ - uses: anthropic/claude-4-sonnet
+ with:
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} # Use a hub secret
+```
+
+### Organization
+
+Organize your local configurations using these directories:
+
+
+
+ `.continue/models`
+
+
+
+ `.continue/rules`
+
+
+
+ `.continue/mcpServers`
+
+
+
+## Working with Secrets
+
+Models, and many MCP servers, require a secret for things like API keys.
+
+On the hub, you can configure secrets when adding a model or MCP server.
+
+This will use mustache notation to pass the secret, eg `${{ secrets.SECRET_NAME }}`
+
+When configuring a local model or MCP server, you can use the same mustache notation for secrets which read from:
+
+
+
+`.env` file in `~/.continue/.env`
+
+
+
+`.env` file at your project root
+
+
+
+## Overriding Properties
+
+You can directly override properties using the `override` syntax:
+
+```yaml title="config.yaml" highlight={10-13}
+name: myprofile/custom-agent
+version: 1.0.0
+schema: v1
+
+models:
+ - uses: myprofile/custom-model
+ with:
+ ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }}
+ TEMP: 0.9
+ override:
+ roles:
+ - chat
+```
+
+## Advanced
+
+### Inputs
+
+Models and MCP server authors can configure inputs that require the user to provide a secret value by defining a `${{ inputs.SECRET_NAME }}` value.
+
+For example, here is how you could require that the user provide a value for the `apiKey` property on a model:
+
+```yaml title="config.yaml" highlight={8}
+name: myprofile/custom-model
+version: 1.0.0
+schema: v1
+
+models:
+ - name: My Favorite Model
+ # ... other model properties ...
+ apiKey: ${{ inputs.SECRET_NAME }}
+```
+
+Users then map their secret to this input using a `${{ secrets.SECRET_NAME }}` value that maps to a property name which matches the required input, e.g. `SECRET_NAME`.
+
+```yaml title="config.yaml" highlight={8}
+name: myprofile/custom-agent
+version: 1.0.0
+schema: v1
+
+models:
+ - uses: myprofile/custom-model
+ with:
+ SECRET_NAME: ${{ secrets.SECRET_NAME }}
+```
+
+## Next Steps
+
+Now that you understand how models, rules, and tools work, explore:
+
+- **[Config Reference](/reference)**: Detailed documentation of all available properties
+- **[Continue Hub](https://hub.continue.dev)**: Browse community models, rules, and tools
+- **[Custom Context Providers](/customize/deep-dives/custom-providers)**: Create advanced context integrations
+- **[Model Roles](/customize/model-roles/intro)**: Understanding how different models work together
diff --git a/docs/guides/continue-docs-mcp-cookbook.mdx b/docs/guides/continue-docs-mcp-cookbook.mdx
new file mode 100644
index 000000000..76c4637dd
--- /dev/null
+++ b/docs/guides/continue-docs-mcp-cookbook.mdx
@@ -0,0 +1,542 @@
+---
+title: "Contributing to Continue with Model Context Protocol (MCP)"
+description: "Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows."
+sidebarTitle: "Continue Docs MCP Cookbook"
+---
+
+
+ Master using the Continue Docs MCP to contribute documentation, create cookbooks, and maintain consistency across Continue's docs - all through natural language prompts.
+
+
+## Prerequisites
+
+Before starting, ensure you have:
+
+- Continue account with **Hub access**
+- Read: [Contributing to Continue Documentation](/CONTRIBUTING) for setup instructions
+- Forked the [continuedev/continue](https://github.com/continuedev/continue) repository
+- Node.js 20+ and Continue CLI installed
+
+
+ This cookbook assumes you've read the setup in the [CONTRIBUTING guide](/CONTRIBUTING). If you haven't, start there first.
+
+
+## Continue Docs MCP Setup
+
+
+ Use the pre-built [Docs Assistant - Mintlify agent](https://hub.continue.dev/continuedev/docs-mintlify) that includes the Continue Docs MCP and is ready to use immediately.
+
+
+
+
+ ```bash
+ # From your Continue docs directory
+ cn --config continuedev/docs-mintlify
+ ```
+
+ This agent includes:
+ - **Continue Docs MCP** for searching Continue documentation
+ - **Mintlify formatting rules** for proper component usage
+ - **Documentation-focused prompts** for common tasks
+
+
+
+ If you want to customize, create your own agent and add:
+ 1. [Continue Docs MCP](https://hub.continue.dev/continuedev/continue-docs-mcp)
+ 2. [Mintlify Technical Writing Rule](https://hub.continue.dev/mintlify/technical-writing-rule)
+
+ See the [CONTRIBUTING guide](/CONTRIBUTING#option-2-create-your-own-custom-agent) for details.
+
+
+
+---
+
+## What is the Continue Docs MCP?
+
+
+ A Model Context Protocol server built with [Mintlify's MCP generation](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs) that enables semantic search across Continue documentation. [Learn more β](/reference/continue-mcp)
+
+
+The MCP helps you:
+- **Find examples** from existing documentation
+- **Maintain consistency** with established patterns
+- **Source accurate information** about Continue features
+- **Write better documentation** faster
+
+---
+
+## Documentation Workflows with Prompts
+
+### π Creating a New Cookbook
+
+Cookbooks show how to use Continue CLI with specific tools or services. Here's how to create one using the Continue Docs MCP:
+
+
+
+ ```bash
+ cn --config continuedev/docs-mintlify
+ ```
+
+ **Prompt:**
+ ```
+ "Show me the structure of existing MCP cookbooks in the Continue docs.
+ I want to create a cookbook for GitHub MCP."
+ ```
+
+ The agent will find examples like the dlt, Snyk, and Sanity cookbooks.
+
+
+
+ **Prompt:**
+ ```
+ "Using the Continue Docs MCP, find information about how GitHub MCP works.
+ Then search the web for the official GitHub MCP documentation and combine
+ both sources to create a cookbook following the same structure as the
+ dlt cookbook."
+ ```
+
+ The agent will:
+ - Search Continue docs for MCP patterns
+ - Fetch GitHub MCP official documentation
+ - Combine both sources
+ - Generate a cookbook with consistent formatting
+
+
+
+ **Prompt:**
+ ```
+ "Add my new github-mcp-continue-cookbook.mdx to the docs.json navigation
+ under the Cookbooks section."
+ ```
+
+
+
+ ```bash
+ npm run dev
+ # Visit http://localhost:3000
+ ```
+
+ **Refine with prompts:**
+ ```
+ "Add more examples to the troubleshooting section"
+ "Include a CI/CD workflow example using GitHub Actions"
+ "Add authentication setup using environment variables"
+ ```
+
+
+
+
+ **Pro Tip:** The agent uses the Continue Docs MCP to maintain consistency with existing cookbooks automatically.
+
+
+---
+
+### βοΈ Updating Existing Documentation
+
+
+
+ **Prompt:**
+ ```
+ "Where is the MCP tools documentation located? Show me the file path."
+ ```
+
+
+
+ **Prompt:**
+ ```
+ "Update the MCP tools documentation at docs/customization/mcp-tools.mdx
+ to include information about the new Slack MCP server. Use the Continue
+ Docs MCP to find examples of how other MCP servers are documented, then
+ add a similar section for Slack."
+ ```
+
+
+
+---
+
+### π Adding New Guides
+
+
+
+ **Prompt:**
+ ```
+ "I want to create a guide for setting up Continue with Amazon Bedrock.
+ Search the Continue docs for similar model provider setup guides and
+ show me the common structure they follow."
+ ```
+
+
+
+ **Prompt:**
+ ```
+ "Create a new guide at docs/guides/amazon-bedrock-setup.mdx following
+ the structure you found. Include:
+ - Prerequisites
+ - Step-by-step setup with code examples
+ - Configuration options
+ - Troubleshooting common issues
+
+ Use the Continue Docs MCP to find accurate information about Continue's
+ model provider configuration."
+ ```
+
+
+
+ **Prompt:**
+ ```
+ "Add this guide to docs.json under the Model Providers section"
+ ```
+
+
+
+---
+
+## Real-World Cookbook Examples
+
+### Example 1: PostgreSQL MCP Cookbook
+
+**Prompt:**
+```
+"Create a cookbook for using Continue with PostgreSQL MCP. Follow the same
+structure as the dlt cookbook, but customize it for database operations.
+
+Include these sections:
+1. Quick start with pre-built agent
+2. Manual setup with MCP configuration
+3. Common database tasks (schema exploration, query writing, migrations)
+4. Troubleshooting database connection issues
+
+Use the Continue Docs MCP to find MCP configuration patterns and search the
+web for PostgreSQL MCP documentation."
+```
+
+### Example 2: Sentry Error Tracking Cookbook
+
+**Prompt:**
+```
+"Create a cookbook showing how to use Continue to analyze Sentry errors.
+
+The cookbook should demonstrate:
+1. Setting up Sentry MCP integration
+2. Querying recent errors
+3. Analyzing error patterns with AI
+4. Generating fixes for common errors
+5. CI/CD integration for automated error analysis
+
+Research the Snyk cookbook structure since it's also about error detection,
+and adapt it for Sentry."
+```
+
+### Example 3: OpenAPI Documentation Cookbook
+
+**Prompt:**
+```
+"I want to create a cookbook for using Continue to work with OpenAPI specs.
+
+Show how to:
+1. Load OpenAPI specs into Continue's context
+2. Generate API client code from specs
+3. Create tests based on API endpoints
+4. Update documentation when APIs change
+
+Use the Continue Docs MCP to find how context providers work, then combine
+that with OpenAPI MCP information."
+```
+
+---
+
+## Advanced Prompt Patterns
+
+
+
+ ```bash
+ "Use the Continue Docs MCP to understand how agents
+ work in Continue, then search the web for Anthropic's
+ Computer Use MCP. Create a cookbook showing how to
+ combine Continue agents with Computer Use for
+ automated testing."
+ ```
+
+
+
+ ```bash
+ "Find all mentions of MCP servers across Continue
+ documentation. Then create a comprehensive reference
+ page that links to all MCP-related guides and
+ configurations."
+ ```
+
+
+
+ ```bash
+ "Review all cookbook files in docs/guides/ and check
+ if they follow the same structure. List any
+ inconsistencies and suggest updates to make them
+ uniform."
+ ```
+
+
+
+ ```bash
+ "Extract all code examples showing MCP server
+ configuration from the Continue docs. Format them
+ as a single reference page with explanations for
+ each pattern."
+ ```
+
+
+
+---
+
+## Testing Your Documentation
+
+### Local Preview
+
+```bash
+cd docs
+npm run dev
+# Visit http://localhost:3000
+```
+
+### Validation Prompts
+
+```bash
+# Check formatting
+"Review this documentation for Mintlify formatting issues and fix any problems"
+
+# Verify links
+"Check all links in this file and ensure they point to existing documentation"
+
+# Test code examples
+"Verify that all code examples in this cookbook are syntactically correct"
+```
+
+---
+
+## Submitting Your Contribution
+
+**Prompt:**
+```bash
+"Create a pull request with my documentation changes and use the repo's
+PR template to write the description"
+```
+
+The agent will:
+- Create a feature branch
+- Stage and commit your changes
+- Push to your fork
+- Generate a PR description following the template
+- Open the PR for review
+
+
+ See the full [Contributing Guide](/CONTRIBUTING#submitting-your-contribution) for manual PR submission details.
+
+
+---
+
+## Automated Documentation Checks with GitHub Actions
+
+Add automated documentation checks to your PR workflow using the Continue Docs MCP agent:
+
+```yaml title=".github/workflows/docs-check.yml"
+name: Documentation Check
+
+on:
+ pull_request:
+ types: [opened, synchronize]
+ paths:
+ - 'core/**'
+ - 'extensions/**'
+ - 'packages/**'
+ - 'gui/**'
+
+jobs:
+ check-docs:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+
+ - name: Install Continue CLI
+ run: npm i -g @continuedev/cli
+
+ - name: Analyze Changes for Documentation Needs
+ id: analyze
+ env:
+ CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
+ run: |
+ echo "π Analyzing code changes for documentation needs..."
+
+ # Get changed files
+ git diff origin/${{ github.base_ref }}..HEAD --name-only > changed_files.txt
+
+ # Create detailed diff
+ git diff origin/${{ github.base_ref }}..HEAD > changes.diff
+
+ # Use Continue agent to check if docs need updates
+ PROMPT="Review these code changes and determine if documentation updates are needed.
+
+ Changed files: $(cat changed_files.txt | tr '\n' ' ')
+
+ Consider:
+ - New features or APIs
+ - Breaking changes
+ - New configuration options
+ - Modified CLI commands
+ - New MCP integrations
+
+ If docs updates are needed, specify which files in docs/ should be updated.
+ If no updates needed, respond with 'NO_DOCS_NEEDED'.
+ Be specific and concise."
+
+ cn --config continuedev/docs-mintlify -p "$PROMPT" --auto > analysis.md || {
+ echo "β οΈ Analysis failed"
+ echo "needs_docs=false" >> $GITHUB_OUTPUT
+ exit 0
+ }
+
+ if grep -q "NO_DOCS_NEEDED" analysis.md; then
+ echo "needs_docs=false" >> $GITHUB_OUTPUT
+ else
+ echo "needs_docs=true" >> $GITHUB_OUTPUT
+ fi
+
+ - name: Post Documentation Recommendation
+ if: steps.analyze.outputs.needs_docs == 'true'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ echo "π Creating PR comment with documentation recommendations..."
+
+ cat > pr-comment.md <<'EOF'
+## π Documentation Update Recommended
+
+Based on the code changes in this PR, documentation updates may be needed:
+
+EOF
+
+ cat analysis.md >> pr-comment.md
+
+ cat >> pr-comment.md <<'EOF'
+
+---
+
+### Next Steps
+
+1. Review the suggested documentation areas above
+2. Update relevant files in the `/docs` folder
+3. Consider updating:
+ - API references for interface changes
+ - Guides for workflow changes
+ - Configuration docs for new settings
+ - MCP cookbooks for new integrations
+
+### Resources
+- [Contributing to Docs](/CONTRIBUTING)
+- [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook)
+
+*This analysis was generated using the Continue Docs MCP agent.*
+EOF
+
+ gh pr comment ${{ github.event.pull_request.number }} --body-file pr-comment.md
+
+ - name: Add Label
+ if: steps.analyze.outputs.needs_docs == 'true'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ gh pr edit ${{ github.event.pull_request.number }} --add-label "docs-needed"
+```
+
+
+ This workflow uses the Continue Docs MCP agent to analyze code changes and automatically comment on PRs when documentation updates are recommended.
+
+
+---
+
+## Documentation MCP for Other Projects
+
+Want to create documentation MCPs for your own projects? Mintlify makes it easy:
+
+
+
+ ```bash
+ npm i -g mintlify
+ mintlify init
+ ```
+
+
+
+ Mintlify automatically generates an MCP server for your documentation, enabling semantic search.
+
+ [Learn more about Mintlify MCP generation β](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs)
+
+
+
+ Share your docs MCP on [Continue Hub](https://hub.continue.dev/new?type=mcp) so others can use it with Continue agents.
+
+
+
+
+ The [Continue Docs MCP](/reference/continue-mcp) itself was built this way!
+
+
+---
+
+## Key Prompts Cheat Sheet
+
+| Task | Prompt |
+|:-----|:-------|
+| **Find structure** | "Show me the structure of existing cookbooks in Continue docs" |
+| **Create cookbook** | "Create a cookbook for [tool] MCP following the dlt cookbook structure" |
+| **Update docs** | "Update [file] to include information about [feature], using Continue Docs MCP to find examples" |
+| **Add navigation** | "Add [file] to docs.json under the [section] section" |
+| **Check consistency** | "Review this file for consistency with other Continue documentation" |
+| **Fix formatting** | "Review for Mintlify formatting issues and fix any problems" |
+| **Extract examples** | "Find all examples of [topic] in Continue docs" |
+| **Research feature** | "Use Continue Docs MCP to explain how [feature] works in Continue" |
+
+---
+
+## Resources
+
+### Continue Documentation
+- [Contributing Guide](/CONTRIBUTING) - Setup and submission process
+- [Continue Docs MCP Reference](/reference/continue-mcp) - MCP server details
+- [Understanding Agents](/guides/understanding-agents) - How agents work
+
+### Mintlify
+- [MCP Generation Guide](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs)
+- [Mintlify Documentation](https://mintlify.com/docs)
+
+### Community
+- [Continue Discord](https://discord.gg/continue) - #documentation channel
+- [GitHub Discussions](https://github.com/continuedev/continue/discussions)
+
+---
+
+## Next Steps
+
+
+
+ Set up your environment
+
+
+
+ Install pre-built agent
+
+
+
+ See cookbook examples
+
+
+
+ Get help from community
+
+
diff --git a/docs/guides/continuous-ai-readiness-assessment.mdx b/docs/guides/continuous-ai-readiness-assessment.mdx
new file mode 100644
index 000000000..f72e5dd85
--- /dev/null
+++ b/docs/guides/continuous-ai-readiness-assessment.mdx
@@ -0,0 +1,309 @@
+---
+title: Assessing Your Team's Readiness for Continuous AI
+description: Complete framework to evaluate team readiness for Continuous AI adoption with maturity levels, assessment criteria, and implementation roadmap.
+sidebarTitle: Continuous AI Readiness Assessment
+---
+
+
+ **TL;DR:** Use this assessment framework to determine if your team is ready to
+ move from individual AI tool usage to automated Continuous AI workflows.
+ Covers technical infrastructure, processes, culture, and organizational
+ support.
+
+
+## Assessing Continuous AI Readiness
+
+Continuous AI can dramatically improve development velocity and code quality, but successful implementation requires careful evaluation across four key dimensions.
+
+
+ Rushing into Continuous AI without proper foundations leads to frustration and
+ failed initiatives. Use this framework to identify gaps before scaling.
+
+
+### 1. Identify Your Current Maturity Level
+
+Determine where your team falls on the Continuous AI maturity spectrum:
+
+
+
+ Developers use AI tools inconsistently with highly variable results.
+
+ **Characteristics:**
+ - High rejection rates of AI-generated code (>50%)
+ - No shared standards or prompting rules
+ - AI tools lack context about your codebase
+ - Ad-hoc usage without team coordination
+
+
+
+
+ AI is systematically integrated into team workflows and CI/CD pipelines.
+
+**Characteristics:**
+
+- Consistent adoption across 80%+ of team members
+- AI integrated into code reviews and deployment processes
+- Documented standards for prompts and tool usage
+- Basic metrics tracking AI impact
+
+
+
+
+ Certain development processes run autonomously with minimal human oversight.
+
+ **Characteristics:**
+ - Human intervention rates below 15%
+ - Robust monitoring and automated rollback systems
+ - Measurable ROI from automation initiatives
+ - Advanced context awareness and learning loops
+
+
+
+
+### 2. Evaluate Readiness Across Four Key Dimensions
+
+Assess your team's strengths and potential risks across these critical areas:
+
+
+
+ **Key Questions:**
+ - Do our development tools integrate reliably?
+ - Can we measure AI effectiveness and impact?
+ - Are security policies compatible with AI workflows?
+
+ **π’ Green Flags:**
+ - Stable tool integrations with >99.5% uptime
+ - Comprehensive monitoring and observability
+ - Security policies that support AI tool usage
+ - Automated testing and deployment pipelines
+
+ **π΄ Red Flags:**
+ - Frequent integration breakdowns
+ - No performance tracking or metrics
+ - Restrictive security policies blocking AI tools
+ - Manual deployment processes
+
+
+
+
+ **Key Questions:**
+ - Are our development workflows consistent and documented?
+ - Do we have quality gates and review processes?
+ - Can we reproduce builds and deployments reliably?
+
+ **π’ Green Flags:**
+ - Clear coding standards and style guides
+ - Automated CI/CD with quality gates
+ - Documented, repeatable processes
+ - Consistent code review practices
+
+ **π΄ Red Flags:**
+ - Inconsistent code reviews
+ - Ad-hoc deployment processes
+ - "Works on my machine" culture
+ - Undocumented tribal knowledge
+
+
+
+
+ **Key Questions:**
+ - Are developers open to adopting new AI-powered workflows?
+ - How does the team handle experimentation and failure?
+ - Do team members collaborate effectively on new initiatives?
+
+ **π’ Green Flags:**
+ - High curiosity and willingness to experiment
+ - Collaborative problem-solving culture
+ - Constructive feedback and learning mindset
+ - Active knowledge sharing practices
+
+**π΄ Red Flags:**
+
+- Strong resistance to workflow changes
+- Blame culture around mistakes
+- Perfectionism blocking experimentation
+- Siloed work with minimal collaboration
+
+
+
+
+ **Key Questions:**
+ - Does leadership provide budget and resources for AI initiatives?
+ - Is there tolerance for experimentation and learning?
+ - Are expectations realistic for ROI timelines?
+
+ **π’ Green Flags:**
+ - Executive buy-in and strategic alignment
+ - Dedicated budget for training and tools
+ - 3-6 month ROI expectations
+ - Support for calculated risk-taking
+
+ **π΄ Red Flags:**
+ - Pressure for immediate ROI (weeks)
+ - No allocated budget for AI initiatives
+ - High risk aversion culture
+ - Lack of leadership engagement
+
+
+
+
+### 3. Critical Warning Signs
+
+
+ **Stop and address these issues before scaling Continuous AI:**
+
+
+
+
+ - Builds breaking regularly (>5% failure rate)
+ - Unstable deployments or rollback frequency >10%
+ - No monitoring or observability systems
+ - Critical security policy conflicts
+
+
+
+
+ - More than 30% of team opposed to AI tools
+ - No established feedback or learning culture
+ - History of failed automation initiatives
+ - Resistance to changing existing workflows
+
+
+
+
+ - Inconsistent development workflows
+ - No quality gates or review processes
+ - Manual deployment and testing processes
+ - Lack of documentation and standards
+
+
+
+
+ - Leadership expecting ROI in weeks vs months
+ - No allocated budget for AI initiatives
+ - High pressure, low experimentation tolerance
+ - Lack of strategic alignment on AI adoption
+
+
+
+
+### 4. Implementation Roadmap
+
+Based on your assessment results, follow this step-by-step approach:
+
+
+
+ Document current performance across key areas:
+
+ - Development velocity (story
+ points, cycle time)
+ - Code quality metrics (bug rates, technical debt)
+ - Review times and approval rates
+ - Developer satisfaction and productivity
+ scores
+
+
+
+
+ Choose one high-impact, low-risk workflow to automate first:
+
+ - **Code Review:** Automated analysis and suggestions
+ - **Documentation:** Auto-generated API docs and README updates
+ - **Testing:** Automated test generation and maintenance
+ - **Refactoring:** Systematic code improvement suggestions
+
+
+
+
+ Create and document consistent practices:
+ - AI tool selection and configuration guidelines
+
+ - Prompting standards and best practices
+
+ - Quality gates and review processes
+
+ - Security and compliance requirements
+
+
+
+
+ Run controlled experiments with success criteria:
+ - Start with 2-3 team members for 2-4 weeks
+ - Track metrics against baseline performance
+ - Gather qualitative feedback on developer experience
+ - Document lessons learned and optimization opportunities
+
+
+
+
+ Expand successful pilots across the organization:
+ - Roll out to additional team members gradually
+ - Implement monitoring and alerting systems
+ - Establish feedback loops for continuous improvement
+ - Plan next automation targets based on results
+
+
+
+
+
+
+ Comprehensive explanation of maturity levels and organizational readiness
+ factors
+
+
+
+ Technical implementation details and best practices for Continuous AI
+ workflows
+
+
+
+## Quick Assessment Checklist
+
+
+ **Ready to get started?** Use this quick checklist to gauge your immediate
+ readiness:
+
+
+**Technical Foundation (Score: \_\_\_/4)**
+
+- Stable CI/CD pipelines with \<5% failure rate
+- Monitoring and observability systems in place
+- Security policies support AI tool integration
+- Development environment standardization
+
+**Process Maturity (Score: \_\_\_/4)**
+
+- Documented coding standards and review processes
+- Consistent deployment and rollback procedures
+- Quality gates and automated testing
+- Regular retrospectives and process improvement
+
+**Team Culture (Score: \_\_\_/4)**
+
+- \<30% resistance to AI tool adoption
+- Active experimentation and learning culture
+- Collaborative problem-solving approach
+- Constructive feedback and knowledge sharing
+
+**Organizational Support (Score: \_\_\_/4)**
+
+- Leadership buy-in and strategic alignment
+- Dedicated budget for AI initiatives and training
+- 3-6 month ROI expectations (not weeks)
+- Support for calculated risk-taking
+
+---
+
+**Overall Readiness Score: \_\_\_/16**
+
+- **12-16:** Ready to begin Continuous AI implementation
+- **8-11:** Address gaps in 1-2 areas before scaling
+- **\<8:** Focus on foundational improvements first
diff --git a/docs/guides/continuous-ai.mdx b/docs/guides/continuous-ai.mdx
new file mode 100644
index 000000000..bd88c2228
--- /dev/null
+++ b/docs/guides/continuous-ai.mdx
@@ -0,0 +1,207 @@
+---
+title: "Continuous AI: A Developer's Guide"
+description: "Learn how to integrate intelligent automation into development workflows, making AI assistance as natural as syntax highlighting. Implement systematic AI workflows that compound productivity gains over time."
+---
+
+Continuous AI is the integration of intelligent automation directly into development workflows, making AI assistance as natural and reliable as syntax highlighting or code completion. Its purpose is to amplify developer intent at every stage of the coding process.
+
+Think of it this way: DevOps automated the mechanical aspects of software deliveryβbuilding, testing, deploying. Continuous AI automates the intelligence aspectsβunderstanding context, making suggestions, adapting to patterns, and learning from developer feedback.
+
+## Why Continuous AI Matters Now
+
+The same market forces that made DevOps inevitable are now driving Continuous AI adoption:
+
+
+
+ Engineering teams are rapidly adopting AI tools, with many seeing
+ significant productivity improvements in their workflows.
+
+
+
+ AI-assisted coding is contributing measurable increases in developer output,
+ creating competitive advantages for early adopters.
+
+
+
+ Unlike DevOps, Continuous AI can be implemented incrementally on existing
+ development stacks without major infrastructure changes.
+
+
+
+The teams that implement systematic AI workflows first create advantages that compound over time.
+
+## The Continuous AI Maturity Model
+
+Teams typically progress through three stages when adopting Continuous AI:
+
+
+You prompt the AI when you remember, and it completes the task. This is great for quick productivity boosts but remains highly manual and inconsistent.
+
+**Example**: Using AI to draft a function or suggest a test case only when you think to ask for it.
+
+**Continue Implementation**: Using [Chat](/features/chat/quick-start) or [Edit](/features/edit/quick-start) mode for one-off coding tasks.
+
+
+
+
+AI handles routine tasks with human oversight. This is where teams start seeing compounding gains.
+
+**Examples**:
+
+- AI adds missing documentation during PR review
+- Automatic code formatting and style corrections
+- Generated unit tests for new functions
+- Updated issue tracking when branches are merged
+
+**Continue Implementation**: Using [Continue CLI](/guides/cli) with custom rules and integrations into CI/CD pipelines.
+
+
+
+
+AI autonomously completes processes end-to-end without human input, but only for very specific, low-risk workflows.
+
+**Examples**:
+
+- AI merges safe dependency updates after automated tests pass
+- Automatic documentation updates when code changes
+- Self-healing test suites that fix themselves based on failure patterns
+
+**Continue Implementation**: Fully automated [agents](/features/agent/quick-start) with strict permissions and safety guardrails.
+
+
+
+## Building Your Continuous AI Workflow
+
+### Start with Level 1 β Level 2: Pick One Workflow
+
+Don't try to automate everything at once. Choose a specific daily friction point:
+
+```bash
+# Example: Automated code review comments
+git diff | cn -p "review this diff and suggest improvements following our team standards"
+
+# Example: Generate missing tests
+cn -p "create unit tests for the functions in src/auth.js"
+
+# Example: Update documentation
+cn -p "update the README with the new API endpoints from the recent changes"
+```
+
+### Configure Team-Wide Intelligence
+
+The most effective Continuous AI is tuned to your codebase, standards, and practices:
+
+```yaml config.yaml
+rules:
+ - name: code-review
+ description: "Review code following team standards"
+ rule: "Review following our TypeScript style guide and security practices"
+ context:
+ - "docs/style-guide.md"
+ - "security-checklist.md"
+```
+
+### Implement Progressive Permissions
+
+Use Continue CLI's permission system to gradually expand AI capabilities:
+
+```yaml ~/.continue/permissions.yaml
+permissions:
+ - allow: "Bash(git*)" # Git commands are safe
+ - ask: "Write(**/*.ts)" # Ask before modifying TypeScript files
+ - deny: "Bash(rm*)" # Never allow deletions
+```
+
+### Measure What Matters: Intervention Rate
+
+Track how often you need to correct AI output. Lower intervention rates mean higher trust and compounding productivity gains.
+
+## Real-World Implementation Patterns
+
+
+
+ Imagine setting up an AI agent that checks new GitHub issues every morning and leaves the first helpful response. This lightens the load for maintainers and ensures community members feel heard quickly.
+
+
+
+ AI can automatically review new pull requests for security, performance, and style issues. The reviewer still has the final say, but the agent highlights common problems and speeds up the feedback loop.
+
+
+
+ Whenever code changes, AI can scan for mismatches in documentation and suggest updates. This keeps docs current without relying on developers to remember every detail.
+
+
+## Best Practices for Sustainable Continuous AI
+
+
+
+ AI should amplify human intelligence, not replace it. Always validate AI
+ suggestions rather than blindly accepting them.
+
+
+
+ Begin with low-risk, high-value automations. Gradually expand as you build
+ trust and understanding.
+
+
+
+ Generic AI suggestions are often wrong or irrelevant. Configure AI to
+ understand your specific patterns and requirements.
+
+
+
+ Use permission systems, code review processes, and testing to ensure AI
+ actions are safe and reversible.
+
+
+
+## Common Pitfalls to Avoid
+
+
+ **Over-automation**: Don't automate processes you don't fully understand
+
+
+
+ **Ignoring Context**: AI works best when it understands your codebase and team
+ practices
+
+
+
+ **Skipping Safety**: Always implement proper permissions and review processes
+
+
+
+ **Vanity Metrics**: Focus on intervention rate and actual time saved, not "AI
+ suggestions generated"
+
+
+## Getting Started Today
+
+
+
+ ```bash npm i -g @continuedev/cli ```
+
+
+Choose a daily friction point to automate
+
+Configure safe boundaries for AI actions
+
+Track intervention rates and time saved
+
+ Gradually add more automated workflows
+
+
+## The Competitive Advantage
+
+Teams implementing Continuous AI are coding faster and building institutional intelligence that scales with their organization. While others manually perform routine tasks, your AI handles the repetitive work so your team can focus on innovation and complex problem-solving.
+
+## What's Next?
+
+As AI capabilities continue to improve and tooling matures, we're moving toward a world where intelligent assistance is as fundamental to development as version control or IDEs. The teams that start building these capabilities now will have refined systems, cultural readiness, and institutional knowledge when Continuous AI becomes the industry standard.
+
+Ready to amplify your development workflow with Continuous AI? Start with one simple automation and build from there.
+
+
+ Check out our guides on [Continue CLI](/guides/cli) and [Understanding
+ Agents](/guides/understanding-agents).
+
diff --git a/docs/guides/dlt-mcp-continue-cookbook.mdx b/docs/guides/dlt-mcp-continue-cookbook.mdx
new file mode 100644
index 000000000..c3460ed24
--- /dev/null
+++ b/docs/guides/dlt-mcp-continue-cookbook.mdx
@@ -0,0 +1,484 @@
+---
+title: "Building Data Pipelines with dlt MCP and Continue"
+description: "Set up an AI-powered data engineering workflow that helps you develop, debug, and inspect dlt data pipelines using natural language commands."
+sidebarTitle: "dlt Data Pipelines with Continue"
+---
+
+
+ An AI-powered data pipeline development system that uses Continue's AI agent with dlt
+ MCP to inspect pipeline execution, retrieve schemas, analyze datasets, and debug load errors - all through simple natural language prompts
+
+
+## Prerequisites
+
+Before starting, ensure you have:
+
+- Continue account with **Hub access**
+- Read: [Understanding Agents β How to get started with Hub agents](/guides/understanding-agents#how-to-get-started-with-hub-agents)
+- Python 3.8+ installed locally
+- A dlt pipeline project (or create one during this guide)
+- Basic understanding of data pipelines
+
+For all options, first:
+
+
+ ```bash
+ npm i -g @continuedev/cli
+ ```
+
+
+
+ ```bash
+ pip install dlt
+ ```
+
+
+
+ To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys).
+
+
+## dlt MCP Workflow Options
+
+
+ Skip the manual setup and use our pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) that includes
+ the dlt MCP and optimized data pipeline workflows for more consistent results. You can [remix this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to customize it for your specific needs.
+
+
+
+After ensuring you meet the **Prerequisites** above, you have two paths to get started:
+
+
+
+
+
+ Navigate to your pipeline project directory and run:
+ ```bash
+ cn --config dlthub/dlt-assistant
+ ```
+
+ This agent includes:
+ - **dlt MCP** pre-configured and ready to use
+ - **Pipeline-focused rules** for data engineering best practices
+
+
+
+ Start with a comprehensive pipeline check:
+ ```bash
+ # TUI mode
+ Inspect the execution of my dlt pipeline and summarize the load info, including timing and file sizes.
+ ```
+
+ That's it! The agent handles everything automatically.
+
+
+
+
+ **Why Use the Agent?** The pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) provides consistent pipeline development workflows and handles MCP configuration automatically, making it easier to get started with AI-powered data engineering. You can [remix and customize this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) later to fit your team's specific workflow.
+
+
+
+
+
+
+
+ Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent).
+
+
+
+ Visit the [dlt MCP on Continue Hub](https://hub.continue.dev/dlthub/dlt-mcp) and click **Install** to add it to the agent you created in the step above.
+
+ This will add dlt MCP to your agent's available tools. The Hub listing automatically configures the MCP command.
+
+
+ **Alternative installation methods:**
+ 1. **Quick CLI install**: `cn --mcp dlthub/dlt-mcp`
+ 2. **Manual configuration**: Add the MCP to your `~/.continue/config.json` under the `mcpServers` section
+
+ Once installed, dlt MCP tools become available to your Continue agent for all prompts.
+
+
+
+ The MCP will work with your existing dlt pipelines in your current directory.
+
+
+
+
+
+ Start with a comprehensive pipeline check:
+ ```bash
+ # TUI mode
+ cn
+ # Then type: Inspect the execution of my dlt pipeline and summarize the load info, including timing and file sizes.
+ ```
+
+
+
+
+
+
+
+ To use the pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant), you need either:
+ - **Continue CLI Pro Plan** with the models add-on, OR
+ - **Your own API keys** added to Continue Hub secrets (same as manual setup)
+
+ The agent will automatically detect and use your configuration along with the pre-configured dlt MCP for pipeline operations.
+
+
+
+---
+
+## dlt MCP vs dlt+ MCP
+
+
+ **dlt MCP** is focused on local pipeline development and inspection. It provides tools to:
+ - Inspect pipeline execution and load information
+ - Retrieve schema metadata from your local pipelines
+ - Query dataset records from destination databases
+ - Analyze load errors, timings, and file sizes
+
+ **[dlt+ MCP](https://hub.continue.dev/dlthub/dlt-plus-mcp)** extends these capabilities with cloud-based features for production deployments:
+ - Connect to dlt+ Projects and manage deployments
+ - Monitor pipeline runs across multiple environments
+ - Access centralized logging and observability
+ - Collaborate with team members on pipeline development
+
+ For local development and getting started, **[dlt MCP](https://hub.continue.dev/dlthub/dlt-mcp)** is the right choice. Consider **[dlt+ MCP](https://hub.continue.dev/dlthub/dlt-plus-mcp)** when you need production deployment features and team collaboration.
+
+
+---
+
+## Pipeline Development Recipes
+
+Now you can use natural language prompts to develop and debug your dlt pipelines. The Continue agent automatically calls the appropriate dlt MCP tools.
+
+
+You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section.
+
+
+
+ **Where to run these workflows:**
+ - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs
+ - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts
+ - **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands
+
+ **Test in Plan Mode First**: Before running pipeline operations that might make
+ changes, test your prompts in plan mode (see the [Plan Mode
+ Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes in TUI/IDE). This
+ shows you what the agent will do without executing it.
+
+
+
+
+ **About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like pipeline inspection, schema retrieval, and error analysis.
+
+
+
+### Pipeline Inspection
+
+
+ Review pipeline execution details including load timing and file sizes.
+
+**TUI Mode Prompt:**
+```
+Inspect my dlt pipeline execution and provide a summary of the load info.
+Show me the timing breakdown and file sizes for each table.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Inspect my dlt pipeline execution and provide a summary of the load info. Show me the timing breakdown and file sizes for each table." --auto
+```
+
+
+
+### Schema Management
+
+
+ Get detailed schema information for your pipeline's tables.
+
+**TUI Mode Prompt:**
+```
+Show me the schema for my users table including all columns,
+data types, and any constraints.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Show me the schema for my users table including all columns, data types, and any constraints." --auto
+```
+
+
+
+### Data Exploration
+
+
+ Retrieve and analyze records from your destination database.
+
+**TUI Mode Prompt:**
+```
+Get the last 10 records from my orders table and show me
+the distribution of order statuses.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Get the last 10 records from my orders table and show me the distribution of order statuses." --auto
+```
+
+
+
+### Error Debugging
+
+
+ Investigate and understand pipeline load errors.
+
+**TUI Mode Prompt:**
+```
+Check for any load errors in my last pipeline run. If there are errors,
+explain what went wrong and suggest fixes.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Check for any load errors in my last pipeline run. If there are errors, explain what went wrong and suggest fixes." --auto
+```
+
+
+
+### Pipeline Creation
+
+
+ Create a new dlt pipeline from an API or data source.
+
+**TUI Mode Prompt:**
+```
+Help me create a new dlt pipeline that loads data from the
+JSONPlaceholder API users endpoint into DuckDB.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Help me create a new dlt pipeline that loads data from the JSONPlaceholder API users endpoint into DuckDB." --auto
+```
+
+
+
+### Schema Evolution
+
+
+ Review and manage schema evolution in your pipelines.
+
+**TUI Mode Prompt:**
+```
+Check if my pipeline schema has evolved since the last run.
+Show me what columns were added or modified.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Check if my pipeline schema has evolved since the last run. Show me what columns were added or modified." --auto
+```
+
+
+
+## Continuous Data Pipelines with GitHub Actions
+
+This example demonstrates a **Continuous AI workflow** where data pipeline validation runs automatically in your CI/CD pipeline in headless mode using the [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant). Consider [remixing this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to add your organization's specific validation rules.
+
+### Add GitHub Secrets
+
+Navigate to **Repository Settings β Secrets and variables β Actions** and add:
+
+- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
+- Any required database credentials for your destination
+
+
+ The workflow uses the pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) with `--config dlthub/dlt-assistant`. This agent comes pre-configured with the dlt MCP and optimized rules for pipeline operations. You can [remix this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to customize the validation rules and prompts for your specific pipeline requirements.
+
+
+### Create Workflow File
+
+This workflow automatically validates your dlt data pipelines on pull requests using the Continue CLI in [headless mode](/cli/overview#headless-mode%3A-production-automation). It inspects pipeline schemas, checks for errors, and posts a summary report as a PR comment. The workflow can also be triggered manually via `workflow_dispatch`.
+
+Create `.github/workflows/dlt-pipeline-validation.yml` in your repository:
+
+```yaml
+name: Data Pipeline Validation with dlt MCP
+
+on:
+ pull_request:
+ branches: [main]
+ workflow_dispatch:
+
+jobs:
+ validate-pipeline:
+ runs-on: ubuntu-latest
+ env:
+ CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: "18"
+
+ - name: Install dlt
+ run: |
+ pip install dlt
+ echo "β
dlt installed"
+
+ - name: Install Continue CLI
+ run: |
+ npm install -g @continuedev/cli
+ echo "β
Continue CLI installed"
+
+ - name: Validate Pipeline Schema
+ run: |
+ echo "π Validating pipeline schema..."
+ cn --config dlthub/dlt-assistant \
+ -p "Inspect the pipeline schema and verify all required tables
+ and columns are present. Flag any missing or unexpected changes." \
+ --auto
+
+ - name: Check Pipeline Health
+ run: |
+ echo "π Checking pipeline health..."
+ cn --config dlthub/dlt-assistant \
+ -p "Analyze the last pipeline run for errors or warnings.
+ Report any issues that need attention." \
+ --auto
+
+ - name: Comment Pipeline Report on PR
+ if: always() && github.event_name == 'pull_request'
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ REPORT=$(cn --config dlthub/dlt-assistant \
+ -p "Generate a concise summary (200 words or less) of:
+ - Pipeline schemas and row counts
+ - Any load errors or warnings
+ - Performance metrics (timing, file sizes)
+ - Recommended improvements" \
+ --auto)
+
+ gh pr comment ${{ github.event.pull_request.number }} --body "$REPORT"
+```
+
+
+ The dlt MCP works with your local pipeline state. Make sure your CI environment
+ has access to the necessary pipeline configuration and credentials.
+
+
+## Pipeline Development Best Practices
+
+Implement automated pipeline quality checks using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips.
+
+
+ ```bash
+ "Before committing pipeline changes, verify the schema
+ matches expectations and flag any unexpected modifications."
+ ```
+
+
+
+ ```bash
+ "When load errors occur, analyze the error details and
+ suggest specific code fixes to handle the data issues."
+ ```
+
+
+
+ ```bash
+ "Track pipeline execution times and file sizes. Alert if
+ performance degrades significantly from baseline."
+ ```
+
+
+
+ ```bash
+ "After each pipeline run, validate row counts and check for
+ null values in critical columns."
+ ```
+
+
+## Troubleshooting
+
+### Pipeline Not Found
+
+```bash
+"Check if there's a dlt pipeline in the current directory.
+If not, help me initialize a new pipeline."
+```
+
+### Destination Connection Issues
+
+```bash
+"Verify the destination connection and credentials for my pipeline.
+Test the connection and report any issues."
+```
+
+### Schema Inference Problems
+
+
+ **Verification Steps:**
+ - dlt MCP is installed via [Continue Hub](https://hub.continue.dev/dlthub/dlt-mcp)
+ - Pipeline directory is accessible
+ - Destination database credentials are configured
+ - Pipeline has been run at least once
+
+
+## What You've Built
+
+After completing this guide, you have a complete **AI-powered data pipeline development system** that:
+
+β
Uses natural language β Simple prompts instead of complex pipeline commands
+β
Debugs automatically β AI analyzes errors and suggests fixes
+β
Runs continuously β Automated validation in CI/CD pipelines
+β
Ensures quality β Pipeline checks prevent bad data from shipping
+
+
+ Your data pipeline workflow now operates at **[Level 2 Continuous
+ AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
+ AI handles routine pipeline inspection and debugging with human oversight
+ through review and approval of changes.
+
+
+## Next Steps
+
+1. **Inspect your first pipeline** - Try the pipeline inspection prompt on your current project
+2. **Debug load errors** - Use the error analysis prompt to fix any issues
+3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo
+4. **Create new pipelines** - Use AI to scaffold new data sources
+5. **Monitor performance** - Track pipeline execution metrics over time
+
+## Additional Resources
+
+
+
+ Complete dlt platform documentation
+
+
+ Explore more MCP integrations and agents
+
+
+ Learn about AI assistants, MCP, and Continue integration
+
+
+ Deep dive into dlt MCP integration
+
+
\ No newline at end of file
diff --git a/docs/guides/doc-writing-agent-cli.mdx b/docs/guides/doc-writing-agent-cli.mdx
new file mode 100644
index 000000000..56c50cce9
--- /dev/null
+++ b/docs/guides/doc-writing-agent-cli.mdx
@@ -0,0 +1,350 @@
+---
+title: "Automating Documentation Updates with Continue CLI"
+sidebarTitle: "Automating Documentation Updates with Continue CLI"
+description: "Learn how to create automated documentation generation workflows using Continue CLI. Set up AI agents to analyze code changes and generate or update documentation automatically in GitHub workflows or local development."
+---
+# Automating Documentation Updates with Continue CLI
+
+This guide demonstrates how to create automated documentation generation based on code updates in a git branch using the Continue CLI, either as part of your local workflow or as part of a GitHub workflow.
+
+This process utilizes the **Continue CLI** (`cn`) in **headless mode** to analyze changes and generate the necessary documentation, and commit and push the changes. The goal is to keep the workflow as simple as possible by using straightforward shell commands, Continue CLI prompts, and basic git operations.
+
+## Why Use Continue CLI for Documentation?
+
+
+
+ AI agents understand your codebase and documentation patterns, analyzing git diffs to identify what needs documenting.
+
+
+
+ Integrate seamlessly into CI/CD pipelines or local development workflows with minimal setup.
+
+
+
+ Agents can read files, explore projects, and access Git history to generate accurate, relevant documentation.
+
+
+
+ Restrict agent actions to specific files and operations, ensuring safe automated documentation updates.
+
+
+
+## Prerequisites
+
+
+
+ Continue CLI requires Node.js 18 or higher. Install globally with:
+ ```bash
+ npm i -g @continuedev/cli
+ ```
+
+
+
+ Get your API key from [Continue Hub](https://hub.continue.dev/settings/api-keys) and set:
+ ```bash
+ export CONTINUE_API_KEY=your_key_here
+ ```
+
+ You can use the Continue CLI in headless mode without interactive login by setting the `CONTINUE_API_KEY` environment variable.
+
+
+
+
+ A project with code and documentation, or use an open-source project to experiment with the workflow.
+
+
+
+# Documentation Generation Workflow
+
+## Workflow Overview
+
+The documentation generation process follows these sequential steps:
+
+
+
+ Validate environment, install Continue CLI, and set up authentication with API keys.
+
+
+
+ Generate git diff context and analyze code changes between branches to identify new functionality.
+
+
+
+ Create a dedicated documentation branch following the pattern `{original-branch}-docs-update-{timestamp}`.
+
+
+
+ Use Continue CLI with custom rules to analyze changes and generate or update documentation files.
+
+ Use an agent configuration with rules specific for documentation writing in your project and fine-tune it to work for your team's standards.
+
+
+
+
+ Review generated documentation, commit changes to the docs directory, and push to origin.
+
+
+
+ Remove temporary files and output completion summary with branch information.
+
+
+
+
+
+## Implementation
+
+
+
+
+### GitHub Actions Implementation
+
+
+This example uses a manual workflow dispatch that requires two inputs: the repository name and the branch containing your code changes. This is helpful when you want to generate documentation for a feature branch before creating a pull request.
+
+
+**Required Inputs:**
+- **repository:** The repository you are operating on (format: `owner/repo`)
+- **branch_name:** The name of the branch you have code changes on and want to generate documentation for
+- **continue_config:** The Continue agent configuration to use
+ - Consider setting a default value if you have a default config your'd like to use
+- **continue_org:** The Continue org to use
+ - Consider setting a default value if you have a default org your'd like to use
+
+
+```yaml title=".github/workflows/generate-docs.yml"
+name: Generate Docs for Branch
+
+on:
+ workflow_dispatch:
+ inputs:
+ repository:
+ description: 'Repository (owner/repo)'
+ required: true
+ default: 'owner/repo'
+ branch_name:
+ description: 'Branch name to generate docs for'
+ required: true
+ continue_config:
+ description: 'Continue agent configuration to use'
+ required: true
+ # Set a default value if you have a default config your'd like to use
+ # default: 'agent-config-name'
+ continue_org:
+ description: 'Continue org to use'
+ required: true
+ # Set a default value if you have a default org your'd like to use
+ # default: 'your-org-name'
+
+jobs:
+ write-docs:
+ runs-on: ubuntu-latest
+ name: Write Documentation for Branch
+ env:
+ CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
+ CONTINUE_ORG: ${{ github.event.inputs.continue_org }}
+ CONTINUE_CONFIG: ${{ github.event.inputs.continue_config }}
+
+ steps:
+
+ - name: Checkout fork repository
+ uses: actions/checkout@v4
+ with:
+ repository: ${{ github.event.inputs.repository || 'owner/repo' }}
+ token: ${{ secrets.GH_PAT }}
+ fetch-depth: 0 # Full history needed for sync
+
+ - name: Setup git configuration
+ run: |
+ git config user.name "github-actions[doc-writer-bot]"
+ git config user.email "yourname@email.com"
+
+ - name: Checkout target branch
+ run: |
+ git fetch origin ${{ github.event.inputs.branch_name }}
+ git checkout ${{ github.event.inputs.branch_name }}
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '18'
+
+ - name: Install Continue CLI
+ run: |
+ echo "Installing Continue CLI..."
+ npm i -g @continuedev/cli
+
+ - name: Verify Continue CLI installation
+ run: |
+ echo "Checking Continue CLI version..."
+ cn --version || exit 1
+
+ - name: Set branch name
+ id: branch
+ run: |
+ BRANCH_NAME="${{ github.event.inputs.branch_name }}-docs-update-$(date +%Y-%m-%d-%H-%M-%S)"
+ echo "branch_name=$BRANCH_NAME" >> $GITHUB_OUTPUT
+ echo "Branch name: $BRANCH_NAME"
+
+ - name: Generate git diff context
+ run: |
+ echo "Git changes:" > context.txt
+ git diff origin/main..HEAD --stat >> context.txt
+ echo -e "\n\nFile list:" >> context.txt
+ git diff origin/main..HEAD >> context.txt
+ echo "Generated context file:"
+ cat context.txt
+
+ - name: Create documentation branch
+ run: |
+ echo "Creating branch: ${{ steps.branch.outputs.branch_name }}"
+ git checkout -b "${{ steps.branch.outputs.branch_name }}"
+
+ - name: Generate documentation with Continue CLI
+ run: |
+ echo "Running Continue agent to generate documentation..."
+ cn --config / \
+ --auto \
+ --allow Write \
+ -p \
+ --prompt ./context.txt \
+ "Analyze the provided git diff and identify any new functionality introduced. Summarise the new features in a few sentences. Then search the existing documentation in the site docs/ directory to determine whether these features are already documented in a way that enables users to use them. If documentation is missing or incomplete, create or modify Markdown files under the site diretory (without changing any code) to add clear explanations, usage instructions and examples for the new features in the same style and format as the existing documentation. Finally, print a brief summary of the documentation changes you made."
+
+ - name: Clean up temporary files
+ run: rm -f context.txt
+
+ - name: Commit and push documentation changes
+ run: |
+ echo "Review git status..."
+ git status
+
+ echo "Adding files edited in site directory to git..."
+ git add site/
+
+ echo "Committing changes..."
+ git commit -s -m "docs: update for new functionality from branch ${{ github.event.inputs.branch_name }}"
+
+ echo "Pushing changes to origin..."
+ git push --set-upstream origin "${{ steps.branch.outputs.branch_name }}"
+
+```
+
+
+
+
+### Local Development Implementation
+
+
+Make sure to set your `CONTINUE_API_KEY` environment variable before running local scripts to enable headless mode.
+
+
+When using the Continue CLI on your local machine, you can build workflows in various ways, one of which is by simply creating shell scripts that you can run, which call the CLI.
+
+The below shell script snippet shows the final part of a docs updating shell script that can be used to generate documentation for the code changes in a branch of a git repository.
+
+For the example snippet below to work you will need to set the following variables:
+- `CONTINUE_ORG`
+- `CONTINUE_CONFIG`
+- `BASE_BRANCH`
+- `COMPARE_BRANCH`
+- `DOCS_BRANCH_NAME`
+
+For example you can either set these as environment variables or as command line arguments to be used by the script.
+
+**Example shell script snippet for generating documentation**
+```bash title="generate-docs.sh"
+#!/bin/bash
+# The script below shows the final part of a docs updating shell script that can be used to generate documentation for the code changes in a branch of a git repository.
+
+# Generate git diff context
+echo "Generating git diff context..."
+echo "Git changes:" > context.txt
+git diff "$BASE_BRANCH..$COMPARE_BRANCH" --stat >> context.txt
+echo -e "\n\nFile list:" >> context.txt
+git diff "$BASE_BRANCH..$COMPARE_BRANCH" >> context.txt
+echo "Generated context file:"
+cat context.txt
+
+# Create documentation branch
+echo "Creating branch: $DOCS_BRANCH_NAME"
+git checkout -b "$DOCS_BRANCH_NAME"
+
+# Generate documentation with Continue CLI
+echo "Running Continue agent to generate documentation..."
+cn -config "$CONTINUE_ORG/$CONTINUE_CONFIG" \
+ --auto \
+ --allow Write \
+ -p \
+ --prompt ./context.txt \
+ "Analyze the provided git diff and identify any new functionality introduced. Summarise the new features in a few sentences. Then search the existing documentation in the site docs/ directory to determine whether these features are already documented in a way that enables users to use them. If documentation is missing or incomplete, create or modify Markdown files under the site diretory (without changing any code) to add clear explanations, usage instructions and examples for the new features in the same style and format as the existing documentation. Finally, print a brief summary of the documentation changes you made."
+
+# Clean up temporary files
+echo "Cleaning up temporary files..."
+rm -f context.txt
+
+# Commit and push documentation changes
+echo "Reviewing git status..."
+git status
+
+# Only adding files that have been added and modified in the site directory
+echo "Adding files edited in site directory to git..."
+git add site/
+
+if git diff --cached --quiet; then
+ echo "No documentation changes to commit"
+else
+ echo "Committing changes..."
+ git commit -s -m "docs: update for new functionality from branch $BRANCH_NAME"
+
+ echo "Pushing changes to origin..."
+ git push --set-upstream origin "$DOCS_BRANCH_NAME"
+
+ echo "Documentation branch created and pushed: $DOCS_BRANCH_NAME"
+fi
+```
+
+
+
+
+## Enhancement Ideas
+
+The workflow above is a basic example and can be enhanced in various ways to fit your needs. Here are some ideas:
+
+
+
+ Define a specialized agent for analyzing changes and generating targeted prompts for documentation writers, improving output quality.
+
+
+
+ Create GitHub workflows that automatically generate documentation PRs when new features are merged to main.
+
+
+
+ Build an agent that reviews older merged PRs to identify undocumented features and generates missing documentation.
+
+
+
+ Add a post-processing agent to enhance writing quality with rules like "use short sentences and simple words."
+
+
+
+## Next Steps
+
+Ready to implement automated documentation with Continue CLI? Here are some helpful resources to get you started:
+
+
+
+ Learn the fundamentals of using Continue CLI for automated coding tasks and headless workflows.
+
+
+
+ Discover how to configure and customize AI agents for your specific documentation needs.
+
+
+
+ Checkout this video from Tetrate about using Continue Agents to help with writing your docs.
+
+
+
+ Browse pre-built agents and configurations from the Continue community.
+
+
diff --git a/docs/guides/instinct.mdx b/docs/guides/instinct.mdx
new file mode 100644
index 000000000..ac933c33c
--- /dev/null
+++ b/docs/guides/instinct.mdx
@@ -0,0 +1,39 @@
+---
+title: "Using Instinct with Ollama in Continue"
+description: "Learn how to run Instinct, Continue's leading open Next Edit model, on your own hardware with Ollama"
+---
+
+
+ Instinct is a 7 billion parameter model. You should expect slow responses if
+ running on a laptop. To learn how to inference Instinct on a GPU, see our
+ [HuggingFace model card](https://huggingface.co/continuedev/instinct).
+
+
+We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev/instinct/).
+
+
+
+
+
+### 1. Install Ollama
+
+If you haven't already installed Ollama, see our guide [here](./ollama-guide).
+
+### 2. Download Instinct
+
+```bash
+ollama run nate/instinct
+```
+
+### 3. Update your `config.yaml`
+
+Open your `config.yaml` and add Instinct to the models section:
+
+```yaml
+# ... rest of config.yaml ...
+
+models:
+ - uses: continuedev/instinct
+```
+
+Alternatively, you can just click to add the block at https://hub.continue.dev/continuedev/instinct.
diff --git a/docs/guides/netlify-mcp-continuous-deployment.mdx b/docs/guides/netlify-mcp-continuous-deployment.mdx
new file mode 100644
index 000000000..c852de1de
--- /dev/null
+++ b/docs/guides/netlify-mcp-continuous-deployment.mdx
@@ -0,0 +1,715 @@
+---
+title: "Netlify Performance Optimization Cookbook"
+description: "Optimize web performance with A/B testing, automated monitoring, and data-driven improvements using Netlify MCP and Continue."
+sidebarTitle: "Using Netlify MCP for Performance Optimization"
+---
+
+
+ Use AI to automatically monitor performance metrics, run A/B tests between
+ branches, and get actionable optimization suggestions based on real user data
+ from Netlify Analytics
+
+
+
+ **Did You Know?** Netlify is more than just static hosting! It offers:
+ - [Split Testing](https://docs.netlify.com/site-deploys/split-testing/) for A/B testing branches
+ - [Analytics](https://docs.netlify.com/analytics/get-started/) with Core Web Vitals tracking
+ - [Edge Functions](https://docs.netlify.com/edge-functions/overview/) for personalization at the edge
+ - [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) ecosystem with 100+ integrations
+ - [Forms](https://docs.netlify.com/forms/setup/) with built-in spam protection
+ - [Identity](https://docs.netlify.com/visitor-access/identity/) for user authentication
+ - [Large Media](https://docs.netlify.com/large-media/overview/) for Git LFS support
+
+This guide shows you how to leverage these features through natural language with Continue CLI!
+
+
+
+## What You'll Learn
+
+This cookbook teaches you to:
+
+- Run [A/B tests](https://docs.netlify.com/site-deploys/split-testing/) between branches to measure performance impact
+- Monitor [Core Web Vitals](https://docs.netlify.com/analytics/get-started/#core-web-vitals) and build performance metrics
+- Automatically block deploys that degrade performance using [Deploy Contexts](https://docs.netlify.com/site-deploys/overview/#deploy-contexts)
+- Optimize build times with [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) and bundle sizes with AI assistance
+
+## Prerequisites
+
+- GitHub repository with a web project
+- [Netlify account](https://netlify.com) (free tier works)
+- Node.js 22+ installed (required for Netlify)
+- [Continue CLI](https://docs.continue.dev/guides/cli) (`npm i -g @continuedev/cli`)
+- [Netlify MCP](https://hub.continue.dev/netlify/netlify-mcp) configured
+- [Netlify Development Rules](https://hub.continue.dev/netlify/netlify-development) (recommended)
+
+## Quick Setup
+
+
+ The Netlify Development Rules bundle includes guardrails for:
+ - Proper `.gitignore` configuration
+ - Function structure and placement
+ - Edge function constraints
+ - Local development best practices
+
+
+For all options, first:
+
+
+ ```bash
+ npm i -g @continuedev/cli
+ ```
+
+
+
+
+ 1. Install Netlify CLI: `npm i -g netlify-cli`
+ 2. Authenticate with Netlify:
+ `netlify login`
+
+
+
+## Netlify Continuous AI Workflow Options
+
+
+ Skip the manual setup and use our pre-built Netlify Continuous AI agent that includes
+ optimized prompts, rules, and the Netlify MCP for more consistent results.
+
+
+After completing **Quick Setup** above, you have two paths to get started:
+
+
+
+
+
+
+ Visit the [Netlify Continuous AI Agent](https://hub.continue.dev/continuedev/netlify-continuous-ai) on Continue Hub and click **"Install Agent"**
+
+ This agent includes:
+ - **Optimized prompts** for Netlify deployment and performance analysis
+ - **Built-in rules** for consistent formatting and error handling
+ - **Netlify MCP** for more reliable API interactions
+
+
+
+ The agent uses the Netlify MCP automatically and includes best practice rules for deployment and performance optimization.
+
+
+
+ Navigate to your project directory and run:
+ ```bash
+ cn "Analyze my Netlify site's performance and optimize it for better Core Web Vitals."
+ ```
+
+ That's it! The agent handles everything automatically.
+
+
+
+
+ **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the Netlify MCP integration and pre-tested prompts. You can remix the agent later to customize it to your needs.
+
+
+
+
+
+
+
+
+ 1. Authenticate with Netlify:
+ `netlify login`
+ 2. Visit [Netlify MCP on Continue
+ Hub](https://hub.continue.dev/netlify/netlify-mcp)
+ 3. Follow the configuration instructions for your editor
+
+
+
+
+ Install the [Netlify Development Rules](https://hub.continue.dev/netlify/netlify-development) bundle for best practices:
+
+ 1. Visit the bundle page on Continue Hub
+ 2. Click **"Install Rules"**
+ 3. Rules automatically apply to your agent
+
+
+
+
+ Test the connection with cn CLI:
+
+ ```bash
+ cn
+ # Then in TUI mode:
+ "Check my Netlify auth and list sites"
+ ```
+
+
+
+
+
+
+ You're all set! Now you can use cn CLI to interact with Netlify using natural language prompts. Check out the examples below to get started.
+
+
+
+
+
+ To use the pre-built agent, you need either:
+ - **Continue CLI Pro Plan** with
+ the models add-on, OR
+ - **Your own API keys** added to Continue Hub secrets
+ The agent will automatically detect and use your
+ configuration along with the Netlify MCP for deployment operations.
+
+
+
+---
+
+## Performance Optimization Steps
+
+### Step 1: Baseline Performance Metrics
+
+Establish your current performance baseline using cn CLI:
+
+```bash
+# Start cn in TUI mode
+cn
+
+# Then ask:
+"Show my site's Core Web Vitals and build times"
+```
+
+
+ **Test in Plan Mode First**: Before making performance optimizations that
+ might affect your site, test your prompts in plan mode (see the [Plan Mode
+ Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes). This
+ shows you what the agent will do without executing it. For example: `"Set up
+ A/B testing between main and feature branch with performance monitoring"`
+
+
+
+
+ Netlify automatically tracks:
+ - **Build Performance**: Compile times, cache
+ hits
+ - **Runtime Performance**: Core Web Vitals, Time to Interactive
+ - **Resource Usage**: Bandwidth, function execution times
+
+
+
+### Step 2: A/B Test Branch Performance
+
+Compare performance between branches:
+
+```bash
+# In cn TUI mode:
+"Set up A/B test between main and feature branch on Netlify:
+- Split traffic 50/50 between branches
+- Track Core Web Vitals for each variant
+- Monitor conversion metrics and bounce rate
+- Enable analytics to measure performance impact
+- Configure cookie-based visitor persistence
+- Set test duration for 1000 unique visitors
+- Auto-conclude test when statistical significance reached
+Report winner based on performance + conversion metrics"
+```
+
+
+ **Enhanced Analytics**: Combine Netlify's A/B testing with PostHog session
+ recordings to understand not just which variant performs better, but why users
+ behave differently. See our [PostHog session analysis
+ guide](/guides/posthog-github-continuous-ai) to set up session tracking and
+ create a complete continuous AI analytics workflow.
+
+
+### Step 3: Advanced Build Optimization with Netlify
+
+Leverage Netlify's powerful build features to dramatically reduce build times:
+
+```bash
+# In cn TUI mode:
+"Optimize my Netlify build performance using these features:
+
+1. Enable Netlify Cache Plugin for dependency caching
+ - Configure @netlify/plugin-cache for node_modules
+ - Set up custom cache directories for .next/cache or .nuxt
+ - Enable Gatsby's incremental builds if applicable
+
+2. Set up Build Plugins from Netlify's ecosystem:
+ - Install @netlify/plugin-lighthouse for performance monitoring
+ - Add netlify-plugin-checklinks to prevent broken links
+ - Configure netlify-plugin-submit-sitemap for SEO
+
+3. Implement Conditional Builds:
+ - Skip builds when only docs change (ignore: /docs/**)
+ - Use build.ignore script for custom logic
+ - Set up monorepo-specific build triggers
+
+4. Configure concurrent builds for monorepos
+ - Set base directory per package
+ - Use pnpm workspaces or yarn workspaces
+
+Show me the netlify.toml configuration and explain each optimization"
+```
+
+
+ **Netlify Build Features You're Getting**:
+ - [Build Caching](https://docs.netlify.com/configure-builds/build-caching/) - Persist dependencies between builds
+ - [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) - Extend build process with 100+ plugins
+ - [Conditional Builds](https://docs.netlify.com/configure-builds/ignore-builds/) - Skip unnecessary builds
+ - [Monorepo Support](https://docs.netlify.com/configure-builds/monorepos/) - Optimize multi-package repos
+
+These features can reduce build times by 50-70% for most projects!
+
+
+
+
+ **Discover more optimization prompts!** The Netlify community has documented dozens of build optimization strategies in their [Support Guide: How can I optimize my Netlify build time](https://answers.netlify.com/t/support-guide-how-can-i-optimize-my-netlify-build-time/3907).
+
+ Use this guide as inspiration for cn CLI prompts not covered in this cookbook, such as:
+ - `"Configure my builds to skip Dependabot PRs automatically"`
+ - `"Set up custom ignore patterns for documentation-only changes"`
+ - `"Optimize my Contentful webhooks to prevent duplicate builds"`
+ - `"Show me how to use build hooks instead of automatic git triggers"`
+ - `"Help me choose between Astro and Hugo based on build performance"`
+
+ The community guide contains real-world scenarios that you can turn into AI-assisted solutions - just describe what you want to achieve and let cn CLI handle the implementation!
+
+
+### Step 4: Bundle Analysis with Netlify's Built-in Tools
+
+Use Netlify's bundle analyzer and optimization features:
+
+```bash
+# In cn TUI mode:
+"Analyze and optimize my bundle using Netlify's tools:
+
+1. Enable Netlify Bundle Analyzer:
+ - Add @netlify/plugin-bundle-analyzer to plugins
+ - Configure size thresholds in netlify.toml
+ - Generate visual bundle reports
+
+2. Set up Asset Optimization:
+ - Enable automatic JS minification
+ - Configure CSS optimization
+ - Turn on HTML minification
+ - Set up image processing pipeline
+
+3. Implement Smart Code Splitting:
+ - Analyze current chunks with the bundle analyzer
+ - Identify components over 50KB for splitting
+ - Configure webpack/vite for optimal chunking
+ - Set up route-based code splitting
+
+4. Configure Netlify's CDN for optimal delivery:
+ - Set cache headers for static assets
+ - Enable Brotli compression
+ - Configure edge caching rules
+
+Generate a full report with before/after bundle sizes"
+```
+
+
+
+ **Features Available Through Netlify MCP**:
+ - [Bundle
+ Analyzer](https://docs.netlify.com/configure-builds/build-plugins/bundle-analyzer/): Visualize your JavaScript bundles
+ - [Asset
+ Optimization](https://docs.netlify.com/configure-builds/post-processing/):
+ Automatic minification and compression
+ - [Edge
+ Network](https://docs.netlify.com/platform/edge-network/): Global CDN with
+ smart caching
+ - [Deploy
+ Previews](https://docs.netlify.com/site-deploys/deploy-previews/): Test
+ optimizations before production
+
+
+
+### Step 5: Image Optimization
+
+Optimize images for better performance:
+
+```bash
+# In cn TUI mode:
+"Set up Cloudinary image optimization for my Netlify site:
+- Install @cloudinary/netlify-plugin via MCP
+- Auto-convert images to WebP with fallbacks
+- Generate responsive sizes (320w, 640w, 1024w, 1920w)
+- Add lazy loading for all images
+- Configure blur-up placeholders
+- Update netlify.toml with Cloudinary settings
+Target: Reduce image payload by 60-80% and improve LCP"
+```
+
+## Continuous Performance Monitoring
+
+### Step 6: Performance Budget Enforcement with Lighthouse CI
+
+Set and enforce performance budgets with automated testing:
+
+```bash
+# In cn TUI mode:
+"Set up Lighthouse CI with performance budgets for my Netlify site:
+
+Requirements:
+- LCP must be < 2.5 seconds
+- JavaScript bundle must be < 200KB
+- Total size < 500KB
+- Performance score >= 90
+
+Setup needed:
+1. Install @lhci/cli and @netlify/plugin-lighthouse
+2. Create lighthouserc.js with these budget assertions
+3. Configure netlify.toml to run checks on all deploys
+4. Add GitHub status checks to block PRs that exceed budgets
+5. Create performance dashboard at /lighthouse-reports
+
+Please configure the complete Lighthouse CI setup with these budgets."
+```
+
+
+ This comprehensive setup will automatically test every deploy preview and
+ production deployment, blocking any changes that violate your performance
+ budgets.
+
+
+### Step 7: Real User Monitoring with Netlify Analytics
+
+Leverage Netlify's built-in analytics and integrate advanced RUM solutions:
+
+```bash
+# In cn TUI mode:
+"Set up comprehensive Real User Monitoring for my Netlify site:
+
+1. Configure Netlify Analytics Pro (requires Pro account):
+ - Set up server-side analytics (no JS required)
+ - Track Core Web Vitals (LCP, FID, CLS, INP)
+ - Monitor top pages by performance score
+ - Create custom performance alerts
+ - Configure weekly performance reports
+
+2. Integrate Web Vitals tracking:
+ - Install web-vitals library for detailed metrics
+ - Send metrics to Netlify Functions endpoint
+ - Store performance data in Netlify Blobs
+ - Create performance dashboard at /metrics
+
+3. Set up Performance Alerts:
+ - Alert when P75 LCP > 3 seconds
+ - Notify if CLS increases by 20%
+ - Monitor JavaScript error rates
+ - Track 404s and broken resources
+ - Send alerts to Slack via Netlify Functions
+
+4. Configure Geographic Performance Monitoring:
+ - Use Netlify Edge Functions to track region-specific metrics
+ - Identify slow regions with Edge geo data
+ - Compare performance across CDN nodes
+ - Optimize edge caching for slow regions
+
+5. Create Custom Performance Dashboard:
+ - Build dashboard page using Netlify Functions
+ - Display real-time Core Web Vitals
+ - Show performance trends over time
+ - Include browser and device breakdowns
+
+Show me the complete implementation with all code and configurations"
+```
+
+
+ **Note**: Netlify Analytics Pro requires a paid Netlify Pro account ($19/month
+ per site). The prompt above assumes you have this plan. For free tier users,
+ focus on steps 2-5 which use Netlify Functions and Edge Functions to build
+ custom analytics.
+
+
+
+ **Netlify Analytics Advantages**:
+ - [Server-side Analytics](https://docs.netlify.com/analytics/get-started/) - No client-side JavaScript needed
+ - [Core Web Vitals](https://docs.netlify.com/analytics/core-web-vitals/) - Automatic tracking of Google's metrics
+ - [Custom Metrics](https://docs.netlify.com/functions/logs/) - Track any metric via Functions
+ - [Edge Insights](https://docs.netlify.com/edge-functions/overview/#geolocation) - Geographic performance data
+ - [No Cookie Banner Required](https://docs.netlify.com/analytics/get-started/#privacy) - GDPR compliant by default
+
+Unlike Google Analytics, Netlify Analytics:
+
+- Doesn't slow down your site (server-side)
+- Captures 100% of traffic (no ad blockers)
+- Respects user privacy (no cookies)
+- Shows bot traffic separately
+
+
+
+
+ **Pro Tip**
+ Combine Netlify Analytics with Edge Functions to create a
+ powerful RUM solution that:
+ - Tracks performance by user segment
+ - A/B tests
+ performance optimizations
+ - Personalizes content based on connection speed
+ - Automatically serves lighter assets to slow connections
+
+
+
+## Automated Performance Checks
+
+### Add GitHub Secrets
+
+Navigate to **Repository Settings β Secrets and variables β Actions** and add:
+
+- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
+- `NETLIFY_AUTH_TOKEN`: Your Netlify personal access token
+- `NETLIFY_SITE_ID`: Your Netlify site ID
+
+### GitHub Actions Performance Guard
+
+Block PRs that degrade performance:
+
+```yaml
+name: Performance Check
+
+on:
+ pull_request:
+
+jobs:
+ performance:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "22"
+
+ - name: Install Continue CLI
+ run: |
+ npm install -g @continuedev/cli
+ echo "β
Continue CLI installed"
+
+ - name: Authenticate Continue CLI
+ env:
+ CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
+ run: |
+ cn auth login --api-key "$CONTINUE_API_KEY"
+ echo "β
Continue CLI authenticated"
+
+ - name: Deploy and Test Performance
+ id: perf
+ env:
+ NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
+ NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
+ run: |
+ echo "π Deploying PR preview and analyzing performance..."
+ cn -p "Deploy PR preview and run Lighthouse.
+ Compare scores with main branch.
+ Output JSON with score deltas." > performance.json
+
+ - name: Comment Performance Results
+ uses: actions/github-script@v7
+ with:
+ script: |
+ const fs = require('fs');
+ const perf = JSON.parse(fs.readFileSync('performance.json'));
+
+ const emoji = perf.score_delta < -10 ? 'π΄' :
+ perf.score_delta < 0 ? 'π‘' : 'π’';
+
+ const comment = `## ${emoji} Performance Impact
+
+ | Metric | Main | PR | Delta |
+ |--------|------|----|---------|
+ | Performance Score | ${perf.main_score} | ${perf.pr_score} | ${perf.score_delta > 0 ? '+' : ''}${perf.score_delta} |
+ | LCP | ${perf.main_lcp}s | ${perf.pr_lcp}s | ${perf.lcp_delta > 0 ? '+' : ''}${perf.lcp_delta}s |
+ | Bundle Size | ${perf.main_bundle}KB | ${perf.pr_bundle}KB | ${perf.bundle_delta > 0 ? '+' : ''}${perf.bundle_delta}KB |
+
+ ${perf.score_delta < -10 ? 'β οΈ **This PR significantly degrades performance. Please optimize before merging.**' : ''}
+
+ [View Full Report](${perf.report_url})`;
+
+ github.rest.issues.createComment({
+ issue_number: context.issue.number,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ body: comment
+ });
+
+ // Fail check if performance degrades significantly
+ if (perf.score_delta < -10) {
+ core.setFailed('Performance degraded by more than 10 points');
+ }
+```
+
+
+ This workflow will:
+ - **Block merge** if performance score drops >10 points
+ - **Warn** on any performance regression
+ - **Celebrate** improvements with green indicators
+
+
+
+## Performance Testing Locally
+
+### Step 8: Local Performance Testing
+
+Test performance before deploying:
+
+```bash
+# In cn TUI mode:
+"Run production build and measure bundle sizes"
+```
+
+### Step 9: Pre-commit Performance Checks
+
+Prevent performance regressions before they happen:
+
+```bash
+# In cn TUI mode:
+"Add pre-commit hooks for bundle size limits"
+```
+
+## Performance Troubleshooting
+
+### Debug Performance Issues
+
+Identify and fix performance bottlenecks:
+
+```bash
+# In cn TUI mode:
+"Why did my performance score drop?"
+```
+
+### Performance Issue Quick Fixes
+
+| Issue | Quick Fix Command (in cn TUI) |
+| ------------- | --------------------------------- |
+| Slow LCP | `"Preload critical resources"` |
+| High CLS | `"Add size attributes to images"` |
+| Large bundles | `"Implement code splitting"` |
+| Slow builds | `"Enable build caching"` |
+| Poor caching | `"Configure cache headers"` |
+
+## What You've Accomplished
+
+
+
+ You've built an AI-powered performance optimization system that:
+ - Automatically monitors Core Web Vitals
+ - Runs A/B tests between branches
+ - Blocks deployments that degrade performance
+ - Provides actionable optimization
+ suggestions
+
+
+
+## Discover Netlify's Hidden Performance Gems
+
+Features many developers don't know Netlify offers:
+
+
+
+
+ **[Netlify Edge Functions](https://docs.netlify.com/edge-functions/overview/)**
+ - Run code at the edge, closer to users
+ - Transform responses on-the-fly
+ - A/B test at the edge level
+ - Personalize content without client-side JS
+
+
+
+
+
+ **[Netlify Graph](https://docs.netlify.com/graph/overview/)**
+ - Unified GraphQL gateway for all your APIs
+ - Automatic TypeScript generation
+ - Built-in authentication handling
+ - Zero client-side API keys needed
+
+
+
+
+ **[On-Demand
+ Builders](https://docs.netlify.com/configure-builds/on-demand-builders/)**
+ - Generate pages only when requested
+ - Cache dynamically generated content
+ - Perfect for large sites (10k+ pages)
+ - Reduce build times dramatically
+
+
+
+
+ **[Background Functions](https://docs.netlify.com/functions/background-functions/)**
+ - Run tasks up to 15 minutes
+ - Process webhooks asynchronously
+ - Handle heavy computations
+ - No timeout worries
+
+
+
+```bash
+# Try these advanced features in cn TUI mode:
+"Show me how to use Netlify Edge Functions for geo-based personalization"
+"Set up On-Demand Builders for my blog with 5000 posts"
+"Configure Background Functions for image processing"
+```
+
+## Performance Best Practices
+
+The Netlify Performance Rules enforce:
+
+
+
+ - Dependency caching enabled
+ - Parallel builds when possible
+ - Incremental compilation
+ - Smart cache invalidation
+
+
+
+ - Automatic image optimization
+ - Efficient resource hints (preload, prefetch)
+ - Optimal cache headers
+ - CDN configuration
+
+
+
+ - Performance budgets enforced
+ - Core Web Vitals tracking
+ - Real user monitoring
+ - Automated alerts
+
+
+
+## Advanced Performance Strategies
+
+### Progressive Enhancement
+
+```bash
+# In cn TUI mode:
+"Implement progressive enhancement with basic HTML first"
+```
+
+### Multi-variant Testing
+
+```bash
+# In cn TUI mode:
+"Test 3 bundle strategies and auto-select winner"
+```
+
+### Predictive Prefetching
+
+```bash
+# In cn TUI mode:
+"Analyze navigation patterns and prefetch next pages"
+```
+
+## Next Steps
+
+- Install [Netlify MCP](https://hub.continue.dev/netlify/netlify-mcp) from Continue Hub
+- Set up [Performance Monitoring](https://docs.netlify.com/analytics/get-started/)
+- Configure [A/B Testing](https://docs.netlify.com/split-testing/overview/)
+- Join the [Continue Discord](https://discord.gg/continue) for support
+
+## Resources
+
+- [Netlify MCP on Continue Hub](https://hub.continue.dev/netlify/netlify-mcp)
+- [Core Web Vitals Guide](https://web.dev/vitals/)
+- [Netlify Analytics Documentation](https://docs.netlify.com/analytics/)
+- [Continue Performance Guides](https://docs.continue.dev/guides)
diff --git a/docs/guides/ollama-guide.mdx b/docs/guides/ollama-guide.mdx
index 8aaf74f1c..724afa1ef 100644
--- a/docs/guides/ollama-guide.mdx
+++ b/docs/guides/ollama-guide.mdx
@@ -34,15 +34,15 @@ curl -fsSL https://ollama.ai/install.sh | sh
After installation, start the Ollama service:
```bash
+# Check Ollama version - verify it's installed
+ollama --version
+
# Start Ollama (runs in background)
ollama serve
# Verify it's running
curl http://localhost:11434
# Should return "Ollama is running"
-
-# Check Ollama version
-ollama --version
```
### Step 3: Download Models
@@ -86,8 +86,8 @@ There are multiple ways to configure Ollama models in Continue:
The easiest way is to use [pre-configured model blocks](/reference#local-blocks) from the Continue Hub in your local configuration:
-```yaml title="~/.continue/assistants/My Local Assistant.yaml"
-name: My Local Assistant
+```yaml title="~/.continue/agents/My Local Agent.yaml"
+name: My Local Agent
version: 0.0.1
schema: v1
models:
@@ -190,9 +190,12 @@ models:
#### If Agent Mode Shows "Not Supported"
+
+
1. First, add `capabilities: [tool_use]` to your model config
2. If you still get errors, the model may not actually support tools despite documentation
3. Use a different model known to work with tools (e.g., Llama 3.1, Mistral)
+4. Alternatively, you can turn on [System Message tools](/features/agent/model-setup#how-system-message-tools-work)
See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for more details.
@@ -309,11 +312,11 @@ ollama pull deepseek-r1:32b
#### Using Hub Blocks in Local Config
**Problem**: Unclear how to use hub models locally
-**Solution**: Create a local assistant file:
+**Solution**: Create a local agent file:
```yaml
-# ~/.continue/assistants/Local.yaml
-name: Local Assistant
+# ~/.continue/agents/Local.yaml
+name: Local Agent
version: 0.0.1
schema: v1
models:
diff --git a/docs/guides/overview.mdx b/docs/guides/overview.mdx
index c1aff9224..fb0f486e3 100644
--- a/docs/guides/overview.mdx
+++ b/docs/guides/overview.mdx
@@ -9,6 +9,23 @@ description: "Comprehensive collection of practical guides for Continue includin
- [How to Self-Host a Model](/guides/how-to-self-host-a-model) - Self-hosting AI models
- [Running Continue Without Internet](/guides/running-continue-without-internet) - Offline development setup
+## Continuous AI
+
+- [Continuous AI: A Developer's Guide](/guides/continuous-ai) - Integrating AI into development workflows
+- [How to Use Continue CLI (cn)](/guides/cli) - Command-line interface for Continue
+- [Continuous AI Readiness Assessment](/guides/continuous-ai-readiness-assessment) - Evaluate team readiness for Continuous AI adoption
+
+## MCP Integration Cookbooks
+
+Step-by-step guides for integrating Model Context Protocol (MCP) servers with Continue:
+
+- [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook) - Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows
+- [PostHog Session Analysis Cookbook](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation
+- [Netlify Performance Optimization Cookbook](/guides/netlify-mcp-continuous-deployment) - Optimize web performance with A/B testing and automated monitoring using Netlify MCP
+- [Sanity CMS Integration Cookbook](/guides/sanity-mcp-continue-cookbook) - Manage headless CMS content with AI-powered workflows using Sanity MCP
+- [Snyk + Continue Hub Agent Cookbook (MCP)](/guides/snyk-mcp-continue-cookbook) - Integrate Snyk MCP via Continue Hub to scan code, deps, IaC, and containers
+- [dlt Data Pipelines Cookbook](/guides/dlt-mcp-continue-cookbook) - Build AI-powered data pipelines with dlt MCP for pipeline inspection, schema management, and debugging
+
## What Advanced Tutorials Are Available
- [Codebase and Documentation Awareness](/guides/codebase-documentation-awareness) - Make your agent aware of codebases and documentation
diff --git a/docs/guides/posthog-github-continuous-ai.mdx b/docs/guides/posthog-github-continuous-ai.mdx
new file mode 100644
index 000000000..b5aac1a1b
--- /dev/null
+++ b/docs/guides/posthog-github-continuous-ai.mdx
@@ -0,0 +1,360 @@
+---
+title: "Building a Continuous AI Workflow with PostHog and GitHub"
+description: "Build an automated system that continuously monitors PostHog analytics, analyzes user behavior with AI, and creates GitHub issues automatically using PostHog MCP."
+sidebarTitle: "PostHog Analytics with Continue CLI"
+---
+
+
+ A fully automated workflow that uses Continue CLI with the PostHog MCP to fetch analytics data, analyze user experience issues with AI, and automatically create GitHub
+ issues with the GitHub CLI.
+
+
+## What You'll Learn
+
+This cookbook teaches you to:
+
+- Use [PostHog MCP](https://posthog.com/docs/model-context-protocol) to query [analytics](https://posthog.com/docs/web-analytics), [errors](https://posthog.com/docs/error-tracking), and [feature flags](https://posthog.com/docs/feature-flags)
+- Analyze user behavior patterns with AI
+- Automatically create GitHub issues using GitHub CLI
+- Set up continuous monitoring with GitHub Actions
+
+## Prerequisites
+
+Before starting, ensure you have:
+
+- GitHub repository where you want to create issues
+- [PostHog account](https://posthog.com) with [session recordings enabled](https://posthog.com/docs/session-replay/installation) and data collecting
+- Node.js 18+ installed locally
+- [Continue CLI](https://docs.continue.dev/guides/cli) with **active credits** (required for API usage)
+- [GitHub CLI](https://cli.github.com/) installed (`gh` command)
+
+
+
+ ```bash
+ npm i -g @continuedev/cli
+ ```
+
+
+
+ 1. Visit [Continue Organizations](https://hub.continue.dev/settings/organizations)
+ 2. Sign up or log in to your Continue account
+ 3. Navigate to your organization settings
+ 4. Click **"API Keys"** and then **"+ New API Key"**
+ 5. Copy the API key immediately (you won't see it again!)
+ 6. Login to the CLI: `cn login`
+
+
+
+ Continue CLI will securely store your API keys as secrets that can be referenced in prompts.
+
+
+
+
+ Continue CLI handles the complex API interactions - you just need to provide
+ the right prompts!
+
+
+## Step 1: Set Up Your Credentials
+
+First, you'll need to gather your PostHog and GitHub API credentials and add them as secrets in Continue CLI.
+
+
+
+ You'll need a **Personal API Key** (not a Project API key) to access session recordings:
+
+ 1. Go to [Personal API Keys](https://app.posthog.com/settings/user-api-keys) in PostHog
+ 2. Click **+ Create a personal API Key**
+ 3. Name it "Continue CLI Session Analysis"
+ 4. Select these scopes:
+ - `session_recording:read` - **Required** for accessing session data
+ - `feature_flag:read` - **Required** for feature flag auditing
+ - `insight:read`
+ - `query:read`
+ - `session_recording_playlist:read`
+ 5. Copy the key immediately (you won't see it again!)
+ 6. Note your **Project ID** from your PostHog project settings
+ 7. Note your PostHog host URL (e.g., `https://us.posthog.com` or your custom domain)
+ 8. You'll also need your POSTHOG_AUTH_HEADER value, which is simply `Bearer YOUR_API_KEY`
+
+
+ **Continue Secrets**: The `POSTHOG_AUTH_HEADER` secret should be stored in
+ Continue's secure secrets storage. This keeps your API key safe and the MCP
+ automatically connects to your default PostHog project.
+
+
+
+
+ GitHub CLI handles authentication automatically - no manual PAT needed:
+
+ 1. Install GitHub CLI if not already installed
+ 2. Run `gh auth login` and follow the prompts
+ 3. Choose authentication method (browser or token)
+ 4. Grant necessary permissions when prompted (`issues:write` is **required** for creating issues)
+
+
+
+
+
+See https://docs.continue.dev/hub/secrets/secret-types#secret-types for adding secrets
+
+
+You only need to configure the PostHog MCP credential - it automatically handles project selection. To add environment variables to your Continue Hub account:
+
+1. Go to the [Continue Hub](https://hub.continue.dev)
+2. Sign in to your account
+3. Navigate to your user settings
+4. Look for the "Secrets" section
+5. Add your Personal API Key from PostHog (phx_...) as POSTHOG_AUTH_HEADER secret with format: Bearer YOUR_API_KEY
+
+
+
+
+## PostHog GitHub Continuous AI Workflow Options
+
+
+ Skip the manual setup and use our pre-built PostHog GitHub agent that includes
+ optimized prompts, rules, and the PostHog MCP for more consistent results.
+
+
+
+ **How PostHog MCP Works**:
+ - Your API key is tied to your PostHog account and
+ organization
+ - It automatically uses your default project (no project ID
+ needed)
+ - If you have multiple projects, use `mcp__posthog__switch-project` to
+ change
+ - The MCP connects via `https://mcp.posthog.com/sse` using your account context.
+
+
+
+
+
+ **Perfect for:** Immediate results with optimized prompts and built-in debugging
+
+
+
+ Visit the [PostHog GitHub Continuous AI Agent](https://hub.continue.dev/continuedev/awesome-models-posthog-gh) on Continue Hub and click **"Install Agent"** or run:
+
+ ```bash
+ cn --config continuedev/awesome-models-posthog-gh
+ ```
+
+ This agent includes:
+ - **Optimized prompts** for [PostHog analysis](https://hub.continue.dev/continuedev/posthog-analysis) and [GitHub issue creation](https://hub.continue.dev/continuedev/posthog-github-issues)
+ - **[Built-in rules](https://hub.continue.dev/bekah-hawrot-weigel/posthog-github-continuous-ai-rules)** for consistent formatting and error handling
+ - **[PostHog MCP](https://hub.continue.dev/posthog/posthog-mcp)** for more reliable API interactions
+
+
+
+ Navigate to your project directory and run:
+ ```bash
+ cn "Give me my PostHog Session data and create GitHub issues based on the problems."
+ ```
+
+ That's it! The agent handles everything automatically.
+
+
+
+
+ **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the PostHog MCP integration and pre-tested prompts.
+
+
+
+
+
+
+
+ First, install the [PostHog MCP](https://hub.continue.dev/posthog/posthog-mcp) or run:
+ ```bash
+ npx -y mcp-remote@latest https://mcp.posthog.com/sse --header Authorization:${{ secrets.continuedev/awesome-models-posthog-gh/posthog/posthog-mcp/POSTHOG_AUTH_HEADER }}
+ ```
+
+
+ In the Continue Hub, add the [PostHog GitHub Continuous AI Rules](https://hub.continue.dev/bekah-hawrot-weigel/posthog-github-continuous-ai-rules) to your account for better formatting and error handling.
+
+
+ Use this prompt with Continue CLI to analyze PostHog data and create GitHub issues:
+
+ ```bash
+
+ # In cn TUI mode:
+ "Create GitHub issues from the PostHog analysis using gh CLI:
+ - For each issue, run: gh issue create --title 'π UX Issue: [title]' --body '[details]'
+ - Add labels: --label 'bug,user-experience,automated'
+ - Set priority labels (high/medium/low)
+ - Include session data and technical details in the body
+ Execute the commands and confirm each issue was created with URL."
+ ```
+
+
+
+
+
+
+
+ **Why GitHub CLI over GitHub MCP**: While GitHub MCP is available, it can be
+ token-expensive to run. The `gh` CLI is more efficient, requires no API tokens
+ (authenticated via `gh auth login`), and provides a cleaner command-line
+ experience. GitHub MCP remains an option if you prefer full MCP integration.
+
+
+
+ To use the pre-built agent, you need either:
+ - **Continue CLI Pro Plan** with
+ the models add-on, OR
+ - **Your own API keys** added to Continue Hub secrets
+ (same as Step 1 below) The agent will automatically detect and use your
+ configuration.
+
+
+
+---
+
+
+**Repository Labels Required**: Make sure your GitHub repository has these labels:
+- `bug`, `enhancement`, `technical-debt`
+- `high-priority`, `medium-priority`, `low-priority`
+- `user-experience`, `automated`, `feature-flag`, `cleanup`
+
+Create missing labels in your repo at: **Settings β Labels β New label**
+
+
+
+
+ **What Continue CLI Does:**
+ - Parses your analysis results automatically
+ - Makes authenticated GitHub API calls using your stored token
+ - Creates properly formatted issues with appropriate labels
+ - Checks for duplicate issues to avoid spam
+ - Provides confirmation with issue URLs
+
+
+
+
+## What You've Built
+
+After completing this guide, you have a complete **Continuous AI system** that:
+
+- **Monitors user experience** - Automatically fetches and analyzes PostHog session data
+
+- **Identifies problems intelligently** - Uses AI to spot patterns and technical issues
+
+- **Creates actionable tasks** - Generates GitHub issues with specific recommendations
+
+- **Runs autonomously** - Operates daily without manual intervention using GitHub Actions
+
+- **Scales with your team** - Handles growing amounts of session data automatically
+
+
+ Your system now operates at **[Level 2 Continuous
+ AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
+ AI handles routine analysis tasks with human oversight through GitHub issue
+ review and prioritization.
+
+
+## Security Best Practices
+
+
+
+ **Protect Your API Keys:**
+ - Store all credentials as GitHub Secrets, never in
+ code
+ - Use Continue CLI's secure secret storage
+ - Limit token scopes to minimum required permissions
+ - Rotate API keys regularly (every 90 days recommended)
+ - Monitor token usage for unusual activity
+
+
+
+## Example Use Cases
+
+Here are practical examples of what you can build with PostHog MCP and Continue CLI:
+
+### Session Recording Analysis (Current Implementation)
+
+The main workflow above focuses on analyzing session recordings to identify UX issues and create GitHub issues automatically.
+
+### Feature Flag Audit and Cleanup
+
+
+ Automatically audit your feature flags to identify unused, outdated, or problematic flags that need attention.
+
+
+**What this workflow does:**
+- Fetches all feature flags from your PostHog project
+- Analyzes flag usage, rollout status, and configuration
+- Identifies flags that may be candidates for removal or updates
+- Creates GitHub issues for flag cleanup tasks
+
+**Example Continue CLI prompts:**
+
+```bash
+# Get all feature flags and analyze them
+cn "Use PostHog MCP to fetch all feature flags with mcp__posthog__feature-flag-get-all. Then analyze each flag to identify: 1) Flags that are 100% rolled out and could be removed, 2) Flags that haven't been updated in 90+ days, 3) Flags with complex targeting that might need simplification, 4) Experimental flags that should be cleaned up."
+
+# Create cleanup issues for identified flags
+cn "For each problematic feature flag identified, create a GitHub issue using gh CLI:
+- Title: 'π Feature Flag Cleanup: [flag_name]'
+- Include flag details: rollout percentage, last modified date, targeting rules
+- Add labels: 'technical-debt', 'feature-flag', 'cleanup'
+- Set priority based on risk level (high for 100% rollouts, medium for stale flags)
+- Include specific recommendations for each flag"
+
+# Audit flag performance impact
+cn "Cross-reference feature flags with PostHog performance metrics to identify flags that may be impacting user experience or site performance. Create performance-focused GitHub issues for flags showing negative impact."
+```
+
+**Required PostHog MCP Tools:**
+- `feature-flag-get-all` - Retrieve all feature flags
+- `feature-flag-get-definition` - Get detailed flag configuration
+- `query-run` - Run analytics queries to check flag usage
+- `insights-get-all` - Get insights related to flag performance
+
+**Sample Output:**
+This workflow creates GitHub issues like:
+- "π Feature Flag Cleanup: dark-mode-toggle" (100% rollout, safe to remove)
+- "π Feature Flag Review: experimental-checkout" (unused for 120 days)
+- "π Feature Flag Simplify: complex-user-targeting" (overly complex rules)
+
+### Advanced Prompts
+
+Consider enhancing your workflow with these advanced Continue CLI prompts:
+
+
+
+ "Analyze [PostHog performance
+ metrics](https://posthog.com/docs/web-analytics) alongside session
+ recordings to identify slow page loads affecting user experience"
+
+
+ "Cross-reference JavaScript console errors with user actions to identify the
+ root cause of UX issues"
+
+
+ "Use PostHog MCP to correlate feature flag rollouts with performance metrics and user behavior changes to identify flags causing issues"
+
+
+ "Create Slack alerts when critical UX issues are detected in PostHog
+ sessions or when feature flags need attention"
+
+
+
+## Next Steps
+
+- Consider [GitHub MCP](https://hub.continue.dev/github/github-mcp) as an alternative (note: can be token-expensive)
+- Configure [Slack MCP](https://hub.continue.dev/slack/slack-mcp) for alerts
+- Set up [PostHog performance monitoring](https://posthog.com/docs/web-analytics)
+- Join the [Continue Discord](https://discord.gg/continue) for support
+
+## Resources
+
+- [PostHog API Documentation](https://posthog.com/docs/api)
+- [PostHog MCP Documentation](https://posthog.com/docs/model-context-protocol)
+- [PostHog Session Replay](https://posthog.com/docs/session-replay)
+- [PostHog Feature Flags](https://posthog.com/docs/feature-flags)
+- [PostHog Error Tracking](https://posthog.com/docs/error-tracking)
+- [GitHub CLI Documentation](https://cli.github.com/)
+- [GitHub MCP on Continue Hub](https://hub.continue.dev/github/github-mcp) (alternative option)
+- [Continue CLI Guide](https://docs.continue.dev/guides/cli)
+- [Continuous AI Best Practices](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)
diff --git a/docs/guides/running-continue-without-internet.mdx b/docs/guides/running-continue-without-internet.mdx
index 9217d66da..98e80b974 100644
--- a/docs/guides/running-continue-without-internet.mdx
+++ b/docs/guides/running-continue-without-internet.mdx
@@ -3,7 +3,7 @@ title: "How to Run Continue Without Internet"
description: "Learn how to set up Continue for air-gapped or offline environments using local models, including steps to disable telemetry and configure local model providers"
---
-1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix).
-2. Turn off "Allow Anonymous Telemetry" in the user settings. This will stop Continue from attempting requests to PostHog for [anonymous telemetry](/customize/telemetry).
-3. Also in `config.json`, set the default model to a local model. You can available options [here](/customization/models#openai).
-4. Restart VS Code to ensure that the changes to `config.json` or `config.yaml` take effect.
+1. Download the latest .vsix file from the [GitHub Releases page](https://github.com/continuedev/continue/releases) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix).
+2. Turn off "Allow Anonymous Telemetry" in the user settings. This will stop Continue from attempting requests to PostHog for [anonymous telemetry](https://docs.continue.dev/reference/telemetry).
+3. In your `config.yaml` file (or through the Continue UI), set the default model to a local model. You can find available local model options [here](https://docs.continue.dev/reference/model-providers/ollama).
+4. Restart VS Code to ensure that the changes to `config.yaml` take effect.
diff --git a/docs/guides/sanity-mcp-continue-cookbook.mdx b/docs/guides/sanity-mcp-continue-cookbook.mdx
new file mode 100644
index 000000000..8af21df8d
--- /dev/null
+++ b/docs/guides/sanity-mcp-continue-cookbook.mdx
@@ -0,0 +1,610 @@
+---
+title: "Content Management with Sanity MCP and Continue"
+description: "Set up an AI-powered content management workflow that helps you manage schemas, run GROQ queries, handle documentation, and perform migrations using natural language commands."
+sidebarTitle: "Sanity CMS with Continue"
+---
+
+
+ An AI-powered content management system workflow that uses Continue's AI agent with Sanity
+ MCP to manage schemas, execute GROQ queries, handle migrations, and maintain documentation - all through simple natural language prompts
+
+
+## Prerequisites
+
+Before starting, ensure you have:
+
+- Continue account with **Hub access**
+- Read: [Understanding Agents β How to get started with Hub agents](/guides/understanding-agents#how-to-get-started-with-hub-agents)
+- Node.js 20+ installed locally
+- A [Sanity account](https://www.sanity.io/) and project (free tier works)
+- Basic understanding of content management systems
+
+For all options, first:
+
+
+ ```bash
+ npm i -g @continuedev/cli
+ ```
+
+
+
+ ```bash
+ npm install -g @sanity/cli
+ ```
+
+
+
+ To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys) and proper environment variable configuration.
+
+
+## Getting Started with Sanity
+
+
+
+New to Sanity? Follow the [Sanity Getting Started Guide](https://www.sanity.io/docs/getting-started) to set up your first project.
+
+**Quick setup:**
+```bash
+npm create sanity@latest
+cd your-project-name
+npm run dev
+```
+
+**Key resources:**
+- [Sanity Studio](https://www.sanity.io/docs/sanity-studio) - Content editing interface
+- [Schema Types](https://www.sanity.io/docs/schema-types) - Define content structure
+- [GROQ](https://www.sanity.io/docs/groq) - Query language for fetching content
+- [Content Lake](https://www.sanity.io/docs/datastore) - Real-time data store
+
+
+
+## Sanity MCP Workflow Options
+
+
+ Skip the manual setup and use our pre-built Sanity Assistant agent that includes
+ the Sanity MCP and optimized content management workflows for more consistent results. You can [remix this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to customize it for your specific needs.
+
+
+
+After ensuring you meet the **Prerequisites** above, you have two paths to get started:
+
+
+
+
+
+ Visit the [Sanity Agent Config](https://hub.continue.dev/continuedev/sanity-agent-config) on Continue Hub and click **"Install Agent"** or run:
+
+ ```bash
+ cn --config continuedev/sanity-agent-config
+ ```
+
+ This agent includes:
+ - **[Sanity MCP](https://hub.continue.dev/sanity/sanity-mcp)** pre-configured and ready to use
+ - **Content management rules** for best practices
+ - **Schema optimization** guidelines
+
+
+
+ Start with these beginner-friendly prompts to explore your content:
+
+ ```bash
+ # Content exploration
+ "Show me all blog posts published in the last month"
+
+ # Schema understanding
+ "Show me all the document types in my Sanity schema and explain their relationships"
+
+ # Content management
+ "Create a new product page for our upcoming feature"
+ ```
+
+ That's it! The agent handles everything automatically. For more starter prompts and examples, see the [official Sanity MCP blog post](https://www.sanity.io/blog/model-context-protocol).
+
+
+
+
+ **Why Use the Agent?** The pre-built Sanity Assistant agent provides consistent content management workflows and handles MCP configuration automatically, making it easier to get started with AI-powered CMS operations. Results are more consistent and debugging is easier thanks to the [Sanity MCP](https://hub.continue.dev/sanity/sanity-mcp) integration and pre-tested prompts.
+
+
+
+
+
+
+
+ Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent).
+
+
+
+ Visit the [Sanity MCP on Continue Hub](https://hub.continue.dev/sanity/sanity-mcp) and click **"Install"** to add it to the agent you created in the step above.
+
+ This will add Sanity MCP to your agent's available tools. The Hub listing automatically configures the MCP connection.
+
+
+ **Alternative installation methods:**
+ 1. **Quick CLI install**: `cn --mcp sanity/sanity-mcp`
+ 2. **With config**: Use [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config) for environment variable setup
+ 3. **Manual configuration**: Add the MCP to your agent configuration
+
+ Once installed, Sanity MCP tools become available to your Continue agent for all prompts.
+
+
+
+ **Authentication Options:**
+ - **Interactive mode**: OAuth authentication via browser (expires after 7 days)
+ - **Headless/CI mode**: Uses environment variables (SANITY_API_TOKEN, SANITY_PROJECT_ID, etc.)
+
+ See [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config) for environment variable setup.
+
+
+
+
+
+ Start with these beginner-friendly prompts:
+ ```bash
+ cn
+ # Try these starter prompts:
+ # "Show me all blog posts published in the last month"
+ # "Show me all the document types in my Sanity schema and explain their relationships"
+ # "Create a new product page for our upcoming feature"
+ ```
+
+ For more examples, see the [Sanity MCP blog post](https://www.sanity.io/blog/model-context-protocol).
+
+
+
+
+
+
+
+ To use the pre-built Sanity Assistant agent, you need either:
+ - **Continue CLI Pro Plan** with the models add-on, OR
+ - **Your own API keys** added to Continue Hub secrets
+
+ The agent will automatically detect and use your configuration along with the pre-configured Sanity MCP for content operations. Note that OAuth authentication will be required on first use.
+
+
+
+---
+
+## Sanity MCP Capabilities
+
+
+ **Sanity MCP** provides comprehensive tools for content management:
+ - Execute [GROQ queries](https://www.sanity.io/docs/groq) to fetch and analyze content
+ - Explore and modify [document schemas](https://www.sanity.io/docs/schema-types)
+ - Manage [content releases](https://www.sanity.io/docs/release-schedules) and versions
+ - Handle content [migrations](https://www.sanity.io/docs/migrating-data) between environments
+ - Automate documentation generation
+ - Perform bulk content operations
+ - Manage [localization](https://www.sanity.io/docs/localization) and translations
+
+ The MCP integrates seamlessly with your existing Sanity workspace, providing AI-powered assistance for both development and content operations.
+
+
+---
+
+## Your First MCP Conversation
+
+With everything set up, you're ready for your first AI-powered content conversation! Try these beginner-friendly starter prompts:
+
+
+
+ ```
+ "Show me all blog posts published in the last month"
+ ```
+
+
+ ```
+ "Create a new product page for our upcoming feature"
+ ```
+
+
+ ```
+ "Update our pricing information across all service pages"
+ ```
+
+
+ ```
+ "Schedule the Easter marketing campaign content release for next Tuesday"
+ ```
+
+
+
+
+**New to MCP?** These prompts demonstrate the power of natural language content management. For more examples and detailed explanations, check out the [official Sanity MCP blog post](https://www.sanity.io/blog/model-context-protocol).
+
+
+## Content Management Recipes
+
+Now you can use natural language prompts to manage your Sanity content and schemas. The Continue agent automatically calls the appropriate Sanity MCP tools.
+
+
+You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section.
+
+
+
+ **Where to run these workflows:**
+ - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs
+ - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts
+ - **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands
+
+ **Test in Plan Mode First**: Before running operations that might make
+ changes, test your prompts in plan mode (see the [Plan Mode
+ Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes in TUI/IDE). This
+ shows you what the agent will do without executing it.
+
+
+
+
+ **About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like schema exploration, GROQ execution, and content migration.
+
+
+
+### Schema Management
+
+
+ Review and understand your content schema structure.
+
+**TUI Mode Prompt:**
+```
+Show me all document types in my Sanity schema with their fields,
+validation rules, and relationships to other types.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Show me all document types in my Sanity schema with their fields, validation rules, and relationships to other types." --auto
+```
+
+
+
+### GROQ Queries
+
+
+ Run GROQ queries to fetch and analyze content.
+
+**TUI Mode Prompt:**
+```
+Run a GROQ query to fetch all articles published in the last 30 days,
+including their titles, authors, categories, and view counts.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Run a GROQ query to fetch all articles published in the last 30 days, including their titles, authors, categories, and view counts." --auto
+```
+
+
+
+### Content Operations
+
+
+ Perform bulk operations on your content.
+
+**TUI Mode Prompt:**
+```
+Find all blog posts with the category "News" and update their
+status to "archived" if they are older than 6 months.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Find all blog posts with the category 'News' and update their status to 'archived' if they are older than 6 months." --auto
+```
+
+
+
+### Localization
+
+
+ Set up and manage content translations.
+
+**TUI Mode Prompt:**
+```
+Add localization support to my article document type for
+Spanish and French languages with appropriate field configurations.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Add localization support to my article document type for Spanish and French languages with appropriate field configurations." --auto
+```
+
+
+
+### Content Migration
+
+
+ Migrate content between different schemas or environments.
+
+**TUI Mode Prompt:**
+```
+Help me migrate my blog posts from the old schema structure
+to the new one, mapping the deprecated fields to the new format.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Help me migrate my blog posts from the old schema structure to the new one, mapping the deprecated fields to the new format." --auto
+```
+
+
+
+### Documentation Generation
+
+
+ Automatically generate documentation for your content model.
+
+**TUI Mode Prompt:**
+```
+Generate comprehensive documentation for my Sanity schema including
+all document types, their purposes, field descriptions, and usage examples.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Generate comprehensive documentation for my Sanity schema including all document types, their purposes, field descriptions, and usage examples." --auto
+```
+
+
+
+### Content Releases
+
+
+ Work with Sanity's content release feature.
+
+**TUI Mode Prompt:**
+```
+List all active releases in my dataset and show me the content
+changes scheduled for each release.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "List all active releases in my dataset and show me the content changes scheduled for each release." --auto
+```
+
+
+
+### Performance Analysis
+
+
+ Optimize GROQ queries for better performance.
+
+**TUI Mode Prompt:**
+```
+Analyze the performance of my most frequent GROQ queries and
+suggest optimizations to improve response times.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Analyze the performance of my most frequent GROQ queries and suggest optimizations to improve response times." --auto
+```
+
+
+
+## Continuous Content Management with GitHub Actions
+
+This example demonstrates a **Continuous AI workflow** where content validation and schema checks run automatically in your CI/CD pipeline in headless mode using the Sanity agent config. Consider [remixing this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to add your organization's specific content governance rules.
+
+### Add GitHub Secrets
+
+Navigate to **Repository Settings β Secrets and variables β Actions** and add:
+
+- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
+- `SANITY_PROJECT_ID`: Your Sanity project ID
+- `SANITY_DATASET`: Your Sanity dataset name (usually "production")
+- `SANITY_API_TOKEN`: Your Sanity API token with appropriate permissions
+- `MCP_USER_ROLE`: Your MCP user role (typically "admin" or "editor")
+
+
+ The workflow uses the [Sanity Agent Config](https://hub.continue.dev/continuedev/sanity-agent-config) with environment variable authentication via [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config). This enables headless mode operation without OAuth browser authentication.
+
+
+### Create Workflow File
+
+This workflow automatically validates your Sanity schemas and content on pull requests using the Continue CLI in [headless mode](/cli/overview#headless-mode%3A-production-automation). It checks schema integrity, validates content relationships, and posts a summary report as a PR comment.
+
+Create `.github/workflows/sanity-content-validation.yml` in your repository:
+
+```yaml
+name: Sanity Content Validation with MCP
+
+on:
+ pull_request:
+ branches: [main]
+ workflow_dispatch:
+
+jobs:
+ validate-content:
+ runs-on: ubuntu-latest
+ env:
+ CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
+ SANITY_PROJECT_ID: ${{ secrets.SANITY_PROJECT_ID }}
+ SANITY_DATASET: ${{ secrets.SANITY_DATASET }}
+ SANITY_API_TOKEN: ${{ secrets.SANITY_API_TOKEN }}
+ MCP_USER_ROLE: ${{ secrets.MCP_USER_ROLE }}
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: "18"
+
+ - name: Install Sanity CLI
+ run: |
+ npm install -g @sanity/cli
+ echo "β
Sanity CLI installed"
+
+ - name: Install Continue CLI
+ run: |
+ npm install -g @continuedev/cli
+ echo "β
Continue CLI installed"
+
+ - name: Validate Schema Structure
+ run: |
+ echo "π Validating schema structure..."
+ cn --config continuedev/sanity-agent-config \
+ -p "Analyze the Sanity schema for any structural issues,
+ missing required fields, or broken references between document types." \
+ --auto
+
+ - name: Check Content Integrity
+ run: |
+ echo "π Checking content integrity..."
+ cn --config continuedev/sanity-agent-config \
+ -p "Run GROQ queries to identify any orphaned documents,
+ broken references, or missing required fields in the content." \
+ --auto
+
+ - name: Generate Schema Documentation
+ run: |
+ echo "π Generating schema documentation..."
+ cn --config continuedev/sanity-agent-config \
+ -p "Generate a markdown summary of all schema changes
+ in this PR and their potential impact on existing content." \
+ --auto > schema-changes.md
+
+ - name: Comment Report on PR
+ if: always() && github.event_name == 'pull_request'
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ REPORT=$(cn --config continuedev/sanity-agent-config \
+ -p "Generate a concise summary (200 words or less) of:
+ - Schema validation results
+ - Content integrity checks
+ - Any breaking changes detected
+ - Recommended actions before merging" \
+ --auto)
+
+ gh pr comment ${{ github.event.pull_request.number }} --body "$REPORT"
+```
+
+
+ Environment variables enable the MCP to authenticate without OAuth browser prompts. The [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config) documentation provides detailed setup instructions for all required variables.
+
+
+## Content Management Best Practices
+
+Implement automated content quality checks using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips.
+
+
+ ```bash
+ "Before deploying schema changes, validate that all required fields
+ are present and that no breaking changes affect existing content."
+ ```
+
+
+
+ ```bash
+ "When creating new content types, ensure they follow the existing
+ naming conventions and field patterns established in the schema."
+ ```
+
+
+
+ ```bash
+ "Review GROQ queries for performance issues and suggest indexes
+ or query restructuring to improve response times."
+ ```
+
+
+
+ ```bash
+ "Ensure all user-facing content fields have proper localization
+ support configured for the required languages."
+ ```
+
+
+## Troubleshooting
+
+### Authentication Issues
+
+```bash
+"Check if I'm properly authenticated with Sanity.
+If not, help me set up OAuth or API token authentication."
+```
+
+### Schema Not Found
+
+```bash
+"Verify that the Sanity project is properly configured
+and that the schema files are accessible in the current directory."
+```
+
+### GROQ Query Errors
+
+```bash
+"Debug this GROQ query and explain why it's failing,
+then provide a corrected version that achieves the intended result."
+```
+
+### Migration Conflicts
+
+
+ **Verification Steps:**
+ - Sanity MCP is installed via [Continue Hub](https://hub.continue.dev/sanity/sanity-mcp)
+ - Project is authenticated with Sanity
+ - Schema files are present and valid
+ - Dataset permissions are correctly configured
+
+
+## What You've Built
+
+After completing this guide, you have a complete **AI-powered content management system** that:
+
+- β
Uses natural language β Simple prompts instead of complex CMS commands
+- β
Manages schemas automatically β AI handles schema evolution and migrations
+- β
Runs continuously β Automated validation in CI/CD pipelines
+- β
Ensures quality β Content checks prevent broken references and invalid data
+
+
+ Your content management workflow now operates at **[Level 2 Continuous
+ AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
+ AI handles routine content operations and schema management with human oversight
+ through review and approval of changes.
+
+
+## Next Steps
+
+1. **Explore your schema** - Try the schema exploration prompt on your current project
+2. **Run GROQ queries** - Use natural language to query your content
+3. **Set up CI validation** - Add the GitHub Actions workflow to your repo
+4. **Create documentation** - Generate comprehensive docs for your content model
+5. **Optimize performance** - Analyze and improve query performance
+
+## Additional Resources
+
+
+
+ Complete Sanity platform documentation
+
+
+ Explore more MCP integrations and agents
+
+
+ Learn GROQ query language
+
+
+ Official Sanity MCP introduction with examples
+
+
+ Official Sanity MCP documentation
+
+
\ No newline at end of file
diff --git a/docs/guides/snyk-mcp-continue-cookbook.mdx b/docs/guides/snyk-mcp-continue-cookbook.mdx
new file mode 100644
index 000000000..850b1f212
--- /dev/null
+++ b/docs/guides/snyk-mcp-continue-cookbook.mdx
@@ -0,0 +1,695 @@
+---
+title: "Automated Security Scanning with Snyk MCP and Continue"
+description: "Set up an AI-powered security workflow that automatically scans your code, dependencies, infrastructure, and containers using natural language commands."
+sidebarTitle: "Snyk Security Scanning with Continue"
+---
+
+
+ An automated security scanning system that uses Continue's AI agent with Snyk
+ MCP to identify vulnerabilities in code, dependencies, infrastructure, and
+ containers - all through simple natural language prompts
+
+
+## Prerequisites
+
+Before starting, ensure you have:
+
+- Continue account with **Hub access**
+- Read: [Understanding Agents β How to get started with Hub agents](/guides/understanding-agents#how-to-get-started-with-hub-agents)
+- Node.js 18+ installed locally
+- [Snyk account](https://snyk.io/) (free tier works)
+- A local project to scan for vulnerabilities
+
+For all options, first:
+
+
+ ```bash
+ npm i -g @continuedev/cli
+ ```
+
+
+
+
+ 1. Sign up for a Snyk account at [snyk.io](https://snyk.io/)
+ 2. Create a new project in Snyk by importing your code repository (Git
+ provider or manual upload)
+ 3. Install and authenticate the Snyk CLI locally:
+ ```bash
+ npm install -g snyk
+ snyk auth
+ ```
+ This will open your browser to authenticate with your Snyk account.
+
+
+
+
+ **Important**: The Snyk MCP requires the Snyk CLI to be authenticated locally. Run `snyk auth` to authenticate before using the Continue agent with Snyk MCP.
+
+
+ To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys).
+
+
+## Snyk Continuous AI Workflow Options
+
+
+ Skip the manual setup and use our pre-built Snyk Continuous AI agent that includes
+ the Snyk MCP and optimized security scanning workflows for more consistent results.
+
+
+
+After ensuring you meet the **Prerequisites** above, you have two paths to get started:
+
+
+
+
+
+ Navigate to your project directory and run:
+ ```bash
+ cn --config continuedev/snyk-continuous-ai
+ ```
+
+ This agent includes:
+ - **Snyk MCP** pre-configured and ready to use
+ - **Security-focused rules** for best practices
+
+
+
+ Start with a comprehensive security scan:
+ ```bash
+ # Headless mode
+ cn -p "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity." --auto
+ ```
+
+ That's it! The agent handles everything automatically.
+
+
+
+
+ **Why Use the Agent?** The pre-built agent provides consistent security scanning workflows and handles MCP configuration automatically, making it easier to get started with AI-powered security scanning.
+
+
+
+
+
+
+
+ Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent).
+
+
+
+ Visit the [Snyk MCP on Continue Hub](https://hub.continue.dev/snyk/snyk-mcp) and click **Install** to add it to the agent you created in the step above.
+
+ This will add Snyk MCP to your agent's available tools. The Hub listing automatically configures the MCP command:
+ ```bash
+ npx -y snyk@latest mcp -t stdio
+ ```
+
+
+ **Alternative installation methods:**
+ 1. **Quick CLI install**: `cn --mcp snyk/snyk-mcp`
+ 2. **Manual configuration**: Add the MCP to your `~/.continue/config.json` under the `mcpServers` section
+
+ Once installed, Snyk MCP tools become available to your Continue agent for all prompts.
+
+
+
+ The MCP will request authentication and folder trust permissions when first used.
+ This is handled automatically by the Continue agent.
+
+
+
+
+
+ Install the [Snyk Secure-at-Inception rules](https://hub.continue.dev/snyk/secure-at-inception) from the Hub to enable automatic security scanning.
+
+ **How to add rules to your agent:**
+ 1. Visit the rules link above and click **Install**
+ 2. The rules will be added to your agent configuration automatically
+ 3. Rules apply globally to all your Continue sessions
+
+ These rules configure your agent to:
+ - **Run [SAST](https://snyk.io/learn/application-security/sast/) scans** on newly generated or modified code
+ - **Check dependencies** when adding or updating packages
+ - **Auto-fix issues** using Snyk's recommendations, then rescan
+
+
+
+
+ Start with a comprehensive security scan:
+ ```bash
+ # TUI mode
+ cn "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity."
+ ```
+
+
+
+
+
+
+
+ To use the pre-built agent, you need either:
+ - **Continue CLI Pro Plan** with the models add-on, OR
+ - **Your own API keys** added to Continue Hub secrets (same as manual setup)
+
+ The agent will automatically detect and use your configuration along with the pre-configured Snyk MCP for security scanning operations.
+
+
+
+---
+
+## Security Scanning Recipes
+
+Now you can use natural language prompts to run comprehensive security scans. The Continue agent automatically calls the appropriate Snyk MCP tools.
+
+
+You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section.
+
+
+
+ **Where to run these workflows:**
+ - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs
+ - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts
+ - **CLI (headless mode)**: Use `cn -p "your prompt" --auto` for headless commands
+
+ **Test in Plan Mode First**: Before running security scans that might make
+ changes, test your prompts in plan mode (see the [Plan Mode
+ Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes in TUI/IDE). This
+ shows you what the agent will do without executing it. For example: `"Run a
+ Snyk Code scan and fix the top 3 issues"`
+
+
+### Code Vulnerability Scanning ([SAST](https://snyk.io/learn/application-security/sast/))
+
+
+ Scan your source code for security vulnerabilities and code quality issues.
+
+**TUI Mode Prompt:**
+```
+Run a Snyk Code scan on this repo with severity threshold medium.
+Summarize issues with file:line. Propose minimal diffs for the top 3
+and rerun to verify.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Run a Snyk Code scan on this repo with severity threshold medium. Summarize issues with file:line. Propose minimal diffs for the top 3 and rerun to verify." --auto
+```
+
+
+
+### Dependency Scanning ([SCA](https://snyk.io/learn/software-composition-analysis-sca/))
+
+
+ Check open source dependencies for known vulnerabilities.
+
+**TUI Mode Prompt:**
+```
+Run Snyk Open Source on this repo (include dev deps).
+Summarize vulnerable paths and propose a minimal-risk upgrade plan.
+Re-test after the plan (dry run).
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Run Snyk Open Source on this repo (include dev deps). Summarize vulnerable paths and propose a minimal-risk upgrade plan. Re-test after the plan (dry run)." --auto
+```
+
+
+
+### Infrastructure as Code ([IaC](https://snyk.io/learn/infrastructure-as-code-iac/))
+
+
+ Scan Terraform, CloudFormation, and Kubernetes configs for misconfigurations.
+
+**TUI Mode Prompt:**
+```
+Scan ./infra with Snyk IaC. Report high/critical misconfigs
+with exact files/lines. Provide code changes and re-scan to confirm.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Scan ./infra with Snyk IaC. Report high/critical misconfigs with exact files/lines. Provide code changes and re-scan to confirm." --auto
+```
+
+
+
+### Container Scanning
+
+
+ Analyze Docker images for vulnerabilities in base images and packages.
+
+**TUI Mode Prompt:**
+```
+Scan image my-api:latest. Exclude base image vulns.
+Print dependency tree. Recommend a safer base image or upgrades.
+Re-test after the change (dry run).
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Scan image my-api:latest. Exclude base image vulns. Print dependency tree. Recommend a safer base image or upgrades. Re-test after the change (dry run)." --auto
+```
+
+
+
+### Pull Request Scanning
+
+
+ Focus scanning on modified files to catch issues before merging.
+
+**TUI Mode Prompt:**
+```
+Scan only files changed since origin/main with Snyk Code.
+Block if new high issues would be introduced. Show deltas.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Scan only files changed since origin/main with Snyk Code. Block if new high issues would be introduced. Show deltas." --auto
+```
+
+
+
+### Security Learning
+
+
+ Access security education resources based on identified vulnerabilities ([CWE](https://cwe.mitre.org/)).
+
+**TUI Mode Prompt:**
+```
+Open Snyk Learn lessons related to the top CWE(s) from this scan.
+```
+
+**Headless Mode Prompt:**
+```bash
+cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan." --auto
+```
+
+
+
+## Continuous Security with GitHub Actions
+
+This example demonstrates a **Continuous AI workflow** where security scanning runs automatically on pull requests, generates AI-powered mitigation suggestions, and posts them as PR comments.
+
+
+
+ **About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like security scanning, vulnerability analysis, and fix validation.
+
+
+
+### Add GitHub Secrets
+
+Navigate to **Repository Settings β Secrets and variables β Actions** and add:
+
+- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
+- `SNYK_TOKEN`: Your Snyk authentication token from [app.snyk.io/account](https://app.snyk.io/account)
+
+### Create Workflow File
+
+Create `.github/workflows/snyk-security.yml` in your repository:
+
+```yaml
+name: Snyk Security Scanning
+
+on:
+ pull_request:
+ branches: [main]
+
+jobs:
+ security-scan:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0 # Fetch all history for git diff
+
+ - name: Get Changed Files
+ id: changed-files
+ run: |
+ echo "π Getting changed files since main branch..."
+ CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | tr '\n' ' ')
+ echo "changed_files=$CHANGED_FILES" >> $GITHUB_OUTPUT
+ echo "Changed files: $CHANGED_FILES"
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '18'
+
+ - name: Install Snyk CLI
+ run: |
+ npm install -g snyk
+ echo "β
Snyk CLI installed"
+
+ - name: Install Continue CLI
+ run: |
+ npm install -g @continuedev/cli
+ echo "β
Continue CLI installed"
+
+ - name: Validate Secrets
+ run: |
+ if [ -z "${{ secrets.SNYK_TOKEN }}" ]; then
+ echo "β Error: SNYK_TOKEN secret is not set"
+ exit 1
+ fi
+ if [ -z "${{ secrets.CONTINUE_API_KEY }}" ]; then
+ echo "β οΈ Warning: CONTINUE_API_KEY not set - AI mitigation suggestions will be skipped"
+ fi
+ echo "β
Required secrets validated"
+
+ - name: Authenticate Snyk
+ env:
+ SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
+ run: |
+ snyk auth "$SNYK_TOKEN"
+ echo "β
Snyk authenticated"
+
+ - name: Run Security Scans
+ id: security-scan
+ continue-on-error: true
+ env:
+ SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
+ CHANGED_FILES: ${{ steps.changed-files.outputs.changed_files }}
+ run: |
+ SCAN_FAILED=0
+
+ if [ -n "$CHANGED_FILES" ]; then
+ echo "π Running targeted scan on changed files..."
+ echo "Changed files: $CHANGED_FILES"
+ FILE_ARGS=""
+ for file in $CHANGED_FILES; do
+ if [[ "$file" =~ \.(js|jsx|ts|tsx|py|java|go|rb)$ ]]; then
+ FILE_ARGS="$FILE_ARGS --file=$file"
+ fi
+ done
+
+ if [ -n "$FILE_ARGS" ]; then
+ echo "π Running Snyk Code scan on changed files..."
+ snyk code test $FILE_ARGS --severity-threshold=high --json > snyk-code-results.json || {
+ echo "β Snyk Code found high severity issues in changed files"
+ SCAN_FAILED=1
+ }
+ else
+ echo "β οΈ No scannable code files changed, skipping Snyk Code scan"
+ echo '{"runs": [{"results": []}]}' > snyk-code-results.json
+ fi
+ else
+ echo "β οΈ No changed files detected, creating empty results"
+ echo '{"runs": [{"results": []}]}' > snyk-code-results.json
+ fi
+
+ echo "π¦ Checking dependencies..."
+ snyk test --severity-threshold=high --json > snyk-oss-results.json || {
+ echo "β Snyk Open Source found high severity issues"
+ SCAN_FAILED=1
+ }
+
+ if [ $SCAN_FAILED -eq 1 ]; then
+ echo "scan_status=failed" >> $GITHUB_OUTPUT
+ echo "β οΈ Scans completed with issues - continuing to generate mitigation suggestions"
+ else
+ echo "scan_status=passed" >> $GITHUB_OUTPUT
+ echo "β
All security scans passed"
+ fi
+
+ - name: Generate AI Mitigation Suggestions
+ if: always() && steps.security-scan.outputs.scan_status == 'failed'
+ continue-on-error: true
+ env:
+ CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
+ SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
+ run: |
+ echo "π€ Generating AI-powered mitigation suggestions..."
+
+ # Create a summary of findings for Continue CLI
+ FINDINGS_SUMMARY=$(cat snyk-code-results.json snyk-oss-results.json | jq -r '
+ if .runs then
+ .runs[0].results[] | "Code Issue: \(.message.text) in \(.locations[0].physicalLocation.artifactLocation.uri) (Severity: \(.level))"
+ elif .vulnerabilities then
+ .vulnerabilities[] | "Dependency Issue: \(.title) in \(.packageName)@\(.version) (Severity: \(.severity))"
+ else
+ empty
+ end
+ ' | head -20)
+
+ if [ -n "$FINDINGS_SUMMARY" ]; then
+ echo "π Security findings to analyze:"
+ echo "$FINDINGS_SUMMARY"
+ echo ""
+
+ # Use Continue CLI to generate mitigation suggestions
+ PROMPT="Analyze these Snyk security findings and provide specific, actionable mitigation steps for each issue. Focus on: 1) Root cause, 2) Immediate fix, 3) Long-term prevention. Findings: $FINDINGS_SUMMARY. Provide clear, prioritized recommendations."
+
+ cn --config continuedev/snyk-continuous-ai -p "$PROMPT" --auto > mitigation-suggestions.md || {
+ echo "β οΈ Warning: Could not generate AI suggestions"
+ exit 0
+ }
+
+ if [ -f mitigation-suggestions.md ]; then
+ echo "β
AI mitigation suggestions generated"
+ echo ""
+ echo "--- Mitigation Suggestions ---"
+ cat mitigation-suggestions.md
+ fi
+ else
+ echo "β οΈ No findings to analyze"
+ fi
+
+ - name: Post Mitigation Summary to PR
+ if: steps.security-scan.outputs.scan_status == 'failed' && hashFiles('mitigation-suggestions.md') != ''
+ continue-on-error: true
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ if [ -f mitigation-suggestions.md ]; then
+ echo "π¬ Posting mitigation summary to PR..."
+
+ # Create PR comment with mitigation suggestions
+ cat > pr-comment.md <<'EOF'
+ ## π‘οΈ Snyk Mitigation Summary
+
+ Snyk has identified security issues in this PR. Here are AI-generated mitigation recommendations:
+
+ EOF
+
+ cat mitigation-suggestions.md >> pr-comment.md
+
+ cat >> pr-comment.md < scan-results.md
+
+ if [ -f scan-results.md ]; then
+ echo "β
Security report generated successfully"
+ cat scan-results.md
+ else
+ echo "β οΈ Warning: scan-results.md was not created"
+ fi
+
+ - name: Upload Security Report
+ if: always()
+ continue-on-error: true
+ uses: actions/upload-artifact@v4
+ with:
+ name: security-scan-results
+ path: |
+ scan-results.md
+ snyk-code-results.json
+ snyk-oss-results.json
+ mitigation-suggestions.md
+ if-no-files-found: warn
+
+ - name: Fail if Security Issues Found
+ if: steps.security-scan.outputs.scan_status == 'failed'
+ run: |
+ echo "β Security scan failed - high severity issues found"
+ echo "π Review the security report artifact for details and mitigation suggestions"
+ exit 1
+```
+
+
+ **About SNYK_TOKEN**: The workflow uses the SNYK_TOKEN in two ways:
+ 1. **Direct Snyk CLI authentication** - Authenticates the Snyk CLI for running scans
+ 2. **Continue CLI access** - Available as an environment variable when Continue generates AI mitigation suggestions
+
+ The `cn` agent automatically uses the SNYK_TOKEN when needed for Snyk MCP operations.
+
+
+
+ This workflow demonstrates several advanced features:
+ - **Changed Files Detection**: Only scans files modified in the PR
+ - **AI Mitigation**: Uses Continue CLI to generate actionable mitigation steps
+ - **PR Comments**: Automatically posts mitigation suggestions as PR comments
+ - **Comprehensive Reporting**: Generates detailed security reports with artifacts
+
+
+## Security Guardrails
+
+Implement automated security policies using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips.
+
+
+ **Coming Soon**: These security guardrail prompts will be available as pre-configured rules on the Continue Hub for easy installation.
+
+
+
+ ```bash
+ "Always run Snyk Code before committing newly
+ generated code; refuse to proceed if high
+ issues remain."
+ ```
+
+
+
+ ```bash
+ "When adding/updating a dependency, run Snyk Open Source, choose the
+ lowest-risk upgrade, and re-test."
+ ```
+
+
+
+ ```bash
+ "Before building containers, scan base images and recommend
+ security-hardened alternatives."
+ ```
+
+
+
+ ```bash
+ "Scan all Terraform changes for compliance
+ violations before applying infrastructure."
+ ```
+
+
+
+ Enable the **Secure-at-Inception** rules from the Hub to automatically apply
+ these guardrails to all code generation and modifications.
+
+
+## Troubleshooting
+
+### Authentication Issues
+
+```bash
+"Check Snyk auth status and current org. If not authenticated,
+help me authenticate. Then run a quick Code scan on ./
+with severity medium and print one example issue."
+```
+
+### Fix Validation
+
+```bash
+"Propose minimal diffs only in affected files,
+then rerun the same Snyk scan to confirm resolution."
+```
+
+### Connection Problems
+
+
+ **Verification Steps:** - Snyk MCP is installed via [Continue
+ Hub](https://hub.continue.dev/snyk/snyk-mcp) - Secure-at-Inception rules are
+ [enabled](https://hub.continue.dev/snyk/secure-at-inception) - Authentication
+ completed successfully - Project folder has been trusted
+
+
+## What You've Built
+
+After completing this guide, you have a complete **AI-powered security system** that:
+
+- β
Uses natural language β Simple prompts instead of complex CLI commands
+- β
Fixes automatically β AI suggests and validates security fixes
+- β
Runs continuously β Automated scanning in CI/CD pipelines
+- β
Enforces guardrails β Security rules prevent vulnerable code from shipping
+
+
+ Your security workflow now operates at **[Level 2 Continuous
+ AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
+ AI handles routine security scanning and remediation with human oversight
+ through review and approval of fixes.
+
+
+## Next Steps
+
+1. **Run your first scan** - Try the [SAST](https://snyk.io/learn/application-security/sast/) prompt on your current project
+2. **Review findings** - Analyze the security report and implement fixes
+3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo
+4. **Customize rules** - Add project-specific security policies
+5. **Monitor trends** - Track [vulnerability](https://snyk.io/learn/security-vulnerability/) reduction over time
+
+## Additional Resources
+
+
+
+ Complete Snyk platform documentation
+
+
+ Explore more MCP integrations and agents
+
+
+ Learn about secure coding practices
+
+
+ Understanding MCP architecture
+
+
diff --git a/docs/guides/understanding-assistants.mdx b/docs/guides/understanding-agents.mdx
similarity index 62%
rename from docs/guides/understanding-assistants.mdx
rename to docs/guides/understanding-agents.mdx
index 4bc35693b..d03ce8758 100644
--- a/docs/guides/understanding-assistants.mdx
+++ b/docs/guides/understanding-agents.mdx
@@ -1,63 +1,63 @@
---
-title: "How to Understand Assistants: Hub vs Local Configuration"
-description: "Learn how to choose between cloud-managed Hub assistants and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach"
+title: "How to Understand Agents: Hub vs Local Configuration"
+description: "Learn how to choose between cloud-managed Hub agents and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach"
---
Every developer has unique needs when it comes to AI assistance. Some prefer the convenience of cloud-managed configurations, while others need the control and privacy of local setups. Continue offers both paths, and this guide will help you choose the right one for your workflow.
## What Are the Two Paths to AI Assistance?
-Continue provides two distinct ways to configure your AI assistant:
+Continue provides two distinct ways to configure your AI agent:
Think of Continue's configuration options like choosing between a managed service and self-hosting. Both get you to the same destinationβpowerful AI assistance in your IDEβbut the journey and control level differ significantly.
-### How to Access Your Assistant Configuration
+### How to Access Your Agent Configuration
Before we dive into the specifics, let's understand how to access your configuration:
1. Open the Continue Chat sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)
-2. Click the Assistant selector above the main chat input
-3. Hover over an assistant and click:
- - `new window` icon for Hub assistants
- - `gear` icon for Local assistants
+2. Click the Agent selector above the main chat input
+3. Hover over an agent and click:
+ - `new window` icon for Hub agents
+ - `gear` icon for Local agents
-
+
-## What Are Hub Assistants: The Managed Experience
+## What Are Hub Agents: The Managed Experience
-Hub Assistants represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured assistants that sync seamlessly across all your development environments.
+Hub Agents represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured agents that sync seamlessly across all your development environments.
-### Why Should You Choose Hub Assistants?
+### Why Should You Choose Hub Agents?
**The Power of Simplicity**
-- **Instant Setup**: Browse the [assistant marketplace](https://hub.continue.dev/explore/assistants) and add any assistant to your account with a single click
+- **Instant Setup**: Browse the [agent marketplace](https://hub.continue.dev) and add any agent to your account with a single click
- **Web-Based Management**: Configure models, add secrets, and customize settings through an intuitive web interfaceβno JSON editing required
- **Automatic Synchronization**: Make a change on the hub, and it reflects immediately across all your IDE instances
-- **Team Collaboration**: Share custom assistants with your team, ensuring everyone uses the same optimized configurations
+- **Team Collaboration**: Share custom agents with your team, ensuring everyone uses the same optimized configurations
-
+
-### How to Get Started with Hub Assistants
+### How to Get Started with Hub Agents
The journey from zero to AI-powered coding takes just four steps:
-1. **Select Your Assistant**: Click the assistant selector in your IDE's Continue panel
-2. **Explore or Create**: Browse community assistants or craft your own specialized helper
+1. **Select Your Agent**: Click the agent selector in your IDE's Continue panel
+2. **Explore or Create**: Browse community agents or craft your own specialized helper
3. **Secure Your Keys**: Add API keys as [User Secrets](https://hub.continue.dev/settings/secrets) in the hubβthey're encrypted and never exposed
4. **Sync and Code**: Click "Reload config" to pull your latest settings
-Pro tip: Hub Assistants are perfect for teams. Create a custom assistant with your team's coding standards, preferred models, and context sources, then share it with a simple link.
+Pro tip: Hub Agents are perfect for teams. Create a custom agent with your team's coding standards, preferred models, and context sources, then share it with a simple link.
-### How to Manage Hub Assistants
+### How to Manage Hub Agents
-All Hub Assistant management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Assistant](/hub/assistants/edit-an-assistant).
+All Hub Agent management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Agent](/hub/agents/edit-an-agent).
-## What Are Local Assistants: The Power User's Choice
+## What Are Local Agents: The Power User's Choice
-Local Assistants put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI assistant's behavior, with all configuration stored directly on your machine.
+Local Agents put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI agent's behavior, with all configuration stored directly on your machine.
-### Why Should You Choose Local Assistants?
+### Why Should You Choose Local Agents?
**Complete Control and Privacy**
@@ -66,7 +66,7 @@ Local Assistants put you in the driver's seat. Using a `config.yaml` file, you h
- **Offline Capability**: Once configured, no internet connection needed (assuming you're using local models)
- **Unlimited Customization**: Access every configuration option, experimental feature, and advanced setting
-### How to Set Up Local Assistants
+### How to Set Up Local Agents
Local configuration lives in a single YAML file in your home directory:
@@ -77,13 +77,13 @@ Local configuration lives in a single YAML file in your home directory:
**Quick Access Method:**
-1. Open the assistants dropdown in your IDE
-2. Click the gear icon next to "Local Assistant"
+1. Open the agents dropdown in your IDE
+2. Click the gear icon next to "Local Agent"
3. The `config.yaml` file opens in your editor

-### The Local Assistant Experience
+### The Local Agent Experience
When you edit your `config.yaml`, Continue provides intelligent autocomplete for all available options. Save the file, and Continue automatically reloads your configurationβno restart required.
@@ -93,9 +93,9 @@ For the complete configuration reference, see our [config.yaml documentation](/r
## How to Make the Right Choice
-The decision between Hub and Local assistants often comes down to your specific needs and constraints. Here's a framework to help you decide:
+The decision between Hub and Local agents often comes down to your specific needs and constraints. Here's a framework to help you decide:
-### Choose Hub Assistants When You:
+### Choose Hub Agents When You:
**Value Convenience Over Control**
@@ -106,7 +106,7 @@ The decision between Hub and Local assistants often comes down to your specific
**Need Advanced Collaboration**
-- Want to share custom assistants with teammates
+- Want to share custom agents with teammates
- Need centralized API key management
- Require quick updates across your entire organization
@@ -116,7 +116,7 @@ The decision between Hub and Local assistants often comes down to your specific
- Want to experiment with different models and configurations
- Prefer guided setup experiences
-### Choose Local Assistants When You:
+### Choose Local Agents When You:
**Require Maximum Control**
@@ -140,21 +140,21 @@ The decision between Hub and Local assistants often comes down to your specific
Here's a secret: you don't have to choose just one. Many developers use both approaches:
-- **Hub Assistants** for general development and experimentation
-- **Local Assistants** for production work or client projects with specific requirements
+- **Hub Agents** for general development and experimentation
+- **Local Agents** for production work or client projects with specific requirements
-You can switch between them seamlessly using the assistant selector in your IDE.
+You can switch between them seamlessly using the agent selector in your IDE.
## Common Patterns and Best Practices
-### For Hub Assistant Users
+### For Hub Agent Users
-1. **Start with Community Assistants**: Before creating your own, explore what others have built
+1. **Start with Community Agents**: Before creating your own, explore what others have built
2. **Use Secrets Properly**: Never hardcode API keysβalways use the User Secrets feature
-3. **Create Specialized Assistants**: Make different assistants for different contexts (frontend, backend, DevOps)
+3. **Create Specialized Agents**: Make different agents for different contexts (frontend, backend, DevOps)
4. **Share Liberally**: If you create something useful, share it with the community
-### For Local Assistant Users
+### For Local Agent Users
1. **Version Control Your Config**: Treat your `config.yaml` like codeβcommit it, review changes, and maintain history
2. **Use Environment Variables**: For sensitive data, reference environment variables instead of hardcoding values
@@ -163,7 +163,7 @@ You can switch between them seamlessly using the assistant selector in your IDE.
## Troubleshooting and Tips
-### Hub Assistant Issues
+### Hub Agent Issues
**Changes Not Reflecting?**
@@ -171,12 +171,12 @@ You can switch between them seamlessly using the assistant selector in your IDE.
- Check your internet connection
- Ensure you're signed in to the correct account
-**Assistant Not Available?**
+**Agent Not Available?**
- Verify it's added to your account on the hub
- Check if it requires specific API keys
-### Local Assistant Issues
+### Local Agent Issues
**Config Not Loading?**
@@ -193,7 +193,7 @@ You can switch between them seamlessly using the assistant selector in your IDE.
Now that you understand both configuration approaches, you're ready to dive deeper:
-- **For Hub Users**: [Create Your First Assistant](/hub/assistants/create-an-assistant)
+- **For Hub Users**: [Create Your First Agent](/hub/agents/create-an-agent)
- **For Local Users**: [Explore the Config Reference](/reference)
- **For Everyone**: [Discover Available Models](/customize/model-providers/overview)
diff --git a/docs/hub/agents/create-an-agent.mdx b/docs/hub/agents/create-an-agent.mdx
new file mode 100644
index 000000000..27de80846
--- /dev/null
+++ b/docs/hub/agents/create-an-agent.mdx
@@ -0,0 +1,35 @@
+---
+title: "How to Create an AI Agent"
+description: "Learn how to create custom AI coding agents in Continue Hub by remixing existing agents or building new ones from scratch with reusable blocks and YAML configuration."
+sidebarTitle: "Create an AI Agent"
+---
+
+## How to Create an AI Agent from Scratch
+
+To create an agent from scratch, select βNew agentβ in the top bar.
+
+
+
+
+Choose a name, slug, description, and icon for your agent.
+
+The easiest way to create an agent is to click "Create agent" with the default configuration and then add / remove blocks using the sidebar.
+
+Alternatively, you can edit the agent YAML directly before clicking "Create agent". Refer to examples of agents on [hub.continue.dev](https://hub.continue.dev) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details.
+
+
+
+## How to Remix an Agent
+
+You can also create an agent by remixing an existing one. This is useful if you want to start with a pre-configured agent and make modifications.
+
+By clicking the βremixβ button, youβll be taken to the βCreate a remixβ page.
+
+
+
+Once here, youβll be able to
+
+1. add or remove blocks in YAML configuration
+2. change the name, description, icon, etc.
+
+Clicking βCreate agentβ will make this agent available for use.
diff --git a/docs/hub/agents/edit-an-agent.mdx b/docs/hub/agents/edit-an-agent.mdx
new file mode 100644
index 000000000..d4f74fd5b
--- /dev/null
+++ b/docs/hub/agents/edit-an-agent.mdx
@@ -0,0 +1,20 @@
+---
+title: "How to Edit an Agent"
+description: "New versions of an agent can be created and published using the sidebar."
+---
+
+
+
+First, select an agent from the dropdown at the top.
+
+While editing an agent, you can explore the hub and click "Add Block" from a block page to add it to your agent.
+
+For blocks that require secret values like API keys, you will see a small notification on the block's tile in the sidebar that will indicate if action is needed.
+
+To delete a block, click the trash icon.
+
+If a block you want to use does not exist yet, you can [create a new block](/hub/blocks/create-a-block).
+
+When you are done editing, click "Publish" to publish a new version of the agent.
+
+Click "Open VS Code" or "Open JetBrains" to open your IDE for using the agent.
diff --git a/docs/hub/agents/intro.mdx b/docs/hub/agents/intro.mdx
new file mode 100644
index 000000000..7747c8145
--- /dev/null
+++ b/docs/hub/agents/intro.mdx
@@ -0,0 +1,8 @@
+---
+title: "Introduction to Agents"
+description: "Custom AI code agents are configurations of building blocks that enable a coding experience tailored to your specific use cases."
+---
+
+`config.yaml` is a format for defining custom AI code agents. An agent has some top-level properties (e.g. `name`, `version`), but otherwise consists of composable lists of **blocks** such as `models` and `rules`, which are the atomic building blocks of an agent.
+
+The `config.yaml` is parsed by the open-source Continue IDE extensions to create custom agent experiences. When you log in to [hub.continue.dev](https://hub.continue.dev/), your agents will automatically be synced with the IDE extensions.
diff --git a/docs/hub/agents/use-an-agent.mdx b/docs/hub/agents/use-an-agent.mdx
new file mode 100644
index 000000000..afefad9a3
--- /dev/null
+++ b/docs/hub/agents/use-an-agent.mdx
@@ -0,0 +1,19 @@
+---
+title: "How to Use an Agent"
+description: "Learn how to add, configure, and use an AI agent in Continue, including setting required inputs and selecting it in your IDE extension."
+---
+
+## Steps to Use an AI Agent in Continue
+
+Once you've found the agent you want to use on Continue Hub:
+
+1. Click βAdd Agentβ on its page
+2. Add any required inputs (e.g. secrets like API keys)
+3. Select βSave changesβ in agent sidebar on the right hand side
+
+After saving, open your IDE extension and:
+
+- Select the agent from the **agent dropdown** in the Continue extension.
+- Begin using it for chat, code generation, or other configured capabilities.
+
+
diff --git a/docs/hub/assistants/create-an-assistant.mdx b/docs/hub/assistants/create-an-assistant.mdx
deleted file mode 100644
index dd7ee9678..000000000
--- a/docs/hub/assistants/create-an-assistant.mdx
+++ /dev/null
@@ -1,34 +0,0 @@
----
-title: "How to Create an AI Assistant"
-description: "Learn how to create custom AI coding assistants in Continue Hub by remixing existing assistants or building new ones from scratch with reusable blocks and YAML configuration."
-sidebarTitle: "Create an AI Assistant"
----
-
-## How to Create an AI Assistant from Scratch
-
-To create an assistant from scratch, select βNew assistantβ in the top bar.
-
-
-
-Choose a name, slug, description, and icon for your assistant.
-
-The easiest way to create an assistant is to click "Create assistant" with the default configuration and then add / remove blocks using the sidebar.
-
-Alternatively, you can edit the assistant YAML directly before clicking "Create assistant". Refer to examples of assistants on [hub.continue.dev](https://hub.continue.dev/explore/assistants) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details.
-
-
-
-## How to Remix an Assistant
-
-You can also create an assistant by remixing an existing one. This is useful if you want to start with a pre-configured assistant and make modifications.
-
-By clicking the βremixβ button, youβll be taken to the βCreate a remixβ page.
-
-
-
-Once here, youβll be able to
-
-1. add or remove blocks in YAML configuration
-2. change the name, description, icon, etc.
-
-Clicking βCreate assistantβ will make this assistant available for use.
diff --git a/docs/hub/assistants/edit-an-assistant.mdx b/docs/hub/assistants/edit-an-assistant.mdx
deleted file mode 100644
index 235b01358..000000000
--- a/docs/hub/assistants/edit-an-assistant.mdx
+++ /dev/null
@@ -1,20 +0,0 @@
----
-title: "How to Edit an Assistant"
-description: "New versions of an assistant can be created and published using the sidebar."
----
-
-
-
-First, select an assistant from the dropdown at the top.
-
-While editing an assistant, you can explore the hub and click "Add Block" from a block page to add it to your assistant.
-
-For blocks that require secret values like API keys, you will see a small notification on the block's tile in the sidebar that will indicate if action is needed.
-
-To delete a block, click the trash icon.
-
-If a block you want to use does not exist yet, you can [create a new block](/hub/blocks/create-a-block).
-
-When you are done editing, click "Publish" to publish a new version of the assistant.
-
-Click "Open VS Code" or "Open JetBrains" to open your IDE for using the assistant.
diff --git a/docs/hub/assistants/intro.mdx b/docs/hub/assistants/intro.mdx
deleted file mode 100644
index fd556b16a..000000000
--- a/docs/hub/assistants/intro.mdx
+++ /dev/null
@@ -1,8 +0,0 @@
----
-title: "Introduction to Assistants"
-description: "Custom AI code assistants are configurations of building blocks that enable a coding experience tailored to your specific use cases."
----
-
-`config.yaml` is a format for defining custom AI code assistants. An assistant has some top-level properties (e.g. `name`, `version`), but otherwise consists of composable lists of **blocks** such as `models` and `rules`, which are the atomic building blocks of an assistant.
-
-The `config.yaml` is parsed by the open-source Continue IDE extensions to create custom assistant experiences. When you log in to [hub.continue.dev](https://hub.continue.dev/), your assistants will automatically be synced with the IDE extensions.
diff --git a/docs/hub/assistants/use-an-assistant.mdx b/docs/hub/assistants/use-an-assistant.mdx
deleted file mode 100644
index f6d19b836..000000000
--- a/docs/hub/assistants/use-an-assistant.mdx
+++ /dev/null
@@ -1,19 +0,0 @@
----
-title: "How to Use an Assistant"
-description: "Learn how to add, configure, and use an AI assistant in Continue, including setting required inputs and selecting it in your IDE extension."
----
-
-## Steps to Use an AI Assistant in Continue
-
-Once you've found the assistant you want to use on Continue Hub:
-
-1. Click βAdd Assistantβ on its page
-2. Add any required inputs (e.g. secrets like API keys)
-3. Select βSave changesβ in assistant sidebar on the right hand side
-
-After saving, open your IDE extension and:
-
-- Select the assistant from the **assistant dropdown** in the Continue extension.
-- Begin using it for chat, code generation, or other configured capabilities.
-
-
diff --git a/docs/hub/blocks/block-types.mdx b/docs/hub/blocks/block-types.mdx
index f544885f9..9e31200e1 100644
--- a/docs/hub/blocks/block-types.mdx
+++ b/docs/hub/blocks/block-types.mdx
@@ -1,34 +1,31 @@
---
-title: "Blocks: Models, Rules, Prompts, and MCP servers"
+title: "Models, Rules, Prompts, and MCP servers"
sideBarTitle: "Block Types"
description: "Explore the different types of reusable blocks in Continue Hub including models, MCP servers, rules, and prompts"
---
## Models
-Models are blocks that let you specify Large Language Models (LLMs) and other deep learning models to be used for various roles in the open-source IDE extension like Chat, Autocomplete, Edit, Embed, Rerank, etc. You can explore available models on [the hub](https://hub.continue.dev/explore/models).
-
-Continue supports [many model providers](/customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](/customize/model-roles). View [`models`](/reference#models) in the YAML Reference for more details.
+Models are blocks that let you specify Large Language Models (LLMs) and other deep learning models to be used for various roles in the open-source IDE extension like Chat, Autocomplete, Edit, Embed, Rerank, etc. You can explore available models on [the hub](https://hub.continue.dev/?type=models).
+Continue supports [many model providers](/customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
+Read more about roles [here](/customize/model-roles) and view [`models`](/reference#models) in the YAML Reference for more details.
## MCP Servers
-Model Context Protocol (MCP) is a standard way of building and sharing tools for language models. MCP Servers can be defined in `mcpServers` blocks. [Explore MCP Servers](https://hub.continue.dev/explore/mcp) on the hub.
+Model Context Protocol (MCP) is a standard way of building and sharing tools for language models. MCP Servers can be defined in `mcpServers` blocks.
-Learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
+[Explore MCP Servers](https://hub.continue.dev/?type=mcpServers) on the Hub, learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
## Rules
-Rules blocks are instructions that your custom AI code assistant will always keep in mind - the contents of rules are inserted into the system message for all Chat requests. [Explore rules](https://hub.continue.dev/explore/rules) on the hub.
+Rules blocks are instructions that your custom AI code agent will always keep in mind - the contents of rules are inserted into the system message for all Chat, Plan, and Agent requests.
-Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.
+[Explore rules](https://hub.continue.dev/?type=rules) on the Hub, learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.
## Prompts
-Prompts blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub.
-
-Prompt blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub.
-Prompt blocks have the same syntax as [prompt files](/customize/deep-dives/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).
-
+Prompts blocks are pre-written, reusable instructions that are used to kick off a task. They are especially useful as context for repetitive and/or complex tasks.
+[Explore prompts](https://hub.continue.dev/?type=prompts) on the Hub, learn more in the [prompts deep dive](/customize/deep-dives/prompts), and view [`prompts`](/reference#prompts) in the YAML Reference for more details.
\ No newline at end of file
diff --git a/docs/hub/blocks/create-a-block.mdx b/docs/hub/blocks/create-a-block.mdx
index 2c5dc58fb..3b59267a8 100644
--- a/docs/hub/blocks/create-a-block.mdx
+++ b/docs/hub/blocks/create-a-block.mdx
@@ -12,7 +12,7 @@ By clicking the βremixβ button, youβll be taken to the βCreate a remix

-Once here, youβll be able to 1) edit YAML configuration for the block and 2) change name, description, icon, etc. Clicking βCreate blockβ will make this block available for use in an assistant.
+Once here, youβll be able to 1) edit YAML configuration for the block and 2) change name, description, icon, etc. Clicking βCreate blockβ will make this block available for use in an agent.
## How to Create a Block from Scratch
@@ -26,4 +26,4 @@ After filling out information on the block, you will want to create a block foll
### Block Inputs
-Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their assistant.
+Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their agent.
diff --git a/docs/hub/blocks/intro.mdx b/docs/hub/blocks/intro.mdx
index d4cc1c25c..7180b3f63 100644
--- a/docs/hub/blocks/intro.mdx
+++ b/docs/hub/blocks/intro.mdx
@@ -1,6 +1,6 @@
---
title: "Introduction"
-description: "Blocks are the components you use to build a custom AI code assistant. These include Models, MCP Servers, Rules, and Prompts."
+description: "Blocks are the components you use to build a custom AI code agent. These include Models, MCP Servers, Rules, and Prompts."
---
-Blocks follow the [`config.yaml`](/reference) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code assistant.
+Blocks follow the [`config.yaml`](/reference) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code agent.
diff --git a/docs/hub/blocks/use-a-block.mdx b/docs/hub/blocks/use-a-block.mdx
index 3971dbc63..ed5ff7cb3 100644
--- a/docs/hub/blocks/use-a-block.mdx
+++ b/docs/hub/blocks/use-a-block.mdx
@@ -1,12 +1,12 @@
---
title: "How to Use a Block"
-description: "Learn how to use blocks in Continue Hub to enhance your AI code assistant."
+description: "Learn how to use blocks in Continue Hub to enhance your AI code agent."
---
-Blocks are used to build custom AI code assistants in Continue Hub. Learn more:
+Blocks are used to build custom AI code agents in Continue Hub. Learn more:
-- [Create an assistant](/hub/assistants/create-an-assistant)
-- [Edit an assistant](/hub/assistants/edit-an-assistant)
+- [Create an agent](/hub/agents/create-an-agent)
+- [Edit an agent](/hub/agents/edit-an-agent)
Some blocks require inputs. If you are missing an input for a block, a notification icon will show up in the sidebar next to the block. Click the notification to select which secret to use for the block input:
diff --git a/docs/hub/governance/creating-an-org.mdx b/docs/hub/governance/creating-an-org.mdx
index dfcb0665e..c0a021000 100644
--- a/docs/hub/governance/creating-an-org.mdx
+++ b/docs/hub/governance/creating-an-org.mdx
@@ -6,7 +6,7 @@ description: "To Create an Organization, click the organization selector in the

1. Choose a name, which will be used as the display name for your organization throughout the hub
-2. Add a slug, which will be used for your org URL and as the prefix to all organization blocks and assistant slugs
+2. Add a slug, which will be used for your org URL and as the prefix to all organization blocks and agent slugs
3. Select an icon for your organization using the image uploader
4. Finally, add a Biography, which will be displayed on your org Home Page
diff --git a/docs/hub/introduction.mdx b/docs/hub/introduction.mdx
index 29061ec2a..449a59e8f 100644
--- a/docs/hub/introduction.mdx
+++ b/docs/hub/introduction.mdx
@@ -10,6 +10,6 @@ Continue Hub provides a centralized platform for managing the essential building
- **[Models](/hub/blocks/block-types#models)**: Discover and configure models from various providers
- **[MCP Tools](/hub/blocks/block-types#mcp-servers)**: Access and integrate Model Context Protocol tools to retrieve real-time data and take action
- **[Rules](/hub/blocks/block-types#rules)**: Define custom guidelines for your custom AI coding agent to follow
-- **[Prompts](/hub/blocks/block-types#prompts)**: Create and share reusable prompts that kickoff your custom AI coding agent
+- **[Prompts](/hub/blocks/block-types#prompts)**: Create and share reusable instructions that kickoff your agent
Continue Hub also makes it easy for engineering leaders to centrally [configure](/hub/secrets/secret-types) and [govern](/hub/governance/org-permissions) these resources for their organization.
\ No newline at end of file
diff --git a/docs/hub/secrets/secret-types.mdx b/docs/hub/secrets/secret-types.mdx
index b5f75de6a..ebf3d39ca 100644
--- a/docs/hub/secrets/secret-types.mdx
+++ b/docs/hub/secrets/secret-types.mdx
@@ -1,16 +1,16 @@
---
title: "Secret Types"
-description: "The Continue Hub comes with secrets management built-in. Secrets are values such as API keys or endpoints that can be shared across assistants and within organizations."
+description: "The Continue Hub comes with secrets management built-in. Secrets are values such as API keys or endpoints that can be shared across agents and within organizations."
---
## User secrets
-User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside the assistant `config.yaml`.
+User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside the agent `config.yaml`.
This allows API requests to be made directly from the IDE extensions. You can use user secrets with [Solo](/hub/governance/pricing#solo), [Teams](/hub/governance/pricing#teams), and [Enterprise](/hub/governance/pricing#enterprise). User secrets can be managed [here](https://hub.continue.dev/settings/secrets) in the hub.
## Org secrets
-Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with assistants in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys).
+Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with agents in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys).
This is why LLM requests are proxied through api.continue.dev / on-premise proxy and secrets are never sent to the IDE extensions. You can only use org secrets on [Teams](/hub/governance/pricing#teams) and [Enterprise](/hub/governance/pricing#enterprise). If you are an admin, you can manage secrets for your organization from the org settings page.
diff --git a/docs/hub/sharing.mdx b/docs/hub/sharing.mdx
index d8de121a0..014e90ab6 100644
--- a/docs/hub/sharing.mdx
+++ b/docs/hub/sharing.mdx
@@ -15,17 +15,17 @@ Share your custom assistants, blocks, and configurations with the Continue commu
[Visit the Hub β](https://hub.continue.dev)
-## Browse Assistants
+## Browse Agents
Explore assistants created by the community for specific use cases and workflows.
-[Browse Assistants β](https://hub.continue.dev)
+[Browse Agents β](https://hub.continue.dev)
-## Using Assistants
+## Using Agents
Learn how to discover, install, and use community-created assistants in your projects.
-[Learn About Assistants β](/hub/assistants/intro)
+[Learn About Agents β](/hub/agents/intro)
---
diff --git a/docs/hub/source-control.mdx b/docs/hub/source-control.mdx
index 5e863336b..ee0c410ec 100644
--- a/docs/hub/source-control.mdx
+++ b/docs/hub/source-control.mdx
@@ -1,6 +1,6 @@
---
title: "Source Control"
-description: "When managing your custom assistants within an organization, you might want to take advantage of your usual source control workflows. Continue makes this easy with a that automatically syncs your YAML files with hub.continue.dev. We are also planning on adding automations for GitLab, BitBucket, Gitee, and others. If you are interested, please reach out to us on ."
+description: "When managing your custom agents within an organization, you might want to take advantage of your usual source control workflows. Continue makes this easy with a that automatically syncs your YAML files with hub.continue.dev. We are also planning on adding automations for GitLab, BitBucket, Gitee, and others. If you are interested, please reach out to us on ."
---
## Quickstart
@@ -34,11 +34,11 @@ This is the only configuration necessary, but you can view the full list of opti
### 4. Commit and push
-Add the [YAML for your assistants and blocks](/reference) to the appropriate directories. The name of the file will be the slug of the assistant/block.
+Add the [YAML for your agents and blocks](/reference) to the appropriate directories. The name of the file will be the slug of the agent/block.
-- `assistants/public` for public assistants
-- `assistants/private` for private (visible only within your organization) assistants
+- `assistants/public` for public agents
+- `assistants/private` for private (visible only within your organization) agents
- `blocks/public` for public blocks
- `blocks/private` for private blocks
-Then, commit and push your changes. Once the GitHub Action has completed running, you should be able to view the assistants within your organization on hub.continue.dev. For subsequent changes, make sure to increment the `version` property of your updated YAML file(s).
+Then, commit and push your changes. Once the GitHub Action has completed running, you should be able to view the agents within your organization on hub.continue.dev. For subsequent changes, make sure to increment the `version` property of your updated YAML file(s).
diff --git a/docs/hub/workflows/intro.mdx b/docs/hub/workflows/intro.mdx
new file mode 100644
index 000000000..1c5fd3d5b
--- /dev/null
+++ b/docs/hub/workflows/intro.mdx
@@ -0,0 +1,97 @@
+---
+title: "Introduction"
+description: "Run Continuous AI workflows in the background"
+---
+
+
+ Workflows are in beta. Please share any feedback with us in [GitHub discussions](https://github.com/continuedev/continue/discussions/8051).
+
+
+Workflows are a way to run and manage background agents in Continue. You can use them for:
+- Addressing small nitpicks and bugs
+- Building boilerplate-heavy features
+- Investigating an issue to kickstart your work
+- [Automated security scanning](../../guides/snyk-mcp-continue-cookbook)
+- Running repeatable tasks with your own rules, prompts, and MCP servers
+- Much more!
+
+## Quickstart
+
+To run your first workflow
+
+1. Go to [hub.continue.dev/agents](https://hub.continue.dev/agents)
+
+
+
+2. Connect with your GitHub account
+3. Enter the prompt for your agent
+
+## Example Workflow Tasks
+
+Here are some example tasks you can try with your workflows:
+
+
+
+
+ - "Fix the TypeError in api/users.ts where the user object might be undefined"
+ - "Add null checks to all database query results in the services/ directory"
+ - "Fix all ESLint warnings in the components folder"
+ - "Update deprecated React lifecycle methods to hooks in legacy components"
+
+
+
+
+
+ - "Create a new REST endpoint for user profile updates with validation and error handling"
+ - "Add pagination to the products list page with previous/next buttons"
+ - "Implement dark mode toggle using Tailwind CSS classes across all pages"
+ - "Add unit tests for the authentication service using Jest"
+
+
+
+
+
+ - "Scan the codebase for hardcoded API keys and move them to environment variables"
+ - "Add input sanitization to all user-facing form fields"
+ - "Update all npm packages with known security vulnerabilities"
+ - "Implement rate limiting on the /api/login endpoint"
+
+
+
+
+
+ - "Add JSDoc comments to all exported functions in the utils/ directory"
+ - "Create a README.md for the new payment-processing module with setup instructions"
+ - "Generate TypeScript interfaces for all API response schemas"
+ - "Add error handling boilerplate to all async functions missing try-catch blocks"
+
+
+
+
+
+ - "Investigate why the login API is returning 500 errors intermittently and suggest fixes"
+ - "Analyze the performance bottleneck in the data processing pipeline"
+ - "Review the database schema for the orders table and suggest optimizations"
+ - "Find all TODO comments related to authentication and create a summary"
+
+
+
+
+
+ - "Extract the repeated validation logic in controllers into a shared utility function"
+ - "Convert all class components in src/legacy to functional components with hooks"
+ - "Rename all instances of 'userId' to 'accountId' across the codebase"
+ - "Split the 500-line UserService.ts into smaller, single-responsibility services"
+
+
+
+
+## How to use background agents
+
+The practice of using background agents, which we call Continuous AI, requires practice and forethought to set up the right guiderails and habits to fit your development workflow, much like learning to work with a larger engineering team. We are constantly sharing our learnings on the [Continuous AI Blog](https://blog.continue.dev), but these few high-level tips are a great way to quickly become successful with workflows:
+
+- Practice first with the [Continue CLI](../../guides/cli) in "TUI mode". The same agent that powers our CLI is used for workflows, so you can easily test your prompts locally.
+- Identify and begin with tasks that you are confident can be accomplished by Continue. For example, ask Continue to fix a small bug where you already know the solution is simple.
+- Once you have merged a PR created by Continue, be increasingly ambitious with your tasks. By being willing to start tasks that might not succeed on the first try, you will learn about prompting best practices and limitations of current language models.
+- Use thorough prompts. Workflows can run for a long time to complete their task, so it is worthwhile to invest in sharing all of the important details.
+- Discuss the use of workflows with your team. Truly embracing Continuous AI likely means acknowledging that a higher volume of PRs will be created and adjusting your code review habits.
diff --git a/docs/images/assistant-selector-dropdown.png b/docs/images/assistant-selector-dropdown.png
new file mode 100644
index 000000000..9b4b69f3e
Binary files /dev/null and b/docs/images/assistant-selector-dropdown.png differ
diff --git a/docs/images/autocomplete-model-selection.png b/docs/images/autocomplete-model-selection.png
new file mode 100644
index 000000000..530b30a63
Binary files /dev/null and b/docs/images/autocomplete-model-selection.png differ
diff --git a/docs/images/autocomplete-settings.png b/docs/images/autocomplete-settings.png
new file mode 100644
index 000000000..fa3fe2fd6
Binary files /dev/null and b/docs/images/autocomplete-settings.png differ
diff --git a/docs/images/cn-demo.gif b/docs/images/cn-demo.gif
index 795be614d..4b37b3f77 100644
Binary files a/docs/images/cn-demo.gif and b/docs/images/cn-demo.gif differ
diff --git a/docs/images/continue-settings-card-layout.png b/docs/images/continue-settings-card-layout.png
new file mode 100644
index 000000000..4fc8c6d8b
Binary files /dev/null and b/docs/images/continue-settings-card-layout.png differ
diff --git a/docs/images/features/autocomplete/images/instinct-autocomplete.png b/docs/images/features/autocomplete/images/instinct-autocomplete.png
new file mode 100644
index 000000000..3da34143d
Binary files /dev/null and b/docs/images/features/autocomplete/images/instinct-autocomplete.png differ
diff --git a/docs/images/guides/images/agent-not-supported.png b/docs/images/guides/images/agent-not-supported.png
new file mode 100644
index 000000000..1846dede1
Binary files /dev/null and b/docs/images/guides/images/agent-not-supported.png differ
diff --git a/docs/images/hub/agent-remix-button.png b/docs/images/hub/agent-remix-button.png
new file mode 100644
index 000000000..8410177f6
Binary files /dev/null and b/docs/images/hub/agent-remix-button.png differ
diff --git a/docs/images/hub/assistant-new-button.png b/docs/images/hub/assistant-new-button.png
deleted file mode 100644
index d6088a061..000000000
Binary files a/docs/images/hub/assistant-new-button.png and /dev/null differ
diff --git a/docs/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png b/docs/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png
deleted file mode 100644
index d6088a061..000000000
Binary files a/docs/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png and /dev/null differ
diff --git a/docs/images/hub/assistants/images/assistant-new-button.png b/docs/images/hub/assistants/images/assistant-new-button.png
deleted file mode 100644
index d6088a061..000000000
Binary files a/docs/images/hub/assistants/images/assistant-new-button.png and /dev/null differ
diff --git a/docs/images/hub/assistants/images/assistant-remix-button.png b/docs/images/hub/assistants/images/assistant-remix-button.png
deleted file mode 100644
index 02c9d34ef..000000000
Binary files a/docs/images/hub/assistants/images/assistant-remix-button.png and /dev/null differ
diff --git a/docs/images/hub/new-agent-button.png b/docs/images/hub/new-agent-button.png
new file mode 100644
index 000000000..b4c6525ac
Binary files /dev/null and b/docs/images/hub/new-agent-button.png differ
diff --git a/docs/images/hub/workflows/images/workflows-setup.png b/docs/images/hub/workflows/images/workflows-setup.png
new file mode 100644
index 000000000..05419e84d
Binary files /dev/null and b/docs/images/hub/workflows/images/workflows-setup.png differ
diff --git a/docs/images/indexing-settings.png b/docs/images/indexing-settings.png
new file mode 100644
index 000000000..1b4cb9be6
Binary files /dev/null and b/docs/images/indexing-settings.png differ
diff --git a/docs/images/instinct.gif b/docs/images/instinct.gif
new file mode 100644
index 000000000..840a8f304
Binary files /dev/null and b/docs/images/instinct.gif differ
diff --git a/docs/index.mdx b/docs/index.mdx
index 4df6c30cc..52c753c11 100644
--- a/docs/index.mdx
+++ b/docs/index.mdx
@@ -1,55 +1,148 @@
---
-title: "Introduction"
+title: "Welcome to Continue"
icon: book-open
-description: "Continue is an open source platform for building AI-powered coding assistants with customizable components for chat, autocomplete, edit, and agent workflows in VS Code and JetBrains IDEs"
+description: "Practice Continuous AI with an open-source CLI, open-source IDE extensions, and a Hub for custom AI coding agents"
---
-**Continue enables developers to ship faster with Continuous AI.**
+
+ **Build faster with AI across your IDE, terminal, and CI/CD pipelines with
+ Continue.**
+
-**You can use Continue to build and run custom agents across your IDE, terminal, and CI.**
+## Continue CLI
-1. Get started with Continue in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions
+Terminal-native AI coding assistance with TUI and headless modes.
-2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback
+
-3. Discover models, rules, and MCP tools on [Continue Hub](https://hub.continue.dev/)
+ ```bash npm
+ npm install -g @continuedev/cli
+ ```
+
+ ```bash yarn
+ yarn global add @continuedev/cli
+ ```
+
+ ```bash pnpm
+ pnpm add -g @continuedev/cli
+ ```
+
+
- to work on development tasks together with AI
+ Interactive terminal interface for development workflows
+
+ β’ Automate builds & refactoring
+
+ β’ Pre-commit hooks & scripted fixes
+
+ β’ Terminal-first development
- to ask general questions and clarify code sections
+ Automated AI coding for CI/CD and server environments
+
+ β’ Run in CI/CD pipelines
+
+ β’ Batch processing & bulk operations
+
+ β’ Server & container deployments
+
+
+
+## IDE Extensions
+
+
+ **Complement your CLI workflow** - Rich editor integrations for interactive
+ development.
+
+
+
+
+ Install from VS Code Marketplace
+
+ Real-time coding assistance and refactoring
- to modify a code section without leaving your current file
+ Install from JetBrains Plugin Repository
+
+ Autocomplete and multi-file edits
+
+
+
+## Core Features
+
+
+
+ Multi-step workflows and complex task automation
+
+
+ Ask questions and explore your codebase
+
+
+ In-place code editing without breaking flow
- to receive inline code suggestions as you type
+ Inline AI suggestions as you type
+
+
+
+## Configuration
+
+
+
+ Connect your preferred AI models
+
+
+ Configure AI behavior and constraints
+
+
+ Extend functionality with MCP tools
+
+
+
+## Resources
+
+
+
+ Community models, rules, and tools
+
+
+ Get help from the community
+
+
+ TUI and headless workflow examples
-
diff --git a/docs/package-lock.json b/docs/package-lock.json
index 22f0e47fd..9727e1e34 100644
--- a/docs/package-lock.json
+++ b/docs/package-lock.json
@@ -675,14 +675,14 @@
}
},
"node_modules/@inquirer/core": {
- "version": "10.1.14",
- "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-10.1.14.tgz",
- "integrity": "sha512-Ma+ZpOJPewtIYl6HZHZckeX1STvDnHTCB2GVINNUlSEn2Am6LddWwfPkIGY0IUFVjUUrr/93XlBwTK6mfLjf0A==",
+ "version": "10.2.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-10.2.0.tgz",
+ "integrity": "sha512-NyDSjPqhSvpZEMZrLCYUquWNl+XC/moEcVFqS55IEYIYsY0a1cUCevSqk7ctOlnm/RaSBU5psFryNlxcmGrjaA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@inquirer/figures": "^1.0.12",
- "@inquirer/type": "^3.0.7",
+ "@inquirer/figures": "^1.0.13",
+ "@inquirer/type": "^3.0.8",
"ansi-escapes": "^4.3.2",
"cli-width": "^4.1.0",
"mute-stream": "^2.0.0",
@@ -831,15 +831,15 @@
}
},
"node_modules/@inquirer/editor": {
- "version": "4.2.14",
- "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-4.2.14.tgz",
- "integrity": "sha512-yd2qtLl4QIIax9DTMZ1ZN2pFrrj+yL3kgIWxm34SS6uwCr0sIhsNyudUjAo5q3TqI03xx4SEBkUJqZuAInp9uA==",
+ "version": "4.2.18",
+ "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-4.2.18.tgz",
+ "integrity": "sha512-yeQN3AXjCm7+Hmq5L6Dm2wEDeBRdAZuyZ4I7tWSSanbxDzqM0KqzoDbKM7p4ebllAYdoQuPJS6N71/3L281i6w==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^10.1.14",
- "@inquirer/type": "^3.0.7",
- "external-editor": "^3.1.0"
+ "@inquirer/core": "^10.2.0",
+ "@inquirer/external-editor": "^1.0.1",
+ "@inquirer/type": "^3.0.8"
},
"engines": {
"node": ">=18"
@@ -876,10 +876,45 @@
}
}
},
+ "node_modules/@inquirer/external-editor": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-1.0.1.tgz",
+ "integrity": "sha512-Oau4yL24d2B5IL4ma4UpbQigkVhzPDXLoqy1ggK4gnHg/stmkffJE4oOXHXF3uz0UEpywG68KcyXsyYpA1Re/Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "chardet": "^2.1.0",
+ "iconv-lite": "^0.6.3"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/external-editor/node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/@inquirer/figures": {
- "version": "1.0.12",
- "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-1.0.12.tgz",
- "integrity": "sha512-MJttijd8rMFcKJC8NYmprWr6hD3r9Gd9qUC0XwPNwoEPWSMVJwA2MlXxF+nhZZNMY+HXsWa+o7KY2emWYIn0jQ==",
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-1.0.13.tgz",
+ "integrity": "sha512-lGPVU3yO9ZNqA7vTYz26jny41lE7yoQansmqdMLBEfqaGsmdg7V3W9mK9Pvb5IL4EVZ9GnSDGMO/cJXud5dMaw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -1114,9 +1149,9 @@
}
},
"node_modules/@inquirer/type": {
- "version": "3.0.7",
- "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-3.0.7.tgz",
- "integrity": "sha512-PfunHQcjwnju84L+ycmcMKB/pTPIngjUJvfnRhKY6FKPuYXlM4aQCb/nIdTFR6BEhMjFvngzvng/vBAJMZpLSA==",
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-3.0.8.tgz",
+ "integrity": "sha512-lg9Whz8onIHRthWaN1Q9EGLa/0LFJjyM8mEUbL1eTi6yMGvBf8gvyDLtxSXztQsxMvhxxNpJYrwa1YHdq+w4Jw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -5198,9 +5233,9 @@
}
},
"node_modules/chardet": {
- "version": "0.7.0",
- "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz",
- "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==",
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.1.0.tgz",
+ "integrity": "sha512-bNFETTG/pM5ryzQ9Ad0lJOTa6HWD/YsScAR3EnCPZRPlQh77JocYktSHOUHelyhm8IARL+o4c4F1bP5KVOjiRA==",
"dev": true,
"license": "MIT"
},
@@ -6830,21 +6865,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/external-editor": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz",
- "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "chardet": "^0.7.0",
- "iconv-lite": "^0.4.24",
- "tmp": "^0.0.33"
- },
- "engines": {
- "node": ">=4"
- }
- },
"node_modules/extract-zip": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz",
@@ -10800,16 +10820,6 @@
"integrity": "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==",
"license": "MIT"
},
- "node_modules/os-tmpdir": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz",
- "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=0.10.0"
- }
- },
"node_modules/own-keys": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz",
@@ -13056,19 +13066,6 @@
"tinycolor2": "^1.6.0"
}
},
- "node_modules/tmp": {
- "version": "0.0.33",
- "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz",
- "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "os-tmpdir": "~1.0.2"
- },
- "engines": {
- "node": ">=0.6.0"
- }
- },
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
diff --git a/docs/reference.mdx b/docs/reference.mdx
index e67d5dad9..c35459e44 100644
--- a/docs/reference.mdx
+++ b/docs/reference.mdx
@@ -1,136 +1,23 @@
---
title: "config.yaml Reference"
-description: "Comprehensive guide to the config.yaml format used by Continue.dev for building custom coding assistants. Learn how to define models, context providers, rules, prompts, and more using reusable blocks and YAML configuration."
+description: "Comprehensive guide to the config.yaml format used by Continue.dev for building custom coding agents. Learn how to define models, context providers, rules, prompts, and more using YAML configuration."
---
## Introduction
-Continue hub assistants are defined using the `config.yaml` specification. Assistants can be loaded from [the Hub](https://hub.continue.dev/explore/assistants) or locally
+Continue Agents are defined using the `config.yaml` specification.
-- [Continue Hub](https://hub.continue.dev/explore/assistants) - YAML is stored on the hub and automatically synced to the extension
+**Agents** are composed of models, rules, and tools (MCP servers).
-- Locally
- - in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/assistants`. The name of the file will be used as the display name of the assistant, e.g. `My Assistant.yaml`
- - in your workspace in a `/.continue/assistants` folder, with the same naming convention
+
+
+Learn how to work with Continue's configuration system, including using hub models, rules, and tools, creating local configurations, and organizing your setup.
+
-
- Config YAML replaces `config.json`, which is deprecated. View the **[Migration
- Guide](/reference/yaml-migration)**.
-
-
-An assistant is made up of:
-
-1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the assistant
-2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as models, docs, and context providers.
-
-A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is.
-
-Examples of blocks and assistants can be found on the [Continue hub](https://hub.continue.dev/explore/assistants).
-
-Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks.
-
-### Using Blocks
-
-Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev).
-
-Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type.
-
-For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one.
-
-Assistant models section
-
-```yaml
-name: Team Agent
-version: 1.0.0
-schema: v1
-
-models:
- - uses: anthropic/claude-3.5-sonnet # an imported model block
- - model: deepseek-reasoner # an explicit model block
- provider: ollama
-```
-
-### Local Blocks
-
-It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of your workspace (these will automatically be applied to all assistants when you are in that workspace) or in your home directory at `~/.continue` (these will automatically be applied globally).
-
-Place your YAML files in the following folders:
-
-Assistants:
-
-- `.continue/assistants` - for assistants
-
-Blocks:
-
-- `.continue/rules` - for rules
-- `.continue/models` - for models
-- `.continue/prompts` - for prompts
-- `.continue/context` - for context providers
-- `.continue/docs` - for docs
-- `.continue/data` - for data
-- `.continue/mcpServers` - for MCP Servers
-
-You can find many examples of each of these block types on the [Continue Explore Page](https://hub.continue.dev/explore/models)
-
-
-Local blocks utilizing mustache notation for secrets (`${{ secrets.SECRET_NAME }}`) can read secret values:
-
-- globally, from a `.env` located in the global `.continue` folder (`~/.continue/.env`)
-- per-workspace, from a `.env` file located at the root of the current workspace.
-
-
-
-### Inputs
-
-Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows:
-
-```yaml title="config.yaml"
-name: myprofile/custom-model
-version: 1.0.0
-schema: v1
-
-models:
- - name: My Favorite Model
- provider: anthropic
- apiKey: ${{ inputs.ANTHROPIC_API_KEY }}
- defaultCompletionOptions:
- temperature: ${{ inputs.TEMP }}
-```
-
-Which can then be imported like this:
-
-```yaml title="config.yaml"
-name: myprofile/custom-assistant
-version: 1.0.0
-schema: v1
-
-models:
- - uses: myprofile/custom-model
- with:
- ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }}
- TEMP: 0.9
-```
-
-Note that hub secrets can be passed as inputs, using a similar mustache format: `secrets.SECRET_NAME`.
-
-### Overrides
-
-Block properties can be also be directly overriden using `override`. For example:
-
-```yaml title="config.yaml"
-name: myprofile/custom-assistant
-version: 1.0.0
-schema: v1
-
-models:
- - uses: myprofile/custom-model
- with:
- ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }}
- TEMP: 0.9
- override:
- roles:
- - chat
-```
+
+Learn how to build and configure agents, understand their capabilities, and customize them for your development workflow.
+
+
## Properties
@@ -219,7 +106,7 @@ The `models` section defines the language models used in your configuration. Mod
- `topP`: The cumulative probability for nucleus sampling.
- `topK`: Maximum number of tokens considered at each step.
- `stop`: An array of stop tokens that will terminate the completion.
- - `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ models.
+ - `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ and some Ollama models.
- `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models.
- `requestOptions`: HTTP request options specific to the model.
@@ -251,6 +138,7 @@ The `models` section defines the language models used in your configuration. Mod
- `modelTimeout`: Model timeout for autocomplete requests in milliseconds.
- `maxSuffixPercentage`: Maximum percentage of prompt allocated for suffix.
- `prefixPercentage`: Percentage of input allocated for prefix.
+ - `transform`: If `false`, disables trimming of multiline completions. Defaults to `true`. Useful for models that generate better multiline completions without transformations.
- `template`: Custom template for autocomplete using Mustache syntax. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables.
- `onlyMyCode`: Only includes code within the repository for context.
- `useCache`: If `true`, enables caching for completions.
@@ -325,47 +213,55 @@ context:
### `rules`
-List of rules that the LLM should follow. These are concatenated into the system message for all [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) requests. See the [rules deep dive](/customize/deep-dives/rules) for details.
+Rules are concatenated into the system message for all [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) requests.
-Explicit rules can either be simple text or an object with the following properties:
+Confiugration example:
-- `name` (**required**): A display name/title for the rule
-- `rule` (**required**): The text content of the rule
-- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
-
-```yaml title="config.yaml"l
+```yaml title="config.yaml"
rules:
- - Always annotate Python functions with their parameter and return types
- - name: TypeScript best practices
- rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly.
- globs: "**/*.{ts,tsx}"
- - name: TypeScript test patterns
- rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking.
- globs:
- - "src/**/*.test.ts"
- - "tests/**/*.ts"
- - uses: myprofile/my-mood-setter
- with:
- TONE: concise
+ - uses: sanity/sanity-opinionated # rules file stored on Continue Hub
+ - uses: file://user/Desktop/rules.md # rules file stored on local computer
```
+Rules file example:
+
+```md title="rules.md"
+---
+name: Pirate rule
+---
+
+Talk like a pirate
+```
+
+See the [rules deep dive](/customize/deep-dives/rules) for more details.
+
---
### `prompts`
-A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text.
+Prompts can be invoked with a / command.
+
+Configuration example:
```yaml title="config.yaml"
prompts:
- - name: check
- description: Check for mistakes in my code
- prompt: |
- Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:
- - Syntax errors
- - Logic errors
- - Security vulnerabilities
+ - uses: supabase/create-functions # prompts file stored on Continue Hub
+ - uses: file://user/Desktop/prompts.md # prompts file stored on local computer
```
+Prompts file example:
+
+```md title="prompts.md"
+---
+name: Make pirate comments
+invokable: true
+---
+
+Rewrite all comments in the active file to talk like a pirate
+```
+
+See the [prompts deep dive](/customize/deep-dives/prompts) for more details.
+
---
### `docs`
@@ -401,7 +297,8 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a
- `args`: An optional array of arguments for the command.
- `env`: An optional map of environment variables for the server process.
- `cwd`: An optional working directory to run the command in. Can be absolute or relative path.
-- `connectionTimeout`: An optional connection timeout number to the server in milliseconds.
+- `requestOptions`: Optional request options for `sse` and `streamable-http` servers. Same format as [model requestOptions](#models).
+- `connectionTimeout`: Optional timeout for _initial_ connection to MCP server
**Example:**
@@ -564,3 +461,9 @@ models:
maxPromptTokens: 1024
onlyMyCode: true
```
+
+---
+
+## `config.json` Deprecation
+
+`config.yaml `replaces `config.json`, which is deprecated. View the **[Migration Guide](/reference/yaml-migration)** for help transitioning from the old format.
diff --git a/docs/reference/continue-mcp.mdx b/docs/reference/continue-mcp.mdx
index bd7d7d3cf..882a662c8 100644
--- a/docs/reference/continue-mcp.mdx
+++ b/docs/reference/continue-mcp.mdx
@@ -45,7 +45,7 @@ What context providers are available in Continue?
### Customization
```
-How do I add custom rules to my assistant in Continue?
+How do I add custom rules to my agent in Continue?
```
## Troubleshooting
diff --git a/docs/reference/deprecated-docs.mdx b/docs/reference/deprecated-docs.mdx
index c972db7fa..a62e88b49 100644
--- a/docs/reference/deprecated-docs.mdx
+++ b/docs/reference/deprecated-docs.mdx
@@ -408,4 +408,4 @@ The following configuration example includes:
-This setup could also involve enabling Chromium as a backup for local documentation through the [User Settings Page](../customize/settings).
\ No newline at end of file
+This setup could also involve enabling Chromium as a backup for local documentation through the User Settings Page (Gear Icon).
\ No newline at end of file
diff --git a/docs/reference/json-reference.mdx b/docs/reference/json-reference.mdx
index 5960f07f8..6f1a015b0 100644
--- a/docs/reference/json-reference.mdx
+++ b/docs/reference/json-reference.mdx
@@ -6,7 +6,7 @@ noindex: true
**This page documents deprecated functionality.** For creating slash commands and customizing Continue, please use:
- - [Prompt blocks and prompt files](/customize/deep-dives/slash-commands) for slash commands
+ - [Prompt blocks and prompt files](/customize/deep-dives/prompts) for slash commands
- [config.yaml](/reference) for configuration
See the `config.yaml` reference and migration guide
@@ -191,7 +191,7 @@ Parameters that control the behavior of text generation and completion settings.
- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes).
- `numGpu`: For Ollama, this parameter overrides the number of gpu layers that will be used to load the model into VRAM.
- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream.
-- `reasoning`: Enables thinking/reasoning for Anthropic Claude 3.7+ models.
+- `reasoning`: Enables thinking/reasoning for Anthropic Claude 3.7+ and some Ollama models.
- `reasoningBudgetTokens`: Sets budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models.
Example
@@ -485,8 +485,6 @@ Several experimental config parameters are available, as described below:
- `applyCodeBlock`: Model title for applying code blocks.
- `repoMapFileSelection`: Model title for repo map selections.
-
-
- `modelContextProtocolServers`: See [Model Context Protocol](/customize/deep-dives/mcp)
Example
@@ -540,5 +538,3 @@ Some deprecated `config.json` settings are no longer stored in config and have b
- `codeWrap`
- `displayRawMarkdown`
- `showChatScrollbar`
-
-
diff --git a/docs/reference/yaml-migration.mdx b/docs/reference/yaml-migration.mdx
index 4abcaf154..302237faf 100644
--- a/docs/reference/yaml-migration.mdx
+++ b/docs/reference/yaml-migration.mdx
@@ -1,17 +1,16 @@
---
title: "Migrating Config to YAML"
-description: "Continue's YAML configuration format provides more readable, maintainable, consistent configuration files, as well as new configuration options and removal of some old configuration options. YAML is the preferred format and will be used to integrate with future Continue products. Below is a brief guide for migration from to ."
+description: "Continue's YAML configuration format provides more readable, maintainable, consistent configuration files, as well as new configuration options and removal of some old configuration options. YAML is the preferred format and will be used to integrate with future Continue products. Below is a brief guide for migration from config.json to config.yaml."
---
See also
- [Intro to YAML](https://yaml.org/)
-- [JSON Continue Config Reference](/reference)
- [YAML Continue Config Reference](/reference)
## Create YAML file
-Create a `config.yaml` file in your Continue Global Directory (`~/.continue` on Mac, `%USERPROFILE%\.continue`) alongside your current `config.json` file. If a `config.yaml` file is present, it will be loaded instead of `config.json`.
+Create a `config.yaml` file in your Continue Global Directory (`~/.continue` on Mac, `%USERPROFILE%\.continue`) alongside your current config.json file. If a `config.yaml` file is present, it will be loaded instead of config.json.
Give your configuration a `name` and a `version`:
@@ -87,12 +86,12 @@ config.json
config.yaml
-```
+```yaml
models:
- name: GPT-4
provider: openai
model: gpt-4
- apiKey:
+ apiKey:
defaultCompletionOptions:
temperature: 0.5
maxTokens: 2000
@@ -101,7 +100,8 @@ models:
- edit
- name: My Voyage Reranker
provider: voyage
- apiKey:
+ model: rerank-2
+ apiKey:
roles:
- rerank
- name: My Starcoder
@@ -111,22 +111,25 @@ models:
- autocomplete
- name: My Ada Embedder
provider: openai
- apiKey:
+ model: text-embedding-ada-002
+ apiKey:
roles:
- embed
embedOptions:
- - maxChunkSize: 256
- - maxBatchSize: 5
+ maxChunkSize: 256
+ maxBatchSize: 5
- name: Ollama Autodetect
provider: ollama
model: AUTODETECT
- - name: My Open AI Compatible Model - Apply
+ roles:
+ - chat
+ - name: My Open AI Compatible Model
provider: openai
model: my-openai-compatible-model
apiBase: http://3.3.3.3/v1
requestOptions:
headers:
- X-Auth-Token:
+ X-Auth-Token:
roles:
- chat
- apply
@@ -159,7 +162,7 @@ config.json
config.yaml
-```
+```yaml
context:
- provider: docs
- provider: codebase
@@ -178,14 +181,16 @@ The `systemMessage` property has been replaced with a `rules` property that take
config.json
```json
-{ "systemMessage": "Always give concise responses" }
+{
+ "systemMessage": "Always give concise responses"
+}
```
**After**
config.yaml
-```
+```yaml
rules:
- Always give concise responses
```
@@ -214,7 +219,7 @@ config.json
config.yaml
-```
+```yaml
prompts:
- name: check
description: Check for mistakes in my code
@@ -239,8 +244,14 @@ config.json
```json
{
"docs": [
- { "startUrl": "https://docs.nestjs.com/", "title": "nest.js" },
- { "startUrl": "https://mysite.com/docs/", "title": "My site" }
+ {
+ "startUrl": "https://docs.nestjs.com/",
+ "title": "nest.js"
+ },
+ {
+ "startUrl": "https://mysite.com/docs/",
+ "title": "My site"
+ }
]
}
```
@@ -249,7 +260,7 @@ config.json
config.yaml
-```
+```yaml
docs:
- name: nest.js
startUrl: https://docs.nestjs.com/
@@ -279,8 +290,14 @@ config.json
"transport": {
"type": "stdio",
"command": "uvx",
- "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"],
- "env": { "KEY": "" }
+ "args": [
+ "mcp-server-sqlite",
+ "--db-path",
+ "/Users/NAME/test.db"
+ ],
+ "env": {
+ "KEY": ""
+ }
}
}
]
@@ -292,7 +309,7 @@ config.json
config.yaml
-```
+```yaml
mcpServers:
- name: My MCP Server
command: uvx
@@ -308,13 +325,11 @@ mcpServers:
## Deprecated configuration options
-Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the user settings (Gear Icon). If found in `config.json`, they will be auto-migrated to User Settings and removed from `config.json`.
+Some deprecated config.json settings are no longer stored in config and have been moved to be editable through the user settings (Gear Icon). If found in config.json, they will be auto-migrated to User Settings and removed from config.json.
-See the [JSON Config Reference](/reference) for more information on fully deprecated options.
+The following top-level fields from config.json have been deprecated and don't have a config.yaml equivalent:
-The following top-level fields from `config.json` still work when using `config.json` but have been deprecated and don't have a YAML equivalent:
-
-- Slash commands (JSON `slashCommands`)
+- Slash commands (`slashCommands`)
- top-level `requestOptions`
@@ -332,7 +347,7 @@ The following top-level fields from `config.json` still work when using `config.
- `analytics`
-The following top-level fields from `config.json` have been deprecated. Most UI-related and user-specific options will move into a settings page in the UI
+The following top-level fields from config.json have been deprecated. Most UI-related and user-specific options will move into a settings page in the UI
- `customCommands`
- `experimental`
diff --git a/docs/snippets/ModelRecommendations.jsx b/docs/snippets/ModelRecommendations.jsx
index a65e04371..a802e96b7 100644
--- a/docs/snippets/ModelRecommendations.jsx
+++ b/docs/snippets/ModelRecommendations.jsx
@@ -50,8 +50,8 @@ export const ModelRecommendations = ({ role = "all" }) => {
"[Kimi K2 (1T)](https://hub.continue.dev/openrouter/kimi-k2)",
"[gpt-oss (120B)](https://hub.continue.dev/openrouter/gpt-oss-120b)",
"[gpt-oss (20B)](https://hub.continue.dev/ollama/gpt-oss-20b)",
- "GLM 4.5 (355B)",
- "GLM 4.5 Air (106B)",
+ "[GLM 4.5 (355B)](https://hub.continue.dev/openrouter/glm-4-5)",
+ "[GLM 4.5 Air (106B)](https://hub.continue.dev/openrouter/glm-4-5-air)",
],
closed: [
"[Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus)",
@@ -83,7 +83,7 @@ export const ModelRecommendations = ({ role = "all" }) => {
],
closed: [
"[Codestral](https://hub.continue.dev/mistral/codestral)",
- "[Mercury Coder](https://hub.continue.dev/inceptionlabs/mercury-coder)",
+ "[Mercury Coder](https://hub.continue.dev/inception/mercury-coder)",
],
notes: "Closed models are slightly better than open models",
},
@@ -117,11 +117,11 @@ export const ModelRecommendations = ({ role = "all" }) => {
notes: "Open models are beginning to emerge for this model role",
},
next_edit: {
- open: ["N/A"],
+ open: ["[Instinct](https://hub.continue.dev/continuedev/instinct)"],
closed: [
- "[Mercury Coder](https://hub.continue.dev/inceptionlabs/mercury-coder)",
+ "[Mercury Coder](https://hub.continue.dev/inception/mercury-coder)",
],
- notes: "Closed models are significantly better than open models",
+ notes: "Closed models are better than open models",
},
};
diff --git a/extensions/cli/.github/workflows/respond-to-cubic-dev-ai.yml b/extensions/cli/.github/workflows/respond-to-cubic-dev-ai.yml
deleted file mode 100644
index 5d3f40c56..000000000
--- a/extensions/cli/.github/workflows/respond-to-cubic-dev-ai.yml
+++ /dev/null
@@ -1,215 +0,0 @@
-name: Respond to @continuedev Comments
-
-on:
- issue_comment:
- types: [created]
- pull_request_review_comment:
- types: [created]
-
-permissions:
- contents: write
- pull-requests: write
- issues: write
-
-jobs:
- respond-to-comment:
- # Only run on pull request comments
- if: github.event_name == 'issue_comment' && github.event.issue.pull_request
- runs-on: ubuntu-latest
-
- steps:
- - name: Check if comment contains @continuedev
- id: check-mention
- run: |
- if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
- echo "contains_mention=true" >> $GITHUB_OUTPUT
- else
- echo "contains_mention=false" >> $GITHUB_OUTPUT
- fi
-
- - name: Checkout PR branch
- if: steps.check-mention.outputs.contains_mention == 'true'
- uses: actions/checkout@v4
- with:
- token: ${{ secrets.GITHUB_TOKEN }}
- fetch-depth: 0
-
- - name: Get PR information
- if: steps.check-mention.outputs.contains_mention == 'true'
- id: pr-info
- uses: actions/github-script@v7
- with:
- script: |
- const { data: pr } = await github.rest.pulls.get({
- owner: context.repo.owner,
- repo: context.repo.repo,
- pull_number: context.issue.number
- });
-
- core.setOutput('head_ref', pr.head.ref);
- core.setOutput('head_sha', pr.head.sha);
- return pr;
-
- - name: Checkout PR branch
- if: steps.check-mention.outputs.contains_mention == 'true'
- run: |
- git checkout ${{ steps.pr-info.outputs.head_ref }}
-
- - name: Setup Node.js
- if: steps.check-mention.outputs.contains_mention == 'true'
- uses: actions/setup-node@v4
- with:
- node-version: "20"
-
- - name: Install Continue CLI globally
- if: steps.check-mention.outputs.contains_mention == 'true'
- run: npm i -g @continuedev/cli
-
- - name: Start remote session
- if: steps.check-mention.outputs.contains_mention == 'true'
- id: remote-session
- env:
- CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
- run: |
- # Create the prompt for remote session
- PROMPT="Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}:
-
- ${{ github.event.comment.body }}
-
- Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch."
-
- # Start remote session and capture JSON output
- SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }})
- echo "Raw session output: $SESSION_OUTPUT"
-
- # Extract URL from JSON output
- SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
-
- if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
- echo "Failed to extract session URL from output: $SESSION_OUTPUT"
- exit 1
- fi
-
- echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
- echo "β
Started remote session: $SESSION_URL"
-
- - name: Comment with session URL
- if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
- uses: actions/github-script@v7
- with:
- script: |
- const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
- > ${{ github.event.comment.body }}`;
-
- await github.rest.issues.createComment({
- owner: context.repo.owner,
- repo: context.repo.repo,
- issue_number: context.issue.number,
- body: commentBody
- });
-
- - name: Log session details
- if: steps.check-mention.outputs.contains_mention == 'true'
- run: |
- echo "β
Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}"
- echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
- echo "Original comment: ${{ github.event.comment.body }}"
-
- respond-to-review-comment:
- # Only run on pull request review comments
- if: github.event_name == 'pull_request_review_comment'
- runs-on: ubuntu-latest
-
- steps:
- - name: Check if comment contains @continuedev
- id: check-mention
- run: |
- if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
- echo "contains_mention=true" >> $GITHUB_OUTPUT
- else
- echo "contains_mention=false" >> $GITHUB_OUTPUT
- fi
-
- - name: Checkout PR branch
- if: steps.check-mention.outputs.contains_mention == 'true'
- uses: actions/checkout@v4
- with:
- token: ${{ secrets.GITHUB_TOKEN }}
- fetch-depth: 0
- ref: ${{ github.event.pull_request.head.ref }}
-
- - name: Setup Node.js
- if: steps.check-mention.outputs.contains_mention == 'true'
- uses: actions/setup-node@v4
- with:
- node-version: "20"
-
- - name: Install Continue CLI globally
- if: steps.check-mention.outputs.contains_mention == 'true'
- run: npm i -g @continuedev/cli
-
- - name: Start remote session
- if: steps.check-mention.outputs.contains_mention == 'true'
- id: remote-session
- env:
- CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
- run: |
- # Create a temporary file for the prompt to handle special characters and newlines properly
- cat > /tmp/prompt.txt << 'PROMPT_EOF'
- Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}:
-
- **File:** ${{ github.event.comment.path }}
- **Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
- **Comment:** ${{ github.event.comment.body }}
-
- Please analyze the specific file and line mentioned, understand the review feedback, implement the necessary changes, and commit them to this branch.
- PROMPT_EOF
-
- # Debug output
- echo "PROMPT content:"
- cat /tmp/prompt.txt
-
- # Start remote session and capture JSON output
- echo "Starting cn with prompt..."
- SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --branch ${{ github.event.pull_request.head.ref }})
- echo "Raw session output: $SESSION_OUTPUT"
-
- # Extract URL from JSON output
- SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
-
- if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
- echo "Failed to extract session URL from output: $SESSION_OUTPUT"
- exit 1
- fi
-
- echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
- echo "β
Started remote session: $SESSION_URL"
-
- - name: Comment with session URL
- if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
- uses: actions/github-script@v7
- with:
- script: |
- const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
- > ${{ github.event.comment.body }}`;
-
- const commentParams = {
- owner: context.repo.owner,
- repo: context.repo.repo,
- pull_number: ${{ github.event.pull_request.number }},
- body: commentBody,
- commit_id: '${{ github.event.pull_request.head.sha }}',
- path: '${{ github.event.comment.path }}',
- in_reply_to: ${{ github.event.comment.id }}
- };
-
- await github.rest.pulls.createReviewComment(commentParams);
-
- - name: Log session details
- if: steps.check-mention.outputs.contains_mention == 'true'
- run: |
- echo "β
Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}"
- echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
- echo "File: ${{ github.event.comment.path }}"
- echo "Line: ${{ github.event.comment.line }}"
- echo "Original comment: ${{ github.event.comment.body }}"
diff --git a/extensions/cli/build.mjs b/extensions/cli/build.mjs
index f5f20778c..11515b20b 100644
--- a/extensions/cli/build.mjs
+++ b/extensions/cli/build.mjs
@@ -1,10 +1,14 @@
#!/usr/bin/env node
import * as esbuild from "esbuild";
-import { chmodSync, writeFileSync } from "fs";
+import { chmodSync, copyFileSync, writeFileSync } from "fs";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
+// Parse command line arguments
+const args = process.argv.slice(2);
+const noMinify = args.includes("--no-minify");
+
const __dirname = dirname(fileURLToPath(import.meta.url));
// List of packages to mark as external (ONLY native modules that cannot be bundled)
@@ -13,6 +17,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
const external = [
"@sentry/profiling-node", // Contains native profiler bindings (optional)
"fsevents", // macOS native file watcher (optional dependency)
+ "./xhr-sync-worker.js", // JSDOM worker file that needs to be copied separately
];
console.log("Building CLI with esbuild...");
@@ -38,7 +43,7 @@ try {
outfile: "dist/index.js",
external,
sourcemap: true,
- minify: true, // Minify for smaller bundle size
+ minify: !noMinify, // Use --no-minify flag to control minification
metafile: true,
plugins: [optionalDevtoolsPlugin],
@@ -68,20 +73,40 @@ try {
__dirname,
"../../packages/llm-info/dist/index.js",
),
+ "@continuedev/terminal-security": resolve(
+ __dirname,
+ "../../packages/terminal-security/dist/index.js",
+ ),
},
// Add banner to create require for CommonJS packages
banner: {
- js: `import { createRequire } from 'module';
-const require = createRequire(import.meta.url);`,
+ js: `import { createRequire as __createRequire } from 'module';
+const require = __createRequire(import.meta.url);`,
},
});
// Write metafile for analysis
writeFileSync("dist/meta.json", JSON.stringify(result.metafile, null, 2));
- // Create wrapper script with shebang
- writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');");
+ // Create wrapper script with shebang that explicitly runs the CLI
+ // Note: We must call runCli(); a plain dynamic import will not execute the CLI.
+ writeFileSync(
+ "dist/cn.js",
+ "#!/usr/bin/env node\nimport { runCli } from './index.js';\nawait runCli();\n",
+ );
+ // Copy worker files needed by JSDOM
+ const workerSource = resolve(
+ __dirname,
+ "node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js",
+ );
+ const workerDest = resolve(__dirname, "dist/xhr-sync-worker.js");
+ try {
+ copyFileSync(workerSource, workerDest);
+ console.log("β Copied xhr-sync-worker.js");
+ } catch (error) {
+ console.warn("Warning: Could not copy xhr-sync-worker.js:", error.message);
+ }
// Make the wrapper script executable
chmodSync("dist/cn.js", 0o755);
diff --git a/extensions/cli/docs/storage-sync.md b/extensions/cli/docs/storage-sync.md
new file mode 100644
index 000000000..fd42e674c
--- /dev/null
+++ b/extensions/cli/docs/storage-sync.md
@@ -0,0 +1,55 @@
+# Storage Sync Flow for `cn serve`
+
+## Overview
+
+The `--id ` flag enables the `cn serve` command to periodically persist session state to an external Continue-managed storage bucket. On startup, the CLI exchanges the provided `storageId` for two pre-signed S3 URLs - one for `session.json` and one for `diff.txt` - and then pushes fresh copies of those files every 30 seconds.
+
+This document captures the responsibilities for both the CLI and backend components so we can iterate on the feature together.
+
+## CLI Responsibilities
+
+- **Flag plumbing**: When `cn serve` is invoked with `--id `, the CLI treats that value as an opaque identifier.
+- **API key auth**: The CLI attaches the user-level Continue API key (same mechanism we already use for other authenticated requests) to backend calls.
+- **Presign handshake**:
+ 1. On startup, issue `POST https://api.continue.dev/agents/storage/presigned-url` with JSON payload `{ "storageId": "" }`.
+ 2. Expect a response payload containing two pre-signed `PUT` URLs and their target object keys:
+ ```json
+ {
+ "session": {
+ "key": "sessions//session.json",
+ "putUrl": "https:///..."
+ },
+ "diff": {
+ "key": "sessions//diff.txt",
+ "putUrl": "https:///..."
+ }
+ }
+ ```
+ 3. If the call fails, log and continue without remote storage (no retries yet).
+- **Periodic uploads**:
+ - Every 30 seconds (configurable later), serialize the in-memory session to `session.json` and fetch the `/diff` payload to produce `diff.txt`.
+ - Upload both artifacts using their respective `PUT` URLs. For now we overwrite the same objects each cycle.
+ - Errors should be logged but non-fatal; the server keeps running.
+ - If the repo check fails (no git repo or missing `main`), `diff.txt` uploads an empty string and we log the condition once for debugging.
+
+## Backend Responsibilities
+
+- **Endpoint surface**: `POST /agents/storage/presigned-url` accepts a JSON body `{ "storageId": string }`.
+- **Authentication**: Leverage the caller's Continue API key (the request arrives with the standard `Authorization: Bearer ` header). Apply normal auth/tenant validation so users can only request URLs tied to their account/org.
+- **URL issuance**:
+ - Resolve `storageId` into the desired S3 prefix (e.g., `sessions///`).
+ - Generate two short-lived pre-signed `PUT` URLs: one for `session.json`, one for `diff.txt`.
+ - Return both URLs and their keys in the response payload described above.
+- **Expiration**: The initial implementation can hand out URLs with a generous TTL (e.g., 60 minutes). Later we will add CLI-side refresh logic before expiry.
+
+## Open Questions & Future Enhancements
+
+- **URL refresh**: When the presigned URLs expire we currently have no refresh cycle. We'd need either a renewal endpoint or to re-call the existing endpoint on failure.
+- **Upload cadence**: The 30-second interval is hard-coded for now. Consider making it configurable in both CLI and backend policies.
+- **Error telemetry**: Decide if repeated upload failures should trip analytics or circuit breakers.
+- **Diff source**: `diff.txt` currently mirrors the `/diff` endpoint response. Confirm backend expectations for format and size limits.
+- **Security**: We might want to sign responses or enforce stricter scope on `storageId` mapping (e.g., require both org + storageId and validate ownership).
+
+---
+
+This document should evolve alongside implementation details; update it whenever the API contract or client behavior changes.
diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json
index 6da2ba6db..0a965615f 100644
--- a/extensions/cli/package-lock.json
+++ b/extensions/cli/package-lock.json
@@ -9,7 +9,9 @@
"version": "0.0.0-dev",
"license": "Apache-2.0",
"dependencies": {
- "@sentry/profiling-node": "^9.43.0"
+ "@sentry/profiling-node": "^9.43.0",
+ "fdir": "^6.4.2",
+ "fzf": "^0.5.2"
},
"bin": {
"cn": "dist/cn.js"
@@ -18,6 +20,7 @@
"@continuedev/config-yaml": "file:../../packages/config-yaml",
"@continuedev/openai-adapters": "file:../../packages/openai-adapters",
"@continuedev/sdk": "^0.0.13",
+ "@continuedev/terminal-security": "file:../../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.17.2",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0",
@@ -42,7 +45,6 @@
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
"@types/react": "^19.1.8",
- "@types/readline-sync": "^1.4.8",
"@types/shell-quote": "^1.7.5",
"@types/supertest": "^6.0.3",
"@types/turndown": "^5.0.5",
@@ -52,6 +54,7 @@
"@vitest/ui": "^3.2.4",
"@workos-inc/node": "^7.45.0",
"chalk": "^5.4.1",
+ "clipboardy": "^4.0.0",
"commander": "^14.0.0",
"conventional-changelog-conventionalcommits": "^9.1.0",
"core": "file:../../core",
@@ -84,8 +87,8 @@
"open": "^10.1.0",
"posthog-node": "^5.6.0",
"prettier": "^3.6.2",
+ "prettier-plugin-tailwindcss": "^0.6.14",
"react": "^19.1.0",
- "readline-sync": "^1.4.10",
"semantic-release": "^24.2.7",
"shell-quote": "^1.8.3",
"supertest": "^7.1.3",
@@ -98,6 +101,14 @@
"vitest": "^3.2.4",
"winston": "^3.17.0",
"yaml": "^2.8.0"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "^0.33.5",
+ "@img/sharp-darwin-x64": "^0.33.5",
+ "@img/sharp-linux-arm": "^0.33.5",
+ "@img/sharp-linux-arm64": "^0.33.5",
+ "@img/sharp-linux-x64": "^0.33.5",
+ "@img/sharp-win32-x64": "^0.33.5"
}
},
"../../core": {
@@ -106,6 +117,7 @@
"dev": true,
"license": "Apache-2.0",
"dependencies": {
+ "@anthropic-ai/sdk": "^0.62.0",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
"@aws-sdk/credential-providers": "^3.778.0",
@@ -114,6 +126,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
+ "@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@@ -164,6 +177,7 @@
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",
"request": "^2.88.2",
+ "shell-quote": "^1.8.3",
"socket.io-client": "^4.7.3",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
@@ -198,6 +212,7 @@
"@types/pg": "^8.11.6",
"@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
+ "@types/shell-quote": "^1.7.5",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
@@ -222,11 +237,11 @@
},
"../../packages/config-yaml": {
"name": "@continuedev/config-yaml",
- "version": "1.0.96",
+ "version": "1.23.0",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
- "@continuedev/config-types": "file:../config-types",
+ "@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},
@@ -250,15 +265,16 @@
},
"../../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
- "version": "1.5.1",
+ "version": "1.15.0",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
+ "@anthropic-ai/sdk": "^0.62.0",
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.14",
- "@continuedev/config-yaml": "^1.8.0",
- "@continuedev/fetch": "^1.0.16",
+ "@continuedev/config-yaml": "^1.14.0",
+ "@continuedev/fetch": "^1.1.0",
"dotenv": "^16.5.0",
"google-auth-library": "^10.1.0",
"json-schema": "^0.4.0",
@@ -285,6 +301,21 @@
"vitest": "^3.2.4"
}
},
+ "../../packages/terminal-security": {
+ "name": "@continuedev/terminal-security",
+ "version": "1.0.0",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "shell-quote": "^1.8.1"
+ },
+ "devDependencies": {
+ "@types/node": "^20.11.19",
+ "@types/shell-quote": "^1.7.5",
+ "typescript": "^5.5.2",
+ "vitest": "^3.2.4"
+ }
+ },
"node_modules/@alcalzone/ansi-tokenize": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.2.0.tgz",
@@ -377,6 +408,10 @@
"openai": "^4.96.2"
}
},
+ "node_modules/@continuedev/terminal-security": {
+ "resolved": "../../packages/terminal-security",
+ "link": true
+ },
"node_modules/@cspotcode/source-map-support": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
@@ -1256,6 +1291,215 @@
"url": "https://github.com/sponsors/nzakas"
}
},
+ "node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz",
+ "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz",
+ "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz",
+ "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz",
+ "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz",
+ "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz",
+ "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz",
+ "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz",
+ "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.0.5"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz",
+ "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz",
+ "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.0.4"
+ }
+ },
+ "node_modules/@img/sharp-win32-x64": {
+ "version": "0.33.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz",
+ "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
"node_modules/@isaacs/balanced-match": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz",
@@ -5163,13 +5407,6 @@
"csstype": "^3.0.2"
}
},
- "node_modules/@types/readline-sync": {
- "version": "1.4.8",
- "resolved": "https://registry.npmjs.org/@types/readline-sync/-/readline-sync-1.4.8.tgz",
- "integrity": "sha512-BL7xOf0yKLA6baAX6MMOnYkoflUyj/c7y3pqMRfU0va7XlwHAOTOIo4x55P/qLfMsuaYdJJKubToLqRVmRtRZA==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/send": {
"version": "0.17.5",
"resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.5.tgz",
@@ -6988,6 +7225,155 @@
"url": "https://github.com/chalk/slice-ansi?sponsor=1"
}
},
+ "node_modules/clipboardy": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/clipboardy/-/clipboardy-4.0.0.tgz",
+ "integrity": "sha512-5mOlNS0mhX0707P2I0aZ2V/cmHUEO/fL7VFLqszkhUsxt7RwnmrInf/eEQKlf5GzvYeHIjT+Ov1HRfNmymlG0w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "execa": "^8.0.1",
+ "is-wsl": "^3.1.0",
+ "is64bit": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/clipboardy/node_modules/execa": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz",
+ "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cross-spawn": "^7.0.3",
+ "get-stream": "^8.0.1",
+ "human-signals": "^5.0.0",
+ "is-stream": "^3.0.0",
+ "merge-stream": "^2.0.0",
+ "npm-run-path": "^5.1.0",
+ "onetime": "^6.0.0",
+ "signal-exit": "^4.1.0",
+ "strip-final-newline": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=16.17"
+ },
+ "funding": {
+ "url": "https://github.com/sindresorhus/execa?sponsor=1"
+ }
+ },
+ "node_modules/clipboardy/node_modules/get-stream": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz",
+ "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/clipboardy/node_modules/human-signals": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz",
+ "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=16.17.0"
+ }
+ },
+ "node_modules/clipboardy/node_modules/is-stream": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz",
+ "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/clipboardy/node_modules/mimic-fn": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz",
+ "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/clipboardy/node_modules/npm-run-path": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz",
+ "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^4.0.0"
+ },
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/clipboardy/node_modules/onetime": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz",
+ "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "mimic-fn": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/clipboardy/node_modules/path-key": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz",
+ "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/clipboardy/node_modules/strip-final-newline": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz",
+ "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/cliui": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
@@ -9087,6 +9473,23 @@
"reusify": "^1.0.4"
}
},
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
"node_modules/fecha": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",
@@ -9515,6 +9918,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/fzf": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/fzf/-/fzf-0.5.2.tgz",
+ "integrity": "sha512-Tt4kuxLXFKHy8KT40zwsUPUkg1CrsgY25FxA2U/j/0WgEDCk3ddc/zLTCCcbSHX9FcKtLuVaDGtGE/STWC+j3Q==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
@@ -11044,6 +11453,22 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/is64bit": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/is64bit/-/is64bit-2.0.0.tgz",
+ "integrity": "sha512-jv+8jaWCl0g2lSBkNSVXdzfBA0npK1HGC2KtWM9FumFRoGS94g3NbCCLVnCYHLjp4GrW2KZeeSTMo5ddtznmGw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "system-architecture": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
@@ -11654,6 +12079,19 @@
"node": ">=8.6"
}
},
+ "node_modules/micromatch/node_modules/picomatch": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
+ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
"node_modules/mime": {
"version": "4.0.7",
"resolved": "https://registry.npmjs.org/mime/-/mime-4.0.7.tgz",
@@ -15330,13 +15768,13 @@
"license": "ISC"
},
"node_modules/picomatch": {
- "version": "2.3.1",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
- "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
- "dev": true,
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
+ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
+ "devOptional": true,
"license": "MIT",
"engines": {
- "node": ">=8.6"
+ "node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
@@ -15566,6 +16004,93 @@
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
+ "node_modules/prettier-plugin-tailwindcss": {
+ "version": "0.6.14",
+ "resolved": "https://registry.npmjs.org/prettier-plugin-tailwindcss/-/prettier-plugin-tailwindcss-0.6.14.tgz",
+ "integrity": "sha512-pi2e/+ZygeIqntN+vC573BcW5Cve8zUB0SSAGxqpB4f96boZF4M3phPVoOFCeypwkpRYdi7+jQ5YJJUwrkGUAg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.21.3"
+ },
+ "peerDependencies": {
+ "@ianvs/prettier-plugin-sort-imports": "*",
+ "@prettier/plugin-hermes": "*",
+ "@prettier/plugin-oxc": "*",
+ "@prettier/plugin-pug": "*",
+ "@shopify/prettier-plugin-liquid": "*",
+ "@trivago/prettier-plugin-sort-imports": "*",
+ "@zackad/prettier-plugin-twig": "*",
+ "prettier": "^3.0",
+ "prettier-plugin-astro": "*",
+ "prettier-plugin-css-order": "*",
+ "prettier-plugin-import-sort": "*",
+ "prettier-plugin-jsdoc": "*",
+ "prettier-plugin-marko": "*",
+ "prettier-plugin-multiline-arrays": "*",
+ "prettier-plugin-organize-attributes": "*",
+ "prettier-plugin-organize-imports": "*",
+ "prettier-plugin-sort-imports": "*",
+ "prettier-plugin-style-order": "*",
+ "prettier-plugin-svelte": "*"
+ },
+ "peerDependenciesMeta": {
+ "@ianvs/prettier-plugin-sort-imports": {
+ "optional": true
+ },
+ "@prettier/plugin-hermes": {
+ "optional": true
+ },
+ "@prettier/plugin-oxc": {
+ "optional": true
+ },
+ "@prettier/plugin-pug": {
+ "optional": true
+ },
+ "@shopify/prettier-plugin-liquid": {
+ "optional": true
+ },
+ "@trivago/prettier-plugin-sort-imports": {
+ "optional": true
+ },
+ "@zackad/prettier-plugin-twig": {
+ "optional": true
+ },
+ "prettier-plugin-astro": {
+ "optional": true
+ },
+ "prettier-plugin-css-order": {
+ "optional": true
+ },
+ "prettier-plugin-import-sort": {
+ "optional": true
+ },
+ "prettier-plugin-jsdoc": {
+ "optional": true
+ },
+ "prettier-plugin-marko": {
+ "optional": true
+ },
+ "prettier-plugin-multiline-arrays": {
+ "optional": true
+ },
+ "prettier-plugin-organize-attributes": {
+ "optional": true
+ },
+ "prettier-plugin-organize-imports": {
+ "optional": true
+ },
+ "prettier-plugin-sort-imports": {
+ "optional": true
+ },
+ "prettier-plugin-style-order": {
+ "optional": true
+ },
+ "prettier-plugin-svelte": {
+ "optional": true
+ }
+ }
+ },
"node_modules/pretty-format": {
"version": "27.5.1",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
@@ -15916,16 +16441,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/readline-sync": {
- "version": "1.4.10",
- "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz",
- "integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 0.8.0"
- }
- },
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -17449,6 +17964,19 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/system-architecture": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/system-architecture/-/system-architecture-0.1.0.tgz",
+ "integrity": "sha512-ulAk51I9UVUyJgxlv9M6lFot2WP3e7t8Kz9+IS6D4rVba1tR9kON+Ey69f+1R4Q8cd45Lod6a4IcJIxnzGc/zA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/temp-dir": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-3.0.0.tgz",
@@ -17599,37 +18127,6 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
- "node_modules/tinyglobby/node_modules/fdir": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
- "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12.0.0"
- },
- "peerDependencies": {
- "picomatch": "^3 || ^4"
- },
- "peerDependenciesMeta": {
- "picomatch": {
- "optional": true
- }
- }
- },
- "node_modules/tinyglobby/node_modules/picomatch": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
- "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/jonschlinkert"
- }
- },
"node_modules/tinygradient": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/tinygradient/-/tinygradient-1.1.5.tgz",
@@ -18340,37 +18837,6 @@
"url": "https://opencollective.com/vitest"
}
},
- "node_modules/vite/node_modules/fdir": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
- "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12.0.0"
- },
- "peerDependencies": {
- "picomatch": "^3 || ^4"
- },
- "peerDependenciesMeta": {
- "picomatch": {
- "optional": true
- }
- }
- },
- "node_modules/vite/node_modules/picomatch": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
- "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/jonschlinkert"
- }
- },
"node_modules/vitest": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz",
@@ -18444,19 +18910,6 @@
}
}
},
- "node_modules/vitest/node_modules/picomatch": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
- "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/jonschlinkert"
- }
- },
"node_modules/w3c-xmlserializer": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
diff --git a/extensions/cli/package.json b/extensions/cli/package.json
index bdc480e60..4932efa40 100644
--- a/extensions/cli/package.json
+++ b/extensions/cli/package.json
@@ -15,7 +15,7 @@
"test:e2e": "vitest run --config vitest.e2e.config.ts",
"test:smoke": "node smoke-test.mjs",
"build:tsc": "tsc -p tsconfig.build.json",
- "build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && npm run build && cd ../extensions/cli && npm i",
+ "build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../terminal-security && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && npm run build && cd ../extensions/cli && npm i",
"build:validate": "node validate-aliases.mjs",
"build:bundle": "node build.mjs",
"build": "npm run build:validate && npm run build:bundle",
@@ -37,19 +37,22 @@
"license": "Apache-2.0",
"repository": {
"type": "git",
- "url": "https://github.com/continuedev/cli.git"
+ "url": "https://github.com/continuedev/continue.git"
},
"bugs": {
"url": "https://github.com/continuedev/continue/issues"
},
"homepage": "https://continue.dev",
"dependencies": {
- "@sentry/profiling-node": "^9.43.0"
+ "@sentry/profiling-node": "^9.43.0",
+ "fdir": "^6.4.2",
+ "fzf": "^0.5.2"
},
"devDependencies": {
"@continuedev/config-yaml": "file:../../packages/config-yaml",
"@continuedev/openai-adapters": "file:../../packages/openai-adapters",
"@continuedev/sdk": "^0.0.13",
+ "@continuedev/terminal-security": "file:../../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.17.2",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0",
@@ -59,79 +62,87 @@
"@opentelemetry/resources": "^2.0.1",
"@opentelemetry/sdk-node": "^0.203.0",
"@opentelemetry/semantic-conventions": "^1.36.0",
- "@sentry/node": "^9.43.0",
- "@types/express": "^5.0.3",
- "@types/react": "^19.1.8",
- "@types/turndown": "^5.0.5",
- "@workos-inc/node": "^7.45.0",
- "chalk": "^5.4.1",
- "commander": "^14.0.0",
- "core": "file:../../core",
- "date-fns": "^4.1.0",
- "diff": "^7.0.0",
- "dotenv": "^16.5.0",
- "express": "^5.1.0",
- "glob": "^11.0.3",
- "gpt-tokenizer": "^3.0.1",
- "gradient-string": "^3.0.0",
- "ignore": "^7.0.5",
- "ignore-walk": "^7.0.0",
- "ink": "^6.1.0",
- "jszip": "^3.10.1",
- "lowlight": "^3.3.0",
- "minimatch": "^10.0.3",
- "node-fetch": "^3.3.2",
- "node-machine-id": "^1.1.12",
- "open": "^10.1.0",
- "posthog-node": "^5.6.0",
- "react": "^19.1.0",
- "readline-sync": "^1.4.10",
- "shell-quote": "^1.8.3",
- "swr": "^2.3.4",
- "turndown": "^7.2.0",
- "typescript": "^5.8.3",
- "uuid": "^9.0.1",
- "winston": "^3.17.0",
- "yaml": "^2.8.0",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^11.0.3",
"@semantic-release/npm": "^12.0.2",
+ "@sentry/node": "^9.43.0",
"@testing-library/react": "^16.3.0",
"@types/date-fns": "^2.5.3",
"@types/diff": "^7.0.2",
+ "@types/express": "^5.0.3",
"@types/glob": "^8.1.0",
"@types/ignore-walk": "^4.0.3",
"@types/ink-testing-library": "^1.0.4",
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
- "@types/readline-sync": "^1.4.8",
+ "@types/react": "^19.1.8",
"@types/shell-quote": "^1.7.5",
"@types/supertest": "^6.0.3",
+ "@types/turndown": "^5.0.5",
"@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^8.39.0",
"@typescript-eslint/parser": "^8.39.0",
"@vitest/ui": "^3.2.4",
+ "@workos-inc/node": "^7.45.0",
+ "chalk": "^5.4.1",
+ "commander": "^14.0.0",
"conventional-changelog-conventionalcommits": "^9.1.0",
+ "core": "file:../../core",
"cross-env": "^7.0.3",
+ "date-fns": "^4.1.0",
+ "diff": "^7.0.0",
+ "dotenv": "^16.5.0",
"esbuild": "^0.25.9",
"eslint": "^9.32.0",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-unused-imports": "^4.1.4",
"execa": "^9.6.0",
+ "clipboardy": "^4.0.0",
+ "express": "^5.1.0",
+ "glob": "^11.0.3",
+ "gpt-tokenizer": "^3.0.1",
+ "gradient-string": "^3.0.0",
"happy-dom": "^18.0.1",
+ "ignore": "^7.0.5",
+ "ignore-walk": "^7.0.0",
+ "ink": "^6.1.0",
"ink-testing-library": "^4.0.0",
"jsdom": "^26.1.0",
+ "jszip": "^3.10.1",
+ "lowlight": "^3.3.0",
+ "minimatch": "^10.0.3",
"nock": "^14.0.5",
+ "node-fetch": "^3.3.2",
+ "node-machine-id": "^1.1.12",
+ "open": "^10.1.0",
+ "posthog-node": "^5.6.0",
"prettier": "^3.6.2",
+ "prettier-plugin-tailwindcss": "^0.6.14",
+ "react": "^19.1.0",
"semantic-release": "^24.2.7",
+ "shell-quote": "^1.8.3",
"supertest": "^7.1.3",
+ "swr": "^2.3.4",
"ts-node": "^10.9.2",
"tsx": "^4.20.3",
- "vitest": "^3.2.4"
+ "turndown": "^7.2.0",
+ "typescript": "^5.8.3",
+ "uuid": "^9.0.1",
+ "vitest": "^3.2.4",
+ "winston": "^3.17.0",
+ "yaml": "^2.8.0"
},
"engine": {
"node": ">=18"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "^0.33.5",
+ "@img/sharp-darwin-x64": "^0.33.5",
+ "@img/sharp-linux-arm": "^0.33.5",
+ "@img/sharp-linux-arm64": "^0.33.5",
+ "@img/sharp-linux-x64": "^0.33.5",
+ "@img/sharp-win32-x64": "^0.33.5"
}
}
diff --git a/extensions/cli/spec/ctrl-c-behavior.md b/extensions/cli/spec/ctrl-c-behavior.md
new file mode 100644
index 000000000..9d11f26ab
--- /dev/null
+++ b/extensions/cli/spec/ctrl-c-behavior.md
@@ -0,0 +1,32 @@
+# Ctrl+C Exit Behavior
+
+## Overview
+
+Ctrl+C operates on two levels:
+
+1. **Menus/Selectors**: Immediate cancellation and return to previous state
+2. **Main Application**: Two-stage exit requiring double Ctrl+C within 1 second
+
+## Two-Stage Exit (Main Application)
+
+### First Ctrl+C
+
+- Shows temporary status message "ctrl+c to exit" in bottom-left status bar
+- Message automatically disappears after 1 second
+- Clears any text in the input field (if focused)
+- Does **not** exit the application
+
+### Second Ctrl+C (within 1 second)
+
+- Exits the application immediately
+- Performs graceful shutdown
+
+### Second Ctrl+C (after 1 second)
+
+- Treated as a new "first Ctrl+C"
+- Shows exit message again
+- User must press Ctrl+C twice within 1 second window to actually exit
+
+## Menu/Selector Cancellation
+
+Ctrl+C immediately cancels and returns to the previous state in all interactive menus and selectors.
diff --git a/extensions/cli/spec/modes.md b/extensions/cli/spec/modes.md
index 7296a19eb..49838a3b3 100644
--- a/extensions/cli/spec/modes.md
+++ b/extensions/cli/spec/modes.md
@@ -57,8 +57,7 @@ Users can switch modes during chat sessions using:
Modes are implemented through the permission system:
-- **ModeService**: Singleton service managing the current mode and initialization
-- **ToolPermissionService**: Extended to support mode-specific policies with highest priority
+- **ToolPermissionService**: Rectifies current mode and tool policies
- **ModeIndicator**: UI component showing current mode (hidden for normal mode)
- **Keyboard shortcuts**: Shift+Tab cycles through modes instantly
- **Backward compatibility**: Existing `--readonly` flag maps to plan mode
diff --git a/extensions/cli/spec/onboarding.md b/extensions/cli/spec/onboarding.md
index 523b9067e..58c651322 100644
--- a/extensions/cli/spec/onboarding.md
+++ b/extensions/cli/spec/onboarding.md
@@ -7,7 +7,8 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb
**The onboarding flow runs when the user hasn't completed onboarding before, regardless of whether they have a valid config.yaml file.**
1. If the --config flag is provided, load this config
-2. Otherwise, we will present the user with two options:
+2. If the CONTINUE_USE_BEDROCK environment variable is set to "1", automatically use AWS Bedrock configuration and skip interactive prompts
+3. Present the user with available options:
- Log in with Continue: log them in, which will automatically create their assistant and then we can load the first assistant from the first org
- Enter your Anthropic API key: let them enter the key, and then either create a ~/.continue/config.yaml with the following contents OR update the existing config.yaml to add the model
@@ -23,7 +24,26 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb
ANTHROPIC_API_KEY:
```
-When something in the onboarding flow is done automatically, we should tell the user what happened.
+ When CONTINUE_USE_BEDROCK=1 is detected, it will use AWS Bedrock configuration. The user must have AWS credentials configured through the standard AWS credential chain (AWS CLI, environment variables, IAM roles, etc.).
+
+When something in the onboarding flow is done automatically, we should tell the user what happened. For example, when CONTINUE_USE_BEDROCK=1 is detected, the CLI displays: "β Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)"
+
+### AWS Bedrock Environment Variable
+
+Users can bypass the interactive onboarding menu by setting the `CONTINUE_USE_BEDROCK` environment variable to "1":
+
+```bash
+export CONTINUE_USE_BEDROCK=1
+cn
+```
+
+This will:
+
+- Skip the interactive onboarding prompts
+- Automatically configure the CLI to use AWS Bedrock
+- Require that AWS credentials are already configured through the standard AWS credential chain
+- Display a confirmation message to the user
+- Mark onboarding as completed
## Normal flow
diff --git a/extensions/cli/spec/otlp-metrics.md b/extensions/cli/spec/otlp-metrics.md
index 744709b10..f1398558f 100644
--- a/extensions/cli/spec/otlp-metrics.md
+++ b/extensions/cli/spec/otlp-metrics.md
@@ -51,7 +51,7 @@ All metrics and events share these standard attributes:
## Core Metrics
-### β
`continue.cli.session.count`
+### β
`continue_cli_session_count`
**Type:** Counter
**Unit:** `count`
@@ -65,7 +65,7 @@ All metrics and events share these standard attributes:
---
-### β
`continue.cli.lines_of_code.count`
+### β
`continue_cli_lines_of_code_count`
**Type:** Counter
**Unit:** `count`
@@ -80,7 +80,7 @@ All metrics and events share these standard attributes:
---
-### β
`continue.cli.pull_request.count`
+### β
`continue_cli_pull_request_count`
**Type:** Counter
**Unit:** `count`
@@ -94,7 +94,7 @@ All metrics and events share these standard attributes:
---
-### β
`continue.cli.commit.count`
+### β
`continue_cli_commit_count`
**Type:** Counter
**Unit:** `count`
@@ -108,7 +108,7 @@ All metrics and events share these standard attributes:
---
-### β
`continue.cli.cost.usage`
+### β
`continue_cli_cost_usage`
**Type:** Counter
**Unit:** `USD`
@@ -123,7 +123,7 @@ All metrics and events share these standard attributes:
---
-### β
`continue.cli.token.usage`
+### β
`continue_cli_token_usage`
**Type:** Counter
**Unit:** `tokens`
@@ -139,7 +139,7 @@ All metrics and events share these standard attributes:
---
-### β `continue.cli.code_edit_tool.decision`
+### β `continue_cli_code_edit_tool_decision`
**Type:** Counter
**Unit:** `count`
@@ -156,7 +156,7 @@ All metrics and events share these standard attributes:
---
-### β
`continue.cli.active_time.total`
+### β
`continue_cli_active_time_total`
**Type:** Counter
**Unit:** `s`
@@ -172,7 +172,7 @@ All metrics and events share these standard attributes:
### β
User Prompt Event
-**Event Name:** `continue.cli.user_prompt`
+**Event Name:** `continue_cli_user_prompt`
**Attributes:**
@@ -188,7 +188,7 @@ All metrics and events share these standard attributes:
### β
Tool Result Event
-**Event Name:** `continue.cli.tool_result`
+**Event Name:** `continue_cli_tool_result`
**Attributes:**
@@ -209,7 +209,7 @@ All metrics and events share these standard attributes:
### β
API Request Event
-**Event Name:** `continue.cli.api_request`
+**Event Name:** `continue_cli_api_request`
**Attributes:**
@@ -232,7 +232,7 @@ These metrics are unique to Continue CLI and provide additional insights without
### Authentication Metrics
-#### β
`continue.cli.auth.attempts`
+#### β
`continue_cli_auth_attempts`
**Type:** Counter
**Unit:** `{attempt}`
@@ -248,7 +248,7 @@ These metrics are unique to Continue CLI and provide additional insights without
### MCP Integration Metrics
-#### β `continue.cli.mcp.connections`
+#### β `continue_cli_mcp_connections`
**Type:** Gauge
**Unit:** `{connection}`
@@ -264,7 +264,7 @@ These metrics are unique to Continue CLI and provide additional insights without
### Performance Metrics
-#### β `continue.cli.startup.time`
+#### β `continue_cli_startup_time`
**Type:** Histogram
**Unit:** `ms`
@@ -278,7 +278,7 @@ These metrics are unique to Continue CLI and provide additional insights without
**Implementation:** Track in `src/index.ts` and `src/commands/chat.ts`
-#### β
`continue.cli.response_time`
+#### β
`continue_cli_response_time`
**Type:** Histogram
**Unit:** `ms`
@@ -297,7 +297,7 @@ These metrics are unique to Continue CLI and provide additional insights without
### Migration from Claude Code Dashboards
-The core metrics (`session.count`, `lines_of_code.count`, `token.usage`, `cost.usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code.*` to `continue.cli.*`.
+The core metrics (`session_count`, `lines_of_code_count`, `token_usage`, `cost_usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code_*` to `continue_cli_*`.
### Privacy Considerations
@@ -337,6 +337,6 @@ All metrics should include these resource attributes:
**Missing implementations:**
-- `continue.cli.code_edit_tool.decision` - requires user confirmation UI
-- `continue.cli.mcp.connections` - needs MCP service monitoring
-- `continue.cli.startup.time` - needs startup time tracking
+- `continue_cli_code_edit_tool_decision` - requires user confirmation UI
+- `continue_cli_mcp_connections` - needs MCP service monitoring
+- `continue_cli_startup_time` - needs startup time tracking
diff --git a/extensions/cli/spec/shell-mode.md b/extensions/cli/spec/shell-mode.md
new file mode 100644
index 000000000..06ad477e9
--- /dev/null
+++ b/extensions/cli/spec/shell-mode.md
@@ -0,0 +1,69 @@
+Shell Mode (CLI TUI)
+
+Overview
+
+- Shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!).
+- It is intended for quick terminal command execution without leaving the TUI.
+
+Activation
+
+- Shell mode is activated when the current input (trimmed) starts with !
+ - Example: "!git status" or " !ls -la" both activate Shell mode.
+- Visual indicator:
+ - Input border color changes to yellow.
+ - The input prompt indicator changes to a yellow "$".
+ - The input placeholder includes "! for shell mode".
+
+Deactivation / Exiting Shell Mode
+
+- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result.
+- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode.
+- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior.
+
+Interaction with other input helpers
+
+- When in shell mode (input starts with !):
+ - "@" file search suggestions are disabled.
+ - "/" slash command UI is disabled.
+- When in slash command mode (input starts with /):
+ - "@" file search suggestions are disabled.
+
+Submission behavior
+
+- On submit (Enter) with a shell-mode input:
+ - The leading ! is removed and the remainder is treated as the shell command to run.
+ - The TUI immediately appends an assistant message representing a Shell tool call, with status set to calling, so users can see that the command is in progress.
+ - The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated.
+
+Execution semantics
+
+- The command is executed in the same way as terminal tool commands, minus permissions, and inserted into the chat history the same.
+
+Output handling
+
+- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success.
+- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown.
+- Output is truncated to the first 5000 lines if exceeded.
+- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like:
+ "[Command timed out after 30 seconds of no output]".
+
+Keyboard behaviors (summary)
+
+- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending Shell tool call immediately.
+- Shift+Enter: new line.
+- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual.
+- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context.
+
+Scope / Modes
+
+- Shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing.
+
+Error handling
+
+- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available).
+
+Examples
+
+- "!git status" β shows a Shell tool call immediately, then populates with the git status output.
+- "!echo hello" β shows a Shell tool call immediately, then output "hello".
+- "!some-unknown-cmd" β shows a Shell tool call immediately, then sets status to error with an error message.
diff --git a/extensions/cli/spec/tui.md b/extensions/cli/spec/tui.md
new file mode 100644
index 000000000..a127661db
--- /dev/null
+++ b/extensions/cli/spec/tui.md
@@ -0,0 +1,15 @@
+# Continue CLI Terminal UI spec
+
+This spec is incomplete.
+
+## Stack
+
+The Continue CLI uses Ink as a react TUI library.
+
+## cwd/git display
+
+The lower left corner of the TUI should display
+
+- the current git branch if in a git repo
+- also the current owner/repo if enough columns are available to display and it's a gh repo
+- if not in git, the cwd
diff --git a/extensions/cli/src/__mocks__/args.ts b/extensions/cli/src/__mocks__/args.ts
deleted file mode 100644
index f982bdd09..000000000
--- a/extensions/cli/src/__mocks__/args.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { vi } from "vitest";
-
-export const processPromptOrRule = vi.fn<(spec: string) => Promise>();
-
-export const processPrompt = vi.fn<(prompt: string) => Promise>();
diff --git a/extensions/cli/src/__mocks__/config.ts b/extensions/cli/src/__mocks__/config.ts
index 8b69b7944..c12019479 100644
--- a/extensions/cli/src/__mocks__/config.ts
+++ b/extensions/cli/src/__mocks__/config.ts
@@ -13,5 +13,4 @@ export const getLlmApi =
) => [any, any]
>();
export const getModel = vi.fn<(config: any, modelName: string) => any>();
-export const createLlmApi =
- vi.fn<(modelConfig: any, authConfig: any, orgScopeId?: string) => any>();
+export const createLlmApi = vi.fn<(model: any, authConfig: any) => any>();
diff --git a/extensions/cli/src/__mocks__/services/BaseService.ts b/extensions/cli/src/__mocks__/services/BaseService.ts
new file mode 100644
index 000000000..4294a69e6
--- /dev/null
+++ b/extensions/cli/src/__mocks__/services/BaseService.ts
@@ -0,0 +1,74 @@
+import { EventEmitter } from "events";
+import { vi } from "vitest";
+
+/**
+ * Mocked base service class for testing
+ */
+export class BaseService extends EventEmitter {
+ protected serviceName: string;
+ protected currentState: TState;
+ private isInitialized: boolean = false;
+
+ constructor(serviceName: string, initialState: TState) {
+ super();
+ this.serviceName = serviceName;
+ this.currentState = initialState;
+ }
+
+ // Mock the abstract method
+ doInitialize = vi.fn();
+
+ async initialize(...args: any[]): Promise {
+ this.emit("initializing");
+ try {
+ const state = await this.doInitialize(...args);
+ this.currentState = state;
+ this.isInitialized = true;
+ this.emit("initialized", state);
+ return state;
+ } catch (error) {
+ this.emit("error", error);
+ throw error;
+ }
+ }
+
+ getState(): TState {
+ return { ...this.currentState };
+ }
+
+ protected setState(newState: Partial): void {
+ const previousState = this.currentState;
+ this.currentState = { ...this.currentState, ...newState };
+ this.emit("stateChanged", this.currentState, previousState);
+ }
+
+ isReady(): boolean {
+ return this.isInitialized;
+ }
+
+ async reload(...args: any[]): Promise {
+ this.isInitialized = false;
+ return this.initialize(...args);
+ }
+
+ async cleanup(): Promise {
+ this.removeAllListeners();
+ this.isInitialized = false;
+ }
+}
+
+/**
+ * Interface for services with dependencies
+ */
+export interface ServiceWithDependencies {
+ getDependencies(): string[];
+}
+
+/**
+ * Helper to check if a service has dependencies
+ */
+export function hasDependencies(
+ service: any,
+): service is ServiceWithDependencies {
+ return !!service && typeof service.getDependencies === "function";
+}
diff --git a/extensions/cli/src/__mocks__/services/index.ts b/extensions/cli/src/__mocks__/services/index.ts
index 7ea28d99b..a062ef2a4 100644
--- a/extensions/cli/src/__mocks__/services/index.ts
+++ b/extensions/cli/src/__mocks__/services/index.ts
@@ -1,3 +1,4 @@
+import { ToolPermissionService } from "src/services/ToolPermissionService.js";
import { vi } from "vitest";
export const services = {
@@ -7,14 +8,23 @@ export const services = {
switchOrganization: vi.fn(() => Promise.resolve({})),
getAvailableOrganizations: vi.fn(() => Promise.resolve([])),
},
+ toolPermissions: vi.mocked(new ToolPermissionService()),
};
export const reloadService = vi.fn(() => Promise.resolve(undefined));
export const SERVICE_NAMES = {
AUTH: "auth",
- API_CLIENT: "apiClient",
CONFIG: "config",
MODEL: "model",
MCP: "mcp",
-};
+ API_CLIENT: "apiClient",
+ TOOL_PERMISSIONS: "toolPermissions",
+ FILE_INDEX: "fileIndex",
+ RESOURCE_MONITORING: "resourceMonitoring",
+ SYSTEM_MESSAGE: "systemMessage",
+ CHAT_HISTORY: "chatHistory",
+ UPDATE: "update",
+ STORAGE_SYNC: "storageSync",
+ WORKFLOW: "workflow",
+} as const;
diff --git a/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts b/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts
new file mode 100644
index 000000000..563efbbe9
--- /dev/null
+++ b/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from "vitest";
+
+describe("Process SIGINT handling functions", () => {
+ it("exports the necessary functions for exit message handling", async () => {
+ const indexModule = await import("../index.js");
+
+ // Verify the functions exist
+ expect(typeof indexModule.shouldShowExitMessage).toBe("function");
+ expect(typeof indexModule.setExitMessageCallback).toBe("function");
+ expect(typeof indexModule.setTUIUnmount).toBe("function");
+ });
+});
diff --git a/extensions/cli/src/args-mcp.test.ts b/extensions/cli/src/args-mcp.test.ts
deleted file mode 100644
index 95f77cc7d..000000000
--- a/extensions/cli/src/args-mcp.test.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { beforeEach, describe, expect, it } from "vitest";
-
-import { parseArgs } from "./args.js";
-
-describe("parseArgs --mcp flag", () => {
- beforeEach(() => {
- // Clear process.argv before each test
- process.argv = ["node", "test"];
- });
-
- it("should parse single MCP from --mcp flag", () => {
- process.argv = ["node", "test", "--mcp", "my-org/my-mcp"];
- const result = parseArgs();
- expect(result.mcps).toEqual(["my-org/my-mcp"]);
- });
-
- it("should parse multiple MCPs from multiple --mcp flags", () => {
- process.argv = ["node", "test", "--mcp", "org1/mcp1", "--mcp", "org2/mcp2"];
- const result = parseArgs();
- expect(result.mcps).toEqual(["org1/mcp1", "org2/mcp2"]);
- });
-
- it("should handle MCP flag with other flags", () => {
- process.argv = [
- "node",
- "test",
- "--config",
- "my-config.yaml",
- "--mcp",
- "my-org/my-mcp",
- "--org",
- "test-org",
- ];
- const result = parseArgs();
- expect(result.configPath).toBe("my-config.yaml");
- expect(result.mcps).toEqual(["my-org/my-mcp"]);
- expect(result.organizationSlug).toBe("test-org");
- });
-
- it("should handle MCP flag with prompt", () => {
- process.argv = ["node", "test", "--mcp", "my-org/my-mcp", "hello world"];
- const result = parseArgs();
- expect(result.mcps).toEqual(["my-org/my-mcp"]);
- expect(result.prompt).toBe("hello world");
- });
-
- it("should ignore MCP and rule flag values when extracting prompt", () => {
- process.argv = [
- "node",
- "test",
- "actual prompt",
- "--rule",
- "my-rule",
- "--mcp",
- "my-org/my-mcp",
- ];
- const result = parseArgs();
- expect(result.prompt).toBe("actual prompt");
- expect(result.rules).toEqual(["my-rule"]);
- expect(result.mcps).toEqual(["my-org/my-mcp"]);
- });
-
- it("should handle MCP flag without value", () => {
- process.argv = ["node", "test", "--mcp"];
- const result = parseArgs();
- expect(result.mcps).toEqual([]);
- });
-
- it("should handle MCP flag at the end without value", () => {
- process.argv = ["node", "test", "my prompt", "--mcp"];
- const result = parseArgs();
- expect(result.prompt).toBe("my prompt");
- expect(result.mcps).toEqual([]);
- });
-});
diff --git a/extensions/cli/src/args.prompt.test.ts b/extensions/cli/src/args.prompt.test.ts
deleted file mode 100644
index 46b70b4db..000000000
--- a/extensions/cli/src/args.prompt.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { describe, it, expect, beforeEach, afterAll } from "vitest";
-
-import { parseArgs, processPromptOrRule } from "./args.js";
-
-describe("args --prompt flag", () => {
- const originalArgv = process.argv;
-
- beforeEach(() => {
- // Reset process.argv for each test
- process.argv = ["node", "script.js"];
- });
-
- afterAll(() => {
- // Restore original process.argv after all tests
- process.argv = originalArgv;
- });
-
- it("should parse single prompt from --prompt flag", () => {
- process.argv = ["node", "script.js", "--prompt", "my-prompt"];
- const result = parseArgs();
- expect(result.prompts).toEqual(["my-prompt"]);
- });
-
- it("should parse multiple prompts from multiple --prompt flags", () => {
- process.argv = [
- "node",
- "script.js",
- "--prompt",
- "prompt1",
- "--prompt",
- "prompt2",
- ];
- const result = parseArgs();
- expect(result.prompts).toEqual(["prompt1", "prompt2"]);
- });
-
- it("should handle mixed flags including --prompt", () => {
- process.argv = [
- "node",
- "script.js",
- "--config",
- "myconfig",
- "--prompt",
- "myprompt",
- "--resume",
- ];
- const result = parseArgs();
- expect(result.configPath).toBe("myconfig");
- expect(result.prompts).toEqual(["myprompt"]);
- expect(result.resume).toBe(true);
- });
-
- it("should not include --prompt value in non-flag arguments", () => {
- process.argv = [
- "node",
- "script.js",
- "--prompt",
- "prompt-value",
- "actual-prompt",
- ];
- const result = parseArgs();
- expect(result.prompts).toEqual(["prompt-value"]);
- expect(result.prompt).toBe("actual-prompt");
- });
-
- it("should handle both --rule and --prompt flags", () => {
- process.argv = [
- "node",
- "script.js",
- "--rule",
- "my-rule",
- "--prompt",
- "my-prompt",
- ];
- const result = parseArgs();
- expect(result.rules).toEqual(["my-rule"]);
- expect(result.prompts).toEqual(["my-prompt"]);
- });
-
- it("should process direct string content", async () => {
- const result = await processPromptOrRule("This is a direct prompt");
- expect(result).toBe("This is a direct prompt");
- });
-});
diff --git a/extensions/cli/src/args.test.ts b/extensions/cli/src/args.test.ts
index d22333c05..1b345971c 100644
--- a/extensions/cli/src/args.test.ts
+++ b/extensions/cli/src/args.test.ts
@@ -1,222 +1,6 @@
import { vi } from "vitest";
-import { parseArgs, processPromptOrRule } from "./args.js";
-
-describe("parseArgs", () => {
- const originalArgv = process.argv;
-
- beforeEach(() => {
- // Reset process.argv before each test
- process.argv = ["node", "script.js"];
- });
-
- afterAll(() => {
- // Restore original argv
- process.argv = originalArgv;
- });
-
- it("should return default values when no arguments provided", () => {
- const result = parseArgs();
- expect(result).toEqual({});
- });
-
- it("should set resume to true when --resume flag is present", () => {
- process.argv = ["node", "script.js", "--resume"];
- const result = parseArgs();
- expect(result.resume).toBe(true);
- });
-
- it("should set readonly to true when --readonly flag is present", () => {
- process.argv = ["node", "script.js", "--readonly"];
- const result = parseArgs();
- expect(result.readonly).toBe(true);
- });
-
- it("should parse config path from --config flag", () => {
- process.argv = ["node", "script.js", "--config", "/path/to/config.yaml"];
- const result = parseArgs();
- expect(result.configPath).toBe("/path/to/config.yaml");
- });
-
- it("should parse single rule from --rule flag", () => {
- process.argv = ["node", "script.js", "--rule", "my-rule"];
- const result = parseArgs();
- expect(result.rules).toEqual(["my-rule"]);
- });
-
- it("should parse multiple rules from multiple --rule flags", () => {
- process.argv = ["node", "script.js", "--rule", "rule1", "--rule", "rule2"];
- const result = parseArgs();
- expect(result.rules).toEqual(["rule1", "rule2"]);
- });
-
- it("should parse prompt from last non-flag argument", () => {
- process.argv = ["node", "script.js", "Hello world"];
- const result = parseArgs();
- expect(result.prompt).toBe("Hello world");
- });
-
- it("should handle multiple flags together", () => {
- process.argv = ["node", "script.js", "--print", "--readonly", "--resume"];
- const result = parseArgs();
- expect(result).toEqual({
- readonly: true,
- resume: true,
- });
- });
-
- it("should handle config flag with other flags", () => {
- process.argv = ["node", "script.js", "--config", "config.yaml", "--print"];
- const result = parseArgs();
- expect(result).toEqual({
- configPath: "config.yaml",
- });
- });
-
- it("should handle rule flag with other flags", () => {
- process.argv = ["node", "script.js", "--rule", "my-rule", "--print"];
- const result = parseArgs();
- expect(result).toEqual({
- rules: ["my-rule"],
- });
- });
-
- it("should handle prompt with flags", () => {
- process.argv = ["node", "script.js", "--print", "What is the weather?"];
- const result = parseArgs();
- expect(result).toEqual({
- prompt: "What is the weather?",
- });
- });
-
- it("should handle config flag with prompt", () => {
- process.argv = [
- "node",
- "script.js",
- "--config",
- "config.yaml",
- "Test prompt",
- ];
- const result = parseArgs();
- expect(result).toEqual({
- configPath: "config.yaml",
- prompt: "Test prompt",
- });
- });
-
- it("should handle rule flag with prompt", () => {
- process.argv = ["node", "script.js", "--rule", "my-rule", "Test prompt"];
- const result = parseArgs();
- expect(result).toEqual({
- rules: ["my-rule"],
- prompt: "Test prompt",
- });
- });
-
- it("should ignore config and rule flag values when extracting prompt", () => {
- process.argv = [
- "node",
- "script.js",
- "--config",
- "config.yaml",
- "--rule",
- "my-rule",
- "actual-prompt",
- ];
- const result = parseArgs();
- expect(result.prompt).toBe("actual-prompt");
- expect(result.configPath).toBe("config.yaml");
- expect(result.rules).toEqual(["my-rule"]);
- });
-
- it("should handle multiple non-flag arguments and use the last one as prompt", () => {
- process.argv = ["node", "script.js", "first", "second", "third"];
- const result = parseArgs();
- expect(result.prompt).toBe("third");
- });
-
- it("should handle complex argument combinations", () => {
- process.argv = [
- "node",
- "script.js",
- "--print",
- "--config",
- "my-config.yaml",
- "--rule",
- "rule1",
- "--rule",
- "rule2",
- "--readonly",
- "--resume",
- "Complex prompt with spaces",
- ];
- const result = parseArgs();
- expect(result).toEqual({
- configPath: "my-config.yaml",
- rules: ["rule1", "rule2"],
- readonly: true,
- resume: true,
- prompt: "Complex prompt with spaces",
- });
- });
-
- it("should handle config flag without value", () => {
- process.argv = ["node", "script.js", "--config"];
- const result = parseArgs();
- expect(result.configPath).toBeUndefined();
- });
-
- it("should handle rule flag without value", () => {
- process.argv = ["node", "script.js", "--rule"];
- const result = parseArgs();
- expect(result.rules).toEqual([]);
- });
-
- it("should handle config flag at the end without value", () => {
- process.argv = ["node", "script.js", "--print", "--config"];
- const result = parseArgs();
- expect(result.configPath).toBeUndefined();
- });
-
- it("should handle rule flag at the end without value", () => {
- process.argv = ["node", "script.js", "--print", "--rule"];
- const result = parseArgs();
- expect(result.rules).toEqual([]);
- });
-
- it("should handle empty arguments array", () => {
- process.argv = ["node", "script.js"];
- const result = parseArgs();
- expect(result).toEqual({});
- });
-
- it("should handle multiple boolean flags", () => {
- process.argv = ["node", "script.js", "--readonly", "--resume"];
- const result = parseArgs();
- expect(result.readonly).toBe(true);
- expect(result.resume).toBe(true);
- });
-
- it("should handle multiple rules with complex combinations", () => {
- process.argv = [
- "node",
- "script.js",
- "--rule",
- "file.txt",
- "--rule",
- "owner/package",
- "--rule",
- "direct string rule",
- ];
- const result = parseArgs();
- expect(result.rules).toEqual([
- "file.txt",
- "owner/package",
- "direct string rule",
- ]);
- });
-});
-
+import { processRule as processPromptOrRule } from "./hubLoader.js";
describe("processPromptOrRule (loadRuleFromHub integration)", () => {
// Mock fetch for hub tests
const originalFetch = global.fetch;
diff --git a/extensions/cli/src/args.ts b/extensions/cli/src/args.ts
deleted file mode 100644
index fca0c86e5..000000000
--- a/extensions/cli/src/args.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-export interface CommandLineArgs {
- configPath?: string;
- organizationSlug?: string; // Organization slug to use for this session
- prompt?: string; // Optional prompt argument
- resume?: boolean; // Resume from last session
- readonly?: boolean; // Start in plan mode (backward compatibility)
- rules?: string[]; // Array of rule specifications
- mcps?: string[]; // Array of MCP server slugs from the hub
- models?: string[]; // Array of model slugs from the hub
- prompts?: string[]; // Array of prompt slugs from the hub
- format?: "json"; // Output format for headless mode
-}
-
-// Re-export hub loader functions for backward compatibility
-export { loadMcpFromHub, processRule } from "./hubLoader.js";
-// Alias processRule as processPromptOrRule for backward compatibility
-export { processRule as processPromptOrRule } from "./hubLoader.js";
-
-/**
- * Extract values for a specific flag that can appear multiple times
- */
-function extractMultipleFlags(args: string[], flagName: string): string[] {
- const indices: number[] = [];
- for (let i = 0; i < args.length; i++) {
- if (args[i] === flagName) {
- indices.push(i);
- }
- }
-
- const values: string[] = [];
- for (const index of indices) {
- if (index + 1 < args.length && !args[index + 1].startsWith("--")) {
- values.push(args[index + 1]);
- }
- }
- return values;
-}
-
-/**
- * Extract value for a single-value flag
- */
-function extractSingleFlag(
- args: string[],
- flagName: string,
-): string | undefined {
- const index = args.indexOf(flagName);
- if (
- index !== -1 &&
- index + 1 < args.length &&
- !args[index + 1].startsWith("--")
- ) {
- return args[index + 1];
- }
- return undefined;
-}
-
-/**
- * Parse command line arguments for non-permission related flags
- * @deprecated Most functionality has been moved to services. This is only kept for backward compatibility.
- * @returns Parsed command line arguments
- */
-export function parseArgs(): CommandLineArgs {
- const args = process.argv.slice(2);
- const result: CommandLineArgs = {};
-
- // Parse boolean flags
- if (args.includes("--resume")) {
- result.resume = true;
- }
- if (args.includes("--readonly")) {
- result.readonly = true;
- }
-
- // Parse single-value flags
- const formatValue = extractSingleFlag(args, "--format");
- if (formatValue === "json") {
- result.format = "json";
- }
-
- result.configPath = extractSingleFlag(args, "--config");
-
- const orgValue = extractSingleFlag(args, "--org");
- if (orgValue) {
- result.organizationSlug =
- orgValue.toLowerCase() === "personal" ? undefined : orgValue;
- }
-
- // Parse multi-value flags
- const rules = extractMultipleFlags(args, "--rule");
- if (rules.length > 0) {
- result.rules = rules;
- } else if (args.includes("--rule")) {
- result.rules = [];
- }
-
- const mcps = extractMultipleFlags(args, "--mcp");
- if (mcps.length > 0) {
- result.mcps = mcps;
- } else if (args.includes("--mcp")) {
- // Ensure we have an empty array if --mcp flag is present but has no values
- result.mcps = [];
- }
-
- const models = extractMultipleFlags(args, "--model");
- if (models.length > 0) {
- result.models = models;
- } else if (args.includes("--model")) {
- result.models = [];
- }
-
- const prompts = extractMultipleFlags(args, "--prompt");
- if (prompts.length > 0) {
- result.prompts = prompts;
- } else if (args.includes("--prompt")) {
- result.prompts = [];
- }
-
- // Extract prompt from non-flag arguments
- const flagsWithValues = [
- "--config",
- "--org",
- "--rule",
- "--mcp",
- "--model",
- "--prompt",
- "--format",
- ];
- const nonFlagArgs = args.filter((arg, index) => {
- if (arg.startsWith("--") || arg === "-p") return false;
- const prevArg = index > 0 ? args[index - 1] : "";
- return !flagsWithValues.includes(prevArg);
- });
-
- if (nonFlagArgs.length > 0) {
- result.prompt = nonFlagArgs[nonFlagArgs.length - 1];
- }
-
- return result;
-}
diff --git a/extensions/cli/src/auth/authEnv.ts b/extensions/cli/src/auth/authEnv.ts
new file mode 100644
index 000000000..6b58ad963
--- /dev/null
+++ b/extensions/cli/src/auth/authEnv.ts
@@ -0,0 +1,5 @@
+import * as path from "path";
+
+import { env } from "../env.js";
+
+export const AUTH_CONFIG_PATH = path.join(env.continueHome, "auth.json");
diff --git a/extensions/cli/src/auth/orgSelection.test.ts b/extensions/cli/src/auth/orgSelection.test.ts
new file mode 100644
index 000000000..838a20899
--- /dev/null
+++ b/extensions/cli/src/auth/orgSelection.test.ts
@@ -0,0 +1,233 @@
+import * as fs from "fs";
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ autoSelectOrganizationAndConfig,
+ createUpdatedAuthConfig,
+} from "./orgSelection.js";
+import type { AuthenticatedConfig } from "./workos.js";
+
+// Mock dependencies
+vi.mock("fs");
+vi.mock("../config.js");
+vi.mock("../env.js");
+vi.mock("./workos.js");
+
+const mockApiClient = {
+ listOrganizations: vi.fn(),
+ listAssistants: vi.fn(),
+} as any; // Mock API client for testing
+
+describe("orgSelection", () => {
+ const mockConfig: AuthenticatedConfig = {
+ userId: "user123",
+ userEmail: "user@example.com",
+ accessToken: "token123",
+ refreshToken: "refresh123",
+ expiresAt: Date.now() + 3600000,
+ organizationId: undefined,
+ configUri: undefined,
+ modelName: undefined,
+ };
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+
+ // Mock modules using vi.mocked
+ const configMod = await import("../config.js");
+ const envMod = await import("../env.js");
+ const workosMod = await import("./workos.js");
+
+ vi.mocked(configMod.getApiClient).mockReturnValue(mockApiClient);
+ vi.mocked(envMod.env).continueHome = "/mock/home";
+ vi.mocked(workosMod.saveAuthConfig).mockImplementation(() => {});
+
+ // Default: no local config
+ vi.mocked(fs.existsSync).mockReturnValue(false);
+ });
+
+ describe("createUpdatedAuthConfig", () => {
+ it("should update organization ID", () => {
+ const result = createUpdatedAuthConfig(mockConfig, "org123");
+ expect(result.organizationId).toBe("org123");
+ });
+
+ it("should update organization ID and config URI", () => {
+ const result = createUpdatedAuthConfig(
+ mockConfig,
+ "org123",
+ "slug://owner/assistant",
+ );
+ expect(result.organizationId).toBe("org123");
+ expect(result!.configUri).toBe("slug://owner/assistant");
+ });
+
+ it("should set personal organization", () => {
+ const result = createUpdatedAuthConfig(mockConfig, null);
+ expect(result.organizationId).toBe(null);
+ });
+ });
+
+ describe("autoSelectOrganizationAndConfig scenarios", () => {
+ it("Priority 1: Org with assistants β select first assistant", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [
+ { id: "org1", name: "Org 1" },
+ { id: "org2", name: "Org 2" },
+ ],
+ });
+
+ // Mock API calls in order: org1 assistants, org2 assistants
+ mockApiClient.listAssistants.mockImplementation(
+ ({ organizationId }: { organizationId?: string }) => {
+ if (organizationId === "org1") return Promise.resolve([]);
+ if (organizationId === "org2")
+ return Promise.resolve([
+ { ownerSlug: "owner", packageSlug: "assistant1" },
+ ]);
+ return Promise.resolve([]);
+ },
+ );
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe("org2");
+ expect(result!.configUri).toBe("slug://owner/assistant1");
+ });
+
+ it("Priority 2: No org assistants β personal assistants exist", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [{ id: "org1", name: "Org 1" }],
+ });
+
+ mockApiClient.listAssistants.mockImplementation(
+ ({ organizationId }: { organizationId?: string }) => {
+ if (organizationId === "org1") return Promise.resolve([]);
+ if (organizationId === undefined)
+ return Promise.resolve([
+ { ownerSlug: "personal", packageSlug: "my-assistant" },
+ ]);
+ return Promise.resolve([]);
+ },
+ );
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null); // personal org
+ expect(result!.configUri).toBe("slug://personal/my-assistant");
+ expect(mockApiClient.listAssistants).toHaveBeenCalledWith({
+ organizationId: undefined,
+ });
+ });
+
+ it("Priority 3: No assistants anywhere β local config.yaml exists", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [{ id: "org1", name: "Org 1" }],
+ });
+
+ mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere
+ vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null);
+ expect(result!.configUri).toContain("config.yaml");
+ });
+
+ it("Priority 4: No assistants, no config.yaml β fallback", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [{ id: "org1", name: "Org 1" }],
+ });
+
+ mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere
+ vi.mocked(fs.existsSync).mockReturnValue(false); // No config.yaml
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null);
+ expect(result!.configUri).toBeUndefined();
+ });
+
+ it("Multiple orgs with assistants β pick first one", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [
+ { id: "org1", name: "Org 1" },
+ { id: "org2", name: "Org 2" },
+ ],
+ });
+
+ mockApiClient.listAssistants.mockImplementation(
+ ({ organizationId }: { organizationId?: string }) => {
+ if (organizationId === "org1")
+ return Promise.resolve([
+ { ownerSlug: "owner1", packageSlug: "assistant1" },
+ ]);
+ if (organizationId === "org2")
+ return Promise.resolve([
+ { ownerSlug: "owner2", packageSlug: "assistant2" },
+ ]);
+ return Promise.resolve([]);
+ },
+ );
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe("org1"); // First org wins
+ expect(result!.configUri).toBe("slug://owner1/assistant1");
+ });
+
+ it("Personal assistants API fails β fallback to config.yaml", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [{ id: "org1", name: "Org 1" }],
+ });
+
+ mockApiClient.listAssistants
+ .mockResolvedValueOnce([]) // org1: no assistants
+ .mockRejectedValueOnce(new Error("Personal API failed")); // personal: API error
+
+ vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null);
+ expect(result!.configUri).toContain("config.yaml");
+ });
+
+ it("Empty organizations list β check personal assistants", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [], // No orgs
+ });
+
+ mockApiClient.listAssistants.mockResolvedValue([
+ { ownerSlug: "personal", packageSlug: "my-assistant" },
+ ]);
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null);
+ expect(result!.configUri).toBe("slug://personal/my-assistant");
+ });
+
+ it("API error β fallback with error message", async () => {
+ mockApiClient.listOrganizations.mockRejectedValue(
+ new Error("Network error"),
+ );
+
+ const consoleSpy = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null);
+ expect(result!.configUri).toBeUndefined();
+ expect(consoleSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Error fetching organizations:"),
+ "Network error",
+ );
+
+ consoleSpy.mockRestore();
+ });
+ });
+});
diff --git a/extensions/cli/src/auth/orgSelection.ts b/extensions/cli/src/auth/orgSelection.ts
new file mode 100644
index 000000000..e82bea8ae
--- /dev/null
+++ b/extensions/cli/src/auth/orgSelection.ts
@@ -0,0 +1,155 @@
+import * as fs from "fs";
+import * as path from "path";
+
+import chalk from "chalk";
+
+import type { AuthConfig, AuthenticatedConfig } from "../auth/workos.js";
+import { saveAuthConfig } from "../auth/workos.js";
+import { getApiClient } from "../config.js";
+import { env } from "../env.js";
+
+/**
+ * Creates an updated AuthenticatedConfig with a new organization ID and optional config URI
+ */
+export function createUpdatedAuthConfig(
+ config: AuthenticatedConfig,
+ organizationId: string | null | undefined,
+ configUri?: string | null,
+): AuthenticatedConfig {
+ return {
+ userId: config.userId,
+ userEmail: config.userEmail,
+ accessToken: config.accessToken,
+ refreshToken: config.refreshToken,
+ expiresAt: config.expiresAt,
+ organizationId,
+ configUri: configUri ?? config.configUri,
+ modelName: config.modelName,
+ };
+}
+
+/**
+ * Check if an organization has available assistants
+ */
+async function hasOrgAssistants(
+ apiClient: ReturnType,
+ organizationId: string,
+): Promise {
+ try {
+ const assistants = await apiClient.listAssistants({ organizationId });
+ return assistants.length > 0;
+ } catch {
+ // If we can't check, assume no assistants
+ return false;
+ }
+}
+
+/**
+ * Get the first available assistant from an organization
+ */
+async function getFirstAssistant(
+ apiClient: ReturnType,
+ organizationId: string,
+): Promise {
+ try {
+ const assistants = await apiClient.listAssistants({ organizationId });
+ if (assistants.length > 0) {
+ const first = assistants[0];
+ return `${first.ownerSlug}/${first.packageSlug}`;
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Check if personal local config.yaml exists
+ */
+function hasPersonalLocalConfig(): boolean {
+ const defaultConfigPath = path.join(env.continueHome, "config.yaml");
+ return fs.existsSync(defaultConfigPath);
+}
+
+/**
+ * Automatically select organization and configuration for authenticated config
+ * Priority: 1) Org with assistants (+ first assistant), 2) Personal with local config.yaml, 3) Personal fallback
+ */
+export async function autoSelectOrganizationAndConfig(
+ authenticatedConfig: AuthenticatedConfig,
+): Promise {
+ const apiClient = getApiClient(authenticatedConfig.accessToken);
+
+ try {
+ const resp = await apiClient.listOrganizations();
+ const organizations = resp.organizations;
+
+ // Priority 1: Find any organization that has assistants - use first assistant
+ for (const org of organizations) {
+ const hasAssistants = await hasOrgAssistants(apiClient, org.id);
+ if (hasAssistants) {
+ // Get the first assistant from this org
+ const firstAssistantSlug = await getFirstAssistant(apiClient, org.id);
+ const configUri = firstAssistantSlug
+ ? `slug://${firstAssistantSlug}`
+ : undefined;
+
+ const updatedConfig = createUpdatedAuthConfig(
+ authenticatedConfig,
+ org.id,
+ configUri,
+ );
+ saveAuthConfig(updatedConfig);
+ return updatedConfig;
+ }
+ }
+
+ // Priority 2: Check if personal organization has assistants
+ try {
+ const personalAssistants = await apiClient.listAssistants({
+ organizationId: undefined,
+ });
+ if (personalAssistants.length > 0) {
+ const firstAssistant = personalAssistants[0];
+ const firstAssistantSlug = `${firstAssistant.ownerSlug}/${firstAssistant.packageSlug}`;
+ const configUri = `slug://${firstAssistantSlug}`;
+
+ const updatedConfig = createUpdatedAuthConfig(
+ authenticatedConfig,
+ null,
+ configUri,
+ );
+ saveAuthConfig(updatedConfig);
+ console.log(chalk.green("β Automatically selected personal assistant"));
+ return updatedConfig;
+ }
+ } catch {
+ // If personal assistants can't be fetched, continue to next priority
+ }
+
+ // Priority 3: If no assistants anywhere, use local config.yaml
+ if (hasPersonalLocalConfig()) {
+ const updatedConfig = createUpdatedAuthConfig(
+ authenticatedConfig,
+ null,
+ `file://${path.join(env.continueHome, "config.yaml")}`,
+ );
+ saveAuthConfig(updatedConfig);
+ console.log(chalk.green("β Using local config.yaml"));
+ return updatedConfig;
+ }
+
+ // no org assistants or config.yaml
+ const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
+ saveAuthConfig(updatedConfig);
+ return updatedConfig;
+ } catch (error: any) {
+ console.error(
+ chalk.red("Error fetching organizations:"),
+ error.response?.data?.message || error.message || error,
+ );
+ const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
+ saveAuthConfig(updatedConfig);
+ return updatedConfig;
+ }
+}
diff --git a/extensions/cli/src/auth/workos.helpers.ts b/extensions/cli/src/auth/workos.helpers.ts
index efd2151cc..cc4690cdf 100644
--- a/extensions/cli/src/auth/workos.helpers.ts
+++ b/extensions/cli/src/auth/workos.helpers.ts
@@ -2,6 +2,7 @@ import chalk from "chalk";
import { getApiClient } from "../config.js";
import { safeStderr } from "../init.js";
+import { gracefulExit } from "../util/exit.js";
import type {
AuthConfig,
@@ -15,7 +16,7 @@ import { saveAuthConfig } from "./workos.js";
*/
export function createUpdatedAuthConfig(
config: AuthenticatedConfig,
- organizationId: string | null,
+ organizationId: string | null | undefined,
): AuthenticatedConfig {
return {
userId: config.userId,
@@ -76,7 +77,7 @@ export async function handleCliOrgForEnvironmentAuth(
"The --org flag is only supported in headless mode (with -p/--print flag)\n",
),
);
- process.exit(1);
+ await gracefulExit(1);
}
const apiClient = getApiClient(authConfig.accessToken);
@@ -107,7 +108,7 @@ export async function handleCliOrgForAuthenticatedConfig(
"The --org flag is only supported in headless mode (with -p/--print flag)\n",
),
);
- process.exit(1);
+ await gracefulExit(1);
}
const apiClient = getApiClient(authenticatedConfig.accessToken);
@@ -123,43 +124,3 @@ export async function handleCliOrgForAuthenticatedConfig(
saveAuthConfig(updatedConfig);
return updatedConfig;
}
-
-/**
- * Automatically select organization for authenticated config
- */
-export async function autoSelectOrganization(
- authenticatedConfig: AuthenticatedConfig,
-): Promise {
- const apiClient = getApiClient(authenticatedConfig.accessToken);
-
- try {
- const resp = await apiClient.listOrganizations();
- const organizations = resp.organizations;
-
- if (organizations.length === 0) {
- const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
- saveAuthConfig(updatedConfig);
- return updatedConfig;
- }
-
- // Automatically select the first organization if available
- const selectedOrg = organizations[0];
- const selectedOrgId = selectedOrg.id;
-
- const updatedConfig = createUpdatedAuthConfig(
- authenticatedConfig,
- selectedOrgId,
- );
- saveAuthConfig(updatedConfig);
- return updatedConfig;
- } catch (error: any) {
- console.error(
- chalk.red("Error fetching organizations:"),
- error.response?.data?.message || error.message || error,
- );
- console.info(chalk.yellow("Continuing without organization selection."));
- const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
- saveAuthConfig(updatedConfig);
- return updatedConfig;
- }
-}
diff --git a/extensions/cli/src/auth/workos.orgScope.test.ts b/extensions/cli/src/auth/workos.orgScope.test.ts
new file mode 100644
index 000000000..7367a3024
--- /dev/null
+++ b/extensions/cli/src/auth/workos.orgScope.test.ts
@@ -0,0 +1,58 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+
+import { ensureOrganization, isEnvironmentAuthConfig } from "./workos.js";
+
+describe("ensureOrganization with API key org scope", () => {
+ const originalEnv = { ...process.env };
+ const originalFetch = global.fetch;
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ afterEach(() => {
+ process.env = { ...originalEnv };
+ global.fetch = originalFetch as any;
+ });
+
+ it("resolves organizationId via auth/scope for API key auth", async () => {
+ const mockFetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ organizationId: "org_123" }),
+ });
+ (global as any).fetch = mockFetch;
+
+ const envAuthConfig = {
+ accessToken: "sk_test_api_key",
+ organizationId: null as string | null,
+ } as const;
+
+ const result = await ensureOrganization(envAuthConfig, true);
+ expect(result).not.toBeNull();
+ if (result && isEnvironmentAuthConfig(result)) {
+ expect(result.organizationId).toBe("org_123");
+ } else {
+ throw new Error("Expected environment auth config result");
+ }
+ expect(mockFetch).toHaveBeenCalledOnce();
+ });
+
+ it("keeps organizationId null if endpoint not available", async () => {
+ const mockFetch = vi.fn().mockResolvedValue({ ok: false });
+ (global as any).fetch = mockFetch;
+
+ const envAuthConfig = {
+ accessToken: "sk_test_api_key",
+ organizationId: null as string | null,
+ } as const;
+
+ const result = await ensureOrganization(envAuthConfig, true);
+ expect(result).not.toBeNull();
+ if (result && isEnvironmentAuthConfig(result)) {
+ expect(result.organizationId).toBeNull();
+ } else {
+ throw new Error("Expected environment auth config result");
+ }
+ expect(mockFetch).toHaveBeenCalledOnce();
+ });
+});
diff --git a/extensions/cli/src/auth/workos.ts b/extensions/cli/src/auth/workos.ts
index 8ae14c25f..a005eb56a 100644
--- a/extensions/cli/src/auth/workos.ts
+++ b/extensions/cli/src/auth/workos.ts
@@ -1,4 +1,5 @@
import * as fs from "fs";
+import * as os from "os";
import * as path from "path";
import chalk from "chalk";
@@ -7,13 +8,18 @@ import nodeFetch from "node-fetch";
import open from "open";
import { getApiClient } from "../config.js";
+// eslint-disable-next-line import/order
import { env } from "../env.js";
if (!globalThis.fetch) {
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
}
-// Config file path
-const AUTH_CONFIG_PATH = path.join(env.continueHome, "auth.json");
+// Config file path - define as a function to avoid initialization order issues
+function getAuthConfigPath() {
+ const continueHome =
+ process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue");
+ return path.join(continueHome, "auth.json");
+}
// Represents an authenticated user's configuration
export interface AuthenticatedConfig {
@@ -22,7 +28,7 @@ export interface AuthenticatedConfig {
accessToken: string;
refreshToken: string;
expiresAt: number;
- organizationId: string | null; // null means personal organization
+ organizationId: string | null | undefined; // null means personal organization, undefined triggers auto-selection
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
modelName?: string; // Name of the selected model
}
@@ -74,7 +80,9 @@ export function getAccessToken(config: AuthConfig): string | null {
/**
* Gets the organization ID from any auth config type
*/
-export function getOrganizationId(config: AuthConfig): string | null {
+export function getOrganizationId(
+ config: AuthConfig,
+): string | null | undefined {
if (config === null) return null;
return config.organizationId;
}
@@ -89,17 +97,27 @@ export function getConfigUri(config: AuthConfig): string | null {
/**
* Gets the model name from any auth config type
+ * For unauthenticated users or when auth config has no modelName, checks GlobalContext
*/
export function getModelName(config: AuthConfig): string | null {
- if (config === null) return null;
- return config.modelName || null;
+ // Priority 1: Logged-in users with modelName in auth config
+ if (config !== null && config.modelName) {
+ return config.modelName;
+ }
+
+ // Priority 2: Fall back to GlobalContext (for logged-out users or logged-in without modelName)
+ return getPersistedModelName();
}
// URI utility functions have been moved to ./uriUtils.ts
+import {
+ getPersistedModelName,
+ persistModelName,
+} from "../util/modelPersistence.js";
+
+import { autoSelectOrganizationAndConfig } from "./orgSelection.js";
import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
import {
- autoSelectOrganization,
- createUpdatedAuthConfig,
handleCliOrgForAuthenticatedConfig,
handleCliOrgForEnvironmentAuth,
} from "./workos.helpers.js";
@@ -130,8 +148,9 @@ export function loadAuthConfig(): AuthConfig {
}
try {
- if (fs.existsSync(AUTH_CONFIG_PATH)) {
- const data = JSON.parse(fs.readFileSync(AUTH_CONFIG_PATH, "utf8"));
+ const authConfigPath = getAuthConfigPath();
+ if (fs.existsSync(authConfigPath)) {
+ const data = JSON.parse(fs.readFileSync(authConfigPath, "utf8"));
// Validate that we have all required fields for authenticated config
if (
@@ -173,13 +192,14 @@ export function saveAuthConfig(config: AuthenticatedConfig): void {
}
try {
+ const authConfigPath = getAuthConfigPath();
// Make sure the directory exists
- const dir = path.dirname(AUTH_CONFIG_PATH);
+ const dir = path.dirname(authConfigPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
- fs.writeFileSync(AUTH_CONFIG_PATH, JSON.stringify(config, null, 2));
+ fs.writeFileSync(authConfigPath, JSON.stringify(config, null, 2));
} catch (error) {
console.error(`Error saving auth config: ${error}`);
}
@@ -206,21 +226,30 @@ export function updateConfigUri(configUri: string | null): void {
/**
* Updates the model name in the authentication configuration
+ * Returns the updated config so the caller can update in-memory state
+ * For unauthenticated users, saves to GlobalContext
*/
-export function updateModelName(modelName: string | null): void {
+export function updateModelName(modelName: string | null): AuthConfig {
// If using CONTINUE_API_KEY environment variable, don't save anything
if (process.env.CONTINUE_API_KEY) {
- return;
+ return loadAuthConfig();
}
const config = loadAuthConfig();
+
+ // If logged in, save to auth.json
if (config && isAuthenticatedConfig(config)) {
const updatedConfig: AuthenticatedConfig = {
...config,
modelName: modelName || undefined,
};
saveAuthConfig(updatedConfig);
+ return updatedConfig;
}
+
+ // If logged out, save to GlobalContext
+ persistModelName(modelName);
+ return config;
}
/**
@@ -360,7 +389,7 @@ async function pollForDeviceToken(
accessToken: access_token,
refreshToken: refresh_token,
expiresAt: tokenExpiresAt,
- organizationId: null,
+ organizationId: undefined, // undefined triggers auto-selection, null means personal org selected
};
// Save the config
@@ -540,8 +569,10 @@ export async function ensureOrganization(
);
}
} else if (isEnvironmentAuthConfig(authConfig)) {
- // No CLI organization slug (or "personal" was specified) - return as-is
- return authConfig;
+ // No CLI organization slug (or "personal" was specified)
+ // If using API key auth, attempt to resolve its organization scope once
+ const resolved = await resolveOrgScopeForApiKey(authConfig);
+ return resolved;
}
// If not authenticated, return as-is
@@ -561,20 +592,71 @@ export async function ensureOrganization(
);
}
- // If already have organization ID (including null for personal), return as-is
- if (authenticatedConfig.organizationId !== undefined) {
- return authenticatedConfig;
+ // Only auto-select if user hasn't made any previous selections
+ // - organizationId === undefined means first-time setup
+ // - configUri being set means they've chosen a specific assistant/config
+ if (
+ authenticatedConfig.organizationId === undefined &&
+ !authenticatedConfig.configUri
+ ) {
+ return autoSelectOrganizationAndConfig(authenticatedConfig);
}
- // In headless mode, default to personal organization if none saved
- if (isHeadless) {
- const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
- saveAuthConfig(updatedConfig);
- return updatedConfig;
+ // User already has made a selection (org or config) - respect their choice
+ return authenticatedConfig;
+}
+
+/**
+ * Attempts to resolve the organization scope for API key auth (environment-based auth).
+ * Calls a lightweight backend endpoint to determine if the API key is an org-scoped key.
+ * If successful, returns a new EnvironmentAuthConfig with organizationId set; otherwise returns the original config.
+ */
+async function resolveOrgScopeForApiKey(
+ envConfig: EnvironmentAuthConfig,
+): Promise {
+ // If already set (including explicit null), return as-is
+ if (envConfig.organizationId !== null) {
+ return envConfig;
}
- // Need to select organization
- return autoSelectOrganization(authenticatedConfig);
+ const accessToken = envConfig.accessToken;
+ if (!accessToken) return envConfig;
+
+ try {
+ // Prefer a dedicated endpoint for scope discovery. This should return JSON like:
+ // { organizationId: string | null } (aka orgScopeId)
+ const url = new URL("auth/scope", env.apiBase);
+ const resp = await fetch(url, {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!resp.ok) {
+ // Gracefully ignore if the endpoint isn't available yet (e.g., 404) or other non-2xx errors
+ return envConfig;
+ }
+
+ const data: any = await resp.json().catch(() => ({}));
+ const orgId =
+ data?.organizationId ??
+ data?.orgScopeId ??
+ data?.organization?.id ??
+ null;
+
+ if (orgId && typeof orgId === "string") {
+ return {
+ ...envConfig,
+ organizationId: orgId,
+ };
+ }
+ } catch {
+ // Network or parsing issues: leave config unchanged
+ }
+
+ return envConfig;
}
/**
@@ -624,10 +706,9 @@ export async function hasMultipleOrganizations(): Promise {
* Logs the user out by clearing saved credentials
*/
export function logout(): void {
- const onboardingFlagPath = path.join(
- env.continueHome,
- ".onboarding_complete",
- );
+ const continueHome =
+ process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue");
+ const onboardingFlagPath = path.join(continueHome, ".onboarding_complete");
// Remove onboarding completion flag so user will go through onboarding again
if (fs.existsSync(onboardingFlagPath)) {
@@ -643,8 +724,9 @@ export function logout(): void {
return;
}
- if (fs.existsSync(AUTH_CONFIG_PATH)) {
- fs.unlinkSync(AUTH_CONFIG_PATH);
+ const authConfigPath = getAuthConfigPath();
+ if (fs.existsSync(authConfigPath)) {
+ fs.unlinkSync(authConfigPath);
console.info(chalk.green("Successfully logged out"));
} else {
console.info(chalk.yellow("No active session found"));
diff --git a/extensions/cli/src/commands/BaseCommandOptions.ts b/extensions/cli/src/commands/BaseCommandOptions.ts
index 0d0808ea3..bb32e9a90 100644
--- a/extensions/cli/src/commands/BaseCommandOptions.ts
+++ b/extensions/cli/src/commands/BaseCommandOptions.ts
@@ -21,6 +21,8 @@ export interface BaseCommandOptions {
ask?: string[];
/** Array of tools to exclude from use (--exclude) */
exclude?: string[];
+ /** Workflow slug from the hub (--workflow) */
+ workflow?: string;
}
/**
diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts
index c62b656c4..05332d80e 100644
--- a/extensions/cli/src/commands/chat.ts
+++ b/extensions/cli/src/commands/chat.ts
@@ -1,22 +1,22 @@
import { ModelConfig } from "@continuedev/config-yaml";
+import { BaseLlmApi } from "@continuedev/openai-adapters";
import chalk from "chalk";
-import type { ChatHistoryItem, Session } from "core/index.js";
+import { ChatHistoryItem, Session } from "core";
import { ChatDescriber } from "core/util/chatDescriber.js";
-import * as readlineSync from "readline-sync";
-import {
- compactChatHistory,
- findCompactionIndex,
- getHistoryForLLM,
-} from "../compaction.js";
+import { compactChatHistory, findCompactionIndex } from "../compaction.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
-import { safeStdout } from "../init.js";
+import { safeStderr, safeStdout } from "../init.js";
import { configureLogger } from "../logger.js";
import * as logging from "../logging.js";
import { sentryService } from "../sentry.js";
-import { initializeServices } from "../services/index.js";
+import { initializeServices, services } from "../services/index.js";
import { serviceContainer } from "../services/ServiceContainer.js";
-import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
+import {
+ ModelServiceState,
+ SERVICE_NAMES,
+ WorkflowServiceState,
+} from "../services/types.js";
import {
loadSession,
updateSessionHistory,
@@ -26,8 +26,10 @@ import { streamChatResponse } from "../stream/streamChatResponse.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
+import { gracefulExit } from "../util/exit.js";
import { formatAnthropicError, formatError } from "../util/formatError.js";
import { logger } from "../util/logger.js";
+import { question } from "../util/prompt.js";
import {
calculateContextUsagePercentage,
countChatHistoryTokens,
@@ -80,6 +82,7 @@ function stripThinkTags(response: string): string {
export interface ChatOptions extends ExtendedCommandOptions {
headless?: boolean;
resume?: boolean;
+ fork?: string; // Fork from an existing session ID
format?: "json"; // Output format for headless mode
silent?: boolean; // Strip tags and excess whitespace
}
@@ -89,6 +92,20 @@ export async function initializeChatHistory(
): Promise {
let session: Session | null = null;
+ // Fork from an existing session if --fork flag is used
+ if (options.fork) {
+ const { loadSessionById, startNewSession } = await import("../session.js");
+ const sessionToFork = loadSessionById(options.fork);
+ if (sessionToFork) {
+ logger.info(chalk.yellow("Forking from existing session..."));
+ const newSession = startNewSession(sessionToFork.history);
+ return newSession.history;
+ } else {
+ logger.error(chalk.red(`Session with ID "${options.fork}" not found.`));
+ await gracefulExit(1);
+ }
+ }
+
// Load previous session if --resume flag is used
if (options.resume) {
session = loadSession();
@@ -107,7 +124,7 @@ export async function initializeChatHistory(
async function handleManualCompaction(
chatHistory: ChatHistoryItem[],
model: ModelConfig,
- llmApi: any,
+ llmApi: BaseLlmApi,
isHeadless: boolean,
): Promise<{ compactionIndex?: number | null } | void> {
if (!isHeadless) {
@@ -115,21 +132,21 @@ async function handleManualCompaction(
}
try {
- const result = await compactChatHistory(chatHistory, model, llmApi);
+ const current = services.chatHistory.getHistory();
+ const result = await compactChatHistory(current, model, llmApi);
- // Replace chat history with compacted version
- chatHistory.length = 0;
- chatHistory.push(...result.compactedHistory);
-
- // Save the compacted session
- updateSessionHistory(chatHistory);
+ // Update service-driven history (persistence handled by service)
+ services.chatHistory.compact(
+ result.compactedHistory,
+ result.compactionIndex,
+ );
if (isHeadless) {
safeStdout(
JSON.stringify({
status: "success",
message: "Chat history compacted",
- historyLength: chatHistory.length,
+ historyLength: services.chatHistory.getHistory().length,
}) + "\n",
);
} else {
@@ -148,11 +165,66 @@ async function handleManualCompaction(
}
}
+// Helper function to get streaming response based on compaction state
+async function getStreamingResponse(
+ compactionIndex: number | null | undefined,
+ model: ModelConfig,
+ llmApi: BaseLlmApi,
+): Promise {
+ const abortController = new AbortController();
+
+ if (compactionIndex !== null && compactionIndex !== undefined) {
+ // Use service to compute history for LLM
+ const historyForLLM =
+ services.chatHistory.getHistoryForLLM(compactionIndex);
+
+ return await streamChatResponse(
+ historyForLLM,
+ model,
+ llmApi,
+ abortController,
+ );
+ } else {
+ // No compaction - get full history from service
+ return await streamChatResponse(
+ services.chatHistory.getHistory(),
+ model,
+ llmApi,
+ abortController,
+ );
+ }
+}
+
+// Helper function to process and output response in headless mode
+function processAndOutputResponse(
+ finalResponse: string,
+ isHeadless: boolean,
+ silent?: boolean,
+ format?: "json",
+): void {
+ if (isHeadless && finalResponse && finalResponse.trim()) {
+ let processedResponse = finalResponse;
+
+ // Strip think tags if --silent flag is enabled
+ if (silent) {
+ processedResponse = stripThinkTags(processedResponse);
+ }
+
+ // Process output based on format
+ const outputResponse =
+ format === "json"
+ ? processJsonOutput(processedResponse)
+ : processedResponse;
+
+ safeStdout(outputResponse + "\n");
+ }
+}
+
// Helper function to handle auto-compaction for headless mode
async function handleAutoCompaction(
chatHistory: ChatHistoryItem[],
model: ModelConfig,
- llmApi: any,
+ llmApi: BaseLlmApi,
isHeadless: boolean,
format?: "json",
): Promise {
@@ -176,7 +248,7 @@ async function handleAutoCompaction(
message: "Auto-compacting triggered",
contextUsage:
calculateContextUsagePercentage(
- countChatHistoryTokens(chatHistory),
+ countChatHistoryTokens(services.chatHistory.getHistory()),
model,
) + "%",
}) + "\n",
@@ -186,11 +258,11 @@ async function handleAutoCompaction(
if (!isHeadless) {
console.info(chalk.green(message));
} else if (format === "json") {
+ // Omit history length here; service updates occur after compaction completes
safeStdout(
JSON.stringify({
status: "success",
message: "Auto-compacted successfully",
- historyLength: chatHistory.length,
}) + "\n",
);
}
@@ -210,15 +282,19 @@ async function handleAutoCompaction(
},
};
- const result = await coreAutoCompaction(chatHistory, model, llmApi, {
- isHeadless,
- format,
- callbacks,
- });
+ const result = await coreAutoCompaction(
+ services.chatHistory.getHistory(),
+ model,
+ llmApi,
+ {
+ isHeadless,
+ format,
+ callbacks,
+ },
+ );
- // Update the original array reference for headless mode
- chatHistory.length = 0;
- chatHistory.push(...result.chatHistory);
+ // Update service-driven history
+ services.chatHistory.setHistory(result.chatHistory);
return result.compactionIndex;
}
@@ -228,7 +304,7 @@ async function handleAutoCompaction(
*/
async function handleTitleGeneration(
assistantResponse: string,
- llmApi: any,
+ llmApi: BaseLlmApi,
model: ModelConfig,
): Promise {
try {
@@ -254,7 +330,7 @@ interface ProcessMessageOptions {
userInput: string;
chatHistory: ChatHistoryItem[];
model: ModelConfig;
- llmApi: any;
+ llmApi: BaseLlmApi;
isHeadless: boolean;
format?: "json";
silent?: boolean;
@@ -286,7 +362,7 @@ async function processMessage(
telemetryService.logUserPrompt(userInput.length, userInput);
// Check if auto-compacting is needed BEFORE adding user message
- if (shouldAutoCompact(chatHistory, model)) {
+ if (shouldAutoCompact(services.chatHistory.getHistory(), model)) {
const newIndex = await handleAutoCompaction(
chatHistory,
model,
@@ -296,17 +372,12 @@ async function processMessage(
);
if (newIndex !== null) {
compactionIndex = newIndex;
- // Replace chatHistory with compacted version
- chatHistory.length = 0;
- chatHistory.push(...chatHistory);
+ // Service already updated in handleAutoCompaction via setHistory
}
}
// Add user message to history AFTER potential compaction
- chatHistory.push({
- message: { role: "user", content: userInput },
- contextItems: [],
- });
+ services.chatHistory.addUserMessage(userInput);
// Get AI response with potential tool usage
if (!isHeadless) {
@@ -314,79 +385,56 @@ async function processMessage(
}
try {
- const abortController = new AbortController();
-
- // Handle compaction properly - streamChatResponse modifies the array in place
- let finalResponse;
- if (compactionIndex !== null && compactionIndex !== undefined) {
- // When using compaction, we need to send a subset but capture the full history
- const historyForLLM = getHistoryForLLM(chatHistory, compactionIndex);
- const originalLength = historyForLLM.length;
-
- finalResponse = await streamChatResponse(
- historyForLLM,
- model,
- llmApi,
- abortController,
- );
-
- // Append any new messages (assistant/tool) that were added by streamChatResponse
- const newMessages = historyForLLM.slice(originalLength);
- chatHistory.push(...newMessages);
- } else {
- // No compaction - just pass the full history directly
- finalResponse = await streamChatResponse(
- chatHistory,
- model,
- llmApi,
- abortController,
- );
- // No need to sync back - streamChatResponse modifies chatHistory in place
- }
+ // Get AI response with potential tool usage
+ const finalResponse = await getStreamingResponse(
+ compactionIndex,
+ model,
+ llmApi,
+ );
// Generate session title after first assistant response
if (firstAssistantResponse && finalResponse && finalResponse.trim()) {
await handleTitleGeneration(finalResponse, llmApi, model);
}
- // In headless mode, only print the final response using safe stdout
- if (isHeadless && finalResponse && finalResponse.trim()) {
- let processedResponse = finalResponse;
-
- // Strip think tags if --silent flag is enabled
- if (silent) {
- processedResponse = stripThinkTags(processedResponse);
- }
-
- // Process output based on format
- const outputResponse =
- format === "json"
- ? processJsonOutput(processedResponse)
- : processedResponse;
-
- safeStdout(outputResponse + "\n");
- }
+ // Process and output response in headless mode
+ processAndOutputResponse(finalResponse, isHeadless, silent, format);
// Save session after each successful response
- updateSessionHistory(chatHistory);
+ updateSessionHistory(services.chatHistory.getHistory());
} catch (e: any) {
const error = e instanceof Error ? e : new Error(String(e));
- if (model.provider === "anthropic") {
- logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`);
- } else {
- logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
+ // In headless mode, don't output JSON here - let error bubble up to main handler
+ if (!isHeadless) {
+ // Non-headless mode: use colored console output
+ if (model.provider === "anthropic") {
+ logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`);
+ } else {
+ logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
+ }
+
+ logger.info(
+ chalk.dim(
+ `Chat history:\n${JSON.stringify(
+ services.chatHistory.getHistory(),
+ null,
+ 2,
+ )}`,
+ ),
+ );
}
sentryService.captureException(error, {
context: "chat_response",
isHeadless,
- chatHistoryLength: chatHistory.length,
+ chatHistoryLength: services.chatHistory.getHistory().length,
});
- if (!isHeadless) {
- logger.info(
- chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`),
- );
+
+ // In headless mode, re-throw the error to bubble up to main error handler
+ // This preserves downstream logic like telemetry cleanup
+ if (isHeadless) {
+ throw error;
}
}
}
@@ -414,12 +462,15 @@ async function runHeadlessMode(
throw new Error("No models were found.");
}
- // Initialize chat history
- const chatHistory = await initializeChatHistory(options);
+ if (!llmApi) {
+ throw new Error("No LLM API instance found.");
+ }
- // Track compaction index if resuming with compacted history
+ // Initialize service-driven history (resume if requested)
+ const chatHistory = await initializeChatHistory(options);
let compactionIndex: number | null = null;
- if (options.resume) {
+ if (options.resume || options.fork) {
+ services.chatHistory.setHistory(chatHistory);
compactionIndex = findCompactionIndex(chatHistory);
}
@@ -427,9 +478,15 @@ async function runHeadlessMode(
const { processAndCombinePrompts } = await import(
"../util/promptProcessor.js"
);
+ const workflowState = await serviceContainer.get(
+ SERVICE_NAMES.WORKFLOW,
+ );
+ const initialPrompt =
+ `${workflowState?.workflowFile?.prompt ?? ""}\n\n${prompt ?? ""}`.trim() ||
+ undefined;
const initialUserInput = await processAndCombinePrompts(
options.prompt,
- prompt,
+ initialPrompt,
);
let isFirstMessage = true;
@@ -443,7 +500,7 @@ async function runHeadlessMode(
const userInput =
isFirstMessage && initialUserInput
? initialUserInput
- : readlineSync.question(`\n${chalk.bold.green("You:")} `);
+ : await question(`\n${chalk.bold.green("You:")} `);
isFirstMessage = false;
@@ -485,23 +542,26 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
if (!options.headless) {
// Process flags for TUI mode
const { permissionOverrides } = processCommandFlags(options);
-
// Initialize services with onboarding handled internally
- const initResult = await initializeServices({
+ await initializeServices({
options,
headless: false,
toolPermissionOverrides: permissionOverrides,
});
- // If onboarding was completed, show success message
- if (initResult.wasOnboarded) {
- console.log(chalk.green("β Setup complete! Starting chat..."));
- }
+ const workflowState = await serviceContainer.get(
+ SERVICE_NAMES.WORKFLOW,
+ );
+
+ const initialPrompt =
+ `${workflowState?.workflowFile?.prompt ?? ""}\n\n${prompt ?? ""}`.trim() ||
+ undefined;
// Start TUI with skipOnboarding since we already handled it
const tuiOptions: any = {
- initialPrompt: prompt,
+ initialPrompt,
resume: options.resume,
+ fork: options.fork,
config: options.config,
org: options.org,
rule: options.rule,
@@ -528,15 +588,30 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
await runHeadlessMode(prompt, options);
} catch (error: any) {
const err = error instanceof Error ? error : new Error(String(error));
- // Use headless-aware error logging to ensure fatal errors are shown in headless mode
- logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
+
+ // In headless mode, output error as JSON to stdout
+ if (options.headless) {
+ const errorOutput = {
+ status: "error",
+ message: err.message || String(err),
+ };
+ safeStderr(JSON.stringify(errorOutput) + "\n");
+ } else {
+ // Use headless-aware error logging for non-headless mode
+ logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
+ }
+
sentryService.captureException(err, {
context: "chat_command_fatal",
headless: options.headless,
});
- process.exit(1);
+
+ // Stop active time tracking BEFORE graceful exit
+ telemetryService.stopActiveTime();
+
+ await gracefulExit(1);
} finally {
- // Stop active time tracking
+ // Stop active time tracking for normal completion
telemetryService.stopActiveTime();
}
}
diff --git a/extensions/cli/src/commands/commands.integration.test.ts b/extensions/cli/src/commands/commands.integration.test.ts
index 17bf24428..59984fc9f 100644
--- a/extensions/cli/src/commands/commands.integration.test.ts
+++ b/extensions/cli/src/commands/commands.integration.test.ts
@@ -71,15 +71,17 @@ describe("Slash Commands Integration", () => {
});
});
- it("should only show exit command in remote mode", () => {
+ it("should only show remote mode commands in remote mode", () => {
const commands = getAllSlashCommands(mockAssistant, {
isRemoteMode: true,
});
const commandNames = commands.map((cmd) => cmd.name);
- // In remote mode, only exit command should be available
+ // In remote mode, only remote commands should be available
expect(commandNames).toContain("exit");
- expect(commandNames).toHaveLength(1);
+ expect(commandNames).toContain("diff");
+ expect(commandNames).toContain("apply");
+ expect(commandNames).toHaveLength(3);
});
});
});
diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts
index d1e6325e9..d9886273e 100644
--- a/extensions/cli/src/commands/commands.ts
+++ b/extensions/cli/src/commands/commands.ts
@@ -40,6 +40,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Sign out of your current session",
category: "system",
},
+ {
+ name: "update",
+ description: "Update the Continue CLI",
+ category: "system",
+ },
{
name: "whoami",
description: "Check who you're currently logged in as",
@@ -65,7 +70,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Manage MCP server connections",
category: "system",
},
-
+ {
+ name: "init",
+ description: "Create an AGENTS.md file",
+ category: "system",
+ },
{
name: "compact",
description: "Summarize chat history into a compact form",
@@ -76,6 +85,16 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Resume a previous chat session",
category: "system",
},
+ {
+ name: "fork",
+ description: "Start a forked chat session from the current history",
+ category: "system",
+ },
+ {
+ name: "title",
+ description: "Set the title for the current session",
+ category: "system",
+ },
{
name: "exit",
description: "Exit the chat",
@@ -90,6 +109,16 @@ export const REMOTE_MODE_SLASH_COMMANDS: SlashCommand[] = [
description: "Exit the remote environment",
category: "system",
},
+ {
+ name: "diff",
+ description: "Show the current diff from the remote environment",
+ category: "system",
+ },
+ {
+ name: "apply",
+ description: "Apply the current diff to the local working tree",
+ category: "system",
+ },
];
/**
@@ -117,7 +146,10 @@ export function getAllSlashCommands(
category: "assistant" as const,
})) || [];
- return [...systemCommands, ...assistantCommands];
+ // Get invokable rule commands
+ const invokableRuleCommands = getInvokableRuleSlashCommands(assistant);
+
+ return [...systemCommands, ...assistantCommands, ...invokableRuleCommands];
}
/**
@@ -134,3 +166,33 @@ export function getAssistantSlashCommands(
})) || []
);
}
+
+/**
+ * Get invokable rule commands from assistant config
+ */
+export function getInvokableRuleSlashCommands(
+ assistant: AssistantConfig,
+): SlashCommand[] {
+ if (!assistant?.rules) {
+ return [];
+ }
+
+ return assistant.rules
+ .filter((rule) => {
+ // Handle both string rules and rule objects
+ if (!rule || typeof rule === "string") {
+ return false;
+ }
+ // Only include rules with invokable: true
+ return rule.invokable === true;
+ })
+ .map((rule) => {
+ // TypeScript now knows rule is an object with invokable: true
+ const ruleObj = rule as any;
+ return {
+ name: ruleObj.name || "",
+ description: ruleObj.description || "",
+ category: "assistant" as const,
+ };
+ });
+}
diff --git a/extensions/cli/src/commands/init.ts b/extensions/cli/src/commands/init.ts
new file mode 100644
index 000000000..ad50333ef
--- /dev/null
+++ b/extensions/cli/src/commands/init.ts
@@ -0,0 +1,63 @@
+import { type AssistantConfig } from "@continuedev/sdk";
+import { createRelativeRuleFilePath } from "core/config/markdown/utils.js";
+
+import { SlashCommandResult } from "../ui/hooks/useChat.types.js";
+
+function createInitPrompt(): string {
+ const relativeRuleFilepath = createRelativeRuleFilePath("review");
+ return `Please analyze this repository and create a comprehensive AGENTS.md file, along with a custom slash command. Use your available tools to understand the project structure, read important files like README.md, package.json, requirements.txt, and other configuration files to understand the technology stack and setup.
+
+Create an AGENTS.md file with the following structure:
+
+# Repository Overview
+
+## Project Description
+- What this project does
+- Main purpose and goals
+- Key technologies used
+
+## Architecture Overview
+- High-level architecture
+- Main components and their relationships
+- Data flow and system interactions
+
+## Directory Structure
+- Important directories and their purposes
+- Key files and configuration
+- Entry points and main modules
+
+## Development Workflow
+- How to build/run the project
+- Testing approach
+- Development environment setup
+- Lint and format commands
+
+Additionally, create a slash command file at ${relativeRuleFilepath} with the following structure:
+
+\`\`\`md
+---
+invokable: true
+---
+
+Review this code for potential issues, including:
+
+
+
+Provide specific, actionable feedback for improvements.
+\`\`\`
+
+This slash command will be invokable using /review and will provide instructions for code review tasks common to this repository.
+
+Please create both the AGENTS.md file and the .continue/rules/review.md file using the Write tool after analyzing the repository. Focus on providing actionable information that would help both AI agents and human developers understand and work effectively with this codebase. Keep the files concise but informational.`;
+}
+
+export async function handleInit(
+ _args: string[],
+ _assistant: AssistantConfig,
+): Promise {
+ const prompt = createInitPrompt();
+
+ return {
+ newInput: prompt,
+ };
+}
diff --git a/extensions/cli/src/commands/login.ts b/extensions/cli/src/commands/login.ts
index 5786904ae..e5abf3136 100644
--- a/extensions/cli/src/commands/login.ts
+++ b/extensions/cli/src/commands/login.ts
@@ -1,6 +1,9 @@
import chalk from "chalk";
import { login as workosLogin } from "../auth/workos.js";
+import { gracefulExit } from "../util/exit.js";
+
+import { chat } from "./chat.js";
export async function login() {
console.info(chalk.yellow("Logging in to Continue..."));
@@ -8,8 +11,12 @@ export async function login() {
try {
await workosLogin();
console.info(chalk.green("Successfully logged in!"));
+
+ // Start the CLI session after successful login
+ console.info(chalk.blue("Starting Continue CLI..."));
+ await chat();
} catch (error: any) {
console.error(chalk.red(`Login failed: ${error.message}`));
- process.exit(1);
+ await gracefulExit(1);
}
}
diff --git a/extensions/cli/src/commands/ls.test.ts b/extensions/cli/src/commands/ls.test.ts
index a7d84d058..c56b7eb8c 100644
--- a/extensions/cli/src/commands/ls.test.ts
+++ b/extensions/cli/src/commands/ls.test.ts
@@ -20,16 +20,26 @@ vi.mock("ink", () => ({
render: vi.fn(() => ({ unmount: vi.fn() })),
}));
-// Mock react
-vi.mock("react", () => ({
- createElement: vi.fn(),
-}));
+// Mock react with createContext
+vi.mock("react", async (importOriginal) => {
+ const actual: any = await importOriginal();
+ return {
+ ...actual,
+ createElement: vi.fn(),
+ createContext: vi.fn(() => ({ Provider: vi.fn(), Consumer: vi.fn() })),
+ };
+});
// Mock the chat command
vi.mock("./chat.js", () => ({
chat: vi.fn(),
}));
+// Mock the remote command
+vi.mock("./remote.js", () => ({
+ remote: vi.fn(),
+}));
+
describe("listSessionsCommand", () => {
const mockListSessions = vi.mocked(sessionModule.listSessions);
@@ -49,6 +59,7 @@ describe("listSessionsCommand", () => {
dateCreated: "2023-01-01T10:00:00.000Z",
workspaceDirectory: "/workspace",
firstUserMessage: "Hello world",
+ isRemote: false,
},
{
sessionId: "session-2",
@@ -56,10 +67,12 @@ describe("listSessionsCommand", () => {
dateCreated: "2023-01-01T09:00:00.000Z",
workspaceDirectory: "/workspace",
firstUserMessage: "Test message",
+ isRemote: true,
+ remoteId: "agent-123",
},
];
- mockListSessions.mockReturnValue(mockSessions);
+ mockListSessions.mockResolvedValue(mockSessions);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
@@ -75,6 +88,8 @@ describe("listSessionsCommand", () => {
workspaceDirectory: "/workspace",
title: "Session 1",
firstUserMessage: "Hello world",
+ isRemote: false,
+ remoteId: undefined,
},
{
id: "session-2",
@@ -82,6 +97,8 @@ describe("listSessionsCommand", () => {
workspaceDirectory: "/workspace",
title: "Session 2",
firstUserMessage: "Test message",
+ isRemote: true,
+ remoteId: "agent-123",
},
],
},
@@ -93,20 +110,23 @@ describe("listSessionsCommand", () => {
consoleSpy.mockRestore();
});
- it("should use limit of 10 for JSON and 20 for TUI", async () => {
- mockListSessions.mockReturnValue([]);
+ it("should call listSessions without limit restrictions", async () => {
+ mockListSessions.mockResolvedValue([]);
- // JSON mode should fetch 10
+ // JSON mode - should call listSessions (implementation decides limit)
await listSessionsCommand({ format: "json" });
- expect(mockListSessions).toHaveBeenCalledWith(10);
+ expect(mockListSessions).toHaveBeenCalled();
- // TUI mode should fetch 20 (so UI can choose how many to display)
+ // TUI mode - should call listSessions (implementation decides limit)
await listSessionsCommand({});
- expect(mockListSessions).toHaveBeenCalledWith(20);
+ expect(mockListSessions).toHaveBeenCalled();
+
+ // Verify it was called twice total
+ expect(mockListSessions).toHaveBeenCalledTimes(2);
});
it("should handle empty sessions gracefully in JSON mode", async () => {
- mockListSessions.mockReturnValue([]);
+ mockListSessions.mockResolvedValue([]);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
@@ -120,7 +140,7 @@ describe("listSessionsCommand", () => {
});
it("should handle empty sessions gracefully in TUI mode", async () => {
- mockListSessions.mockReturnValue([]);
+ mockListSessions.mockResolvedValue([]);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
diff --git a/extensions/cli/src/commands/ls.ts b/extensions/cli/src/commands/ls.ts
index 1962e5ac3..529c711b8 100644
--- a/extensions/cli/src/commands/ls.ts
+++ b/extensions/cli/src/commands/ls.ts
@@ -1,11 +1,13 @@
import { render } from "ink";
import React from "react";
-import { loadSessionById, listSessions } from "../session.js";
+import { listSessions, loadSessionById } from "../session.js";
import { SessionSelector } from "../ui/SessionSelector.js";
+import { ApiRequestError, post } from "../util/apiClient.js";
import { logger } from "../util/logger.js";
import { chat } from "./chat.js";
+import { remote } from "./remote.js";
interface ListSessionsOptions {
format?: "json";
@@ -23,18 +25,31 @@ function setSessionId(sessionId: string): void {
);
}
+export async function getTunnelForAgent(agentId: string): Promise {
+ try {
+ const response = await post<{ url: string }>(
+ `agents/${encodeURIComponent(agentId)}/tunnel`,
+ );
+ return response.data.url;
+ } catch (error) {
+ if (error instanceof ApiRequestError) {
+ throw new Error(
+ `Failed to get tunnel for agent ${agentId}: ${error.response || error.statusText}`,
+ );
+ }
+ throw error;
+ }
+}
+
/**
* List recent chat sessions and allow selection
*/
export async function listSessionsCommand(
options: ListSessionsOptions = {},
): Promise {
- // Fetch more sessions than we might display so the UI can choose based on screen height
- // But still limit for JSON output to keep it reasonable
- const sessions = listSessions(options.format === "json" ? 10 : 20);
-
- // Handle JSON format output
+ // Handle JSON format output first
if (options.format === "json") {
+ const sessions = await listSessions();
console.log(
JSON.stringify(
{
@@ -44,6 +59,8 @@ export async function listSessionsCommand(
workspaceDirectory: session.workspaceDirectory,
title: session.title,
firstUserMessage: session.firstUserMessage,
+ isRemote: session.isRemote,
+ remoteId: session.remoteId,
})),
},
null,
@@ -53,6 +70,9 @@ export async function listSessionsCommand(
return;
}
+ // For TUI mode, fetch more sessions than we might display so the UI can choose based on screen height
+ const sessions = await listSessions();
+
// Handle empty sessions case
if (sessions.length === 0) {
console.log(
@@ -67,25 +87,37 @@ export async function listSessionsCommand(
try {
app.unmount();
- // Verify the session exists before trying to load it
- const sessionHistory = loadSessionById(sessionId);
- if (!sessionHistory) {
- console.error(`Session ${sessionId} could not be loaded.`);
- resolve();
- return;
+ // Find the selected session to check if it's remote
+ const selectedSession = sessions.find((s) => s.sessionId === sessionId);
+
+ if (selectedSession?.isRemote && selectedSession.remoteId) {
+ // Handle remote session - use the remote command with the agent URL
+ logger.info(`Opening remote session: ${selectedSession.remoteId}`);
+
+ const tunnelUrl = await getTunnelForAgent(selectedSession.remoteId);
+
+ await remote(undefined, { url: tunnelUrl });
+ } else {
+ // Handle local session
+ const sessionHistory = loadSessionById(sessionId);
+ if (!sessionHistory) {
+ logger.error(`Session ${sessionId} could not be loaded.`);
+ resolve();
+ return;
+ }
+
+ logger.info(`Loading session: ${sessionId}`);
+
+ // Set the session ID so that when chat() runs, it will load this session
+ setSessionId(sessionId);
+
+ // Start chat with resume flag to load the selected session
+ await chat(undefined, {
+ resume: true,
+ headless: false,
+ });
}
- logger.info(`Loading session: ${sessionId}`);
-
- // Set the session ID so that when chat() runs, it will load this session
- setSessionId(sessionId);
-
- // Start chat with resume flag to load the selected session
- await chat(undefined, {
- resume: true,
- headless: false,
- });
-
resolve();
} catch (error) {
logger.error("Error loading session:", error);
diff --git a/extensions/cli/src/commands/remote-test.ts b/extensions/cli/src/commands/remote-test.ts
index e3404c86f..dc5e016e3 100644
--- a/extensions/cli/src/commands/remote-test.ts
+++ b/extensions/cli/src/commands/remote-test.ts
@@ -2,6 +2,7 @@ import chalk from "chalk";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
+import { gracefulExit } from "../util/exit.js";
import { logger } from "../util/logger.js";
export async function remoteTest(
@@ -25,6 +26,6 @@ export async function remoteTest(
logger.error(
chalk.red(`Failed to connect to remote environment: ${error.message}`),
);
- process.exit(1);
+ await gracefulExit(1);
}
}
diff --git a/extensions/cli/src/commands/remote.test.ts b/extensions/cli/src/commands/remote.test.ts
index 5fb3e87f3..a8025a4d7 100644
--- a/extensions/cli/src/commands/remote.test.ts
+++ b/extensions/cli/src/commands/remote.test.ts
@@ -8,11 +8,13 @@ vi.mock("../env.js");
vi.mock("../telemetry/telemetryService.js");
vi.mock("../ui/index.js");
vi.mock("../util/git.js");
+vi.mock("../util/exit.js");
const mockWorkos = vi.mocked(await import("../auth/workos.js"));
const mockEnv = vi.mocked(await import("../env.js"));
const mockGit = vi.mocked(await import("../util/git.js"));
const mockStartRemoteTUIChat = vi.mocked(await import("../ui/index.js"));
+const mockExit = vi.mocked(await import("../util/exit.js"));
// Mock fetch globally
const mockFetch = vi.fn();
@@ -62,6 +64,10 @@ describe("remote command", () => {
mockFetch.mockResolvedValue({
ok: true,
+ headers: {
+ get: (name: string) =>
+ name === "content-type" ? "application/json" : null,
+ },
json: async () => ({
id: "test-agent-id",
url: "ws://test-url.com",
@@ -70,6 +76,9 @@ describe("remote command", () => {
});
mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any);
+
+ // Mock gracefulExit to prevent process.exit during tests
+ mockExit.gracefulExit.mockResolvedValue(undefined);
});
it("should include idempotency key in request body when provided", async () => {
@@ -78,7 +87,7 @@ describe("remote command", () => {
await remote("test prompt", { idempotencyKey: testIdempotencyKey });
expect(mockFetch).toHaveBeenCalledWith(
- new URL("agents/devboxes", mockEnv.env.apiBase),
+ new URL("agents", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
@@ -96,7 +105,7 @@ describe("remote command", () => {
await remote("test prompt", {});
expect(mockFetch).toHaveBeenCalledWith(
- new URL("agents/devboxes", mockEnv.env.apiBase),
+ new URL("agents", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
@@ -145,6 +154,89 @@ describe("remote command", () => {
expect(mockConsoleLog).not.toHaveBeenCalled();
});
+ it("should fetch tunnel and connect when id option is provided", async () => {
+ const agentId = "agent-789";
+
+ mockFetch
+ .mockResolvedValueOnce({
+ ok: true,
+ headers: {
+ get: (name: string) =>
+ name === "content-type" ? "application/json" : null,
+ },
+ json: async () => ({ url: "ws://tunnel-url.com", port: 9090 }),
+ })
+ .mockResolvedValue({
+ ok: true,
+ headers: {
+ get: (name: string) =>
+ name === "content-type" ? "application/json" : null,
+ },
+ json: async () => ({
+ id: "test-agent-id",
+ url: "ws://test-url.com",
+ port: 8080,
+ }),
+ });
+
+ await remote("test prompt", { id: agentId });
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ new URL(`agents/${agentId}/tunnel`, mockEnv.env.apiBase),
+ expect.objectContaining({
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: "Bearer test-token",
+ },
+ }),
+ );
+
+ expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith(
+ "ws://tunnel-url.com",
+ "test prompt",
+ );
+ });
+
+ it("should output JSON without starting TUI when using --id with --start", async () => {
+ const agentId = "agent-456";
+ const tunnelResponse = { url: "ws://existing-tunnel.com", port: 7070 };
+
+ mockFetch.mockResolvedValueOnce({
+ ok: true,
+ headers: {
+ get: (name: string) =>
+ name === "content-type" ? "application/json" : null,
+ },
+ json: async () => tunnelResponse,
+ });
+
+ await remote("test prompt", { id: agentId, start: true });
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ new URL(`agents/${agentId}/tunnel`, mockEnv.env.apiBase),
+ expect.objectContaining({
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: "Bearer test-token",
+ },
+ }),
+ );
+
+ expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
+ expect(mockConsoleLog).toHaveBeenCalledWith(
+ JSON.stringify({
+ status: "success",
+ message: "Remote agent tunnel connection details",
+ url: tunnelResponse.url,
+ containerPort: tunnelResponse.port,
+ agentId,
+ mode: "existing_agent",
+ }),
+ );
+ });
+
it("should handle proper request body structure with all fields", async () => {
const testIdempotencyKey = "structured-test-key";
@@ -190,7 +282,7 @@ describe("remote command", () => {
await remote("test prompt", { branch: testBranch });
expect(mockFetch).toHaveBeenCalledWith(
- new URL("agents/devboxes", mockEnv.env.apiBase),
+ new URL("agents", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
@@ -206,7 +298,7 @@ describe("remote command", () => {
await remote("test prompt", {});
expect(mockFetch).toHaveBeenCalledWith(
- new URL("agents/devboxes", mockEnv.env.apiBase),
+ new URL("agents", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
@@ -236,9 +328,74 @@ describe("remote command", () => {
prompt: "test prompt",
idempotencyKey: testIdempotencyKey,
branchName: testBranch,
+ agent: undefined,
+ config: undefined,
});
});
+ it("should include config in request body when config option is provided", async () => {
+ const testConfig = "test-config-path";
+
+ await remote("test prompt", { config: testConfig });
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ new URL("agents", mockEnv.env.apiBase),
+ expect.objectContaining({
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: "Bearer test-token",
+ },
+ body: expect.stringContaining(`"config":"${testConfig}"`),
+ }),
+ );
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ new URL("agents", mockEnv.env.apiBase),
+ expect.objectContaining({
+ body: expect.stringContaining(`"agent":"${testConfig}"`),
+ }),
+ );
+ });
+
+ it("should handle proper request body structure with config field", async () => {
+ const testConfig = "my-agent-config";
+ const testIdempotencyKey = "test-with-config";
+
+ await remote("test prompt", {
+ config: testConfig,
+ idempotencyKey: testIdempotencyKey,
+ });
+
+ const fetchCall = mockFetch.mock.calls[0];
+ const requestBody = JSON.parse(fetchCall[1].body);
+
+ expect(requestBody).toEqual({
+ repoUrl: "https://github.com/user/test-repo.git",
+ name: expect.stringMatching(/^devbox-\d+$/),
+ prompt: "test prompt",
+ idempotencyKey: testIdempotencyKey,
+ agent: testConfig,
+ config: testConfig,
+ });
+ });
+
+ it("should not include config in request body when config option is not provided", async () => {
+ await remote("test prompt", {});
+
+ const fetchCall = mockFetch.mock.calls[0];
+ const requestBody = JSON.parse(fetchCall[1].body);
+
+ expect(requestBody).toEqual({
+ repoUrl: "https://github.com/user/test-repo.git",
+ name: expect.stringMatching(/^devbox-\d+$/),
+ prompt: "test prompt",
+ agent: undefined,
+ config: undefined,
+ });
+ expect(requestBody).not.toHaveProperty("idempotencyKey");
+ });
+
describe("start mode (-s / --start flag)", () => {
it("should output JSON and exit without starting TUI when using --start with direct URL", async () => {
const testUrl = "ws://test-url.com";
@@ -267,7 +424,7 @@ describe("remote command", () => {
// Should make POST request to create environment
expect(mockFetch).toHaveBeenCalledWith(
- new URL("agents/devboxes", mockEnv.env.apiBase),
+ new URL("agents", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
diff --git a/extensions/cli/src/commands/remote.ts b/extensions/cli/src/commands/remote.ts
index 1d0594dcb..919c720fd 100644
--- a/extensions/cli/src/commands/remote.ts
+++ b/extensions/cli/src/commands/remote.ts
@@ -1,159 +1,226 @@
import chalk from "chalk";
-import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
import { env } from "../env.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
+import {
+ ApiRequestError,
+ AuthenticationRequiredError,
+ post,
+} from "../util/apiClient.js";
+import { gracefulExit } from "../util/exit.js";
import { getRepoUrl } from "../util/git.js";
import { logger } from "../util/logger.js";
import { readStdinSync } from "../util/stdin.js";
+type RemoteCommandOptions = {
+ url?: string;
+ id?: string;
+ idempotencyKey?: string;
+ start?: boolean;
+ branch?: string;
+ repo?: string;
+ config?: string;
+};
+
+type TunnelResponse = {
+ url: string;
+ port?: number;
+};
+
+type AgentCreationResponse = TunnelResponse & {
+ id: string;
+};
+
export async function remote(
prompt: string | undefined,
- options: {
- url?: string;
- idempotencyKey?: string;
- start?: boolean;
- branch?: string;
- repo?: string;
- } = {},
+ options: RemoteCommandOptions = {},
) {
- // Check if prompt should come from stdin instead of parameter
- let actualPrompt = prompt;
- if (prompt) {
- // If prompt is provided, still check for stdin and combine them
- const stdinInput = readStdinSync();
- if (stdinInput) {
- // Combine stdin and prompt argument - stdin comes first in XML block
- actualPrompt = `\n${stdinInput}\n \n\n${prompt}`;
- }
- } else {
- // Try to read from stdin (for piped input like: echo "hello" | cn remote -s)
- const stdinInput = readStdinSync();
- if (stdinInput) {
- actualPrompt = stdinInput;
- }
- }
- // If --url is provided, connect directly to that URL
- if (options.url) {
- if (options.start) {
- // In start mode, output connection details as JSON and exit
- console.log(
- JSON.stringify({
- status: "success",
- message: "Remote environment connection details",
- url: options.url,
- mode: "direct_url",
- }),
- );
+ const actualPrompt = resolvePrompt(prompt);
+
+ try {
+ if (options.url) {
+ await connectToRemoteUrl(options.url, actualPrompt, options.start);
return;
}
- console.info(
- chalk.white(`Connecting to remote environment at: ${options.url}`),
- );
-
- // Record session start
- telemetryService.recordSessionStart();
- telemetryService.startActiveTime();
-
- try {
- // Start the TUI in remote mode
- await startRemoteTUIChat(options.url, actualPrompt);
- } finally {
- telemetryService.stopActiveTime();
+ if (options.id) {
+ await connectExistingAgent(options.id, actualPrompt, options.start);
+ return;
}
+
+ await createAndConnectRemoteEnvironment(actualPrompt, options);
+ } catch (error) {
+ await handleRemoteError(error);
+ }
+}
+
+function resolvePrompt(prompt: string | undefined): string | undefined {
+ const stdinInput = readStdinSync();
+
+ if (!stdinInput) {
+ return prompt;
+ }
+
+ if (!prompt) {
+ return stdinInput;
+ }
+
+ return `\n${stdinInput}\n \n\n${prompt}`;
+}
+
+async function connectToRemoteUrl(
+ remoteUrl: string,
+ prompt: string | undefined,
+ startOnly?: boolean,
+) {
+ if (startOnly) {
+ printStartJson({
+ status: "success",
+ message: "Remote environment connection details",
+ url: remoteUrl,
+ mode: "direct_url",
+ });
return;
}
- try {
- const authConfig = loadAuthConfig();
+ console.info(
+ chalk.white(`Connecting to remote environment at: ${remoteUrl}`),
+ );
+ await launchRemoteTUI(remoteUrl, prompt);
+}
- // Check if we have any valid authentication (file-based or environment variable)
- if (!authConfig || !getAccessToken(authConfig)) {
- console.error(
- chalk.red("Not authenticated. Please run 'cn login' first."),
- );
- process.exit(1);
- }
+async function connectExistingAgent(
+ agentId: string,
+ prompt: string | undefined,
+ startOnly?: boolean,
+) {
+ const tunnel = await fetchAgentTunnel(agentId);
- const accessToken = getAccessToken(authConfig);
-
- const requestBody: any = {
- repoUrl: options.repo || getRepoUrl(),
- name: `devbox-${Date.now()}`,
- prompt: actualPrompt,
- idempotencyKey: options.idempotencyKey,
- };
-
- // Add branchName to request body if branch option is provided
- if (options.branch) {
- requestBody.branchName = options.branch;
- }
-
- const response = await fetch(new URL("agents/devboxes", env.apiBase), {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${accessToken}`,
- },
- body: JSON.stringify(requestBody),
+ if (startOnly) {
+ printStartJson({
+ status: "success",
+ message: "Remote agent tunnel connection details",
+ url: tunnel.url,
+ containerPort: tunnel.port,
+ agentId,
+ mode: "existing_agent",
});
+ return;
+ }
- if (!response.ok) {
- const errorText = await response.text();
+ console.info(
+ chalk.white(`Connecting to remote agent tunnel at: ${tunnel.url}`),
+ );
+ await launchRemoteTUI(tunnel.url, prompt);
+}
+
+async function createAndConnectRemoteEnvironment(
+ prompt: string | undefined,
+ options: RemoteCommandOptions,
+) {
+ const requestBody = buildAgentRequestBody(options, prompt);
+
+ let result: AgentCreationResponse;
+ try {
+ const response = await post("agents", requestBody);
+ result = response.data;
+ } catch (error) {
+ if (error instanceof ApiRequestError) {
throw new Error(
- `Failed to create remote environment: ${response.status} ${errorText}`,
+ `Failed to create remote environment: ${error.status} ${error.response || error.statusText}`,
);
}
+ throw error;
+ }
- const result = await response.json();
+ if (options.start) {
+ printStartJson({
+ status: "success",
+ message: "Remote development environment created successfully",
+ url: `${env.appUrl}/agents/${result.id}`,
+ containerUrl: result.url,
+ containerPort: result.port,
+ name: requestBody.name,
+ mode: "new_environment",
+ });
+ return;
+ }
- if (options.start) {
- // In start mode, output connection details as JSON and exit
- console.log(
- JSON.stringify({
- status: "success",
- message: "Remote development environment created successfully",
- url: `${env.appUrl}/agents/${result.id}`,
- containerUrl: result.url,
- containerPort: result.port,
- name: requestBody.name,
- mode: "new_environment",
- }),
- );
- return;
- }
+ console.info(
+ chalk.green("β
Remote development environment created successfully!"),
+ );
- console.info(
- chalk.green("β
Remote development environment created successfully!"),
- );
+ if (!result.url) {
+ throw new Error("No URL returned from remote environment creation");
+ }
- if (result.url && result.port) {
- const remoteUrl = result.url;
- console.info(
- chalk.white(`Connecting to remote environment at: ${remoteUrl}`),
- );
+ console.info(
+ chalk.white(`Connecting to remote environment at: ${result.url}`),
+ );
+ await launchRemoteTUI(result.url, prompt);
+}
- // Record session start
- telemetryService.recordSessionStart();
- telemetryService.startActiveTime();
+function buildAgentRequestBody(
+ options: RemoteCommandOptions,
+ prompt: string | undefined,
+) {
+ const body: Record = {
+ repoUrl: options.repo ?? getRepoUrl(),
+ name: `devbox-${Date.now()}`,
+ prompt,
+ agent: options.config,
+ config: options.config,
+ };
- try {
- // Start the TUI in remote mode (prompt is optional)
- await startRemoteTUIChat(remoteUrl, actualPrompt);
- } finally {
- telemetryService.stopActiveTime();
- }
- } else {
+ if (options.idempotencyKey) {
+ body.idempotencyKey = options.idempotencyKey;
+ }
+
+ if (options.branch) {
+ body.branchName = options.branch;
+ }
+
+ return body;
+}
+
+async function fetchAgentTunnel(agentId: string) {
+ try {
+ const response = await post(`agents/${agentId}/tunnel`);
+ return response.data;
+ } catch (error) {
+ if (error instanceof ApiRequestError) {
throw new Error(
- "No URL or port returned from remote environment creation",
+ `Failed to create tunnel for agent ${agentId}: ${error.status} ${error.response || error.statusText}`,
);
}
- } catch (error: any) {
- logger.error(
- chalk.red(`Failed to create remote environment: ${error.message}`),
- );
- process.exit(1);
+ throw error;
}
}
+
+async function launchRemoteTUI(remoteUrl: string, prompt: string | undefined) {
+ telemetryService.recordSessionStart();
+ telemetryService.startActiveTime();
+
+ try {
+ await startRemoteTUIChat(remoteUrl, prompt);
+ } finally {
+ telemetryService.stopActiveTime();
+ }
+}
+
+function printStartJson(payload: Record) {
+ console.log(JSON.stringify(payload));
+}
+
+async function handleRemoteError(error: unknown) {
+ if (error instanceof AuthenticationRequiredError) {
+ logger.error(chalk.red(error.message));
+ } else if (error instanceof Error) {
+ logger.error(chalk.red(error.message));
+ } else {
+ logger.error(chalk.red("An unknown error occurred while starting remote"));
+ }
+
+ await gracefulExit(1);
+}
diff --git a/extensions/cli/src/commands/serve.helpers.ts b/extensions/cli/src/commands/serve.helpers.ts
index 35d67116d..51db4d9d0 100644
--- a/extensions/cli/src/commands/serve.helpers.ts
+++ b/extensions/cli/src/commands/serve.helpers.ts
@@ -1,7 +1,9 @@
-import type { Session, ToolCallState, ToolStatus } from "core/index.js";
+import type { Session, ToolStatus } from "core/index.js";
+import { services } from "../services/index.js";
import { streamChatResponse } from "../stream/streamChatResponse.js";
import { StreamCallbacks } from "../stream/streamChatResponse.types.js";
+import { logger } from "../util/logger.js";
// Modified version of streamChatResponse that supports interruption
export async function streamChatResponseWithInterruption(
@@ -38,47 +40,11 @@ export async function streamChatResponseWithInterruption(
// This callback is just for notification/UI updates
// The tool call state is already created and added by handleToolCalls
},
- onToolResult: (result: string, toolName: string, status: ToolStatus) => {
- // Update only the tool call state status
- // The actual result is already added as a separate message by handleToolCalls
- for (let i = state.session.history.length - 1; i >= 0; i--) {
- const item = state.session.history[i];
- if (item.toolCallStates) {
- const toolState = item.toolCallStates.find(
- (ts: ToolCallState) =>
- ts.toolCall.function.name === toolName &&
- (ts.status === "calling" || ts.status === "generated"),
- );
- if (toolState) {
- // Only update the status, not the output
- toolState.status = status;
- break;
- }
- }
- }
+ onToolResult: (_result: string, _toolName: string, _status: ToolStatus) => {
+ // No-op when using ChatHistoryService; it updates tool states/results
},
- onToolError: (error: string, toolName?: string) => {
- // Only update the tool call state to errored status when tool name is provided
- // The error message is already added as a separate tool result message
- // by handleToolCalls/preprocessStreamedToolCalls/executeStreamedToolCalls
- if (toolName) {
- // Find and update the corresponding tool call state
- for (let i = state.session.history.length - 1; i >= 0; i--) {
- const item = state.session.history[i];
- if (item.toolCallStates) {
- const toolState = item.toolCallStates.find(
- (ts: ToolCallState) =>
- ts.toolCall.function.name === toolName &&
- (ts.status === "calling" || ts.status === "generated"),
- );
- if (toolState) {
- // Only update the status, not the output
- toolState.status = "errored";
- break;
- }
- }
- }
- }
+ onToolError: (_error: string, _toolName?: string) => {
+ // No-op; errors are added to history via handleToolCalls flow
},
onToolPermissionRequest: (
toolName: string,
@@ -95,25 +61,33 @@ export async function streamChatResponseWithInterruption(
toolCallPreview,
};
- // Add a system message indicating permission is needed
- state.session.history.push({
- message: {
- role: "system",
- content: `WARNING: Tool ${toolName} requires permission`,
- },
- contextItems: [],
- });
+ // Add a system message indicating permission is needed via service
+ try {
+ services.chatHistory.addSystemMessage(
+ `WARNING: Tool ${toolName} requires permission`,
+ );
+ } catch (err) {
+ // Do not mutate session history; ChatHistoryService is the source of truth
+ logger.error(
+ "Failed to add system message via ChatHistoryService",
+ err,
+ { context: "onToolPermissionRequest", toolName, requestId },
+ );
+ }
// Don't wait here - the streamChatResponse will handle waiting
},
onSystemMessage: (message: string) => {
- state.session.history.push({
- message: {
- role: "system",
- content: message,
- },
- contextItems: [],
- });
+ try {
+ services.chatHistory.addSystemMessage(message);
+ } catch (err) {
+ // Do not mutate session history; ChatHistoryService is the source of truth
+ logger.error(
+ "Failed to add system message via ChatHistoryService",
+ err,
+ { context: "onSystemMessage" },
+ );
+ }
},
};
@@ -145,9 +119,7 @@ export interface ServerState {
model: any;
isProcessing: boolean;
lastActivity: number;
- messageQueue: string[];
currentAbortController: AbortController | null;
- shouldInterrupt: boolean;
serverRunning: boolean;
pendingPermission: PendingPermission | null;
systemMessage?: string;
diff --git a/extensions/cli/src/commands/serve.test.ts b/extensions/cli/src/commands/serve.test.ts
index 2bc8428bd..87487dc32 100644
--- a/extensions/cli/src/commands/serve.test.ts
+++ b/extensions/cli/src/commands/serve.test.ts
@@ -25,6 +25,7 @@ describe("serve command", () => {
ensureOrganization: vi.fn(),
getOrganizationId: vi.fn(),
isAuthenticated: vi.fn(() => false),
+ isAuthenticatedConfig: vi.fn(() => false),
}));
vi.mock("../onboarding.js", () => ({
diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts
index 8d8e726d5..bba7efa00 100644
--- a/extensions/cli/src/commands/serve.ts
+++ b/extensions/cli/src/commands/serve.ts
@@ -1,27 +1,32 @@
-import { exec } from "child_process";
-import { promisify } from "util";
-
import chalk from "chalk";
import type { ChatHistoryItem } from "core/index.js";
import express, { Request, Response } from "express";
-import { getAssistantSlug } from "../auth/workos.js";
+import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js";
+import { posthogService } from "src/telemetry/posthogService.js";
+
+import { getAccessToken, getAssistantSlug } from "../auth/workos.js";
+import { runEnvironmentInstallSafe } from "../environment/environmentHandler.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import {
getService,
initializeServices,
SERVICE_NAMES,
+ services,
} from "../services/index.js";
import {
AuthServiceState,
ConfigServiceState,
ModelServiceState,
} from "../services/types.js";
-import { createSession, updateSessionHistory } from "../session.js";
+import { createSession, getCompleteStateSnapshot } from "../session.js";
+import { messageQueue } from "../stream/messageQueue.js";
import { constructSystemMessage } from "../systemMessage.js";
import { telemetryService } from "../telemetry/telemetryService.js";
+import { gracefulExit } from "../util/exit.js";
import { formatError } from "../util/formatError.js";
+import { getGitDiffSnapshot } from "../util/git.js";
import { logger } from "../util/logger.js";
import { readStdinSync } from "../util/stdin.js";
@@ -31,14 +36,17 @@ import {
type ServerState,
} from "./serve.helpers.js";
-const execAsync = promisify(exec);
-
interface ServeOptions extends ExtendedCommandOptions {
timeout?: string;
port?: string;
+ /** Storage identifier for remote sync */
+ id?: string;
}
+// eslint-disable-next-line max-statements
export async function serve(prompt?: string, options: ServeOptions = {}) {
+ await posthogService.capture("sessionStart", {});
+
// Check if prompt should come from stdin instead of parameter
let actualPrompt = prompt;
if (!prompt) {
@@ -53,6 +61,8 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
const timeoutMs = timeoutSeconds * 1000;
const port = parseInt(options.port || "8000", 10);
+ // Environment install script will be deferred until after server startup to avoid blocking
+
// Initialize services with tool permission overrides
const { permissionOverrides } = processCommandFlags(options);
@@ -63,9 +73,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
});
// Get initialized services from the service container
- const [configState, modelState] = await Promise.all([
+ const [configState, modelState, permissionsState] = await Promise.all([
getService(SERVICE_NAMES.CONFIG),
getService(SERVICE_NAMES.MODEL),
+ getService(SERVICE_NAMES.TOOL_PERMISSIONS),
]);
if (!configState.config || !modelState.llmApi || !modelState.model) {
@@ -83,6 +94,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
if (authState.organizationId) {
telemetryService.updateOrganization(authState.organizationId);
}
+ const accessToken = getAccessToken(authState.authConfig);
// Log configuration information
const organizationId = authState.organizationId || "personal";
@@ -107,6 +119,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// Initialize session with system message
const systemMessage = await constructSystemMessage(
+ permissionsState.currentMode,
options.rule,
undefined,
true,
@@ -122,6 +135,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
const session = createSession(initialHistory);
+ // Align ChatHistoryService with server session and enable remote mode
+ try {
+ await services.chatHistory.initialize(session, false);
+ } catch {
+ // Fallback: continue even if service init fails; stream will still work with arrays
+ }
+
// Initialize server state
const state: ServerState = {
session,
@@ -129,13 +149,43 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
model,
isProcessing: false,
lastActivity: Date.now(),
- messageQueue: [],
currentAbortController: null,
- shouldInterrupt: false,
serverRunning: true,
pendingPermission: null,
};
+ const syncSessionHistory = () => {
+ try {
+ state.session.history = services.chatHistory.getHistory();
+ } catch (e) {
+ logger.debug(
+ `Failed to sync session history from ChatHistoryService: ${formatError(e)}`,
+ );
+ }
+ };
+
+ const storageSyncService = services.storageSync;
+ let storageSyncActive = await storageSyncService.startFromOptions({
+ storageOption: options.id,
+ accessToken,
+ syncSessionHistory,
+ getCompleteStateSnapshot: () =>
+ getCompleteStateSnapshot(
+ state.session,
+ state.isProcessing,
+ messageQueue.getQueueLength(),
+ state.pendingPermission,
+ ),
+ isActive: () => state.serverRunning,
+ });
+
+ const stopStorageSync = () => {
+ if (storageSyncActive) {
+ storageSyncService.stop();
+ storageSyncActive = false;
+ }
+ };
+
// Record session start
telemetryService.recordSessionStart();
telemetryService.startActiveTime();
@@ -146,12 +196,14 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// GET /state - Return the current state
app.get("/state", (_req: Request, res: Response) => {
state.lastActivity = Date.now();
- res.json({
- session: state.session, // Return session directly instead of converting
- isProcessing: state.isProcessing,
- messageQueueLength: state.messageQueue.length,
- pendingPermission: state.pendingPermission,
- });
+ syncSessionHistory();
+ const stateSnapshot = getCompleteStateSnapshot(
+ state.session,
+ state.isProcessing,
+ messageQueue.getQueueLength(),
+ state.pendingPermission,
+ );
+ res.json(stateSnapshot);
});
// POST /message - Queue a message and potentially interrupt
@@ -164,17 +216,11 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
// Queue the message
- state.messageQueue.push(message);
-
- // If currently processing, set interrupt flag
- if (state.isProcessing && state.currentAbortController) {
- state.shouldInterrupt = true;
- }
+ await messageQueue.enqueueMessage(message);
res.json({
queued: true,
- position: state.messageQueue.length,
- willInterrupt: state.shouldInterrupt,
+ position: messageQueue.getQueueLength(),
});
// Process messages if not already processing
@@ -216,39 +262,56 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
});
});
+ // POST /pause - Pause the current agent run (like pressing escape in TUI)
+ app.post("/pause", async (_req: Request, res: Response) => {
+ state.lastActivity = Date.now();
+
+ // Check if there's anything to pause
+ if (!state.isProcessing) {
+ return res.json({
+ success: false,
+ message: "No active processing to pause",
+ });
+ }
+
+ // Abort the current processing
+ if (state.currentAbortController) {
+ state.currentAbortController.abort();
+ }
+
+ // Set isProcessing to false
+ state.isProcessing = false;
+
+ res.json({
+ success: true,
+ message: "Agent run paused",
+ });
+ });
+
// GET /diff - Return git diff against main branch
app.get("/diff", async (_req: Request, res: Response) => {
state.lastActivity = Date.now();
try {
- // First check if we're in a git repository
- await execAsync("git rev-parse --git-dir");
+ const diffResult = await getGitDiffSnapshot();
- // Get the diff against main branch
- const { stdout } = await execAsync("git diff main");
-
- res.json({
- diff: stdout,
- });
- } catch (error: any) {
- // Git diff returns exit code 1 when there are differences, which is normal
- if (error.code === 1 && error.stdout) {
- res.json({
- diff: error.stdout,
- });
- } else if (error.code === 128) {
- // Handle case where we're not in a git repo or main branch doesn't exist
+ if (!diffResult.repoFound) {
res.status(404).json({
error: "Not in a git repository or main branch doesn't exist",
diff: "",
});
- } else {
- logger.error(`Git diff error: ${formatError(error)}`);
- res.status(500).json({
- error: `Failed to get git diff: ${formatError(error)}`,
- diff: "",
- });
+ return;
}
+
+ res.json({
+ diff: diffResult.diff,
+ });
+ } catch (error) {
+ logger.error(`Git diff error: ${formatError(error)}`);
+ res.status(500).json({
+ error: `Failed to get git diff: ${formatError(error)}`,
+ diff: "",
+ });
}
});
@@ -269,15 +332,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// Set server running flag to false to stop processing
state.serverRunning = false;
+ stopStorageSync();
// Abort any current processing
if (state.currentAbortController) {
state.currentAbortController.abort();
}
- // Clear the message queue
- state.messageQueue = [];
-
// Clean up intervals
if (inactivityChecker) {
clearInterval(inactivityChecker);
@@ -285,15 +346,19 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
// Give a moment for the response to be sent
- setTimeout(() => {
+ const handleExitResponse = () => {
server.close(() => {
telemetryService.stopActiveTime();
- process.exit(0);
+ gracefulExit(0).catch((err) => {
+ logger.error(`Graceful exit failed: ${formatError(err)}`);
+ process.exit(1);
+ });
});
- }, 100);
+ };
+ setTimeout(handleExitResponse, 100);
});
- const server = app.listen(port, () => {
+ const server = app.listen(port, async () => {
console.log(chalk.green(`Server started on http://localhost:${port}`));
console.log(chalk.dim("Endpoints:"));
console.log(chalk.dim(" GET /state - Get current agent state"));
@@ -307,6 +372,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
" POST /permission - Approve/reject tool (body: { requestId, approved })",
),
);
+ console.log(chalk.dim(" POST /pause - Pause the current agent run"));
console.log(
chalk.dim(" GET /diff - Get git diff against main branch"),
);
@@ -319,27 +385,62 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
),
);
+ // Run environment install script after server startup
+ runEnvironmentInstallSafe();
+
// If initial prompt provided, queue it for processing
if (actualPrompt) {
console.log(chalk.dim("\nProcessing initial prompt..."));
- state.messageQueue.push(actualPrompt);
+ await messageQueue.enqueueMessage(actualPrompt);
processMessages(state, llmApi);
}
});
// Process messages from the queue
- async function processMessages(state: ServerState, llmApi: any) {
- while (state.messageQueue.length > 0 && state.serverRunning) {
- const userMessage = state.messageQueue.shift()!;
- state.isProcessing = true;
- state.shouldInterrupt = false;
- state.lastActivity = Date.now();
+ function removePartialAssistantMessage(state: ServerState) {
+ try {
+ const svcHistory = services.chatHistory.getHistory();
+ const last = svcHistory[svcHistory.length - 1];
+ if (last && last.message.role === "assistant" && !last.message.content) {
+ const trimmed = svcHistory.slice(0, -1);
+ services.chatHistory.setHistory(trimmed);
+ }
+ } catch {
+ const lastMessage =
+ state.session.history[state.session.history.length - 1];
+ if (
+ lastMessage &&
+ lastMessage.message.role === "assistant" &&
+ !lastMessage.message.content
+ ) {
+ state.session.history.pop();
+ }
+ }
+ }
- // Add user message to history
- state.session.history.push({
- message: { role: "user", content: userMessage },
- contextItems: [],
- });
+ async function processMessages(state: ServerState, llmApi: any) {
+ let processedMessage = false;
+ while (state.serverRunning) {
+ const queuedMessage = messageQueue.getNextMessage();
+ if (!queuedMessage) {
+ break;
+ }
+
+ const userMessage = queuedMessage.message;
+ state.isProcessing = true;
+ state.lastActivity = Date.now();
+ processedMessage = true;
+
+ // Add user message via ChatHistoryService (single source of truth)
+ try {
+ services.chatHistory.addUserMessage(userMessage);
+ } catch {
+ // Fallback to local array if service unavailable
+ state.session.history.push({
+ message: { role: "user", content: userMessage },
+ contextItems: [],
+ });
+ }
try {
// Create new abort controller for this response
@@ -350,40 +451,43 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
state,
llmApi,
state.currentAbortController,
- () => state.shouldInterrupt,
+ () => false,
);
- // Save session after successful response
- updateSessionHistory(state.session.history);
+ // No direct persistence here; ChatHistoryService handles persistence when appropriate
state.lastActivity = Date.now();
} catch (e: any) {
if (e.name === "AbortError") {
logger.debug("Response interrupted");
- // Remove the partial assistant message if it exists
- const lastMessage =
- state.session.history[state.session.history.length - 1];
- if (
- lastMessage &&
- lastMessage.message.role === "assistant" &&
- !lastMessage.message.content
- ) {
- state.session.history.pop();
- }
+ // Remove any partial assistant message
+ removePartialAssistantMessage(state);
} else {
logger.error(`Error: ${formatError(e)}`);
- // Add error message to chat history and display messages
+ // Add error message via ChatHistoryService
const errorMessage = `Error: ${formatError(e)}`;
- state.session.history.push({
- message: { role: "assistant", content: errorMessage },
- contextItems: [],
- });
+ try {
+ services.chatHistory.addAssistantMessage(errorMessage);
+ } catch {
+ state.session.history.push({
+ message: { role: "assistant", content: errorMessage },
+ contextItems: [],
+ });
+ }
}
} finally {
state.currentAbortController = null;
state.isProcessing = false;
}
}
+
+ if (
+ processedMessage &&
+ state.serverRunning &&
+ messageQueue.getQueueLength() === 0
+ ) {
+ await storageSyncService.markAgentStatusUnread();
+ }
}
// Check for inactivity and shutdown
@@ -395,9 +499,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
),
);
state.serverRunning = false;
+ stopStorageSync();
server.close(() => {
telemetryService.stopActiveTime();
- process.exit(0);
+ gracefulExit(0).catch((err) => {
+ logger.error(`Graceful exit failed: ${formatError(err)}`);
+ process.exit(1);
+ });
});
if (inactivityChecker) {
clearInterval(inactivityChecker);
@@ -410,13 +518,17 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
process.on("SIGINT", () => {
console.log(chalk.yellow("\nShutting down server..."));
state.serverRunning = false;
+ stopStorageSync();
if (inactivityChecker) {
clearInterval(inactivityChecker);
inactivityChecker = null;
}
server.close(() => {
telemetryService.stopActiveTime();
- process.exit(0);
+ gracefulExit(0).catch((err) => {
+ logger.error(`Graceful exit failed: ${formatError(err)}`);
+ process.exit(1);
+ });
});
});
}
diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts
index 3edbe0260..2205e7976 100644
--- a/extensions/cli/src/compaction.ts
+++ b/extensions/cli/src/compaction.ts
@@ -28,6 +28,7 @@ export interface CompactionCallbacks {
* @param model The model configuration
* @param llmApi The LLM API instance
* @param callbacks Optional callbacks for streaming updates
+ * @param abortController Optional abort controller for cancellation
* @returns The compacted history with compaction index
*/
export async function compactChatHistory(
@@ -35,6 +36,7 @@ export async function compactChatHistory(
model: ModelConfig,
llmApi: BaseLlmApi,
callbacks?: CompactionCallbacks,
+ abortController?: AbortController,
): Promise {
// Create a prompt to summarize the conversation
const compactionPrompt: ChatHistoryItem = {
@@ -80,8 +82,8 @@ export async function compactChatHistory(
historyForCompaction = [...historyToUse, compactionPrompt];
}
- // Stream the compaction response
- const controller = new AbortController();
+ // Stream the compaction response (service drives updates; this collects content locally)
+ const controller = abortController || new AbortController();
let compactionContent = "";
const streamCallbacks: StreamCallbacks = {
diff --git a/extensions/cli/src/config.ts b/extensions/cli/src/config.ts
index 6ff59e327..6c97767bc 100644
--- a/extensions/cli/src/config.ts
+++ b/extensions/cli/src/config.ts
@@ -19,6 +19,43 @@ import { loadConfiguration } from "./configLoader.js";
import { env } from "./env.js";
import { MCPService } from "./services/MCPService.js";
+/**
+ * Creates an LLM API instance from a ModelConfig and auth configuration
+ * Handles special logic for continue-proxy provider and constructs the API
+ */
+export function createLlmApi(
+ model: ModelConfig,
+ authConfig: AuthConfig | null,
+): BaseLlmApi | null {
+ const accessToken = getAccessToken(authConfig);
+ const organizationId = getOrganizationId(authConfig);
+
+ const config: LLMConfig =
+ model.provider === "continue-proxy"
+ ? {
+ provider: model.provider,
+ requestOptions: model.requestOptions,
+ apiBase: model.apiBase,
+ apiKey: accessToken ?? undefined,
+ env: {
+ apiKeyLocation: (model as any).apiKeyLocation,
+ orgScopeId: organizationId ?? null,
+ proxyUrl:
+ (model as { onPremProxyUrl: string | undefined })
+ .onPremProxyUrl ?? undefined,
+ },
+ }
+ : {
+ provider: model.provider as any,
+ apiKey: model.apiKey,
+ apiBase: model.apiBase,
+ requestOptions: model.requestOptions,
+ env: model.env,
+ };
+
+ return constructLlmApi(config) ?? null;
+}
+
export function getLlmApi(
assistant: AssistantUnrolled,
authConfig: AuthConfig,
@@ -38,32 +75,7 @@ export function getLlmApi(
);
}
- const accessToken = getAccessToken(authConfig);
- const organizationId = getOrganizationId(authConfig);
-
- const config: LLMConfig =
- model.provider === "continue-proxy"
- ? {
- provider: model.provider,
- requestOptions: model.requestOptions,
- apiBase: model.apiBase,
- apiKey: accessToken ?? undefined,
- env: {
- apiKeyLocation: (model as any).apiKeyLocation,
- // envSecretLocations: model.env,
- orgScopeId: organizationId,
- proxyUrl: undefined, // TODO
- },
- }
- : {
- provider: model.provider as any,
- apiKey: model.apiKey,
- apiBase: model.apiBase,
- requestOptions: model.requestOptions,
- env: model.env,
- };
-
- const llmApi = constructLlmApi(config);
+ const llmApi = createLlmApi(model, authConfig);
if (!llmApi) {
throw new Error(
diff --git a/extensions/cli/src/configEnhancer.test.ts b/extensions/cli/src/configEnhancer.test.ts
index bbee50c0b..3aaea15b4 100644
--- a/extensions/cli/src/configEnhancer.test.ts
+++ b/extensions/cli/src/configEnhancer.test.ts
@@ -13,11 +13,34 @@ vi.mock("./hubLoader.js", () => ({
// Return as-is for direct content
return Promise.resolve(rule);
}),
+ loadPackageFromHub: vi.fn(() =>
+ Promise.resolve({ name: "test", provider: "test" }),
+ ),
loadPackagesFromHub: vi.fn(() => Promise.resolve([])),
mcpProcessor: {},
modelProcessor: {},
}));
+// Mock the service container to provide empty workflow state
+vi.mock("./services/ServiceContainer.js", () => ({
+ serviceContainer: {
+ get: vi.fn(() =>
+ Promise.resolve({
+ workflowService: null,
+ workflowModelName: null,
+ workflowFile: null,
+ workflow: null,
+ }),
+ ),
+ },
+}));
+
+vi.mock("./services/types.js", () => ({
+ SERVICE_NAMES: {
+ WORKFLOW: "workflow",
+ },
+}));
+
describe("ConfigEnhancer", () => {
let enhancer: ConfigEnhancer;
let mockConfig: any;
@@ -199,4 +222,42 @@ describe("ConfigEnhancer", () => {
command: "existing-mcp",
});
});
+
+ it("should handle workflow integration gracefully when no workflow", async () => {
+ // The mocked service container returns null workflow state
+ const options: BaseCommandOptions = {
+ rule: ["test-rule"],
+ };
+
+ const config = await enhancer.enhanceConfig(mockConfig, options);
+
+ // Should work normally when no workflow is active
+ expect(config.rules).toEqual(["test-rule"]);
+ });
+
+ it("should handle workflow integration when workflow is active", async () => {
+ // Mock service container to return active workflow
+ const options: BaseCommandOptions = {
+ rule: ["user-rule"],
+ prompt: ["user-prompt"],
+ };
+
+ const config = await enhancer.enhanceConfig(mockConfig, options, {
+ workflowFile: {
+ name: "Test Workflow",
+ prompt: "You are a test assistant",
+ rules: "Always be helpful",
+ model: "gpt-4",
+ tools: "bash,read",
+ },
+ slug: "owner/test-workflow",
+ workflowModelName: null,
+ workflowService: null,
+ });
+
+ // Should have both workflow and user rules
+ expect(config.rules).toHaveLength(2);
+ expect(config.rules?.[0]).toBe("Always be helpful"); // Workflow rule first
+ expect(config.rules?.[1]).toBe("user-rule"); // User rule second
+ });
});
diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts
index ee1c9b254..49e464f2f 100644
--- a/extensions/cli/src/configEnhancer.ts
+++ b/extensions/cli/src/configEnhancer.ts
@@ -1,43 +1,115 @@
-import { AssistantUnrolled, Rule } from "@continuedev/config-yaml";
+import {
+ AssistantUnrolled,
+ parseWorkflowTools,
+ Rule,
+} from "@continuedev/config-yaml";
import { BaseCommandOptions } from "./commands/BaseCommandOptions.js";
import {
+ loadPackageFromHub,
loadPackagesFromHub,
mcpProcessor,
modelProcessor,
processRule,
} from "./hubLoader.js";
+import { WorkflowServiceState } from "./services/types.js";
import { logger } from "./util/logger.js";
/**
* Enhances a configuration by injecting additional components from CLI flags
*/
export class ConfigEnhancer {
+ // added this for lint complexity rule
+ private async enhanceConfigFromWorkflow(
+ config: AssistantUnrolled,
+ _options: BaseCommandOptions | undefined,
+ workflowState?: WorkflowServiceState,
+ ) {
+ const enhancedConfig = { ...config };
+ const options = { ..._options };
+
+ if (workflowState?.workflowFile) {
+ const { rules, model, tools, prompt } = workflowState?.workflowFile;
+ if (rules) {
+ options.rule = [
+ ...rules
+ .split(",")
+ .filter(Boolean)
+ .map((r) => r.trim()),
+ ...(options.rule || []),
+ ];
+ }
+
+ if (tools) {
+ try {
+ const parsedTools = parseWorkflowTools(tools);
+ if (parsedTools.mcpServers.length > 0) {
+ options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])];
+ }
+ } catch (e) {
+ logger.error("Failed to parse workflow tools", e);
+ }
+ }
+
+ // --model takes precedence over workflow model
+ if (model) {
+ try {
+ const workflowModel = await loadPackageFromHub(model, modelProcessor);
+ enhancedConfig.models = [
+ workflowModel,
+ ...(enhancedConfig.models ?? []),
+ ];
+ workflowState?.workflowService?.setWorkflowModelName(
+ workflowModel.name,
+ );
+ } catch (e) {
+ logger.error("Failed to load workflow model", e);
+ }
+ }
+
+ // Workflow prompt is included as a slash command, initial kickoff is handled elsewhere
+ if (prompt) {
+ enhancedConfig.prompts = [
+ {
+ name: `Workflow prompt (${workflowState.workflowFile.name})`,
+ prompt,
+ description: workflowState.workflowFile.description,
+ },
+ ...(enhancedConfig.prompts ?? []),
+ ];
+ }
+ }
+ return { options, enhancedConfig };
+ }
/**
* Apply all enhancements to a configuration
*/
async enhanceConfig(
config: AssistantUnrolled,
- options: BaseCommandOptions,
+ _options?: BaseCommandOptions,
+ workflowState?: WorkflowServiceState,
): Promise {
- let enhancedConfig = { ...config };
+ const enhanced = await this.enhanceConfigFromWorkflow(
+ config,
+ _options,
+ workflowState,
+ );
+ let { enhancedConfig } = enhanced;
+ const { options } = enhanced;
- // Apply rules
+ // Inject resolved items into config
if (options.rule && options.rule.length > 0) {
enhancedConfig = await this.injectRules(enhancedConfig, options.rule);
}
- // Apply MCPs
if (options.mcp && options.mcp.length > 0) {
enhancedConfig = await this.injectMcps(enhancedConfig, options.mcp);
}
- // Apply models
if (options.model && options.model.length > 0) {
enhancedConfig = await this.injectModels(enhancedConfig, options.model);
}
- // Apply prompts
if (options.prompt && options.prompt.length > 0) {
enhancedConfig = await this.injectPrompts(enhancedConfig, options.prompt);
}
@@ -105,11 +177,8 @@ export class ConfigEnhancer {
const modifiedConfig = { ...config };
// Prepend processed MCPs to existing mcpServers array for consistency
- const existingMcpServers = (modifiedConfig as any).mcpServers || [];
- (modifiedConfig as any).mcpServers = [
- ...processedMcps,
- ...existingMcpServers,
- ];
+ const existingMcpServers = modifiedConfig.mcpServers || [];
+ modifiedConfig.mcpServers = [...processedMcps, ...existingMcpServers];
return modifiedConfig;
}
@@ -123,26 +192,28 @@ export class ConfigEnhancer {
): Promise {
const processedModels = await loadPackagesFromHub(models, modelProcessor);
- // Clone the config to avoid mutating the original
const modifiedConfig = { ...config };
// Prepend processed models to existing models array so they become the default
- const existingModels = (modifiedConfig as any).models || [];
- (modifiedConfig as any).models = [...processedModels, ...existingModels];
+ const existingModels = modifiedConfig.models || [];
+ modifiedConfig.models = [...processedModels, ...existingModels];
return modifiedConfig;
}
/**
* Inject prompts into the configuration
+ * Note: Prompts are processed at runtime via processAndCombinePrompts(),
+ * not injected into the config. This method exists for consistency with
+ * other injection methods but doesn't modify the config.
*/
private async injectPrompts(
config: AssistantUnrolled,
prompts: string[],
): Promise {
- // For prompts, we'll need a different approach since they become slash commands
- // This is a placeholder implementation
- logger.debug("Prompt injection not yet implemented", { prompts });
+ // Prompts are handled at runtime by processAndCombinePrompts in chat.ts
+ // They don't need to be injected into the configuration
+ logger.debug("Prompts will be processed at runtime", { prompts });
return config;
}
}
diff --git a/extensions/cli/src/configLoader.ts b/extensions/cli/src/configLoader.ts
index 79e3cc9f3..423875312 100644
--- a/extensions/cli/src/configLoader.ts
+++ b/extensions/cli/src/configLoader.ts
@@ -55,7 +55,7 @@ export async function loadConfiguration(
const config = await loadFromSource(
configSource,
accessToken,
- organizationId,
+ organizationId ?? null,
apiClient,
);
@@ -229,9 +229,18 @@ async function loadUserAssistantWithFallback(
if (assistants.length > 0) {
const result = assistants[0].configResult;
- if (result.errors?.length || !result.config) {
+ if (!result.config) {
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
}
+
+ const errors = result.errors;
+ if (errors?.some((e: any) => e.fatal)) {
+ throw new Error(
+ errors.map((e: any) => e.message).join("\n") ??
+ "Failed to load assistant.",
+ );
+ }
+
return result.config as AssistantUnrolled;
}
@@ -373,8 +382,12 @@ async function loadAssistantSlug(
});
const result = resp.configResult;
- if (result.errors?.length || !result.config) {
- throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
+ const errors = result.errors;
+ if (errors?.some((e: any) => e.fatal)) {
+ throw new Error(
+ errors.map((e: any) => e.message).join("\n") ??
+ "Failed to load assistant.",
+ );
}
return result.config as AssistantUnrolled;
diff --git a/extensions/cli/src/e2e/git-branch-display.test.ts b/extensions/cli/src/e2e/git-branch-display.test.ts
new file mode 100644
index 000000000..2224a057d
--- /dev/null
+++ b/extensions/cli/src/e2e/git-branch-display.test.ts
@@ -0,0 +1,258 @@
+import { execSync } from "child_process";
+import fs from "fs/promises";
+import path from "path";
+
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import {
+ cleanupTestContext,
+ createTestConfig,
+ createTestContext,
+ runCLI,
+ type CLITestContext,
+} from "../test-helpers/cli-helpers.js";
+
+describe("E2E: Git Branch Display", () => {
+ let context: CLITestContext;
+ let originalCwd: string;
+
+ const testConfig = `name: Test Assistant
+version: 1.0.0
+schema: v1
+models:
+ - model: gpt-4
+ provider: openai
+ apiKey: test-key
+ roles:
+ - chat`;
+
+ beforeEach(async () => {
+ context = await createTestContext();
+ originalCwd = process.cwd();
+ });
+
+ afterEach(async () => {
+ await cleanupTestContext(context);
+ process.chdir(originalCwd);
+ });
+
+ describe("git branch display in status bar", () => {
+ it("should show branch name when in a git repository", async () => {
+ // Initialize a git repo in the test directory
+ process.chdir(context.testDir);
+
+ try {
+ // Initialize git repo
+ execSync("git init", { stdio: "ignore" });
+ execSync("git config user.email 'test@example.com'", {
+ stdio: "ignore",
+ });
+ execSync("git config user.name 'Test User'", { stdio: "ignore" });
+
+ // Create a test file and initial commit
+ await fs.writeFile(
+ path.join(context.testDir, "test.txt"),
+ "test content",
+ );
+ execSync("git add .", { stdio: "ignore" });
+ execSync("git commit -m 'Initial commit'", { stdio: "ignore" });
+
+ // Create and checkout a test branch
+ const testBranchName = "feature/test-branch";
+ execSync(`git checkout -b ${testBranchName}`, { stdio: "ignore" });
+
+ // Create config file
+ await createTestConfig(context, testConfig);
+
+ // Run CLI in TUI mode - it should fail quickly but show the branch in output
+ const result = await runCLI(context, {
+ args: ["--config", context.configPath!, "--help"],
+ timeout: 3000,
+ });
+
+ // The help command should succeed
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toContain("Continue CLI");
+
+ // Now let's test that our git utils work in this context
+ // We can't easily test the full TUI display, but we can verify the git functions work
+ const { getGitBranch } = await import("../util/git.js");
+ const branch = getGitBranch();
+ expect(branch).toBe(testBranchName);
+ } catch (error) {
+ // Skip test if git is not available or fails
+ console.warn("Skipping git branch test - git not available:", error);
+ return;
+ }
+ });
+
+ it("should handle non-git directory gracefully", async () => {
+ // Don't initialize git in test directory
+ process.chdir(context.testDir);
+
+ await createTestConfig(context, testConfig);
+
+ // Test that git functions return null in non-git directory
+ const { getGitBranch, isGitRepo } = await import("../util/git.js");
+
+ expect(isGitRepo()).toBe(false);
+ expect(getGitBranch()).toBeNull();
+
+ // CLI should still work without git
+ const result = await runCLI(context, {
+ args: ["--help"],
+ timeout: 3000,
+ });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toContain("Continue CLI");
+ });
+
+ it("should handle detached HEAD state", async () => {
+ process.chdir(context.testDir);
+
+ try {
+ // Initialize git repo
+ execSync("git init", { stdio: "ignore" });
+ execSync("git config user.email 'test@example.com'", {
+ stdio: "ignore",
+ });
+ execSync("git config user.name 'Test User'", { stdio: "ignore" });
+
+ // Create initial commit
+ await fs.writeFile(
+ path.join(context.testDir, "test.txt"),
+ "test content",
+ );
+ execSync("git add .", { stdio: "ignore" });
+ execSync("git commit -m 'Initial commit'", { stdio: "ignore" });
+
+ // Create another commit
+ await fs.writeFile(
+ path.join(context.testDir, "test2.txt"),
+ "test content 2",
+ );
+ execSync("git add .", { stdio: "ignore" });
+ execSync("git commit -m 'Second commit'", { stdio: "ignore" });
+
+ // Get first commit hash and checkout to detached HEAD
+ const firstCommit = execSync(
+ "git rev-list --max-count=1 --reverse HEAD",
+ {
+ encoding: "utf-8",
+ },
+ ).trim();
+ execSync(`git checkout ${firstCommit}`, { stdio: "ignore" });
+
+ // Test git functions in detached HEAD state
+ const { getGitBranch, isGitRepo } = await import("../util/git.js");
+
+ expect(isGitRepo()).toBe(true);
+ // In detached HEAD state, git branch --show-current returns empty string
+ // which our function converts to null
+ expect(getGitBranch()).toBeNull();
+ } catch (error) {
+ // Skip test if git operations fail
+ console.warn(
+ "Skipping detached HEAD test - git operations failed:",
+ error,
+ );
+ return;
+ }
+ });
+
+ it("should handle branch names with special characters", async () => {
+ process.chdir(context.testDir);
+
+ try {
+ // Initialize git repo
+ execSync("git init", { stdio: "ignore" });
+ execSync("git config user.email 'test@example.com'", {
+ stdio: "ignore",
+ });
+ execSync("git config user.name 'Test User'", { stdio: "ignore" });
+
+ // Create initial commit
+ await fs.writeFile(
+ path.join(context.testDir, "test.txt"),
+ "test content",
+ );
+ execSync("git add .", { stdio: "ignore" });
+ execSync("git commit -m 'Initial commit'", { stdio: "ignore" });
+
+ // Create branch with special characters
+ const specialBranchName = "feature/fix-123_with-dashes.and.dots";
+ execSync(`git checkout -b "${specialBranchName}"`, { stdio: "ignore" });
+
+ // Test git functions
+ const { getGitBranch } = await import("../util/git.js");
+ const branch = getGitBranch();
+ expect(branch).toBe(specialBranchName);
+ } catch (error) {
+ // Skip test if git operations fail
+ console.warn(
+ "Skipping special characters test - git operations failed:",
+ error,
+ );
+ return;
+ }
+ });
+ });
+
+ describe("getRepoUrlText function with branch", () => {
+ it("should format repo URL with branch correctly", async () => {
+ process.chdir(context.testDir);
+
+ try {
+ // Initialize git repo with remote
+ execSync("git init", { stdio: "ignore" });
+ execSync("git config user.email 'test@example.com'", {
+ stdio: "ignore",
+ });
+ execSync("git config user.name 'Test User'", { stdio: "ignore" });
+
+ // Add a fake remote
+ execSync(
+ "git remote add origin https://github.com/testuser/testrepo.git",
+ { stdio: "ignore" },
+ );
+
+ // Create initial commit and branch
+ await fs.writeFile(
+ path.join(context.testDir, "test.txt"),
+ "test content",
+ );
+ execSync("git add .", { stdio: "ignore" });
+ execSync("git commit -m 'Initial commit'", { stdio: "ignore" });
+ execSync("git checkout -b test-branch", { stdio: "ignore" });
+
+ // Test the formatting function
+ const { getResponsiveRepoText } = await import(
+ "../ui/hooks/useTUIChatHooks.js"
+ );
+ const repoText = getResponsiveRepoText();
+
+ // Should include both repo and branch
+ expect(repoText).toEqual("");
+ } catch (error) {
+ // Skip test if git operations fail
+ console.warn(
+ "Skipping repo URL formatting test - git operations failed:",
+ error,
+ );
+ return;
+ }
+ });
+
+ it("should handle repo URL without branch when not in git repo", async () => {
+ process.chdir(context.testDir);
+
+ // Test without git repo
+ const { getRepoUrlText } = await import("../ui/hooks/useTUIChatHooks.js");
+ const repoText = getRepoUrlText();
+
+ // Should not contain branch separator
+ expect(repoText).toEqual("");
+ });
+ });
+});
diff --git a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts
index a13823c69..ccb2437c9 100644
--- a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts
+++ b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts
@@ -8,8 +8,8 @@ import {
} from "../test-helpers/cli-helpers.js";
import {
cleanupMockLLMServer,
- type MockLLMServer,
createMockLLMServer,
+ type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
describe("E2E: Headless Mode with ANTHROPIC_API_KEY", () => {
@@ -80,9 +80,9 @@ models:
expect(userMessage.content).toBe("Hi there");
}, 20000);
- it("should create config and work with ANTHROPIC_API_KEY when no config exists", async () => {
+ it("should create config but fail with invalid API key when no config exists", async () => {
// This test verifies that CLI automatically creates config from ANTHROPIC_API_KEY
- // when no config file exists in headless mode
+ // when no config file exists, but fails when the API key is invalid
const result = await runCLI(context, {
args: ["-p", "test prompt"],
@@ -90,13 +90,17 @@ models:
ANTHROPIC_API_KEY: "TEST-test-invalid-key-format",
CONTINUE_GLOBAL_DIR: context.testDir + "/.continue",
},
- expectError: false, // Config creation succeeds even with invalid key
+ expectError: true, // API call should fail with invalid key
timeout: 15000,
});
- // The CLI should create config and exit successfully in headless mode
- // (it doesn't actually make API calls unless there's a valid provider setup)
- expect(result.exitCode).toBe(0);
+ // The CLI should create config but fail due to invalid API key
+ // This is expected behavior - invalid API keys should cause authentication errors
+ expect(result.exitCode).toBe(1);
+
+ // Should contain authentication error (not service initialization error)
+ expect(result.stderr).toContain("authentication_error");
+ expect(result.stderr).toContain("invalid x-api-key");
// Should NOT contain the old error about service initialization
expect(result.stderr).not.toContain("Failed to initialize ConfigService");
@@ -111,7 +115,7 @@ models:
if (configExists) {
const configContent = await fs.readFile(configPath, "utf-8");
- expect(configContent).toContain("anthropic/claude-4-sonnet");
+ expect(configContent).toContain("anthropic/claude-sonnet-4-5");
expect(configContent).toContain(
"ANTHROPIC_API_KEY: TEST-test-invalid-key-format",
);
diff --git a/extensions/cli/src/e2e/headless-permission-error.test.ts b/extensions/cli/src/e2e/headless-permission-error.test.ts
new file mode 100644
index 000000000..60a10d16f
--- /dev/null
+++ b/extensions/cli/src/e2e/headless-permission-error.test.ts
@@ -0,0 +1,209 @@
+/**
+ * E2E test for headless mode permission errors
+ * Verifies that when a tool requires permission in headless mode,
+ * an appropriate error message is displayed suggesting the --auto flag
+ */
+import * as http from "http";
+
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import {
+ cleanupTestContext,
+ createTestContext,
+ runCLI,
+} from "../test-helpers/cli-helpers.js";
+import {
+ cleanupMockLLMServer,
+ setupMockLLMTest,
+ type MockLLMServer,
+} from "../test-helpers/mock-llm-server.js";
+
+describe("E2E: Headless Mode Permission Errors", () => {
+ let context: any;
+ let mockServer: MockLLMServer;
+
+ beforeEach(async () => {
+ context = await createTestContext();
+ });
+
+ afterEach(async () => {
+ if (mockServer) {
+ await cleanupMockLLMServer(mockServer);
+ }
+ await cleanupTestContext(context);
+ });
+ it("should display error message with --auto suggestion when tool requires permission", async () => {
+ // Set up mock LLM to return a tool call that requires permission (Write tool)
+ mockServer = await setupMockLLMTest(context, {
+ customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => {
+ let body = "";
+ req.on("data", (chunk) => {
+ body += chunk.toString();
+ });
+
+ req.on("end", () => {
+ if (req.method === "POST" && req.url === "/chat/completions") {
+ res.writeHead(200, {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache",
+ Connection: "keep-alive",
+ });
+
+ // Send a Write tool call (requires permission by default)
+ res.write(
+ `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`,
+ );
+ res.write(
+ `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`,
+ );
+
+ // Send usage data
+ res.write(
+ `data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`,
+ );
+
+ // End the stream
+ res.write(`data: [DONE]\n\n`);
+ res.end();
+ } else {
+ res.writeHead(404);
+ res.end("Not found");
+ }
+ });
+ },
+ });
+
+ // Run CLI in headless mode without permission flags
+ const result = await runCLI(context, {
+ args: ["-p", "--config", context.configPath, "Create a file test.txt"],
+ timeout: 15000,
+ });
+
+ // Expect non-zero exit code
+ expect(result.exitCode).toBe(1);
+
+ // Verify the error message contains the expected information
+ expect(result.stderr).toContain("requires permission");
+ expect(result.stderr).toContain("headless mode");
+ expect(result.stderr).toContain("--auto");
+ expect(result.stderr).toContain("--allow");
+ expect(result.stderr).toContain("--exclude");
+ }, 20000);
+
+ it("should succeed with --auto flag when tool requires permission", async () => {
+ // Set up mock LLM to return a Write tool call
+ mockServer = await setupMockLLMTest(context, {
+ customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => {
+ let body = "";
+ req.on("data", (chunk) => {
+ body += chunk.toString();
+ });
+
+ req.on("end", () => {
+ if (req.method === "POST" && req.url === "/chat/completions") {
+ res.writeHead(200, {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache",
+ Connection: "keep-alive",
+ });
+
+ // Send a Write tool call
+ res.write(
+ `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`,
+ );
+ res.write(
+ `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`,
+ );
+
+ // Send usage data
+ res.write(
+ `data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`,
+ );
+
+ // End the stream
+ res.write(`data: [DONE]\n\n`);
+ res.end();
+ } else {
+ res.writeHead(404);
+ res.end("Not found");
+ }
+ });
+ },
+ });
+
+ // Run CLI with --auto flag
+ const result = await runCLI(context, {
+ args: [
+ "-p",
+ "--auto",
+ "--config",
+ context.configPath,
+ "Create a file test.txt",
+ ],
+ timeout: 15000,
+ });
+
+ // Should succeed
+ expect(result.exitCode).toBe(0);
+ expect(result.stderr).not.toContain("requires permission");
+ }, 20000);
+
+ it("should succeed with --allow flag for specific tool", async () => {
+ // Set up mock LLM to return a Write tool call
+ mockServer = await setupMockLLMTest(context, {
+ customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => {
+ let body = "";
+ req.on("data", (chunk) => {
+ body += chunk.toString();
+ });
+
+ req.on("end", () => {
+ if (req.method === "POST" && req.url === "/chat/completions") {
+ res.writeHead(200, {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache",
+ Connection: "keep-alive",
+ });
+
+ // Send a Write tool call
+ res.write(
+ `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`,
+ );
+ res.write(
+ `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`,
+ );
+
+ // Send usage data
+ res.write(
+ `data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`,
+ );
+
+ // End the stream
+ res.write(`data: [DONE]\n\n`);
+ res.end();
+ } else {
+ res.writeHead(404);
+ res.end("Not found");
+ }
+ });
+ },
+ });
+
+ // Run CLI with --allow Write flag
+ const result = await runCLI(context, {
+ args: [
+ "-p",
+ "--allow",
+ "Write",
+ "--config",
+ context.configPath,
+ "Create a file test.txt",
+ ],
+ timeout: 15000,
+ });
+
+ // Should succeed
+ expect(result.exitCode).toBe(0);
+ expect(result.stderr).not.toContain("requires permission");
+ }, 20000);
+});
diff --git a/extensions/cli/src/environment/environmentHandler.ts b/extensions/cli/src/environment/environmentHandler.ts
new file mode 100644
index 000000000..55afac91a
--- /dev/null
+++ b/extensions/cli/src/environment/environmentHandler.ts
@@ -0,0 +1,123 @@
+import { exec } from "child_process";
+import { existsSync, readFileSync } from "fs";
+import path from "path";
+import { promisify } from "util";
+
+import chalk from "chalk";
+
+const execAsync = promisify(exec);
+
+import { formatError } from "../util/formatError.js";
+import { logger } from "../util/logger.js";
+
+interface EnvironmentConfig {
+ install?: string;
+}
+
+const ENVIRONMENT_FILE_NAME = "environment.json";
+const ENVIRONMENT_SEARCH_PATHS = [".continue"];
+
+/**
+ * Finds and reads the environment.json file
+ */
+function findEnvironmentFile(): EnvironmentConfig | null {
+ for (const searchPath of ENVIRONMENT_SEARCH_PATHS) {
+ const environmentPath = path.join(
+ process.cwd(),
+ searchPath,
+ ENVIRONMENT_FILE_NAME,
+ );
+
+ if (existsSync(environmentPath)) {
+ try {
+ const content = readFileSync(environmentPath, "utf-8");
+ const config = JSON.parse(content) as EnvironmentConfig;
+ logger.debug(`Found environment.json at: ${environmentPath}`);
+ return config;
+ } catch (error) {
+ logger.error(
+ `Failed to parse environment.json at ${environmentPath}: ${formatError(error)}`,
+ );
+ return null;
+ }
+ }
+ }
+
+ logger.debug("No environment.json file found");
+ return null;
+}
+
+/**
+ * Runs the install script from environment.json if present
+ * Now runs asynchronously to avoid blocking server startup
+ */
+export async function runEnvironmentInstall(): Promise {
+ const environmentConfig = findEnvironmentFile();
+
+ if (!environmentConfig || !environmentConfig.install) {
+ logger.debug("No install script found in environment.json, skipping...");
+ return;
+ }
+
+ const installScript = environmentConfig.install;
+ logger.debug(
+ chalk.blue(
+ `\nRunning environment install script: ${chalk.dim(installScript)}`,
+ ),
+ );
+
+ try {
+ await execAsync(installScript, {
+ cwd: process.cwd(),
+ encoding: "utf-8",
+ });
+
+ logger.debug(
+ chalk.green("β Environment install script completed successfully"),
+ );
+ } catch (error) {
+ logger.error(`Environment install script failed: ${formatError(error)}`);
+ throw new Error(
+ `Failed to run environment install script: ${formatError(error)}`,
+ );
+ }
+}
+
+/**
+ * Runs the install script from environment.json if present, with error handling
+ * This version doesn't throw errors to avoid blocking server startup
+ */
+export async function runEnvironmentInstallSafe(): Promise {
+ const environmentConfig = findEnvironmentFile();
+
+ if (!environmentConfig || !environmentConfig.install) {
+ logger.debug("No environment install script to run");
+ return;
+ }
+
+ logger.debug(
+ chalk.blue("Running environment install script in background..."),
+ );
+
+ try {
+ await runEnvironmentInstall();
+ logger.debug(
+ chalk.green("β Environment install script completed successfully"),
+ );
+ } catch (error) {
+ logger.error(
+ chalk.yellow("Warning: Environment install script failed:"),
+ formatError(error),
+ );
+ logger.error(
+ chalk.dim("Server will continue to run without the install script."),
+ );
+ }
+}
+
+/**
+ * Gets the environment configuration if available
+ */
+export function getEnvironmentConfig(): EnvironmentConfig | null {
+ return findEnvironmentFile();
+}
diff --git a/extensions/cli/src/flags/flagValidator.ts b/extensions/cli/src/flags/flagValidator.ts
index 60e084a10..2c5790b5a 100644
--- a/extensions/cli/src/flags/flagValidator.ts
+++ b/extensions/cli/src/flags/flagValidator.ts
@@ -16,6 +16,10 @@ export interface ValidationOptions {
auto?: boolean;
config?: string;
+ // Session flags
+ resume?: boolean;
+ fork?: string;
+
// Permission flags
allow?: string[];
ask?: string[];
@@ -101,6 +105,29 @@ function validateModeFlags(options: ValidationOptions): ValidationError[] {
return errors;
}
+/**
+ * Validate session flags
+ */
+function validateSessionFlags(options: ValidationOptions): ValidationError[] {
+ const errors: ValidationError[] = [];
+
+ if (options.resume && options.fork) {
+ errors.push({
+ code: "CONFLICTING_SESSION_FLAGS",
+ message: "Error: Cannot use both --resume and --fork flags together",
+ });
+ }
+
+ if (options.fork !== undefined && (!options.fork || !options.fork.trim())) {
+ errors.push({
+ code: "FORK_REQUIRES_SESSION_ID",
+ message: "Error: --fork requires a session ID (e.g., --fork abc123)",
+ });
+ }
+
+ return errors;
+}
+
/**
* Validate config path exists (basic check)
*/
@@ -164,6 +191,7 @@ export function validateFlags(options: ValidationOptions): ValidationResult {
validateSilentFlag,
validateFormatValue,
validateModeFlags,
+ validateSessionFlags,
validateConfigPath,
validatePermissionFlags,
];
@@ -191,5 +219,7 @@ export function handleValidationErrors(errors: ValidationError[]): never {
safeStderr(`\nFound ${errors.length} validation errors.\n`);
}
- process.exit(1);
+ // Use async graceful exit without awaiting (we must satisfy never)
+ import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1));
+ throw new Error("Exiting due to validation errors");
}
diff --git a/extensions/cli/src/freeTrialTransition.ts b/extensions/cli/src/freeTrialTransition.ts
index 2a2514c89..f7b7eee69 100644
--- a/extensions/cli/src/freeTrialTransition.ts
+++ b/extensions/cli/src/freeTrialTransition.ts
@@ -4,13 +4,14 @@ import * as path from "path";
import chalk from "chalk";
import open from "open";
-import * as readlineSync from "readline-sync";
import { env } from "./env.js";
import {
- isValidAnthropicApiKey,
getApiKeyValidationError,
+ isValidAnthropicApiKey,
} from "./util/apiKeyValidation.js";
+import { gracefulExit } from "./util/exit.js";
+import { question, questionWithChoices } from "./util/prompt.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
@@ -51,10 +52,12 @@ export async function handleMaxedOutFreeTrial(
console.log(chalk.white("1. π³ Sign up for models add-on"));
console.log(chalk.white("2. π Enter your Anthropic API key"));
- const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), {
- limit: ["1", "2", ""],
- limitMessage: chalk.dim("Please enter 1 or 2"),
- });
+ const choice = await questionWithChoices(
+ chalk.yellow("\nEnter choice (1): "),
+ ["1", "2", ""],
+ "1",
+ chalk.dim("Please enter 1 or 2"),
+ );
if (choice === "1" || choice === "") {
// Option 1: Open models setup page
@@ -80,20 +83,17 @@ export async function handleMaxedOutFreeTrial(
}
// Wait for user to acknowledge
- readlineSync.question(chalk.dim("\nPress Enter to exit..."));
- process.exit(0);
+ await question(chalk.dim("\nPress Enter to exit..."));
+ await gracefulExit(0);
} else if (choice === "2") {
// Option 2: Enter Anthropic API key
- const apiKey = readlineSync.question(
+ const apiKey = await question(
chalk.white("\nEnter your Anthropic API key: "),
- {
- hideEchoBack: true,
- },
);
if (!isValidAnthropicApiKey(apiKey)) {
console.log(chalk.red(`β ${getApiKeyValidationError(apiKey)}`));
- process.exit(1);
+ await gracefulExit(1);
}
try {
@@ -108,7 +108,7 @@ export async function handleMaxedOutFreeTrial(
}
} catch (error) {
console.log(chalk.red(`β Error saving API key: ${error}`));
- process.exit(1);
+ await gracefulExit(1);
}
}
@@ -137,5 +137,5 @@ export async function handleMaxedOutFreeTrial(
child.unref();
// Exit the current process
- process.exit(0);
+ await gracefulExit(0);
}
diff --git a/extensions/cli/src/hooks/useService.ts b/extensions/cli/src/hooks/useService.ts
index dcbbd57b8..d659652f4 100644
--- a/extensions/cli/src/hooks/useService.ts
+++ b/extensions/cli/src/hooks/useService.ts
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { useServiceContainer } from "../services/ServiceContainerContext.js";
import { ServiceResult } from "../services/types.js";
@@ -96,47 +96,54 @@ export function useServices>(
allReady: boolean;
} {
const container = useServiceContainer();
- const [services, setServices] = useState>({});
+
+ const getServiceStates = useCallback(() => {
+ const services: Partial = {};
+ let hasLoading = false;
+ let hasError: Error | null = null;
+
+ for (const serviceName of serviceNames) {
+ const result = container.getSync(serviceName as string);
+
+ if (result.state === "loading") {
+ hasLoading = true;
+ } else if (result.state === "error") {
+ hasError = result.error;
+ } else if (result.state === "idle") {
+ // Auto-load idle services
+ container.load(serviceName as string).catch(() => {});
+ } else if (result.state === "ready" && result.value !== null) {
+ services[serviceName] = result.value as T[keyof T];
+ } else {
+ }
+ }
+
+ return {
+ hasLoading,
+ hasError,
+ services,
+ };
+ }, [serviceNames, container]);
+
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
+ const [services, setServices] = useState>(
+ getServiceStates().services,
+ );
useEffect(() => {
- const updateState = () => {
- const newServices: Partial = {};
- let hasLoading = false;
- let hasError: Error | null = null;
-
- for (const serviceName of serviceNames) {
- const result = container.getSync(serviceName as string);
-
- if (result.state === "loading") {
- hasLoading = true;
- } else if (result.state === "error") {
- hasError = result.error;
- } else if (result.state === "idle") {
- // Auto-load idle services
- container.load(serviceName as string).catch(() => {});
- } else if (result.state === "ready" && result.value !== null) {
- newServices[serviceName] = result.value as T[keyof T];
- } else {
- }
- }
-
- setServices(newServices);
- setLoading(hasLoading);
- setError(hasError);
- };
-
- // Initial state
- updateState();
-
// Set up listeners for all services
const listeners: Array<() => void> = [];
for (const serviceName of serviceNames) {
const name = serviceName as string;
- const onAnyChange = () => updateState();
+ const onAnyChange = () => {
+ const { hasLoading, hasError, services } = getServiceStates();
+ setLoading(hasLoading);
+ setError(hasError);
+ setServices(services);
+ };
container.on(`${name}:loading`, onAnyChange);
container.on(`${name}:ready`, onAnyChange);
@@ -155,7 +162,7 @@ export function useServices>(
return () => {
listeners.forEach((cleanup) => cleanup());
};
- }, [serviceNames.join(","), container]);
+ }, [serviceNames.join(","), container, getServiceStates]);
const allReady = serviceNames.every((name) =>
container.isReady(name as string),
diff --git a/extensions/cli/src/hubLoader.test.ts b/extensions/cli/src/hubLoader.test.ts
index b19d32f97..542f34556 100644
--- a/extensions/cli/src/hubLoader.test.ts
+++ b/extensions/cli/src/hubLoader.test.ts
@@ -1,12 +1,15 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import {
+import * as hubLoader from "./hubLoader.js";
+
+const {
loadPackageFromHub,
mcpProcessor,
modelProcessor,
promptProcessor,
ruleProcessor,
-} from "./hubLoader.js";
+ processRule,
+} = hubLoader;
// Store the original fetch before any mocking
const originalFetch = global.fetch;
@@ -136,6 +139,46 @@ describe("hubLoader", () => {
});
});
+ describe("processRule", () => {
+ beforeEach(() => {
+ // Ensure mocks are set up properly for processRule tests
+ global.fetch = mockFetch;
+ });
+
+ it("should treat multi-line strings as inline rules", async () => {
+ const loadRuleSpy = vi
+ .spyOn(hubLoader, "loadRuleFromHub")
+ .mockResolvedValue("hub-content");
+
+ const multilineRule = "Line one\nEnsure /tmp is ignored\nFinal line";
+ const result = await processRule(multilineRule);
+
+ expect(result).toBe(multilineRule);
+ expect(loadRuleSpy).not.toHaveBeenCalled();
+
+ loadRuleSpy.mockRestore();
+ });
+
+ it("should still treat owner/package strings as hub slugs", async () => {
+ // Mock fetch to return a proper response for this test
+ const JSZip = (await import("jszip")).default;
+ const zip = new JSZip();
+ zip.file("rule.md", "hub-content");
+ const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
+
+ mockFetch.mockResolvedValueOnce({
+ ok: true,
+ arrayBuffer: () => Promise.resolve(zipBuffer),
+ } as Response);
+
+ const slug = "owner/package";
+ const result = await processRule(slug);
+
+ expect(result).toBe("hub-content");
+ expect(mockFetch).toHaveBeenCalled();
+ });
+ });
+
describe("processors", () => {
it("should define rule processor correctly", () => {
expect(ruleProcessor.type).toBe("rule");
diff --git a/extensions/cli/src/hubLoader.ts b/extensions/cli/src/hubLoader.ts
index 0a6e39756..006cda7a8 100644
--- a/extensions/cli/src/hubLoader.ts
+++ b/extensions/cli/src/hubLoader.ts
@@ -1,12 +1,18 @@
+import { parseWorkflowFile, WorkflowFile } from "@continuedev/config-yaml";
import JSZip from "jszip";
import { env } from "./env.js";
import { logger } from "./util/logger.js";
+/**
+ * Pattern to match valid hub slugs (owner/package format)
+ */
+const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
+
/**
* Hub package type definitions
*/
-export type HubPackageType = "rule" | "mcp" | "model" | "prompt";
+export type HubPackageType = "rule" | "mcp" | "model" | "prompt" | "workflow";
/**
* Hub package processor interface
@@ -94,6 +100,15 @@ export const promptProcessor: HubPackageProcessor = {
parseContent: (content: string) => content,
};
+export const workflowProcessor: HubPackageProcessor = {
+ type: "workflow",
+ expectedFileExtensions: [".md"],
+ parseContent: (content: string) => parseWorkflowFile(content),
+ validateContent: (workflowFile: WorkflowFile) => {
+ return !!workflowFile.name;
+ },
+};
+
/**
* Generic hub package loader
*/
@@ -220,28 +235,23 @@ export const loadPromptFromHub = (slug: string) =>
* Process a rule specification - supports file paths, hub slugs, or direct content
*/
export async function processRule(ruleSpec: string): Promise {
- // If it looks like a hub slug (contains / but doesn't start with . or /)
- if (
- ruleSpec.includes("/") &&
- !ruleSpec.startsWith(".") &&
- !ruleSpec.startsWith("/")
- ) {
- return await loadRuleFromHub(ruleSpec);
- }
+ const trimmedRuleSpec = ruleSpec.trim();
+ const hasNewline = /[\r\n]/.test(ruleSpec);
- // If it looks like a file path
- if (
- ruleSpec.startsWith(".") ||
- ruleSpec.startsWith("/") ||
- ruleSpec.includes("/") ||
- ruleSpec.includes("\\") ||
- /\.[a-zA-Z]+$/.test(ruleSpec) // Has file extension at the end
- ) {
+ // If it looks like a file path (single line, typical path indicators)
+ const looksLikePath =
+ !hasNewline &&
+ (trimmedRuleSpec.startsWith(".") ||
+ trimmedRuleSpec.startsWith("/") ||
+ trimmedRuleSpec.includes("\\") ||
+ /\.[a-zA-Z]+$/.test(trimmedRuleSpec));
+
+ if (looksLikePath) {
const fs = await import("fs");
const path = await import("path");
try {
- const absolutePath = path.resolve(ruleSpec);
+ const absolutePath = path.resolve(trimmedRuleSpec);
if (!fs.existsSync(absolutePath)) {
throw new Error(`Rule file not found: ${ruleSpec}`);
}
@@ -253,6 +263,23 @@ export async function processRule(ruleSpec: string): Promise {
}
}
+ // Check if it might be a hub slug (contains "/" and is a single line)
+ if (!hasNewline && trimmedRuleSpec.includes("/")) {
+ const parts = trimmedRuleSpec.split("/");
+
+ // If it's exactly 2 parts and matches hub slug pattern, treat as hub slug
+ if (parts.length === 2 && HUB_SLUG_PATTERN.test(trimmedRuleSpec)) {
+ return await loadRuleFromHub(trimmedRuleSpec);
+ }
+
+ // If it has more than 2 parts, it's an invalid hub slug
+ if (parts.length > 2) {
+ throw new Error(
+ `Invalid hub slug format. Expected "owner/package", got: ${trimmedRuleSpec}`,
+ );
+ }
+ }
+
// Otherwise, treat it as direct string content
return ruleSpec;
}
diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts
index 1d2da1cb9..4946604dd 100644
--- a/extensions/cli/src/index.ts
+++ b/extensions/cli/src/index.ts
@@ -19,10 +19,76 @@ import {
import { configureConsoleForHeadless, safeStderr } from "./init.js";
import { sentryService } from "./sentry.js";
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
+import { posthogService } from "./telemetry/posthogService.js";
+import { gracefulExit } from "./util/exit.js";
import { logger } from "./util/logger.js";
import { readStdinSync } from "./util/stdin.js";
import { getVersion } from "./version.js";
+// TUI lifecycle and two-stage exit state management
+let tuiUnmount: (() => void) | null;
+let showExitMessage: boolean;
+let exitMessageCallback: (() => void) | null;
+let lastCtrlCTime: number;
+
+// Initialize state immediately to avoid temporal dead zone issues with exported functions
+(function initializeTUIState() {
+ tuiUnmount = null;
+ showExitMessage = false;
+ exitMessageCallback = null;
+ lastCtrlCTime = 0;
+})();
+
+// Register TUI cleanup function for graceful shutdown
+export function setTUIUnmount(unmount: () => void) {
+ tuiUnmount = unmount;
+}
+
+// Register callback to trigger UI updates when exit message state changes
+export function setExitMessageCallback(callback: () => void) {
+ exitMessageCallback = callback;
+}
+
+// Sets up SIGINT handler that requires double Ctrl+C within 1 second to exit
+export function enableSigintHandler() {
+ // Remove all existing SIGINT listeners first
+ process.removeAllListeners("SIGINT");
+
+ process.on("SIGINT", async () => {
+ const now = Date.now();
+ const timeSinceLastCtrlC = now - lastCtrlCTime;
+
+ if (timeSinceLastCtrlC <= 1000 && lastCtrlCTime !== 0) {
+ // Second Ctrl+C within 1 second - exit
+ showExitMessage = false;
+ if (tuiUnmount) {
+ tuiUnmount();
+ }
+ await gracefulExit(0);
+ } else {
+ // First Ctrl+C or too much time elapsed - show exit message
+ lastCtrlCTime = now;
+ showExitMessage = true;
+ if (exitMessageCallback) {
+ exitMessageCallback();
+ }
+
+ // Hide message after 1 second
+ setTimeout(() => {
+ showExitMessage = false;
+ if (exitMessageCallback) {
+ exitMessageCallback();
+ }
+ }, 1000);
+ }
+ });
+}
+
+// Check if "ctrl+c to exit" message should be displayed
+export function shouldShowExitMessage(): boolean {
+ return showExitMessage;
+}
+
// Add global error handlers to prevent uncaught errors from crashing the process
process.on("unhandledRejection", (reason, promise) => {
logger.error("Unhandled Rejection at:", { promise, reason });
@@ -41,6 +107,11 @@ process.on("uncaughtException", (error) => {
// Don't exit the process, just log the error
});
+// keyboard interruption handler for non-TUI flows
+process.on("SIGINT", async () => {
+ await gracefulExit(130);
+});
+
const program = new Command();
program
@@ -48,7 +119,7 @@ program
.description(
"Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output.",
)
- .version(getVersion());
+ .version(getVersion(), "-v, --version", "Display version number");
// Root command - chat functionality (default)
// Add common options to the root command
@@ -64,7 +135,10 @@ addCommonOptions(program)
"Strip tags and excess whitespace from output. Only works with -p/--print flag.",
)
.option("--resume", "Resume from last session")
+ .option("--fork ", "Fork from an existing session ID")
.action(async (prompt, options) => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "cn" });
// Handle piped input - detect it early and decide on mode
let stdinInput = null;
@@ -100,6 +174,8 @@ addCommonOptions(program)
readonly: options.readonly,
auto: options.auto,
config: options.config,
+ resume: options.resume,
+ fork: options.fork,
allow: options.allow,
ask: options.ask,
exclude: options.exclude,
@@ -149,7 +225,7 @@ addCommonOptions(program)
safeStderr(' cn -p "please review my current git diff"\n');
safeStderr(' echo "hello" | cn -p\n');
safeStderr(' cn -p "analyze the code in src/"\n');
- process.exit(1);
+ await gracefulExit(1);
}
// Map --print to headless mode
@@ -163,6 +239,8 @@ program
.command("login")
.description("Authenticate with Continue")
.action(async () => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "login" });
await login();
});
@@ -171,6 +249,8 @@ program
.command("logout")
.description("Log out from Continue")
.action(async () => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "logout" });
await logout();
});
@@ -180,19 +260,27 @@ program
.description("List recent chat sessions and select one to resume")
.option("--json", "Output in JSON format")
.action(async (options) => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "ls" });
await listSessionsCommand({
format: options.json ? "json" : undefined,
});
});
// Remote subcommand
-program
- .command("remote [prompt]", { hidden: true })
- .description("Launch a remote instance of the cn agent")
+addCommonOptions(
+ program
+ .command("remote [prompt]", { hidden: true })
+ .description("Launch a remote instance of the cn agent"),
+)
.option(
"--url ",
"Connect directly to the specified URL instead of creating a new remote environment",
)
+ .option(
+ "--id ",
+ "Connect to an existing remote agent by id and establish a tunnel",
+ )
.option(
"--idempotency-key ",
"Idempotency key for session management - allows resuming existing sessions",
@@ -210,6 +298,11 @@ program
"Specify the repository URL to use in the remote environment",
)
.action(async (prompt: string | undefined, options) => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", {
+ command: "remote",
+ flagS: options.start,
+ });
await remote(prompt, options);
});
@@ -223,7 +316,13 @@ program
"300",
)
.option("--port ", "Port to run the server on (default: 8000)", "8000")
+ .option(
+ "--id ",
+ "Upload session snapshots to Continue-managed storage using the provided identifier",
+ )
.action(async (prompt, options) => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "serve" });
// Merge parent options with subcommand options
const mergedOptions = mergeParentOptions(program, options);
@@ -241,6 +340,8 @@ program
.description("Test remote TUI mode with a local server")
.option("--url ", "Server URL (default: http://localhost:8000)")
.action(async (prompt: string | undefined, options) => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "remote-test" });
await remoteTest(prompt, options.url);
});
@@ -248,27 +349,22 @@ program
program.on("command:*", () => {
console.error(`Error: Unknown command '${program.args.join(" ")}'\n`);
program.outputHelp();
- process.exit(1);
+ void gracefulExit(1);
});
-// Parse arguments and handle errors
-try {
- program.parse();
-} catch (error) {
- console.error(error);
- sentryService.captureException(
- error instanceof Error ? error : new Error(String(error)),
- );
- process.exit(1);
+export async function runCli(): Promise {
+ // Parse arguments and handle errors
+ try {
+ program.parse();
+ } catch (error) {
+ console.error(error);
+ sentryService.captureException(
+ error instanceof Error ? error : new Error(String(error)),
+ );
+ process.exit(1);
+ }
+
+ process.on("SIGTERM", async () => {
+ await gracefulExit(0);
+ });
}
-
-// Graceful shutdown - flush Sentry data
-process.on("SIGINT", async () => {
- await sentryService.flush();
- process.exit(0);
-});
-
-process.on("SIGTERM", async () => {
- await sentryService.flush();
- process.exit(0);
-});
diff --git a/extensions/cli/src/infoScreen.ts b/extensions/cli/src/infoScreen.ts
new file mode 100644
index 000000000..fc495c94c
--- /dev/null
+++ b/extensions/cli/src/infoScreen.ts
@@ -0,0 +1,133 @@
+import { execSync } from "child_process";
+
+import chalk from "chalk";
+
+import {
+ isAuthenticated,
+ isAuthenticatedConfig,
+ loadAuthConfig,
+} from "./auth/workos.js";
+import { services } from "./services/index.js";
+import { getCurrentSession, getSessionFilePath } from "./session.js";
+import { logger } from "./util/logger.js";
+import { getVersion } from "./version.js";
+
+export async function handleInfoSlashCommand() {
+ const infoLines = [];
+
+ // Version and working directory info
+ const version = getVersion();
+ const cwd = process.cwd();
+
+ infoLines.push(
+ chalk.white("CLI Information:"),
+ ` Version: ${chalk.green(version)}`,
+ ` Working Directory: ${chalk.blue(cwd)}`,
+ );
+
+ // Auth info
+ if (isAuthenticated()) {
+ const config = loadAuthConfig();
+ if (config && isAuthenticatedConfig(config)) {
+ const email = config.userEmail || config.userId;
+ const orgId = config.organizationId;
+ infoLines.push(
+ "",
+ chalk.white("Authentication:"),
+ ` Email: ${chalk.green(email)}`,
+ ` Org ID: ${chalk.cyan(orgId)}`,
+ );
+ } else {
+ infoLines.push(
+ "",
+ chalk.white("Authentication:"),
+ ` ${chalk.yellow("Authenticated via environment variable")}`,
+ );
+ }
+ } else {
+ infoLines.push(
+ "",
+ chalk.white("Authentication:"),
+ ` ${chalk.red("Not logged in")}`,
+ );
+ }
+
+ // Config info
+ try {
+ const configState = services.config.getState();
+ infoLines.push("", chalk.white("Configuration:"));
+ if (configState.config) {
+ infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`);
+ } else {
+ infoLines.push(` ${chalk.red(`Config not found`)}`);
+ }
+ if (configState.configPath) {
+ infoLines.push(` Path: ${chalk.blue(configState.configPath)}`);
+ }
+
+ // Add current model info
+ try {
+ const modelInfo = services.model?.getModelInfo();
+ if (modelInfo) {
+ infoLines.push(` Model: ${chalk.cyan(modelInfo.name)}`);
+ } else {
+ infoLines.push(` Model: ${chalk.red("Not available")}`);
+ }
+ } catch {
+ infoLines.push(` Model: ${chalk.red("Error retrieving model info")}`);
+ }
+ } catch {
+ infoLines.push(
+ "",
+ chalk.white("Configuration:"),
+ ` ${chalk.red("Configuration service not available")}`,
+ );
+ }
+
+ // Session info
+ infoLines.push("", chalk.white("Session:"));
+ try {
+ const currentSession = getCurrentSession();
+ const sessionFilePath = getSessionFilePath();
+ infoLines.push(
+ ` Title: ${chalk.green(currentSession.title)}`,
+ ` ID: ${chalk.gray(currentSession.sessionId)}`,
+ ` File: ${chalk.blue(sessionFilePath)}`,
+ );
+ } catch {
+ infoLines.push(` ${chalk.red("Session not available")}`);
+ }
+
+ // Runtime diagnostic info
+ const nodePath = process.execPath;
+ const invokedPath = process.argv[1];
+
+ // Get npm version
+ let npmVersion = "unknown";
+ try {
+ npmVersion = execSync("npm --version", {
+ encoding: "utf8",
+ timeout: 5000,
+ stdio: ["pipe", "pipe", "ignore"],
+ }).trim();
+ } catch (error) {
+ // If npm command fails, fallback to "unknown"
+ logger.warn("Failed to get npm version:", error);
+ }
+
+ // Diagnostic info
+ infoLines.push(
+ "",
+ chalk.white("Diagnostic Info"),
+ ` Currently running: npm-global (${chalk.green(npmVersion)})`,
+ ` Path: ${chalk.blue(nodePath)}`,
+ ` Invoked: ${chalk.blue(invokedPath)}`,
+ );
+
+ // TODO add global settings like auto update etc.
+
+ return {
+ exit: false,
+ output: infoLines.join("\n"),
+ };
+}
diff --git a/extensions/cli/src/init.ts b/extensions/cli/src/init.ts
index 47766c0bb..809400492 100644
--- a/extensions/cli/src/init.ts
+++ b/extensions/cli/src/init.ts
@@ -3,10 +3,11 @@
* This file intercepts console and stdout/stderr to prevent dependency logging
*/
+import { isHeadlessMode as checkIsHeadlessMode } from "./util/cli.js";
+
// Check if we're in headless mode by looking at process arguments
// We need to do this before any imports to catch early logging
-const args = process.argv.slice(2);
-const isHeadlessMode = args.includes("-p") || args.includes("--print");
+const isHeadlessMode = checkIsHeadlessMode();
// Store original methods before ANY dependencies can use them
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
diff --git a/extensions/cli/src/integration/model-persistence-e2e.test.ts b/extensions/cli/src/integration/model-persistence-e2e.test.ts
new file mode 100644
index 000000000..22354c989
--- /dev/null
+++ b/extensions/cli/src/integration/model-persistence-e2e.test.ts
@@ -0,0 +1,205 @@
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+
+import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import {
+ AuthenticatedConfig,
+ getModelName,
+ loadAuthConfig,
+ saveAuthConfig,
+ updateModelName,
+} from "../auth/workos.js";
+import * as config from "../config.js";
+import { ModelService } from "../services/ModelService.js";
+import { persistModelName } from "../util/modelPersistence.js";
+
+// Mock the config module
+vi.mock("../config.js");
+
+describe("Model Persistence End-to-End", () => {
+ let testDir: string;
+ let originalContinueHome: string | undefined;
+ let mockAssistant: AssistantUnrolled;
+ let mockAuthConfig: AuthenticatedConfig;
+ const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ // Create a temporary directory for testing
+ testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
+ originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
+ process.env.CONTINUE_GLOBAL_DIR = testDir;
+
+ // Clear GlobalContext for clean test state
+ persistModelName(null);
+
+ mockAssistant = {
+ name: "test-assistant",
+ version: "1.0.0",
+ models: [
+ {
+ provider: "openai",
+ model: "gpt-4",
+ name: "GPT-4",
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ {
+ provider: "anthropic",
+ model: "claude-3-5-sonnet-20241022",
+ name: "Claude 3.5 Sonnet",
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ {
+ provider: "anthropic",
+ model: "claude-3-opus-20240229",
+ name: "Claude 3 Opus",
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ ],
+ } as AssistantUnrolled;
+
+ mockAuthConfig = {
+ userId: "test-user",
+ userEmail: "test@example.com",
+ accessToken: "test-token",
+ refreshToken: "test-refresh",
+ expiresAt: Date.now() + 3600000, // 1 hour from now
+ organizationId: "test-org",
+ };
+
+ // Setup default mock behavior
+ vi.mocked(config.getLlmApi).mockReturnValue([
+ mockLlmApi as any,
+ mockAssistant.models![0] as ModelConfig,
+ ]);
+ vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
+ });
+
+ afterEach(() => {
+ // Cleanup
+ if (fs.existsSync(testDir)) {
+ fs.rmSync(testDir, { recursive: true });
+ }
+ if (originalContinueHome) {
+ process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
+ } else {
+ delete process.env.CONTINUE_GLOBAL_DIR;
+ }
+ });
+
+ test("should restore model selection after restart", async () => {
+ // Step 1: Initial session - user starts with default model (GPT-4)
+ saveAuthConfig(mockAuthConfig);
+ let service = new ModelService();
+ let state = await service.initialize(mockAssistant, mockAuthConfig);
+
+ console.log("Initial model:", state.model?.name);
+ expect(state.model?.name).toBe("GPT-4");
+
+ // Step 2: User switches to Claude 3.5 Sonnet (index 1)
+ await service.switchModel(1);
+ state = service.getState();
+
+ console.log("After switch:", state.model?.name);
+ expect(state.model?.name).toBe("Claude 3.5 Sonnet");
+
+ // Step 3: Persist the model choice (this should happen in useModelSelector)
+ updateModelName("Claude 3.5 Sonnet");
+
+ // Verify it was saved to auth.json
+ const savedConfig = loadAuthConfig();
+ console.log("Saved model name:", getModelName(savedConfig));
+ expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet");
+
+ // Step 4: Simulate restart - create new service instance
+ // Load fresh auth config from disk (this is what the real code does)
+ const freshAuthConfig = loadAuthConfig();
+ console.log("Fresh auth config model name:", getModelName(freshAuthConfig));
+
+ service = new ModelService();
+ state = await service.initialize(mockAssistant, freshAuthConfig);
+
+ // Step 5: Verify the persisted model is restored
+ console.log("After restart:", state.model?.name);
+ expect(state.model?.name).toBe("Claude 3.5 Sonnet");
+ expect(state.model?.provider).toBe("anthropic");
+ });
+
+ test("should handle model name mismatch gracefully", async () => {
+ // Save auth config with a model that doesn't exist
+ mockAuthConfig.modelName = "Non-existent Model";
+ saveAuthConfig(mockAuthConfig);
+
+ const service = new ModelService();
+ const state = await service.initialize(mockAssistant, mockAuthConfig);
+
+ // Should fall back to first available model (GPT-4)
+ expect(state.model?.name).toBe("GPT-4");
+ });
+
+ test("should check both name and model fields when matching", async () => {
+ // Some configs might have model field instead of name
+ const assistantWithModelField = {
+ ...mockAssistant,
+ models: [
+ {
+ provider: "openai",
+ model: "gpt-4",
+ // No name field, just model
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ {
+ provider: "anthropic",
+ model: "claude-3-5-sonnet-20241022",
+ // No name field, just model
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ ],
+ } as AssistantUnrolled;
+
+ mockAuthConfig.modelName = "claude-3-5-sonnet-20241022";
+ saveAuthConfig(mockAuthConfig);
+
+ const service = new ModelService();
+ const state = await service.initialize(
+ assistantWithModelField,
+ mockAuthConfig,
+ );
+
+ // Should match by model field
+ expect(state.model?.model).toBe("claude-3-5-sonnet-20241022");
+ });
+
+ test("should persist model through multiple switches", async () => {
+ saveAuthConfig(mockAuthConfig);
+ const service = new ModelService();
+ await service.initialize(mockAssistant, mockAuthConfig);
+
+ // Switch to Claude 3.5 Sonnet
+ await service.switchModel(1);
+ updateModelName("Claude 3.5 Sonnet");
+ expect(getModelName(loadAuthConfig())).toBe("Claude 3.5 Sonnet");
+
+ // Switch to Claude 3 Opus
+ await service.switchModel(2);
+ updateModelName("Claude 3 Opus");
+ expect(getModelName(loadAuthConfig())).toBe("Claude 3 Opus");
+
+ // Restart and verify last selection
+ const freshAuthConfig = loadAuthConfig();
+ console.log("Fresh auth config model name:", getModelName(freshAuthConfig));
+
+ const newService = new ModelService();
+ const state = await newService.initialize(mockAssistant, freshAuthConfig);
+ expect(state.model?.name).toBe("Claude 3 Opus");
+ });
+});
diff --git a/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts b/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts
new file mode 100644
index 000000000..db4b30ee4
--- /dev/null
+++ b/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts
@@ -0,0 +1,245 @@
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+
+import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import {
+ getModelName,
+ loadAuthConfig,
+ updateModelName,
+} from "../auth/workos.js";
+import * as config from "../config.js";
+import { ModelService } from "../services/ModelService.js";
+import {
+ getPersistedModelName,
+ persistModelName,
+} from "../util/modelPersistence.js";
+
+// Mock the config module
+vi.mock("../config.js");
+
+describe("Model Persistence for Unauthenticated Users", () => {
+ let testDir: string;
+ let originalContinueHome: string | undefined;
+ let mockAssistant: AssistantUnrolled;
+ const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ // Create a temporary directory for testing
+ testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
+ originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
+ process.env.CONTINUE_GLOBAL_DIR = testDir;
+
+ // Clear GlobalContext for clean test state
+ persistModelName(null);
+
+ mockAssistant = {
+ name: "test-assistant",
+ version: "1.0.0",
+ models: [
+ {
+ provider: "openai",
+ model: "gpt-4",
+ name: "GPT-4",
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ {
+ provider: "anthropic",
+ model: "claude-3-5-sonnet-20241022",
+ name: "Claude 3.5 Sonnet",
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ {
+ provider: "anthropic",
+ model: "claude-3-opus-20240229",
+ name: "Claude 3 Opus",
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ ],
+ } as AssistantUnrolled;
+
+ // Setup default mock behavior
+ vi.mocked(config.getLlmApi).mockReturnValue([
+ mockLlmApi as any,
+ mockAssistant.models![0] as ModelConfig,
+ ]);
+ vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
+ });
+
+ afterEach(() => {
+ // Cleanup
+ if (fs.existsSync(testDir)) {
+ fs.rmSync(testDir, { recursive: true });
+ }
+ if (originalContinueHome) {
+ process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
+ } else {
+ delete process.env.CONTINUE_GLOBAL_DIR;
+ }
+ });
+
+ test("should persist model selection for logged-out users", () => {
+ // User is logged out (no auth config)
+ const authConfig = loadAuthConfig();
+ expect(authConfig).toBeNull();
+
+ // User switches model
+ updateModelName("Claude 3.5 Sonnet");
+
+ // Verify it was saved to GlobalContext
+ const persistedModel = getPersistedModelName();
+ expect(persistedModel).toBe("Claude 3.5 Sonnet");
+
+ // Verify getModelName returns it for null config
+ expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
+ });
+
+ test("should restore model selection on next session for logged-out users", async () => {
+ // Session 1: User is logged out and switches model
+ const authConfig = loadAuthConfig();
+ expect(authConfig).toBeNull();
+
+ const modelService = new ModelService();
+ await modelService.initialize(mockAssistant, authConfig);
+
+ await modelService.switchModel(1);
+ updateModelName("Claude 3.5 Sonnet");
+
+ // Session 2: User reopens CLI (still logged out)
+ const newAuthConfig = loadAuthConfig();
+ expect(newAuthConfig).toBeNull();
+
+ const newModelService = new ModelService();
+ const state = await newModelService.initialize(
+ mockAssistant,
+ newAuthConfig,
+ );
+
+ // Should restore Claude 3.5 Sonnet
+ expect(state.model?.name).toBe("Claude 3.5 Sonnet");
+ });
+
+ test("should handle multiple model switches for logged-out users", () => {
+ updateModelName("GPT-4");
+ expect(getModelName(null)).toBe("GPT-4");
+
+ updateModelName("Claude 3.5 Sonnet");
+ expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
+
+ updateModelName("Claude 3 Opus");
+ expect(getModelName(null)).toBe("Claude 3 Opus");
+ });
+
+ test("should clear model selection when set to null", () => {
+ updateModelName("Claude 3.5 Sonnet");
+ expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
+
+ updateModelName(null);
+ expect(getModelName(null)).toBeNull();
+ });
+
+ test("should preserve GlobalContext model when user logs in", () => {
+ // User is logged out with a persisted model
+ updateModelName("Claude 3.5 Sonnet");
+ expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
+
+ // User logs in (simulated by having auth.json)
+ const authPath = path.join(testDir, "auth.json");
+ fs.writeFileSync(
+ authPath,
+ JSON.stringify({
+ userId: "test-user",
+ userEmail: "test@example.com",
+ accessToken: "test-token",
+ refreshToken: "test-refresh",
+ expiresAt: Date.now() + 3600000,
+ organizationId: "test-org",
+ }),
+ );
+
+ const authConfig = loadAuthConfig();
+ expect(authConfig).not.toBeNull();
+
+ // GlobalContext model should still exist
+ expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
+
+ // When auth config has no modelName, it should fall back to GlobalContext
+ expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet");
+ });
+
+ test("should use auth config model when both exist", () => {
+ // Clear previous state
+ updateModelName(null);
+
+ // Set GlobalContext model
+ updateModelName("GPT-4");
+ expect(getPersistedModelName()).toBe("GPT-4");
+
+ // Create auth config with different model
+ const authPath = path.join(testDir, "auth.json");
+ fs.writeFileSync(
+ authPath,
+ JSON.stringify({
+ userId: "test-user",
+ userEmail: "test@example.com",
+ accessToken: "test-token",
+ refreshToken: "test-refresh",
+ expiresAt: Date.now() + 3600000,
+ organizationId: "test-org",
+ modelName: "Claude 3.5 Sonnet",
+ }),
+ );
+
+ const authConfig = loadAuthConfig();
+
+ // Auth config should take precedence
+ expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet");
+ });
+
+ test("should not save to GlobalContext when using CONTINUE_API_KEY", () => {
+ // Clear any existing model
+ updateModelName(null);
+ expect(getPersistedModelName()).toBeNull();
+
+ // Capture original value to restore after test
+ const originalApiKey = process.env.CONTINUE_API_KEY;
+ process.env.CONTINUE_API_KEY = "test-api-key";
+
+ updateModelName("Claude 3.5 Sonnet");
+
+ // Should not be saved to GlobalContext
+ expect(getPersistedModelName()).toBeNull();
+
+ // Restore original value
+ if (originalApiKey === undefined) {
+ delete process.env.CONTINUE_API_KEY;
+ } else {
+ process.env.CONTINUE_API_KEY = originalApiKey;
+ }
+ });
+
+ test("should work across config changes for logged-out users", async () => {
+ // User switches model with one config
+ updateModelName("Claude 3.5 Sonnet");
+
+ const modelService = new ModelService();
+ let state = await modelService.initialize(mockAssistant, null);
+ expect(state.model?.name).toBe("Claude 3.5 Sonnet");
+
+ // User switches to a different model
+ await modelService.switchModel(2);
+ updateModelName("Claude 3 Opus");
+
+ // Create new service (simulating restart)
+ const newModelService = new ModelService();
+ state = await newModelService.initialize(mockAssistant, null);
+ expect(state.model?.name).toBe("Claude 3 Opus");
+ });
+});
diff --git a/extensions/cli/src/integration/model-persistence-user-flow.test.ts b/extensions/cli/src/integration/model-persistence-user-flow.test.ts
new file mode 100644
index 000000000..3aef05071
--- /dev/null
+++ b/extensions/cli/src/integration/model-persistence-user-flow.test.ts
@@ -0,0 +1,155 @@
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+
+import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { AuthService } from "src/services/AuthService.js";
+
+import {
+ AuthenticatedConfig,
+ getModelName,
+ loadAuthConfig,
+ saveAuthConfig,
+} from "../auth/workos.js";
+import * as config from "../config.js";
+import { ModelService } from "../services/ModelService.js";
+
+// Mock the config module
+vi.mock("../config.js");
+
+describe("Model Persistence User Flow", () => {
+ let testDir: string;
+ let originalContinueHome: string | undefined;
+ let mockAssistant: AssistantUnrolled;
+ let mockAuthConfig: AuthenticatedConfig;
+ const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+
+ // Create a temporary directory for testing
+ testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
+ originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
+ process.env.CONTINUE_GLOBAL_DIR = testDir;
+
+ mockAssistant = {
+ name: "test-assistant",
+ version: "1.0.0",
+ models: [
+ {
+ provider: "openai",
+ model: "gpt-4",
+ name: "GPT-4",
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ {
+ provider: "anthropic",
+ model: "claude-3-5-sonnet-20241022",
+ name: "Claude 3.5 Sonnet",
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ {
+ provider: "anthropic",
+ model: "claude-3-opus-20240229",
+ name: "Claude 3 Opus",
+ apiKey: "test-key",
+ roles: ["chat"],
+ } as ModelConfig,
+ ],
+ } as AssistantUnrolled;
+
+ mockAuthConfig = {
+ userId: "test-user",
+ userEmail: "test@example.com",
+ accessToken: "test-token",
+ refreshToken: "test-refresh",
+ expiresAt: Date.now() + 3600000, // 1 hour from now
+ organizationId: "test-org",
+ modelName: "GPT-4",
+ };
+
+ // Setup default mock behavior
+ vi.mocked(config.getLlmApi).mockReturnValue([
+ mockLlmApi as any,
+ mockAssistant.models![0] as ModelConfig,
+ ]);
+ vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
+ });
+
+ afterEach(() => {
+ // Cleanup
+ if (fs.existsSync(testDir)) {
+ fs.rmSync(testDir, { recursive: true });
+ }
+ if (originalContinueHome) {
+ process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
+ } else {
+ delete process.env.CONTINUE_GLOBAL_DIR;
+ }
+ });
+
+ test("should persist model choice exactly as user experiences it", async () => {
+ console.log("\n=== SESSION 1: User opens cn and switches model ===");
+
+ // Session 1: User starts CLI
+ // Save initial auth config (what happens after login)
+ saveAuthConfig(mockAuthConfig);
+ console.log("1. Initial auth.json saved");
+
+ // Initialize ModelService (what happens on CLI start)
+ const modelService = new ModelService();
+ const state = await modelService.initialize(mockAssistant, mockAuthConfig);
+ console.log("2. Initial model:", state.model?.name);
+ expect(state.model?.name).toBe("GPT-4");
+
+ // User switches to Claude 3.5 Sonnet via UI
+ await modelService.switchModel(1);
+ const modelInfo = modelService.getModelInfo();
+ console.log("3. User switched to:", modelInfo?.name);
+ expect(modelInfo?.name).toBe("Claude 3.5 Sonnet");
+
+ // useModelSelector calls updateModelName
+ const { updateModelName } = await import("../auth/workos.js");
+ const updatedAuthConfig = updateModelName("Claude 3.5 Sonnet");
+ console.log("4. Model name persisted to disk");
+
+ // Verify it was saved
+ const savedConfig = loadAuthConfig();
+ console.log("5. Read back from disk:", getModelName(savedConfig));
+ expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet");
+
+ // User closes CLI
+ console.log("6. User exits CLI\n");
+
+ console.log("=== SESSION 2: User reopens cn ===");
+
+ // Session 2: User restarts CLI
+ // Initialize AuthService (loads from disk)
+ const authService = new AuthService();
+ const authState = await authService.initialize();
+ console.log(
+ "7. AuthService loaded, modelName in auth:",
+ getModelName(authState.authConfig),
+ );
+
+ // Initialize ModelService with fresh auth state
+ const newModelService = new ModelService();
+ const newState = await newModelService.initialize(
+ mockAssistant,
+ authState.authConfig,
+ );
+ console.log(
+ "8. ModelService initialized with model:",
+ newState.model?.name,
+ );
+
+ // EXPECTATION: Should restore Claude 3.5 Sonnet
+ expect(newState.model?.name).toBe("Claude 3.5 Sonnet");
+ expect(newState.model?.provider).toBe("anthropic");
+ console.log("β
Model persisted correctly!\n");
+ });
+});
diff --git a/extensions/cli/src/integration/model-persistence.test.ts b/extensions/cli/src/integration/model-persistence.test.ts
new file mode 100644
index 000000000..9e352143d
--- /dev/null
+++ b/extensions/cli/src/integration/model-persistence.test.ts
@@ -0,0 +1,194 @@
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+
+import { afterEach, beforeEach, describe, expect, test } from "vitest";
+
+import {
+ AuthenticatedConfig,
+ getModelName,
+ loadAuthConfig,
+ saveAuthConfig,
+ updateModelName,
+} from "../auth/workos.js";
+import { persistModelName } from "../util/modelPersistence.js";
+
+describe("Model Persistence Integration", () => {
+ let testDir: string;
+ let originalContinueHome: string | undefined;
+
+ beforeEach(() => {
+ // Create a temporary directory for testing
+ testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
+ originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
+ process.env.CONTINUE_GLOBAL_DIR = testDir;
+
+ // Clear GlobalContext for clean test state
+ persistModelName(null);
+ });
+
+ afterEach(() => {
+ // Cleanup
+ if (fs.existsSync(testDir)) {
+ fs.rmSync(testDir, { recursive: true });
+ }
+ if (originalContinueHome) {
+ process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
+ } else {
+ delete process.env.CONTINUE_GLOBAL_DIR;
+ }
+ });
+
+ test("should persist model name when user selects a model", () => {
+ // Create initial auth config without model name
+ const authConfig: AuthenticatedConfig = {
+ userId: "test-user",
+ userEmail: "test@example.com",
+ accessToken: "test-token",
+ refreshToken: "test-refresh",
+ expiresAt: Date.now() + 3600000,
+ organizationId: "test-org",
+ };
+
+ saveAuthConfig(authConfig);
+
+ // User selects a model
+ updateModelName("Claude 3.5 Sonnet");
+
+ // Load config and verify model name is persisted
+ const loadedConfig = loadAuthConfig();
+ expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet");
+ });
+
+ test("should update model name when user switches models", () => {
+ // Create initial auth config with a model
+ const authConfig: AuthenticatedConfig = {
+ userId: "test-user",
+ userEmail: "test@example.com",
+ accessToken: "test-token",
+ refreshToken: "test-refresh",
+ expiresAt: Date.now() + 3600000,
+ organizationId: "test-org",
+ modelName: "GPT-4",
+ };
+
+ saveAuthConfig(authConfig);
+
+ // User switches to a different model
+ updateModelName("Claude 3.5 Sonnet");
+
+ // Load config and verify new model name
+ const loadedConfig = loadAuthConfig();
+ expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet");
+ });
+
+ test("should preserve other auth config fields when updating model", () => {
+ // Create initial auth config
+ const authConfig: AuthenticatedConfig = {
+ userId: "test-user",
+ userEmail: "test@example.com",
+ accessToken: "test-token",
+ refreshToken: "test-refresh",
+ expiresAt: Date.now() + 3600000,
+ organizationId: "test-org",
+ configUri: "slug://owner/my-config",
+ };
+
+ saveAuthConfig(authConfig);
+
+ // Update model name
+ updateModelName("Claude 3.5 Sonnet");
+
+ // Load config and verify all fields are preserved
+ const loadedConfig = loadAuthConfig();
+ expect(loadedConfig).toMatchObject({
+ userId: "test-user",
+ userEmail: "test@example.com",
+ organizationId: "test-org",
+ configUri: "slug://owner/my-config",
+ modelName: "Claude 3.5 Sonnet",
+ });
+ });
+
+ test("should clear model name when set to null", () => {
+ // Create initial auth config with a model
+ const authConfig: AuthenticatedConfig = {
+ userId: "test-user",
+ userEmail: "test@example.com",
+ accessToken: "test-token",
+ refreshToken: "test-refresh",
+ expiresAt: Date.now() + 3600000,
+ organizationId: "test-org",
+ modelName: "GPT-4",
+ };
+
+ saveAuthConfig(authConfig);
+
+ // Clear model name
+ updateModelName(null);
+
+ // Load config and verify model name is cleared
+ const loadedConfig = loadAuthConfig();
+ expect(getModelName(loadedConfig)).toBeNull();
+ });
+
+ test("should return null for model name when not authenticated and no GlobalContext", () => {
+ // No auth config exists and no GlobalContext model
+ persistModelName(null); // Ensure GlobalContext is clear
+ const loadedConfig = loadAuthConfig();
+ expect(getModelName(loadedConfig)).toBeNull();
+ });
+
+ test("should not persist model name when using CONTINUE_API_KEY", () => {
+ // Clear GlobalContext first
+ persistModelName(null);
+
+ // Capture original value to restore after test
+ const originalApiKey = process.env.CONTINUE_API_KEY;
+ // Set environment variable
+ process.env.CONTINUE_API_KEY = "test-api-key";
+
+ // Try to update model name
+ updateModelName("Claude 3.5 Sonnet");
+
+ // Load config - should be environment auth config without model name
+ const loadedConfig = loadAuthConfig();
+ expect(getModelName(loadedConfig)).toBeNull();
+
+ // Restore original value
+ if (originalApiKey === undefined) {
+ delete process.env.CONTINUE_API_KEY;
+ } else {
+ process.env.CONTINUE_API_KEY = originalApiKey;
+ }
+ });
+
+ test("should persist model name in auth.json file with correct format", () => {
+ // Create and save auth config
+ const authConfig: AuthenticatedConfig = {
+ userId: "test-user",
+ userEmail: "test@example.com",
+ accessToken: "test-token",
+ refreshToken: "test-refresh",
+ expiresAt: Date.now() + 3600000,
+ organizationId: "test-org",
+ };
+
+ saveAuthConfig(authConfig);
+ updateModelName("Claude 3.5 Sonnet");
+
+ // Read the raw file content
+ const authPath = path.join(testDir, "auth.json");
+ const rawContent = fs.readFileSync(authPath, "utf8");
+ const parsedContent = JSON.parse(rawContent);
+
+ // Verify the file structure
+ expect(parsedContent).toHaveProperty("userId", "test-user");
+ expect(parsedContent).toHaveProperty("userEmail", "test@example.com");
+ expect(parsedContent).toHaveProperty("organizationId", "test-org");
+ expect(parsedContent).toHaveProperty("modelName", "Claude 3.5 Sonnet");
+
+ // Verify it's pretty-printed (has indentation)
+ expect(rawContent).toContain("\n ");
+ });
+});
diff --git a/extensions/cli/src/integration/rule-duplication.test.ts b/extensions/cli/src/integration/rule-duplication.test.ts
index e68a3eff9..83143dede 100644
--- a/extensions/cli/src/integration/rule-duplication.test.ts
+++ b/extensions/cli/src/integration/rule-duplication.test.ts
@@ -19,6 +19,24 @@ vi.mock("../hubLoader.js", () => ({
modelProcessor: {},
}));
+// Mock the service container to provide empty workflow state
+vi.mock("../services/ServiceContainer.js", () => ({
+ serviceContainer: {
+ get: vi.fn(() =>
+ Promise.resolve({
+ workflowFile: null,
+ slug: null,
+ }),
+ ),
+ },
+}));
+
+vi.mock("../services/types.js", () => ({
+ SERVICE_NAMES: {
+ WORKFLOW: "workflow",
+ },
+}));
+
describe("Rule duplication integration test", () => {
it("should not duplicate rules when using --rule flag", async () => {
const enhancer = new ConfigEnhancer();
diff --git a/extensions/cli/src/loadMcpFromHub.test.ts b/extensions/cli/src/loadMcpFromHub.test.ts
index 92dd69cf8..cbd49a53a 100644
--- a/extensions/cli/src/loadMcpFromHub.test.ts
+++ b/extensions/cli/src/loadMcpFromHub.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { loadMcpFromHub } from "./args.js";
+import { loadMcpFromHub } from "./hubLoader.js";
// Store original fetch to restore later
const originalFetch = global.fetch;
diff --git a/extensions/cli/src/mcp-flag.integration.test.ts b/extensions/cli/src/mcp-flag.integration.test.ts
index a040c45b4..863e1ea32 100644
--- a/extensions/cli/src/mcp-flag.integration.test.ts
+++ b/extensions/cli/src/mcp-flag.integration.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { parseArgs, loadMcpFromHub } from "./args.js";
+import { loadMcpFromHub } from "./hubLoader.js";
// Integration test to demonstrate the --mcp flag functionality
describe("--mcp flag integration", () => {
@@ -10,35 +10,6 @@ describe("--mcp flag integration", () => {
vi.clearAllMocks();
});
- it("should demonstrate the complete --mcp flag functionality", () => {
- // Test command line parsing
- process.argv = [
- "node",
- "test",
- "--config",
- "my-config.yaml",
- "--mcp",
- "continuedev/filesystem",
- "--mcp",
- "continuedev/github",
- "hello world",
- ];
-
- const args = parseArgs();
-
- // Verify the parsed command line arguments
- expect(args).toEqual({
- configPath: "my-config.yaml",
- mcps: ["continuedev/filesystem", "continuedev/github"],
- prompt: "hello world",
- });
-
- // Verify MCP slugs are properly captured
- expect(args.mcps).toHaveLength(2);
- expect(args.mcps).toContain("continuedev/filesystem");
- expect(args.mcps).toContain("continuedev/github");
- });
-
it("should validate MCP slug format", async () => {
// Test that invalid slug formats are rejected
await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow(
@@ -58,35 +29,4 @@ describe("--mcp flag integration", () => {
'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found',
);
});
-
- it("should demonstrate MCP flag with other command line options", () => {
- process.argv = [
- "node",
- "test",
- "--config",
- "test-config.yaml",
- "--org",
- "my-org",
- "--rule",
- "my-rule",
- "--mcp",
- "continuedev/filesystem",
- "--allow",
- "readFile",
- "--readonly",
- "analyze this code",
- ];
-
- const args = parseArgs();
-
- // Verify all flags are parsed correctly together
- expect(args).toEqual({
- configPath: "test-config.yaml",
- organizationSlug: "my-org",
- rules: ["my-rule"],
- mcps: ["continuedev/filesystem"],
- readonly: true,
- prompt: "analyze this code",
- });
- });
});
diff --git a/extensions/cli/src/onboarding.test.ts b/extensions/cli/src/onboarding.test.ts
index c31bc1608..1864e6368 100644
--- a/extensions/cli/src/onboarding.test.ts
+++ b/extensions/cli/src/onboarding.test.ts
@@ -2,7 +2,7 @@ import * as fs from "fs";
import * as os from "os";
import * as path from "path";
-import { describe, expect, test, beforeEach, afterEach } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import type { AuthConfig } from "./auth/workos.js";
import { runNormalFlow } from "./onboarding.js";
@@ -160,3 +160,93 @@ name: "Incomplete Config"
}
});
});
+
+// Separate describe block with its own mocking for BEDROCK tests
+describe("CONTINUE_USE_BEDROCK environment variable", () => {
+ const mockConsoleLog = vi.fn();
+ let mockAuthConfig: AuthConfig;
+ const originalEnv = process.env.CONTINUE_USE_BEDROCK;
+
+ // Mock initialize for these tests only
+ const mockInitialize = vi.fn().mockResolvedValue({
+ config: { name: "test-config", models: [], rules: [] },
+ llmApi: {},
+ model: { name: "test-model" },
+ mcpService: {},
+ apiClient: {},
+ });
+
+ beforeEach(() => {
+ mockConsoleLog.mockClear();
+ mockInitialize.mockClear();
+
+ // Spy on console.log for these tests
+ vi.spyOn(console, "log").mockImplementation(mockConsoleLog);
+
+ // Mock the config module
+ vi.doMock("./config.js", () => ({ initialize: mockInitialize }));
+
+ mockAuthConfig = {
+ userId: "test-user",
+ userEmail: "test@example.com",
+ accessToken: "test-token",
+ refreshToken: "test-refresh",
+ expiresAt: Date.now() + 3600000,
+ organizationId: "test-org",
+ };
+ });
+
+ afterEach(() => {
+ if (originalEnv) {
+ process.env.CONTINUE_USE_BEDROCK = originalEnv;
+ } else {
+ delete process.env.CONTINUE_USE_BEDROCK;
+ }
+ vi.restoreAllMocks();
+ vi.doUnmock("./config.js");
+ });
+
+ test("should bypass interactive options when CONTINUE_USE_BEDROCK=1", async () => {
+ process.env.CONTINUE_USE_BEDROCK = "1";
+
+ // Re-import to get the mocked version
+ vi.resetModules();
+ const { runOnboardingFlow } = await import("./onboarding.js");
+
+ const result = await runOnboardingFlow(undefined, mockAuthConfig);
+
+ expect(result.wasOnboarded).toBe(true);
+ expect(mockConsoleLog).toHaveBeenCalledWith(
+ expect.stringContaining(
+ "β Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)",
+ ),
+ );
+ });
+
+ test("should not bypass when CONTINUE_USE_BEDROCK is not '1'", async () => {
+ process.env.CONTINUE_USE_BEDROCK = "0";
+
+ // Re-import to get the mocked version
+ vi.resetModules();
+ const { runOnboardingFlow } = await import("./onboarding.js");
+
+ // Mock non-interactive environment to avoid hanging
+ const originalIsTTY = process.stdin.isTTY;
+ process.stdin.isTTY = false;
+
+ try {
+ await runOnboardingFlow(undefined, mockAuthConfig);
+
+ // Verify the Bedrock message was NOT called by checking all calls
+ const allCalls = mockConsoleLog.mock.calls.flat();
+ const hasBedrockMessage = allCalls.some((call) =>
+ String(call).includes(
+ "β Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)",
+ ),
+ );
+ expect(hasBedrockMessage).toBe(false);
+ } finally {
+ process.stdin.isTTY = originalIsTTY;
+ }
+ });
+});
diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts
index 7eb59d89a..0108baa90 100644
--- a/extensions/cli/src/onboarding.ts
+++ b/extensions/cli/src/onboarding.ts
@@ -5,17 +5,17 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
-import * as readlineSync from "readline-sync";
-import { processPromptOrRule } from "./args.js";
import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
import { initialize } from "./config.js";
import { env } from "./env.js";
+import { processRule } from "./hubLoader.js";
import { MCPService } from "./services/MCPService.js";
import {
getApiKeyValidationError,
isValidAnthropicApiKey,
} from "./util/apiKeyValidation.js";
+import { question, questionWithChoices } from "./util/prompt.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
@@ -59,7 +59,7 @@ export async function createOrUpdateConfig(apiKey: string): Promise {
fs.writeFileSync(CONFIG_PATH, updatedContent);
}
-async function runOnboardingFlow(
+export async function runOnboardingFlow(
configPath: string | undefined,
authConfig: AuthConfig,
): Promise {
@@ -69,7 +69,16 @@ async function runOnboardingFlow(
return { ...result, wasOnboarded: false };
}
- // Step 2: Check if we're in a test/CI environment - if so, skip interactive prompts
+ // Step 2: Check for CONTINUE_USE_BEDROCK environment variable first (before test env check)
+ if (process.env.CONTINUE_USE_BEDROCK === "1") {
+ console.log(
+ chalk.blue("β Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)"),
+ );
+ const result = await initialize(authConfig, CONFIG_PATH);
+ return { ...result, wasOnboarded: true };
+ }
+
+ // Step 3: Check if we're in a test/CI environment - if so, skip interactive prompts
const isTestEnv =
process.env.NODE_ENV === "test" ||
process.env.CI === "true" ||
@@ -92,27 +101,29 @@ async function runOnboardingFlow(
return { ...result, wasOnboarded: false };
}
- // Step 3: Present user with two options
+ // Step 4: Present user with two options
console.log(chalk.yellow("How do you want to get started?"));
console.log(chalk.white("1. β© Log in with Continue"));
console.log(chalk.white("2. π Enter your Anthropic API key"));
- const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), {
- limit: ["1", "2", ""],
- limitMessage: chalk.dim("Please enter 1 or 2"),
- });
+ const choice = await questionWithChoices(
+ chalk.yellow("\nEnter choice (1): "),
+ ["1", "2", ""],
+ "1",
+ chalk.dim("Please enter 1 or 2"),
+ );
if (choice === "1" || choice === "") {
const newAuthConfig = await login();
- const result = await initialize(newAuthConfig, undefined);
+ const { ensureOrganization } = await import("./auth/workos.js");
+ const finalAuthConfig = await ensureOrganization(newAuthConfig);
+
+ const result = await initialize(finalAuthConfig, undefined);
return { ...result, wasOnboarded: true };
} else if (choice === "2") {
- const apiKey = readlineSync.question(
+ const apiKey = await question(
chalk.white("\nEnter your Anthropic API key: "),
- {
- hideEchoBack: true,
- },
);
if (!isValidAnthropicApiKey(apiKey)) {
@@ -127,7 +138,7 @@ async function runOnboardingFlow(
const result = await initialize(authConfig, CONFIG_PATH);
return { ...result, wasOnboarded: true };
} else {
- throw new Error("Invalid choice. Please select 1 or 2.");
+ throw new Error(`Invalid choice. Please select "1" or "2"`);
}
}
@@ -239,7 +250,7 @@ async function injectRulesIntoConfig(
const processedRules: string[] = [];
for (const ruleSpec of rules) {
try {
- const processedRule = await processPromptOrRule(ruleSpec);
+ const processedRule = await processRule(ruleSpec);
processedRules.push(processedRule);
} catch (error: any) {
console.warn(
diff --git a/extensions/cli/src/permissions/permissionChecker.test.ts b/extensions/cli/src/permissions/permissionChecker.test.ts
index c860a6454..259dd06c5 100644
--- a/extensions/cli/src/permissions/permissionChecker.test.ts
+++ b/extensions/cli/src/permissions/permissionChecker.test.ts
@@ -1,3 +1,7 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import * as toolsModule from "../tools/index.js";
+
import {
checkToolPermission,
filterExcludedTools,
@@ -593,4 +597,379 @@ describe("Permission Checker", () => {
expect(filtered).toEqual(tools);
});
});
+
+ describe("Hybrid Permission Model with Dynamic Evaluation", () => {
+ // Mock the runTerminalCommand tool with evaluateToolCallPolicy
+ const mockBashTool = {
+ name: "Bash",
+ displayName: "Bash",
+ description: "Execute bash commands",
+ parameters: {
+ type: "object" as const,
+ properties: {},
+ },
+ isBuiltIn: true,
+ evaluateToolCallPolicy: vi.fn(),
+ run: vi.fn(),
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Mock getAllBuiltinTools to return our test tool
+ vi.spyOn(toolsModule, "getAllBuiltinTools").mockReturnValue([
+ mockBashTool,
+ ]);
+
+ // Reset mock between tests
+ mockBashTool.evaluateToolCallPolicy.mockClear();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ describe("User has Bash in 'allow' mode", () => {
+ const permissions: ToolPermissions = {
+ policies: [
+ { tool: "Bash", permission: "allow" },
+ { tool: "*", permission: "ask" },
+ ],
+ };
+
+ it("should allow safe commands (echo hello)", () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue(
+ "allowedWithoutPermission",
+ );
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "echo hello" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("allow"); // User preference wins
+ expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
+ "allowedWithoutPermission", // converted from "allow"
+ { command: "echo hello" },
+ );
+ });
+
+ it("should allow risky commands based on user preference (curl)", () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue(
+ "allowedWithPermission",
+ );
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "curl https://example.com" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("allow"); // User preference wins over "ask"
+ expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
+ "allowedWithoutPermission", // converted from "allow"
+ { command: "curl https://example.com" },
+ );
+ });
+
+ it("should block dangerous commands despite user preference (eval)", () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "eval 'echo safe'" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("exclude"); // Security wins
+ expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
+ "allowedWithoutPermission", // converted from "allow"
+ { command: "eval 'echo safe'" },
+ );
+ });
+
+ it("should block sudo commands despite user preference", () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "sudo rm -rf /" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("exclude"); // Security wins
+ });
+ });
+
+ describe("User has Bash in 'ask' mode (default)", () => {
+ const permissions: ToolPermissions = {
+ policies: [
+ { tool: "Bash", permission: "ask" },
+ { tool: "*", permission: "ask" },
+ ],
+ };
+
+ it("should ask for safe commands based on user preference (echo)", () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue(
+ "allowedWithoutPermission",
+ );
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "echo hello" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("ask"); // User preference wins
+ expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
+ "allowedWithPermission", // converted from "ask"
+ { command: "echo hello" },
+ );
+ });
+
+ it("should ask for risky commands (curl)", () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue(
+ "allowedWithPermission",
+ );
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "curl https://example.com" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("ask"); // Both agree on "ask"
+ expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
+ "allowedWithPermission", // converted from "ask"
+ { command: "curl https://example.com" },
+ );
+ });
+
+ it("should block dangerous commands (eval)", () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "eval 'echo safe'" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("exclude"); // Security wins
+ expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
+ "allowedWithPermission", // converted from "ask"
+ { command: "eval 'echo safe'" },
+ );
+ });
+
+ it("should block rm -rf commands", () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "rm -rf /tmp/important" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("exclude"); // Security wins
+ });
+ });
+
+ describe("User has Bash in 'exclude' mode", () => {
+ const permissions: ToolPermissions = {
+ policies: [{ tool: "Bash", permission: "exclude" }],
+ };
+
+ it("should always exclude regardless of dynamic evaluation", () => {
+ // Even if dynamic evaluation would allow it
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue(
+ "allowedWithoutPermission",
+ );
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "echo hello" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("exclude"); // User excluded the tool entirely
+ expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
+ "disabled", // converted from "exclude"
+ { command: "echo hello" },
+ );
+ });
+ });
+
+ describe("Comprehensive command testing", () => {
+ const permissions: ToolPermissions = {
+ policies: [{ tool: "Bash", permission: "allow" }],
+ };
+
+ const testCases = [
+ // Safe commands
+ {
+ command: "ls",
+ dynamicResult: "allowedWithoutPermission",
+ expected: "allow",
+ },
+ {
+ command: "pwd",
+ dynamicResult: "allowedWithoutPermission",
+ expected: "allow",
+ },
+ {
+ command: "date",
+ dynamicResult: "allowedWithoutPermission",
+ expected: "allow",
+ },
+ {
+ command: "echo test",
+ dynamicResult: "allowedWithoutPermission",
+ expected: "allow",
+ },
+ {
+ command: "git status",
+ dynamicResult: "allowedWithoutPermission",
+ expected: "allow",
+ },
+
+ // Risky commands (user preference wins when not disabled)
+ {
+ command: "npm install pkg",
+ dynamicResult: "allowedWithPermission",
+ expected: "allow",
+ },
+ {
+ command: "rm file.txt",
+ dynamicResult: "allowedWithPermission",
+ expected: "allow",
+ },
+ {
+ command: "curl https://api.example.com",
+ dynamicResult: "allowedWithPermission",
+ expected: "allow",
+ },
+ {
+ command: "wget https://example.com/file",
+ dynamicResult: "allowedWithPermission",
+ expected: "allow",
+ },
+
+ // Dangerous commands (always blocked)
+ {
+ command: "sudo rm -rf /",
+ dynamicResult: "disabled",
+ expected: "exclude",
+ },
+ {
+ command: "exec bash",
+ dynamicResult: "disabled",
+ expected: "exclude",
+ },
+ {
+ command: "eval 'malicious code'",
+ dynamicResult: "disabled",
+ expected: "exclude",
+ },
+ { command: "rm -rf /", dynamicResult: "disabled", expected: "exclude" },
+ ];
+
+ testCases.forEach(({ command, dynamicResult, expected }) => {
+ it(`should handle '${command}' correctly`, () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue(dynamicResult);
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command } },
+ permissions,
+ );
+
+ expect(result.permission).toBe(expected);
+ });
+ });
+ });
+
+ describe("Edge cases", () => {
+ it("should handle tools without dynamic evaluation", () => {
+ // Mock a Read tool without evaluateToolCallPolicy
+ const mockReadTool = {
+ name: "Read",
+ displayName: "Read",
+ description: "Read files",
+ parameters: {
+ type: "object" as const,
+ properties: {},
+ },
+ isBuiltIn: true,
+ run: vi.fn(),
+ // No evaluateToolCallPolicy
+ };
+ vi.mocked(toolsModule.getAllBuiltinTools).mockReturnValue([
+ mockReadTool,
+ mockBashTool,
+ ]);
+
+ const permissions: ToolPermissions = {
+ policies: [{ tool: "Read", permission: "allow" }],
+ };
+
+ const result = checkToolPermission(
+ { name: "Read", arguments: { path: "/tmp/file.txt" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("allow");
+ expect(mockBashTool.evaluateToolCallPolicy).not.toHaveBeenCalled();
+ });
+
+ it("should use default 'ask' when no policy matches", () => {
+ const permissions: ToolPermissions = {
+ policies: [],
+ };
+
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue(
+ "allowedWithPermission",
+ );
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "echo test" } },
+ permissions,
+ );
+
+ expect(result.permission).toBe("ask"); // Default fallback, user preference wins
+ expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
+ "allowedWithPermission", // converted from default "ask"
+ { command: "echo test" },
+ );
+ });
+
+ it("should handle null/undefined arguments gracefully", () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue(
+ "allowedWithPermission",
+ );
+
+ const permissions: ToolPermissions = {
+ policies: [{ tool: "Bash", permission: "allow" }],
+ };
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: {} },
+ permissions,
+ );
+
+ expect(result.permission).toBe("allow");
+ expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
+ "allowedWithoutPermission",
+ {},
+ );
+ });
+
+ it("should maintain matched policy information", () => {
+ mockBashTool.evaluateToolCallPolicy.mockReturnValue(
+ "allowedWithoutPermission",
+ );
+
+ const policy = { tool: "Bash", permission: "allow" as const };
+ const permissions: ToolPermissions = {
+ policies: [policy],
+ };
+
+ const result = checkToolPermission(
+ { name: "Bash", arguments: { command: "ls" } },
+ permissions,
+ );
+
+ expect(result.matchedPolicy).toBe(policy);
+ });
+ });
+ });
});
diff --git a/extensions/cli/src/permissions/permissionChecker.ts b/extensions/cli/src/permissions/permissionChecker.ts
index 9b2f5d557..738de9a56 100644
--- a/extensions/cli/src/permissions/permissionChecker.ts
+++ b/extensions/cli/src/permissions/permissionChecker.ts
@@ -1,10 +1,15 @@
+import type { ToolPolicy } from "@continuedev/terminal-security";
+
+import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js";
+
import { getServiceSync } from "../services/index.js";
-import type { ToolPermissionServiceState } from "../services/types.js";
import { SERVICE_NAMES } from "../services/types.js";
+import { getAllBuiltinTools } from "../tools/index.js";
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
import {
PermissionCheckResult,
+ PermissionPolicy,
ToolCallRequest,
ToolPermissions,
} from "./types.js";
@@ -103,6 +108,24 @@ export function matchesArguments(
return true;
}
+/**
+ * Converts CLI's PermissionPolicy to core's ToolPolicy
+ */
+function permissionPolicyToToolPolicy(
+ permission: PermissionPolicy,
+): ToolPolicy {
+ switch (permission) {
+ case "allow":
+ return "allowedWithoutPermission";
+ case "ask":
+ return "allowedWithPermission";
+ case "exclude":
+ return "disabled";
+ default:
+ return "allowedWithPermission";
+ }
+}
+
/**
* Evaluates a tool call request against a set of permission policies.
* Returns the permission for the first matching policy.
@@ -129,21 +152,54 @@ export function checkToolPermission(
}
}
+ // First, get the base permission from static policies
+ let basePermission: PermissionPolicy = "ask";
+ let matchedPolicy = undefined;
+
for (const policy of policies) {
if (
matchesToolPattern(toolCall.name, policy.tool, toolCall.arguments) &&
matchesArguments(toolCall.arguments, policy.argumentMatches)
) {
- return {
- permission: policy.permission,
- matchedPolicy: policy,
- };
+ basePermission = policy.permission;
+ matchedPolicy = policy;
+ break;
}
}
- // Fallback to "ask" if no policy matches
+ // Check if tool has dynamic policy evaluation
+ const builtinTools = getAllBuiltinTools();
+ const tool = builtinTools.find((t) => t.name === toolCall.name);
+
+ if (tool?.evaluateToolCallPolicy) {
+ // Convert CLI permission to core policy
+ const basePolicy = permissionPolicyToToolPolicy(basePermission);
+
+ // Evaluate the dynamic policy
+ const evaluatedPolicy = tool.evaluateToolCallPolicy(
+ basePolicy,
+ toolCall.arguments,
+ );
+
+ // If dynamic evaluation says disabled, that ALWAYS takes precedence
+ if (evaluatedPolicy === "disabled") {
+ return {
+ permission: "exclude",
+ matchedPolicy,
+ };
+ }
+
+ // Otherwise, user preference wins - return the original base permission
+ return {
+ permission: basePermission,
+ matchedPolicy,
+ };
+ }
+
+ // No dynamic evaluation, return static result
return {
- permission: "ask",
+ permission: basePermission,
+ matchedPolicy,
};
}
diff --git a/extensions/cli/src/services/AuthService.refactored.ts b/extensions/cli/src/services/AuthService.refactored.ts
index 0a3a79653..c79d563d2 100644
--- a/extensions/cli/src/services/AuthService.refactored.ts
+++ b/extensions/cli/src/services/AuthService.refactored.ts
@@ -1,205 +1,206 @@
-import {
- AuthenticatedConfig,
- login as doLogin,
- logout as doLogout,
- ensureOrganization,
- isAuthenticated,
- listUserOrganizations,
- loadAuthConfig,
- saveAuthConfig,
-} from "../auth/workos.js";
-import { logger } from "../util/logger.js";
+// import {
+// AuthenticatedConfig,
+// login as doLogin,
+// logout as doLogout,
+// ensureOrganization,
+// isAuthenticated,
+// listUserOrganizations,
+// loadAuthConfig,
+// saveAuthConfig,
+// } from "../auth/workos.js";
+// import { logger } from "../util/logger.js";
-import { BaseService } from "./BaseService.js";
-import { AuthServiceState } from "./types.js";
+// import { BaseService } from "./BaseService.js";
+// import { AuthServiceState } from "./types.js";
-/**
- * Service for managing authentication state and operations
- * Now extends BaseService for common functionality
- */
-export class AuthService extends BaseService {
- constructor() {
- super("AuthService", {
- authConfig: null,
- isAuthenticated: false,
- });
- }
+// /**
+// * Service for managing authentication state and operations
+// * Now extends BaseService for common functionality
+// */
+// export class AuthService extends BaseService {
+// constructor() {
+// super("AuthService", {
+// authConfig: null,
+// isAuthenticated: false,
+// });
+// }
- /**
- * Initialize the auth service by loading current config
- */
- async doInitialize(): Promise {
- const authConfig = loadAuthConfig();
- const authenticated = isAuthenticated();
+// /**
+// * Initialize the auth service by loading current config
+// */
+// async doInitialize(): Promise {
+// const authConfig = loadAuthConfig();
+// const authenticated = isAuthenticated();
- const state: AuthServiceState = {
- authConfig,
- isAuthenticated: authenticated,
- organizationId: authConfig?.organizationId || undefined,
- };
+// const state: AuthServiceState = {
+// authConfig,
+// isAuthenticated: authenticated,
+// organizationId: authConfig?.organizationId || undefined,
+// };
- logger.debug("AuthService initialized", {
- authenticated,
- hasConfig: !!authConfig,
- orgId: state.organizationId,
- });
+// logger.debug("AuthService initialized", {
+// authenticated,
+// hasConfig: !!authConfig,
+// orgId: state.organizationId,
+// });
- return state;
- }
+// return state;
+// }
- /**
- * Perform login flow
- */
- async login(): Promise {
- logger.debug("Starting login flow");
+// /**
+// * Perform login flow
+// */
+// async login(): Promise {
+// logger.debug("Starting login flow");
- try {
- const newAuthConfig = await doLogin();
+// try {
+// const newAuthConfig = await doLogin();
- this.setState({
- authConfig: newAuthConfig,
- isAuthenticated: true,
- organizationId: newAuthConfig?.organizationId || undefined,
- });
+// this.setState({
+// authConfig: newAuthConfig,
+// isAuthenticated: true,
+// organizationId: newAuthConfig?.organizationId || undefined,
+// });
- logger.debug("Login successful", {
- orgId: this.currentState.organizationId,
- });
+// logger.debug("Login successful", {
+// orgId: this.currentState.organizationId,
+// });
- return this.getState();
- } catch (error: any) {
- logger.error("Login failed:", error);
- this.emit("error", error);
- throw error;
- }
- }
+// return this.getState();
+// } catch (error: any) {
+// logger.error("Login failed:", error);
+// this.emit("error", error);
+// throw error;
+// }
+// }
- /**
- * Perform logout
- */
- async logout(): Promise {
- logger.debug("Logging out");
+// /**
+// * Perform logout
+// */
+// async logout(): Promise {
+// logger.debug("Logging out");
- doLogout();
+// doLogout();
- this.setState({
- authConfig: null,
- isAuthenticated: false,
- organizationId: undefined,
- });
+// this.setState({
+// authConfig: null,
+// isAuthenticated: false,
+// organizationId: undefined,
+// });
- logger.debug("Logout complete");
- return this.getState();
- }
+// logger.debug("Logout complete");
+// return this.getState();
+// }
- /**
- * Ensure organization is selected, prompting if necessary
- */
- async ensureOrganization(
- isHeadless: boolean = false,
- ): Promise {
- if (!this.currentState.authConfig) {
- throw new Error("Not authenticated - cannot ensure organization");
- }
+// /**
+// * Ensure organization is selected, prompting if necessary
+// */
+// async ensureOrganization(
+// isHeadless: boolean = false,
+// ): Promise {
+// if (!this.currentState.authConfig) {
+// throw new Error("Not authenticated - cannot ensure organization");
+// }
- logger.debug("Ensuring organization is selected", {
- currentOrgId: this.currentState.organizationId,
- isHeadless,
- });
+// logger.debug("Ensuring organization is selected", {
+// currentOrgId: this.currentState.organizationId,
+// isHeadless,
+// });
- const updatedConfig = await ensureOrganization(
- this.currentState.authConfig,
- isHeadless,
- );
+// const updatedConfig = await ensureOrganization(
+// this.currentState.authConfig,
+// isHeadless,
+// );
- this.setState({
- authConfig: updatedConfig,
- isAuthenticated: true,
- organizationId: updatedConfig?.organizationId || undefined,
- });
+// this.setState({
+// authConfig: updatedConfig,
+// isAuthenticated: true,
+// organizationId: updatedConfig?.organizationId || undefined,
+// });
- logger.debug("Organization ensured", {
- orgId: this.currentState.organizationId,
- });
+// logger.debug("Organization ensured", {
+// orgId: this.currentState.organizationId,
+// });
- return this.getState();
- }
+// return this.getState();
+// }
- /**
- * Switch to a different organization
- */
- async switchOrganization(
- organizationId: string | null,
- ): Promise {
- if (
- !this.currentState.authConfig ||
- !("userId" in this.currentState.authConfig)
- ) {
- throw new Error(
- "Not authenticated with file-based auth - cannot switch organizations",
- );
- }
+// /**
+// * Switch to a different organization
+// */
+// async switchOrganization(
+// organizationId: string | null,
+// ): Promise {
+// if (
+// !this.currentState.authConfig ||
+// !("userId" in this.currentState.authConfig)
+// ) {
+// throw new Error(
+// "Not authenticated with file-based auth - cannot switch organizations",
+// );
+// }
- logger.debug("Switching organization", {
- from: this.currentState.organizationId,
- to: organizationId,
- });
+// logger.debug("Switching organization", {
+// from: this.currentState.organizationId,
+// to: organizationId,
+// });
- const authenticatedConfig = this.currentState
- .authConfig as AuthenticatedConfig;
+// const authenticatedConfig = this.currentState
+// .authConfig as AuthenticatedConfig;
- const updatedConfig: AuthenticatedConfig = {
- ...authenticatedConfig,
- organizationId,
- };
+// const updatedConfig: AuthenticatedConfig = {
+// ...authenticatedConfig,
+// organizationId,
+// };
- saveAuthConfig(updatedConfig);
+// saveAuthConfig(updatedConfig);
- this.setState({
- authConfig: updatedConfig,
- isAuthenticated: true,
- organizationId: organizationId || undefined,
- });
+// this.setState({
+// authConfig: updatedConfig,
+// isAuthenticated: true,
+// organizationId: organizationId || undefined,
+// });
- logger.debug("Organization switched", {
- newOrgId: this.currentState.organizationId,
- });
+// logger.debug("Organization switched", {
+// newOrgId: this.currentState.organizationId,
+// });
- return this.getState();
- }
+// return this.getState();
+// }
- /**
- * Get available organizations for the current user
- */
- async getAvailableOrganizations(): Promise<
- { id: string; name: string }[] | null
- > {
- if (!this.currentState.isAuthenticated) {
- return null;
- }
+// /**
+// * Get available organizations for the current user
+// */
+// async getAvailableOrganizations(): Promise<
+// { id: string; name: string }[] | null
+// > {
+// if (!this.currentState.isAuthenticated) {
+// return null;
+// }
- try {
- return await listUserOrganizations();
- } catch (error: any) {
- logger.error("Failed to list organizations:", error);
- this.emit("error", error);
- return null;
- }
- }
+// try {
+// return await listUserOrganizations();
+// } catch (error: any) {
+// logger.error("Failed to list organizations:", error);
+// this.emit("error", error);
+// return null;
+// }
+// }
- /**
- * Check if the current user has multiple organizations available
- */
- async hasMultipleOrganizations(): Promise {
- const orgs = await this.getAvailableOrganizations();
- return orgs !== null && orgs.length > 0;
- }
+// /**
+// * Check if the current user has multiple organizations available
+// */
+// async hasMultipleOrganizations(): Promise {
+// const orgs = await this.getAvailableOrganizations();
+// return orgs !== null && orgs.length > 0;
+// }
- /**
- * Refresh auth state from disk (useful after external changes)
- */
- async refresh(): Promise {
- logger.debug("Refreshing auth state from disk");
- return this.reload();
- }
-}
+// /**
+// * Refresh auth state from disk (useful after external changes)
+// */
+// async refresh(): Promise {
+// logger.debug("Refreshing auth state from disk");
+// return this.reload();
+// }
+// }
+export {};
diff --git a/extensions/cli/src/services/BaseService.test.ts b/extensions/cli/src/services/BaseService.test.ts
index 2bf581bc1..cd14d665f 100644
--- a/extensions/cli/src/services/BaseService.test.ts
+++ b/extensions/cli/src/services/BaseService.test.ts
@@ -1,10 +1,118 @@
-import { describe, expect, test, beforeEach, vi } from "vitest";
+import { EventEmitter } from "events";
-import {
- BaseService,
- hasDependencies,
- ServiceWithDependencies,
-} from "./BaseService.js";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import { logger } from "../util/logger.js";
+
+/**
+ * Base abstract class for all services
+ * Provides common lifecycle methods and state management
+ */
+abstract class BaseService extends EventEmitter {
+ protected serviceName: string;
+ protected currentState: TState;
+ private isInitialized: boolean = false;
+
+ constructor(serviceName: string, initialState: TState) {
+ super();
+ this.serviceName = serviceName;
+ this.currentState = initialState;
+ }
+
+ /**
+ * Initialize the service (must be implemented by subclasses)
+ * This is automatically wrapped with initialization logic
+ */
+ abstract doInitialize(...args: any[]): Promise;
+
+ /**
+ * Public initialization method that wraps the implementation
+ */
+ async initialize(...args: any[]): Promise {
+ logger.debug(`Initializing ${this.serviceName}`, {
+ wasInitialized: this.isInitialized,
+ hadPreviousState: !!this.currentState,
+ });
+ this.emit("initializing");
+
+ try {
+ const state = await this.doInitialize(...args);
+ this.currentState = state;
+ this.isInitialized = true;
+ logger.debug(`${this.serviceName} initialized successfully`, {
+ stateKeys: state ? Object.keys(state as any) : [],
+ isNowInitialized: this.isInitialized,
+ });
+ this.emit("initialized", state);
+ return state;
+ } catch (error: any) {
+ logger.debug(`Failed to initialize ${this.serviceName}:`, error);
+ if (this.listenerCount("error") > 0) {
+ this.emit("error", error);
+ }
+ throw error;
+ }
+ }
+
+ /**
+ * Get current service state (shallow copy for immutability)
+ */
+ getState(): TState {
+ return { ...this.currentState };
+ }
+
+ /**
+ * Update service state and emit change event
+ */
+ protected setState(newState: Partial): void {
+ const previousState = this.currentState;
+ this.currentState = { ...this.currentState, ...newState };
+ // Only log state updates if not in production to avoid circular reference issues
+ if (process.env.NODE_ENV !== "production") {
+ logger.debug(`${this.serviceName} state updated`);
+ }
+ this.emit("stateChanged", this.currentState, previousState);
+ }
+
+ /**
+ * Check if service is ready for use
+ */
+ isReady(): boolean {
+ return this.isInitialized;
+ }
+
+ /**
+ * Reload/refresh the service
+ */
+ async reload(...args: any[]): Promise {
+ logger.debug(`Reloading ${this.serviceName}`);
+ this.isInitialized = false;
+ return this.initialize(...args);
+ }
+
+ /**
+ * Cleanup resources (can be overridden by subclasses)
+ */
+ async cleanup(): Promise {
+ logger.debug(`Cleaning up ${this.serviceName}`);
+ this.removeAllListeners();
+ this.isInitialized = false;
+ }
+}
+
+/**
+ * Interface for services with dependencies
+ */
+interface ServiceWithDependencies {
+ getDependencies(): string[];
+}
+
+/**
+ * Helper to check if a service has dependencies
+ */
+function hasDependencies(service: any): service is ServiceWithDependencies {
+ return !!service && typeof service.getDependencies === "function";
+}
// Test implementation of BaseService
interface TestState {
diff --git a/extensions/cli/src/services/ChatHistoryService.test.ts b/extensions/cli/src/services/ChatHistoryService.test.ts
new file mode 100644
index 000000000..e5edef8ba
--- /dev/null
+++ b/extensions/cli/src/services/ChatHistoryService.test.ts
@@ -0,0 +1,548 @@
+import type { ChatHistoryItem } from "core/index.js";
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+import { ChatHistoryService } from "./ChatHistoryService.js";
+
+// Mock the dependencies
+vi.mock("../session.js", () => ({
+ updateSessionHistory: vi.fn(),
+ loadSession: vi.fn(),
+ createSession: vi.fn((history) => ({
+ sessionId: "test-session-id",
+ history: history || [],
+ title: "Test Session",
+ workspaceDirectory: "/test",
+ })),
+}));
+
+vi.mock("../util/logger.js", () => ({
+ logger: {
+ debug: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+}));
+
+describe("ChatHistoryService", () => {
+ let service: ChatHistoryService;
+
+ beforeEach(() => {
+ service = new ChatHistoryService();
+ vi.clearAllMocks();
+ });
+
+ describe("initialization", () => {
+ it("should initialize with empty state", async () => {
+ const state = await service.initialize();
+
+ expect(state.history).toEqual([]);
+ expect(state.compactionIndex).toBeNull();
+ expect(state.sessionId).toBe("test-session-id");
+ expect(state.isRemoteMode).toBe(false);
+ });
+
+ it("should initialize with provided session", async () => {
+ const mockHistory: ChatHistoryItem[] = [
+ {
+ message: { role: "user", content: "Hello" },
+ contextItems: [],
+ },
+ ];
+
+ const mockSession = {
+ sessionId: "custom-session",
+ history: mockHistory,
+ title: "Custom Session",
+ workspaceDirectory: "/custom",
+ };
+
+ const state = await service.initialize(mockSession);
+
+ expect(state.history).toEqual(mockHistory);
+ expect(state.sessionId).toBe("custom-session");
+ });
+
+ it("should detect compaction index on initialization", async () => {
+ const mockHistory: ChatHistoryItem[] = [
+ {
+ message: { role: "user", content: "First message" },
+ contextItems: [],
+ },
+ {
+ message: { role: "assistant", content: "Summary here" },
+ contextItems: [],
+ conversationSummary: "Summary here",
+ },
+ {
+ message: { role: "user", content: "After compaction" },
+ contextItems: [],
+ },
+ ];
+
+ const mockSession = {
+ sessionId: "session-with-compaction",
+ history: mockHistory,
+ title: "Compacted Session",
+ workspaceDirectory: "/compacted",
+ };
+
+ const state = await service.initialize(mockSession);
+
+ expect(state.compactionIndex).toBe(1);
+ });
+
+ it("should set remote mode on initialization", async () => {
+ const state = await service.initialize(undefined, true);
+
+ expect(state.isRemoteMode).toBe(true);
+ });
+ });
+
+ describe("addUserMessage", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should add a user message to history", () => {
+ const message = service.addUserMessage("Hello, world!");
+
+ expect(message.message.role).toBe("user");
+ expect(message.message.content).toBe("Hello, world!");
+
+ const state = service.getState();
+ expect(state.history).toHaveLength(1);
+ expect(state.history[0]).toBe(message);
+ });
+
+ it("should include context items", () => {
+ const contextItems = [
+ { content: "file.txt", name: "File", description: "A text file" },
+ ];
+
+ const message = service.addUserMessage("Check this file", contextItems);
+
+ expect(message.contextItems).toEqual(contextItems);
+ });
+
+ it("should emit state change event", () => {
+ const listener = vi.fn();
+ service.on("stateChanged", listener);
+
+ service.addUserMessage("Test message");
+
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(listener).toHaveBeenCalledWith(
+ expect.objectContaining({
+ history: expect.arrayContaining([
+ expect.objectContaining({
+ message: expect.objectContaining({
+ role: "user",
+ content: "Test message",
+ }),
+ }),
+ ]),
+ }),
+ expect.any(Object),
+ );
+ });
+
+ it("should not save to session in remote mode", async () => {
+ const { updateSessionHistory } = await import("../session.js");
+
+ await service.initialize(undefined, true);
+ service.addUserMessage("Remote message");
+
+ expect(updateSessionHistory).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("addAssistantMessage", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should add an assistant message without tool calls", () => {
+ const message = service.addAssistantMessage("I can help with that");
+
+ expect(message.message.role).toBe("assistant");
+ expect(message.message.content).toBe("I can help with that");
+ expect(message.toolCallStates).toBeUndefined();
+ });
+
+ it("should add an assistant message with tool calls", () => {
+ const toolCalls = [
+ {
+ id: "tool-123",
+ name: "readFile",
+ arguments: { path: "test.txt" },
+ },
+ ];
+
+ const message = service.addAssistantMessage(
+ "Let me read that file",
+ toolCalls,
+ );
+
+ expect(message.message.role).toBe("assistant");
+ expect(message.toolCallStates).toHaveLength(1);
+ expect(message.toolCallStates![0].toolCallId).toBe("tool-123");
+ expect(message.toolCallStates![0].status).toBe("generated");
+ });
+ });
+
+ describe("addSystemMessage", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should add a system message", () => {
+ const message = service.addSystemMessage("System notification");
+
+ expect(message.message.role).toBe("system");
+ expect(message.message.content).toBe("System notification");
+ });
+ });
+
+ describe("updateToolCallState", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should update tool call state", () => {
+ // Add assistant message with tool call
+ const toolCalls = [
+ {
+ id: "tool-456",
+ name: "writeFile",
+ arguments: { path: "output.txt", content: "data" },
+ },
+ ];
+
+ service.addAssistantMessage("Writing file", toolCalls);
+
+ // Update the tool call state
+ service.updateToolCallState(0, "tool-456", {
+ status: "done",
+ output: [
+ {
+ content: "File written successfully",
+ name: "Result",
+ description: "",
+ },
+ ],
+ });
+
+ const state = service.getState();
+ const toolState = state.history[0].toolCallStates![0];
+
+ expect(toolState.status).toBe("done");
+ expect(toolState.output).toHaveLength(1);
+ expect(toolState.output![0].content).toBe("File written successfully");
+ });
+
+ it("should handle missing tool call gracefully", () => {
+ service.addAssistantMessage("No tools here");
+
+ // Should not throw
+ service.updateToolCallState(0, "non-existent", {
+ status: "done",
+ });
+
+ // State should remain unchanged
+ const state = service.getState();
+ expect(state.history[0].toolCallStates).toBeUndefined();
+ });
+ });
+
+ describe("addToolResult", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should add tool result to the correct message", () => {
+ // Add messages with tool calls
+ service.addUserMessage("Do something");
+ service.addAssistantMessage("Using tool", [
+ { id: "tool-789", name: "search", arguments: { query: "test" } },
+ ]);
+
+ // Add tool result
+ service.addToolResult("tool-789", "Search results: found 5 items");
+
+ const state = service.getState();
+ const assistantMessage = state.history[1];
+ const toolState = assistantMessage.toolCallStates![0];
+
+ expect(toolState.status).toBe("done");
+ expect(toolState.output![0].content).toBe(
+ "Search results: found 5 items",
+ );
+ });
+ });
+
+ describe("compact", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should compact history and update index", () => {
+ // Add initial messages
+ service.addUserMessage("Message 1");
+ service.addAssistantMessage("Response 1");
+ service.addUserMessage("Message 2");
+ service.addAssistantMessage("Response 2");
+
+ // Create compacted history
+ const compactedHistory: ChatHistoryItem[] = [
+ {
+ message: {
+ role: "system",
+ content: "[Compacted] Summary of messages 1-2",
+ },
+ contextItems: [],
+ },
+ {
+ message: { role: "user", content: "Message 3" },
+ contextItems: [],
+ },
+ ];
+
+ service.compact(compactedHistory, 0);
+
+ const state = service.getState();
+ expect(state.history).toEqual(compactedHistory);
+ expect(state.compactionIndex).toBe(0);
+ });
+ });
+
+ describe("clear", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should clear all history", () => {
+ service.addUserMessage("Message");
+ service.addAssistantMessage("Response");
+
+ service.clear();
+
+ const state = service.getState();
+ expect(state.history).toEqual([]);
+ expect(state.compactionIndex).toBeNull();
+ });
+ });
+
+ describe("getHistory and getHistoryForLLM", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should return immutable copy of history", () => {
+ service.addUserMessage("Test");
+
+ const history1 = service.getHistory();
+ const history2 = service.getHistory();
+
+ expect(history1).not.toBe(history2); // Different arrays
+ expect(history1).toEqual(history2); // Same content
+ });
+
+ it("should return full history when no compaction", () => {
+ service.addUserMessage("Message 1");
+ service.addAssistantMessage("Response 1");
+
+ const historyForLLM = service.getHistoryForLLM();
+ const fullHistory = service.getHistory();
+
+ expect(historyForLLM).toEqual(fullHistory);
+ });
+
+ it("should return history after compaction index", () => {
+ const history: ChatHistoryItem[] = [
+ {
+ message: { role: "user", content: "Old message" },
+ contextItems: [],
+ },
+ {
+ message: { role: "system", content: "[Compacted] Summary" },
+ contextItems: [],
+ },
+ {
+ message: { role: "user", content: "New message" },
+ contextItems: [],
+ },
+ ];
+
+ service.setHistory(history);
+ service.setCompactionIndex(1);
+
+ const historyForLLM = service.getHistoryForLLM();
+
+ expect(historyForLLM).toHaveLength(2); // Compacted message + new message
+ expect(historyForLLM[0].message.content).toBe("[Compacted] Summary");
+ expect(historyForLLM[1].message.content).toBe("New message");
+ });
+ });
+
+ describe("setHistory", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should set entire history", () => {
+ const newHistory: ChatHistoryItem[] = [
+ {
+ message: { role: "user", content: "Imported message" },
+ contextItems: [],
+ },
+ ];
+
+ service.setHistory(newHistory);
+
+ const state = service.getState();
+ expect(state.history).toEqual(newHistory);
+ });
+
+ it("should detect compaction index when setting history", () => {
+ const historyWithCompaction: ChatHistoryItem[] = [
+ {
+ message: { role: "assistant", content: "old summary" },
+ contextItems: [],
+ conversationSummary: "old summary",
+ },
+ {
+ message: { role: "user", content: "Recent message" },
+ contextItems: [],
+ },
+ ];
+
+ service.setHistory(historyWithCompaction);
+
+ const state = service.getState();
+ expect(state.compactionIndex).toBe(0);
+ });
+ });
+
+ describe("undo/redo", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should undo last change and redo it", () => {
+ service.addUserMessage("A");
+ service.addAssistantMessage("B");
+
+ expect(service.getState().history.map((m) => m.message.content)).toEqual([
+ "A",
+ "B",
+ ]);
+
+ expect(service.canUndo()).toBe(true);
+ service.undo();
+ expect(service.getState().history.map((m) => m.message.content)).toEqual([
+ "A",
+ ]);
+
+ expect(service.canRedo()).toBe(true);
+ service.redo();
+ expect(service.getState().history.map((m) => m.message.content)).toEqual([
+ "A",
+ "B",
+ ]);
+ });
+
+ it("should support undoing tool state updates", () => {
+ service.addAssistantMessage("Using tool", [
+ { id: "t1", name: "Read", arguments: { path: "file" } },
+ ]);
+ const before = service.getHistory();
+ service.addToolResult("t1", "ok", "done");
+ const after = service.getHistory();
+
+ expect(after[0].toolCallStates?.[0].status).toBe("done");
+ service.undo();
+ const undone = service.getHistory();
+ expect(undone[0].toolCallStates?.[0].status).toBe(
+ before[0].toolCallStates?.[0].status,
+ );
+ });
+ });
+
+ describe("immutability", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should not allow external mutation of state", () => {
+ service.addUserMessage("Test");
+
+ const state = service.getState();
+ const originalLength = state.history.length;
+
+ // Try to mutate
+ state.history.push({
+ message: { role: "user", content: "Hacked!" },
+ contextItems: [],
+ });
+
+ // Check that internal state wasn't affected
+ const newState = service.getState();
+ expect(newState.history).toHaveLength(originalLength);
+ });
+
+ it("should not allow mutation through getHistory", () => {
+ service.addUserMessage("Test");
+
+ const history = service.getHistory();
+ const originalLength = history.length;
+
+ // Try to mutate
+ history.push({
+ message: { role: "user", content: "Hacked!" },
+ contextItems: [],
+ });
+
+ // Check that internal state wasn't affected
+ const newHistory = service.getHistory();
+ expect(newHistory).toHaveLength(originalLength);
+ });
+ });
+
+ describe("event emissions", () => {
+ beforeEach(async () => {
+ await service.initialize();
+ });
+
+ it("should emit stateChanged on every update", () => {
+ const listener = vi.fn();
+ service.on("stateChanged", listener);
+
+ service.addUserMessage("Message 1");
+ service.addAssistantMessage("Response 1");
+ service.addSystemMessage("System");
+ service.clear();
+
+ expect(listener).toHaveBeenCalledTimes(4);
+ });
+
+ it("should provide old and new state in event", () => {
+ const listener = vi.fn();
+ service.on("stateChanged", listener);
+
+ service.addUserMessage("Test");
+
+ expect(listener).toHaveBeenCalledWith(
+ expect.objectContaining({
+ history: expect.arrayContaining([
+ expect.objectContaining({
+ message: expect.objectContaining({ content: "Test" }),
+ }),
+ ]),
+ }),
+ expect.objectContaining({
+ history: [],
+ }),
+ );
+ });
+ });
+});
diff --git a/extensions/cli/src/services/ChatHistoryService.ts b/extensions/cli/src/services/ChatHistoryService.ts
new file mode 100644
index 000000000..0ebc9de50
--- /dev/null
+++ b/extensions/cli/src/services/ChatHistoryService.ts
@@ -0,0 +1,534 @@
+import type { ChatHistoryItem, ToolStatus } from "core/index.js";
+import { createHistoryItem } from "core/util/messageConversion.js";
+
+import {
+ updateSessionHistory,
+ loadSessionById,
+ createSession,
+} from "../session.js";
+import { logger } from "../util/logger.js";
+
+import { BaseService } from "./BaseService.js";
+
+/**
+ * State managed by the ChatHistoryService
+ */
+export interface ChatHistoryState {
+ history: ChatHistoryItem[];
+ compactionIndex: number | null;
+ sessionId: string;
+ isRemoteMode: boolean;
+}
+
+/**
+ * Service for managing chat history as the single source of truth
+ * Provides immutable updates and automatic React integration via events
+ */
+export class ChatHistoryService extends BaseService {
+ // Simple undo/redo stacks for history snapshots
+ private past: ChatHistoryItem[][] = [];
+ private future: ChatHistoryItem[][] = [];
+ // Memoized snapshot for referential stability in getState()
+ private _memoSnapshot: {
+ stateRef: ChatHistoryState | null;
+ historyRef: ChatHistoryItem[] | null;
+ snapshot: ChatHistoryState | null;
+ } = { stateRef: null, historyRef: null, snapshot: null };
+
+ constructor() {
+ super("ChatHistoryService", {
+ history: [],
+ compactionIndex: null,
+ sessionId: "",
+ isRemoteMode: false,
+ });
+ this.setMaxListeners(50);
+ }
+
+ private setHistoryInternal(
+ history: ChatHistoryItem[],
+ options: {
+ recordUndo?: boolean;
+ compactionIndex?: number | null;
+ persist?: boolean; // set to false to skip persistence (rare)
+ } = {},
+ ): void {
+ const { recordUndo = true, compactionIndex, persist } = options;
+ const prev = this.currentState.history;
+ if (recordUndo) {
+ this.past.push([...prev]);
+ this.future = [];
+ }
+ this.setState({
+ history: [...history],
+ compactionIndex:
+ compactionIndex === undefined
+ ? this.findCompactionIndex(history)
+ : compactionIndex,
+ });
+
+ if (this.currentState.isRemoteMode) {
+ // Skip persistence in remote mode
+ } else if (persist !== false) {
+ updateSessionHistory(history);
+ }
+ }
+
+ /**
+ * Initialize the service with optional session
+ */
+ async doInitialize(
+ session?: any,
+ isRemoteMode = false,
+ ): Promise